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 |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 1,362 | 2.515625 | 3 | [] | no_license | package ru.relex.restaurant.db.entity;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;
@Embeddable
public class DishIngredientId implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
@Column(name = "dish_id")
private Integer dishId;
@Column(name = "ingredient_id")
private Integer ingredientId;
public DishIngredientId() {
}
public Integer getDishId() {
return dishId;
}
public void setDishId(Integer dishId) {
this.dishId = dishId;
}
public Integer getIngredientId() {
return ingredientId;
}
public void setIngredientId(Integer ingredientId) {
this.ingredientId = ingredientId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DishIngredientId that = (DishIngredientId) o;
return Objects.equals(dishId, that.dishId) &&
Objects.equals(ingredientId, that.ingredientId);
}
@Override
public int hashCode() {
return Objects.hash(dishId, ingredientId);
}
@Override
public String toString() {
return "DishIngredientId{" +
"dishId=" + dishId +
", ingredienetId=" + ingredientId +
'}';
}
}
|
Markdown | UTF-8 | 2,089 | 2.765625 | 3 | [] | no_license | # dataplatform--teradata
## Script teradatagit.sh
### Prérequis
Le flow Git utilisé dans le cadre de ce Repo transverse est différent de l'usage classique.
Il est donc important d'avoir pris connaissance du <a href="https://training-dot-lmfr-ddp-dcp-prd.appspot.com/codelabs/how-to-work-with-Git-on-teradata-project/"> CodeLab </a> pour comprendre les mécanismes qui sont employés.
### Objectif
En automatisant les opérations écrites dans le CodeLab, le script teradatagit.sh facilite et accélère les opérations de rebase et push de votre branche feature sur les branches develop, integration et master.
### Usage
Avant de commencer :
- Assurez-vous que les branches develop, integration et master sont bien alignées. Dans le cas contraire, contactez un référent Git.
- Assurez-vous aussi d'avoir créé votre branche feature en local depuis la master (nommée ici <feat/ma-branche>) et l'avoir poussée sur Github (Cette branche feature servira de référence).
Puis :
- Sur votre poste local, vous pouvez vous placer sur n'importe quelle branche, le script fera les checkouts adéquats.
- Ouvrir GitBash dans le dossier contenant le script
- Pour pousser vos modifications sur la branche develop, saisissez la commande suivante dans GitBash :
```sh
sh teradatagit.sh push feat/ma-branche develop
```
En cas d'erreur ou d'incohérence détectée sur les branches, le script s'arrêtera et ne pushera pas vers Github.
Dans le cas contraire, il vous invitera à confirmer le Push, auquel cas tapez 'Y'.
Vérifiez sur Gitlab que le pipeline de CI/CD s'est bien lancé et qu'il a réussi.
- Pour pousser vos modifications sur la branche intégration, de même, saisissez la commande :
```sh
sh teradatagit.sh push feat/ma-branche integration
```
Vérifiez sur Gitlab que le pipeline a réussi.
- Enfin, pour pousser vos modifications sur la branche master :
```sh
sh teradatagit.sh push feat/ma-branche master
```
Vérifiez sur Gitlab que le pipeline a réussi.
Pensez à supprimer votre branche feature en suivant les commandes décrites dans le CodeLab.
|
Python | UTF-8 | 3,491 | 2.640625 | 3 | [] | no_license | import urllib.request
import urllib
import re
import random
#from urllib import request
#url=r"http://www.baidu.com/"
wd={"wd":"北京"}
url="http://www.baidu.com/s?" #url 编码
#构造url 编码*********
wdcode=urllib.parse.urlencode(wd)
url=url+wdcode
# print(url)
#伪装PC机QQ浏览器/Android 华为Mate 10 Pro/vivo/火狐/360进行访问 注意分行时使用\(反斜线)进行上下连接
agent1="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)\
Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6756.400 QQBrowser/10.3.2473.400"
agent2="Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BLA-AL00 Build/HUAWEIBLA-AL00)\
AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/8.9 Mobile Safari/537.36"
agent3="Mozilla/5.0 (Linux; Android 5.1.1; vivo X6S A Build/LMY47V; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0\
Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/044207 Mobile Safari/537.36 MicroMessenger/6.7.3.1340(0x26070332) NetType/4G Language/zh_CN Process/tools"
agent4="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:52.0) Gecko/20100101 Firefox/52.0"
agent5="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"
list1=[agent1,agent2,agent3,agent4,agent5]
agent=random.choice(list1)
#print(agent)********** 添加多个请求头通过随机数组短时间内多次进行访问而减少触发对应服务器的反爬机制
header={
"User-Agent":agent} #字典(键值对)
#********创建自定义请求对象 除了URL之外的信息封装进去(cookie...)(可以通过伪装浏览器(参数:user-agent)进行访问)用来对抗服务器的反爬虫机制1(判断用户是否通过浏览器访问)
req=urllib.request.Request(url,headers=header)
#使用代理IP地址来访问http服务器
# proxylist=[
# {"http":"189.194.48.154:33880"},
# {"http":"111.90.179.182:8080"},
# {"http":"144.48.109.161:8080"},
# {"http":"103.255.30.34:3128"},
# {"http":"170.38.16.175:80"}
# ]
# proxy=random.choice(proxylist)
# print(proxy)
#构建代理处理器对象
# proxyHandler=urllib.request.ProxyHandler(proxy)
#发送请求 获取响应信息读取 这里requset自动创建请求对象************
reponse=urllib.request.urlopen(url).read().decode()
#构建http处理器对象(专门处理http请求对象)
http_hander=urllib.request.HTTPHandler()
#urlopen是一个特殊的opener(不支持代理/cookie) 创建自定义opener对象调用open()发送请求/(why use opener.open())反爬虫机制2 代理:当使用同一台电脑进行多次访问时,对方服务器会记录你的IP地址
opener=urllib.request.build_opener(http_hander)
# opener=urllib.request.build_opener(proxyHandler)
# reponse=opener.open(req).read().decode() #发送请求 获取响应
#将自定义的opener设置为全局变量,这样用urlopener发送的请求也会使用自定义的opener
urllib.request.install_opener(opener)
reponse=urllib.request.urlopen(req).read().decode() #解码--->编码(encode)爬取网页之后进行中文处理
#print(type(reponse)) #显示请求到的数据的类型(bytes 二进制/str 字符串)
#print(len(reponse)) #显示整个HTML的长度
#print(reponse) #显示响应的HTML网页数据
pat=r"<title>(.*?)</title>" #通过正则表达式进行简单的数据清洗(获取标题)
data=re.findall(pat,reponse)
print(data[0]) #findall有多个list列表信息
|
C++ | UTF-8 | 5,785 | 3.46875 | 3 | [] | no_license | #pragma once
#include "GameManager.h"
// @param level - name ot .txt file
// @param saveFile - name of binary file
GameManager& GameManager::getInstance(const char* level, const char* saveFile)
{
static GameManager instance(level, saveFile);
return instance;
}
// @param level - name ot .txt file
// @param saveFile - name of binary file
GameManager::GameManager(const char* level, const char* saveFile)
{
saveFileName = saveFile;
try
{
this->map = new Map(level);
this->hero = new Hero(*map);
}
catch(std::bad_alloc& e)
{
system("cls");
std::cout << "Problem with memory. Restart the app.\n";
std::cout << "\"" << e.what() << "\"";
}
}
GameManager::~GameManager()
{
delete map;
delete hero;
}
// Starts the game
void GameManager::start()
{
char input;
while(true)
{
system("cls");
std::cin.sync();
printInfo();
std::cin.get(input);
//toLowerCase(input);
char currentCell = '\0';
std::cout << input;
if(input == 'M' || input == 'm')
this->menu();
if(input == 'w' || input == 'a' || input == 's' || input == 'd')
this->heroMovement(input);
}
}
// Represents menu for the user
void GameManager::menu()
{
system("cls");
std::cout << "Select: \n"
<< "1. Inventory\n"
<< "2. Save Game\n"
<< "3. Load Game\n"
<< "4. Quit\n"
<< "5. Back\n";
char input;
std::cin >> input;
switch(input)
{
case '1' :
{
hero->putOnItem();
break;
}
case '2' :
{
saveGame(saveFileName);
break;
}
case '3' :
{
loadGame(saveFileName);
break;
}
case '4' :
{
exit(0);
break;
}
default :
{
std::cout << "\nBad input!\n";
system("PAUSE");
}
}
}
// Moves the hero on the map
// by given direction
void GameManager::heroMovement(const char direction)
{
Position currentPos = hero->getPosition();
int i = currentPos.i;
int j = currentPos.j;
char currentCell = '\0';
switch(direction)
{
case 'w' :
{
if(map->getCell(i-1, j) != '#')
{
currentCell = map->getCell(i-1, j);
if(processCell(currentCell))
hero->moveUp(*map);
}
break;
}
case 's' :
{
if(map->getCell(i+1, j) != '#')
{
currentCell = map->getCell(i+1, j);
if(processCell(currentCell))
hero->moveDown(*map);
}
break;
}
case 'a' :
{
if(map->getCell(i, j-1) != '#')
{
currentCell = map->getCell(i, j-1);
if(processCell(currentCell))
hero->moveLeft(*map);
}
break;
}
case 'd' :
{
if(map->getCell(i, j+1) != '#')
{
currentCell = map->getCell(i, j+1);
if(processCell(currentCell))
hero->moveRight(*map);
}
break;
}
}
}
// Prints state of game
// and instructions for the user
void GameManager::printInfo() const
{
map->printMap();
hero->printHeroState();
std::cout << "Controls:\n";
std::cout << "Move - w, a, s, d\n";
std::cout << "Menu - m\n";
}
// Calculates the outcome from battle
// between hero and given monster
void GameManager::battle(Monster* m)
{
float monsterOverall = m->getAttack() + m->getDefence() + m->getLife();
float heroOverall = hero->getAttack() + hero->getDefence() + hero->getLife();
float newLife = hero->getLife() - (monsterOverall / heroOverall) * 50;
float newGold = hero->getGold() + m->getGold();
if(newLife <= 0)
{
std::cout << "\nYOU ARE DEAD!!!";
std::cout << "\nYOU ARE DEAD!!!";
std::cout << "\nYOU ARE DEAD!!!\n";
exit(0);
}
else
{
hero->setLife(newLife);
hero->setGold(newGold);
}
delete m;
}
// Process the char of the current position of Hero
// \return - true if the hero have to be moved
// - false if the hero don't have to be moved
bool GameManager::processCell(const char currentCell)
{
if(currentCell == 'A' || currentCell == 'S' || currentCell == 'P')
{
hero->addItemInInventory(currentCell);
return true;
}
if(currentCell == '1' || currentCell == '2' || currentCell == '3')
{
changeLevel(currentCell);
return false;
}
if(currentCell == 'O' || currentCell == 'U')
{
Monster* monster = NULL;
try
{
monster = createMonster(currentCell);
battle(monster);
return true;
}
catch(std::bad_alloc&)
{
std::cout << "\nMemory problem. The monster is not created\n";
return false;
}
}
if(currentCell == 'F')
{
if(hero->getGold() >= REQUIRED_GOLD)
{
system("cls");
std::cout << '\a';
std::cout << "CONGRATS !!! YOU WON !!!\n";
exit(0);
}
else
{
std::cout << "\nYou need "
<< REQUIRED_GOLD
<< " gold to finish the game.\n";
system("PAUSE");
return false;
}
}
return true;
}
// Creates various monsters
Monster* GameManager::createMonster(const char cell)
{
if(cell == 'O')
return new Orc();
if(cell == 'U')
return new Undead();
}
// Loads next level from text file
void GameManager::changeLevel(const char level)
{
switch(level)
{
case '1' :
{
map->loadMapTextFile("level1.txt");
hero->findHeroPosition(*map);
break;
}
case'2' :
{
map->loadMapTextFile("level2.txt");
hero->findHeroPosition(*map);
break;
}
case'3' :
{
map->loadMapTextFile("level3.txt");
hero->findHeroPosition(*map);
break;
}
}
}
// Saves the game in binary file
void GameManager::saveGame(const char* file) const
{
std::ofstream ofs;
ofs.open(file, std::ios::binary | std::ios::out | std::ios::trunc);
if(ofs)
{
hero->save(ofs);
map->save(ofs);
ofs.close();
}
else
{
std::cout << "\nCan't open file. ";
std::cout << "The game is not saved.";
}
}
// Loads game from binary file
void GameManager::loadGame(const char* file)
{
std::ifstream ifs;
ifs.open(file, std::ios::binary | std::ios::in);
if(ifs)
{
hero->load(ifs);
map->load(ifs);
ifs.close();
}
else
{
std::cout << "\nCan't open file. ";
std::cout << "The game is not loaded.";
}
}
|
Python | UTF-8 | 997 | 3.578125 | 4 | [] | no_license | class Node:
def __init__(self, initdata=None):
self.data = initdata
self.next = None
class Queue:
def __init__(self, node=None):
self.__front = node
self.last = node
def remove(self):
if self.__front is None:
raise IndexError('Remove from empty queue')
removed_node = self.__front
self.__front = self.__front.next
if self.__front == None:
self.last = None
return removed_node.data
def add(self, node=None):
if node is not None:
if self.last is not None:
self.last.next = node
else:
self.__front = node
self.last = node
self.last = node
def peek(self):
if self.__front is None:
raise IndexError('Remove from empty queue')
return self.__front.data
def is_empty(self):
if self.__front is None:
return True
return False
|
Java | UTF-8 | 26,762 | 1.585938 | 2 | [] | no_license | package com.hll.jxtapp;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hll.adapter.ItemOfChatContentAdapter;
import com.hll.adapter.QueueGroupListAdapter;
import com.hll.common.SocketDadaBaseHelper;
import com.hll.common.SocketService;
import com.hll.common.SocketService.SocketSendBinder;
import com.hll.entity.QueueListItemBean;
import com.hll.entity.Item;
import com.hll.entity.ItemOfChatContentBean;
import com.hll.entity.MessageChat;
import com.hll.entity.OrderLeanO;
import com.hll.entity.Queue;
import com.hll.entity.QueueListItemBean;
import com.hll.entity.SchoolPlaceO;
import com.hll.entity.SocketChatO;
import com.hll.entity.SocketMsg;
import com.hll.entity.UserO;
import com.hll.util.JxtUtil;
import com.hll.util.MyApplication;
import com.hll.util.NetworkInfoUtil;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/*
* 排队等待页面
* @author heyi
* 2016/8/12
*/
public class QueueWait extends FragmentActivity implements OnClickListener {
private ImageView returnPre;
private TextView titleSce;
private TextView queueWaitMsg;
private TextView queueWaitUserMsg;
private ListView chatRoomShowListView;
private TextView chatRoomIn;
private TextView chatRoonSend;
private String userName;
private String placeName;
private int planWalkTime;
private int onTheCarNum;
private int youQueueNum;
private ScrollView secScrollView;
private QueueGroupListAdapter adapter;
private List<QueueListItemBean> list;
private ListView listView;
private QueueGroupListAdapter queueStateAdapter; //排队状态listView 适配器
private List<QueueListItemBean> queueStateList = new ArrayList<QueueListItemBean>(); //排队状态数据list
private ListView queueStateListView; //排队状态listView
private TextView queueGroup;
private TextView chatRoom;
private ItemOfChatContentAdapter chatAdapter;
private List<SocketChatO> chatList = new ArrayList<>(); //聊天框中的内容 list
private TextView queueBtn; //加入排队
private TextView queueNoBtn; //取消排队
private LinearLayout msgSendIn;
private Spinner driverPlaceSpinner;
private ArrayAdapter<Item> driverPlaces;
private List<Item> driverPlacesList = new ArrayList<>();
private SocketBroadcastReceiver socketBroadcastReceivr; //socket广播接收器
private SocketSendBinder socketSendBinder; //绑定 socket service
private List<Queue> queueInfo; //排队的数据
private LocalBroadcastManager localBroadcastManager;
private SQLiteDatabase SocketDatabase;
private int firstChatNum=0;
private boolean hasHistoryChat = true;
private OrderLeanO userQueueInfo; //用户的排队信息
private Context context;
private Gson gson;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.queue_wait);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
titleSce = (TextView) findViewById(R.id.id_sec_title);
queueWaitMsg = (TextView) findViewById(R.id.id_queue_wait_queue_msg);
queueWaitUserMsg = (TextView) findViewById(R.id.id_queue_wait_user_msg);
returnPre = (ImageView) findViewById(R.id.id_return);
chatRoomShowListView = (ListView) findViewById(R.id.id_chat_room_show);
chatRoomIn = (TextView) findViewById(R.id.id_chat_room_in);
chatRoonSend = (TextView) findViewById(R.id.id_chat_room_send);
queueStateListView = (ListView) findViewById(R.id.id_queue_list_view);
secScrollView=(ScrollView) findViewById(R.id.id_queue_wait_scrollview);
queueGroup=(TextView) findViewById(R.id.id_queue_group);
chatRoom=(TextView) findViewById(R.id.id_chat_room);
View footer=getLayoutInflater().inflate(R.layout.queue_or_no, null);
queueStateListView.addFooterView(footer);
queueBtn=(TextView) findViewById(R.id.id_queue_btn);
queueNoBtn=(TextView) findViewById(R.id.id_queue_no_btn);
msgSendIn=(LinearLayout) findViewById(R.id.id_msg_in_and_send);
driverPlaceSpinner=(Spinner) findViewById(R.id.id_driver_place_queue_spinner);
context = this;
SQLiteOpenHelper socketDbHelper = new SocketDadaBaseHelper(context, "Socket.db", null, 3);
SocketDatabase = socketDbHelper.getWritableDatabase();
}
@Override
protected void onStart() {
super.onStart();
SocketService.tranType = true; //改socket信息 通知为 广播
getPrepareData(); //用户排队数据初始化,查询是否登陆,是否报名了驾校,可选场地...
showUserInfoByPlace(); //显示用户基本信息,姓名、电话
initEvent(); //按钮初始化事件
initList();
initPage();
boolean bl = prepare();
if(bl==false){
return;
}
registSocketReceiver(); //注册广播接收器
startSocketService(); //启动socket服务
bindSocketService(); //绑定 socket 服务
}
@Override
protected void onDestroy() {
super.onDestroy();
SocketService.tranType = false; //改socket信息 广播为通知
unRegistSocketReceiver(); //解除websocket广播接收器
unBindSocketService(); //解除绑定 websocketService
}
/**
* 用户排队数据初始化,查询是否登陆,是否报名了驾校,可选场地... liaoyun 2016-8-14
* @return
*/
private void getPrepareData() {
Thread thread1 = new Thread(){
@Override
public void run() {
String url = NetworkInfoUtil.baseUtl + "/queue/getOrderLeanInfo.action";
OrderLeanO myOrder = JxtUtil.getObjectFromServer(OrderLeanO.class, url);
userQueueInfo = myOrder;
}
};
thread1.start();
try {
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 预约前的初始化工作,判断用户是否登陆,是否报名了驾校
* liaoyun 2016-8-12
*/
private boolean prepare() {
if(userQueueInfo==null){
JxtUtil.toastCenter(this, "没有连上网络,网络质量差 ",Toast.LENGTH_LONG);
return false;
}else if(userQueueInfo.getLoginState() == 0){ //没有登陆服务器
JxtUtil.toastCenter(this, "您还没有登陆 ",Toast.LENGTH_LONG);
return false;
}else if(userQueueInfo.getSchoolPlace()==null || userQueueInfo.getSchoolPlace().size()<1){//没有报名驾校
JxtUtil.toastCenter(this, "您还没有在驾校报名 ",Toast.LENGTH_LONG);
return false;
}
return true;
}
private void initList() {
secScrollView.smoothScrollBy(0, 0);
queueStateAdapter = new QueueGroupListAdapter(this, queueStateList);
queueStateListView.setAdapter(queueStateAdapter);
setListViewHeightBasedOnChildren(queueStateListView);
chatAdapter=new ItemOfChatContentAdapter(this, chatList);
chatRoomShowListView.setAdapter(chatAdapter);
chatRoomShowListView.setOnScrollListener(new ChatOnScrollListener()); //向下滑动加载历史数据
}
//初始化页面
private void initPage() {
driverPlacesList.add(new Item("-1", "请选择场地"));
List<SchoolPlaceO> list = userQueueInfo.getSchoolPlace();
for (SchoolPlaceO vo : list) {
driverPlacesList.add(new Item(""+vo.getId(), vo.getPlaceName()));
}
driverPlaces=new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, driverPlacesList);
driverPlaces.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
driverPlaceSpinner.setAdapter(driverPlaces);
driverPlaceSpinner.setOnItemSelectedListener(new SpinnerOnItemClickListener()); //下拉框绑定监听器
}
private void initEvent() {
returnPre.setOnClickListener(this); //返回按钮点击事件
chatRoonSend.setOnClickListener(this); //
queueGroup.setOnClickListener(this); //
chatRoom.setOnClickListener(this); //
msgSendIn.setOnClickListener(this);
}
//初始化页面
private void showUserInfoByPlace() {
titleSce.setText("排队等候");
UserO userInfo = JxtUtil.getLastUserInfo();
userName = userInfo.getNickName();
if(userInfo.getTel() != null && !userInfo.getTel().trim().equals("")){
userName = userName + " (" + userInfo.getTel() + ")";
}
placeName = "东湖";
planWalkTime = 19;
queueWaitUserMsg.setText(" 尊敬的" + userName + ",您选择" + placeName + "训练场,需步行 " + planWalkTime + " 分钟。");
onTheCarNum = 3;
youQueueNum = 10;
queueWaitMsg.setText("目前在车内的是第 " + onTheCarNum + " 位,你排在第" + youQueueNum + " 位");
queueBtn.setText("确定排队");
queueNoBtn.setText("取消排队");
queueBtn.setOnClickListener(this);
queueNoBtn.setOnClickListener(this);
}
// 获取并设置ListView高度的方法
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
listView.setLayoutParams(params);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.id_return:
finish(); //退出页面
break;
case R.id.id_chat_room_send:
sendChatMessage(); //群发消息
String msg=chatRoomIn.getText().toString();
//new SendMessageThread(msg).start();
chatRoomIn.setText("");
break;
case R.id.id_queue_group:
chatRoomShowListView.setVisibility(View.GONE);
queueStateListView.setVisibility(View.VISIBLE);
msgSendIn.setVisibility(View.GONE);
queueWaitMsg.setVisibility(View.VISIBLE);
queueWaitUserMsg.setVisibility(View.VISIBLE);
//getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
break;
case R.id.id_chat_room: //进入聊天页面
chatRoomShowListView.setVisibility(View.VISIBLE);
queueStateListView.setVisibility(View.GONE);
msgSendIn.setVisibility(View.VISIBLE);
queueWaitMsg.setVisibility(View.GONE);
queueWaitUserMsg.setVisibility(View.GONE);
break;
case R.id.id_queue_btn: //加入排队
insertIntoTeam();
break;
case R.id.id_queue_no_btn: //取消排队
giveUpTeam();
break;
default:
break;
}
}
/**
* 群发消息
*/
private void sendChatMessage() {
List<Queue> list = queueInfo;
if(list == null || list.size()==0){
JxtUtil.toastCenter(context, "没有人排队了", Toast.LENGTH_LONG);
return;
}
String message = (String) chatRoomIn.getText().toString();
if(message == null || message.trim().equals("")){
return;
}
List<String> users = new ArrayList<>();
for (Queue q : list) {
users.add(q.getUserAccount().trim());
}
SocketMsg socketMsg = JxtUtil.createSocketMsg(SocketMsg.SCENE_CHAT, SocketMsg.TYPE_TRANSMIT, users, message);
socketSendBinder.sendMessage(socketMsg);
}
/* * 开启一个线程,用来发送消息到后台数据库中
* @author heyi
* 2016/8/17
*/
private class SendMessageThread extends Thread{
String msg;
public SendMessageThread(String msg) {
this.msg=msg;
}
Item item = (Item) driverPlaceSpinner.getSelectedItem();
MessageChat messageChat;
UserO userInfo = JxtUtil.getLastUserInfo();
@Override
public void run() {
super.run();
String placeName =item.getDesc();
String schoolAccount = userQueueInfo.getSchoolPlace().get(0).getSchoolAccount();
String userAccount=userInfo.getAccount();
messageChat.setSchollAccount(schoolAccount);
messageChat.setPlaceName(placeName);
messageChat.setUserAccount(userAccount);
messageChat.setMsg(msg);
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=sdf.format(date);
messageChat.setSendTime(time);
String msgJson=gson.toJson(messageChat);
HttpURLConnection conn=JxtUtil.postHttpConn(NetworkInfoUtil.baseUtl+"/messageChat/addMessage.action", msgJson);
//接收数据
try {
InputStream is=conn.getInputStream();
String str=JxtUtil.streamToJsonString(is);
SocketChatO chatContent=gson.fromJson(str, new TypeToken<ItemOfChatContentBean>(){}.getType());
//添加最新消息到聊天框
chatList.add(chatContent);
//更新ui聊天框
new ChatMsgHandler().sendEmptyMessage(0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 更新了chatlist,发给handler去更新ui
* @author heyi
* 2016/8/17
*/
private class ChatMsgHandler extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
chatAdapter.notifyDataSetChanged();
}
}
/**
* 取消排队 liaoyun 2016-8-15
*/
private void giveUpTeam() {
Item item = (Item) driverPlaceSpinner.getSelectedItem();
String code = item.getCode();
final String url = NetworkInfoUtil.baseUtl + "/queue/giveUpMyQueue/" + code + ".action";
final QueueStateHandler handler = new QueueStateHandler();
new Thread(){
public void run() {
Looper.prepare();
List<Queue> list = JxtUtil.getListObjectFromServer(Queue.class, url);
Message msg = new Message();
msg.obj = list;
handler.sendMessage(msg);
Looper.loop();
};
}.start();
}
/**
* 加入排队 liaoyun 2016-8-15
*/
private void insertIntoTeam() {
Item item = (Item) driverPlaceSpinner.getSelectedItem();
String code = item.getCode();
final String url = NetworkInfoUtil.baseUtl + "/queue/insertQueue/" + code + ".action";
final QueueStateHandler handler = new QueueStateHandler();
new Thread(){
public void run() {
Looper.prepare();
List<Queue> list = JxtUtil.getListObjectFromServer(Queue.class, url);
Message msg = new Message();
msg.obj = list;
handler.sendMessage(msg);
Looper.loop();
};
}.start();
}
/**
* 场地下拉框 监听
* @author LiaoYun 2016-8-23
*/
private class SpinnerOnItemClickListener implements OnItemSelectedListener{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String code = getPlaceSpinnerCode();
if(!code.equals("-1")){
getQueueStateByPlaceId(code); //按场地id加载排队信息
List<SocketChatO> list = setOpenPageChat(SocketDatabase); //刚 进入页面时,加载的聊天信息,取最近的10条
chatList.addAll(list);
chatAdapter.notifyDataSetChanged(); //通知chatList显示更新
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
/**
* 获取 当前 场地 spinner中的场地 code
* @return
*/
private String getPlaceSpinnerCode() {
Item item = (Item) driverPlaceSpinner.getSelectedItem();
String code = item.getCode();
return code;
}
/**
* 按场地id加载排队信息 liaoyun 2016-8-15
* @param code
*/
public void getQueueStateByPlaceId(final String code) {
final QueueStateHandler handler = new QueueStateHandler();
new Thread(){
public void run() {
Looper.prepare();
String url = NetworkInfoUtil.baseUtl + "/queue/findLastQueueState/" + code + ".action";
List<Queue> list = JxtUtil.getListObjectFromServer(Queue.class, url);
Message msg = new Message(); //显示当前的排队信息
msg.obj = list;
handler.sendMessage(msg);
Looper.loop();
};
}.start();
}
@SuppressLint("HandlerLeak")
private class QueueStateHandler extends Handler{
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
List<Queue> list = (List<Queue>) msg.obj;
queueInfo = list;
showQueueState(list);
}
}
/**
* 在页面上展示排队信息 liaoyun 2016-8-15
* @param list
*/
protected void showQueueState(List<Queue> list) {
queueStateList.clear();
if(list == null || list.size()==0){
JxtUtil.toastCenter(context, "现在还没有人排队", Toast.LENGTH_SHORT);
queueStateAdapter.notifyDataSetChanged();
return;
}
for (Queue vo : list) {
queueStateList.add(new QueueListItemBean(vo.getMySet(),vo.getUserNickName(), R.drawable.queue_list_sure,R.drawable.queue_list_sure));
queueStateAdapter.notifyDataSetChanged();
}
}
/**
* 注册广播接收器
*/
@SuppressWarnings("static-access")
private void registSocketReceiver(){
Log.e("socket","regist Socket broadcast Receiver ");
localBroadcastManager = localBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.hll.socketBroadcast.SOCKET_BROADCAST");
socketBroadcastReceivr = new SocketBroadcastReceiver();
localBroadcastManager.registerReceiver(socketBroadcastReceivr, intentFilter);
//registerReceiver(socketBroadcastReceivr, intentFilter);
}
/**
* 销毁广播接收器
*/
private void unRegistSocketReceiver(){
try{
localBroadcastManager.unregisterReceiver(socketBroadcastReceivr);
}catch(Exception e){
e.printStackTrace();
}
//unregisterReceiver(socketBroadcastReceivr);
}
/**
* 接收 websocket 推送的 广播接收器
* @author liaoyun 2016-8-20
*/
private class SocketBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context con, Intent intent) {
//JxtUtil.toastCenter(context, "收到信息", Toast.LENGTH_LONG);
//收到消息后的处理,两种情况, 1:聊天信息; 2:排队变化信息
SocketMsg smg = (SocketMsg) intent.getSerializableExtra("message");
if(smg.getScene()==SocketMsg.SCENE_CHAT){ //如果是聊天信息
//1、数据存入数据库
String placeId = getPlaceSpinnerCode();
SocketChatO socketChat = new SocketChatO(placeId,smg.getAccount(), smg.getName(), smg.getNickName(), smg.getMessage(), smg.getTime());
long newId = insertChat(SocketDatabase, socketChat);
//2、数据加入到聊天显示框尾部
socketChat.setId(newId);
chatList.add(socketChat);
chatAdapter.notifyDataSetChanged();
//显示 到最下面一行
chatRoomShowListView.setSelection(chatList.size()-1);
//清空输入框
chatRoomIn.setText("");
}else if(smg.getScene()==SocketMsg.SCENE_QUEUE){ //如果是排队变化信息
//更新队列信息
JxtUtil.toastCenter(context, smg.getMessage(), Toast.LENGTH_LONG);
}else if(smg.getScene()==SocketMsg.SCENE_LOGIN){ //websocekt 登陆成功
JxtUtil.toastCenter(context, smg.getMessage(), Toast.LENGTH_LONG);
}
}
}
/**
* 向 表 chat_t 插入聊天信息,并返回 插入 的 id
* @param db
* @param socketChat
*/
private long insertChat(SQLiteDatabase db,SocketChatO socketChat){
String code = getPlaceSpinnerCode();
ContentValues values = new ContentValues();
values.put("placeid", code);
values.put("account", socketChat.getAccount());
values.put("name", socketChat.getName());
values.put("nickName", socketChat.getNickName());
values.put("content", socketChat.getContent());
values.put("sendTime", socketChat.getSendTime());
db.insert("chat_t", null, values);
//查询插入的当前记录的 id
long id = 0;
String sql = "select max(id) as id from chat_t where placeid = ?";
Cursor result = db.rawQuery(sql, new String[]{code});
if(result.moveToFirst()){
id = result.getLong(result.getColumnIndex("id"));
}
return id;
}
/**
* 从数据库 chat_t 中取出数据,查询历史记录。 LiaoYun 2016-8-23
* @param db
* @param start 开始位置(用 id指定即可)
* @param num 条数
* @return
*/
private List<SocketChatO> getChat(SQLiteDatabase db,long start,int num){
String sql="select t.* from (select id, account, name, nickName, content, sendTime from chat_t "
+ "where placeid = ? and id < ? order by id desc limit ? offset 0) t order by t.id";
String code = getPlaceSpinnerCode();
Cursor result = db.rawQuery(sql, new String[]{code,""+start, ""+num});
List<SocketChatO> list = new ArrayList<SocketChatO>();
if(result.moveToFirst()){
do{
long id = result.getInt(result.getColumnIndex("id"));
String account = result.getString(result.getColumnIndex("account"));
String name = result.getString(result.getColumnIndex("name"));
String nickName = result.getString(result.getColumnIndex("nickName"));
String content = result.getString(result.getColumnIndex("content"));
String sendTime = result.getString(result.getColumnIndex("sendTime"));
SocketChatO vo = new SocketChatO(id, code, account, name, nickName, content, sendTime);
list.add(vo);
}while(result.moveToNext());
}
return list;
}
/**
* 获取 刚 进入页面时,加载的聊天信息,取最近的10条, LiaoYun 2016-8-23
* @param db
* @return
*/
private List<SocketChatO> setOpenPageChat(SQLiteDatabase db){
String sql = "select t.* from (select id, account, name, nickName, content, sendTime from chat_t"
+ " where placeid = ? order by id desc limit 10 offset 0) t order by t.id";
String code = getPlaceSpinnerCode();
Cursor result = db.rawQuery(sql,new String[]{code});
List<SocketChatO> list = new ArrayList<SocketChatO>();
if(result.moveToFirst()){
do{
long id = result.getInt(result.getColumnIndex("id"));
String account = result.getString(result.getColumnIndex("account"));
String name = result.getString(result.getColumnIndex("name"));
String nickName = result.getString(result.getColumnIndex("nickName"));
String content = result.getString(result.getColumnIndex("content"));
String sendTime = result.getString(result.getColumnIndex("sendTime"));
SocketChatO vo = new SocketChatO(id, code, account, name, nickName, content, sendTime);
list.add(vo);
}while(result.moveToNext());
}
return list;
}
/**
* chat list 滑动监听,,,当滑动到最上面时,下拉加载历史数据
* @author LiaoYun 2016-8-23
*/
private class ChatOnScrollListener implements OnScrollListener{
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
firstChatNum = firstVisibleItem;
}
@Override
public void onScrollStateChanged(AbsListView arg0, int scrollState) {
//当第一条显示为第0条数据 ,且滑动为静止,且有历史数据时,加载历时数据
if(firstChatNum==0 && scrollState==OnScrollListener.SCROLL_STATE_IDLE && hasHistoryChat){
long start = chatList.get(0).getId();
List<SocketChatO> list = getChat(SocketDatabase, start, 10);
if(list==null || list.size()==0){
hasHistoryChat = false; //没有历史数据了
JxtUtil.toastCenter(context, "没有数据了", Toast.LENGTH_LONG);
}else{
chatList.addAll(0, list);
chatAdapter.notifyDataSetChanged();
}
}
}
}
/**
* 如果SocketService还没有启动,则启动SocketService
*/
private void startSocketService(){
boolean isRuning = SocketService.IS_STARTED;
if(!isRuning){
Log.e("socket","服务 还没有启动。。。。。。。。。。。。。。。。。。。。");
Intent intent = new Intent(MyApplication.getContext(), SocketService.class);
startService(intent);
}
}
/**
* 绑定 socket 服务
*/
private void bindSocketService(){
Intent bindIntend = new Intent(context, SocketService.class);
bindService(bindIntend, connection, BIND_AUTO_CREATE);
}
/**
* 取消 绑定 socket 服务
*/
private void unBindSocketService(){
unbindService(connection);
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName arg0) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
socketSendBinder = (SocketSendBinder) iBinder;
}
};
}
|
Java | UTF-8 | 354 | 2.0625 | 2 | [] | no_license | package oop.inherit4;
public class Test01 {
public static void main(String[] args) {
// chrome
Chrome c = new Chrome();
c.setUrl("ㅇㅇ");
c.setVersion("ㅇㅇ");
c.move();
c.back();
c.store();
// firefox
Firefox f = new Firefox();
f.setUrl("ㅇㅇ");
f.setVersion("ㅇㅇ");
f.move();
f.back();
}
}
|
C | UTF-8 | 1,075 | 3.421875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char const *argv[]) {
int quantidade = 0;
int vetor[20];
printf("digite 20 números\n");
for (int i = 0; i < 20; i++) {
scanf("%d", &vetor[i]);
}
int indexVerificado = 0;
int vetorNumerosVerificados[20];
for (int i = 0; i < 20; i++) {
if (i == 0) {
vetorNumerosVerificados[i] = vetor[i];
indexVerificado++;
} else {
bool numeroRepetido = false;
for (int j = 0; j < indexVerificado; j++) {
if (vetor[i] == vetorNumerosVerificados[j]) {
numeroRepetido = true;
}
}
if (!numeroRepetido) {
vetorNumerosVerificados[indexVerificado] = vetor[i];
indexVerificado++;
}
}
}
puts("\nLista de número que não se repetem\n");
for (int i = 0; i < indexVerificado; i++) {
printf("%d ", vetorNumerosVerificados[i]);
}
puts("\n");
return 0;
}
|
Java | UTF-8 | 4,013 | 2.21875 | 2 | [] | no_license | /*
* CoadunationTypeManagerConsole: The type management console.
* Copyright (C) 2010 2015 Burntjam
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* RDFViewFactory.java
*/
package com.rift.coad.type.manager.client;
import com.rift.coad.gwt.lib.client.console.ConsolePanel;
import com.rift.coad.gwt.lib.client.console.PanelFactory;
import com.smartgwt.client.types.HeaderControls;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.layout.VLayout;
/**
* This object displays the RDF xml information.
*
* @author brett chaldecott
*/
public class RDFViewFactory implements PanelFactory {
/**
* The panel with rdf information.
*/
public class RDFPanel extends ConsolePanel {
/**
* The default constructor for the RDF panel
*/
public RDFPanel() {
}
/**
* This method returns the panel reference.
*
* @return The reference to the panel.
*/
@Override
public Canvas getViewPanel() {
VLayout layout = new VLayout();
layout.setWidth100();
layout.setHeight100();
Window window = new Window();
window.setTitle("http://[hostname]:[port]" + URI);
window.setWidth100();
window.setHeight100();
window.setCanDragReposition(false);
window.setCanDragResize(true);
window.setHeaderControls(HeaderControls.HEADER_LABEL);
window.setSrc(URI);
layout.addMember(window);
return layout;
}
/**
* The name of the panel
*
* @return The string containing the name of the panel.
*/
@Override
public String getName() {
return "RDF View";
}
}
// class constants
private final static String URI = "/RDFTypeSource/Query?";
// class singleton
private static RDFViewFactory singleton = null;
// private member variables
private String id;
private RDFPanel panel;
/**
* The default constructor for the RDFView factory.
*/
private RDFViewFactory() {
}
/**
* This method returns an instance of the RDFViewFactory.
*
* @return The reference to the factory.
*/
public static RDFViewFactory getInstance() {
if (singleton == null) {
singleton = new RDFViewFactory();
}
return singleton;
}
/**
* This method returns a reference to a new panel.
*
* @return The reference to the new panel.
*/
public Canvas create() {
if (panel == null) {
panel = new RDFPanel();
id = panel.getID();
} else if (!panel.isDrawn()) {
panel = new RDFPanel();
panel.draw();
id = panel.getID();
}
return panel;
}
/**
* This method returns the id for the panel
*
* @return The id for the panel
*/
public String getID() {
return id;
}
/**
* This method returns the description of the view factory.
*
* @return The description of the view factory.
*/
public String getDescription() {
return URI;
}
}
|
Markdown | UTF-8 | 9,954 | 2.984375 | 3 | [] | no_license | ---
title: Angels
permalink: wiki/Angels/
layout: wiki
---
### Angels
Angels are a humanoid spacefaring race that’s older than most, their clear difference being their massive wings, along with their genetic propensity for unusual eye colors. They also have quite the range of height, able to grow up to seven feet tall naturally- however it’s not infrequent to come upon one that’s around five feet. They only occupy one planet, Sanctum. They have a reclusive society, stringent laws, technology befitting of their age-old race, and a high propensity to judge others based on their own well ingrained societal morals. While all of this is true, it also means that they’re adept at reading others’ emotions and understanding them, and lends to wonderful organizational skills. Should you see one on the station, it’s not uncommon to see them in positions of leadership, security, or as your psychiatrist. They are locked in an age-old struggle with the only other race inhabiting their home system, the Demons.
### Angel Society
Angel society highlights moral integrity and devotion to their borderline religious beliefs around their society’s laws. While rates of crime and imprisonment are found lower in angel society than in any other galactic race, their law like moral code finds many individuals perpetually ostracized for what other societies may deem normal. They also have an in depth supportive and state paid education system, teaching dedicated and mandatory classes about the importance of understanding and order.
Sanctum’s education is highly complex and highly split into specialized fields. Angel children often pick their chosen occupation somewhere before a human would go to high school, and usually stick with this choice for the rest of their lives. While there are obvious problems inherent in such a system, one cannot deny that their rate of unemployment is low and that their technology is always advancing. There are few Angels who voice complaints with their chosen vocation, but that’s not to say all enjoy their choice; After all, idle hands are the devil’s playthings.
Sanctum, as of current, refuses to accept any lifetime immigrants without using numerous loopholes or constantly renewing licenses. Visits are encouraged; However, anyone of lower status visiting the planet is mandated to be accompanied by a parole officer of sorts labeled as a guardian. Should someone be visiting on the recommendation of a particular citizen, that citizen can choose to take guardian certification courses themselves, and step in as their guardian.
Sanctum’s populace has a high reliance on their advanced tech. From translocators, to lasers, to nanomachines- many problems can be easily solved by their robotic workforce. While much of this technology is a small leap ahead from the rest of the galaxy’s combined efforts, the Angels refuse to let other races even inspect it, and their tamper-proofing is also steps ahead of the galactic norm. By law, any technology produced comes with wired in failsafe and anything not galactically available that leaves the planet must be fitted with a self-destruct.
As a result of such technology, as well as the ability to produce food and power cheaply and with little to no cost, Sanctum’s citizens often have the state cover most of their very basic needs, power, net access, water, housing, and food. Anything luxury is typically paid for out of pocket.
### Sanctum Law
Sanctum’s laws are most easily understood by human society as being strangely parallel with fundamentals of Christian belief, however they have no issues with same-sex couples, and adopt equal gender roles. Public indecency, most drug use, overconsumption, promiscuity, any form of non-defensive violence, theft, and refusal to contribute to society are all punished equally in most of their forms. Even where these offenses are too small to be rightly punished by even the most stringent judgment by law enforcement, an angel’s peers may become their jailor instead- Angels are often punished for their perceived wrongdoings by involuntarily becoming somewhat of an outcast. Someone outed for doing immoral things will easily lose friends, social status, and potentially their job. Luckily, their system for those unemployed is also quite sophisticated, however, it usually moves people across vast distances for a new job. Angels tend to be quite suspicious of new people in their workplace.
The Angels do not believe in execution, and instead, offer would-be death row prisoners another option. They get an inexpensive probe filled with enough fuel to barely leave their solar system, a probe that’s programmed to be unable to return to Sanctum. This is framed as the choice for a new life in exile, however, in reality, there is no choice involved. There is only one other inhabited planet in the solar system, that of their bitter rivals, the Demons. Some choose death in space over the only other option.
Sanctum’s ruling class is synonymous with their judicial system. Various different courts are established across territories, with each having seven judges presiding over it, elected to their position from smaller courts. This all moves upwards to the members of the sanctum high court of holy law, who are the de facto leaders of their race. Judges ruling over large territories are referred to as Seraphim, and the members of the high court are referred to as Archangels. Their election process is highly complex as a result of so many candidates shuffling around and attempting to move up, but despite this Sanctum usually has an unusually high voter turnout.
### Angel Physiology
Despite having obvious similarities to humans, there are marked differences in the physiologies of Angels that set them apart from their terrestrial counterparts. Angels are far less dense in both musculature and bone structure, leading to their ability to fly and the light gravity of their homeworld. They have a low susceptibility to most easily visible facial flaws, such as freckles or moles, and externally their skin is almost always soft and smooth. They don’t callous easily either. As a result of stringent genetic modification programs, most genetic disorders have been entirely wiped from the angel’s genome. Angels tend to live about as long as Demons do, an average of about five hundred years.
### Sanctum
Sanctum's atmosphere is similar to Earth's, but the gravity is significantly lighter, allowing many of the creatures that inhabit it to evolve for flight. The terrain consists of spire-like mountains, often tall enough to reach through clouds and plateaus that sport forests and other wildlife. There are two oceans, which cover a quarter of the planet's surface and many lakes. It has a population of four billion.
Sanctum shares a solar system with seven sister planets, only one inhabited by their bitter rivals, the Demons. The weather of Sanctum is a balance of sunny skies, overcasts and rain storms. Earthquakes are common, powerful ones are rare. A year lasts four hundred and seventy days, days last twenty hours, with Fourteen of sunlight.
### Language
Angels speak Enochian, a mess of a harmonic song that often requires years of practice to sing correctly. It’s frequently reported by first-time listeners to be a soothing and beautiful language, many Angels singing it so deftly that you ‘can practically feel yourself getting lost in their voice’. It’s much less pleasant when you’re learning it though. There are many different exceptions and general inconsistencies in its structure to the point where it’s one of the more complex galactic languages.
### Galactic Influence
Angels have no colonies outside of their homeworld and generally only seem to be interested in observing the rest of galactic society. They find a place at most councils or alliance tables, frequently offering advice and support, and find the defense of their many established listening posts and observation stations from their allies. Said listening posts comprise most of angel society’s off-world citizens and have been stationed across the galaxy since before most races developed space travel. They collect all sorts of data, usually on the development and evolution of sentient or near-sentient life. It is as of yet unknown why this data is being collected.
### Demonic War
The Angels have been locked in an age-old struggle with their neighbors in the system, the Demons, for as long as any Angel can remember. Old Angel texts have the segment of history determined to be both the start of the war and the entrance of Demons into the picture stricken from their records, which is curious, as no mention of the race was present during the angel’s first steps into space travel onward. While there are large genetic similarities between angels and Demons and the only real differences coming from a plethora of specialized genetic modifications, the galactic scientific community at large still refuses to regard them as the same species. There have been a few papers published on the subject, but they’ve never passed peer review.
The Demons have a similar, but a lower level of technology, and test Sanctum’s defenses regularly. While the ongoing conflict doesn’t have the massive land invasions and bombings it once did, that’s only due to countermeasures in place by both sides. It’s not uncommon to see Angel and Demon ships go missing even today, and their wreckages litter the system.
The Demons are largely regarded as boogeymen in angel society, often looked at as lesser beings unworthy of mercy. Some view them with pity as not being enlightened by the same structure an order that they are, but these are in the minority and are never vocal about such a thing. This makes sense, given how starkly angel culture contrasts with their counterparts.
|
JavaScript | UTF-8 | 325 | 3.21875 | 3 | [] | no_license | /**
* @param {number[]} costs
* @param {number} coins
* @return {number}
*/
var maxIceCream = function (costs, coins) {
// 挑便宜的买,小男孩Tony从小就很会过日子
costs.sort((x, y) => x - y);
let head = 0;
while (coins >= costs[head]) {
coins -= costs[head];
head++;
}
return head;
};
|
JavaScript | UTF-8 | 853 | 4.375 | 4 | [] | no_license | function main() {
// Put your code here
console.log("Let's roll some dice, baby!")
console.log("---------------------------")
for(let i = 0; i < 10; i++){
let die1 = Roll()
let die2= Roll()
let message = `${Die(die1)} + ${Die(die2)} == ${die1 + die2}`
if (die1 === die2){
message += " DOUBLES"
}
console.log(message)
}
function Roll(){
let dieValue = Math.floor(Math.random() * 6) + 1; // returns a random integer from 1 to 6
return dieValue;
}
function Die(value){
let dieString = "Unknown"
switch(value){
case 1:
dieString = "\u2680";
break;
case 2:
dieString = "\u2681";
break;
case 3:
dieString = "\u2682";
break;
case 4:
dieString = "\u2683";
break;
case 5:
dieString = "\u2684";
break;
case 6:
dieString = "\u2685";
break;
}
return dieString;
}
}
main(); |
Java | UTF-8 | 675 | 3.71875 | 4 | [] | no_license | package complexnumberdemo;
public class ComplexNumberDemo {
public static void main(String[] args) {
ComplexNumber x = new ComplexNumber(4, 5);
ComplexNumber y = new ComplexNumber(2, 3);
System.out.printf("x = ");
x.print();
System.out.printf("y = ");
y.print();
System.out.printf("x + y = ");
x.add(y).print();
System.out.printf("x - y = ");
x.subtract(y).print();
System.out.printf("x * y = ");
x.multiply(y).print();
System.out.printf("x / y = ");
x.divide(y).print();
}
}
|
Python | UTF-8 | 1,439 | 2.546875 | 3 | [] | no_license | ### Calculate nucleotide diversity from MSA of refseq(assembled) data
# require
import os, sys
from utilities3.basic import *
from utilities3.custom_classes import *
from joblib import Parallel, delayed
# start clock
start = time()
# number of threads
nt = int(sys.argv[1])
### Generate instances of class MSA ###
# paths
dr = 'codon_msa'
f_out = 'nucdiv_asm.tab'
# list of cds FASTA files
fls = [ os.path.join( dr, i) for i in os.listdir(dr)]
# Function to tabulate analysis results of multiple MSAs
def tabulate_msa_data(fname):
# check if file exists and is non-zero
if not filetest_s(fname): return
msa = MSA(fname,seqtype='n')
out = [ msa.gene, msa.ncol, msa.nogapcol, msa.ndif, msa.div()]
return out
# header for the table
header = [ 'gene', 'nuc_len', 'nuc_nogap', 'nuc_ndif', 'nuc_div']
# execute, if output doesn't exist already
if not os.path.exists(f_out):
print("%s: generating genes' summaries on nucleotide sequence\n"%timer(start))
stat = filter( None, Parallel(n_jobs=nt)( delayed(tabulate_msa_data) (i) for i in fls) )
stat = { i[0]:i[1:] for i in stat}
print("%s: Assembling data into a table and writing to file\n"%timer(start))
divtab = [ [k] + stat[k] for k in sorted(stat.keys())]
writecsv( data=divtab, fl=f_out, sep='\t',header=header)
print("%s: program finished\n"%timer(start))
else:
print("%s: output file %s already exists\n"%(timer(start),f_out))
|
JavaScript | UTF-8 | 3,043 | 2.671875 | 3 | [] | no_license | import React from 'react'
import Fade from 'grommet/components/Animate';
import Heading from 'grommet/components/Heading';
class Animate extends React.Component {
constructor(props) {
super(props);
this.state = {
currentQuestion: 'test',
visible: true,
showFull: false
}
}
componentWillMount() {
this.setState({currentQuestion: this.props.text})
}
componentWillReceiveProps(nextProps) {
if (nextProps.text !== this.props.text) {
this.setState({visible: false}, ()=> {
setTimeout(()=> {
this.setState({currentQuestion: nextProps.text})
setTimeout(()=> {
this.setState({visible: true})
}, 280)
}, 320)
})
}
}
code = function(text) {
return text.split('~~~').map((item, i)=> {
if (i % 2 === 0) {
return item
} else {
// return (
// <SyntaxHighlighter language='javascript' style={syntaxStyle} >
// {'\n' + text + '\n'}
// </SyntaxHighlighter>
// )
return (
<code
style={{
fontFamily: 'Monaco,Menlo,Consolas,"Courier New",monospace!important',
fontSize: '0.9rem',
whiteSpace: 'normal',
color: '#7026d2',
padding: '2px 3px 1px',
tabSize: '4',
backgroundColor: '#f7f7f9',
border: '1px solid #e1e1e8',
borderRadius: '3px',
lineHeight: '23px'
}}
>
{'\n' + item + '\n'}
</code>
)
}
})
}
render() {
// add a styled "is done" or "not started"
return (
<Fade
visible={this.state.visible}
enter={{"animation": "slide-right", "duration": 300, "delay": 0}}
leave={{"animation": "slide-left", "duration": 300, "delay": 0}}
keep={true}>
<Heading
tag="div"
style={this.state.showFull && this.state.currentQuestion.length >= 55 ? {
overflow: 'visible',
whiteSpace: 'normal',
backgroundColor: 'white',
textOverflow: 'ellipsis',
height: '23px',
width: '500px',
minWidth: '500px',
position: 'relative',
display: 'inline-block',
lineHeight: '23px',
zIndex: '999',
cursor: 'default'
}:
{
overflow: 'hidden',
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
height: '23px',
width: '500px',
display: 'inline-block',
lineHeight: '23px',
}
}
onMouseEnter ={()=> this.setState({showFull: true})}
onMouseLeave ={()=> this.setState({showFull: false})}
>
{this.code(this.state.currentQuestion)}
</Heading>
</Fade>
)
}
}
export default Animate; |
Java | UTF-8 | 805 | 2.4375 | 2 | [
"Apache-2.0"
] | permissive | package io.agent.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* A parameter annotated with @Returned can be used in a Hook's @After method to capture the return value of the instrumented method.
*
* Example: In order to instrument the following method:
* The parameter annotated with @Returned is optional, if the hook does not use the return value, the parameter can be omitted.
* If the instrumented method terminates exceptionally, the type's default value is assigned to the parameter,
* i.e. {@code 0} for numeric types and {@code null} for reference types.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Returned {}
|
Java | UTF-8 | 397 | 2.328125 | 2 | [] | no_license | package midianet.digital.modelo.validador;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class CepValidador implements ConstraintValidator<Cep, String> {
@Override
public void initialize(final Cep cep) {
}
@Override
public boolean isValid(final String valor, final ConstraintValidatorContext contexto) {
return true;
}
}
|
Shell | UTF-8 | 1,331 | 2.859375 | 3 | [] | no_license | #!/bin/sh
# Copyright (C) 2008 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# 'Exercise some lvcreate diagnostics'
. /usr/share/qa/qa_test_lvm2/lib/test
cleanup_lvs() {
lvremove -ff $vg/$lv2
lvremove -ff $vg
if dmsetup table|grep $vg; then
echo "ERROR: lvremove did leave some some mappings in DM behind!"
return 1
fi
}
aux prepare_pvs 2
aux pvcreate --metadatacopies 0 $dev1
aux vgcreate -c n $vg $(cat $TESTDIR/DEVICES)
# ---
# Create snapshots of LVs on --metadatacopies 0 PV (bz450651)
lvcreate -n$lv1 -l4 $vg $dev1
lvcreate -n$lv2 -l4 -s $vg/$lv1
cleanup_lvs
if test is_sp2;then
# ---
# Create mirror on two devices with mirrored log using --alloc anywhere
lvcreate -m 1 -l4 -n $lv1 --mirrorlog mirrored $vg --alloc anywhere $dev1 $dev2
cleanup_lvs
# --
# Create mirror on one dev with mirrored log using --alloc anywhere, should fail
not lvcreate -m 1 -l4 -n $lv1 --mirrorlog mirrored $vg --alloc anywhere $dev1
cleanup_lvs
fi
|
Python | UTF-8 | 10,372 | 2.6875 | 3 | [] | no_license | import getpass
import requests
import urllib3
import yaml
from invoke import UnexpectedExit
from requests.auth import HTTPBasicAuth
from yaml.loader import SafeLoader
from time import sleep
from fabric import Connection, Config
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
# Read inventory and config data from file
inv_file_path = 'inventory.yml'
with open(inv_file_path) as inv_file:
inv_data = yaml.load(inv_file, Loader=SafeLoader)
roles = inv_data['service']['splunk']['roles']
config = inv_data['service']['splunk']['config']
# Disable bad cert warnings when config['verify_tls'] is false
verify_tls = config['verify_tls']
if not verify_tls:
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def init_obj(obj_name):
"""
Simple object creation to allow setting attributes on an empty object
:param obj_name: Name for obj
:return: Object that can have attributes set
"""
ret = type(obj_name, (object,), {})
return ret
def set_pass(passwd, msg=''):
"""
Check if passwd is set via config or prompts the user if no value set
:param passwd: Value of password
:param msg: Message for password prompt
:return: String for password
"""
if passwd:
ret = passwd
else:
ret = getpass.getpass(msg)
return ret
def connect(host, user, passwd=''):
"""
Setup SSH connection to a host
:param host: Hostname of an instance to connect to
:param user: Username to use when connecting
:param passwd: Password to use for username
:return: A connection object
"""
override = Config(overrides={'sudo': {'password': passwd}})
ret = Connection(host=host, user=user, config=override, connect_kwargs={"password": passwd})
return ret
def join_api_url(api_base_url, api_path):
"""
Simple join of a base url and an api path
:param api_base_url: String representing the base url to use when connecting
:param api_path: String representing the api path
:return: A joined url with path
"""
if api_base_url.endswith('/'):
api_base_url = api_base_url[:-1]
if api_path.startswith('/'):
api_path = api_path[1:]
return api_base_url + '/' + api_path
def check_status(con):
"""
Check status by verifying Splunkd is running using sudo
:param con: Connection obj
:return: True if is running else false
"""
try:
status = con.sudo('su - splunk -c "/opt/splunk/bin/splunk status"', hide=True)
if 'is running' in status.stdout:
return True
else:
return False
except (ConnectionError, AuthenticationException, NoValidConnectionsError, UnexpectedExit):
return False
def patch_os(con, os_family='RHEL'):
"""
Run the command to patch the OS using sudo.
:param con: Connection obj
:param os_family: Set the value for os family i.e. RHEL, Debian, etc
:return: Result from command
"""
try:
result = init_obj('result')
result.stdout = ''
# Check OS family and run the appropriate update commands
if os_family.upper() == 'RHEL':
result = con.sudo('yum update -y', hide=True)
elif os_family.upper() == 'DEBIAN':
# TODO: This needs more work
con.sudo('apt-get update -y', hide=True)
result = con.sudo('apt-get dist-upgrade -y', hide=True)
# Get results and set the proper return value
ret = 'OS Type not supported'
if 'Complete!' in result.stdout and 'Nothing to do' not in result.stdout:
ret = 'Updates complete'
elif 'Complete!' in result.stdout and 'Nothing to do' in result.stdout:
ret = 'No Updates'
except (ConnectionError, NoValidConnectionsError):
ret = 'Connection error'
return ret
def cmd_wait(con, run_cmd):
"""
Command will be retried until success unless range value is reached
:param con: Connection obj
:param run_cmd: Command to run
:return: Result from command
"""
# May take up to 5 minutes
sleep(5)
ret = False
for _ in range(25):
try:
result = con.run(run_cmd, hide=True)
if result.return_code == 0:
ret = True
break
except (ConnectionError, NoValidConnectionsError):
sleep(10)
return ret
def check_maintenance_mode(api_url, user, user_pass, verify=False):
"""
Check if maintenance mode is enabled, or disabled based on the value set for maintenance_mode
:param api_url: String representing the base url to use when connecting
:param user: Rest User to use when connecting
:param user_pass: Password to use for Rest User
:param verify: Verify TLS
:return: Enabled, disabled, or unknown depending on requests value
"""
try:
ret = requests.get(api_url, auth=HTTPBasicAuth(user, user_pass), verify=verify)
if ret.json()['entry'][0]['content']['maintenance_mode']:
return 'enabled'
else:
return 'disabled'
except (ConnectionError, NoValidConnectionsError):
return 'unknown'
def set_maintenance_mode(api_set_mm, user, user_pass, data, verify=False):
"""
Set maintenance mode status based on mode passed in as data
:param api_set_mm: String representing the base url to use when connecting
:param user: Rest User to use when connecting
:param user_pass: Password to use for Rest User
:param data: Mode value is True or False
:param verify: Verify TLS
:return: Result from API
"""
try:
ret = requests.post(api_set_mm, auth=HTTPBasicAuth(user, user_pass), data=data, verify=verify)
except (ConnectionError, NoValidConnectionsError):
ret = 'Connection error'
return ret
# Set up account credentials
username = config['system_user']
password = None
if 'system_user_pass' in config:
password = set_pass(config['system_user_pass'], "Enter user password: ")
splunk_user = config['splunk_user']
splunk_user_pass = None
if 'splunk_user_pass' in config:
splunk_user_pass = set_pass(config['splunk_user_pass'], "Enter Splunk user password: ")
# Join API url and path for maintenance mode status check
check_status_url = join_api_url(config['splunk_cm_api_url'], config['splunk_status_check_path'])
# False is the expected value but we return disabled.
if check_maintenance_mode(check_status_url, splunk_user, splunk_user_pass, verify_tls) == 'disabled':
# Perform checks to verify ready to start
for role in roles.keys():
for hostname in roles[role]:
# Create a new session and check Splunkd status
session = connect(hostname, username, password)
if check_status(session):
print('[OK] Splunkd is running: ' + hostname)
else:
print('[FAIL] Status Check: ' + hostname)
# Close session and exit
session.close()
exit(1)
# Close session and continue
session.close()
else:
# Maintenance mode is already enabled.
# We should find out why and try again
print('[FAIL] Maintenance mode already enabled')
exit(1)
print('[OK] All status checks passed... Proceeding')
# Join API url and path for setting maintenance mode value
splunk_api_set_mm = join_api_url(config['splunk_cm_api_url'], config['splunk_set_mm_path'])
# Status checks have passed, do the updates
for role in roles.keys():
# Set maintenance mode status to true
# Only needs to be done for the indexers
if role == 'idx':
rest_data = {'mode': 'true'}
res = set_maintenance_mode(splunk_api_set_mm, splunk_user, splunk_user_pass, rest_data, verify_tls)
if check_maintenance_mode(check_status_url, splunk_user, splunk_user_pass, verify_tls) != 'enabled':
print('[FAIL] Maintenance mode not enabled:')
exit(1)
# Iterate through list of hosts assigned to this role
for hostname in roles[role]:
# Create session
session = connect(hostname, username, password)
# Update host if patches available
is_updated = patch_os(session)
if is_updated == 'Updates complete':
print('[OK] OS Updates complete: ' + hostname)
if role == 'idx':
# Take splunk indexer offline
offline_cmd = 'su - splunk -c "/opt/splunk/bin/splunk offline -auth {}:{}"'.format(splunk_user, splunk_user_pass)
idx_offline = session.sudo(offline_cmd, hide=True)
if idx_offline.return_code == 0:
print('[OK] Splunkd is offline: ' + hostname)
# Reboot host if patches applied
is_rebooted = session.sudo('nohup sudo -b bash -c "sleep 5 && reboot"', hide=True)
if is_rebooted.return_code == 0:
is_running = cmd_wait(session, 'systemctl status Splunkd.service')
if is_running:
print('[OK] Splunkd is running: ' + hostname)
print('[OK] Reboot successful: ' + hostname)
else:
print('[FAIL] Status Check: ' + hostname)
session.close()
exit(1)
else:
print('[FAIL] Something went wrong - Aborting: ' + hostname)
session.close()
exit(1)
elif is_updated == 'Connection error':
print('[FAIL] Connection error - Aborting: ' + hostname)
session.close()
exit(1)
elif is_updated == 'OS Type not supported':
print('[WARN] OS Type not supported - No Updates: ' + hostname)
else:
print('[OK] No updates: ' + hostname)
# Close session
session.close()
# Set maintenance mode status to false
# Only needs to be done for the indexers
if role == 'idx':
rest_data = {'mode': 'false'}
res = set_maintenance_mode(splunk_api_set_mm, splunk_user, splunk_user_pass, rest_data, verify_tls)
if check_maintenance_mode(check_status_url, splunk_user, splunk_user_pass, verify_tls) != 'disabled':
print('[FAIL] Maintenance mode not disabled:')
exit(1)
print('[OK] All hosts finished. Complete!')
|
Python | UTF-8 | 1,396 | 3.40625 | 3 | [
"Apache-2.0"
] | permissive | import numpy as np
def central_difference_z(grid, Nz, Nx, dz, order=1):
"""
Take the differentiation in z of a "2D z-x grid" via central difference.
"""
if (order==1):
grid_temp = np.vstack((np.zeros(Nx), grid, np.zeros(Nx)))
prime_grid = (grid_temp[2:Nz+2] - grid_temp[0:Nz]) / (2*dz)
# Endpoints with 2nd order accuracy
prime_grid[0] = ((-3/2)*grid[0] + 2*grid[1] - (1/2)*grid[2]) / dz
prime_grid[Nz-1] = ((1/2)*grid[Nz-3] - 2*grid[Nz-2] + (3/2)*grid[Nz-1]) / dz
elif (order==2):
grid_temp = np.vstack((np.zeros(Nx), np.zeros(Nx), grid, np.zeros(Nx), np.zeros(Nx)))
prime_grid = (- grid_temp[4:Nz+4] \
+ 8*grid_temp[3:Nz+3] \
- 8*grid_temp[1:Nz+1] \
+ grid_temp[0:Nz]) / (12*dz)
elif (order==3):
grid_temp = np.vstack((np.zeros(Nx),np.zeros(Nx),np.zeros(Nx), grid, np.zeros(Nx),np.zeros(Nx),np.zeros(Nx)))
prime_grid = ( grid_temp[6:Nz+6] \
- 9*grid_temp[5:Nz+5] \
+ 45*grid_temp[4:Nz+4] \
- 45*grid_temp[2:Nz+2] \
+ 9*grid_temp[1:Nz+1] \
- grid_temp[0:Nz] ) / (60*dz)
else:
raise ValueError(' order value has to be 1 or 2 or 3!! ')
return prime_grid |
Java | UTF-8 | 249 | 1.765625 | 2 | [] | no_license | package cj.netos.exchange;
import cj.netos.exchange.bo.SelectKey;
import cj.netos.exchange.model.WenyPurchRecord;
import java.util.List;
public interface IPurchaseService {
List<WenyPurchRecord> page(SelectKey key, int limit, long offset);
}
|
C++ | UTF-8 | 5,410 | 2.640625 | 3 | [] | no_license | # include "stdafx.h"
/***************************************************************************
**
** INVOCATION NAME: G123DSTR
**
** PURPOSE: TO RETRIEVE A STRING INTO A CHARACTER BUFFER BASED ON DELIMITOR
**
** INVOCATION METHOD: G123DSTR(IN_STR, BUF_STR, DELIM)
**
** ARGUMENT LIST:
** NAME TYPE USE DESCRIPTION
** IN_STR[] PTR I POINTER TO A INPUT STRING
** BUF_STR[] PTR I/O POINTER TO A BUFFER
** DELIM CHAR I DELIMITOR CHARACTER
** G123DSTR() LOGICAL O SUCCESS FLAG
**
** EXTERNAL FUNCTION REFERENCES: NONE
**
** INTERNAL VARIABLES:
** NAME TYPE DESCRIPTION
** FTPOS LONG POSITION OF FIELD TERMITATOR
** DLPOS LONG POSITION OF DELIMITOR
** DLSTR[2] CHAR DELIMITOR CHARACTER STRING
**
** GLOBAL REFERENCES: NONE
**
** GLOBAL VARIABLES: NONE
**
** GLOBAL CONSTANTS:
** NAME TYPE DESCRIPTION
** FT CHAR FIELD TERMINATOR
** FT_STR CHAR[2] FIELD TERMINATOR STRING
** NC CHAR NULL CHARACTER
**
** CHANGE HISTORY:
** AUTHOR CHANGE_ID DATE CHANGE SUMMARY
** A. DEWITT 04/23/90 INITIAL PROLOG
** A. DEWITT 04/23/90 INITIAL PDL
** L. MCMILLION 05/09/90 INITIAL CODE
** A. DEWITT 92DR005 04/08/92 ADD FEOF() CALL FOR BINARY FILE
** L. MCMILLION TASK #40 12/15/92 PROLOG/PDL/INLINE COMMENT UPDATED
** J. TAYLOR 93DR023 04/16/93 REDESIGNED TO RETRIEVE STRING
** FROM INPUT STRING RATHER THAN
** FILE
** L. MCMILLION 93DR023 05/13/93 INSERTED SIZE_T CAST FOR STRNCPY
** ARGUMENT
** J. TAYLOR 93DR031 06/16/93 MODIFIED TO STORE DELIMITER IN
** CHARACTER STRING BEFORE CALL TO
** STRCSPN()
**
** PDL:
**
** IF THERE IS A FIELD TERMINATOR IN THE INPUT STRING
** THEN
** SET FTPOS TO POSITION OF FIELD TERMINATOR
** ELSE
** SET FTPOS TO ZERO
** ENDIF
** IF THERE IS A DELIMITOR IN THE INPUT STRING
** THEN
** STORE DELIMITOR IN CHARACTER STRING
** TERMINATE CHARACTER STRING WITH NULL CHARACTER
** SET DLPOS TO POSITION OF DELIMITOR
** ELSE
** SET DLPOS TO ZERO
** ENDIF
** IF DELIMITOR OCCURS BEFORE OR IS FIELD TERMINATOR
** OR DELIMITOR OCCURS BUT FIELD TERMINATOR DOES NOT
** THEN
** COPY DELIMITED STRING FROM INPUT STRING TO BUF_STR
** MOVE BEGINNING OF INPUT STRING PAST DELIMITOR
** APPEND NULL CHARACTER TO BUF_STR
** ELSE IF FIELD TERMINATOR OCCURS BEFORE DELIMITOR
** OR FIELD TERMINATOR OCCURS BUT DELIMITOR DOES NOT
** THEN
** COPY TERMINATED STRING FROM INPUT STRING TO BUF_STR
** MOVE BEGINNING OF INPUT STRING PAST FIELD TERMINATOR
** APPEND NULL CHARACTER TO BUF_STR
** ELSE IF THERE IS NEITHER A DELIMITOR OR FIELD TERMINATOR
** THEN
** RETURN FAILURE
** ENDIF
**
** RETURN SUCCESS
**
*****************************************************************************
** CODE SECTION
**
*****************************************************************************/
#include "stc123.h"
int g123dstr(char **in_str,char *buf_str,int delim)
{
/* LOCAL VARIABLES */
long dlpos;
long ftpos;
char dlstr[2];
/* IF THERE IS A FIELD TERMINATOR IN THE INPUT STRING */
if (strchr(*in_str,FT))
/* SET FTPOS TO POSITION OF FIELD TERMINATOR */
ftpos = strcspn(*in_str,FT_STR) + 1L;
/* ELSE SET FTPOS TO ZERO */
else ftpos = 0;
/* IF THERE IS A DELIMITOR IN THE INPUT STRING */
if (strchr(*in_str,delim)) {
/* STORE DELIMITOR IN CHARACTER STRING */
dlstr[0] = delim;
/* TERMINATE CHARACTER STRING WITH NULL CHARACTER */
dlstr[1] = NC;
/* SET DLPOS TO POSITION OF DELIMITOR */
dlpos = strcspn(*in_str,dlstr) + 1L;
}
/* ELSE SET DLPOS TO ZERO */
else dlpos = 0;
/* IF DELIMITOR OCCURS BEFORE OR IS FIELD TEMRINATOR
OR DELIMITOR OCCURS BUT FIELD TERMINATOR DOES NOT */
if (((dlpos) && (dlpos <= ftpos))
|| ((dlpos) && (!ftpos))) {
/* COPY DELIMITED STRING FROM INPUT STRING TO BUF_STR */
strncpy(buf_str,*in_str,(size_t)dlpos-1);
/* MOVE BEGINNING OF INPUT STRING PAST DELIMITOR */
*in_str = *in_str + dlpos;
/* APPEND NULL CHARACTER TO BUF_STR */
buf_str[dlpos-1] = NC;
}
/* ELSE IF FIELD TERMINATOR OCCURS BEFORE DELIMITOR
OR FIELD TERMINATOR OCCURS BUT DELIMITOR DOES NOT */
else if (((ftpos) && (ftpos < dlpos))
|| ((ftpos) && (!dlpos))) {
/* COPY TERMINATED STRING FROM INPUT STRING TO BUF_STR */
strncpy(buf_str,*in_str,(size_t)ftpos);
/* MOVE BEGINNING OF INPUT STRING PAST FIELD TERMINATOR */
*in_str = *in_str + ftpos;
/* APPEND NULL CHARACTER TO BUF_STR */
buf_str[ftpos] = NC;
}
/* ELSE IF THERE IS NEITHER A DELIMITOR OR FIELD TERMINATOR */
else if ((!dlpos) && (!ftpos)) {
/* RETURN FAILURE */
return(0);
}
/* RETURN SUCCESS */
return(1);
}
|
Python | UTF-8 | 1,685 | 3.71875 | 4 | [] | no_license | import logging
RIGHT = "R"
class Rover(object):
def __init__(self, x, y, facing):
self.facing = facing
self.position = (x, y)
def go(self, instructions):
for instruction in list(instructions):
self.execute(instruction)
def execute(self, instruction):
if instruction == RIGHT:
return self.right()
if instruction == "L":
return self.left()
if instruction == "F":
if self.facing == "N":
self.position = (self.position[0], self.position[1] + 1)
if self.facing == "E":
self.position = (self.position[0] + 1, self.position[1])
if self.facing == "S":
self.position = (self.position[0], self.position[1] - 1)
if self.facing == "W":
self.position = (self.position[0] - 1, self.position[1])
if instruction == "B":
if self.facing == "N":
self.position = (self.position[0], self.position[1] - 1)
if self.facing == "E":
self.position = (self.position[0] - 1, self.position[1])
if self.facing == "S":
self.position = (self.position[0], self.position[1] + 1)
if self.facing == "W":
self.position = (self.position[0] + 1, self.position[1])
def left(self):
anti_clockwise = ["N", "W", "S", "E"]
self.turn(anti_clockwise)
def right(self):
clockwise = ["N", "E", "S", "W"]
self.turn(clockwise)
def turn(self, compass):
current = compass.index(self.facing)
self.facing = compass[(current + 1) % 4]
|
Shell | UTF-8 | 2,639 | 3.4375 | 3 | [] | no_license | #!/bin/bash
output_file="result.log"
seed=0
problem_set=xing.problem.CircularProblem
while (( $# ))
do
case $1 in
--output)
shift
output_file=$1
;;
--seed)
shift
seed=$1
;;
--problem-set)
shift
problem_set=$1
;;
esac
shift
done
script_dir=$(dirname $0)
export PATH="$PATH:$PWD/$script_dir"
pushd . > /dev/null
cd "$script_dir/../java/build" > /dev/null
build_dir="$PWD"
popd > /dev/null
echo $build_dir
program_option="xing.app.text.TextRunner"
program_option+=" $problem_set xing.algorithm.StochasticNicheAlgorithm"
program_option+=" --problem-args --problem-size,200,--circles,3"
(
for death_count in $(seq 1 10)
do
death_rate=$(calc '*' $death_count 0.1 | sed -E 's/(\.)*0+$//g')
# population * death_rate * 2 == raw_evaluation
# Standard evaluation = population * 10000 * 0.75
# Iteration std evaluation / raw_evaluation = 10000 * 0.375 / death_rate
iteration=$(calc '+' $(calc '/' 3750 $death_rate) 0.5 \
| sed -E 's/\..+//g')
for replace_count in $(seq 0 9)
do
replace_rate=$(calc '*' $replace_count 0.1)
for mutation_count in $(seq 0 10)
do
echo "Updating...$death_count $replace_count $mutation_count" \
>> /tmp/xing.log
mutation_rate=$(calc '*' $mutation_count 0.1)
test $(calc '>' \
$(calc '+' $mutation_rate $replace_rate) 1.0) \
-gt 0 && break
migration_rate=$(calc '-' 1.0 \
$(calc '+' $replace_rate $mutation_rate))
echo "===================="
echo Iteration: $iteration
echo Death rate: $death_rate
echo Replace rate: $replace_rate
echo Mutation rate: $mutation_rate
echo Migration rate: $migration_rate
config=--sampler,stochastic
config+=,--algorithm-seed,$seed
config+=,--replace-rate,$replace_rate
config+=,--death-rate,$death_rate
config+=,--mutation-rate,$mutation_rate
config+=,--migration-rate,$migration_rate
config+=,--iteration,$iteration
java -cp "$build_dir" $program_option --algorithm-args $config
done
done
done
) > $output_file
echo "Execution finished"| mail -s "Project result" -a $output_file sc18xy@leeds.ac.uk
|
Java | UTF-8 | 2,506 | 2.046875 | 2 | [] | no_license | package com.examples.twitterapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.widget.RelativeLayout;
import com.examples.twitterapp.main.ui.MainActivity;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterAuthToken;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
public class LoginActivity extends AppCompatActivity {
private TwitterLoginButton loginButton;
private RelativeLayout loginContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (TwitterLoginButton) findViewById(R.id.twitterLogginButton);
loginContainer = (RelativeLayout) findViewById(R.id.container);
if (TwitterCore.getInstance().getSessionManager().getActiveSession() != null) {
navigateToMainScreen();
}
loginButton.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
navigateToMainScreen();
}
@Override
public void failure(TwitterException exception) {
String msgError = String.format(getString(R.string.login_error_message), exception.getMessage());
Snackbar.make(loginContainer, msgError, Snackbar.LENGTH_SHORT).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
loginButton.onActivityResult(requestCode, resultCode, data);
}
public void navigateToMainScreen() {
TwitterAuthToken authToken = TwitterCore.getInstance().getSessionManager().getActiveSession().getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
|
Markdown | UTF-8 | 769 | 2.875 | 3 | [
"MIT"
] | permissive | # elm-brunch
Brunch plugin to compile Elm code
# Install Elm
[Elm instalation instructions](http://elm-lang.org/Install.elm)
# Tips
Update the "source-directories" property in the elm-package.json file if you want to compile multifile elm projects.
Then configure elm-brunch:
```
// Configure your plugins
plugins: {
...
elmBrunch: {
// Set to the elm file(s) containing your "main" function
// `elm make` handles all elm dependencies
mainModules: ['source/path/YourMainModule.elm'],
// Defaults to 'js/' folder in paths.public
outputFolder: 'some/path/'
}
}
```
The output filename is the lowercase version of the main module name:
```
YourMainModule.elm => outputFolder/yourmainmodule.elm
```
|
Java | UTF-8 | 781 | 1.945313 | 2 | [] | no_license | package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
/**
* Created by User on 2/29/2016.
*/
public class BoutiqueListPage extends BasePage { //список бутиков в админке
public static final By addNewBoutique = By.xpath("//span[text()='Добавить новый бутик']");
public static final By boutiqueTable = By.id("boutiqueGrid_table");
public static By getBoutiqueLocatorByName(String name) {
return By.xpath("//td[contains(text(), '" + name + "')]");
}
public BoutiqueListPage(WebDriver driver, WebDriverWait wait){
super(driver, wait);
url = url + "index.php/admin_boutique/adminhtml_boutique/index/key/";
}
}
|
Java | UTF-8 | 8,517 | 2.40625 | 2 | [] | no_license | package model.tester;
import model.CSMT;
import model.CSMTImpl;
import model.TestUtils;
import model.node.LeafNode;
import model.proof.MembershipProof;
import model.proof.Proof;
import org.junit.Test;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.assertArrayEquals;
public class Tester {
@Test
public void merkleTreeTest() {
TestFactory.Test test = TestFactory.getRandomMerkelTest(10);
Merkle<String, byte[]> tree = new Merkle<>(test.hashes.length, test.input,
TestUtils.LEAF_HASH_FUNCTION,
TestUtils.NODE_HASH_FUNCTION);
checkProofs(test, tree);
}
@Test
public void CSMTInsertTest() {
CSMT<String, byte[]> tree = new CSMTImpl<>(
TestUtils.LEAF_HASH_FUNCTION,
TestUtils.NODE_HASH_FUNCTION);
TestFactory.Test test = TestFactory.makeCSMTTest("abc", "cde", "efg", "ghi", "ijk");
for (int i = 0; i != test.input.length; i++) {
tree.insert(BigInteger.valueOf(i), test.input[i]);
}
checkProofs(test, tree);
}
@Test
public void CSMTRemoveTest() {
CSMT<String, byte[]> tree = new CSMTImpl<>(
TestUtils.LEAF_HASH_FUNCTION,
TestUtils.NODE_HASH_FUNCTION);
TestFactory.Test test = TestFactory.makeCSMTTest("abc", "cde", "efg", "ghi", "ijk");
for (int i = 0; i != test.input.length; i++) {
tree.insert(BigInteger.valueOf(i), test.input[i]);
}
for (int i = 0; i != test.input.length; i++) {
test.remove(i);
tree.remove(BigInteger.valueOf(i));
checkProofs(test, tree);
}
}
@Test
public void stressRemoveSCMTTest() {
CSMT<String, byte[]> tree = new CSMTImpl<>(
TestUtils.LEAF_HASH_FUNCTION,
TestUtils.NODE_HASH_FUNCTION);
TestFactory.Test test = TestFactory.getRandomCSMTTest(1000);
for (int i = 0; i != test.input.length; i++) {
tree.insert(BigInteger.valueOf(i), test.input[i]);
}
for (int i = 0; i != test.input.length; i++) {
test.remove(i);
tree.remove(BigInteger.valueOf(i));
checkProofs(test, tree);
}
}
@Test
public void stressInsertCSMTTest() {
CSMT<String, byte[]> tree = new CSMTImpl<>(
TestUtils.LEAF_HASH_FUNCTION,
TestUtils.NODE_HASH_FUNCTION);
TestFactory.Test test = TestFactory.getRandomCSMTTest(500_000);
for (int i = 0; i != test.input.length; i++) {
tree.insert(BigInteger.valueOf(i), test.input[i]);
}
checkProofs(test, tree);
}
private void checkProofs(TestFactory.Test test, CSMT<String, byte[]> tree) {
final int high = TestUtils.log2(test.input.length);
for (int i = 0; i != test.input.length; i++) {
Proof proof = tree.getProof(BigInteger.valueOf(i));
if (proof instanceof MembershipProof) {
MembershipProof membershipProof = (MembershipProof) proof;
LeafNode leaf = membershipProof.getNode();
assertArrayEquals(test.hashes[0][i], (byte[]) leaf.getHash());
int index = i;
Iterator proofIterator = membershipProof.getProof().iterator();
for (int h = 0; h != high; h++) {
int currIndex = index % 2 == 0 ? index + 1 : index - 1;
byte[] testHash = test.hashes[h][currIndex];
if (testHash != null) {
byte[] currHash = (byte[]) ((MembershipProof.Entry) proofIterator.next()).getHash();
assertArrayEquals("at index=" + i + " at level: " + h, testHash, currHash);
}
index /= 2;
}
}
}
}
private void checkProofs(TestFactory.Test test, Merkle<String, byte[]> merkleTree) {
final int high = TestUtils.log2(test.input.length);
for (int i = 0; i != test.input.length; i++) {
MerkleProof proof = merkleTree.getProof(i);
assertArrayEquals(test.hashes[0][i], (byte[]) proof.getTargetByteArray());
List neighbors = proof.getNeighbors();
int index = i;
for (int h = 0; h != high; h++) {
int currIndex = index % 2 == 0 ? index + 1 : index - 1;
byte[] currHash = (byte[]) neighbors.get(h);
assertArrayEquals("at index=" + i + " at level: " + h,
test.hashes[h][currIndex], currHash);
index /= 2;
}
}
}
@Test
public void timeTest() {
System.out.println("time test:");
for (int numberOfElements = 100_000; numberOfElements <= 800_000; numberOfElements *= 2) {
BigInteger[] keys = new BigInteger[numberOfElements];
String[] input = new String[numberOfElements];
final int high = (int) Math.ceil(TestUtils.log2(
TestUtils.toPow2(input.length))) + 1;
for (int i = 0; i != numberOfElements; i++) {
keys[i] = BigInteger.valueOf(i);
input[i] = TestFactory.getRandomString(10);
}
Merkle<String, byte[]> treeMerkle = new Merkle<>(high, input,
TestUtils.LEAF_HASH_FUNCTION,
TestUtils.NODE_HASH_FUNCTION);
long time = -System.currentTimeMillis();
for (int i = 0; i != numberOfElements; i++) {
treeMerkle.getProof(i);
}
System.out.println(String.format("for %d elements Merkle tree: %d",
numberOfElements, System.currentTimeMillis() + time));
CSMT<String, byte[]> treeCSMT = new CSMTImpl<>(TestUtils.LEAF_HASH_FUNCTION, TestUtils.NODE_HASH_FUNCTION);
for (int i = 0; i != numberOfElements; i++) {
treeCSMT.insert(keys[i], input[i]);
}
time = -System.currentTimeMillis();
for (int i = 0; i != numberOfElements; i++) {
treeCSMT.getProof(keys[i]);
}
System.out.println(String.format("for %d elements CSMT: %d",
numberOfElements, System.currentTimeMillis() + time));
System.out.println();
}
}
@Test
public void KeyTimeTest() {
final int step = 50_000;
System.out.println("key time test step: " + step);
for (int count = 100_000; count < 6_000_000; count *= 2) {
BigInteger[] keys = new BigInteger[count];
String[] input = new String[count];
final int high = (int) Math.ceil(TestUtils.log2(
TestUtils.toPow2(input.length))) + 1;
final int numberOfElements = count / step;
System.out.println(String.format("for %d input elements with step %d and %d operations",
numberOfElements, step, numberOfElements * 10000));
for (int i = 0; i != count; i++) {
keys[i] = BigInteger.valueOf(i);
if (i % step == 0) {
input[i] = TestFactory.getRandomString(7);
}
}
Merkle<String, byte[]> treeMerkle = new Merkle<>(high, input,
TestUtils.LEAF_HASH_FUNCTION,
TestUtils.NODE_HASH_FUNCTION);
long time = -System.currentTimeMillis();
for (int k = 0; k != 10000; k++) {
for (int i = 0; i < count; i += step) {
treeMerkle.getProof(i);
}
}
System.out.println(String.format("Merkle tree has %d nulls, time: %d",
treeMerkle.countNulls(), System.currentTimeMillis() + time));
CSMT<String, byte[]> treeCSMT = new CSMTImpl<>(TestUtils.LEAF_HASH_FUNCTION, TestUtils.NODE_HASH_FUNCTION);
for (int i = 0; i < count; i += step) {
treeCSMT.insert(keys[i], input[i]);
}
time = -System.currentTimeMillis();
for (int k = 0; k != 10000; k++) {
for (int i = 0; i < count; i += step) {
treeCSMT.getProof(keys[i]);
}
}
System.out.println("CSMT time: " + (System.currentTimeMillis() + time));
System.out.println();
}
}
}
|
Java | UTF-8 | 861 | 2.3125 | 2 | [] | no_license | package ru.netology.test.geo;
import org.junit.jupiter.api.Assertions;
import ru.netology.entity.Country;
import ru.netology.entity.Location;
import ru.netology.geo.GeoServiceImpl;
public class GeoServiceImplTest {
@org.junit.jupiter.api.Test
void GeoServiceImplTest() {
//given
String ipMoscow = "172.";
String ipNY = "96.";
GeoServiceImpl gs = new GeoServiceImpl();
Location resultLocationM = gs.byIp(ipMoscow);
Location resultLocationNY = gs.byIp(ipNY);
//when
Location exeptedLocationM = new Location("Moscow", Country.RUSSIA, null, 0);
Location exeptedLocationNY = new Location("New York", Country.USA, null, 0);
//then
Assertions.assertEquals(resultLocationM, exeptedLocationM);
Assertions.assertEquals(resultLocationNY, exeptedLocationNY);
}
} |
JavaScript | UTF-8 | 5,779 | 2.625 | 3 | [] | no_license | 'use strict';
//The graph object draws the graph and interpolates its axis boundaries based on the data it is fed
function scatterPlot(argv) {
scatterPlot.superClass.constructor.call(this, argv);
this.mainSvg = this.canvasPtr;
this.miniCanvasPtr = null;
this.baseCSSClass = 'scatterPoint';
this.fadeCSSClass = 'fadeOut';
this.datumSvgs = 'points';
this.xMax = argv.xMax || 3;
this.xMin = argv.xMin || -3;
this.yMax = argv.yMax || 3;
this.yMin = argv.yMin || -3;
this.minified = false;
this.minifiedSize = argv.minifiedSize || 200;
this.pointRadius = argv.pointRadius || 6;
this.svgPoints = [];
}
extend(scatterPlot, graphObject);
//changes the value that is currently displayed (total tasks, seconds / task, delay / task, etc.) by modifying
//the data object that will ALWAYS be graphed
scatterPlot.prototype.setYAttr = function() {
this.setAxes();
this.firstTimeData = null;
for (var i in this.data) {
var cssClass;
if (this.data[i].id == 'R')
cssClass = 'c_rep';
else if (this.data[i].id == 'D')
cssClass = 'c_dem';
else
cssClass = 'c_ind';
var nameSubStr = this.data[i].name.substring(0, this.data[i].name.length - 5);
this.data[i].nameSubStr = nameSubStr
this.data[i].scatterNdx = i;
this.data[i].cssClass = cssClass;
this.currentlyViewedData[i] = {
'data': this.data[i],
'id': nameSubStr + i + 'Point',
'title': this.data[i].name,
'party': this.data[i].id,
'xVal': this.data[i].x,
'yVal': this.data[i].y,
'y': this.mapYValToGraph(this.data[i].y),
'x': this.mapXValToGraph(this.data[i].x),
'cssClass': this.baseCSSClass + ' ' + cssClass,
'svgLabel': null
};
}
if (this.minified)
this.drawMinified();
else
this.draw();
};
scatterPlot.prototype.minify = function(minifiedSize) {
if(!this.minified){
this.minified = true;
this.xLen = 3;
this.yLen = 3;
this.minifiedSize = minifiedSize;
//create the new mini plot
if (!this.miniCanvasPtr) {
this.miniCanvasPtr = d3.select('#scatterMiniCanvas').append('svg')
.attr('id', 'scatterMiniSvg');
}
this.miniCanvasPtr
.style('height', this.minifiedSize)
.style('width', this.minifiedSize)
.attr('viewBox', '0 0 ' + (this.minifiedSize + 50) + ' ' + (this.minifiedSize + 45))
.attr('preserveAspectRatio', 'xMidYMid');
this.mainSvg = this.canvasPtr;
this.canvasPtr = this.miniCanvasPtr;
this.pointRadius = 3;
this.height = this.minifiedSize;
this.width = this.minifiedSize;
this.y = this.minifiedSize;
this.x = 40;
//Destroy the large graph
this.destroyAll();
this.mainSvg.style('height', 0);
this.mapXValToGraph(this.xMin);
this.setYAttr();
}
};
scatterPlot.prototype.drawMinified = function() {
this.drawCenterLine();
this.drawPoints();
this.drawYAxis();
this.drawXAxis();
};
scatterPlot.prototype.draw = function() {
// this.mouseOver = elementMouseOverClosure(this.x, this.y);
// this.mouseOut = elementMouseOutClosure();
this.drawCenterLine();
this.drawPoints();
this.drawYAxisLabel();
this.drawXAxisLabel();
this.drawAxesLegends();
this.drawYAxis();
this.drawXAxis();
this.drawTitle();
};
//------------------------------------------------------------------------------------------------------
//DRAW METHODS - Everything below handles the brunt of the D3 code and draws everything to the canvas
//------------------------------------------------------------------------------------------------------
//Creates the points
scatterPlot.prototype.drawPoints = function() {
var rad = this.pointRadius;
this.svgElements['points'] = this.canvasPtr.selectAll('Points')
.data(this.currentlyViewedData)
.enter()
.append('circle')
.attr('class', function(d) {return d.cssClass;})
.attr('shape-rendering', 'geometricPrecision')
.attr('id', function(d) { return d.id;})
// .style("stroke-width", "2px")
// .style("fill", function(d) {return d.color})
// .style("stroke", function(d) {return d.color})
// .style("stroke-width", 0)
.attr({
cx: function(d) {
d.svgPoint = this;
return d.x;},
cy: function(d) {return d.y;},
r: rad//function(d) {return d.r;},
});
// .on("mouseover", this.mouseOver)
// .on("mouseout", this.mouseOut);
};
scatterPlot.prototype.drawAxesLegends = function() {
var xLabelPadding = 55;
var yLabelPadding = 55;
var textData = [
{
text: 'Liberal',
x: this.x - yLabelPadding,
y: this.y - this.height / 8,
cssClass: 'demText',
align: 'vertical'},
{
text: 'Conservative',
x: this.x - yLabelPadding,
y: this.y - this.height * 7 / 8,
cssClass: 'repText',
align: 'vertical'},
{
text: 'Liberal',
x: this.x + this.width / 8,
y: this.y + xLabelPadding,
cssClass: 'demText',
align: 'horizontal'},
{
text: 'Conservative',
x: this.x + this.width * 7 / 8 ,
y: this.y + xLabelPadding,
cssClass: 'repText',
align: 'horizontal'}
];
this.svgElements['axesLegends'] = this.canvasPtr.selectAll('axesLegend')
.data(textData)
.enter()
.append('text')
.attr('text-anchor', 'middle')
.attr('alignment-baseline', 'middle')
.attr({
class: function(d) {return d.cssClass;},
x: function(d) {return d.x;},
y: function(d) {return d.y;},
transform: function(d) {
if (d.align == 'vertical')
return 'rotate(-90 ' + d.x + ' ' + d.y + ')';
return 'rotate(0 0 0)';
},
id: 'axesLegend'})
.text(function(d) {return d.text});
return this;
};
scatterPlot.prototype.drawCenterLine = function() {
this.svgElements['centerLine'] = this.canvasPtr
.append('line')
.attr('x1', this.mapXValToGraph(this.xMin))
.attr('y1', this.mapYValToGraph(this.yMin))
.attr('x2', this.mapXValToGraph(this.xMax))
.attr('y2', this.mapYValToGraph(this.yMax))
.attr('stroke', '#000')
.style('stroke-width', '3px')
.style('opacity', 0.6);
};
|
Java | UTF-8 | 1,005 | 2.140625 | 2 | [] | no_license | package com.example.lb1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
View tw1 = (View) findViewById(R.id.textView2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(tw1.getVisibility() == View.INVISIBLE){
tw1.setVisibility(View.VISIBLE);
}
else
tw1.setVisibility(View.INVISIBLE);
}
});
}
} |
C# | UTF-8 | 1,220 | 2.796875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace CodeTheWay.Models
{
public class FinancialDonor
{
[Key]
public int Id { get; set; }
[DisplayName("First Name")]
[Required]
public string FirstName { get; set; }
[DisplayName("Last Name")]
[Required]
public string LastName { get; set; }
[EmailAddress]
[Required]
public string Email { get; set; }
/// <summary>
/// An enum that represents how often payments are scheduled.
/// </summary>
public enum Frequency
{
[Display(Name = "Biannual")] BIANNUAL,
[Display(Name = "Weekly")] WEEKLY,
[Display(Name = "Monthly")] MONTHLY,
[Display(Name = "Yearly")] YEARLY,
[Display(Name = "Once")] ONCE
}
[DisplayName("Estimated Amount")]
[DataType(DataType.Currency)]
[Required]
public double EstAmt { get; set; }
[DisplayName("Current Frequency")]
public Frequency CurrentFrequency { get; set; }
}
} |
Markdown | UTF-8 | 14,937 | 3.375 | 3 | [
"Apache-2.0"
] | permissive | ## 1、java中在参数传递时有2种方式
按值传递:值传递是指在调用函数时将实际参数复制一份传递到函数中,这样在函数中如果对参数进行修改,将不会影响到实际参数。
按引用传递:引用传递其实就弥补了上面说的不足,如果每次传参数的时候都复制一份的话,如果这个参数占用的内存空间太大的话,运行效率会很底下,所以引用传递就是直接把内存地址传过去,也就是说引用传递时,操作的其实都是源数据。
## 2、corePoolSize 、maximumPoolSize
线程池的基本大小,即在没有任务需要执行的时候线程池的大小,并且只有在工作队列满了的情况下才会创建超出这个数量的线程。这里需要注意的是:在刚刚创建ThreadPoolExecutor的时候,线程并不会立即启动,而是要等到有任务提交时才会启动,除非调用了prestartCoreThread/prestartAllCoreThreads事先启动核心线程。再考虑到keepAliveTime和allowCoreThreadTimeOut超时参数的影响,所以没有任务需要执行的时候,线程池的大小不一定是corePoolSize。
如果当前大小已经达到了corePoolSize 大小,就将新提交的任务提交到阻塞队列排队,等候处理workQueue.offer(command);
如果队列容量已达上限,并且当前大小poolSize没有达到maximumPoolSize,那么就新增线程来处理任务;
如果队列已满,并且当前线程数目也已经达到上限,那么意味着线程池的处理能力已经达到了极限,此时需要拒绝新增加的任务。至于如何拒绝处理新增
## 3、WeakHashMap 以及ThreadLocal
WeakHashMap的key是用的WeakReference,在没有其它强引用的情况下,下一次GC时才会被垃圾回收
- key和value都没有引用的时候,key都会被回收
- key如果有强引用的话,key是不会被回收的,value也不会被回收
- 如果value有强引用的话,key没有被强引用,也是照样可以被回收的
tomcat 使用的是线程池,在请求后,线程并不收回,所以ThreadLocal的key也没有被收回,因为key没有被收回,value也不会被收回。
ThreadLocal最好要配合remove()方法来用。
## 4、Class.forName和classloader的区别
java中Class.forName 和ClassLoader.loadClass( 都可用来对类进行加载。
class.forName()前者除了将类的.class文件加载到jvm中之外,还会对类进行解释,执行类中的static块。
而classLoader只干一件事情,就是将.class文件加载到jvm中,不会执行static中的内容,只有在newInstance才会去执行static块。
## 5、session和cookie的区别和联系,session的生命周期,多个服务部署时session管理。
cookie机制采用的是在客户端保持状态的方案,而session机制采用的是在服务器端保持状态的方案
一、对于cookie:
①cookie是创建于服务器端
②cookie保存在浏览器端
③cookie的生命周期可以通过cookie.setMaxAge(2000);来设置,如果没有设置setMaxAge,
则cookie的生命周期当浏览器关闭的时候,就消亡了
④cookie可以被多个同类型的浏览器共享 可以把cookie想象成一张表
比较:
①存在的位置:
cookie 存在于客户端,临时文件夹中
session:存在于服务器的内存中,一个session域对象为一个用户浏览器服务
②安全性
cookie是以明文的方式存放在客户端的,安全性低,可以通过一个加密[算法](http://lib.csdn.net/base/datastructure)进行加密后存放
session存放于服务器的内存中,所以安全性好
③网络传输量
cookie会传递消息给服务器
session本身存放于服务器,不会有传送流量
④生命周期(以20分钟为例)
(1)cookie的生命周期是累计的,从创建时,就开始计时,20分钟后,cookie生命周期结束,
(2)session的生命周期是间隔的,从创建时,开始计时如在20分钟,没有访问session,那么session生命周期被销毁
但是,如果在20分钟内(如在第19分钟时)访问过session,那么,将重新计算session的生命周期
(3)关机会造成session生命周期的结束,但是对cookie没有影响
⑤访问范围
session为一个用户浏览器独享
cookie为多个用户浏览器共享
## 6、Java中的队列都有哪些,有什么区别。
1、没有实现的阻塞接口的LinkedList: 实现了java.util.Queue接口和java.util.AbstractQueue接口
内置的不阻塞队列:
PriorityQueue 和 ConcurrentLinkedQueue
2)实现阻塞接口的:
java.util.concurrent 中加入了 BlockingQueue 接口和五个阻塞队列类。它实质上就是一种带有一点扭曲的 FIFO 数据结构。不是立即从队列中添加或者删除元素,线程执行操作阻塞,直到有空间或者元素可用。 五个队列所提供的各有不同:
* ArrayBlockingQueue :一个由数组支持的有界队列。
* LinkedBlockingQueue :一个由链接节点支持的可选有界队列。
* PriorityBlockingQueue :一个由优先级堆支持的无界优先级队列。
* DelayQueue :一个由优先级堆支持的、基于时间的调度队列。
* SynchronousQueue :一个利用 BlockingQueue 接口的简单聚集(rendezvous)机制。
1.ArrayDeque, (数组双端队列) 2.PriorityQueue, (优先级队列) 3.ConcurrentLinkedQueue, (基于链表的并发队列) 4.DelayQueue, (延期阻塞队列)(阻塞队列实现了BlockingQueue接口) 5.ArrayBlockingQueue, (基于数组的并发阻塞队列) 6.LinkedBlockingQueue, (基于链表的FIFO阻塞队列) 7.LinkedBlockingDeque, (基于链表的FIFO双端阻塞队列) 8.PriorityBlockingQueue, (带优先级的无界阻塞队列) 9.SynchronousQueue (并发同步阻塞队列)
## 7、newFixedThreadPool此种线程池如果线程数达到最大值后会怎么办,底层原理
## 8、Java中两个线程是否可以同是访问一个对象的两个不同的synchronized方法?
多个线程访问同一个类的synchronized方法时, 都是串行执行的 ! 就算有多个cpu也不例外 ! synchronized方法使用了类java的内置锁, 即锁住的是方法所属对象本身. 同一个锁某个时刻只能被一个执行线程所获取, 因此其他线程都得等待锁的释放. 因此就算你有多余的cpu可以执行, 但是你没有锁, 所以你还是不能进入synchronized方法执行, CPU因此而空闲. 如果某个线程长期持有一个竞争激烈的锁, 那么将导致其他线程都因等待所的释放而被挂起, 从而导致CPU无法得到利用, 系统吞吐量低下. 因此要尽量避免某个线程对锁的长期占有 !
为了避免对锁的竞争, 你可以使用锁分解,锁分段以及减少线程持有锁的时间, 如果上诉程序中的syncMethod1和syncMethod2方法是两个不相干的方法(请求的资源不存在关系), 那么这两个方法可以分别使用两个不同的锁
```java
public class SyncMethod {
private Object lock1 = new Object();
private Object lock2 = new Object();
public void syncMethod2() {
synchronized (lock1) {
try {
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@ (syncMethod2, 已经获取内置锁`SyncMethod.this`)");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@ (syncMethod2, 即将释放内置锁`SyncMethod.this`)");
}
}
public void syncMethod1() {
synchronized (lock2) {
System.out.println("######################## (syncMethod1, 已经获取内置锁`SyncMethod.this`, 并即将退出)");
}
}
}
```
## 一个类的static构造方法加上synchronized之后的锁的影响。
synchronized是对类的**当前实例(当前对象)**进行加锁,防止其他线程同时访问该类的该实例的所有synchronized块,注意这里是“类的当前实例”, 类的两个不同实例就没有这种约束了。
那么static synchronized恰好就是要控制类的所有实例的并发访问,static synchronized是限制多线程中该类的所有实例同时访问jvm中该类所对应的代码块。实际上,在类中如果某方法或某代码块中有 synchronized,那么在生成一个该类实例后,该实例也就有一个监视块,防止线程并发访问该实例的synchronized保护块,而static synchronized则是所有该类的所有实例公用得一个监视块,这就是他们两个的区别。也就是说synchronized相当于 this.synchronized,而static synchronized相当于AClass.synchronized.
## 9、JVM内存结构
内存结构:
1、指令计数器
2、堆
3、栈
4、方法区,包括类型的常量池、字段,方法信息、方法字节码。通常和永久区(Perm)关联在一起。
5、本地方法栈
## 10、JVM类加载过程
## 11、java.有几种锁,锁的原理是什么
- 公平锁/非公平锁
- 可重入锁
- 独享锁/共享锁
- 互斥锁/读写锁
- 乐观锁/悲观锁
- 分段锁
- 偏向锁/轻量级锁/重量级锁
- 自旋锁
上面是很多锁的名词,这些分类并不是全是指锁的状态,有的指锁的特性,有的指锁的设计,下面总结的内容是对每个锁的名词进行一定的解释。
### 公平锁/非公平锁
公平锁是指多个线程按照申请锁的顺序来获取锁。
非公平锁是指多个线程获取锁的顺序并不是按照申请锁的顺序,有可能后申请的线程比先申请的线程优先获取锁。有可能,会造成优先级反转或者饥饿现象。
对于Java `ReentrantLock`而言,通过构造函数指定该锁是否是公平锁,默认是非公平锁。非公平锁的优点在于吞吐量比公平锁大。
对于`Synchronized`而言,也是一种非公平锁。由于其并不像`ReentrantLock`是通过AQS的来实现线程调度,所以并没有任何办法使其变成公平锁。
## 可重入锁
可重入锁又名递归锁,是指在同一个线程在外层方法获取锁的时候,在进入内层方法会自动获取锁。说的有点抽象,下面会有一个代码的示例。
对于Java `ReentrantLock`而言, 他的名字就可以看出是一个可重入锁,其名字是`Re entrant Lock`重新进入锁。
对于`Synchronized`而言,也是一个可重入锁。可重入锁的一个好处是可一定程度避免死锁。
### 独享锁/共享锁
独享锁是指该锁一次只能被一个线程所持有。
共享锁是指该锁可被多个线程所持有。
对于Java `ReentrantLock`而言,其是独享锁。但是对于Lock的另一个实现类`ReadWriteLock`,其读锁是共享锁,其写锁是独享锁。
读锁的共享锁可保证并发读是非常高效的,读写,写读 ,写写的过程是互斥的。
独享锁与共享锁也是通过AQS来实现的,通过实现不同的方法,来实现独享或者共享。
对于`Synchronized`而言,当然是独享锁。
## 互斥锁/读写锁
上面讲的独享锁/共享锁就是一种广义的说法,互斥锁/读写锁就是具体的实现。
互斥锁在Java中的具体实现就是`ReentrantLock`
读写锁在Java中的具体实现就是`ReadWriteLock`
### 乐观锁/悲观锁
乐观锁与悲观锁不是指具体的什么类型的锁,而是指看待并发同步的角度。
悲观锁认为对于同一个数据的并发操作,一定是会发生修改的,哪怕没有修改,也会认为修改。因此对于同一个数据的并发操作,悲观锁采取加锁的形式。悲观的认为,不加锁的并发操作一定会出问题。
乐观锁则认为对于同一个数据的并发操作,是不会发生修改的。在更新数据的时候,会采用尝试更新,不断重新的方式更新数据。乐观的认为,不加锁的并发操作是没有事情的。
从上面的描述我们可以看出,悲观锁适合写操作非常多的场景,乐观锁适合读操作非常多的场景,不加锁会带来大量的性能提升。
悲观锁在Java中的使用,就是利用各种锁。
乐观锁在Java中的使用,是无锁编程,常常采用的是CAS算法,典型的例子就是原子类,通过CAS自旋实现原子操作的更新。
### 分段锁
分段锁其实是一种锁的设计,并不是具体的一种锁,对于`ConcurrentHashMap`而言,其并发的实现就是通过分段锁的形式来实现高效的并发操作。
我们以`ConcurrentHashMap`来说一下分段锁的含义以及设计思想,`ConcurrentHashMap`中的分段锁称为Segment,它即类似于HashMap(JDK7与JDK8中HashMap的实现)的结构,即内部拥有一个Entry数组,数组中的每个元素又是一个链表;同时又是一个ReentrantLock(Segment继承了ReentrantLock)。
当需要put元素的时候,并不是对整个hashmap进行加锁,而是先通过hashcode来知道他要放在那一个分段中,然后对这个分段进行加锁,所以当多线程put的时候,只要不是放在一个分段中,就实现了真正的并行的插入。
但是,在统计size的时候,可就是获取hashmap全局信息的时候,就需要获取所有的分段锁才能统计。
分段锁的设计目的是细化锁的粒度,当操作不需要更新整个数组的时候,就仅仅针对数组中的一项进行加锁操作。
### 偏向锁/轻量级锁/重量级锁
这三种锁是指锁的状态,并且是针对`Synchronized`。在Java 5通过引入锁升级的机制来实现高效`Synchronized`。这三种锁的状态是通过对象监视器在对象头中的字段来表明的。
偏向锁是指一段同步代码一直被一个线程所访问,那么该线程会自动获取锁。降低获取锁的代价。
轻量级锁是指当锁是偏向锁的时候,被另一个线程所访问,偏向锁就会升级为轻量级锁,其他线程会通过自旋的形式尝试获取锁,不会阻塞,提高性能。
重量级锁是指当锁为轻量级锁的时候,另一个线程虽然是自旋,但自旋不会一直持续下去,当自旋一定次数的时候,还没有获取到锁,就会进入阻塞,该锁膨胀为重量级锁。重量级锁会让其他申请的线程进入阻塞,性能降低。
### 自旋锁
在Java中,自旋锁是指尝试获取锁的线程不会立即阻塞,而是采用循环的方式去尝试获取锁,这样的好处是减少线程上下文切换的消耗,缺点是循环会消耗CPU。
几种常见的复杂度关系
浙江省软件行业协会网上
通知公告-> 3/培训通知 4、审报通知
8971-9267
O(1)<O(log(n))<O(n)<O(nlogn)<O(1)<O(log(n))<O(n)<O(nlogn)<O(n2)<O(2n)<O(n!)<O(nn)O(n2)<O(2n)<O(n!)<O(nn)
|
Markdown | UTF-8 | 4,424 | 2.65625 | 3 | [] | no_license | ---
description: "Recipe of Any-night-of-the-week Springy and Fluffy Whole Wheat Bread with Lots of Soy Milk"
title: "Recipe of Any-night-of-the-week Springy and Fluffy Whole Wheat Bread with Lots of Soy Milk"
slug: 299-recipe-of-any-night-of-the-week-springy-and-fluffy-whole-wheat-bread-with-lots-of-soy-milk
date: 2021-06-30T01:41:14.921Z
image: https://img-global.cpcdn.com/recipes/5253206245376000/680x482cq70/springy-and-fluffy-whole-wheat-bread-with-lots-of-soy-milk-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/5253206245376000/680x482cq70/springy-and-fluffy-whole-wheat-bread-with-lots-of-soy-milk-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/5253206245376000/680x482cq70/springy-and-fluffy-whole-wheat-bread-with-lots-of-soy-milk-recipe-main-photo.jpg
author: Marcus Stephens
ratingvalue: 4.7
reviewcount: 27212
recipeingredient:
- "200 grams Bread strong flour I used Haruyutaka blend"
- "50 grams Whole wheat flour coursely ground 30g finely ground 20g"
- "6 grams Skim milk powder"
- "20 grams Honey"
- "30 grams Nonsalted butter or shortening"
- "3 grams Dry yeast"
- "3 grams Salt"
- "180 ml Soy milk"
recipeinstructions:
- "Put all of the ingredients into the bread maker and let it knead the dough."
- "When the first rising has finished, separate into 8 sections. Let rest for 5-10 minutes."
- "Shape into balls and place on a baking tray. Use the oven's bread proofing function at 40°C for 25-35 minutes to let it rise a second time."
- "Dust with whole wheat flour, cut slits in the tops. Bake for 15 minutes at 170°C."
- "And it's done baking!"
- "Here's a brown sugar version. I also recommend this."
categories:
- Recipe
tags:
- springy
- and
- fluffy
katakunci: springy and fluffy
nutrition: 132 calories
recipecuisine: American
preptime: "PT38M"
cooktime: "PT49M"
recipeyield: "4"
recipecategory: Dessert
---

Hello everybody, I hope you're having an incredible day today. Today, we're going to prepare a special dish, springy and fluffy whole wheat bread with lots of soy milk. It is one of my favorites. This time, I'm gonna make it a little bit unique. This is gonna smell and look delicious.
Springy and Fluffy Whole Wheat Bread with Lots of Soy Milk is one of the most well liked of recent trending meals in the world. It's easy, it is quick, it tastes yummy. It's enjoyed by millions every day. They are fine and they look wonderful. Springy and Fluffy Whole Wheat Bread with Lots of Soy Milk is something that I've loved my whole life.
To get started with this recipe, we must prepare a few ingredients. You can have springy and fluffy whole wheat bread with lots of soy milk using 8 ingredients and 6 steps. Here is how you can achieve that.
<!--inarticleads1-->
##### The ingredients needed to make Springy and Fluffy Whole Wheat Bread with Lots of Soy Milk:
1. Take 200 grams Bread (strong) flour (I used Haruyutaka blend)
1. Prepare 50 grams Whole wheat flour (coursely ground - 30g; finely ground - 20g
1. Make ready 6 grams Skim milk powder
1. Take 20 grams Honey
1. Make ready 30 grams Nonsalted butter (or shortening)
1. Get 3 grams Dry yeast
1. Make ready 3 grams Salt
1. Get 180 ml Soy milk
<!--inarticleads2-->
##### Steps to make Springy and Fluffy Whole Wheat Bread with Lots of Soy Milk:
1. Put all of the ingredients into the bread maker and let it knead the dough.
1. When the first rising has finished, separate into 8 sections. Let rest for 5-10 minutes.
1. Shape into balls and place on a baking tray. Use the oven's bread proofing function at 40°C for 25-35 minutes to let it rise a second time.
1. Dust with whole wheat flour, cut slits in the tops. Bake for 15 minutes at 170°C.
1. And it's done baking!
1. Here's a brown sugar version. I also recommend this.
So that's going to wrap it up with this special food springy and fluffy whole wheat bread with lots of soy milk recipe. Thanks so much for reading. I am confident you will make this at home. There's gonna be more interesting food at home recipes coming up. Don't forget to bookmark this page in your browser, and share it to your loved ones, friends and colleague. Thanks again for reading. Go on get cooking!
|
Python | UTF-8 | 485 | 3.4375 | 3 | [] | no_license | # Pivoting on one variable
import numpy as np
# Pivot for mean weekly_sales for each store type
mean_sales_by_type = sales.pivot_table(values='weekly_sales', index='type')
# Print mean_sales_by_type
print(mean_sales_by_type)
# Fill in missing values and sum values with pivot tables
# Print mean weekly_sales by department and type; fill missing values with 0
print(sales.pivot_table(values='department',
index='type', columns='weekly_sales', fill_value=0))
|
C# | UTF-8 | 2,842 | 3.234375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem2SoftUniKaraoke
{
class SoftUniKaraoke
{
static void Main(string[] args)
{
var participantsList = new List<string>();
var songsList = new List<string>();
var result = new Dictionary<string, Dictionary<string, int>>();
var participants = Console.ReadLine()
.Split(new[] { ", " }, StringSplitOptions
.RemoveEmptyEntries);
for (int i = 0; i < participants.Length; i++)
{
participantsList.Add(participants[i]);
}
var songs = Console.ReadLine()
.Split(new[] { ", " }, StringSplitOptions
.RemoveEmptyEntries);
for (int i = 0; i < songs.Length; i++)
{
songsList.Add(songs[i]);
}
var input = Console.ReadLine()
.Split(new[] { ", ", }, StringSplitOptions
.RemoveEmptyEntries);
while (input[0] != "dawn")
{
var currentParticipant = input[0];
var currentSong = input[1];
var currentAward = input[2];
if (participantsList.Contains(currentParticipant)
&& songsList.Contains(currentSong))
{
if (!result.ContainsKey(currentParticipant))
{
result.Add(currentParticipant, new Dictionary<string, int>());
}
if (!result[currentParticipant].ContainsKey(currentAward))
{
result[currentParticipant].Add(currentAward, 0);
}
result[currentParticipant][currentAward] = 1;
}
input = Console.ReadLine()
.Split(new[] { ", ", }, StringSplitOptions
.RemoveEmptyEntries);
}
if (result.Count == 0)
{
Console.WriteLine("No awards");
return;
}
foreach (var pair in result
.OrderByDescending(x => x.Value.Sum(y => y.Value))
.ThenBy(x => x.Key))
{
var participant = pair.Key;
var awardAndCount = pair.Value;
Console.WriteLine($"{participant}: {result[participant].Values.Sum()} awards");
foreach (var pair2 in awardAndCount.OrderBy(x => x.Key))
{
var award = pair2.Key;
var count = pair2.Value;
Console.WriteLine($"--{award}");
}
}
}
}
}
|
Java | UTF-8 | 4,745 | 2.296875 | 2 | [] | no_license | package com.serverside;
import gvjava.org.json.JSONArray;
import gvjava.org.json.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ViewQuestionsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection con=null;
Statement st=null;
PrintWriter pw=null;
ResultSet rs=null;
public ViewQuestionsServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action=request.getParameter("action");
if(action.equalsIgnoreCase("answer")){
getAnswer(request,response);
}
else if(action.equalsIgnoreCase("vanss")){
getVanss(request,response);
}
}
private void getVanss(HttpServletRequest request,
HttpServletResponse response) {
con=DataBaseConnection.getConnection();
try {
pw=response.getWriter();
st=con.createStatement();
String qstndescrcmnt=request.getParameter("qstndescrval");
System.out.println(qstndescrcmnt);
String queryansid="select Q_ID from QUESTION where Q_DESCR='"+qstndescrcmnt+"'";
System.out.println(queryansid);
rs=st.executeQuery(queryansid);
int qstnidvalue=0;
if(rs.next()){
qstnidvalue=rs.getInt("Q_ID");
}
String querycmnt="select ANS_DESCR from ANSWER where Q_ID="+qstnidvalue+"";
System.out.println(querycmnt);
rs=st.executeQuery(querycmnt);
System.out.println("*************");
JSONArray arr=new JSONArray();
while(rs.next()){
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!#######");
JSONObject obj=new JSONObject();
obj.put("answer",rs.getString("ANS_DESCR"));
System.out.println("%%%%%%%%%"+rs.getString("ANS_DESCR"));
arr.put(obj);
System.out.println("$$$$$$$$$$$$$$$$$$$");
}
pw.print(arr);
} catch (Exception e) {
e.printStackTrace();
}
finally
{
if(rs!=null)
{
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st!=null)
{
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null)
{
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private void getAnswer(HttpServletRequest request,
HttpServletResponse response) {
con=DataBaseConnection.getConnection();
String ansusrname=request.getParameter("ansuname").replace("+", " ");
String ansval=request.getParameter("answervalue");
System.out.println("##################"+ansval);
String ansanoname=request.getParameter("ansanname").replace("+"," ");
String qstndesc=request.getParameter("questiondesc").replace("+", " ");
try {
pw=response.getWriter();
st=con.createStatement();
String query1="select ID_NO from USER_DETAILS where NAME='"+ansusrname+"'";
System.out.println(query1);
rs=st.executeQuery(query1);
int uidvalue=0;
if(rs.next()){
uidvalue=rs.getInt("ID_NO");
}
String query2="select Q_ID from QUESTION where Q_DESCR='"+qstndesc+"'";
System.out.println(query2);
rs=st.executeQuery(query2);
int qstnidvalue=0;
if(rs.next()){
qstnidvalue=rs.getInt("Q_ID");
}
int count=0;
String query3="select count(*) from ANSWER";
System.out.println(query3);
rs=st.executeQuery(query3);
if(rs.next())
{
count=rs.getInt(1);
count=count++;
}
String query4="insert into ANSWER values("+count+",'"+ansval+"',sysdate,'"+ansanoname+"',"+qstnidvalue+","+uidvalue+")";
System.out.println(query4);
int n=st.executeUpdate(query4);
if(n>0)
{System.out.println("Answer submitted");
pw.print("AswerSubmitted");
}
else
{
System.out.println("Not Submitted");
}
} catch (Exception e) {
e.printStackTrace();
}
finally
{
if(rs!=null)
{
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st!=null)
{
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null)
{
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
|
C++ | UTF-8 | 1,154 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | /***************************************************************
* @date: 2007-10-19
* @author: BrucePeng
* @brief: Define the file object(being downloaded)
*/
#include "KDownloadFile.h"
bool CDownloadFile::Create(const char *pszPathFileName)
{
if(NULL == pszPathFileName)
return false;
//Close file If It has been opened
this->Close();
//Create file
m_hFile = CreateFileA(pszPathFileName,
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL
);
return (INVALID_HANDLE_VALUE != m_hFile);
}
bool CDownloadFile::Close(void)
{
if(INVALID_HANDLE_VALUE != m_hFile)
CloseHandle(m_hFile);
m_hFile = INVALID_HANDLE_VALUE;
return true;
}
bool CDownloadFile::Empty(void)
{
if(!SetPointerFromBegin(0))
return false;
return SetEndOfFile(m_hFile) ? true:false;
}
bool CDownloadFile::SetPointerFromBegin(long lMove)
{
DWORD dwRet = 0;
dwRet = SetFilePointer(m_hFile, lMove, NULL, FILE_BEGIN);
return (INVALID_SET_FILE_POINTER != dwRet);
}
|
Java | UTF-8 | 989 | 2.359375 | 2 | [] | no_license | package com.test.kafka.kafka;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.Random;
@Service
@Slf4j
public class TestKafkaProducer {
private final String TOPIC_01 = "TEST.001";
private KafkaTemplate<String, String> messageProducer;
@Autowired
public TestKafkaProducer(KafkaTemplate<String, String> messageProducer) {
this.messageProducer = messageProducer;
}
@Scheduled(cron = "*/10 * * * * *")
public void sendMessageToKafka() {
int i =1;
while( i<5){
String message = String.valueOf(new Random().nextInt(50));
messageProducer.send(TOPIC_01, message);
log.info("KafkaProducer sent : {}", message);
i++;
}
}
}
|
Markdown | UTF-8 | 1,954 | 4.1875 | 4 | [] | no_license | [74. Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/)
* Amazon, Microsoft, Facebook, Uber, Apple
* Array, Binary Search
* Similar Questions:
* Search a 2D Matrix II
## Method 1. My Solution
```java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix==null || matrix.length==0) {
return false;
}
int row = matrix.length - 1;
int col = 0;
while(row>=0 && col<matrix[0].length) {
if(matrix[row][col] == target) {
return true;
} else if(matrix[row][col] > target) {
row--;
} else {
col++;
}
}
return false;
}
}
```
* From left bottom corner to right top corner.
## Method 2. Binary Search
前提:**The first integer of each row is larger than the last integer of the previous row.**
Convert 2D into 1D. One could notice that the input matrix `m x n` could be considered as a sorted array of length `m x n`.

`idx` 和 `row, col` 之间的转换公式: `row = idx / n, col = idx % n`
```java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix==null || matrix.length==0) {
return false;
}
int m = matrix.length;
int n = matrix[0].length;
// Binary Search
int lo = 0;
int hi = m * n - 1;
int pivotIndex;
int pivotElement;
while(lo <= hi) {
pivotIndex = lo + (hi - lo) / 2;
pivotElement = matrix[pivotIndex / n][pivotIndex % n];
if(target == pivotElement) {
return true;
} else if(target < pivotElement) {
hi = pivotIndex - 1;
} else {
lo = pivotIndex + 1;
}
}
return false;
}
}
```
|
C# | UTF-8 | 700 | 3.3125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorld
{
internal class Program
{
public void PrintProgram(string[] args)
{
Console.WriteLine("hello:) Main() ");
const string strMsg = "string messag";
MsgWrite(strMsg);
if (args.Length != 0)
{
Console.WriteLine("hello? {0} !! ", args[0]);
}
else
{
Console.WriteLine("please write your name... ");
}
}
private static void MsgWrite(string msg) {
Console.WriteLine("param : " + msg);
}
}
}
|
TypeScript | UTF-8 | 1,541 | 2.765625 | 3 | [
"MIT"
] | permissive | import _, { Dictionary } from "lodash";
import { DBTables } from "../generated/ghost-db-tables";
import { Context } from "../data-sources/Context";
import { QueryBuilder } from "knex";
export function byColumnLoader<
Tbl extends keyof DBTables,
Key extends Extract<keyof DBTables[Tbl], string>,
KeyType extends Extract<DBTables[Tbl][Key], string | number>
>(
ctx: Context,
table: Tbl,
key: Key,
keys: KeyType[]
): PromiseLike<DBTables[Tbl][]> {
return ctx
.knex(table)
.select(`${table}.*`)
.whereIn(`${table}.${key}`, keys)
.then((rows: DBTables[Tbl][]) => {
const keyed: Dictionary<DBTables[Tbl]> = _.keyBy(rows, key);
return keys.map((k) => {
return keyed[k] || new Error(`Missing row for ${table}:${key} ${k}`);
});
});
}
/**
* A type-safe loader for loading many of a particular item,
* grouped by an individual key.
* @param ctx
* @param table
* @param key
* @param keys
*/
export function manyByColumnLoader<
Tbl extends keyof DBTables,
Key extends Extract<keyof DBTables[Tbl], string>,
KeyType extends Extract<DBTables[Tbl][Key], string | number>
>(
ctx: Context,
tableName: Tbl,
key: Key,
keys: KeyType[],
scope: (qb: QueryBuilder) => QueryBuilder = (qb) => qb
) {
const builder = ctx
.knex(tableName)
.select(`${tableName}.*`)
.whereIn(`${tableName}.${key}`, _.uniq(keys));
return scope(builder).then((rows: DBTables[Tbl][]) => {
const grouped = _.groupBy(rows, key);
return keys.map((id) => grouped[id] || []);
});
}
|
Python | UTF-8 | 417 | 2.546875 | 3 | [] | no_license | # Create your tasks here
# from __future__ import absolute_import, unicode_literals
from celery import shared_task
@shared_task(name="function1")
def add(x, y):
print("inside add 1")
return x+y
@shared_task(name="function2")
def mul(x, y):
return x+y
def sum(x, y):
# to use for diff queue
# add1.apply_async([x, y], queue='custom')
add.delay(x, y)
mul.delay(x, y)
return "done"
|
C++ | UTF-8 | 1,596 | 2.875 | 3 | [
"MIT"
] | permissive | #include "stactiverecord/stactive_record.h"
using namespace stactiverecord;
using namespace std;
/**
Here are some example database connections strings:
// open an sqlite db in memory
Sar_Dbi * Sar_Dbi::dbi = Sar_Dbi::makeStorage("sqlite://:memory:");
// open PostgreSQL db with username and password on localhost, and make each table have a prefix
Sar_Dbi * Sar_Dbi::dbi = Sar_Dbi::makeStorage("postgres://user:password@localhost/myonlydatabase", "stactive_record_");
// open an sqlite db in the file /tmp/db
Sar_Dbi * Sar_Dbi::dbi = Sar_Dbi::makeStorage("sqlite:///tmp/db");
**/
// here are some examples of executing SQL directly
Sar_Dbi * Sar_Dbi::dbi;
int main(int argc, char* argv[]) {
if(argc != 2) {
std::cout << "Usage: ./simple <scheme://[user[:password]@host[:port]/]database>\n";
return 1;
}
Sar_Dbi::dbi = Sar_Dbi::makeStorage(string(argv[1]));
Sar_Dbi::dbi->execute("CREATE TABLE example (id INT, name VARCHAR(255))");
Sar_Dbi::dbi->execute("INSERT INTO example (id, name) VALUES(0, \"Richard Stallman\")");
// KVT's are Key/Value/Type objects - use a vector of them to tell the db which columns you want
// to select
SarVector<KVT> cols;
cols << KVT("name", STRING);
// select name from example where id = 0
SarVector<Row> rows = Sar_Dbi::dbi->select("example", cols, Q("id", 0));
// get the first string column in the first row returned, and put it into "name"
string name;
rows[0].get_string(0, name);
cout << "Next time you see " << name << " say hi to him for me\n";
delete Sar_Dbi::dbi;
return 0;
};
|
C# | UTF-8 | 7,145 | 2.65625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Resources;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TxtToResources
{
public partial class TxtToResources : Form
{
public static ResourceManager rm = null;
public TxtToResources()
{
InitializeComponent();
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false; //该值确定是否可以选择多个文件
dialog.Title = "请选择文件夹";
dialog.Filter = "所有文件(*.txt)|*.txt";
if (dialog.ShowDialog() == DialogResult.OK)
{
string fileTxt = dialog.FileName;
txtOpenFileTxt.Text = fileTxt;
}
}
private void btnCreateResources_Click(object sender, EventArgs e)
{
string fileTxt = txtOpenFileTxt.Text;
string rootDirectory = Path.GetDirectoryName(fileTxt) + @"\"; //获取文件所在目录
string fileName = Path.GetFileNameWithoutExtension(fileTxt); //获取文件名不包含后缀
IResourceWriter writer = new ResourceWriter(rootDirectory + fileName + ".resources");
if (string.IsNullOrWhiteSpace(fileTxt))
{
MessageBox.Show("未选择文件请重试");
return;
}
string txtKeyValue = File.ReadAllText(fileTxt);
string[] strKeyValueArrays = txtKeyValue.Split(',');
foreach (var strKeyValueArray in strKeyValueArrays)
{
string[] strSingleArrays = strKeyValueArray.Split('=');
writer.AddResource( strSingleArrays[0].Trim(), strSingleArrays[1].Trim());
}
writer.Close();
}
private void btnOpenFileResources_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false; //该值确定是否可以选择多个文件
dialog.Title = "请选择文件夹";
dialog.Filter = "所有文件(*.resources)|*.resources";
if (dialog.ShowDialog() == DialogResult.OK)
{
string fileTxt = dialog.FileName;
txtBoxeResources.Text = fileTxt;
}
}
private void btnWriteInResourse_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtBoxeResources.Text))
{
MessageBox.Show("资源文件路径不可为空,请重新输入!");
return;
}
if (string.IsNullOrWhiteSpace(textBoxKey.Text))
{
MessageBox.Show("输入的键不可为空,请重新输入!");
return;
}
if (string.IsNullOrWhiteSpace(textBoxValue.Text))
{
MessageBox.Show("输入值不可为空,请重新输入!");
}
IResourceWriter writer = new ResourceWriter(txtBoxeResources.Text);
writer.AddResource(textBoxKey.Text, textBoxValue.Text);
writer.Close();
}
/// <summary>
/// 选择资源文件,按钮单机事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false; //该值确定是否可以选择多个文件
dialog.Title = "请选择文件夹";
dialog.Filter = "所有文件(*.resources)|*.resources";
if (dialog.ShowDialog() == DialogResult.OK)
{
string fileTxt = dialog.FileName;
textBox1.Text = fileTxt;
}
}
/// <summary>
/// 根据键获取值,按钮单机事件。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
MessageBox.Show("读取操作,资源文本路径不可为空!");
return;
}
if (string.IsNullOrWhiteSpace(textBox2.Text))
{
MessageBox.Show("查询的键值不可为空,请重试!");
return;
}
string fileTxt = textBox1.Text;
string rootDirectory = Path.GetDirectoryName(fileTxt); //获取文件所在目录
string fileName = Path.GetFileNameWithoutExtension(fileTxt); //获取文件名不包含后缀
if (rm != null)
{
rm.ReleaseAllResources();
rm = null;
}
FindFindLanguageResource(rootDirectory, fileName);
string Value = GetStringValue(textBox2.Text);
if (Value == null)
{
MessageBox.Show("该键值对不存在,请核对您输入的键值");
return;
}
textBox3.Text = Value;
}
/// <summary>
/// 获取资源文件
/// </summary>
/// <param name="Charset"></param>
public static void FindFindLanguageResource(string directoryResources,string Charset = "en_US")
{
if (string.IsNullOrWhiteSpace(directoryResources))
{
MessageBox.Show("资源文件路径不存在请重试");
return;
}
DirectoryInfo di = new DirectoryInfo(directoryResources);
string filePath = directoryResources + $"\\{Charset}.resources";
if (di == null)
{
return;
}
if (!Directory.Exists(directoryResources))
{
Console.WriteLine("该路径下文件夹不存在");
return;
}
if (rm != null)
{
rm.ReleaseAllResources();
rm = null;
}
if (!File.Exists(filePath))
{
Console.WriteLine($"{Charset}语言包文件不存在");
return;
}
rm = ResourceManager.CreateFileBasedResourceManager(Charset, directoryResources, null);
}
/// <summary>
/// 获取资源文件键对应的值
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GetStringValue(string str)
{
try
{
return rm.GetString(str);
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}
|
Java | UTF-8 | 3,504 | 2.1875 | 2 | [
"BSD-2-Clause",
"BSD-2-Clause-Views"
] | permissive | /**
* Copyright (c) 2011, SOCIETIES Consortium
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.societies.personalisation.common.api.model;
import java.util.ArrayList;
import java.util.List;
import java.io.Serializable;
public class Action implements IAction, Serializable{
private String value;
private String parameterName;
private ArrayList<String> parameterNames;
private ServiceResourceIdentifier serviceID;
private String serviceType;
private ArrayList<String> types;
private int confidenceLevel;
public Action(){
this.parameterName = "not_initialised";
this.value = "not_initialised";
}
public Action(String par, String val){
this.parameterName = par;
this.value = val;
}
public String getvalue(){
return value;
}
/**
*
* @param newVal
*/
public void setvalue(String newVal){
value = newVal;
}
public String getparameterName(){
return parameterName;
}
/**
*
* @param newVal
*/
public void setparameterName(String newVal){
parameterName = newVal;
}
/**
*
* @param parameter
*/
public void addParameter(String parameter){
this.parameterNames.add(parameter);
}
public ArrayList<String> getparameterNames(){
return parameterNames;
}
public String toString(){
return this.parameterName+"="+this.value;
}
public boolean equals(IAction po){
String par = po.getparameterName();
String val = po.getvalue();
if (this.parameterName.equalsIgnoreCase(par) && this.value.equalsIgnoreCase(val)){
return true;
}
return false;
}
@Override
public ServiceResourceIdentifier getServiceID() {
return this.serviceID;
}
@Override
public String getServiceType() {
return this.serviceType;
}
@Override
public List<String> getServiceTypes() {
return this.types;
}
@Override
public void setServiceID(ServiceResourceIdentifier id) {
this.serviceID = id;
}
@Override
public void setServiceType(String type) {
this.serviceType = type;
}
@Override
public void setServiceTypes(List<String> sTypes) {
this.types = (ArrayList<String>) sTypes;
}
}
|
Java | UTF-8 | 1,095 | 3 | 3 | [] | no_license | package com.mygdx.game;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import java.util.Vector;
public class Background {
class DoublePicture {
private Texture tx;
private Vector2 pos;
public DoublePicture(Vector2 pos) {
tx = new Texture("fon.jpg");
this.pos = pos;
}
}
private int speed;
private DoublePicture[] backs;
public Background(){
speed = 2;
backs = new DoublePicture[2];
backs[0] = new DoublePicture(new Vector2(0,0));
backs[1] = new DoublePicture(new Vector2(1366,0));
}
public void render(SpriteBatch batch)
{
for(int i=0;i<backs.length;i++)
{
batch.draw(backs[i].tx,backs[i].pos.x,backs[i].pos.y);
}
}
public void update(){
for(int i=0;i<backs.length;i++) {
backs[i].pos.x -= speed;
}
if(backs[0].pos.x<-1366){
backs[0].pos.x=0;
backs[1].pos.x=1366;
}
}
}
|
JavaScript | UTF-8 | 1,181 | 2.765625 | 3 | [
"MIT"
] | permissive | import * as THREE from '../../libs/three.module.js';
/**
* トロッコクラスです。
*/
export default class Truck extends THREE.Object3D {
/**
* コンストラクターです。
* @constructor
*/
constructor() {
super();
// 本体
const body = new THREE.Mesh(
new THREE.BoxGeometry(3, 3, 6),
new THREE.MeshPhongMaterial({
color: 0xcccccc,
})
);
body.position.y = 3;
this.add(body);
// 車輪1
const wheel1 = new THREE.Mesh(
new THREE.CylinderBufferGeometry(1, 1, 4, 10),
new THREE.MeshPhongMaterial({
color: 0xffff00,
})
);
wheel1.rotation.x = wheel1.rotation.z = 90 * Math.PI / 180;
wheel1.position.y = 1;
wheel1.position.z = -2;
this.add(wheel1);
// 車輪2
const wheel2 = new THREE.Mesh(
new THREE.CylinderBufferGeometry(1, 1, 4, 10),
new THREE.MeshPhongMaterial({
color: 0xffff00,
})
);
wheel2.rotation.x = wheel2.rotation.z = 90 * Math.PI / 180;
wheel2.position.y = 1;
wheel2.position.z = 2;
this.add(wheel2);
}
/**
* フレーム毎の更新をします。
*/
update() {}
}
|
C++ | GB18030 | 31,876 | 2.546875 | 3 | [] | no_license | #ifndef __CONF_HALL_H__
#define __CONF_HALL_H__
#include "ConfManager.h"
#include "ConfGameSetting.h"
//////////////////////////////////////////////////////////////////////////
class AchieveItem
{
public:
int ID; //ɾID
int Title; //ɾͱ
int Desc; //
int UnLockLv; //ȼ
int Show; //Ƿʾ
int FinishCondition; //
int CompleteTimes; //ɴ
int Tips; //δʾ
int AwardExp; //
int AwardCoin; //
int AwardDiamond; //ʯ
int AwardEnergy; //
int PosType; //λ
int AchieveStar; //ɺ
int CloseDisplay; //رպǷʾ
std::string Icon; //ɾͼ
VecInt FinishParameters; //1,2,3
VecInt EndStartID; //
std::vector<ID_Num> AwardItems; //
};
struct DiffcultItem
{
int DiffID;
int MaxLevel;
int BasicLevel;
int ExLevel;
int UnlockLevel;
VecInt Pic;
};
class ActivityInstanceItem
{
public:
int ID; //ID
int Title; //
int Desc; //
int Place; //ȼ
int Show; //ɺͼ
int Type; //
int CompleteTimes; //ɴ
int BuyTimes; //
int RecoverType; //ָ
int RecoverParam; //ָ
VecInt PlaceTime; //ͼʾʱ
VecInt StartTime; //ʼʱ
VecInt EndTime; //ʱ
VecInt RecoverTime; //ָʱ
std::vector<DiffcultItem> Diffcult; //Ѷ
std::string Pic; //ͼ
};
class CardGambleItem
{
public:
int ID; // ƬID
int Rare; // ϡж12345
int Star; // Ǽ
int Rate; //
int Ratio; // ϵ
//Prob Probability; //ʺϵ
};
//Ч
struct Ability
{
int AbilityID; //ʾЧID
int AbilityParam; //ʾЧ
int AbilityDesc; //ʾЧ
};
//ֽ
struct DecompositMaterial
{
int Decomposit; //װֽ,ӦĵID
int DecompositionParam; //
};
//ϳɲ
struct SynthMaterial
{
int Synthesis; //ID
int SynthesisParam; //
};
struct EquipmentEffect
{
EquipmentEffect()
: SoliderId(0)
, SoliderStart(0)
{
}
int SoliderId; // ˲жϣID߲ͬſɼ츳
int SoliderStart; // ⼤Ǽ츳
std::map<int, int> Buff; // BuffId - Buff
};
#define MAX_BASE_PROP 8 //ѡ
#define MAX_EXTRA_PROP 8 //ѡѡ
struct EffectData
{
int nEffectID; //ЧID
int nMinValue; //ЧСֵ
int nMaxValue; //Чֵ
int nWeight; //ЧȨֵ
EffectData()
{
//memset(this, 0, sizeof(*this));
}
};
//װ
class EquipmentItem
{
public:
int ID; // װID
int Suit; // װID
int Level; // װȼ
int Parts; // װ䲿λ
int Gold; // װֽ
int Rank; // װ
EquipmentEffect ExtEffect; // Ч
std::vector<DecompositMaterial> Decomposit; // װֽ
VecInt Vocation; // װְҵ
};
//װ
class EquipPropCreate
{
public:
int nEquipID; //װID
std::vector<EffectData> VectBaseProp; //װ
std::vector<EffectData> VectExtraProp; //װѡ
EquipPropCreate()
{
nEquipID = 0;
VectBaseProp.clear();
VectExtraProp.clear();
}
};
//װ
class SuitItem
{
public:
int ID; // װID
int Name; // װ(ӦID)
int Desc; // ײ(ӦID)
std::map<int, int> Eq; // װװ(1,2·,3,4Ь,5Ʒ,6Ʒ)
std::map<int, Ability> SuitAbility; // װЧ, key, valueЧ
std::map<int, EquipmentEffect> SuitExtEffect; // װЧ
};
//
class PropItem
{
public:
int ID; // ID
int Name; // ID
int Desc; // ID
int Quality; // Ʒ
int Type; //
int SellPrice; // ۼ۸
int UseLevel; // ʹõȼ
int BagLabel; // ǩ
float Ratio; // ϵ
std::string Icon; // ͼ
VecInt TypeParam; // Ͳ
VecVecInt QuickToStage; // ǰؿ
};
//䵥
struct DropIdData
{
int DropID;
int DropRate;
VecInt DropNum;
};
//id
struct DropCurrencyData
{
int CurrencyId; //id
int UpperLimit; //
int LowerLimit; //
};
//
class DropPropItem
{
public:
int DropRuleID; //ID
int IsCrit; //ɷ
int IsRepeat; //ɷظ
VecInt MeanwhileDropNum; //ε
VecInt ExtraDropRuleID; //
std::vector<DropCurrencyData> DropCurrencys; //
std::vector<DropIdData> DropIDs; //ID
DropPropItem& operator = (DropPropItem &Item)
{
DropRuleID = Item.DropRuleID;
IsCrit = Item.IsCrit;
IsRepeat = Item.IsRepeat;
MeanwhileDropNum.assign(Item.MeanwhileDropNum.begin(), Item.MeanwhileDropNum.end());
ExtraDropRuleID.assign(Item.ExtraDropRuleID.begin(), Item.ExtraDropRuleID.end());
DropCurrencys.assign(Item.DropCurrencys.begin(), Item.DropCurrencys.end());
DropIDs.assign(Item.DropIDs.begin(), Item.DropIDs.end());
return (*this);
}
};
//ʼ
class MailItem
{
public:
int ID; // ʼid
int Topic; // ʼ
int Sender; //
int Content; // ʼ
int LiveTime; // ()
};
//Ӣ
class SoldierUpRateItem
{
public:
int SoldierID; // ӢID
int DefaultStar; // ʼǼ
int TopStar; //
int Source; // ȡ;
VecVecInt QuickToStage; // ǰؿID
};
//ٻʦ
class SaleSummonerConfItem
{
public:
int ID; // ٻʦID
int Type; //
int Num; //
int SummonerMusic; // ٻʦЧID
int NewLabel; // Ƿʾnewǩ
std::string Head_Name; // ɫͷԴ
std::string Bg_Name; // ɫԴ
std::string Bg_Texture; // ɫ
int HeadID; // ͷID
};
class TaskItem
{
public:
int ID; //ID
int Title; //
int Type; //
int Desc; //
int UnlockLv; //ȼ
int Show; //Ƿʾ
int FinishCondition; //
int CompleteTimes; //ɴ
int Tips; //δʾ
int AwardExp; //
int AwardCoin; //
int AwardDiamond; //ʯ
int AwardEnergy; //
int AwardFlashcard; //鿨ȯ
int TaskReset; //
std::string Icon; //ͼ
VecInt QuickTo; //ǰ
VecInt FinishParameters; //
VecInt EndStartID; //
VecInt TaskResetParameters; //ڲ
std::vector<ID_Num> AwardItems; //
};
enum EnhanceConditionTypes
{
EnhanceConditionId = 1, // ID
EnhanceConditionRoleType, // ɫ
EnhanceConditionStar, // Ǽ
EnhanceConditionCrystalCost, // ˮ
EnhanceConditionRace, //
EnhanceConditionSex, // Ա
EnhanceConditionVocation, // ְҵ
EnhanceConditionAttackType, // ʽ
};
enum EnhanceConditionJudgeTypes
{
Greater = 1, // >
Less, // С <
Equal, // ==
GreaterEqual, // ڵ >=
LessEqual, // Сڵ <=
};
struct EnhanceCondition
{
int Type; //ӳö
VecInt Param; //
};
struct EnhanceValue
{
int EffectId; // ӳID
int Param; // ӳֵ
int EffectLanID; // ID
};
class OutterBonusItem
{
public:
int ID; //սԼӳID
int Name; //
int Desc; //
std::vector<EnhanceCondition> EnhanceConditions; //ӳöб
std::vector<EnhanceValue> Enhances; //ӳЧ
std::string Pic;
std::string PicS;
};
class GoldTestConfItem
{
public:
int WeekNum; //ܼ
int Stage; //ؿ
int StageDesc; //ؿ
int Frequency; //
int StageLevel; //ȼ
VecFloat Param; //
};
class GoldTestChestConfItem
{
public:
int Level; //ȼ
int Gold; //
int Damage; //Ϻ
};
class HeroTestItem
{
public:
int ID; //ID
VecInt Time; //ʱ
int Occupation; //ְҵ
int Times; //
int Desc; //
int UpDesc; //
int Title; //
std::vector<DiffcultItem> Diff; //Ѷ
std::string Pic; //ͼƬ
};
//struct TowerDiffcultInfo
//{
// int MaxLevel; //ȼ
// int BasicLevel; //ȼ
// int EXLevel; //ȼϵ
// int Reward; //ʾ
// int ExtraStar; //⽱
// int TCoin; //
//};
class TowerFloorItem
{
public:
int ID; //¥
int MaxLevel; //ȼ
int BasicLevel; //ȼ
int EXLevel; //ȼϵ
VecInt StageID; //¥㱸ѡؿID
int Place; //ս¼λ
int Drop; //ID
};
struct TowerBuffInfo
{
int BuffID; //սԼӳBuffID
int Cost; //buff
};
class TowerBuffItem
{
public:
int ID; //ID
std::vector<TowerBuffInfo> Buff; //Buff
int Max; //¥
int Min; //¥
};
struct TowerRankInfo
{
int ID;
int Num;
};
class TowerRankItem
{
public:
int ID; //ID
VecInt Rank; //
std::vector<TowerRankInfo> Item; //Ʒ
};
class ArenaRewardItem
{
public:
int Reward_ID;
int Reward_Type;
int WinNum_Text;
int Award_Coin;
int Award_Diamond;
int Award_PvpCoin;
int Award_Flashcard;
int Award_Items;
std::string WinNum_Pic;
VecInt Type_Parameter;
VecInt AwardPic;
};
struct ArenaTaskItem
{
int Task_ID; //ID
int Task_Type; // 0=ս 1=ۼʤ 2=ʤ
int Task_Text; //˵
int Complete_Times; //ɴ
int Award_Exp; //ʾ 0ʾûУʾ
int Award_Coin; //ʾ 0ʾûУʾ
int Award_Diamond; //ʾʯ 0ʾûУʾ
int Award_Energy; //ʾ 0ʾûУʾ
int Award_PvpCoin; //ʾ0ʾûУʾ
int Award_Flashcard; //ʾ鿨ȯ
int DropID; //ID
int IsOpen; //ǷĬϿ
int IsReset; //Ƿ
VecInt Award_Items; //ʾ []ʾûУʾ 漷2
VecInt End_StartID; //ID []ʾûҪ
std::string Task_Pic; //ͼ
};
struct AnimationPlayOrderItem
{
int ResID;
std::vector<std::vector<std::string> > VecAnimations;
};
struct HallStandingItem
{
int SpotOrder; // λ
Vec2 Position; // λ
int ZOrder; // 㼶
};
class ShopConfigData
{
public:
ShopConfigData()
{
nShopName = 0;
nLevLimit = 0;
nTimeInterval = 0;
VectType.clear();
VectNum.clear();
}
int nShopName; //̵
std::string strShopIcon; //̵갴ťͼƬ
int nLevLimit; //ȼ
int nTimeInterval; //ˢʱ
VecInt VectType; //̵
std::vector<int> VectNum; //̵ƷPVPλ
};
class ShopGoodsConfigData
{
public:
ShopGoodsConfigData()
{
nShopID = 0;
nShopGoodsID = 0;
nGoodsID = 0;
nGoodsNum = 0;
nCoinType = 0;
nCoinNum = 0;
nWeight = 0;
nSale = 0;
nKind = 0;
nFreshMinLev = 0;
nFreshMaxLev = 0;
}
int nShopID; //̵ID
int nShopGoodsID; //ƷID
int nGoodsID; //ID
int nGoodsNum; //߸
int nCoinType; //
int nCoinNum; //ֵ
int nWeight; //ƷȨֵ
int nSale; //Ʒۿ
int nKind; //Ʒϡж
int nFreshMinLev; //ˢСȼ
int nFreshMaxLev; //ˢȼ
};
class DiamondShopConfigData
{
public:
int nGoodsID; // ID
std::string strPicName; // ƷͼƬID
int nNameLanID; // ƷID
int nDescLanID; // ƷID
int nPrice; // ۸
int nDiamond; // õʯ
};
//PVPƥл
struct SPvpRobotItem
{
int nRobotID; //id
int nRobotMMR; //mmrֵ
int nMinMMR; //mmr
int nMaxMMR; //mmr
int nMinRobotLevel; //˵ȼ
int nMaxRobotLevel; //˵ȼ
VecInt stageIdVec; //б
};
//ÿǩÿ
struct SCheckInDayConfig
{
int nGoodsID;
int nGoodsNum;
int nShowNum; //ʾĿ
};
//ۼǩ
struct SConCheckInConfig
{
int DayNeeds; //
int nGoodsID[3]; //
int nGoodsNum[3]; //Ŀ
int nShowNum[3]; //ʾĿ
};
//׳
struct SFirstPayData
{
std::vector<int> vectGoodsID;
std::vector<int> vectGoodsNum;
int nGrowGiftPrice;
int nGiftDiamonds;
int nGetTimes;
SFirstPayData()
{
vectGoodsID.clear();
vectGoodsNum.clear();
nGrowGiftPrice = 0;
nGiftDiamonds = 0;
nGetTimes = 0;
}
};
//QQ
struct SBDActiveData
{
int nActiveType; //
int nUserLimit; //ȡû
int nConditionParam; //
std::vector<int> vectGoodsID; //ID
std::vector<int> vectGoodsNum; //Ʒ
SBDActiveData()
{
nActiveType = 0;
nUserLimit = 0;
nConditionParam = 0;
vectGoodsID.clear();
vectGoodsNum.clear();
}
};
//QQKey
struct SBDActiveKey
{
int nActiveID;
int nTaskID;
bool operator < (const SBDActiveKey &Key) const
{
if (nActiveID < Key.nActiveID)
{
return true;
}
else if (nActiveID == Key.nActiveID)
{
if (nTaskID < Key.nTaskID)
{
return true;
}
}
return false;
}
};
struct STalentData
{
int TalentID; // 츳id
int TalentName; // 츳
int TalentDes; // 츳
std::string TalentPic; // 츳Դ
std::map<int, int> OutterBonus; // Լӳ
std::vector<ID_Num> BuffId; // buffӳ
};
struct STalentArrangeData
{
int ArrangeID; // 츳ҳid(ְҵ츳츳̶)
VecVecInt FloorTalent; // 츳ϵ츳
};
struct SPVPShareData
{
int ReplayShowCount; // طƵʾط
int ReplayShareCD; // طƵCD룩
int ReplayShareCount; // طƵÿշ
int BattleShareCount; // ÿս
int RefreshCD; // ۿˢ¼룩
int ReplayShowRank; // طƵXʾ
int ShareDescLength; //
int Desc; // Ĭ
};
struct SPVPUploadData
{
int AutoUploadHP; // ԶϴʣѪ
int ApplyRank; // ϰ
int ApplyCount; //
int AutoUploadRank; // ԶϴηΧ
};
//////////////////////////////////////////////////////////////////////////
class CConfGoldTest : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfGoldTestChest : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfHeroTest : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfTowerFloor : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
int getMaxFloor() { return m_nMaxFloor; }
private:
int m_nMaxFloor;
};
class CConfTowerBuff : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
#ifdef RunningInServer
std::vector<int> &getFloorsBuff(int id);
private:
std::map<int, std::vector<int> > m_mapFloorsBuffId;
#endif
};
class CConfTowerRank : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfAchieve : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
int getPreAchieveID(int achieveID);
private:
std::map<int, int> m_mapPreAchieve; // <ǰɾID, ǰóɾID>
};
class CConfActivityInstance : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
typedef std::map<int, std::vector<CardGambleItem*> > MAP_CARDGAMEBLEITEM;
class CConfCardGamble : public CConfBase
{
public:
virtual ~CConfCardGamble();
virtual bool LoadCSV(const std::string& str);
bool getData(int star, std::vector<CardGambleItem*>& vec)
{
MAP_CARDGAMEBLEITEM::iterator iter = m_GardGambleData.find(star);
if (iter != m_GardGambleData.end())
{
vec = iter->second;
return true;
}
return false;
}
private:
MAP_CARDGAMEBLEITEM m_GardGambleData;
};
class CConfEquipment : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfEqupmentCreate :public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfProp : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfDropProp : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
virtual std::map<int, DropPropItem>& GetShowDropPropItem() { return m_ShowDropPropItem; }
virtual DropPropItem* GetRealDropPropItem(int nDropID);
virtual bool ReSetShowDropPropItem();
virtual bool SetShowDropPropItem(int nDropID, DropPropItem &Item);
protected:
std::map<int, DropPropItem> m_ShowDropPropItem; //ĵĵ
};
class CConfMail : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfSoldierUpRate : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfSuit : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfSaleSummoner : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfTask : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfOutterBonus : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfArenaReward : public CConfBase
{
public:
CConfArenaReward();
~CConfArenaReward();
virtual bool LoadCSV(const std::string& str);
public:
ArenaRewardItem * m_pDayWinItem; //ۼʤ
ArenaRewardItem * m_pDayContinusWinItem; //ʤ
ArenaRewardItem * m_pDayBattleItem; //սν
std::vector<ArenaRewardItem *> m_RankRewards; //ƽн
std::vector<ArenaRewardItem *> m_CampionRankRewards; //н
};
class CConfArenaTask : public CConfBase
{
public:
bool LoadCSV(const std::string& str);
};
class CConfAnimationPlayOrder : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfHallStanding : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CShopGoodsData : public CConfBase
{
virtual bool LoadCSV(const std::string& str);
public:
std::list<ShopGoodsConfigData*>* GetShopList(int nShopID);
private:
std::map<int, std::list<ShopGoodsConfigData*> > m_MapShopID;
};
class CShopData : public CConfBase
{
virtual bool LoadCSV(const std::string& str);
};
class CConfDiamondShop : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
//ÿǩ
class CConfDaySign : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
SCheckInDayConfig * GetMonthSignDay(int nMonth, int nDay);
private:
std::map<int, std::map<int, SCheckInDayConfig> > m_MapYearSign; //һǩϢ
};
//ۼǩ
class CConfConDaySign : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfFirstPay : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
SFirstPayData * GetFirstPayData() { return &m_FirstPayData; }
protected:
SFirstPayData m_FirstPayData;
};
class CConfBDActive : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
std::map<SBDActiveKey, SBDActiveData> & getBDAllData() { return m_MapBDActive; }
SBDActiveData* getDBActiveData(int nActiveID, int nTaskID);
protected:
std::map<SBDActiveKey, SBDActiveData> m_MapBDActive;
};
class CConfTalent : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfTalentArrange : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
};
class CConfPVPShare : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
NO_KEY_DATA(SPVPShareData);
};
class CConfPVPUpload : public CConfBase
{
public:
virtual bool LoadCSV(const std::string& str);
NO_KEY_DATA(SPVPUploadData);
};
////////////////////////////////ѯ//////////////////////////////////////////
// ѯ
inline const ActivityInstanceItem* queryConfActivityInstance(int instanceId)
{
CConfActivityInstance *conf = dynamic_cast<CConfActivityInstance*>(
CConfManager::getInstance()->getConf(CONF_ACTIVITY_INSTANCE));
return static_cast<ActivityInstanceItem*>(conf->getData(instanceId));
}
// ѯװ
inline const EquipmentItem* queryConfEquipment(int equipID)
{
CConfEquipment *conf = dynamic_cast<CConfEquipment*>(
CConfManager::getInstance()->getConf(CONF_EQUIPMENT));
return static_cast<EquipmentItem*>(conf->getData(equipID));
}
//ѯװɱ
inline const EquipPropCreate *queryConfEquipCreat(int equipCreatID)
{
CConfEqupmentCreate *conf = dynamic_cast<CConfEqupmentCreate*>(
CConfManager::getInstance()->getConf(CONF_EQUIP_CREATE));
return static_cast<EquipPropCreate*>(conf->getData(equipCreatID));
}
// ѯװ
inline const SuitItem* queryConfSuit(int suitId)
{
CConfSuit* conf = dynamic_cast<CConfSuit*>(
CConfManager::getInstance()->getConf(CONF_SUIT));
return static_cast<SuitItem*>(conf->getData(suitId));
}
// ѯ߱
inline const PropItem* queryConfProp(int itemID)
{
CConfProp *conf = dynamic_cast<CConfProp*>(
CConfManager::getInstance()->getConf(CONF_ITEM));
return static_cast<PropItem*>(conf->getData(itemID));
}
// ѯ
inline const TaskItem* queryConfTask(int taskID)
{
CConfTask *conf = dynamic_cast<CConfTask*>(
CConfManager::getInstance()->getConf(CONF_TASK));
return static_cast<TaskItem*>(conf->getData(taskID));
}
// ѯɾ
inline const AchieveItem* queryConfAchieve(int achieveId)
{
CConfAchieve* conf = dynamic_cast<CConfAchieve*>(
CConfManager::getInstance()->getConf(CONF_ACHIEVE));
return static_cast<AchieveItem*>(conf->getData(achieveId));
}
// ѯٻʦ
inline const SaleSummonerConfItem* queryConfSaleSummoner(int summonerId)
{
CConfSaleSummoner* conf = dynamic_cast<CConfSaleSummoner*>(
CConfManager::getInstance()->getConf(CONF_SALESUMMONER));
return static_cast<SaleSummonerConfItem*>(conf->getData(summonerId));
}
// ѯ齱ʱ
inline const bool queryConfCardGamble(int rare, std::vector<CardGambleItem*> &vec)
{
CConfCardGamble *conf = dynamic_cast<CConfCardGamble*>(
CConfManager::getInstance()->getConf(CONF_CARD_GAMBLE));
return conf->getData(rare, vec);
}
// ѯʿDZ
inline const SoldierUpRateItem* queryConfSoldierUpRateItem(int soldierID)
{
CConfSoldierUpRate *conf = dynamic_cast<CConfSoldierUpRate*>(
CConfManager::getInstance()->getConf(CONF_SOLDIER_UP_RATE));
return static_cast<SoldierUpRateItem*>(conf->getData(soldierID));
}
// ѯʼ
inline const MailItem* queryConfMailItem(int mailID)
{
CConfMail *conf = dynamic_cast<CConfMail*>(
CConfManager::getInstance()->getConf(CONF_MAIL));
return static_cast<MailItem*>(conf->getData(mailID));
}
// ѯսЧ
inline const OutterBonusItem* queryConfOutterBonusItem(int ID)
{
CConfOutterBonus *conf = dynamic_cast<CConfOutterBonus*>(
CConfManager::getInstance()->getConf(CONF_OUTTER_BONUS));
return static_cast<OutterBonusItem*>(conf->getData(ID));
}
// ѯ
inline const DropPropItem* queryConfDropProp(int dropId)
{
CConfDropProp *conf = dynamic_cast<CConfDropProp*>(
CConfManager::getInstance()->getConf(CONF_ITEMDROP));
return static_cast<DropPropItem*>(conf->GetRealDropPropItem(dropId));
}
//Ϣ
inline const GoldTestConfItem * queryConfGoldTest(int nWeekDay)
{
CConfGoldTest * conf = dynamic_cast<CConfGoldTest *>(
CConfManager::getInstance()->getConf(CONF_GOLD_TEST));
return static_cast<GoldTestConfItem *>(conf->getData(nWeekDay));
}
// ѯ
inline const HeroTestItem* queryConfHeroTest(int instanceId)
{
CConfHeroTest *conf = dynamic_cast<CConfHeroTest*>(
CConfManager::getInstance()->getConf(CONF_HERO_TEST));
return static_cast<HeroTestItem*>(conf->getData(instanceId));
}
//
inline const TowerFloorItem *queryConfTowerFloor(int floor)
{
CConfTowerFloor *conf = dynamic_cast<CConfTowerFloor*>(
CConfManager::getInstance()->getConf(CONF_TOWER_FLOOR));
return static_cast<TowerFloorItem*>(conf->getData(floor));
}
// ¥
inline int queryMaxTowerFloor()
{
CConfTowerFloor *conf = dynamic_cast<CConfTowerFloor*>(
CConfManager::getInstance()->getConf(CONF_TOWER_FLOOR));
return conf->getMaxFloor();
}
//buff
inline const TowerBuffItem *queryConfTowerBuff(int id)
{
CConfTowerBuff *conf = dynamic_cast<CConfTowerBuff*>(
CConfManager::getInstance()->getConf(CONF_TOWER_BUFF));
return static_cast<TowerBuffItem*>(conf->getData(id));
}
//ȡһܽ
inline const TowerRankItem* queryConfTowerRankReward(int nIndex)
{
CConfTowerRank *conf = dynamic_cast<CConfTowerRank*>(
CConfManager::getInstance()->getConf(CONF_TOWER_RANK));
std::map<int, void*> MapData = conf->getDatas();
for (std::map<int,void*>::reverse_iterator rator = MapData.rbegin(); rator != MapData.rend(); ++rator)
{
TowerRankItem * pRewardItem = static_cast<TowerRankItem*>(rator->second);
if (pRewardItem == NULL || pRewardItem->Rank.size() != 2)
{
continue;
}
if (nIndex <= pRewardItem->Rank[1] && nIndex >= pRewardItem->Rank[0])
{
return pRewardItem;
}
}
return NULL;
}
// ȡ
inline const GoldTestChestConfItem *queryConfGoldTestChest(int lv)
{
CConfGoldTestChest *conf = dynamic_cast<CConfGoldTestChest*>(
CConfManager::getInstance()->getConf(CONF_GOLD_TEST_CHEST));
return static_cast<GoldTestChestConfItem*>(conf->getData(lv));
}
//ȡPVPÿս(type 0Ϊƽ,1Ϊ)
inline ArenaRewardItem* queryConfPvpRankReward(int nIndex, int type = 0)
{
CConfArenaReward *conf = dynamic_cast<CConfArenaReward*>(
CConfManager::getInstance()->getConf(CONF_ARENA_REWARD));
std::vector<ArenaRewardItem *> VectPvpRankReward;
if (0 == type)
{
VectPvpRankReward = conf->m_RankRewards;
}
else
{
VectPvpRankReward = conf->m_CampionRankRewards;
}
for (std::vector<ArenaRewardItem *>::reverse_iterator rator = VectPvpRankReward.rbegin(); rator != VectPvpRankReward.rend(); ++rator)
{
ArenaRewardItem * pRewardItem = *rator;
if (pRewardItem == NULL || pRewardItem->Type_Parameter.size() != 2)
{
continue;
}
if (nIndex <= pRewardItem->Type_Parameter[1] && nIndex >= pRewardItem->Type_Parameter[0])
{
return pRewardItem;
}
}
return NULL;
}
inline const ArenaTaskItem * queryArenaTaskItem(int taskId)
{
CConfArenaTask *pConf = dynamic_cast<CConfArenaTask*>(
CConfManager::getInstance()->getConf(CONF_ARENA_TASK));
return static_cast<ArenaTaskItem*>(pConf->getData(taskId));
}
inline const AnimationPlayOrderItem* queryConfAnimationPlayOrder(const int& resID)
{
CConfAnimationPlayOrder *confPlayOrder = dynamic_cast<CConfAnimationPlayOrder*>(
CConfManager::getInstance()->getConf(CONF_ANIMATION_PLAY_ORDER));
return static_cast<AnimationPlayOrderItem*>(confPlayOrder->getData(resID));
}
inline const HallStandingItem* queryConfHallStanding(const int& order)
{
CConfHallStanding *conf = dynamic_cast<CConfHallStanding*>(
CConfManager::getInstance()->getConf(CONF_HALL_STANDING));
return static_cast<HallStandingItem*>(conf->getData(order));
}
//ȡij̵Ӧб
inline const std::list<ShopGoodsConfigData*>* queryConfShopList(int nShopID)
{
CShopGoodsData *pConf = dynamic_cast<CShopGoodsData*>(
CConfManager::getInstance()->getConf(CONF_SHOP_GOODS));
return pConf->GetShopList(nShopID);
}
inline const ShopGoodsConfigData * queryConfShopData(int nShopGoodsID)
{
CShopGoodsData *pConf = dynamic_cast<CShopGoodsData*>(
CConfManager::getInstance()->getConf(CONF_SHOP_GOODS));
return static_cast<ShopGoodsConfigData *>(pConf->getData(nShopGoodsID));
}
//ǩ
inline const SCheckInDayConfig *queryCheckInDaySign(int nMonth, int Days)
{
CConfDaySign *pConf = dynamic_cast<CConfDaySign*>(
CConfManager::getInstance()->getConf(CONF_DAYSIGN));
return reinterpret_cast<SCheckInDayConfig *>(pConf->GetMonthSignDay(nMonth, Days));
}
//ۼǩ
inline const SConCheckInConfig * queryConCheckInSign(int nTimes)
{
CConfConDaySign *pConf = dynamic_cast<CConfConDaySign*>(
CConfManager::getInstance()->getConf(CONF_CONDAYSIGN));
return reinterpret_cast<SConCheckInConfig *>(pConf->getData(nTimes));
}
//׳
inline const SFirstPayData *queryFirstPayData()
{
CConfFirstPay * pConf = dynamic_cast<CConfFirstPay*>(
CConfManager::getInstance()->getConf(CONF_FIRSTPAY_SETING));
return pConf->GetFirstPayData();
}
//ȡ츳Ϣ
inline const STalentData *queryTalentData(int talentId)
{
CConfTalent * pConf = dynamic_cast<CConfTalent*>(
CConfManager::getInstance()->getConf(CONF_TALENT));
return static_cast<STalentData *>(pConf->getData(talentId));
}
//ȡ츳ҳϢ
inline const STalentArrangeData *queryTalentArrangeData(int arrangeId)
{
CConfTalentArrange * pConf = dynamic_cast<CConfTalentArrange*>(
CConfManager::getInstance()->getConf(CONF_TALENT_ARRANGE));
return static_cast<STalentArrangeData *>(pConf->getData(arrangeId));
}
#endif
|
Python | UTF-8 | 564 | 2.640625 | 3 | [] | no_license | N,K=map(int,input().split())
List = list(map(int, input().split()))
INF = 10000000000
expList = [INF]*1001
def expectationF(num):
if expList[num] == INF:
exp = 0
for i in range(1,num+1):
exp += i/num
expList[num] = exp
return expList[num]
res = 0
mid = 0
midList=[]
for i in range(N):
if i>=1:
midList.append(expectationF(List[i])+midList[i-1])
else:
midList.append(expectationF(List[i]))
m=K-1
for j in range(N-m):
if j == 0:
mid = midList[j+m]
else:
mid = midList[j+m]- midList[j-1]
res = max(res,mid)
print(res) |
Markdown | UTF-8 | 3,158 | 3.375 | 3 | [] | no_license | # Milestone 6 - Refactoring Report
**Team members:**
Isabel Bolger and Lynnsey Martin
**Github team/repo:**
Edhelen: https://github.ccs.neu.edu/CS4500-S21/Edhelen
## Plan
List areas of your code/design you'd like to improve with brief descriptions,
anything that comes to mind. Tip: translate this list into Github Issues.
1. Ensure all builders took in a Location object instead of 2 ints
2. Change the column and row fields in the Location class to be private. Use getters instead
3. Change the room builder to count the boundaries of the room as part of the origin and bounds
## Changes
Summarize the work you have performed during this week.
1. Ensure all builders took in a Location object instead of 2 ints
- For all methods in the room builders that took in an int for row and an int for column, we changed it to take in a Location object and then accessed the row and column fields from there. This change was pretty big in terms of lines of code being modified, however it was a trivial change, and didn't change funcitonality
2. Change the column and row fields in the Location class to be private. Use getters instead
- We added a getRow() anad getColumn() method in the Location class. Although this change doesn't change functionality, it makes the Location object more of a "read-only" object. This change would defend our program in case we accidentally return a Location object instead of a copy.
3. Change the room builder to count the boundaries of the room as part of the origin and bounds
- Based on the testing case for milestone #3, our current representation of a room as only the walkable tiles in that room may not be accurate. It would be helpful to realign our construction to the definition described in milestone 3 (if that continues to stay consistent). This requires the origin of the "room" and the rows and columns describing its width and height include the outer boundary of the room (e.g. the wall tiles around).
## Future Work
For future work, we recognize the need to update our representation of a level and have plans to relocate adversaries into the level in order to account for the likelihood that adversaries will only exist in a single level (and not carry on with the players). Therefore, we plan to move adversaries (and their construction) inside the level (as opposed to the GameManager).
We also recognize the need to change our representation of a Location sooner rather than later. We currently are limited between only representing a Location as a point on the map or null, but our players will also need to differentiate between being Ejected and having Exited. Therefore, we plan to make Ejected and Exited Locations that extend the current Locations that can represent if a player is not playing any longer.
## Conclusion
This week was valuable not only to execute on refactoring, but to also to allow us to critically analyze the decisions we made in our code and how they have needed to evolve. While we still may not have all the information for future planning that we wanted, this week allowed us to consider the ways our design may not be fully future-proofed or flexible moving forward.
|
Java | UTF-8 | 10,955 | 2.4375 | 2 | [] | no_license | package ru.ivanludvig.ship;
import ru.ivanludvig.starstorm.Gam;
import ru.ivanludvig.tween.SpriteTween;
import ru.ivanludvig.tween.SputnikTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenEquation;
import aurelienribon.tweenengine.TweenEquations;
import aurelienribon.tweenengine.equations.Linear;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
public class Sputnik {
Gam game;
public Sprite sprite;
Vector2 pos;
public Body body;
float PTM = 32f;
public int ammo;
public int gameammo;
public float speed;
public float cspeed;
public float maxspeed;
public int hp;
public float angle = 0f;
public float power;
public float agility;
public float weaponry;
public int count = 1;
public int ccount;
public Vector2 size;
int num;
public ParticleEffect effect;
public Music engine;
public Sputnik(Gam game) {
this.game = game;
ammo = 20;
gameammo = ammo;
engine = (Music)game.manager.get("audio/engine.mp3", Music.class);
engine.setLooping(true);
cspeed = 0f;
/*
this.hp = (int) Stats.str[g];
this.speed = Stats.sp[g];
this.maxspeed = Stats.maxsp[g];
this.power = Stats.pow[g];
this.agility = Stats.ag[g];
this.weaponry = Stats.weap[g];
*/
//body.setLinearVelocity(1f, 1f);]
}
public static final double DEGREES_TO_RADIANS = (double)(Math.PI/180);
public void render(float delta){
effect.setPosition((float) (getPos().x-(Math.cos(sprite.getRotation()*DEGREES_TO_RADIANS)*size.x/2)),
(float) (getPos().y-(Math.sin(sprite.getRotation()*DEGREES_TO_RADIANS)*size.y/2)));
effect.draw(game.defense.batch, delta);
sprite.setBounds(getPos().x-32, getPos().y-32, 64, 64);
sprite.draw(game.defense.batch);
if((game.defense.ui.tp.getKnobPercentX()!=0) || (game.defense.ui.tp.getKnobPercentY()!=0 )){
body.setLinearVelocity(new Vector2(game.defense.ui.tp.getKnobPercentX()*cspeed,
game.defense.ui.tp.getKnobPercentY()*cspeed));
addAngle((float) (new Vector2(game.defense.ui.tp.getKnobPercentX(),
game.defense.ui.tp.getKnobPercentY()).angle()));
tweening();
stween();
}else{
body.setLinearVelocity(cspeed*((float)Math.cos(angle*DEGREES_TO_RADIANS)),
(cspeed*((float)Math.sin(angle*DEGREES_TO_RADIANS))));
slowtween();
}
engine.setVolume(power*cspeed/100f*1.1f);
body.setTransform(body.getWorldCenter(), (float) ((float) sprite.getRotation()*DEGREES_TO_RADIANS));
if(getPos().x>990){
body.setTransform(990/PTM, body.getWorldCenter().y, (float) ((float) sprite.getRotation()*DEGREES_TO_RADIANS));
}else if(getPos().x<-190){
body.setTransform(-190/PTM, body.getWorldCenter().y, (float) ((float) sprite.getRotation()*DEGREES_TO_RADIANS));
}
if(getPos().y>580){
body.setTransform(body.getWorldCenter().x, 580/PTM, (float) ((float) sprite.getRotation()*DEGREES_TO_RADIANS));
}else if(getPos().y<-100){
body.setTransform(body.getWorldCenter().x, -100/PTM, (float) ((float) sprite.getRotation()*DEGREES_TO_RADIANS));
}
if(Math.abs(angle - sprite.getRotation())>1){
}else{
body.setFixedRotation(true);
//cspeed = speed;
}
if(j==1){
shoot(vec2);
}
//cspeed=body.getLinearVelocity().len();
}
public void tweening(){
if(angle-sprite.getRotation()>180){
angle-=360;
}
else if(sprite.getRotation()-angle>180){
angle+=360;
}else{
//angle = acute(angle);
//sprite.setRotation(acute(sprite.getRotation()));
}
if(Math.abs(sprite.getRotation()-angle)>0.1){
game.defense.tweenManager.killTarget(sprite);
Tween.to(sprite, SpriteTween.ROTATION, (Math.abs(sprite.getRotation()-angle))*(1/this.agility)*0.03f)
.target(angle)
.ease(Linear.INOUT)
.start(game.defense.tweenManager);
}else{
}
}
public void stween(){
if(body.getLinearVelocity().len()>1f){
Tween.to(this, SputnikTween.speed, 3f)
.target(maxspeed)
.ease(Linear.INOUT)
.start(game.defense.tweenManager);
}else{
game.defense.tweenManager.killTarget(this);
cspeed = speed;
}
}
public void slowtween(){
if(body.getLinearVelocity().len()>0f){
Tween.to(this, SputnikTween.speed, 3f)
.target(0f)
.ease(Linear.INOUT)
.start(game.defense.tweenManager);
}else{
//game.defense.tweenManager.killTarget(this);
//cspeed = 0f;
}
}
public void shoottween(){
Tween.to(this, SputnikTween.speed, 1f/(float)Math.sqrt(ccount))
.target(-1f*power/agility)
.ease(TweenEquations.easeOutCirc)
.start(game.defense.tweenManager);
}
public float acute(float y){
float g = y;
return g;
}
int j = 0;
Vector2 vec2;
float mangle;
public void shoot(Vector2 vec){
System.out.println(ccount);
if(gameammo>=ccount){
if((game.defense.ui.tp.getKnobPercentX()==0) && (game.defense.ui.tp.getKnobPercentY()==0 )){
shoottween();
if(j==0){
addAngle((float) (((new Vector2(vec)).sub(game.defense.sputnik.getPos())).angle()));
tweening();
}
j=1;
vec2 = vec;
if(Math.abs(sprite.getRotation() - (float) (angle))<5){
switch(ccount){
case 1:
game.defense.shooter.shoot(vec, new Vector2(0,0));
gameammo--;
break;
case 2:
doubleShoot(vec);
gameammo-=2;
break;
case 3:
tripleShoot(vec);
gameammo-=3;
break;
}
j=0;
}
}else{
if(gameammo>=ccount){
switch(ccount){
case 1:
game.defense.shooter.shoot(vec, new Vector2(0,0));
gameammo--;
break;
case 2:
doubleShoot(vec);
gameammo-=2;
break;
case 3:
tripleShoot(vec);
gameammo-=3;
break;
}
j=0;
}
}
}
}
public Vector2 getPos(){
return body.getWorldCenter().scl(PTM);
}
public void addAngle(float r){
if((r - sprite.getRotation())>=360){
while((r - sprite.getRotation())>=360){
r-=360;
}
}else if((sprite.getRotation() - r)>=360){
while((sprite.getRotation() - r)>=360){
r+=360;
}
}
angle = r;
}
public void create(){
this.sprite = new Sprite((Texture) game.manager.get(("ships/"+num+".png")));
pos = new Vector2((float)Math.random()*800, (float)Math.random()*480);
size = new Vector2(Stats.height[num-1], Stats.width[num-1]);
body = createCircle(7);
this.hp = Stats.hpFunc(num);
this.maxspeed = Stats.speedFunc(num);
this.agility = Stats.agilityFunc(num);
this.speed = Stats.minSpeedFunc(maxspeed, agility);
System.out.println(size);
this.power = Stats.powerFunc(num);
this.weaponry = Stats.weapFunc(num, power);
this.sprite.setOrigin(32, 32);
effect = new ParticleEffect((ParticleEffect)
game.manager.get("data/fire/"+Stats.names[game.shipnum].toLowerCase()+".p"));
this.effect.reset();
this.effect.scaleEffect(0.9f);
if(num<=4){
count = 1;
}else if(num>=8){
count = 3;
}else{
count = 2;
}
ccount = 1;
engine.setVolume(power/7f);
cspeed=0f;
angle=(float)Math.random()*360;
sprite.setRotation(angle);
engine.play();
engine.setVolume(power*cspeed/100f*1.5f);
}
public void addAmmo(int amount){
gameammo+=amount;
}
private Body createCircle(int radius) {
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(pos.x/PTM, pos.y/PTM);
Body body = game.defense.world.createBody(bodyDef);
body.setUserData(this);
PolygonShape shape = new PolygonShape();
shape.setAsBox(size.x/2/PTM, size.y/2/PTM);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 5f;
fixtureDef.friction = 0.04f;
fixtureDef.restitution = 0.06f;
Fixture fixture = body.createFixture(fixtureDef);
return body;
}
public void tripleShoot(Vector2 vec){
if((Math.cos(this.angle*this.DEGREES_TO_RADIANS)>0)&&(Math.sin(this.angle*this.DEGREES_TO_RADIANS)>0)
|| (Math.cos(this.angle*this.DEGREES_TO_RADIANS)<0)&&(Math.sin(this.angle*this.DEGREES_TO_RADIANS)<0)){
game.defense.shooter.shoot(vec, new Vector2((float)(this.weaponry*-10*Math.abs(Math.sin(this.angle*this.DEGREES_TO_RADIANS))),
(float)(this.weaponry*20*Math.abs(Math.cos(this.angle*this.DEGREES_TO_RADIANS)))));
game.defense.shooter.shoot(vec, new Vector2(0,0));
game.defense.shooter.shoot(vec, new Vector2((float)(this.weaponry*10*Math.abs(Math.sin(this.angle*this.DEGREES_TO_RADIANS))),
(float)(this.weaponry*-20*Math.abs(Math.cos(this.angle*this.DEGREES_TO_RADIANS)))));
System.out.println("ok this first ");
}else{
game.defense.shooter.shoot(vec, new Vector2((float)(this.weaponry*10*Math.abs(Math.sin(this.angle*this.DEGREES_TO_RADIANS))),
(float)(this.weaponry*20*Math.abs(Math.cos(this.angle*this.DEGREES_TO_RADIANS)))));
game.defense.shooter.shoot(vec, new Vector2(0,0));
game.defense.shooter.shoot(vec, new Vector2((float)(this.weaponry*-10*Math.abs(Math.sin(this.angle*this.DEGREES_TO_RADIANS))),
(float)(this.weaponry*-20*Math.abs(Math.cos(this.angle*this.DEGREES_TO_RADIANS)))));
}
}
public void doubleShoot(Vector2 vec){
if((Math.cos(this.angle*this.DEGREES_TO_RADIANS)>0)&&(Math.sin(this.angle*this.DEGREES_TO_RADIANS)>0)
|| (Math.cos(this.angle*this.DEGREES_TO_RADIANS)<0)&&(Math.sin(this.angle*this.DEGREES_TO_RADIANS)<0)){
game.defense.shooter.shoot(vec, new Vector2((float)(this.weaponry*10*Math.abs(Math.sin(this.angle*this.DEGREES_TO_RADIANS))),
(float)(-10*Math.abs(Math.cos(this.angle*this.DEGREES_TO_RADIANS)))));
game.defense.shooter.shoot(vec, new Vector2((float)(this.weaponry*-10*Math.abs(Math.sin(this.angle*this.DEGREES_TO_RADIANS))),
(float)(10*Math.abs(Math.cos(this.angle*this.DEGREES_TO_RADIANS)))));
}else{
game.defense.shooter.shoot(vec, new Vector2((float)(this.weaponry*10*Math.abs(Math.sin(this.angle*this.DEGREES_TO_RADIANS))),
(float)(10*Math.abs(Math.cos(this.angle*this.DEGREES_TO_RADIANS)))));
game.defense.shooter.shoot(vec, new Vector2((float)(this.weaponry*-10*Math.abs(Math.sin(this.angle*this.DEGREES_TO_RADIANS))),
(float)(-10*Math.abs(Math.cos(this.angle*this.DEGREES_TO_RADIANS)))));
}
}
public void dispose () {
effect.dispose();
}
}
|
C++ | UTF-8 | 370 | 3.109375 | 3 | [] | no_license |
/* Programm is searching how many 0 does number N have?*/
#include <iostream>
using namespace std;
int main()
{
unsigned int N;
int f = 0;
cin >> N;
if (N == 0) {
cout << 1;
return 0;
}
for (;N != 0; N /= 10) {
if (N % 10 / 1 == 0) {
f++;
}
}
if (f == 0) {
cout << " None ";
}
else {
cout << f;
}
return 0;
}
|
C++ | UTF-8 | 365 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
#define INF 100000000
int main()
{
int n;
while(cin >> n, n)
{
int Min = INF, Max = 0;
while(n--)
{
int a, b, c, d, e;
cin >> a >> b >> c >> d >> e;
int sum = a + b + c + d + e;
Min = min(Min, sum);
Max = max(Max, sum);
}
cout << Max << " " << Min << endl;
}
return 0;
}
|
Java | UTF-8 | 5,452 | 2.21875 | 2 | [] | no_license | package com.testyantra.emp.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.testyantra.emp.bean.EmployeeInfoBean;
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
HttpSession session=req.getSession(false);
PrintWriter out=resp.getWriter();
if(session!=null){
EmployeeInfoBean bean=(EmployeeInfoBean) req.getAttribute("bean");
if(bean==null) {
out.print("<html>");
out.print("<body>");
out.print("<h1> <span style=\"color:red\">Employee Not Found</span></h1>");
out.print("</body>");
out.print("</html>");
}else {
out.print("<!DOCTYPE html> ") ;
out.print("<html> ") ;
out.print("<head> ") ;
out.print("<meta charset=\"ISO-8859-1\"> ") ;
out.print("<title>Insert title here</title> ") ;
out.print("<link rel=\"stylesheet\" ") ;
out.print(" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" ") ;
out.print(" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" ") ;
out.print(" crossorigin=\"anonymous\"> ") ;
out.print("<script ") ;
out.print(" src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\" ") ;
out.print(" ></script> ") ;
out.print("</head> ") ;
out.print("<body> ") ;
out.print("<nav class=\"navbar navbar-expand-lg navbar-light bg-light\"> ") ;
out.print(" <a class=\"navbar-brand\" href=\"profile\">EMP</a> ") ;
out.print(" <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navrSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">");
out.print(" <span class=\"navbar-toggler-icon\"></span> ") ;
out.print(" </button> ") ;
out.print(" ") ;
out.print(" ") ;
out.print(" <form class=\"form-inline my-2 my-lg-0\" action=\"./search\"> ") ;
out.print(" <input class=\"form-control mr-sm-2\" type=\"search\" name=\"id\" placeholder=\"Search\" aria-labelSearch\">");
out.print(" <button class=\"btn btn-outline-success my-2 my-sm-0\" type=\"submit\">Search</button") ;
out.print(" </form> ") ;
//out.print(" <a href=\"./html/login.html\">Logout</a> ") ;
out.print(" <a href=\"./employeelogin.html\">Logout</a> ") ;
out.print("</nav> ") ;
out.print(" ") ;
out.print("<br> ID "
+ ">" + bean.getId());
out.print("<br> Name ====>" + bean.getEmpName());
out.print("<br> Age ====>" + bean.getAge());
out.print("<br> Phone ====>" + bean.getPhone());
out.print("<br> Gender ====>" + bean.getGender());
out.print("<br> Salary ====>" + bean.getSalary());
out.print("<br> Joining Date ====>" + bean.getJoiningDate());
out.print("<br> Account number ====>" + bean.getAccountNumber());
out.print("<br>Email ====>" + bean.getEmail());
out.print("<br> Designation ====>" + bean.getDesignation());
out.print("<br> DOB ====>" + bean.getDob());
out.print("<br> DEPT_NO ====>" + bean.getDepartmentId());
out.print("<br> MNGR ID ====>" + bean.getManagerId());
out.print("</body> ") ;
out.print("</html> ") ;
}
}
else {
String path="Login.jsp";
resp.setContentType("text/html");
out.println("invalid session!! please login again ");
RequestDispatcher dispatcher=req.getRequestDispatcher(path);
dispatcher.include(req,resp);
}
}
}
|
Java | UTF-8 | 7,876 | 2.015625 | 2 | [] | no_license | package com.orel.ltg;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
FacebookHandler.getInstance().onActivityResult(requestCode, resultCode, data);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
super.onDestroy();
FacebookHandler.getInstance().onDestroy();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements View.OnClickListener {
private Button mFacebookLoginButton;
private Button mFacebookFriendsButton;
private RecyclerView mFriendsList;
private View mProgressBarView;
private FriendsAdapter mAdapter;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mFacebookLoginButton = (Button) view.findViewById(R.id.facebook_login_btn);
mFacebookFriendsButton = (Button) view.findViewById(R.id.facebook_get_friends_btn);
mFriendsList = (RecyclerView) view.findViewById(R.id.friends_list);
mProgressBarView = view.findViewById(R.id.progress_bar);
registerOnClickListeners(mFacebookLoginButton, mFacebookFriendsButton);
LinearLayoutManager lManager = new LinearLayoutManager(getActivity());
mFriendsList.setHasFixedSize(true);
mFriendsList.setLayoutManager(lManager);
mAdapter = new FriendsAdapter();
mFriendsList.setAdapter(mAdapter);
mAdapter.setListener(new FriendsAdapter.OnFriendClickListener() {
@Override
public void OnFriendClicked(String friendID) {
mProgressBarView.setVisibility(View.VISIBLE);
FacebookHandler.getInstance().shareOnWall(getActivity(), friendID, new FacebookHandler.OnFacebookResult() {
@Override
public void success() {
if(isAdded()) {
Toast.makeText(getActivity(), "Ata Totach", Toast.LENGTH_SHORT).show();
mProgressBarView.setVisibility(View.GONE);
}
}
@Override
public void failed(String error) {
if(isAdded()) {
Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
mProgressBarView.setVisibility(View.GONE);
}
}
});
}
});
// showHashKey(getActivity());
}
private void registerOnClickListeners(View... views) {
for(View v : views) {
v.setOnClickListener(this);
}
}
public static void showHashKey(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(
"com.orel.ltg", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.i("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
@Override
public void onClick(View v) {
if(v.equals(mFacebookLoginButton)) {
FacebookHandler.getInstance().loginToFacebook(getActivity(), false, new FacebookHandler.OnFacebookResult() {
@Override
public void success() {
if(isAdded()) {
Toast.makeText(getActivity(), "Ata Totach", Toast.LENGTH_SHORT).show();
mProgressBarView.setVisibility(View.GONE);
mFacebookFriendsButton.setEnabled(true);
}
}
@Override
public void failed(String error) {
if(isAdded()) {
Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
mProgressBarView.setVisibility(View.GONE);
}
}
});
} else if(v.equals(mFacebookFriendsButton)) {
mProgressBarView.setVisibility(View.VISIBLE);
FacebookHandler.getInstance().getFriendsList(new FacebookHandler.OnFriendsResult() {
@Override
public void success(List<FacebookUser> users) {
if(isAdded()) {
mProgressBarView.setVisibility(View.GONE);
mAdapter.setFriendsList(users);
}
}
@Override
public void failed(String error) {
if(isAdded()) {
mProgressBarView.setVisibility(View.GONE);
Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
}
|
Python | UTF-8 | 888 | 2.734375 | 3 | [
"MIT"
] | permissive | #In[1]:
import pymongo
from pymongo import MongoClient
#In[2]:
client = MongoClient()
db = client.test
#In[3]:
#Inserción:
db.users.insert_one({ 'name' : 'Cristal P' })
#In[4]:
users_to_create = [ {'name':'Holly'}, {'name':'Pete'} ]
db.users.insert_many( users_to_create )
#In[5]:
result = db.users.insert_one(
{
'name' : 'Vella',
'address' : {
'street' : '2 Avenue',
'zip_code' : 44550,
'building' : 1480
},
'phones' : [ 5523749038, 5542359985 ]
}
)
#In[6]: Ver y consultar:
print('Consulta:')
cursor = db.users.find()
[ print(documento) for documento in cursor ]
#In[7]: Modificación
to_modify = { 'name':'Cristal P' }
new_doc = {'name' : 'Cris P'}
db.users.update_one( to_modify, {'$set':new_doc} )
print("Actualizado:")
cursor = db.users.find()
[ print(documento) for documento in cursor ]
# %%
|
JavaScript | UTF-8 | 1,887 | 2.875 | 3 | [] | no_license | const fs = require('fs');
const path = require('path');
const prettierRcPath = path.resolve(__dirname, '.prettierrc');
const prettierRcCopyPath = path.resolve(__dirname, '.prettierrc.copy');
// Version synchrone
try {
const content = fs.readFileSync(prettierRcPath, { encoding: 'utf-8' });
fs.writeFileSync(prettierRcCopyPath, content);
console.log('Copy sync done');
} catch (err) {
console.log(err.message);
}
// Version asynchrone
// Callback Hell / Pyramid of doom
// callbackhell.com
fs.readFile(prettierRcPath, { encoding: 'utf-8' }, (err, content) => {
if (err) {
console.log(err.message);
} else {
fs.writeFile(prettierRcCopyPath, content, (err) => {
if (err) {
console.log(err.message);
} else {
console.log('Copy async done');
}
});
}
});
// Version asynchrone basée sur des promesses
// Depuis ES6 -> Natif en JS, classe Promise
// Avant ES6 -> lib externe bluebird, q
// Concept assez proche : defer -> jQuery 1
fs.promises.readFile(prettierRcPath, { encoding: 'utf-8' })
.then((content) => fs.promises.writeFile(prettierRcCopyPath, content))
.then(() => console.log('Copy async promise done'))
.catch((err) => console.log(err.message))
// ES2017 async / await fonctions asynchrone
async function copyFile() {
try {
const content = await fs.promises.readFile(prettierRcPath, { encoding: 'utf-8' });
await fs.promises.writeFile(prettierRcCopyPath, content);
console.log('Copy sync done');
} catch (err) {
console.log(err.message);
}
}
copyFile();
// ligne suivante
// Top level await TypeScript 3.9+
// ES2020 ou 2021 (stage 3)
// try {
// const content = await fs.promises.readFile(prettierRcPath, { encoding: 'utf-8' });
// await fs.promises.writeFile(prettierRcCopyPath, content);
// console.log('Copy sync done');
// } catch (err) {
// console.log(err.message);
// }
|
Java | UTF-8 | 2,107 | 2.453125 | 2 | [] | no_license | /*
* @Title: ApiResponse.java
* @Package: com.carrefour.vos
* @author: rick_wanshihua@carrefour.com.cn
* @CreateDate:Aug 21, 2019 11:16:18 AM
* @UpdateUser: rick_wanshihua@carrefour.com.cn
* @UpdateDate: Aug 21, 2019 11:16:18 AM
* @UpdateRemark:第一版
* @Description: 后台调用结果类
* @Version: [V1.0]
*/
package org.sky.platform.util;
import org.springframework.http.HttpStatus;
/*
* @ClassName:ApiResponse
* @author: rick_wanshihua@carrefour.com.cn
* @CreateDate: Aug 21, 2019 11:16:18 AM
* @UpdateUser: rick_wanshihua@carrefour.com.cn
* @UpdateDate: Aug 21, 2019 11:16:18 AM
* @UpdateRemark:第一版
* @Description: 后台调用结果类
* @Version: [V1.0]
*/
public class ResponseResult implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 状态码
*/
private int code;
/**
* 返回信息
*/
private String message;
/**
* 返回数据对象
*/
private transient Object data;
public ResponseResult(int code, String message) {
this.code = code;
this.message = message;
this.data = null;
}
public ResponseResult(int code, String message, Object data){
this.code = code;
this.message = message;
this.data = data;
}
/**
* @return the code
*/
public int getCode() {
return code;
}
/**
* @param code the code to set
*/
public void setCode(int code) {
this.code = code;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
public static ResponseResult success(String message) {
return new ResponseResult(HttpStatus.OK.value(), message, null);
}
public static ResponseResult error(String message) {
return new ResponseResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), message, null);
}
public static ResponseResult error(int code, String message) {
return new ResponseResult(code, message, null);
}
/**
* @return the data
*/
public Object getData() {
return data;
}
/**
* @param data the data to set
*/
public void setData(Object data) {
this.data = data;
}
}
|
Python | UTF-8 | 666 | 2.828125 | 3 | [] | no_license | from . import labdb
import pylab
import numpy
import scipy
import os
# get a list of all videos with 'time.txt'
db = labdb.LabDB()
rows = db.execute('SELECT video_id FROM video')
fps = []
for video_id, in rows:
filename = '/Volumes/HD3/video_data/%d/time.txt' % video_id
if os.path.exists('/Volumes/HD3/video_data/%d/time.txt' % video_id):
# open time.txt
t = numpy.loadtxt(filename)
frame = t[:,0]
time = t[:,1]
fit = scipy.polyfit(time, frame, 1)
print(fit)
fps.append(fit[0])
print(video_id)
# make a histogram
pylab.hist(fps)
pylab.show()
# plot time codes and fps for each
|
Java | UTF-8 | 284 | 2.1875 | 2 | [] | no_license | package state;
import main.Game;
public abstract class State {
protected Game mainGame;
public State(Game main){
mainGame = main;
}
public abstract void escIsDown();
public abstract void goBack();
public abstract String enterIsDown();
public abstract void isShow();
}
|
Markdown | UTF-8 | 2,435 | 3.296875 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: 代理、缓存、网关、隧道
tags:
- HTTP
categories: HTTP
description: 代理、缓存、网关、隧道
---
# HTTP代理、缓存、网关、隧道
通信数据转发程序:代理、网关、隧道
# 代理-agent
**位于客户端和服务器之间的HTTP中间实体。**
代理是一种有转发功能的应用程序。接收由客户端发送的请求并转发给服务器,同时也接收服务器返回的响应并转发给客户端。
<div class="rd">
<img src="/assets/images/2017/10-11-12/10-31-1.png" alt="">
</div>
- 缓存代理,会预先将资源的副本(缓存)保存在代理服务器上。
1. 透明代理,转发请求或响应时,不对报文做任何加工的代理类型。
2. 非透明代理,对报文内容进行加工的代理。
# 网关-gateway
连接其他应用程序的特殊Web服务器。
通常用于将HTTP流量转换成其他的协议。**提供非HTTP协议服务。**
<div class="rd">
<img src="/assets/images/2017/10-11-12/10-31-2.png" alt="">
</div>
网关优点:
利用网关能提高通信的安全性,因为可以在客户端与网关之间的通行线路上加密以确保连接的安全。
网关用处:
1. 网关可以连接数据库,使用SQL语句查询数据。
2. web购物网站上进行信用卡结算时,网关可以和信用卡结算系统联动。
# 隧道-tunnel
**对HTTP通信报文进行盲目转发且不会窥探数据的特殊代理。**
<div class="rd">
<img src="/assets/images/2017/10-11-12/10-31-3.png" alt="">
</div>
隧道的目的:
确保客户端能与服务器进行安全的通信。SSL
# 保存资源的缓存-cache
**缓存是指代理服务器或客户端本地磁盘保存的资源副本。**
利用缓存可减少对服务器的访问,因此也就节省了通信流量和通信时间。
<div class="rd">
<img src="/assets/images/2017/10-11-12/10-31-4.png" alt="">
</div>
缓存服务器是代理服务器的一种
## cache的有效期限
<div class="rd">
<img src="/assets/images/2017/10-11-12/10-31-5.png" alt="">
</div>
当判定缓存过期后,缓存服务器需向源服务器确认资源的有效性
## 客户端的缓存-web
浏览器缓存如果有效,就不必再向服务器请求相同的资源了,可以直接从本地磁盘内读取。
<div class="rd">
<img src="/assets/images/2017/10-11-12/10-31-6.png" alt="">
</div>
|
Java | UTF-8 | 3,778 | 2.390625 | 2 | [] | no_license | package com.shahidfoy.reactiveblog;
import com.shahidfoy.reactiveblog.models.Post;
import com.shahidfoy.reactiveblog.models.User;
import com.shahidfoy.reactiveblog.repositories.PostRepository;
import com.shahidfoy.reactiveblog.repositories.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import java.util.Arrays;
import java.util.List;
@Component
@Slf4j
public class DataInitializer implements CommandLineRunner {
private final PostRepository postRepository;
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public DataInitializer(PostRepository postRepository, UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.postRepository = postRepository;
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
@Override
public void run(String[] args) {
log.info("start data initialization ...");
this.postRepository.deleteAll()
.thenMany(
Flux.just("Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two",
"Post one", "Post two")
.flatMap(
title -> this.postRepository.save(Post.builder().title(title).content("content of " + title).build())
)
)
.log()
.subscribe(
null,
null,
() -> log.info("done initialization...")
);
this.userRepository.deleteAll()
.thenMany(
Flux.just("user", "admin")
.flatMap(
username -> {
List<String> roles = "user".equals(username)
? Arrays.asList("ROLE_USER")
: Arrays.asList("ROLE_USER", "ROLE_ADMIN");
User user = User.builder()
.roles(roles)
.username(username)
.password(passwordEncoder.encode("password"))
.email(username + "@auth.com")
.build();
return this.userRepository.save(user);
}
)
)
.log()
.subscribe(
null,
null,
() -> log.info("done users initialization...")
);
}
}
|
C# | UTF-8 | 1,610 | 2.53125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using DotnetAPI.Models;
using DotnetAPI.Services;
namespace DotnetMovieAPI.Controllers
{
public class MovieController : Controller
{
private readonly MovieService _movSvc;
public MovieController(MovieService movieService)
{
_movSvc = movieService;
}
public ActionResult<IList<Movie>> Index() => View(_movSvc.Read());
[HttpGet]
public ActionResult Create() => View();
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult<Movie> Create(Movie movie){
movie.Created = movie.LastUpdated = DateTime.Now;
if(ModelState.IsValid){
_movSvc.Create(movie);
}
return RedirectToAction("Index");
}
[HttpGet]
public ActionResult<Movie> Edit(string id) =>
View(_movSvc.Find(id));
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Movie movie)
{
movie.LastUpdated = DateTime.Now;
movie.Created = movie.Created.ToLocalTime();
if(ModelState.IsValid){
_movSvc.Update(movie);
return RedirectToAction("Index");
}
return View(movie);
}
[HttpGet]
public ActionResult Delete(string id)
{
_movSvc.Delete(id);
return RedirectToAction("Index");
}
}
} |
Swift | UTF-8 | 1,602 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright © 2018 μSwift Authors. All Rights Reserved.
// SPDX-License-Identifier: BSD-3
@frozen
public struct Bool {
@usableFromInline
internal var _value: Builtin.Int1
@_transparent
public init() {
let zero: Int8 = 0
self._value = Builtin.trunc_Int8_Int1(zero._value)
}
@_transparent
@usableFromInline
internal init(_ value: Builtin.Int1) {
self._value = value
}
@inlinable
public init(_ value: Bool) {
self = value
}
}
extension Bool: _ExpressibleByBuiltinBooleanLiteral {
@_transparent
public init(_builtinBooleanLiteral value: Builtin.Int1) {
self._value = value
}
}
extension Bool: ExpressibleByBooleanLiteral {
@_transparent
public init(booleanLiteral value: Bool) {
self = value
}
}
// COMPILER INTRINSIC
extension Bool {
@_transparent
public func _getBuiltinLogicValue() -> Builtin.Int1 {
return _value
}
}
extension Bool: Equatable {
@_transparent
public static func == (_ lhs: Bool, _ rhs: Bool) -> Bool {
return Bool(Builtin.cmp_eq_Int1(lhs._value, rhs._value))
}
}
extension Bool {
@_transparent
public static prefix func ! (_ value: Bool) -> Bool {
return Bool(Builtin.xor_Int1(value._value, true._value))
}
}
extension Bool {
@_transparent
@inline(__always)
public static func && (_ lhs: Bool, _ rhs: @autoclosure () throws -> Bool)
rethrows -> Bool {
return lhs ? try rhs() : false
}
@_transparent
@inline(__always)
public static func || (_ lhs: Bool, _ rhs: @autoclosure () throws -> Bool)
rethrows -> Bool {
return lhs ? true : try rhs()
}
}
|
C++ | UTF-8 | 2,816 | 3.34375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include "NbAleatBorne.h"
#include "NbAleat.h"
using namespace std;
class TabAleat {
private:
int _n;
int _nMax; // On va partir sur le principe qu'on augmente la taille en puissance de 2 pour "gagner" du temps
NbAleat** _tab;
int findNextPowerOfTwo(int nb) {
int power = 1;
while (power < nb) { power *= 2; }
return power;
}
TabAleat& copie(const TabAleat& other) {
_n = other._n;
_nMax = other._nMax;
_tab = new NbAleat*[_nMax];
for (int i = 0; i < _n; i++) {
_tab[i] = other._tab[i]->clone();
}
}
void destruction() {
for (int i = 0; i < _n; i++) {
delete _tab[i];
}
delete _tab;
}
protected:
virtual ostream& affiche(ostream& os) const {
os << "TabAleat [";
os << _n << ", " << _nMax << "," << endl;
for (int i = 0; i < _n; i++) {
os << "\t";
os << *(_tab[i]);
os << endl;
}
os << "]";
return os;
}
public:
TabAleat() {
_n = 0;
_nMax = 1;
_tab = new NbAleat*[_nMax];
}
TabAleat(int nb) {
if (nb < 0) { throw 1; }
_n = nb;
_nMax = findNextPowerOfTwo(nb);
_tab = new NbAleat*[_nMax];
for (int i = 0; i < nb; i++) {
_tab[i] = new NbAleat();
}
}
TabAleat(int nb, int binf, int bsup) {
if (nb < 0) { throw 1; }
_n = nb;
_nMax = findNextPowerOfTwo(nb);
_tab = new NbAleat*[_nMax];
try {
for (int i = 0; i < nb; i++) {
_tab[i] = new NbAleatBorne(binf, bsup);
}
} catch (int) {
throw 2;
}
}
TabAleat(const TabAleat& other) {
copie(other);
}
virtual ~TabAleat() {
destruction();
}
TabAleat& operator=(const TabAleat& other) {
if (this != &other) {
destruction();
copie(other);
}
return *this;
}
TabAleat& ajouter(const NbAleat& nba) {
if (_n == _nMax) {
_nMax *= 2;
NbAleat** _tabTemp = new NbAleat*[_nMax];
for (int i = 0; i < _n; i++) {
_tabTemp[i] = _tab[i];
}
delete[] _tab;
_tab = _tabTemp;
}
_tab[_n] = nba.clone();
_n++;
return *this;
}
TabAleat& operator+=(const NbAleat& nba) {
return ajouter(nba);
}
const NbAleat* operator[](int i) const {
if (i < 0 || i > _n) { throw 1; }
return _tab[i];
}
NbAleat* operator[](int i) {
if (i < 0 || i > _n) { throw 1; }
return _tab[i];
}
TabAleat& reGen() {
for (int i = 0; i < _n; i++) {
_tab[i]->reGen();
}
return *this;
}
int getTabSize() const {
return _n;
}
NbAleat** getTab() const {
return _tab;
}
// De cette maniere, on a plus qu'a redefinir affiche dans les classes filles
friend ostream& operator<<(ostream& os, const TabAleat& tabA);
void print() const {
affiche(cout);
}
};
extern ostream& operator<<(ostream& os, const TabAleat& tabA); |
TypeScript | UTF-8 | 1,354 | 2.6875 | 3 | [] | no_license |
import csv = require('csvtojson');
import PDFDocument = require('pdfkit');
import fs = require('fs');
const csvFilePath='items.csv';
async function test(){
return csv({noheader:true}).fromFile(csvFilePath);
}
async function test2(){
const jsonArray= await test();
var doc = new PDFDocument();
doc.pipe(fs.createWriteStream('output.pdf'));
let i;
for (i = 0; i < jsonArray.length; i += 5) {
if(i+5 < jsonArray.length){
doc.lineWidth(25);
doc.addPage({'layout': 'landscape'})
.fontSize(20)
.text(jsonArray[i].field1 + ' : ' + jsonArray[i].field2 , 50, 100)
.moveTo(50, 170)
.lineTo(500, 170)
.stroke()
.moveDown()
.moveDown()
.moveDown()
.moveDown()
.text(jsonArray[i+1].field1 + ' : ' + jsonArray[+2].field2)
.moveTo(50, 270)
.lineTo(500, 270)
.stroke()
.moveDown()
.moveDown()
.moveDown()
.moveDown()
.text(jsonArray[i+3].field1 + ' : ' + jsonArray[i+3].field2)
.moveTo(50, 360)
.lineTo(500, 360)
.stroke()
.moveDown()
.moveDown()
.moveDown()
.text(jsonArray[i+4].field1 + ' : ' + jsonArray[i+4].field2)
.moveTo(50, 380)
.lineTo(500, 380)
.stroke();
}
}
doc.end();
console.log(jsonArray);
}
// Async / await usage
test2(); |
PHP | UTF-8 | 4,864 | 2.53125 | 3 | [] | no_license | <?php
/**
* module Remote Session for Application
* @package Kutu
*
*/
class Pandamp_Session_SaveHandler_Remote implements Zend_Session_SaveHandler_Interface
{
/**
* Open Session - retrieve resources
*
* @param string $save_path
* @param string $name
*/
public function open($save_path, $name)
{
return true;
}
/**
* Close Session - free resources
*
*/
public function close()
{
return true;
}
/**
* Read session data
*
* @param string $id
*/
public function read($id)
{
$registry = Zend_Registry::getInstance();
$config = $registry->get('config');
$url = $config->session->config->remote->savehandler->url;
$client = new Zend_Http_Client();
$client->setUri($url."/read");
$client->setParameterPost(array(
'key' => $id
));
// RAISE TIMEOUT to 1000 seconds
$configs = array('timeout'=>1000);
$client->setConfig($configs);
if (!empty($_SERVER['HTTP_USER_AGENT'])) {
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$client->setHeaders("User-Agent: $userAgent");
}
// try
// {
$response = $client->request(Zend_Http_Client::POST);
// if($response->isError())
// {
// throw new Zend_Exception($response->isError());
// }
return $sResponse = $response->getBody();
// } catch (Exception $e) {
// /**
// * @see Zend_Auth_Adapter_Exception
// */
// require_once 'Zend/Auth/Adapter/Exception.php';
// throw new Zend_Exception($e->getMessage());
// }
}
/**
* Write Session - commit data to resource
*
* @param string $id
* @param mixed $data
*/
public function write($id, $data)
{
$registry = Zend_Registry::getInstance();
$config = $registry->get('config');
$url = $config->session->config->remote->savehandler->url;
$client = new Zend_Http_Client();
$client->setUri($url."/write");
$client->setParameterPost(array(
'key' => $id,
'value' => $data
));
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$client->setHeaders("User-Agent: $userAgent");
try
{
$response = $client->request(Zend_Http_Client::POST);
if($response->isError())
{
throw new Zend_Exception('SESSION Server reachable, but there was an error');
}
//return $sResponse = $response->getBody();
return true;
} catch (Exception $e) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Exception('Failed contacting SESSION Server');
}
}
/**
* Destroy Session - remove data from resource for
* given session id
*
* @param string $id
*/
public function destroy($id)
{
Zend_Loader::loadClass('Zend_Http_Client');
$registry = Zend_Registry::getInstance();
$config = $registry->get('config');
$url = $config->session->config->remote->savehandler->url;
$client = new Zend_Http_Client();
$client->setUri($url."/destroy");
$client->setParameterPost(array(
'key' => $id
));
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$client->setHeaders("User-Agent: $userAgent");
try
{
$response = $client->request(Zend_Http_Client::POST);
if($response->isError())
{
throw new Zend_Exception('SESSION Server reachable, but there was an error');
}
//return $sResponse = $response->getBody();
return true;
} catch (Exception $e) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Exception('Failed contacting SESSION Server');
}
}
/**
* Garbage Collection - remove old session data older
* than $maxlifetime (in seconds)
*
* @param int $maxlifetime
*/
public function gc($maxlifetime)
{
$registry = Zend_Registry::getInstance();
$config = $registry->get('config');
$url = $config->session->config->remote->savehandler->url;
$client = new Zend_Http_Client();
$client->setUri($url."/gc");
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$client->setHeaders("User-Agent: $userAgent");
try
{
$response = $client->request(Zend_Http_Client::POST);
if($response->isError())
{
throw new Zend_Exception('SESSION Server reachable, but there was an error');
}
//return $sResponse = $response->getBody();
return true;
} catch (Exception $e) {
/**
* @see Zend_Auth_Adapter_Exception
*/
require_once 'Zend/Auth/Adapter/Exception.php';
throw new Zend_Exception('Failed contacting SESSION Server');
}
}
}
?> |
C++ | UTF-8 | 402 | 3.296875 | 3 | [
"MIT"
] | permissive | // Copyright (c) Andreas Fertig.
// SPDX-License-Identifier: MIT
#include <type_traits>
template<typename T>
auto Calculate(T& t)
{
return t;
}
template<typename T>
auto SomeFunction(T& value)
{
// ...
auto x = Calculate(value);
static_assert(std::is_integral_v<decltype(x)>,
"Only integrals are allowed");
// ...
}
int main()
{
int i = 3;
SomeFunction(i);
} |
C# | UTF-8 | 6,992 | 2.5625 | 3 | [] | no_license | using DozorDatabaseLib;
using DozorDatabaseLib.DataClasses;
using DozorWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DozorWeb.Controllers
{
public class MessageController : Controller
{
public ActionResult MessageSending()
{
ViewBag.Message = "Страница для отправки сообщений.";
MessageSendingViewModel viewModel = new MessageSendingViewModel();
var grades = viewModel.GetAllGrades();
viewModel.Grades = grades;
if (grades.Count() > 0)
{
viewModel.Students = viewModel.GetStudents(Int32.Parse(grades.ElementAt(0).Value), -1);
viewModel.Subgroups = viewModel.GetSubgroupsByGrade(Int32.Parse(grades.ElementAt(0).Value));
}
return View(viewModel);
}
private IEnumerable<SelectListItem> GetGrades()
{
DozorDatabase dozorDatabase = DozorDatabase.Instance;
IEnumerable<Grade> grades = dozorDatabase.GetAllGrades();
List<GradeModel> gradesModels = new List<GradeModel>();
foreach (Grade grade in grades)
{
gradesModels.Add(new GradeModel(grade.ID, grade.GRADE));
}
ViewData["Grades"] = new SelectList(gradesModels,
"GradeId",
"Grade");
return new SelectList(gradesModels,
"GradeId",
"Grade");
}
public ActionResult GetStudents(int gradeId, int subgroupId)
{
DozorDatabase dozorDatabase = DozorDatabase.Instance;
IEnumerable<Student> students = new List<Student>();
if(subgroupId == -1)
{
students = dozorDatabase.GetStudentsByGrade(gradeId);
}
else
{
students = dozorDatabase.GetStudentsBySubgroup(subgroupId);
}
List<StudentModel> studentsModels = new List<StudentModel>();
studentsModels.Add(new StudentModel(-1, "Все ученики"));
foreach (Student student in students)
{
studentsModels.Add(new StudentModel(student.ID, student.FIRST_NAME + " " +
student.MIDDLE_NAME + " " +
student.LAST_NAME));
}
return Json(studentsModels, JsonRequestBehavior.AllowGet);
}
public ActionResult GetSubgroups(int gradeId)
{
DozorDatabase dozorDatabase = DozorDatabase.Instance;
IEnumerable<Subgroup> subgroups = dozorDatabase.GetSubgroupsByGradeId(gradeId);
List<SubgroupModel> subgroupsModels = new List<SubgroupModel>();
subgroupsModels.Add(new SubgroupModel(-1, "Все ученики"));
foreach (Subgroup subgroup in subgroups)
{
subgroupsModels.Add(new SubgroupModel(subgroup.ID, subgroup.SUBGROUP));
}
JsonResult jsonResult = new JsonResult();
jsonResult = Json(subgroupsModels, JsonRequestBehavior.AllowGet);
return jsonResult;
}
public JsonResult SendMessage(int gradeId, int subgroupId, int studentId, String messageText, DateTime messageExpirationDateTme, String selectedMessageShowDirection)
{
if (messageText == null || (gradeId == -1 && studentId == -1 && subgroupId == -1))
return Json("Выберите адресата сообщения", JsonRequestBehavior.AllowGet);
DozorDatabase dozorDatabase = DozorDatabase.Instance;
Boolean res = true;
if(messageExpirationDateTme == null)
{
messageExpirationDateTme = DateTime.Now;
}
messageExpirationDateTme = messageExpirationDateTme.AddHours(23 - messageExpirationDateTme.Hour);
messageExpirationDateTme = messageExpirationDateTme.AddMinutes(59 - messageExpirationDateTme.Minute);
int showDirection = 0;
if (selectedMessageShowDirection == "На входе")
showDirection = 1;
else if (selectedMessageShowDirection == "На выходе")
showDirection = 2;
if(studentId != -1)
{
Message message = new Message();
message.DATETIME = DateTime.Now;
message.MESSAGE_TEXT = messageText;
message.STUDENT_ID = studentId;
message.MESSAGE_PRIORITY = 2;
message.EXPIRATION_DATETIME = messageExpirationDateTme;
message.MESSAGE_SHOW_DIRECTION = showDirection;
res &= dozorDatabase.InsertMessage(message);
}
else if(subgroupId != -1)
{
IEnumerable<Student> students = dozorDatabase.GetStudentsBySubgroup(subgroupId);
foreach(Student student in students)
{
Message message = new Message();
message.DATETIME = DateTime.Now;
message.MESSAGE_TEXT = messageText;
message.STUDENT_ID = student.ID;
message.MESSAGE_PRIORITY = 1;
message.EXPIRATION_DATETIME = messageExpirationDateTme;
message.MESSAGE_SHOW_DIRECTION = showDirection;
res &= dozorDatabase.InsertMessage(message);
}
}
else if(gradeId != -1)
{
IEnumerable<Student> students = dozorDatabase.GetStudentsByGrade(gradeId);
foreach (Student student in students)
{
Grade grade = dozorDatabase.GetGradeById(gradeId);
if (grade == null)
return Json(false);
String gradeName = grade.GRADE;
Message message = new Message();
message.DATETIME = DateTime.Now;
message.MESSAGE_TEXT = messageText;
message.STUDENT_ID = student.ID;
message.MESSAGE_PRIORITY = 1;
message.EXPIRATION_DATETIME = messageExpirationDateTme;
message.MESSAGE_SHOW_DIRECTION = showDirection;
res &= dozorDatabase.InsertMessage(message);
}
}
if(res)
{
return Json("Сообщение успешно сохранено", JsonRequestBehavior.AllowGet);
}
return Json("Ошибка при выполнения запроса", JsonRequestBehavior.AllowGet);
}
}
} |
Java | UTF-8 | 7,664 | 2.03125 | 2 | [] | permissive | /* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.controller.edit.listing;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.cornell.mannlib.vedit.beans.ButtonForm;
import edu.cornell.mannlib.vedit.controller.BaseEditController;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyDao;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.utils.JSPPageHandler;
@WebServlet(name = "ObjectPropertyStatementListingController", urlPatterns = {"/listObjectPropertyStatements"} )
public class ObjectPropertyStatementListingController extends
BaseEditController {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
if (!isAuthorizedToDisplayPage(request, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) {
return;
}
VitroRequest vrequest = new VitroRequest(request);
boolean assertedStatementsOnly = false;
String assertParam = request.getParameter("assertedStmts");
if (assertParam!=null && assertParam.equalsIgnoreCase("true")) {
assertedStatementsOnly = true;
}
boolean showVClasses = false;
String displayParam = request.getParameter("showVClasses");
if (displayParam!=null && displayParam.equalsIgnoreCase("true")) {
showVClasses = true; // this will trigger a limitation to asserted vclasses, since we can't easily display all vclasses for an individual
}
int startAt=1;
String startAtParam = request.getParameter("startAt");
if (startAtParam!=null && startAtParam.trim().length()>0) {
try {
startAt = Integer.parseInt(startAtParam);
if (startAt<=0) {
startAt = 1;
}
} catch(NumberFormatException ex) {
throw new Error("Cannot interpret "+startAtParam+" as a number");
}
}
int endAt=50;
String endAtParam = request.getParameter("endAt");
if (endAtParam!=null && endAtParam.trim().length()>0) {
try {
endAt = Integer.parseInt(endAtParam);
if (endAt<=0) {
endAt=1;
}
if (endAt<startAt) {
int temp = startAt;
startAt = endAt;
endAt = temp;
}
} catch(NumberFormatException ex) {
throw new Error("Cannot interpret "+endAtParam+" as a number");
}
}
ArrayList<String> results = new ArrayList();
request.setAttribute("results",results);
results.add("XX");
results.add("subject");
if (showVClasses) results.add("type");
results.add("property");
results.add("object");
if (showVClasses) results.add("type");
ObjectPropertyStatementDao opsDao = null;
if (assertedStatementsOnly){ // get only asserted, not inferred, object property statements
opsDao = vrequest.getUnfilteredAssertionsWebappDaoFactory().getObjectPropertyStatementDao();
} else {
opsDao = vrequest.getUnfilteredWebappDaoFactory().getObjectPropertyStatementDao();
}
// get all object properties -- no concept of asserted vs. inferred object properties
ObjectPropertyDao opDao = vrequest.getUnfilteredWebappDaoFactory().getObjectPropertyDao();
IndividualDao iDao = null;
if (showVClasses) {
iDao = vrequest.getUnfilteredAssertionsWebappDaoFactory().getIndividualDao();
} else {
iDao = vrequest.getUnfilteredWebappDaoFactory().getIndividualDao();
}
String propURIStr = request.getParameter("propertyURI");
ObjectProperty op = opDao.getObjectPropertyByURI(propURIStr);
int count = 0;
for (ObjectPropertyStatement objectPropertyStatement : opsDao.getObjectPropertyStatements(op, startAt, endAt)) {
count++;
ObjectPropertyStatement ops = objectPropertyStatement;
Individual subj = iDao.getIndividualByURI(ops.getSubjectURI());
Individual obj = iDao.getIndividualByURI(ops.getObjectURI());
results.add("XX");
results.add(ListingControllerWebUtils.formatIndividualLink(subj));
if (showVClasses) {
try {
results.add(ListingControllerWebUtils.formatVClassLinks(subj.getVClasses(true)));
} catch (Exception e) {
results.add("?");
}
}
results.add(op.getDomainPublic());
results.add(ListingControllerWebUtils.formatIndividualLink(obj));
if (showVClasses) {
try {
results.add(ListingControllerWebUtils.formatVClassLinks(obj.getVClasses(true)));
} catch (Exception e) {
results.add("?");
}
}
}
if (count == 0) {
results.add("XX");
results.add("No statements found for property \""+op.getPickListName()+"\"");
results.add("");
results.add("");
if (showVClasses) {
results.add("");
results.add("");
}
}
if (showVClasses){
request.setAttribute("columncount",new Integer(6));
} else {
request.setAttribute("columncount",new Integer(4));
}
request.setAttribute("suppressquery","true");
request.setAttribute("title","Object Property Statements");
// new way of adding more than one button
List <ButtonForm> buttons = new ArrayList<ButtonForm>();
HashMap<String,String> newPropParams=new HashMap<String,String>();
newPropParams.put("controller", "Property");
ButtonForm newPropButton = new ButtonForm(Controllers.RETRY_URL,"buttonForm","Add new object property",newPropParams);
buttons.add(newPropButton);
HashMap<String,String> rootPropParams=new HashMap<String,String>();
rootPropParams.put("iffRoot", "true");
ButtonForm rootPropButton = new ButtonForm("showObjectPropertyHierarchy","buttonForm","root properties",rootPropParams);
buttons.add(rootPropButton);
request.setAttribute("topButtons", buttons);
/*
request.setAttribute("horizontalJspAddButtonUrl", Controllers.RETRY_URL);
request.setAttribute("horizontalJspAddButtonText", "Add new object property");
request.setAttribute("horizontalJspAddButtonControllerParam", "Property");
*/
try {
JSPPageHandler.renderBasicPage(request, response, Controllers.HORIZONTAL_JSP);
} catch (Throwable t) {
t.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// don't post to this controller
}
}
|
Java | WINDOWS-1250 | 935 | 3.015625 | 3 | [] | no_license | /* Soubor Kap14\02\vokno\Vokno.java
* Nastaven rozmr, polohy a titulku okna
*/
package vokno;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Vokno extends JFrame
{
public Vokno()
{
//enableEvents(AWTEvent.WINDOW_EVENT_MASK); /* JDK 1.0 */
Dimension obrazovka = Toolkit.getDefaultToolkit().getScreenSize();
Dimension rozm = new Dimension();
rozm.height = obrazovka.height/2;
rozm.width = obrazovka.width/2;
setSize(rozm);
setLocation(rozm.width/2,rozm.height/2);
setTitle("Nae prvn okno");
// Oeten konce programu - JDK 1.2+
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit(0); }
});
}
// JDK 1.0
/* protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
}
}
*/
} |
Java | UTF-8 | 370 | 2.203125 | 2 | [] | no_license | package AppointmentCalendar.model;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class CustomerList {
private static ObservableList<Customer> customerList = FXCollections.observableArrayList();
public static ObservableList<Customer> getCustomerList(){
return customerList;
}
}
|
Python | UTF-8 | 426 | 2.796875 | 3 | [] | no_license | #!/usr/bin/env python
# coding=utf-8
class People(object):
guoji = 'china'
def __init__(self):
self.name = '小明'
def get_name(self):
return self.name
@classmethod
def get_guoji(cls):
return cls.guoji
people01 = People()
print (people01.guoji)
people01.guoji = 'usa'
print (People.guoji)
print (people01.guoji)
del people01.guoji
del People.guoji
#print (people01.guoji)
|
TypeScript | UTF-8 | 2,064 | 2.625 | 3 | [] | no_license | import { Express } from 'express'
import { MongoClient, MongoClientOptions } from 'mongodb'
import { IS_TEST_ENV, MONGO_DB_NAME, MONGO_DB_URL } from '../consts'
import { createCollections } from './collections'
/**
* Defines a mongo client options object
*
* @see `MongoClientOptions`
*/
const mongoClientOptions: MongoClientOptions = {
useUnifiedTopology: true,
useNewUrlParser: true,
keepAlive: true,
connectTimeoutMS: 3600000,
socketTimeoutMS: 3600000
}
/**
* Defines a mongo client object
*
* @param MONGO_DB_URL is the database url to connect
* @param mongoClientOptions are options to configure mongo connection
*/
const mongoClient = new MongoClient( MONGO_DB_URL, mongoClientOptions )
// Event listening for database errors
mongoClient.on( 'error', ( error ) => {
console.error( 'Database error' )
console.error( error )
} )
// Event listening when database is connected
mongoClient.on( 'open', async () => {
console.debug( 'Database connected' )
// Create collection ( repository )
await createCollections( mongoClient.db( MONGO_DB_NAME ) )
} )
// Event listening when database is closed
mongoClient.on( 'close', ( client: MongoClient ) => {
if ( client && !client.isConnected() )
console.debug( 'Database disconnected.' )
} )
/**
* Try to connect to server using mongo client,
* load database and create/retrieve collections
*/
export const loadDatabase = async ( app: Express ) => {
try {
// If is already connect return
if ( mongoClient.isConnected() ) return
// Try to connect
await mongoClient.connect()
// emit event to init server
if ( !IS_TEST_ENV ) app.emit( 'ready' )
} catch ( error ) {
console.error( 'Não foi possível conectar com o banco de dados.' )
console.log()
console.log( MONGO_DB_URL )
console.log()
console.error( error )
}
}
/**
* Closes current mongo client connection to server
*/
export const closeConnection = () => {
mongoClient.close()
}
|
C# | UTF-8 | 5,778 | 3.21875 | 3 | [
"Apache-2.0"
] | permissive | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ScriptureParseApi.Models
{
public static class ScriptureOps
{
public static List<Scripture> ParseScriptureFromString(this string unparsedScriptures)
{
var scriptures = new List<Scripture>();
var scriptureSplits = unparsedScriptures.Replace(", ", ";").Replace(",", ";").Split(';');
foreach (var scripture in scriptureSplits)
{
var trimmedScripture = scripture.Trim();
var cleanedScripture = trimmedScripture.Split(',')[0];
var passage = new Scripture();
if (cleanedScripture.Replace("-", string.Empty).Replace(":", string.Empty).IsNumeric()) //This is either a dangling verse, or another chapter
{
if (!cleanedScripture.Contains(":"))//This is just a verse coupling
{
var chapter = (scriptures.Last().EndChapter != null) ? scriptures.Last().EndChapter : scriptures.Last().StartChapter;
if (cleanedScripture.Contains("-"))//This is a verse range
{
var verses = cleanedScripture.Split("-");
cleanedScripture = $"{scriptures.Last().Book} {chapter}:{verses[0]}-{chapter}:{verses[1]}";
}
else
{
if (scriptures.Last().StartVerse == null && scriptures.Last().EndVerse == null) //Previous entry was chapter sans verses
{
cleanedScripture = $"{scriptures.Last().Book} {cleanedScripture}";
}
else
{
cleanedScripture = $"{scriptures.Last().Book} {chapter}:{cleanedScripture}";
}
}
}
}
var bookName = GetBookName(cleanedScripture);
passage.Book = (bookName.NullOrEmpty()) ? scriptures.Last().Book : bookName;
cleanedScripture = cleanedScripture.Replace(passage.Book, "").Trim();
passage.StartChapter = GetStartChapter(cleanedScripture);
passage.StartVerse = GetStartVerse(cleanedScripture);
passage.EndChapter = GetEndChapter(cleanedScripture);
passage.EndVerse = GetEndVerse(cleanedScripture);
passage.EndChapter = (passage.EndChapter == passage.StartChapter) ? null : passage.EndChapter;
scriptures.Add(passage);
}
return scriptures;
}
private static string GetBookName(string scripture)
{
var spaces = scripture.Split(' ');
if (spaces.IsNumeric())
return null;
if (int.TryParse(spaces[0], out _)) //1 Cor; 1 Pet etc
{
return $"{spaces[0]} {spaces[1]}";
}
if (int.TryParse(spaces[0].Replace(":", "").Replace("-", ""), out _)) //Is this simply a second section of another book?
{
return string.Empty;
}
return spaces[0];
}
private static int GetStartChapter(string scripture)
{
int val = 0;
var scriptureRanges = scripture.Split('-'); //Break apart the range
var chapter = scriptureRanges[0].Split(":")[0]; //Grab the first part of the range (there will always be at least 1, and snag the chapter, even if there's no verses there will be a chapter
int.TryParse(chapter, out val);
return val;
}
private static int? GetStartVerse(string scripture)
{
int val;
var scriptureRanges = scripture.Split('-'); //Break apart the range
var chapterVerse = scriptureRanges[0].Split(':');
var verse = (chapterVerse.Length > 1) ? chapterVerse[1] : null;//If there is a verse, return it
int.TryParse(verse, out val);
return (verse == null || val == 0) ? null : (int?)val;
}
private static int? GetEndChapter(string scripture)
{
int val;
//Romans 5:8-6:1
var scriptureRanges = scripture.Split('-');
if (scriptureRanges.Length == 1) //No range, no end chapter
return null;
var endChapter = (scriptureRanges[1].Contains(':') || !scriptureRanges[0].Contains(':')) ? scriptureRanges[1].Split(':')[0] : null; //Either return the chapter for the second range, or the range is a verse, therefore the chapter is null / same as start chapter
int.TryParse(endChapter, out val);
return (endChapter == null || val == 0) ? null : (int?)val;
}
private static int? GetEndVerse(string scripture)
{
int val;
var scriptureRanges = scripture.Split('-');
if (scriptureRanges.Length == 1) //No range, no end verse
return null;
string endVerse = string.Empty;
if (scriptureRanges[1].Contains(':'))
{
endVerse = scriptureRanges[1].Split(':')[1];
}
else if (scriptureRanges[0].Contains(':'))
{
endVerse = scriptureRanges[1];
}
else
{
return null;
}
int.TryParse(endVerse, out val);
return (endVerse == null || val == 0) ? null : (int?)val;
}
}
}
|
C# | UTF-8 | 1,149 | 2.578125 | 3 | [] | no_license | using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace wedding_planner.Models
{
public class Wedding : BaseEntity
{
public Wedding()
{
Guests = new List<User>();
}
[Key]
public int ID { get; set; }
[Required(ErrorMessage="name of wedder one is required")]
[Display(Name="Wedder One")]
public string WedderOne { get; set; }
[Required(ErrorMessage="name of wedder two is required")]
[Display(Name="Wedder Two")]
public string WedderTwo { get; set; }
[Required(ErrorMessage="wedding date is required")]
[Display(Name="Wedding Date")]
[DataType(DataType.Date)]
public DateTime? WeddingDate { get; set; }
[Required(ErrorMessage="wedding address is required")]
[Display(Name="Wedding Address")]
public string WeddingAddress { get; set; }
public int UserID { get; set; }
public DateTime? CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
public ICollection<User> Guests { get; set; }
}
} |
C | UTF-8 | 534 | 2.859375 | 3 | [] | no_license | #include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
pid_t pid;
int main(int argc, char **argv){
int pid, status;
pid = fork();
switch(pid){
case -1:
exit(-1);
case 0:
if(argc > 1){
printf("Soy el hijo y tengo argumentos para hacer un berrinchito.\n");
sleep(1);
while(1)
printf("BUAA CUÑAA BUAA XO WAA XO BUAAA :'( :'( XO BUAA\t");
}
else{
printf("Soy el hijo y me porto bien\n");
exit(0);
}
default:
sleep(5);
kill(pid, 9);
}
exit(0);
} |
Python | UTF-8 | 1,544 | 2.875 | 3 | [] | no_license | # -*- coding: UTF-8 -*-
"""http处理模块
"""
import requests
import json
from . import BaseHandler
class HttpHandler(BaseHandler):
"""使用http上报机器信息数据
属性:
upload_url: 数据提交接口地址
"""
def __init__(self, config):
self.upload_url = config["uploadUrl"]
def handle_data(self, modules, data):
"""提交数据方法
参数:
modules:["cpu","net","average_load","disk","net"],
data:收集的机器信息
返回:
如果提交成功返回:{"status":0,"ret":""}
如果数据不正确返回:{"status":1, "ret":相应错误信息}
"""
post_data = {
"modules":modules,
"data":data
}
try:
request_result = requests.post(
self.upload_url,
data=json.dumps(post_data),
headers={'Content-type': 'application/json',
'Accept': 'text/plain'}
)
except requests.ConnectionError:
return {
"status":1,
"ret":"http Connection fail"
}
if request_result.status_code != 200:
return {
"status":1,
"ret":request_result.text
}
else:
return {
"status":0,
"ret":""
}
def destroy_connection(self):
"""在实例销毁时做连接关闭处理
"""
pass
|
C++ | UTF-8 | 1,003 | 2.625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <memory>
#define PARAMDEFINE(type , prefix,prarm_name) private:\
type m_##prefix##prarm_name;\
public:\
void Set_##prarm_name(type v_##prarm_name){m_##prefix##prarm_name = v_##prarm_name;};\
type Get_##prarm_name(){return m_##prefix##prarm_name;}
#define SharedPtr(ClassName) typedef shared_ptr<ClassName> p##ClassName;
#define DECLARE_SINGLEINSTANCE(ClassName) \
private:\
static ClassName* singleInstance;\
public:\
static ClassName* shareInstance()\
{\
if(NULL == singleInstance) singleInstance = new ClassName();\
return singleInstance;\
}\
private:\
class CGarbo\
{\
public:\
~CGarbo()\
{if( ClassName::singleInstance )delete ClassName::singleInstance;}\
};\
static CGarbo Garbo;
//
#define DEFINITION_SINGLEINSTANCE(ClassName)\
ClassName* ClassName::singleInstance = NULL; |
Java | UTF-8 | 3,060 | 2.75 | 3 | [] | no_license | package managers;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;
import router.Link;
import router.RouteTable;
import router.Router;
public class RoutersManager {
private static final String FILE_TO_READ = "./roteador.config";
private LinkedList<Router> routersList = new LinkedList<Router>();
private LinksManager linksManager;
public RoutersManager() {
linksManager = new LinksManager();
linksManager.readFile();
this.readFile();
}
public void readFile() {
try {
BufferedReader buffer = new BufferedReader(new FileReader(FILE_TO_READ));
String line = buffer.readLine();
StringTokenizer tokens;
while (line != null) {
if (!line.startsWith("#")) {
tokens = new StringTokenizer(line);
String routerId = tokens.nextToken(" ");
int port = Integer.parseInt(tokens.nextToken(" "));
InetAddress ipAddress = InetAddress.getByName(tokens.nextToken(" "));
routersList.add(new Router(routerId, ipAddress, port));
}
line = buffer.readLine();
}
for (int i = 1; i < routersList.size() + 1; i++) {
RouteTable routeTable = new RouteTable(Integer.toString(i), routersList.size());
routersList.get(i-1).setRouteTable(routeTable);
}
} catch (IOException ioe) {
System.out.println("Erro na leitura do arquivo roteador.config");
}
}
public Router getRouterById(String id) {
for (int i = 0; i < routersList.size(); i++) {
if (routersList.get(i).getId().equalsIgnoreCase(id)) return routersList.get(i);
}
return null;
}
public boolean contains(String id) {
for (int i = 0; i < routersList.size(); i++) {
if (routersList.get(i).getId().equalsIgnoreCase(id)) return true;
}
return false;
}
//Returns the # of routers
public int getSize() {
return routersList.size();
}
public String toString() {
String result = "";
for (int i = 0; i < routersList.size(); i++) {
result += routersList.get(i).toString()+"\n";
}
return result;
}
public HashMap<String, Integer> getNeighbors(String routerId) {
return linksManager.getNeighbors(routerId);
}
private String getRouterIdByPort(int port) {
for (int i = 0; i < routersList.size(); i++) {
if(routersList.get(i).getPort() == port) return routersList.get(i).getId();
}
return "";
}
public void setRouterOn(int port) {
for (int i = 0; i < routersList.size(); i++) {
if(routersList.get(i).getPort() == port) routersList.get(i).setOn(true);
}
}
public void setRouterOff(int port) {
for (int i = 0; i < routersList.size(); i++) {
if(routersList.get(i).getPort() == port) routersList.get(i).setOn(false);
}
}
public Integer getCost(String id, String id2) {
return linksManager.getCost(id, id2);
}
public LinkedList<Router> getRouterList() {
return this.routersList;
}
} |
Java | UTF-8 | 8,764 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | package cn.zhuhongqing.utils.date;
import java.util.Calendar;
import java.util.Locale;
import cn.zhuhongqing.utils.StringUtil;
import cn.zhuhongqing.utils.LocaleUtil;
import cn.zhuhongqing.utils.NumberUtil;
import cn.zhuhongqing.utils.TimeZoneUtil;
/**
* <b>GMT</b> specification, enhanced by some custom patterns. For more
* information see: <a href="http://en.wikipedia.org/wiki/GMT"></a>
*
* <p>
* Patterns list:
*
* <ul>
* <li>G - era</li>
* <li>yyyy + year</li>
* <li>yy + yy</li>
* <li>M + month (1 ~ 12)</li>
* <li>MM + month (01 ~ 12)</li>
* <li>MMM - month short name</li>
* <li>MMMM - month long name</li>
* <li>w - week of year (1 ~ 58)</li>
* <li>ww - week of year (01 ~ 58)</li>
* <li>W - week of month (1 ~ 5)</li>
* <li>F - week of month (1 ~ 5)</li>
* <li>D - day of year (1 ~ 366)</li>
* <li>DDD - day of year (001 ~ 366)</li>
* <li>d + day of month (1 ~ 31)</li>
* <li>dd + day of month (01 ~ 31)</li>
* <li>E - day of week (short name)</li>
* <li>EE - day of week (1 ~ 7)</li>
* <li>EEE - day of week short name</li>
* <li>EEEE - day of week long name</li>
* <li>a - AM/PM</li>
* <li>H + hour of day (0 ~ 23)</li>
* <li>HH + hour of day (00 ~ 23)</li>
* <li>K + hour of day (1 ~ 24)</li>
* <li>KK + hour of day (01 ~ 24)</li>
* <li>h - hour of AM/PM (0 ~ 11)</li>
* <li>H + hour of day (0 ~ 23)</li>
* <li>hh - hour of AM/PM (00 ~ 11)</li>
* <li>k - hour of AM/PM (1 ~ 12)</li>
* <li>kk - hour of AM/PM (01 ~ 12)</li>
* <li>m + minute (0 ~ 59)</li>
* <li>mm + minute (00 ~ 59)</li>
* <li>s + seconds (0 ~ 59)</li>
* <li>ss + seconds (00 ~ 59)</li>
* <li>S + milliseconds (0 ~ 999)</li>
* <li>SSS + milliseconds (000 ~ 999)</li>
* <li>z - timeZone short name</li>
* <li>zzzz - timeZone long name</li>
* <li>X + ("-/+hh" form) timeZone</li>
* <li>XX + ("-/+hhmm" form) timeZone</li>
* <li>XXX + ("-/+hh:mm" form) timeZone</li>
* <li>Z + ("-/+hhmm" form) timeZone</li>
* </ul>
*
* <p>
* Patterns noted with + sign are used both for conversion and parsing. All
* patterns are used for conversion.
*/
public class GenericDateFormat extends DateFormat {
private static final String[] patterns = new String[] { "G", // 0 - era
"yyyy", // 1 + year
"yy", // 2 - short year
"M", // 3 + month (1 ~ 12)
"MM", // 4 + month (01 ~ 12)
"MMM", // 5 - month short name
"MMMM", // 6 - month long name
"w", // 7 - week of year (1 ~ 58)
"ww", // 8 - week of year (01 ~ 58)
"W", // 9 - week of month (1 ~ 5)
"F", // 10 - week of month (1 ~ 5)
"D", // 11 - day of year (1 ~ 366)
"DDD", // 12 - day of year (001 ~ 366)
"d", // 13 + day of month (1 ~ 31)
"dd", // 14 + day of month (01 ~ 31)
"E", // 15 - day of week (short name)
"EE", // 16 - day of week (1 ~ 7)
"EEE", // 17 - day of week short name
"EEEE", // 18 - day of week long name
"a", // 19 - AM/PM
"H", // 20 + hour of day (0 ~ 23)
"HH", // 21 + hour of day (00 ~ 23)
"K", // 22 + hour of day (1 ~ 24)
"KK", // 23 + hour of day (01 ~ 24)
"h", // 24 - hour of AM/PM (0 ~ 11)
"hh", // 25 - hour of AM/PM (00 ~ 11)
"k", // 26 - hour of AM/PM (1 ~ 12)
"kk", // 27 - hour of AM/PM (01 ~ 12)
"m", // 28 + minute (0 ~ 59)
"mm", // 29 + minute (00 ~ 59)
"s", // 30 + seconds (0 ~ 59)
"ss", // 31 + seconds (00 ~ 59)
"S", // 32 + milliseconds (0 ~ 999)
"SSS", // 33 + milliseconds (000 ~ 999)
"z", // 34 - timeZone short name
"zzzz", // 35 - timeZone long name
"X", // 36 + ("-/+hh" form) timeZone
"XX", // 37 + ("-/+hhmm" form) timeZone
"XXX", // 38 + ("-/+hh:mm" form) timeZone
"Z", // 39 + ("-/+hhmm" form) timeZone
};
public GenericDateFormat() {
super(LocaleUtil.getLocale());
}
public GenericDateFormat(Locale locale) {
super(locale);
}
@Override
protected String convertPattern(int patternIndex, Calendar calendar) {
switch (patternIndex) {
case 0:
return LocaleUtil.getEra(calendar.get(Calendar.ERA), locale);
case 1:
return Integer.toString((calendar.get(Calendar.YEAR)));
case 2:
return StringUtil.forwardFilling4((calendar.get(Calendar.YEAR)))
.substring(2, 4);
case 3:
return Integer.toString(calendar.get(Calendar.MONTH) + 1);
case 4:
return StringUtil.forwardFilling2(calendar.get(Calendar.MONTH) + 1);
case 5:
return LocaleUtil.getShortMonthNames(calendar.get(Calendar.MONTH),
locale);
case 6:
return LocaleUtil.getMonthNames(calendar.get(Calendar.MONTH),
locale);
case 7:
return Integer.toString(calendar.get(Calendar.WEEK_OF_YEAR));
case 8:
return StringUtil.forwardFilling2(calendar
.get(Calendar.WEEK_OF_YEAR));
case 9:
return Integer.toString(calendar.get(Calendar.WEEK_OF_MONTH));
case 10:
return Integer.toString(calendar.get(Calendar.WEEK_OF_MONTH));
case 11:
return Integer.toString(calendar.get(Calendar.DAY_OF_YEAR));
case 12:
return StringUtil.forwardFilling3(calendar
.get(Calendar.DAY_OF_YEAR));
case 13:
return Integer.toString(calendar.get(Calendar.DAY_OF_MONTH));
case 14:
return StringUtil.forwardFilling2(calendar
.get(Calendar.DAY_OF_MONTH));
case 15:
return LocaleUtil.getShortWeekday(
calendar.get(Calendar.DAY_OF_WEEK), locale);
case 16:
return Integer.toString(calendar.get(Calendar.DAY_OF_WEEK));
case 17:
return LocaleUtil.getShortWeekday(
calendar.get(Calendar.DAY_OF_WEEK), locale);
case 18:
return LocaleUtil.getWeekday(calendar.get(Calendar.DAY_OF_WEEK),
locale);
case 19:
return LocaleUtil.getAmPm(calendar.get(Calendar.AM_PM), locale);
case 20:
return Integer.toString(calendar.get(Calendar.HOUR_OF_DAY));
case 21:
return StringUtil.forwardFilling2(calendar
.get(Calendar.HOUR_OF_DAY));
case 22:
return Integer.toString(calendar.get(Calendar.HOUR_OF_DAY) + 1);
case 23:
return StringUtil.forwardFilling2(calendar
.get(Calendar.HOUR_OF_DAY) + 1);
case 24:
return Integer.toString(calendar.get(Calendar.HOUR));
case 25:
return StringUtil.forwardFilling2(calendar.get(Calendar.HOUR));
case 26:
return Integer.toString(calendar.get(Calendar.HOUR) + 1);
case 27:
return StringUtil.forwardFilling2(calendar.get(Calendar.HOUR) + 1);
case 28:
return Integer.toString(calendar.get(Calendar.MINUTE));
case 29:
return StringUtil.forwardFilling2(calendar.get(Calendar.MINUTE));
case 30:
return Integer.toString(calendar.get(Calendar.SECOND));
case 31:
return StringUtil.forwardFilling2(calendar.get(Calendar.SECOND));
case 32:
return Integer.toString(calendar.get(Calendar.MILLISECOND));
case 33:
return StringUtil.forwardFilling3(calendar
.get(Calendar.MILLISECOND));
case 34:
return LocaleUtil.getShortTimeZone(calendar.getTime(),
calendar.getTimeZone(), locale);
case 35:
return LocaleUtil.getLongTimeZone(calendar.getTime(),
calendar.getTimeZone(), locale);
case 36:
return TimeZoneUtil.getRFC822TimeZoneShort(calendar);
case 37:
return TimeZoneUtil.getRFC822TimeZone(calendar);
case 38:
return TimeZoneUtil.getRFC822TimeZoneColon(calendar);
case 39:
return TimeZoneUtil.getRFC822TimeZone(calendar);
default:
return new String(patterns[patternIndex]);
}
}
@Override
protected void parseValue(int patternIndex, String value,
DateTimeZoneStamp destination) {
Integer v = null;
if (NumberUtil.isNumber(value)) {
v = Integer.parseInt(value);
}
switch (patternIndex) {
case 1:
destination.year = v;
break;
case 2:
destination.year = v;
break;
case 3:
destination.month = v - 1;
break;
case 4:
destination.month = v - 1;
break;
case 13:
destination.day = v;
break;
case 14:
destination.day = v;
break;
case 20:
destination.hour = v;
break;
case 21:
destination.hour = v;
break;
case 22:
destination.hour = v - 1;
break;
case 23:
destination.hour = v - 1;
break;
case 28:
destination.minute = v;
break;
case 29:
destination.minute = v;
break;
case 30:
destination.second = v;
break;
case 31:
destination.second = v;
break;
case 32:
destination.millisecond = v;
break;
case 33:
destination.millisecond = v;
break;
case 36:
destination.shortTimeZone = TimeZoneUtil.getGMTTimeZoneID(value);
break;
case 37:
destination.shortTimeZone = TimeZoneUtil.getGMTTimeZoneID(value);
break;
case 38:
destination.shortTimeZone = TimeZoneUtil.getGMTTimeZoneID(value);
break;
case 39:
destination.shortTimeZone = TimeZoneUtil.getGMTTimeZoneID(value);
break;
default:
throw new IllegalArgumentException("Invalid template: "
+ new String(patterns[patternIndex]));
}
}
@Override
protected String[] getPatterns() {
return patterns;
}
}
|
Python | UTF-8 | 9,806 | 3.078125 | 3 | [] | no_license | from tkinter import *
from tkinter import ttk
import sqlite3
# function to open the product page
# and configuration of the page.
def click():
global view
view=Toplevel()
view.title("Product Page")
view.iconbitmap("D:/200269_AyushaShrestha_FSMS-master/fashion.ico")
width = 1000
height = 550
screen_width = view.winfo_screenwidth()
screen_height = view.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
view.geometry("%dx%d+%d+%d" % (width, height, x, y))
view.resizable(0, 0)
view.config()
view.config(bg="#ffffff")
ViewPage()
# Display the selected row from table into entry box.
# Exception handling keywords handles the error that is to be occurred.
def displaySelectedRow(event):
database()
try:
global row_selection
row_selection = tree.selection()
for i in row_selection:
set_out_item = tree.item(i)
row_values = set_out_item['values']
global Product_ID
Product_ID = row_values[0]
Product_Name = row_values[1]
Product_Price = row_values[2]
Product_Quantity = row_values[3]
ProductTotalAmount = row_values[4]
id_ety.delete(0, 'end')
id_ety.insert(END, Product_ID)
name_ety.delete(0, 'end')
name_ety.insert(END, Product_Name)
price_ety.delete(0, 'end')
price_ety.insert(END, Product_Price)
quantity_ety.delete(0, 'end')
quantity_ety.insert(END, Product_Quantity)
total_amount_ety.delete(0, 'end')
total_amount_ety.insert(END, ProductTotalAmount)
except Exception as e:
print(e)
pass
# Gives the total calculation of the purchase automatically on entry box by clicking it.
def focusin_onclick(event):
database()
price_value = int(price_ety.get())
quantity_value = int(quantity_ety.get())
tot = price_value * quantity_value
if total_amount_ety.get() == "":
total_amount_ety.insert(0, tot)
total_amount_ety.config(fg='black')
print(type(tot))
# Function to create a frame
# and set the configuration
# and do the editing of products.
def ViewPage():
global tree
global product_id
global prd_name
global prd_price
global qnty
global totalAmount
global id_ety
global name_ety
global price_ety
global quantity_ety
global total_amount_ety
frame1=Frame(view,width=300,relief=SOLID,bd=1)
frame1.pack(side=TOP,fill=X)
label1=Label(frame1,text="View Products List", font=('arial', 15), width=300,bg="#eeeeee")
label1.pack(fill=X)
frame2=Frame(view, width=100,bg="#eeeeee")
frame2.pack(side=LEFT, fill=Y)
label2 = Label(frame2, text="Fashion Store", font=('calibre', 11),bg="#eeeeee")
label2.pack(side=TOP)
# Tree View represents the data hierarchically and gives an improved look to the data columns.
frame3 = Frame(view, width=600)
frame3.pack(side=RIGHT)
x = Scrollbar(frame3, orient=HORIZONTAL)
y = Scrollbar(frame3, orient=VERTICAL)
tree = ttk.Treeview(frame3, columns=(1, 2, 3, 4, 5), show="headings",
selectmode="extended", height=200, yscrollcommand=y.set, xscrollcommand=x.set)
y.config(command=tree.yview)
y.pack(side=RIGHT, fill=Y)
x.config(command=tree.xview)
x.pack(side=BOTTOM, fill=X)
tree.heading(1, text='Product id')
tree.heading(2, text='Product Name')
tree.heading(3, text='Sell Price')
tree.heading(4, text='Quantity')
tree.heading(5, text='Total Amount')
tree.column(1, stretch=YES, width=130)
tree.column(2, stretch=YES, width=230)
tree.column(3, stretch=YES, width=160)
tree.column(4, stretch=YES, width=150)
tree.column(5, stretch=YES, width=170)
tree.pack()
tree.bind('<Double-1>', displaySelectedRow)
product_id=StringVar()
prd_price=StringVar()
prd_name=StringVar()
qnty=StringVar()
totalAmount=StringVar()
id = Label(frame2, text="Product ID:",font=("Calibre",9),bg="#eeeeee")
id.pack(side=TOP,padx=10,anchor=W)
id_ety = Entry(frame2, text=product_id, bg="#ffffff")
id_ety.pack(side=TOP,padx=10,pady=1,fill=X)
name = Label(frame2, text="Product Name:", font=("Calibre", 9), bg="#eeeeee")
name.pack(side=TOP, padx=10, anchor=W)
name_ety = Entry(frame2, text=prd_name, bg="#ffffff")
name_ety.pack(side=TOP, padx=10, pady=1, fill=X)
price = Label(frame2, text="Product Price:", font=("Calibre", 9), bg="#eeeeee")
price.pack(side=TOP, padx=10, anchor=W)
price_ety = Entry(frame2, text=prd_price, bg="#ffffff")
price_ety.pack(side=TOP, padx=10, pady=1, fill=X)
quantity = Label(frame2, text="Quantity:", font=("Calibre", 9), bg="#eeeeee")
quantity.pack(side=TOP, padx=10, anchor=W)
quantity_ety = Entry(frame2, text=qnty, bg="#ffffff")
quantity_ety.pack(side=TOP, padx=10, pady=1, fill=X)
total_amount = Label(frame2, text="Total:", font=("Calibre", 9), bg="#eeeeee")
total_amount.pack(side=TOP, padx=10, anchor=W)
total_amount_ety = Entry(frame2, text=totalAmount, bg="#ffffff")
total_amount_ety.pack(side=TOP, padx=10, pady=1, fill=X)
total_amount_ety.insert(0, "")
total_amount_ety.bind("<FocusIn>", focusin_onclick)
v_btn = Button(frame2, text="Display", bg="#000000", fg="#ffffff", command=ShowItems)
v_btn.pack(side=TOP, padx=20, pady=5, fill=X)
s_btn = Button(frame2, text="Search", bg="#000000", fg="#ffffff", command=SearchItems)
s_btn.pack(side=TOP, padx=20, pady=5, fill=X)
add_btn = Button(frame2, text="Add", bg="#000000", fg="#ffffff", command=AddItems)
add_btn.pack(side=TOP, padx=20, pady=3, fill=X)
updt_btn = Button(frame2, text="Update", bg="#000000", fg="#ffffff", command=UpdateItems)
updt_btn.pack(side=TOP, padx=20, pady=3, fill=X)
dlt_btn = Button(frame2, text="Delete", bg="#000000", fg="#ffffff", command=DeleteItems)
dlt_btn.pack(side=TOP, padx=20, pady=3, fill=X)
total_bill_btn = Button(frame2, text="Total", bg="#000000", fg="#ffffff", command=TotalBill)
total_bill_btn.pack(side=TOP, padx=20, pady=3, fill=X)
# Create the database for the list of product details.
def database():
global product_db, c
product_db=sqlite3.connect("products.db")
c=product_db.cursor()
c.execute(
"CREATE TABLE IF NOT EXISTS ProductItem(id INTEGER PRIMARY KEY, name TEXT, price TEXT, quantity TEXT, total TEXT)")
product_db.commit()
product_db.close()
# Inserting Various Data.
def AddItems():
database()
product_db = sqlite3.connect("products.db")
c = product_db.cursor()
c.execute("INSERT INTO ProductItem (id, name, price, quantity,total) VALUES(?,?,?,?,?)",
(product_id.get(), prd_name.get(), prd_price.get(), qnty.get(), totalAmount.get()))
product_db.commit()
product_id.set("")
prd_name.set("")
prd_price.set("")
qnty.set("")
totalAmount.set("")
ShowItems()
c.close()
product_db.close()
# Clear the data that are in the table.
def clear():
global tree
for records in tree.get_children():
tree.delete(records)
# Display the items.
def ShowItems():
database()
tree.delete(*tree.get_children())
product_db=sqlite3.connect("products.db")
c=product_db.cursor()
c.execute("SELECT * FROM ProductItem")
rows = c.fetchall()
for row in rows:
tree.insert("", END, values=row)
product_db.close()
# Display particular data that we search for.
def SearchItems():
database()
clear()
product_db = sqlite3.connect("products.db")
c = product_db.cursor()
c.execute("SELECT * FROM ProductItem WHERE name=? OR price=? OR quantity=? OR total=?",
(prd_name.get(),prd_price.get(),qnty.get(),totalAmount.get()))
rows = c.fetchall()
for row in rows:
tree.insert("", END, values=row)
product_db.close()
# Modify the selected item in the table.
def UpdateItems():
database()
product_db=sqlite3.connect("products.db")
c=product_db.cursor()
c.execute("UPDATE ProductItem set id=?,name=?,price=?,quantity=?,total=? WHERE id=?",
(product_id.get(),prd_name.get(),prd_price.get(),qnty.get(),totalAmount.get(),product_id.get()))
product_db.commit()
c.close()
product_db.close()
# Delete the selected item from the table.
def DeleteItems():
database()
product_db = sqlite3.connect("products.db")
c = product_db.cursor()
c.execute('DELETE FROM ProductItem WHERE id = ?',(product_id.get(),))
product_db.commit()
c.close()
product_db.close()
# Display the total amount of particular item purchase.
def TotalAmount():
database()
product_db = sqlite3.connect("products.db")
c = product_db.cursor()
sum = c.execute("SELECT sum(total) FROM ProductItem")
total = sum.fetchall()
for x in total:
return(x[0])
product_db.commit()
product_db.close()
# Display the total bill of all the item purchase.
def TotalBill():
database()
product_db = sqlite3.connect("products.db")
c = product_db.execute('select sum(total) from ProductItem')
total = 0
for row in c:
total = row[0]
print(total)
tree.insert('', 'end', text="---------", values=('----------', '---------', '---------', 'Total = ', total))
product_db.commit()
# Create for counting the report of total products.
def count_products():
product_db = sqlite3.connect("products.db")
c = product_db.cursor()
count_prod =c.execute("SELECT COUNT(DISTINCT name) FROM ProductItem")
count_num = count_prod.fetchall()
for num in count_num:
return num
product_db.commit()
product_db.close() |
Shell | UTF-8 | 432 | 3.46875 | 3 | [] | no_license | #!/bin/sh
#
ws () {
local ws
ws=$(cat ~/.ws_list | xargs -n1 | fzy)
[ "$ws" = "" ] && return 1
ws=$(echo $ws | sed "s,^~,$HOME,")
cd $ws
}
register_ws () {
echo $(pwd | sed "s,^$HOME,~,") >> ~/.ws_list
}
unregister_ws () {
local ws
ws=$(cat ~/.ws_list | xargs -n1 | fzy)
[ "$ws" = "" ] && return 1
out=$(echo $ws | sed 's,/,\\/,g' | sed 's,^\~,\\~,')
sed -i -e "/$out/d" ~/.ws_list
echo "$ws is removed"
} |
Java | UTF-8 | 4,263 | 2.3125 | 2 | [] | no_license | package com.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dto.Address;
import com.dto.Cart;
import com.dto.Product;
import com.dto.User;
import com.service.AddressService;
import com.service.CartService;
import com.service.ProductService;
import com.service.UserService;
@Controller
public class SearchController {
@Autowired ProductService ps;
@Autowired AddressService addserv;
@Autowired UserService us;
@Autowired CartService cs;
@GetMapping(path="/autocomplete",
produces= {MediaType.APPLICATION_JSON})
@ResponseBody
public List<String> getWelcomeResponse(@RequestParam String keyword) {
System.out.println(keyword);
System.out.println("in!!");
List<Product>product=ps.searchApi(keyword);
List<String> list=new ArrayList<>();
for(Product s: product ) {
list.add(s.getName());
}
return list; //data which has to be returned
}
@GetMapping(path="/fetchAddress",
produces= {MediaType.APPLICATION_JSON})
@ResponseBody
public Address fetchAddress(@RequestParam int id) {
System.out.println(id);
System.out.println("in!!");
Address address=addserv.getAddresstById(id);
System.out.println("address fetch"+address.toString());
// String gs =new Gson().toJson(address);
return address; //data which has to be returned
}
@SuppressWarnings("unchecked")
@PostMapping(path="/updateCart",
produces= {MediaType.TEXT_PLAIN})
@ResponseBody
public String updateCart(HttpSession session,
@RequestParam("id") int id) {
System.out.println("id "+id);
Product p = ps.getProductById(id);
User user = (User) session.getAttribute("user");
System.out.println(p);
if(user==null) {
Map<Product,Integer> cart= (Map<Product, Integer>) session.getAttribute("cart");
session.removeAttribute("user");
if (cart.containsKey(p)) {
cart.put(p, cart.get(p) - 1);
} else {
cart.put(p, 1);
}
}else {
Boolean isNewCart = false;
Cart c1=user.getCart();
if (c1 == null) {
c1 = new Cart();
isNewCart=true;
user.setCart(c1);
}
Map<Product, Integer> cartList = c1.getCartList();
if (cartList.containsKey(p)) {
cartList.put(p, cartList.get(p) - 1);
} else {
cartList.put(p, 1);
}
if(isNewCart)
{ //cs.updateProduct(c1);
user.setCart(c1);
user.setConfirmPassword(user.getPassword());
us.updateUser(user);
}
else
{
cs.updateProduct(c1);
}
session.setAttribute("cartSize", c1.getCartList().size());
}
session.setAttribute("addMsg", "item added to cart");
return "ok";
}
@SuppressWarnings("unchecked")
@PostMapping(path="/updateAddCart",
produces= {MediaType.TEXT_PLAIN})
@ResponseBody
public String updateAddCart(HttpSession session,
@RequestParam("id") int id) {
System.out.println("id "+id);
Product p = ps.getProductById(id);
User user = (User) session.getAttribute("user");
System.out.println(p);
if(user==null) {
Map<Product,Integer> cart= (Map<Product, Integer>) session.getAttribute("cart");
session.removeAttribute("user");
if (cart.containsKey(p)) {
cart.put(p, cart.get(p) + 1);
} else {
cart.put(p, 1);
}
}else {
Boolean isNewCart = false;
Cart c1=user.getCart();
if (c1 == null) {
c1 = new Cart();
isNewCart=true;
user.setCart(c1);
}
Map<Product, Integer> cartList = c1.getCartList();
if (cartList.containsKey(p)) {
cartList.put(p, cartList.get(p) + 1);
} else {
cartList.put(p, 1);
}
if(isNewCart)
{ //cs.updateProduct(c1);
user.setCart(c1);
user.setConfirmPassword(user.getPassword());
us.updateUser(user);
}
else
{
cs.updateProduct(c1);
}
session.setAttribute("cartSize", c1.getCartList().size());
}
session.setAttribute("addMsg", "item added to cart");
return "ok";
}
}
|
C | UTF-8 | 171 | 3.15625 | 3 | [] | no_license | #include <unistd.h>
int main(void)
{
int a;
int b;
a = '0';
b = '9';
while(b >= a)
{
write(1, &b, 1);
b -= 1; // or b--
}
write(1, "\n", 1);
}
|
Java | UTF-8 | 375 | 1.945313 | 2 | [
"Apache-2.0"
] | permissive | package com.wanhuiyuan.szoa.bean;
public class MeetingVisit {
private String meetingId = "";
private String perId = "";
public String getMeetingId() {
return meetingId;
}
public void setMeetingId(String meetingId) {
this.meetingId = meetingId;
}
public String getPerId() {
return perId;
}
public void setPerId(String perId) {
this.perId = perId;
}
}
|
Java | UTF-8 | 920 | 2.8125 | 3 | [] | no_license | package Models;
public class Product {
private int codigo;
private String descricao;
private Double valorUnitario;
private AdditionalProduct marcaProduto;
public Product(int codigo, String descricao, Double valorUnitario) {
this.codigo = codigo;
this.descricao = descricao;
this.valorUnitario = valorUnitario;
}
public int getCodigo() {
return codigo;
}
public String getDescricao() {
return descricao;
}
public Double getValorUnitario() {
return valorUnitario;
}
public AdditionalProduct getMarcaProduto() {
return marcaProduto;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public void setValorUnitario(double valorUnitario) {
this.valorUnitario = valorUnitario;
}
public void setMarcaProduto(AdditionalProduct marcaProduto) {
this.marcaProduto = marcaProduto;
}
} |
Java | UTF-8 | 1,513 | 3.0625 | 3 | [
"Apache-2.0"
] | permissive | package com.noi.utility.bean;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public class BeanSerializer {
/*
* This class will encode/serialize Beans into XML
* and decode xml back into Objects
*/
private BeanSerializer() {
}
/*
* Make sure the @param obj follows the JavaBean pattern correctly
*/
public static synchronized String encodeObject(Object obj) {
if(obj == null) return null;
//without this, ClassNotFoundException gets thrown for some reason
Thread.currentThread().setContextClassLoader(BeanSerializer.class.getClassLoader());
ByteArrayOutputStream io = new ByteArrayOutputStream();
XMLEncoder e = new XMLEncoder(
new BufferedOutputStream(io));
e.writeObject(obj);
e.close();
return new String(io.toByteArray());
}
public static synchronized Object decodeObject(String encStr) {
if(encStr == null) return null;
//without this, ClassNotFoundException gets thrown for some reason
Thread.currentThread().setContextClassLoader(BeanSerializer.class.getClassLoader());
XMLDecoder d = new XMLDecoder(
new BufferedInputStream(
new ByteArrayInputStream(
encStr.getBytes())));
Object result = d.readObject();
d.close();
return result;
}
}
|
Java | UTF-8 | 3,572 | 2.34375 | 2 | [
"Apache-2.0"
] | permissive | package com.mmrx.yunliao.model.bean.sms;/**
* Created by mmrx on 16/3/8.
*/
import android.database.Cursor;
import com.mmrx.yunliao.presenter.util.MiddlewareProxy;
/**
* 创建人: mmrx
* 时间: 16/3/8下午12:51
* 描述: sms数据库表实体对象
*/
public class SmsBean {
private int _id;//短信序号
private int thread_id;//对话的序号,与同一手机号互发短信,其序号是相同的
private String address;//发件人地址,即手机号
private int person;//发件人,通讯录中的id,陌生人则为null
private long date_long;//日期,long型
private String date_str;//日期,带格式的
private long date_sent_long;//发送日期,long型
private String date_sent_str;//发送日期,格式
private boolean read;//是否阅读,0未读,1已读,这里用boolean来表示
private int status;//短信状态,-1接收,0 complete,64 pending 32
private String subject;//题目
/*type
ALL = 0;
INBOX = 1;
SENT = 2;
DRAFT = 3;
OUTBOX = 4;
FAILED = 5;
QUEUED = 6; */
private int type;
private String body;//短信内容
private int locked;//是否上锁,默认为0
public SmsBean() {
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public int getThread_id() {
return thread_id;
}
public void setThread_id(int thread_id) {
this.thread_id = thread_id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getPerson() {
return person;
}
public void setPerson(int person) {
this.person = person;
}
public long getDate_long() {
return date_long;
}
public void setDate_long(long date_long) {
this.date_long = date_long;
this.date_str = MiddlewareProxy.getInstance().dateFormat(this.date_long);
}
public String getDate_str() {
return date_str;
}
public void setDate_str(String date_str) {
this.date_str = date_str;
}
public long getDate_sent_long() {
return date_sent_long;
}
public void setDate_sent_long(long date_sent_long) {
this.date_sent_long = date_sent_long;
this.date_sent_str = MiddlewareProxy.getInstance().dateFormat(this.date_sent_long);
}
public String getDate_sent_str() {
return date_sent_str;
}
public void setDate_sent_str(String date_sent_str) {
this.date_sent_str = date_sent_str;
}
public boolean isRead() {
return read;
}
public void setRead(boolean read) {
this.read = read;
}
public void setRead(int read) {
this.read = read==1;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public int getLocked() {
return locked;
}
public void setLocked(int locked) {
this.locked = locked;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
|
Java | UTF-8 | 2,786 | 1.835938 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2019 NexCloud Co.,Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nexcloud.api.service.host;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nexcloud.tsdb.adapter.manager.HostDiskAdapterManager;
@Service
public class HostDiskService {
@Autowired private HostDiskAdapterManager adapterManager;
public String getDiskFreeByte(String clusterId, String hostIp, String mountName, String startTime, String time, int limit) {
return adapterManager.adapter().getDiskFreeByte(clusterId, hostIp, mountName, startTime, time, limit);
}
public String getDiskUsagePercent(String clusterId, String hostIp, String mountName, String startTime, String time, int limit) {
return adapterManager.adapter().getDiskUsagePercent(clusterId, hostIp, mountName, startTime, time, limit);
}
public String getDiskReadbyte(String clusterId, String hostIp, String mountName, String startTime, String time, int limit) {
return adapterManager.adapter().getDiskReadbyte(clusterId, hostIp, mountName, startTime, time, limit);
}
public String getDiskWritebyte(String clusterId, String hostIp, String mountName, String startTime, String time, int limit) {
return adapterManager.adapter().getDiskWritebyte(clusterId, hostIp, mountName, startTime, time, limit);
}
public String getDiskTotal(String clusterId, String hostIp, String mountName, String startTime, String time, int limit) {
return adapterManager.adapter().getDiskTotal(clusterId, hostIp, mountName, startTime, time, limit);
}
public String getDiskUsedbyte(String clusterId, String hostIp, String mountName, String startTime, String time, int limit) {
return adapterManager.adapter().getDiskUsedbyte(clusterId, hostIp, mountName, startTime, time, limit);
}
public String getDiskReads(String clusterId, String hostIp, String mountName, String startTime, String time, int limit) {
return adapterManager.adapter().getDiskReads(clusterId, hostIp, mountName, startTime, time, limit);
}
public String getDiskWrites(String clusterId, String hostIp, String mountName, String startTime, String time, int limit) {
return adapterManager.adapter().getDiskWrites(clusterId, hostIp, mountName, startTime, time, limit);
}
}
|
Markdown | UTF-8 | 7,716 | 2.8125 | 3 | [] | no_license | ---
title: Iris Choc/Kailh Low-Profile
---
This guide applies to just the Iris PCB for Kailh Low-Profile switches, where the order of the build steps are slightly different. If you're looking for the guide to the normal PCB, see [Iris Build Guide](iris-rev2-build-guide.md)
Note that some pictures from the normal Iris PCB have been used here, main thing to ignore from those pictures is the diode orientation.
## Build Steps
Here's a summary of the build steps:
1. Prepare components
2. Solder components
1. Solder diodes
2. Solder push button and TRRS jacks
3. Solder I2C resistors \(optional\)
4. Solder LED components \(MOSFET and resistors\) \(optional\)
5. Solder Pro Micro header pins
3. Solder LEDs \(optional\)
4. Insert all switches into plate
5. Solder switches
6. Flash Pro Micros
7. Solder Pro Micros
8. Solder RGB strip \(optional\)
## Prepare components

Bending the diodes. Here, I'm just bending it around my finger

Another way to do it, resistors shown here

Strip of diodes bent

Ripping off the paper holding all the resistors together. Grip the diodes tightly so they don't bend as you're ripping the paper off.

All separated from the paper
## Solder Components
The diodes, resistors, MOSFETs, push buttons, TRRS jacks, and Pro Micro header pins can be soldered in any order.
### Solder diodes
On the bottom side of the PCB, insert diodes with the black line towards the bottom. Square = Black line. The black line will point towards the top on these PCBs. All of the diodes are oriented vertically on the PCB:
Some people stick the diodes on the top side of the PCB, which **is not** recommended, because you can't replace them once everything is assembled using that method.
Bend the legs out to hold the diodes in place for when you solder them in:
### Solder reset push buttons and TRRS jacks
Add the TRRS jacks and reset switches:
Make sure you clip down the leads for the jacks and reset switches after soldering them in, since there is not that much clearance between the top of the PCB and the switch plate. Failing to do this can make the pins touch the switch plate.
### Solder I2C resistors \(optional\)
The default firmware for the Iris uses serial communication between the two halves using a single pin of the TRRS cable. Serial communication only allow for communication between two parts, which is fine for almost all builds.
However, in the future, there might be additional parts that you can add, like a numpad, OLED screen, etc. To support this, the communication protocol would need to be switched over I2C, which can support multiple devices. To add support for I2C, all you need to do is add the 2 4.7kΩ resistors to one of the halves \(other half does not need them\). Also, it doesn't hurt to add these resistors if using serial communication.
tl;dr: Adding this is optional, but you might as well do it as it's only 2 more components to solder.
Add the 2 4.7kΩ resistors for I2C on only one half (I normally do this on the master/left half). Left half shown here:
### Solder LED support components \(optional\)
Add a 4.7kΩ resistor for LED support in the R3 slot:
Add 470Ω resistors for LEDs. Resistors don't have polarity, so orientation doesn't matter. All of the resistor slots are oriented horizontally.
Right PCB:
To add the MOSFET, tin one of the pins on the PCB first:
Hold the MOSFET with a pair of tweezers and align it over the footprint. Then solder the first pin:

Once you're satisfied with the alignment, solder the other 2 pins:
Repeat the MOSFET installation process on the other PCB:
### Solder Pro Micro header pins
:::caution Do not use Peel-A-Way sockets with this PCB if socketing the Pro Micro
Due to the small clearance between the switch plate and PCB, do not use Peel-A-Way sockets to socket the Pro Micro, as the Peel-A-Way sockets will come in contact with the top plate. Using other types of sockets are fine.
:::
Install the header pins for the Pro Micro on the underside of the PCB (left PCB shown). You can use some tape to hold the header pins in place while soldering. Solder one pin on and re-adjust/re-solder as needed before doing the rest of the row:
Completed left PCB:
Right PCB shown:
Prying off the plastic parts of the header pins to made the Pro Micro sit more flush with the PCB is suggested if you are up for it. An added benefit of this is that the Micro USB port for the left half is sandwiched between the Iris PCB and the Pro Micro PCB, making it less likely to be ripped off.
## Solder LEDs \(optional\)
Install the LEDs. Longer leg is the anode and goes with the circular pad marked with \+. The shorter leg is the cathode and goes with the square pad marked with \-:
Trim down the switch pins, LED pins, and resistor pins that the Pro Micro will sit on top of with a flush cutter:
## Insert switches into plate
Due to the tight fit of the Choc switches into the switch plate, insert all of the switches into the switch plate before soldering them in. If you don't do this, you may have trouble getting the switches in the middle of the plate to clip in properly if you've done the outer switches first.
## Solder switches
Fit the switch plate with all the switches onto the PCB, making sure that none of the switch pins are bent prior to doing so. Also make sure the LEDs don't interfere with the actuation of each switch. Solder all of the switches in.
## Flash Pro Micros

The last thing to install is the Pro Micros. Before soldering them to the board, it is highly recommended to flash them first, in case one or both of them are defective.
Refer to the [Flashing Firmware](flashing-firmware.md) Guide for steps on performing a flash to test the Pro Micro controllers.
## Solder Pro Micros
If using a bottom plate that conducts electricity, like a stainless steel or aluminum plate, add Kapton or electric tape on top of the TRRS jack. Also put some down where the Pro Micro will be:

Set the Pro Micro through the pins, making sure RAW and TX0 are aligned properly with the markings on the PCB. The orientation on both PCBs is different. (Left half shown here):

:::info MYTH: Keys will be reversed if the Pro Micro is reversed
TRUTH: **This is totally not the case, so pay attention!** Soldering the Pro Micro on backwards will short VCC and Reset together, preventing you from flashing. Even if flashed beforehand, it will do nothing meaningful in this orientation.
:::
Right half:
Left PCB on the left, right PCB on the right:
## Solder RGB strip \(optional\)
Refer to the [Adding RGB Underglow](adding-rgb-underglow.md) Guide for steps to install the RGB light strip.
|
JavaScript | UTF-8 | 1,654 | 2.6875 | 3 | [] | no_license | import { StaticEntity } from "./static-entity";
import { Assets } from "../../gfx/assets";
export default class Machine extends StaticEntity {
constructor(handler, x, y){
super(handler, x, y);
this.type = 'm';
this.keys = [];
// this.keys = ['test', 'test', 'test', 'test'];
this.assets.p = Assets.getAssets('all').anim['p_mright'];
this.assets.g = Assets.getAssets('all').anim['g_mright'];
this.assets.y = Assets.getAssets('all').anim['y_mright'];
this.assets.b = Assets.getAssets('all').anim['b_mright'];
/* COLLISION BOUNDS */
this.b.x = -1;
this.b.y = 0;
this.b.s = 130; // size
/* COLLISION BOUNDS */
}
tick() {
if (this.keys.length > 3) {
ANIMATION_TIMER.stop = true;
this.handler.getWorld().machineFilled = true;
}
}
render(g) {
let frame = this.myFrame();
g.myDrawImage(this.assets.p[frame](), this.x, this.y, TILE_SIZE, TILE_SIZE);
g.myDrawImage(this.assets.g[frame](), this.x + TILE_SIZE, this.y, TILE_SIZE, TILE_SIZE);
g.myDrawImage(this.assets.y[frame](), this.x + TILE_SIZE, this.y + TILE_SIZE, TILE_SIZE, TILE_SIZE);
g.myDrawImage(this.assets.b[frame](), this.x, this.y + TILE_SIZE, TILE_SIZE, TILE_SIZE);
// ****** DRAW BOUNDING BOX DON'T DELETE!!
// g.fillStyle = 'orange';
// g.fillRect(this.b.x + this.x, this.b.y + this.y, this.b.s, this.b.s);
// ****** DRAW BOUNDING BOX DON'T DELETE!!
}
addKey(item) {
this.keys.push(item);
ANIMATION_TIMER.keyAdded();
}
} |
C | UTF-8 | 239 | 3.671875 | 4 | [] | no_license | #include <stdio.h>
int main()
{
char str[50];
printf("Enter a string : ");
gets(str); //as you can see the gets is like scanf. often times, it's used in strings.
printf("You entered: %s", str);
return(0);
}
|
C++ | UTF-8 | 3,077 | 2.671875 | 3 | [
"MIT"
] | permissive |
#pragma once
#include <sstream>
#ifdef _WIN32
#include <sys/timeb.h>
#else
#include <time.h>
#endif
#ifdef _MSC_VER
#define LN_FUNC_MACRO __FUNCTION__
#else
#define LN_FUNC_MACRO __PRETTY_FUNCTION__
#endif
#define LN_LOG(level) !(::ln::detail::Logger::getInstance() && ::ln::detail::Logger::getInstance()->CheckLevel(level)) ? (void)0 : (*::ln::detail::Logger::getInstance()) += ::ln::detail::LogRecord(level, __FILE__, LN_FUNC_MACRO, __LINE__)
#define LN_LOG_FATAL LN_LOG(::ln::LogLevel::Fatal)
#define LN_LOG_ERROR LN_LOG(::ln::LogLevel::Error)
#define LN_LOG_WARNING LN_LOG(::ln::LogLevel::Warning)
#define LN_LOG_INFO LN_LOG(::ln::LogLevel::Info)
#define LN_LOG_DEBUG LN_LOG(::ln::LogLevel::Debug)
#define LN_LOG_VERBOSE LN_LOG(::ln::LogLevel::Verbose)
LN_NAMESPACE_BEGIN
/** ログの通知レベル */
enum class LogLevel
{
Fatal,
Error,
Warning,
Info,
Debug,
Verbose,
};
/** ログのユーティリティです。*/
class Logger
{
public:
/** 通知レベル */
enum class Level
{
Info = 0, /**< 情報 */
Warning , /**< 警告 */
Error, /**< エラー */
};
public:
/**
@brief ログ機能を初期化し、ログファイルを新規作成します。
@param[in] filePath : ログファイルのパス
@return true=成功 / false=失敗
*/
static bool initialize(const Char* filePath) throw();
/**
@brief 通知レベルを指定して書式指定メッセージを書き込みます。
@param[in] level : 通知レベル (指定しない場合は Level_Info)
@details ログ機能が初期化されていない場合は何もしません。
*/
static void writeLine(Level severity, const char* format, ...) throw();
static void writeLine(Level severity, const wchar_t* format, ...) throw(); /**< @overload WriteLine */
static void writeLine(const char* format, ...) throw(); /**< @overload WriteLine */
static void writeLine(const wchar_t* format, ...) throw(); /**< @overload WriteLine */
};
namespace detail {
#ifdef _WIN32
typedef timeb LogTime;
#else
struct LogTime
{
time_t time;
unsigned short millitm;
};
#endif
class LogRecord
{
public:
LogRecord(LogLevel level, const char* file, const char* func, int line);
const LogTime& getTime() const { return m_time; }
LogLevel GetLevel() const { return m_level; }
const char* getMessage() const;
const char* GetFile() const { return m_file; }
const char* GetFunc() const { return m_func; }
int GetLine() const { return m_line; }
unsigned int getThreadId() const { return m_threadId; }
LogRecord& operator<<(const wchar_t* str);
template<typename T>
LogRecord& operator<<(const T& data)
{
m_message << data;
return *this;
}
private:
LogTime m_time;
LogLevel m_level;
const char* m_file;
const char* m_func;
int m_line;
unsigned int m_threadId;
std::stringstream m_message;
mutable std::string m_messageStr;
};
class Logger
{
public:
static Logger* getInstance();
bool CheckLevel(LogLevel level);
void operator+=(const LogRecord& record);
};
} // namespace detail
LN_NAMESPACE_END
|
Python | UTF-8 | 1,141 | 3.21875 | 3 | [] | no_license | """
@author: Shaun
"""
import constants
def get_movie_url(id):
return constants.TMDB_MOVIE_URL.format(movie_id = id)
def get_company_url(id):
return constants.TMDB_COMPANY_URL.format(company_id = id)
def trim_dict(dict, keys, list_keys):
"""
Make dict smaller - as we need only some details
"""
if keys is None or dict is None:
return dict
return_list = False
if len(keys) == 1:
return dict[keys[0]]
trimmed_dict = {}
for key in keys:
val = None
if key in dict:
val = dict[key]
if list_keys is not None and key in list_keys and isinstance(val, list):
val = trim_dicts_in_lists(val, list_keys[key])
trimmed_dict[key] = val
return trimmed_dict
def trim_dicts_in_lists(list, keys):
"""
Make some lists in the dictionary smaller (eg: we dont need logo path of a production company)
"""
if list == None:
return None
trimmed_list = []
for elem in list:
if isinstance(elem, dict):
trimmed_list.append(trim_dict(elem, keys, None))
return trimmed_list
|
JavaScript | UTF-8 | 1,108 | 2.828125 | 3 | [] | no_license | define(["./exceptions"],
function (Exceptions) {
var inherit = function(currentClass, parentClassOrObject){
if (parentClassOrObject.constructor == Function) {
//Normal Inheritance
currentClass.prototype = new parentClassOrObject;
currentClass.prototype.constructor = currentClass;
currentClass.prototype.parent = parentClassOrObject.prototype;
}
else {
//Pure Virtual Inheritance
currentClass.prototype = parentClassOrObject;
currentClass.prototype.constructor = currentClass;
currentClass.prototype.parent = parentClassOrObject;
}
return currentClass;
}
var is = function(currentClass, parentClassOrObject){
var proto = undefined;
if (parentClassOrObject.constructor == Function) {
proto = parentClassOrObject.prototype
}
else {
proto = parentClassOrObject;
}
while(proto){
if(currentClass.prototype == proto){
return;
}
proto = proto.prototype;
}
throw Exceptions.TypeMismatchException
}
return {
inherit : inherit,
is : is
}
}); |
JavaScript | UTF-8 | 406 | 2.921875 | 3 | [] | no_license | const nightBtn = document.querySelector('.night-mode-btn');
const body = document.querySelector('body');
nightBtn.addEventListener('click', function() {
if(body.className === 'night') {
body.className = '';
nightBtn.textContent = 'Включить ночной режим';
} else {
body.className = 'night';
nightBtn.textContent = 'Выключить ночной режим';
}
}); |
JavaScript | UTF-8 | 1,082 | 3.640625 | 4 | [] | no_license | // var d = new Date();
// d.toLocaleTimeString();
// console.log(d);
// t = d.toLocaleString('en-US', {timeZone: 'America/New_York'});
// console.log(t);
const hourHand = document.getElementById("h");
const minuteHand = document.getElementById("m");
const secondHand = document.getElementById("s");
class Clock{
constructor(country){
this.country = country;
}
setClock() {
const currentDate = this.country;
const secondsRatio = currentDate.getSeconds() / 60;
const minutesRatio = (secondsRatio + currentDate.getMinutes()) / 60;
const hoursRatio = currentDate.getHours() / 12;
setRotation(secondHand, secondsRatio);
setRotation(minuteHand, minutesRatio);
setRotation(hourHand, hoursRatio);
}
}
function setRotation(element, rotationRatio) {
element.style.setProperty('--rotation', rotationRatio * 360);
}
let seoul = new Date(1489199400000);
let ny = new Date(1489199400000 - (840 * 60 * 1000));
console.log(seoul.getHours());
let clock = new Clock(seoul);
setInterval(clock.setClock, 1000); |
Python | UTF-8 | 185 | 3.03125 | 3 | [] | no_license | import myclass
a1=input('enter num1 :')
b1=input('enter num2 :')
print('Add :',myclass.myclass.add(a1,b1))
mul = myclass.myclass.mul(a1,b1)
print('multiplication :',mul) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.