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
| 3,122
| 2.34375
| 2
|
[] |
no_license
|
package com.hzp.client;
import com.hzp.RegisterCenter.RegisterCenter;
import com.hzp.server.RpcRequest;
import com.hzp.server.RpcResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
/**
* Created by huzhipeng on 2018/4/1.
*/
@Component
public class RpcProxy {
private String serverAddress;
private ServerDiscovery serverDiscovery = new ServerDiscovery();
//
public <T> T create(final Class<?> interfaceClass) {
System.out.println("创建代理类对象");
//通过代理返回实现类
return (T)Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
new Class<?>[]{interfaceClass},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
RpcRequest request = new RpcRequest(); // 创建并初始化 RPC 请求
request.setRequestId(UUID.randomUUID().toString());
request.setClassName(method.getDeclaringClass().getName());
System.out.println("--请求的类名--"+request.getClassName());
request.setMethodName(method.getName());
request.setParameterTypes(method.getParameterTypes());
request.setParameters(args);
//从服务中心获取服务地址
// System.out.println(interfaceClass.getName());
// serverDiscovery.getRegisterServerInfoByServerName(interfaceClass.getName());
// if (serverDiscovery.getRegisterServerInfoByServerName(interfaceClass.getName()) != null) {
// serverAddress = serverDiscovery.getRegisterServerInfoByServerName(interfaceClass.getName()); // 发现服务
// }
serverAddress="127.0.0.1:8989";
String[] array = serverAddress.split(":");
String host = array[0];
int port = Integer.parseInt(array[1]);
//通过地址获取所需反射类
RpcClient client = new RpcClient(host, port); // 初始化 RPC 客户端
RpcResponse response = client.sendInfo(request); // 通过 RPC 客户端发送 RPC 请求并获取 RPC 响应
System.out.println("返回代理类实体");
if (response.getRequestId().equals("null")){
System.out.println("返回类为空");
throw response.getError();
} else {
return response.getResult();
}
}
});
}
}
|
Java
|
UTF-8
| 1,430
| 2.21875
| 2
|
[] |
no_license
|
package com.example.springbootshiro.service.impl;
import com.example.springbootshiro.entity.Role;
import com.example.springbootshiro.entity.UserRoleRef;
import com.example.springbootshiro.mapper.RoleMapper;
import com.example.springbootshiro.mapper.UserRoleRefMapper;
import com.example.springbootshiro.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private UserRoleRefMapper userRoleRefMapper;
@Autowired
private RoleMapper roleMapper;
@Override
public List<Role> getRoleListByUserId(Integer userId) {
List<Role> roleList = new ArrayList<>();
List<UserRoleRef> userRoleRefList = userRoleRefMapper.getUserRoleRefByUserId(userId);
for (UserRoleRef userRoleRef : userRoleRefList) {
Role role = roleMapper.selectByPrimaryKey(userRoleRef.getRoleId());
roleList.add(role);
}
return roleList;
}
@Override
public Role getRoleByRoleName(String role) {
return roleMapper.getRoleByRoleName(role);
}
@Override
public List<Role> getAllRole() {
return roleMapper.getAllRole();
}
@Override
public Role getRoleById(Integer id) {
return roleMapper.selectByPrimaryKey(id);
}
}
|
Java
|
UTF-8
| 2,983
| 2.109375
| 2
|
[] |
no_license
|
package com.example.akash.therightstep;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class
getF extends Fragment {
private FirebaseAuth mAuth;
private DatabaseReference databaseReference;
View view;
public getF() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_get, container, false);
mAuth = FirebaseAuth.getInstance();
Button post,calcel;
post=(Button)view.findViewById(R.id.post);
EditText t1,t2;
t1=(EditText)view.findViewById(R.id.question);
t2=(EditText)view.findViewById(R.id.p);
post.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseUser u = FirebaseAuth.getInstance().getCurrentUser();
databaseReference= FirebaseDatabase.getInstance().getReference();
String uid = u.getUid();
String user=u.getDisplayName();
EditText t1,t2;
t1=(EditText)view.findViewById(R.id.question);
t2=(EditText)view.findViewById(R.id.p);
String question,discription;
question=t1.getText().toString();
discription=t2.getText().toString();
get obj=new get(question,discription,user,uid);
databaseReference.child("get").push().setValue(obj).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(getActivity(), "Posted", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getActivity(), "error", Toast.LENGTH_SHORT).show();
}
}
});
}
});
return view;
}
}
|
PHP
|
UTF-8
| 7,080
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
<?php
class Redisengine
{
/**
* Redis是一个开源的使用ANSI C语言编写
* 支持网络、可基于内存
* 亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
*
*/
//1-简单字符串缓存(Simple string cache)
public function sscache(){
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$strCacheKey = 'Test_bihu';
//SET 应用
$arrCacheData = [
'name' => 'job',
'sex' => '男',
'age' => '30'
];
$redis->set($strCacheKey, json_encode($arrCacheData));
$redis->expire($strCacheKey, 30); # 设置30秒后过期
$json_data = $redis->get($strCacheKey);
$data = json_decode($json_data);
print_r($data->age); //输出数据
//HSET 应用
$arrWebSite = [
'google' => [
'google.com',
'google.com.hk'
],
];
$redis->hSet($strCacheKey, 'google', json_encode($arrWebSite['google']));
$json_data = $redis->hGet($strCacheKey, 'google');
$data = json_decode($json_data);
print_r($data); //输出数据
}
//2-简单队列实战(Simple queue combat)
public function sscom(){
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$strQueueName = 'Test_bihu_queue';
//进队列
/* $redis->rpush($strQueueName, json_encode(['uid' => 1,'name' => 'Job']));
$redis->rpush($strQueueName, json_encode(['uid' => 2,'name' => 'Tom']));
$redis->rpush($strQueueName, json_encode(['uid' => 3,'name' => 'John']));*/
echo "---- 进队列成功 ---- <br /><br />";
//查看队列
$strCount = $redis->lrange($strQueueName, 0, -1);
echo "当前队列数据为: <br />";
print_r($strCount);
//出队列
$redis->lpop($strQueueName);
echo "<br /><br /> ---- 出队列成功 ---- <br /><br />";
//查看队列
$strCount = $redis->lrange($strQueueName, 0, -1);
echo "当前队列数据为: <br />";
print_r($strCount);
}
//3-简单发布订阅(Simple publishing subscription)
public function spsub(){
//以下是 pub.php 文件的内容 cli下运行
ini_set('default_socket_timeout', -1);
$redis->connect('127.0.0.1', 6379);
$strChannel = 'Test_bihu_channel';
//发布
$redis->publish($strChannel, "来自{$strChannel}频道的推送");
echo "---- {$strChannel} ---- 频道消息推送成功~ <br/>";
$redis->close();
//以下是 sub.php 文件内容 cli下运行
ini_set('default_socket_timeout', -1);
$redis->connect('127.0.0.1', 6379);
$strChannel = 'Test_bihu_channel';
//订阅
echo "---- 订阅{$strChannel}这个频道,等待消息推送...---- <br/><br/>";
$redis->subscribe([$strChannel], 'callBackFun');
function callBackFun($redis, $channel, $msg)
{
print_r([
'redis' => $redis,
'channel' => $channel,
'msg' => $msg
]);
}
}
//4-简单计数器(Simple counter)
public function simcount(){
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$strKey = 'Test_bihu_comments';
//设置初始值
$redis->set($strKey, 0);
$redis->INCR($strKey); //+1
$redis->INCR($strKey); //+1
$redis->INCR($strKey); //+1
$strNowCount = $redis->get($strKey);
echo "---- 当前数量为{$strNowCount}。 ---- ";
}
//5-排行榜(Leaderboard)
public function leaderb(){
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$strKey = 'Test_bihu_score';
//存储数据
$redis->zadd($strKey, '50', json_encode(['name' => 'Tom']));
$redis->zadd($strKey, '70', json_encode(['name' => 'John']));
$redis->zadd($strKey, '90', json_encode(['name' => 'Jerry']));
$redis->zadd($strKey, '30', json_encode(['name' => 'Job']));
$redis->zadd($strKey, '100', json_encode(['name' => 'LiMing']));
$dataOne = $redis->ZREVRANGE($strKey, 0, -1, true);
echo "---- {$strKey}由大到小的排序 ---- <br /><br />";
print_r($dataOne);
$dataTwo = $redis->ZRANGE($strKey, 0, -1, true);
echo "<br /><br />---- {$strKey}由小到大的排序 ---- <br /><br />";
print_r($dataTwo);
}
//6-简单字符串悲观锁(Simple string pessimistic lock)
public function sspl(){
// 定义锁标识
$key = 'Test_bihu_lock';
// 获取锁
$is_lock = $this->lock($key, 10);
if ($is_lock) {
echo 'get lock success<br>';
echo 'do sth..<br>';
sleep(5);
echo 'success<br>';
$this->unlock($key);
} else { //获取锁失败
echo 'request too frequently<br>';
}
}
//7-简单事务的乐观锁(Optimistic lock for simple transactions)
public function olfst(){
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$strKey = 'Test_bihu_age';
$redis->set($strKey,10);
$age = $redis->get($strKey);
echo "---- Current Age:{$age} ---- <br/><br/>";
$redis->watch($strKey);
// 开启事务
$redis->multi();
//在这个时候新开了一个新会话执行
$redis->set($strKey,30); //新会话
echo "---- Current Age:{$age} ---- <br/><br/>"; //30
$redis->set($strKey,20);
$redis->exec();
$age = $redis->get($strKey);
echo "---- Current Age:{$age} ---- <br/><br/>"; //30
//当exec时候如果监视的key从调用watch后发生过变化,则整个事务会失败
}
/**
* 获取锁
* @param String $key 锁标识
* @param Int $expire 锁过期时间
* @return Boolean
*/
public function lock($key = '', $expire = 5) {
$is_lock = $this->_redis->setnx($key, time()+$expire);
//不能获取锁
if(!$is_lock){
//判断锁是否过期
$lock_time = $this->_redis->get($key);
//锁已过期,删除锁,重新获取
if (time() > $lock_time) {
unlock($key);
$is_lock = $this->_redis->setnx($key, time() + $expire);
}
}
return $is_lock? true : false;
}
/**
* 释放锁
* @param String $key 锁标识
* @return Boolean
*/
public function unlock($key = ''){
return $this->_redis->del($key);
}
}
|
Java
|
UTF-8
| 5,390
| 2.578125
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.TilePane;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
/**
*
* @author ahmed mahfouz
*/
public class RecPage {
String s;
// set title for the stage
public RecPage(Stage stage){
stage.setTitle("Receptionest page");
// create a tile pane
TilePane r = new TilePane();
// create a label
Label l = new Label("choose the action");
l.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 16));
Label l2 = new Label("nothing selected");
// create a toggle group
ToggleGroup tg = new ToggleGroup();
// create radiobuttons
RadioButton r1 = new RadioButton("Book a room");
RadioButton r2 = new RadioButton("Search For a gesut");
RadioButton r3 = new RadioButton("Update guest's data");
RadioButton r4 = new RadioButton("Search for a room");
RadioButton r5 = new RadioButton("Update room's data");
RadioButton r6 = new RadioButton("list rooms");
RadioButton r7 = new RadioButton("list guests");
/* RadioButton r8 = new RadioButton("generate bill"); */
Button b=new Button("Submit");
Button B=new Button("Generate Bill");
Button A=new Button("Logout");
// add radiobuttons to toggle group
r1.setToggleGroup(tg);
r2.setToggleGroup(tg);
r3.setToggleGroup(tg);
r4.setToggleGroup(tg);
r5.setToggleGroup(tg);
r6.setToggleGroup(tg);
r7.setToggleGroup(tg);
/* r8.setToggleGroup(tg);*/
// add label
r.getChildren().add(l);
r.getChildren().add(r1);
r.getChildren().add(r2);
r.getChildren().add(r3);
r.getChildren().add(r4);
r.getChildren().add(r5);
r.getChildren().add(r6);
r.getChildren().add(r7);
/* r.getChildren().add(r8);*/
r.getChildren().add(l2);
r.getChildren().add(b);
r.getChildren().add(B);
r.getChildren().add(A);
// create a scene
Scene sc = new Scene(r, 200, 500);
// add a change listener
tg.selectedToggleProperty().addListener(new ChangeListener<Toggle>()
{
public void changed(ObservableValue <? extends Toggle> ob,
Toggle o, Toggle n)
{
RadioButton rb = (RadioButton)tg.getSelectedToggle();
if (rb != null) {
s = rb.getText();
// change the label
l2.setText(s + " selected");
}
}
});
A.setOnAction(e -> Platform.exit() );
///////////////////////////////////////////////////
B.setOnAction(e -> {
generateBill BBB=new generateBill(stage);
});
/////////////////////////////////////////////////
b.setOnAction(e -> {
if( null != s)switch (s) {
case "Book a room":
recBooking a=new recBooking(stage);
break;
case "Search For a gesut":
System.out.println("2");
searchGuest S=new searchGuest(stage);
break;
case "Update guest's data":
System.out.println("3");
updateGuest u=new updateGuest(stage);
break;
case "Search for a room":
System.out.println("4");
roomSerach d=new roomSerach(stage);
break;
case "Update room's data":
System.out.println("5");
updateRoomRec BB=new updateRoomRec(stage);
break;
case "list rooms":
System.out.println("6");
listRooms SR=new listRooms(stage);
break;
case "list guests":
System.out.println("7");
listGuests UR=new listGuests(stage);
break;
/* case "generate bill":
System.out.println("8");
searchRoom DR=new searchRoom(stage);
break; */
default:
break;
}
});
// set the scene
stage.setScene(sc);
stage.show(); }
}
|
Java
|
UTF-8
| 6,469
| 1.90625
| 2
|
[] |
no_license
|
package com.atguigu.shoppingmall.community.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.atguigu.shoppingmall.R;
import com.atguigu.shoppingmall.community.bean.HotPostBean;
import com.atguigu.shoppingmall.utils.BitmapUtils;
import com.atguigu.shoppingmall.utils.Constants;
import com.atguigu.shoppingmall.utils.DensityUtil;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import java.text.SimpleDateFormat;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class HotPostListViewAdapter extends BaseAdapter {
private Context mContext;
private List<HotPostBean.ResultBean> result;
public HotPostListViewAdapter(Context mContext, List<HotPostBean.ResultBean> result) {
this.mContext = mContext;
this.result = result;
}
@Override
public int getCount() {
return result.size();
}
@Override
public Object getItem(int position) {
return result.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(mContext, R.layout.item_hotpost_listview, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
HotPostBean.ResultBean resultBean = result.get(position);
holder.tvHotUsername.setText(resultBean.getUsername());
SimpleDateFormat myFmt = new SimpleDateFormat("MM-dd HH:mm");
holder.tvHotAddtime.setText(myFmt.format(Integer.parseInt(resultBean.getAdd_time())));
Glide.with(mContext).load(Constants.BASE_URl_IMAGE +resultBean.getFigure()).into(holder.ivHotFigure);
holder.tvHotSaying.setText(resultBean.getSaying());
holder.tvHotLikes.setText(resultBean.getLikes());
holder.tvHotComments.setText(resultBean.getComments());
Picasso.with(mContext).load(resultBean.getAvatar()).transform(new Transformation() {
@Override
public Bitmap transform(Bitmap bitmap) {
//先对图片进行压缩
//Bitmap zoom = BitmapUtils.zoom(bitmap, DensityUtil.dip2px(mContext, 62), DensityUtil.dip2px(mContext, 62));
Bitmap zoom = BitmapUtils.zoom(bitmap, 70, 70);
//对请求回来的Bitmap进行圆形处理
Bitmap ciceBitMap = BitmapUtils.circleBitmap(zoom);
bitmap.recycle();//必须队更改之前的进行回收
return ciceBitMap;
}
@Override
public String key() {
return "";
}
}).into(holder.ibNewPostAvatar);
String is_top = resultBean.getIs_top();
if ("1".equals(is_top)) {
LinearLayout.LayoutParams textViewLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
TextView textView = new TextView(mContext);
textView.setText("置顶");
textViewLp.setMargins(DensityUtil.dip2px(mContext, 10), 0, DensityUtil.dip2px(mContext, 5), 0);
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.WHITE);
textView.setBackgroundResource(R.drawable.is_top_shape);
textView.setPadding(DensityUtil.dip2px(mContext, 5), DensityUtil.dip2px(mContext, 5), DensityUtil.dip2px(mContext, 5), DensityUtil.dip2px(mContext, 5));
holder.llHotPost.removeAllViews();
holder.llHotPost.addView(textView, textViewLp);
}
String is_hot = resultBean.getIs_hot();
if ("1".equals(is_hot)) {
LinearLayout.LayoutParams textViewLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
TextView textView = new TextView(mContext);
textViewLp.setMargins(0, 0, DensityUtil.dip2px(mContext, 5), 0);
textView.setText("热门");
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.WHITE);
textView.setPadding(DensityUtil.dip2px(mContext, 5), DensityUtil.dip2px(mContext, 5), DensityUtil.dip2px(mContext, 5), DensityUtil.dip2px(mContext, 5));
textView.setBackgroundResource(R.drawable.is_hot_shape);
holder.llHotPost.addView(textView, textViewLp);
}
String is_essence = resultBean.getIs_essence();
if ("1".equals(is_essence)) {
LinearLayout.LayoutParams textViewLp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textViewLp.setMargins(0, 0, DensityUtil.dip2px(mContext, 5), 0);
TextView textView = new TextView(mContext);
textView.setText("精华");
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.WHITE);
textView.setPadding(DensityUtil.dip2px(mContext, 5), DensityUtil.dip2px(mContext, 5), DensityUtil.dip2px(mContext, 5), DensityUtil.dip2px(mContext, 5));
textView.setBackgroundResource(R.drawable.is_essence_shape);
holder.llHotPost.addView(textView, textViewLp);
}
return convertView;
}
static class ViewHolder {
@Bind(R.id.tv_hot_username)
TextView tvHotUsername;
@Bind(R.id.tv_hot_addtime)
TextView tvHotAddtime;
@Bind(R.id.iv_hot_figure)
ImageView ivHotFigure;
@Bind(R.id.ll_hot_post)
LinearLayout llHotPost;
@Bind(R.id.tv_hot_saying)
TextView tvHotSaying;
@Bind(R.id.tv_hot_likes)
TextView tvHotLikes;
@Bind(R.id.tv_hot_comments)
TextView tvHotComments;
@Bind(R.id.ib_new_post_avatar)
ImageButton ibNewPostAvatar;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
|
Java
|
UTF-8
| 435
| 1.953125
| 2
|
[] |
no_license
|
package cn.lmx.flow.dao.task;
import org.springframework.stereotype.Repository;
import cn.lmx.flow.dao.flow.BaseDao;
import cn.lmx.flow.entity.task.TaskProcessHistory;
@Repository("TaskProcessHistoryDao")
public class TaskProcessHistoryDao extends BaseDao {
/**
* 取得所有的执行任务
* @return
* @throws Exception
*/
public void add(TaskProcessHistory history) throws Exception {
getSession().save(history);
}
}
|
C++
|
UTF-8
| 1,922
| 3.578125
| 4
|
[] |
no_license
|
#include <string>
#include <map>
#include <vector>
#include <iostream>
using namespace std;
void NewBus (map<string, vector<string>>& buses, map<string, vector<string>>& stops, string bus, int stopCount) {
for (int i = 0; i < stopCount; ++i) {
string stop;
cin >> stop;
buses[bus].push_back(stop);
stops[stop].push_back(bus);
}
}
void BusesForStop (map<string, vector<string>>& stops, string stop) {
if (stops.count(stop) == 0) {
cout << "No stop" << endl;
} else {
for (const auto& item : stops[stop]) {
cout << item << " ";
}
cout << endl;
}
}
void StopsForBus (map<string, vector<string>>& buses, map<string, vector<string>>& stops, string bus) {
if (buses.count(bus) == 0) {
cout << "No bus" << endl;
} else {
for (const auto& stop : buses[bus]) {
cout << "Stop " << stop << ": ";
if (stops[stop].size() == 1) {
cout << "no interchange";
} else {
for (const auto& item : stops[stop]) {
if (item != bus) {
cout << item << " ";
}
}
}
cout << endl;
}
}
}
void AllBuses (map<string, vector<string>>& buses) {
if (buses.size() == 0) {
cout << "No buses" << endl;
} else {
for (const auto& item : buses) {
cout << "Bus " << item.first << ": ";
for (const auto& stop : item.second) {
cout << stop << " ";
}
cout << endl;
}
}
}
int main() {
int q;
cin >> q;
map<string, vector<string>> buses;
map<string, vector<string>> stops;
for (int i = 0; i < q; ++i) {
string op;
cin >> op;
if (op == "NEW_BUS") {
string bus;
cin >> bus;
int stopCount;
cin >> stopCount;
NewBus(buses, stops, bus, stopCount);
} else if (op == "BUSES_FOR_STOP") {
string stop;
cin >> stop;
BusesForStop(stops, stop);
} else if (op == "STOPS_FOR_BUS") {
string bus;
cin >> bus;
StopsForBus(buses, stops, bus);
} else if (op == "ALL_BUSES") {
AllBuses(buses);
}
}
cout << endl;
return 0;
}
|
Python
|
UTF-8
| 585
| 3.40625
| 3
|
[] |
no_license
|
# Wczytanie bibliotek.
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
# Wczytanie danych zawierających tylko dwie klasy.
iris = datasets.load_iris()
features = iris.data[:100,:]
target = iris.target[:100]
# Standaryzowanie cech.
scaler = StandardScaler()
features_standardized = scaler.fit_transform(features)
# Utworzenie obiektu regresji logistycznej.
logistic_regression = LogisticRegression(random_state=0)
# Wytrenowanie modelu.
model = logistic_regression.fit(features_standardized, target)
|
Markdown
|
UTF-8
| 743
| 2.859375
| 3
|
[] |
no_license
|
# Udacity Adventure Game
Text-based space adventure game
# Table of Contents
* Intruduction
* Installations
* Library Files
* Result
# Intruduction:-
Text-based adventure games (also known as IF or Interactive Fiction) is a classic genre where all the interaction takes place through on-screen words, and they’re still alive today. While they were born from hardware limitations, text-based games can still be played on modern devices.
# Installations:-
install the Python 3.6 version and import the library as following.
# Library:-
* random
* time
# Result:-
* copy the project and open the terminal run the file
* run python adventure_game.py
Text-based space adventure game
|
Python
|
UTF-8
| 3,154
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
"""
Authorization/authentication components for Falcon apps.
"""
import logging
import jwt
import falcon
from . import get_uaa_key, UserOrgAccessChecker, NoOrgAccessError, PermissionServiceError
class JwtMiddleware:
"""
JWT middleware for Falcon.
"""
# TODO should be more complex, see https://tools.ietf.org/html/rfc6750#section-3
AUTH_CHALLENGE = 'Bearer'
def __init__(self):
self._verification_key = None
self._log = logging.getLogger(type(self).__name__)
def initialize(self, uaa_key_url):
"""
Prepares the middleware object for work. Needs to be called before any requests to the app.
Actually downloads the public key that will be used to verify JWT signature.
:param str uaa_key_url: URL under which the public key to verify a token can be found.
:raises `UaaError`: when getting the key fails
"""
self._verification_key = get_uaa_key(uaa_key_url)
def process_request(self, req, resp):
"""
Doesn't do anything. Part of Falcon middleware interface.
"""
pass
def process_resource(self, req, resp, resource, params): #pylint: disable=unused-argument
"""
Verifies the JWT token used when calling the resource.
Some resources may have disabled this verification, when they should be publicly accessible.
"""
# TODO check if the resource isn't exempted from security checking
if not req.auth or not req.auth.startswith('bearer '):
err_msg = 'Authorization header missing or not containing "bearer" prefix.'
self._log.error(err_msg)
raise falcon.HTTPUnauthorized('Bad Authorization header', err_msg, self.AUTH_CHALLENGE)
token = req.auth.split()[1] # skip 'bearer'
try:
jwt.decode(token, key=self._verification_key, options={'verify_aud': False})
except Exception as ex:
err_msg = 'Verification of the JWT token has failed.'
self._log.exception(err_msg)
raise falcon.HTTPUnauthorized('Invalid token', err_msg, self.AUTH_CHALLENGE) from ex
def process_response(self, req, resp, resource):
"""
Doesn't do anything. Part of Falcon middleware interface.
"""
pass
class FalconUserOrgAccessChecker(UserOrgAccessChecker):
"""
Wrapper for `UserOrgAccessChecker` that throws Falcon errors.
Should be used from within Falcon resources.
"""
def validate_access(self, user_token, org_ids):
try:
super().validate_access(user_token, org_ids)
except NoOrgAccessError as ex:
raise falcon.HTTPForbidden(
"User doesn't have access to resource.",
"User doesn't have sufficient rights in organization owning the resource."
) from ex
except PermissionServiceError as ex:
raise falcon.HTTPServiceUnavailable(
'Error when contacting permission service.',
"The User Management service couldn't be contacted or experienced errors.",
10
) from ex
|
Java
|
UTF-8
| 1,059
| 2.171875
| 2
|
[] |
no_license
|
package com.cvte.vo;
import com.cvte.po.ApiResponseParameter;
import java.io.Serializable;
/**
* @author pinnuli
* @date 2019/6/25
*/
public class ApiResponseParameterVo implements Serializable {
private static final long serialVersionUID = -8997958286156196856L;
private String name;
private String type;
private String illustration;
public ApiResponseParameterVo(ApiResponseParameter apiResponseParameter) {
this.name = apiResponseParameter.getName();
this.type = apiResponseParameter.getType();
this.illustration = apiResponseParameter.getIllustration();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getIllustration() {
return illustration;
}
public void setIllustration(String illustration) {
this.illustration = illustration;
}
}
|
Ruby
|
UTF-8
| 610
| 3.859375
| 4
|
[] |
no_license
|
class Anagram
attr_reader :word
def initialize(word)
@word = word
end
def match(candidates)
candidates.select { |candidate| anagram?(candidate) }
end
private
def anagram?(candidate)
has_same_characters?(candidate) && is_different_word?(candidate)
end
def has_same_characters?(candidate)
word_chars == sorted_character_set(candidate)
end
def is_different_word?(candidate)
candidate.casecmp(word) != 0
end
def word_chars
@word_chars ||= sorted_character_set(word)
end
def sorted_character_set(string)
string.downcase.chars.sort
end
end
|
C#
|
UTF-8
| 2,163
| 2.6875
| 3
|
[] |
no_license
|
using Microsoft.EntityFrameworkCore;
namespace WebAppProject.Models
{
public class AplicationContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Position> Positions { get; set; }
public AplicationContext(DbContextOptions<AplicationContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasData(
new User[]
{
new User{ Id=1,Name="Ivan",Age=4},
new User{ Id=2,Name="Petro",Age=46},
new User{ Id=3,Name="Stepan",Age=21},
new User{ Id=4,Name="Oleh",Age=32},
new User{ Id=5,Name="Bohdan",Age=65},
new User{ Id=6,Name="Andriy",Age=16},
new User{ Id=7,Name="Kolya",Age=34},
new User{ Id=8,Name="Roman",Age=41},
new User{ Id=9,Name="Nazar",Age=31},
});
modelBuilder.Entity<Position>().HasData(
new Position[]
{
new Position{Id=1 , Location="Berlin"},
new Position{Id=2 , Location="Ivano-Frankivsk"},
new Position{Id=3 , Location="Lviv"},
new Position{Id=4 , Location="Doluna"},
new Position{Id=5 , Location="Paris"},
new Position{Id=6 , Location="Tokio"},
new Position{Id=7 , Location="New York"},
new Position{Id=8 , Location="Kiyv"}
});
modelBuilder.Entity<UserPosition>().HasData(
new UserPosition[]
{
new UserPosition{ Id=1, PositionId=1,UserId=1},
new UserPosition{ Id=2, PositionId=3,UserId=2},
new UserPosition{ Id=3, PositionId=2,UserId=5},
new UserPosition{ Id=4, PositionId=6,UserId=6},
new UserPosition{ Id=5, PositionId=1,UserId=4},
});
}
}
}
|
C++
|
UTF-8
| 1,050
| 2.546875
| 3
|
[] |
no_license
|
#pragma once
#include "CObj.h"
class CGameWorld;
class CCamera2D :
public CObj
{
public:
CCamera2D(CGameWorld& _rGameWorld, CObj* _pOwner = nullptr, float _fX = 0.f, float _fY = 0.f);
~CCamera2D();
public:
virtual void Ready(void) {};
virtual int Update(float _fDeltaTime);
virtual void LateUpdate(void) {};
virtual void Render(HDC& _hdc) {
TCHAR szBuffer[64];
swprintf(szBuffer, sizeof(szBuffer), L"Camera X : %f, Y : %f, Zoom : %f", GetX(), GetY(), m_fZoomMultiple);
TextOut(_hdc, 0, 0, szBuffer, lstrlen(szBuffer));
};
virtual void Release(void) {};
public:
void ZoomIn(float _fDeltaTime);
void ZoomOut(float _fDeltaTime);
float GetZoomMultiple(void) const { return m_fZoomMultiple; }
public:
RECT GetScreenRect(RECT& _rRectW);
pair<float, float> GetScreenPoint(float _fXW, float _fYW);
pair<float, float> GetWorldPoint(float _fXS, float _fYS);
private:
CObj* m_pOwner = nullptr;
float m_fZoomMultiple = 1.f;
const float m_cfZoomSpeed = 2.f;
const float m_cfMaxZoomOut = 0.2f;
const float m_cfMaxZoomIn = 2.0f;
};
|
C#
|
UTF-8
| 295
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Action
{
public int iVal;
public Action(int i)
{
iVal = i;
}
public static implicit operator Action(Direction d)
{
return new Action((int)d);
}
}
|
Java
|
UTF-8
| 842
| 2.53125
| 3
|
[] |
no_license
|
package Presentation.View;
import javax.swing.*;
import java.awt.*;
/**
* Created by LG on 2018-03-31.
*/
public class MyModelDefault extends JTabbedPane {
MyModelPanel myModelPanel=new MyModelPanel();
TemplatePanel templatePanel=new TemplatePanel();
ResultPanel resultPanel=new ResultPanel();
public MyModelDefault(){
setBackground(Color.white);
add("My Model", myModelPanel);
add("Template", templatePanel);
add("Result", resultPanel);
setTabPlacement(JTabbedPane.BOTTOM);
setVisible(true);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(1700,200);
}
public void restartMyModelList() {
remove(myModelPanel);
myModelPanel = new MyModelPanel();
add(myModelPanel,0);
revalidate();
}
}
|
C++
|
UTF-8
| 4,117
| 2.96875
| 3
|
[] |
no_license
|
#include <iostream>
#include <cstring>
#include <queue>
#include <set>
#include <sstream>
#include <algorithm>
#include <map>
#include <vector>
#define mp make_pair
#define pb push_back
#define sqr(x) ((x)*(x))
#define foreach(it,c) for(auto it=(c).begin(); it != (c).end(); ++it)
using namespace std;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int,int> PII;
template<typename T> int size(const T &a) { return a.size(); }
vector<string> cells;
int N,M;
bool update = false;
char apply(char a, bool flag) {
if(a == '?' || flag) return a;
if(a == 'Z') return 'N';
return 'Z';
}
bool equil(int a, int b, bool same) {
for(int i=0;i<M;i++) if(cells[a][i] != '?' || cells[b][i] != '?') {
if(cells[a][i] == '?') update=true, cells[a][i] = apply(cells[b][i], same);
if(cells[b][i] == '?') update=true, cells[b][i] = apply(cells[a][i], same);
if(cells[a][i] != apply(cells[b][i], same)) return false;
}
return true;
}
class ThreeColorability
{
public:
vector <string> lexSmallest(vector <string> cells_)
{
cells = cells_;
N = size(cells);
M = size(cells[0]);
a:
do {
update = false;
for(int i=0;i<N;i++) for(int j=i+1;j<N;j++) {
for(int k=0;k<M;k++) if(cells[i][k] != '?' && cells[j][k] != '?') {
if(equil(i,j, cells[i][k] == cells[j][k]) == false) return vector<string>();
}
}
} while(update);
for(int i=0;i<N;i++) for(int j=0;j<M;j++) {
if(cells[i][j] == '?') {
cells[i][j] = 'N';
goto a;
}
}
return cells;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const vector <string> &Expected, const vector <string> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } }
void test_case_0() { string Arr0[] = {"Z"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"Z" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(0, Arg1, lexSmallest(Arg0)); }
void test_case_1() { string Arr0[] = {"??", "?N"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"NN", "NN" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(1, Arg1, lexSmallest(Arg0)); }
void test_case_2() { string Arr0[] = {"ZZZ", "ZNZ"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(2, Arg1, lexSmallest(Arg0)); }
void test_case_3() { string Arr0[] = {"N?N??NN","??ZN??Z","NN???Z?","ZZZ?Z??","Z???NN?","N?????N","ZZ?N?NN"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(3, Arg1, lexSmallest(Arg0)); }
void test_case_4() { string Arr0[] = {"ZZZZ","ZZZZ","ZZZZ"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"ZZZZ", "ZZZZ", "ZZZZ" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(4, Arg1, lexSmallest(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
ThreeColorability ___test;
___test.run_test(-1);
}
// END CUT HERE
|
SQL
|
UTF-8
| 4,589
| 4.125
| 4
|
[] |
no_license
|
----Contar las HIstorias CLinicas
Select Edad, [Masculino],[Femenino]
from (Select Edad, Sexo , COUNT(DISTINCT Historia) Historia
from (Select Case when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 0 and 2 then ' 0- 2'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 3 and 4 then ' 3- 4'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 5 and 9 then ' 5- 9'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 10 and 14 then '10- 14'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 15 and 19 then '15- 19'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 20 and 24 then '20- 24'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 25 and 29 then '25- 29'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 30 and 34 then '30- 34'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 35 and 39 then '35- 39'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 40 and 44 then '40- 44'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 45 and 49 then '45- 49'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 50 and 54 then '50- 54'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 55 and 59 then '55- 59'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 60 and 64 then '60- 64'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 65 and 69 then '65- 69'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 70 and 74 then '70- 74'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 75 and 79 then '75- 79'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 80 and 84 then '80- 84'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 85 and 89 then '85- 89'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 90 and 94 then '90- 94'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 95 and 99 then '95- 99'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 100 and 104 then '100- 104'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 105 and 109 then '105- 109'
else 'mas de 110' end as Edad, Sexo, Historia
from Estadisticas_E
where Orden>='20200801000' and Orden<='20200831999'
and [Estado orden]='Activa' And CodOrigen IN (8)) as t
Group by Edad, Sexo) as n -- Select de los datos antes de hacer el pivot
PIVOT (SUM(Historia) For Sexo in ([Masculino],[Femenino])) p --Pivot para acomodar los datos del sexo
Order By Edad
---- Contar los examenes y perfiles
Select Edad, [Masculino],[Femenino]
from (Select Edad, Sexo , COUNT(perfil) perfil
from (Select Case when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 0 and 2 then ' 0- 2'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 3 and 4 then ' 3- 4'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 5 and 9 then ' 5- 9'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 10 and 14 then '10- 14'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 15 and 19 then '15- 19'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 20 and 24 then '20- 24'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 25 and 29 then '25- 29'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 30 and 34 then '30- 34'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 35 and 39 then '35- 39'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 40 and 44 then '40- 44'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 45 and 49 then '45- 49'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 50 and 54 then '50- 54'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 55 and 59 then '55- 59'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 60 and 64 then '60- 64'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 65 and 69 then '65- 69'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 70 and 74 then '70- 74'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 75 and 79 then '75- 79'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 80 and 84 then '80- 84'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 85 and 89 then '85- 89'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 90 and 94 then '90- 94'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 95 and 99 then '95- 99'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 100 and 104 then '100- 104'
when SUBSTRING(Edad,1,CHARINDEX(' ', Edad)) Between 105 and 109 then '105- 109'
else 'mas de 110' end as Edad, Sexo, perfil
from Estadisticas_E
where Orden>='20200801000' and Orden<='20200831999'
and [Estado orden]='Activa' And CodOrigen IN (8) and Perfil=0) as t
Group by Edad, Sexo) as n
PIVOT (SUM(perfil) For Sexo in ([Masculino],[Femenino])) p
Order By Edad
|
C++
|
UTF-8
| 1,009
| 3.1875
| 3
|
[] |
no_license
|
// cohort global declarations
#ifndef COHORT_H
#define COHORT_H
#include "IEnum.h"
// class Age, providing type safety for actual age values using
// incremental enumerated type. age values returned from objects of
// this class are equivalent to actual fish ages in years.
enum AgeEnum { AGE1=1, MIN_AGE=AGE1, AGE2, AGE3, AGE4, AGE5, MAX_AGE=AGE5 };
typedef IEnum<AgeEnum, int(MIN_AGE), int(MAX_AGE)> IEAge;
#define FIRST_HV_AGE AGE2 // first age harvested
#define ADULT_AGE AGE3 // adult age
class Age : public IEAge {
public:
Age() : IEAge() {}
Age(AgeEnum age) : IEAge(age) {}
// this routine is explicit instead of a ctor, so as to provide no
// default conversion from int to Age. this is used for initializaton
// purposes.
void assign_from_int(const int v)
{ val = v; check(); }
// converts age enum to corresponding string
char* string() { return age_strings[val-bottom()]; }
private:
static char* age_strings[MAX_AGE - MIN_AGE + 1];
};
#endif
|
Java
|
UTF-8
| 4,122
| 3.40625
| 3
|
[] |
no_license
|
import java.io.*;
import java.util.*;
public class Main {
public static void spiralDisplay(int[][] arr) {
int n = arr.length, m = arr[0].length;
int rmin = 0, cmin = 0, rmax = n - 1, cmax = m - 1;
int count = n * m;
while (count > 0) {
for (int c = cmin; c <= cmax && count > 0; c++) {
System.out.print(arr[rmin][c] + " ");
count--;
}
rmin++;
for (int r = rmin; r <= rmax && count > 0; r++) {
System.out.print(arr[r][cmax] + " ");
count--;
}
cmax--;
for (int c = cmax; c >= cmin && count > 0; c--) {
System.out.print(arr[rmax][c] + " ");
count--;
}
rmax--;
for (int r = rmax; r >= rmin && count > 0; r--) {
System.out.print(arr[r][cmin] + " ");
count--;
}
cmin++;
}
}
public static void exitPoint(int[][] arr) {
int n = arr.length, m = arr[0].length;
int d = 0, r = 0, c = 0;
while (true) {
d = (d + arr[r][c]) % 4;
if (d == 0) { // E
c++;
if (c == m) { // exit point
System.out.println(r);
System.out.println(c - 1);
break;
}
} else if (d == 1) { // N
r++;
if (r == n) { // exit point
System.out.println(r - 1);
System.out.println(c);
break;
}
} else if (d == 2) { // W
c--;
if (c == -1) {
System.out.println(r);
System.out.println(c + 1);
break;
}
} else { // S
r--;
if (r == -1) {
System.out.println(r + 1);
System.out.println(c);
break;
}
}
}
}
public static void swap2D(int[][] arr, int i1, int j1, int i2, int j2) {
int temp = arr[i1][j1];
arr[i1][j1] = arr[i2][j2];
arr[i2][j2] = temp;
}
public static void transpose(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr[0].length; j++) {
swap2D(arr, i, j, j, i);
}
}
}
public static void swapColums(int[][] arr) {
int si = 0, ei = arr[0].length;
while (si < ei) {
for (int i = 0; i < arr.length; i++)
swap2D(arr, si, i, ei, i);
}
}
public static void rotate90D(int[][] arr) {
transpose(arr);
swapColums(arr);
}
public static void diagonalTraversal(int[][] arr) {
for (int gap = 0; gap < arr[0].length; gap++) {
for (int i = 0, j = gap; j < arr[0].length; i++, j++) {
System.out.println(arr[i][j]);
}
}
}
public static void matrixMultiplication(int[][] arr1, int[][] arr2) {
int n = arr1.length, m = arr1[0].length;
int p = arr2.length, q = arr2[0].length;
int[][] ans = new int[n][q];
for (int i = 0; i < n; i++) {
for (int j = 0; j < q; j++) {
int res = 0;
for (int k = 0; k < m; k++) {
res += arr1[i][k] * arr2[k][j];
}
ans[i][j] = res;
}
}
}
public static void serachIn2D(int[][] arr, int data) {
int r = arr.length - 1, c = 0;
while (r >= 0 && c < arr[0].length) {
if (arr[r][c] > data)
r--;
else if (arr[r][c] < data)
c++;
else {
System.out.println(r);
System.out.println(c);
break;
}
}
}
public static void main(String[] args) throws Exception {
// write your code here
}
}
|
JavaScript
|
UTF-8
| 758
| 2.921875
| 3
|
[] |
no_license
|
import React, { useState, useEffect } from 'react'
function Clock() {
const [NowDay, setNowDay] = useState('')
const [NowDate, setNowDate] = useState('')
const [NowTime, setNowTime] = useState('')
useEffect(() => {
setInterval(() => {
let today = new Date();
let dateString = today.toLocaleDateString('ko-Kr');
let dayName = today.toLocaleDateString('ko-KR', { weekday: 'long' });
let timeString = today.toLocaleTimeString('it-IT')
setNowDate(dateString)
setNowDay(dayName)
setNowTime(timeString)
}, 1 * 1000)
}, [])
return (
<p style={{ margin: '0 10px' }}>{NowDate} { NowDay} {NowTime}</p>
)
}
export default Clock
|
C#
|
UTF-8
| 1,255
| 3.21875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZDFixService.Utility
{
public class StopwatchHelper
{
public static StopwatchHelper Instance { get; }
public Stopwatch Stopwatch { get; set; }
static StopwatchHelper()
{
Instance = new StopwatchHelper();
}
StopwatchHelper()
{
Stopwatch = Stopwatch.StartNew();
}
public void Start()
{
Stopwatch.Restart();
}
public void Stop()
{
Stopwatch.Stop();
}
public long ElapsedNanosecond()
{
return Stopwatch.ElapsedTicks * GetNanosecPerTick();
}
/// <summary>
/// 获取当前系统一个时钟周期多少纳秒
/// </summary>
/// <returns></returns>
long GetNanosecPerTick()
{
//1秒(s) =100厘秒(cs)= 1000 毫秒(ms) = 1,000,000 微秒(μs) = 1,000,000,000 纳秒(ns) = 1,000,000,000,000 皮秒(ps)
long nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
return nanosecPerTick;
}
}
}
|
C++
|
UTF-8
| 3,657
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// Created by ARJ on 11/19/15.
//
#ifndef USIG_UFRP3_H
#define USIG_UFRP3_H
#include <memory>
#include "usig.h"
namespace ufrp {
using std::shared_ptr;
using namespace usig;
template <typename VAL_T>
struct Expr {
public:
typedef VAL_T value_type;
virtual ~Expr() {}
virtual value_type operator()() const = 0;
operator value_type() { return (*this)(); };
virtual Expr& operator=(value_type const& v) {
//no set
return *this;
}
signal<> s_Updated;
};
template <typename VAL_T>
class Value : public Expr<VAL_T> {
public:
Value(VAL_T const& initialValue) : _value(initialValue) {}
VAL_T operator()() const { return _value; }
Expr<VAL_T>& operator=(VAL_T const& v) {
_value = v;
this->s_Updated();
return *this;
}
protected:
VAL_T _value;
};
template <typename VAL_T>
using expr = shared_ptr<Expr<VAL_T>>;
template <typename VAL_T>
shared_ptr<Expr<VAL_T>> makeval(VAL_T const& value) {
return std::make_shared<Value<VAL_T>>(value);
}
// ================= expressions =================
template <typename R, typename V1, typename V2>
struct BinaryExpr : public Expr<R> {
BinaryExpr(expr<V1> const& e1, expr<V2> const& e2) :
Expr<R>(),
e1(e1),
e2(e2),
onPredUpdate([this] { this->s_Updated(); })
{
e1->s_Updated.connect(onPredUpdate);
e2->s_Updated.connect(onPredUpdate);
}
operator R() const { return (*this)(); }
protected:
expr<V1> e1;
expr<V2> e2;
slot<> onPredUpdate;
};
template <typename V1, typename V2>
struct Difference : public BinaryExpr<decltype(V1() - V2()), V1, V2> {
typedef BinaryExpr<decltype(V1() - V2()), V1, V2> BinExprType;
using BinExprType::BinExprType;
typename BinExprType::value_type operator()() const { return (*this->e1)() - (*this->e2)(); }
};
template <typename V1, typename V2>
struct Sum : public BinaryExpr<decltype(V1() + V2()), V1, V2> {
typedef BinaryExpr<decltype(V1() + V2()), V1, V2> BinExprType;
using BinExprType::BinExprType;
typename BinExprType::value_type operator()() const { return (*this->e1)() + (*this->e2)(); }
};
template <typename V1, typename V2>
struct Product : public BinaryExpr<decltype(V1() * V2()), V1, V2> {
typedef BinaryExpr<decltype(V1() * V2()), V1, V2> BinExprType;
using BinExprType::BinExprType;
typename BinExprType::value_type operator()() const { return (*this->e1)() * (*this->e2)(); }
};
template <typename V1, typename V2>
struct Quotient : public BinaryExpr<decltype(V1() / V2()), V1, V2> {
typedef BinaryExpr<decltype(V1() / V2()), V1, V2> BinExprType;
using BinExprType::BinExprType;
typename BinExprType::value_type operator()() const { return (*this->e1)() / (*this->e2)(); }
};
template <typename V1, typename V2>
shared_ptr<Expr<typename Difference<V1, V2>::value_type>>
operator-(shared_ptr<Expr<V1>> const& e1, shared_ptr<Expr<V2>> const& e2) {
return std::make_shared<Difference<V1, V2>>(e1, e2);
};
template <typename V1, typename V2>
shared_ptr<Expr<typename Sum<V1, V2>::value_type>>
operator+(shared_ptr<Expr<V1>> const& e1, shared_ptr<Expr<V2>> const& e2) {
return std::make_shared<Sum<V1, V2>>(e1, e2);
};
template <typename V1, typename V2>
shared_ptr<Expr<typename Product<V1, V2>::value_type>>
operator*(shared_ptr<Expr<V1>> const& e1, shared_ptr<Expr<V2>> const& e2) {
return std::make_shared<Product<V1, V2>>(e1, e2);
};
template <typename V1, typename V2>
shared_ptr<Expr<typename Quotient<V1, V2>::value_type>>
operator/(shared_ptr<Expr<V1>> const& e1, shared_ptr<Expr<V2>> const& e2) {
return std::make_shared<Quotient<V1, V2>>(e1, e2);
};
template <typename VAL_T>
VAL_T valof(shared_ptr<Expr<VAL_T>> const& e) {
return (*e)();
};
}
#endif //USIG_UFRP3_H
|
C#
|
UTF-8
| 3,210
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using LightningBug.Polly.Providers.Attributes;
namespace Microsoft.Extensions.DependencyInjection
{
internal static class TypeExtensions
{
public static IEnumerable<Type> GetTypeHeirarchy(this Type type)
{
while (type != typeof(object))
{
if (!type.CanCreateInstanceOfClass()) yield break;
yield return type;
type = type.BaseType;
}
}
private static bool CanCreateInstanceOfClass(this Type type)
{
return type.IsClass
&& !type.IsAbstract
&& !type.IsGenericTypeDefinition;
}
public static bool IsPolicyAttribute(object attribute)
{
return attribute is PolicyAttribute;
}
public static bool IsPolicyAttribute(this Type type)
{
return type.CanCreateInstanceOfClass()
&& typeof(PolicyAttribute).IsAssignableFrom(type);
}
public static bool IsPolicyProvider(this Type type)
{
if (!typeof(IAttributePolicyProvider).IsAssignableFrom(type))
return false;
if (!type.CanCreateInstanceOfClass())
return false;
return type
.GetInterfaces()
.Where(i => i.IsConstructedGenericType)
.Any(i => i.GetGenericTypeDefinition() == typeof(IAttributePolicyProvider<>));
}
public static IEnumerable<Type> GetAttributeTypesOfPolicyProvider(this Type type)
{
if (!type.IsPolicyProvider()) return Enumerable.Empty<Type>();
return type
.GetInterfaces()
.Where(i => i.IsConstructedGenericType)
.Where(i => i.GetGenericTypeDefinition() == typeof(IAttributePolicyProvider<>))
.Select(i => i.GetGenericArguments().Single())
.Where(attr => attr.IsPolicyAttribute())
.ToArray();
}
public static bool IsInterfaceWithPolicyAttribute(this Type type)
{
return type.IsInterface
&& !type.IsGenericTypeDefinition
&& type.GetMembers().Any(mi => mi.IsMemberWithPolicyAttribute());
}
public static IEnumerable<PolicyAttribute> GetAttributeTypesOfServiceInterface(this Type type)
{
if (!type.IsInterface) return Enumerable.Empty<PolicyAttribute>();
if (type.IsGenericTypeDefinition) return Enumerable.Empty<PolicyAttribute>();
return type.GetMembers()
.SelectMany(mi => mi.GetPolicyAttributes());
}
public static IEnumerable<PolicyAttribute> GetPolicyAttributes(this MemberInfo memberInfo)
{
return memberInfo.GetCustomAttributes(true)
.Where(IsPolicyAttribute)
.Cast<PolicyAttribute>();
}
public static bool IsMemberWithPolicyAttribute(this MemberInfo memberInfo)
{
return memberInfo.GetPolicyAttributes().Any();
}
}
}
|
Markdown
|
UTF-8
| 367
| 2.859375
| 3
|
[] |
no_license
|
# iOS Momentum Scrolling
If you are creating a site that contains scrolling overflow elements, iOS doesn't nativly add momentum scrolling to those elements. Simplying adding `-webkit-overflow-scrolling: touch;` to the element will restore that functionality.
A helpful CSS-Tricks post: http://css-tricks.com/snippets/css/momentum-scrolling-on-ios-overflow-elements
|
C#
|
UTF-8
| 3,814
| 3.0625
| 3
|
[] |
no_license
|
using System;
using Lecture9;
using NUnit.Framework;
namespace Tests.AccountsTests
{
[TestFixture]
public class AccountsAddFundsTests
{
[Test]
public void AddCheepFounds()
{
SavingAccount testAccount = new SavingAccount(1, "Test1", 100.1, false);
testAccount.AddFunds(00.01);
const double expectedSum = 100.11;
Assert.IsTrue(Math.Abs(testAccount.Sum - expectedSum) <= 1e-7, $"Фактическая сумма на счете {testAccount.Sum} отличается от ожидаемой {expectedSum}");
}
[Test]
public void AddHugeFounds()
{
AccumulationAccount testAccount = new AccumulationAccount(2, "Test2", 00.00, false, 100.00, 10.1);
testAccount.AddFunds(1000000000000);
const double expectedSum = 1000000000000;
Assert.IsTrue(Math.Abs(testAccount.Sum - expectedSum) <= 1e-7, $"Фактическая сумма на счете {testAccount.Sum} отличается от ожидаемой {expectedSum}");
}
[Test]
public void AddFoundsToMetalAccount()
{
MetalAccount testAccount = new MetalAccount(2, "Test2", 00.00, false, 10.00, "Uran", 100);
testAccount.AddFunds(9999900);
const double expectedSum = 10000900;
const double expectedGramms = 100009;
Assert.IsTrue(Math.Abs(testAccount.Sum - expectedSum) <= 1e-10, $"Фактическая сумма на счете {testAccount.Sum} отличается от ожидаемой {expectedSum}");
Assert.IsTrue(Math.Abs(testAccount.GrammsMetal - expectedGramms) <= 1e-7, $"Фактическое количество грамм на счете {testAccount.GrammsMetal} отличается от ожидаемого {expectedGramms}");
}
[Test]
public void AddOverCheepFounds()
{
SavingAccount testAccount = new SavingAccount(1, "Test1", 100.1, false);
const string expectedExceptionMessage = "Заданный аргумент находится вне диапазона допустимых значений.\r\nИмя параметра: Невозможно пополнить счет. Сумма пополнения не может быть меньше 0,01.";
var factException = Assert.Throws<ArgumentOutOfRangeException>(() => testAccount.AddFunds(00.001));
Assert.That(factException.Message, Is.EqualTo(expectedExceptionMessage));
}
[Test]
public void AddOverHugeFounds()
{
SavingAccount testAccount = new SavingAccount(1, "Test1", 00.01, false);
const string expectedExceptionMessage = "Заданный аргумент находится вне диапазона допустимых значений.\r\nИмя параметра: Невозможно пополнить счет. Баланс счета не может превышать 1 триллион же!";
var factException = Assert.Throws<ArgumentOutOfRangeException>(() => testAccount.AddFunds(1000000000000));
Assert.That(factException.Message, Is.EqualTo(expectedExceptionMessage));
}
[Test]
public void AddFoundsToCloseAccount()
{
SavingAccount testAccount = new SavingAccount(1, "Test1", 00.01, true);
string expectedExceptionMessage = $"Счет {testAccount.Id} закрыт, операция не может быть произведена.";
var factException = Assert.Throws<InvalidOperationException>(() => testAccount.AddFunds(100));
Assert.That(factException.Message, Is.EqualTo(expectedExceptionMessage));
}
}
}
|
PHP
|
UTF-8
| 2,759
| 3.0625
| 3
|
[] |
no_license
|
<?php
require_once("players.php");//подключение рас
define('COUNT_PLAYERS', 10); //количество игроков в команде
class Team{
public $name_team;
// public $unit = '';
public $races = array('Human_Warrior',
'Human_Archer',
'Human_Rider',
'Big_Orc',
'Lit_Orc',
'Elf_Archer',
'Elf_Warrior',
'Fallen_ELf',
'Free_Orc',
'Gnome_Warior');
// foreach ($races as $value) {
// $unit .= $value;
// }
public $team = []; //основной массив игроков команды
public $count_live_players = 10;
//
function __construct($name){
$this->name_team = $name;
// echo <<<END
// <table border = '1'>
// END;
for($i = 0; $i <= COUNT_PLAYERS; $i++)
{
$race = mt_rand(0,9);
$this->team[$i] = new $this->races[$race]();
echo "<br>";
echo $this->races[$race];
echo "<br>";
}
// foreach ($races as $value) {
// $unit .= $value;
// }
// echo <<<END
// </table>
// END;
}
function hit($enemy_team){
$index_enemy = mt_rand(-1,10); //индекс противника в чужой команде
$index_ally = mt_rand(-1,10); //индекс соратника в массиве
//пока просто нанесем удар
if( isset($this->team[$index_ally]) && isset($enemy_team->team[$index_enemy]) ){ //проверка на существование выбранных игроков в команде
$this->team[$index_ally]->hit($enemy_team->team[$index_enemy]);
if($enemy_team->team[$index_enemy]->is_sterben()) {
unset($enemy_team->team[$index_enemy]);
// echo "unit";
// echo get_class($enemy_team->team[$index_enemy]);
echo "<br>";
echo "<span>";
print_r($enemy_team->team[$index_ally]);
echo " is dead";
echo " ";
echo "[$enemy_team->name_team]";
echo " </span>";
echo " <br";
$enemy_team->count_live_players--;
}
}
}
}
?>
|
C++
|
UTF-8
| 3,094
| 2.8125
| 3
|
[] |
no_license
|
//
// Created by fengguang on 10/14/21.
//
#ifndef TEST_PAIRING_HEAP_H
#define TEST_PAIRING_HEAP_H
#include <cassert>
#include <iostream>
#include <string>
#include <vector>
#include "Eecs281PQ.h"
#include "BinaryPQ.h"
#include "UnorderedPQ.h"
#include "PairingPQ.h"
#include "SortedPQ.h"
#include <time.h>
#include <stdlib.h>
#include "testConstructor.h"
#include <algorithm>
#include <random>
using namespace std;
#define SIZE 100000
void testPairingCopyConstructorAndOperator() {
vector<int> vec;
for (int i = 1; i <= SIZE; ++i) {
vec.push_back(i);
}
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(vec.begin(), vec.end(), g);
PairingPQ<int> *pq1 = new PairingPQ<int>(vec.begin(), vec.end());
assert(pq1->size() == SIZE);
PairingPQ<int> *pq2 = new PairingPQ<int>(*((PairingPQ<int> *) pq1));
assert(pq2->size() == SIZE);
PairingPQ<int> *pq3 = new PairingPQ<int>();
assert(pq3->size() == 0);
*pq3 = *((PairingPQ<int> *) pq2);
assert(pq3->size() == SIZE);
for (int i = SIZE; i >= 1; --i) {
assert(pq1->top() == i);
assert(pq2->top() == i);
assert(pq3->top() == i);
pq1->pop();
pq2->pop();
pq3->pop();
assert(pq3->size() == (size_t)(i - 1));
}
assert(pq1->size() == 0);
assert(pq2->size() == 0);
assert(pq3->size() == 0);
delete pq1;
delete pq2;
delete pq3;
}
void testPairingAddNode() {
vector<int> vec;
for (int i = 1; i <= SIZE; ++i) {
vec.push_back(i);
}
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(vec.begin(), vec.end(), g);
PairingPQ<int> *pq1 = new PairingPQ<int>();
for (size_t i = 0; i < SIZE; ++i) {
PairingPQ<int>::Node* node = pq1->addNode(vec.at(i));
assert(node->getElt() == vec.at(i));
}
for (int i = SIZE; i >= 1; --i) {
assert(pq1->top() == i);
pq1->pop();
}
delete pq1;
}
void testPairingUpdateELT() {
vector<int> vec;
int arr[SIZE];
for (int i = 0; i < SIZE; ++i) {
arr[i] = i;
vec.push_back(arr[i]);
}
PairingPQ<int> *pq1 = new PairingPQ<int>();
vector<PairingPQ<int>::Node*> nodes;
for (int i = 0; i < SIZE; ++i) {
PairingPQ<int>::Node* node = pq1->addNode(arr[i]);
nodes.push_back(node);
assert(node->getElt() == arr[i]);
}
srand((unsigned) time(NULL));
for (size_t i = 0; i < SIZE / 2; ++i) {
PairingPQ<int>::Node* node = nodes.at(i);
pq1->updateElt(node, (rand() % (10001)) + node->getElt());
}
PairingPQ<int>::Node* node = nodes.at(5);
pq1->updateElt(node, 100 + node->getElt());
int min = (pq1->top());
for (size_t i = 0; i < SIZE; ++i) {
assert(min >= (pq1->top()));
min = (pq1->top());
pq1->pop();
assert(pq1->size() == (SIZE - i - 1 ));
}
delete pq1;
}
void testPairingHeap() {
testPairingCopyConstructorAndOperator();
testPairingAddNode();
testPairingUpdateELT();
}
#endif // TEST_PAIRING_HEAP_H
|
C
|
UTF-8
| 572
| 2.734375
| 3
|
[] |
no_license
|
#ifndef LL_H
#define LL_H
struct node {
char *word;
struct node *next;
};
struct linkedList {
int count;
int min_length;
struct node *head;
struct node *tail;
};
#include "stdbool.h"
typedef struct node node;
typedef struct linkedList linkedList;
linkedList *linked_init();
void linked_push(linkedList *header, char *word);
void linked_pop(linkedList *header);
int linked_search(linkedList *header, char *search_word);
bool linked_inList(linkedList* header, char* word);
bool is_empty(linkedList *header);
void linked_print(linkedList *header);
#endif
|
Java
|
UTF-8
| 1,461
| 2.5
| 2
|
[
"MIT"
] |
permissive
|
package it.pwned.telegram.bot.api.type;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* This class represents a venue.
*
*/
public class Venue {
private final static String JSON_FIELD_LOCATION = "location";
private final static String JSON_FIELD_TITLE = "title";
private final static String JSON_FIELD_ADDRESS = "address";
private final static String JSON_FIELD_FOURSQUARE_ID = "foursquare_id";
/**
* Venue location
*/
@JsonProperty(JSON_FIELD_LOCATION)
public final Location location;
/**
* Name of the venue
*/
@JsonProperty(JSON_FIELD_TITLE)
public final String title;
/**
* Address of the venue
*/
@JsonProperty(JSON_FIELD_ADDRESS)
public final String address;
/**
* <em>Optional.</em> Foursquare identifier of the venue
*/
@JsonProperty(JSON_FIELD_FOURSQUARE_ID)
public final String foursquareId;
/**
*
* @param location
* Venue location
* @param title
* Name of the venue
* @param address
* Address of the venue
* @param foursquareId
* <em>Optional.</em> Foursquare identifier of the venue
*/
public Venue(@JsonProperty(JSON_FIELD_LOCATION) Location location, @JsonProperty(JSON_FIELD_TITLE) String title,
@JsonProperty(JSON_FIELD_ADDRESS) String address, @JsonProperty(JSON_FIELD_FOURSQUARE_ID) String foursquareId) {
this.location = location;
this.title = title;
this.address = address;
this.foursquareId = foursquareId;
}
}
|
Python
|
UTF-8
| 208
| 3.1875
| 3
|
[] |
no_license
|
#compute the value of n+nn+nnn when input is n+nn+nnn
n=input("enter the value of n :")
nn=str(n)+str(n)
nnn=nn+str(n)
r=n+int(nn)+int(nnn)
print "result is :%d"%r
r=raw_input("press any key tp exit")
|
Java
|
UTF-8
| 1,140
| 2.34375
| 2
|
[] |
no_license
|
package com.example.minutesofmeeting.api.modelmessage;
import com.example.minutesofmeeting.api.model.Content;
import com.example.minutesofmeeting.api.model.SubContent;
public class SubContentResponse extends BaseResponse {
private Integer subContentId;
private String subContentTitle;
private Content content;
public SubContentResponse() {
}
public SubContentResponse(int i, String string) {
super(i,string);
}
public SubContentResponse(SubContent subcontent) {
// TODO Auto-generated constructor stub
this.subContentId=subcontent.getSubContentId();
this.subContentTitle=subcontent.getSubContentTitle();
this.content=subcontent.getContent();
}
public Integer getSubContentId() {
return subContentId;
}
public void setSubContentId(Integer subContentId) {
this.subContentId = subContentId;
}
public String getSubContentTitle() {
return subContentTitle;
}
public void setSubContentTitle(String subContentTitle) {
this.subContentTitle = subContentTitle;
}
public Content getContent() {
return content;
}
public void setContent(Content content) {
this.content = content;
}
}
|
Markdown
|
UTF-8
| 8,462
| 2.59375
| 3
|
[] |
no_license
|
# 金融企业安全体系建设
> 内容来自:https://www.freebuf.com/articles/es/258300.html
金融企业数字化转型过程中,会遇到诸如:数据中心迁移、数据丢失、遭受网络攻击等问题。企业会希望构建完整的安全体系,并要求有流程、实施规划和时间计划、并阐明如何落地、框架导向、参照标准、对标情况等。
## 安全体系建设框架图
<img src="images/金融企业安全建设/安全体系框架图.png">
上图是一家安全咨询专家提出的“安全体系规划 –安全建设体系咨询落地模块”图,目的是引导客户理解体系规划过程。但还没有与金融行业结合,没有落地。
分为几点:
- 安全战略、目标制定
- 需求调研
- 现状分析
- 安全建设评估技术流程
- 安全体系建设框架
- 综合分析论证
<img src="images/金融企业安全建设/安全咨询方向及思路设定和执行的要点.png">
若客户关注安全体系建设,关注数据安全建设,那么可以考虑下图中的体系建设架构图:
<img src="images/金融企业安全建设/安全体系规划 –安全建设体系咨询落地模块.png">
之后再迭代一次,有下面:
<img src="images/金融企业安全建设/安全体系规划–安全建设体系咨询落地模块v3.png">
## 咨询建议书
接下来可以草拟安全体系建设咨询建议书.
### 金融安全体系规划设计需求及必要性
#### 金融商业银行指引和监管应对策略
《JRT 0072-2020金融行业网络安全等级保护测评指南》标准规定了金融行业对第二级、第三级和第四级的等级保护对象的安全测评通用要求和安全测评扩展要求。适用于指导金融机构、测评机构和金融行业网络安全等级保护主管部门对等级保护对象的安全状况进行安全测评。为金融行业网络安全等级保护测评工作提供指导,可参考本标准对金融行业网络安全等级保护对象的安全状况进行测评、自查和评估,进一步完善了金融行业网络安全等级保护体系。
应对策略将结合《JRT 0072-2020金融行业网络安全等级保护测评指南》落实方案中的安全体系框架及安全规划内容,包含安全技术规划设计、安全管理规划设计内容。
针对《JRT 0071-2020个人金融信息保护技术规范》目的在于加强个人金融信息安全管理,指导各相关机构规范处理个人金融信息, 最大程度保障个人金融信息主体合法权益,维护金融市场稳定。应对策略一方面结合个人金融信息保护技术规范中规定的个人金融信息在收集、传输、存储、使用、删除、销毁等生命周期各环节的安全防护要求,从安全技术和安全管理两个方面,对个人金融信息保护提出了规范性要求。
应对策略针对《JRT 0071-2020个人金融信息保护技术规范》要求,参照本方案中的“安全规划内容-数据安全专题设计”落实数据全生命周期管理,进而满足个人金融股信息保护技术规范。同时,在个人金融信息保护技术规范所要求的个人信息保护方面,应结合个人金融信息类型(账户信息、鉴别信息、金融交易信息、个人身份信息、财产信息、借贷信息、其他信息)等提供完善的防护方案,内容包括:
<img src="images/金融企业安全建设/JRT0071-2020个人金融信息保护技术规范-信息属性定义.png">
#### 业务及安全战略一致性
为有效实现安全体系建设咨询项目顺利落地,应在安全体系建设咨询项目开始前,明确安全战略目标并实现业务及安全战略一致性,具体包括:
1)安全战略制定:安全战略建设制定前提应遵循业务发展阶段及业务战略目标,安全战略目标制定应围绕业务战略目标要求进行有效制定,更好的辅助业务战略落地及发展(例如针对业务连续性、业务灾备、业务数据安全性保障等方面综合制定安全战略)。
2)落地性保障:围绕业务战略目标所规划设定的安全战略目标,因其贴合于业务发展规划设计,因此在安全体系建设咨询项目的可用性、组织内外的项目推动性方面存在巨大优势,为安全体系建设落地性提供必要保障。
3)资源获取支撑:有效的安全体系建设,在项目章程构建、项目启动及项目实施过程所需的组织架构高层领导及利益相关方的有效配合,协助安全体系建设咨询方提供必要的安全体系建设资源获取支撑,将为顺利落地安全体系建设框架工作提供必要支撑及保障。
#### 金融安全资源投入规划
数据中心规划【省略,主要为安全建设现状描述】
已有安全资源投入包括安全产品投入、周期性的信息安全服务、风险评估及安全态势感知监测、安全资产的保障应用。但面临新数据中心搬迁后,现网经过未来3-5年内逐步迁移过程中如何确保有效的安全防护建设等问题。同时网络设备、安全设备,目前无法进行合理化使用。采购、购置必要的安全产品、安全服务无有效的参考标准及安全资源投入规划基线及指标依据。信息安全管理工作仍可能存在着不能满足《网络安全法》和相关监管部门相关要求之处,也存在着新的法律法规提出的新风险。在现有的信息安全管理制度有待完善,缺乏信息安全建设规划和实施步骤,企业信息安全工作缺乏明确的目标、方向和详细工作指引。
### 安全体系规划设计框架-框架定义
#### 安全体系框架-设计模型
依据安全建设现状、新数据中心安全需求及3-5年蓝图发展目标的概述,实现定制化安全体系建设框架设计“安全体系建设-咨询整体框架图 V1.0”(图2-讨论稿)。作为第一版安全体系建设咨询项目有效落地重要参考依据,方便理解安全体系建设咨询流程、咨询内容、资源任务分配方面内容,框架图中流程、任务、评估维度以不同颜色模块呈现,并对安全合规性参照、安全体系建设咨询框架设计及服务流程、安全体系框架实践方针进行详细划分,具体如下:
<img src="images/金融企业安全建设/安全体系规划–安全建设体系咨询落地模块v3.png">
深绿色(TOP层):合规性安全参考标准,针对数字化转型战略方针,国家、金融行业安全法律法规、标准作为合规性依据,目的在于确保安全体系建设框架设计落地性同时,实现落地、合规性的有章可循。
浅绿色:浅绿色作为客户方需针对安全体系建设咨询框架设计方提供的理解及输入模块部分,一般以相关模块客户方已有的输入材料作为依据。一方面便于安全体系建设咨询方提供咨询方向选择建议;另一方面,作为安全体系建设咨询项目顶层规划中-宏观方向参考指南及依据,实现基于项目客户方、安全体系建设咨询规划方对咨询项目理解双向的一致性,以及安全体系建设框架设计输出模块部分的落地性及价值交付。
橘色:橘色作为安全体系建设咨询框架设计方的输出流程部分,此部分对安全体系建设咨询方提供的咨询服务流程阶段进行定义。
蓝色:蓝色作为安全体系建设咨询框架设计方的输入部分,此部分输入作为安全体系建设咨询项目的具体价值交付部分呈现,确保安全体系建设咨询项目的落地性实施、操作及价值交付。
黄色:黄色作为安全体系建设咨询框架设计方在框架设计实践阶段,所遵循的最佳实践方针指南参照。即有效指导项目落地及价值交付,说明安全体系建设咨询的框架设计是基于战略一致性、价值交付、风险管理、资源管理、绩效评价五项方针实现框架设计落地性的保证的。
### 安全体系规划设计-详细设计
基于上面安全体系规划框架可以定出整体的每个部分要做的内容及层面了,因此在设计的时候除了将上面的框架进行细化后,同时结合体系框架的核心做具体的描述及输出。篇幅较多,略。
|
PHP
|
UTF-8
| 682
| 3.3125
| 3
|
[] |
no_license
|
<?php
class file_input_stream {
private $file = null;
public function __construct( $file ){
$this->file = $file;
}
public function get_file(){
return $this->file;
}
public function __destruct(){
}
function read_int()
{
$data = fread($this->file, 4);
if($data==""){
throw new Exception("end of data");
}
$raw = unpack('N', $data);
$val = $raw[1] & 0xffffffff;
return $val;
}
function read_utf()
{
$l = $this->read_int();
return fread($this->file,$l);
}
function read_fully($l)
{
return fread($this->file,$l);
}
}
|
Java
|
UTF-8
| 1,121
| 1.734375
| 2
|
[] |
no_license
|
package com.example.zhengai.service.impl;
import java.util.List;
import com.example.zhengai.dao.YzControllerDao;
import com.example.zhengai.model.YzController;
import com.example.zhengai.service.YzControllerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class YzControllerServiceImpl implements YzControllerService {
@Autowired
private YzControllerDao dao;
@Override
public List<YzController> selectByAddUidPrimaryKey(Integer addUid) {
return dao.selectByAddUidPrimaryKey(addUid);
}
@Override
public YzController selectPrimaryKey(Integer id) {
return dao.selectPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(YzController controller) {
return dao.updateByPrimaryKeySelective(controller);
}
@Override
public int insertSelective(YzController controller) {
// TODO Auto-generated method stub
return dao.insertSelective(controller);
}
@Override
public YzController selectAllChartTid(Integer id) {
// TODO Auto-generated method stub
return dao.selectAllChartTid(id);
}
}
|
Swift
|
UTF-8
| 1,369
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
//
// BloomFilterTests.swift
// Buckets
//
// Created by Mauricio Santos on 4/11/15.
// Copyright (c) 2015 Mauricio Santos. All rights reserved.
//
import Foundation
import XCTest
import Buckets
class BloomFilterTests: XCTestCase {
struct TestData {
static let FPP: Double = 0.09
static let List = [Int](1...10)
}
var bloomFilter = BloomFilter<Int>(expectedCount: 1000, FPP: TestData.FPP)
func testEmptyBloomFilter() {
XCTAssertEqual(bloomFilter.FPP, TestData.FPP)
XCTAssertEqual(bloomFilter.FPP, TestData.FPP)
XCTAssertTrue(bloomFilter.isEmpty)
XCTAssertFalse(bloomFilter.contains(1))
}
func testInsert() {
for i in TestData.List {
bloomFilter.insert(i)
}
for i in TestData.List {
XCTAssertTrue(bloomFilter.contains(i))
}
XCTAssertFalse(bloomFilter.contains(-1))
}
func testRoughCount() {
for i in TestData.List {
bloomFilter.insert(i)
}
XCTAssertTrue(bloomFilter.roughCount >= 7)
XCTAssertTrue(bloomFilter.roughCount <= 10)
}
func testRemoveAll() {
for i in TestData.List {
bloomFilter.insert(i)
}
bloomFilter.removeAll()
XCTAssertTrue(bloomFilter.isEmpty)
XCTAssertFalse(bloomFilter.contains(1))
}
}
|
Python
|
UTF-8
| 172
| 3.5625
| 4
|
[] |
no_license
|
#leap_year program
yr=int(input("enter the year"))
print(yr)
if(yr%4==0 and yr%100!=0 or yr%400==5):
print("Leap Year")
else:
print("not leap year")
|
C++
|
GB18030
| 3,679
| 3.40625
| 3
|
[] |
no_license
|
/***************************************************************************************************************************************************
Problem Description
Before ACM can do anything, a budget must be prepared and the necessary financial support obtained.
The main income for this action comes from Irreversibly Bound Money (IBM). The idea behind is simple.
Whenever some ACM member has any small money, he takes all the coins and throws them into a piggy-bank.
You know that this process is irreversible, the coins cannot be removed without breaking the pig.
After a sufficiently long time, there should be enough cash in the piggy-bank to pay everything that needs to be paid.
But there is a big problem with piggy-banks. It is not possible to determine how much money is inside.
So we might break the pig into pieces only to find out that there is not enough money.
Clearly, we want to avoid this unpleasant situation. The only possibility is to weigh the piggy-bank and try to guess how many coins are inside.
Assume that we are able to determine the weight of the pig exactly and that we know the weights of all coins of a given currency.
Then there is some minimum amount of money in the piggy-bank that we can guarantee.
Your task is to find out this worst case and determine the minimum amount of cash inside the piggy-bank.
We need your help. No more prematurely broken pigs!
Input
The input consists of T test cases. The number of them (T) is given on the first line of the input file.
Each test case begins with a line containing two integers E and F.
They indicate the weight of an empty pig and of the pig filled with coins.
Both weights are given in grams. No pig will weigh more than 10 kg, that means 1 <= E <= F <= 10000.
On the second line of each test case, there is an integer number N (1 <= N <= 500) that gives the number of various coins used in the given currency.
Following this are exactly N lines, each specifying one coin type. These lines contain two integers each, Pand W (1 <= P <= 50000, 1 <= W <=10000).
P is the value of the coin in monetary units, W is it's weight in grams.
Output
Print exactly one line of output for each test case.
The line must contain the sentence "The minimum amount of money in the piggy-bank is X." where X is the minimum amount of money
that can be achieved using coins with the given total weight.
If the weight cannot be reached exactly, print a line "This is impossible.".
Sample Input
3
10 110
2
1 1
30 50
10 110
2
1 1
50 30
1 6
2
10 3
20 4
Sample Output
The minimum amount of money in the piggy-bank is 60.
The minimum amount of money in the piggy-bank is 100.
This is impossible.
*******************************************************************************************************************************************************/
//ȫ⣬ұҪȫһʼdp[0]ֵδ塣Ž
#include <iostream>
#include <algorithm>
#define MAX 501
using namespace std;
int weight[MAX];
int value[MAX];
int dp[10001];
int main()
{
int needWeight;
int t, e, f, n;
cin >> t;
while(t--)
{
cin >> e >> f;
needWeight = f - e;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> value[i] >> weight[i];
}
fill(dp, dp + 10001, 10000000);
dp[0] = 0;
for(int i = 0; i < n; i++)
{
for(int j = weight[i]; j <= needWeight; j++)
{
dp[j] = min(dp[j], dp[j - weight[i]] + value[i]);
}
}
if(dp[needWeight] == 10000000)
cout << "This is impossible." << endl;
else
cout << "The minimum amount of money in the piggy-bank is " << dp[needWeight] << "." << endl;
}
return 0;
}
|
Java
|
UTF-8
| 261
| 1.640625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.linkb.jstx.bean;
import java.io.Serializable;
public class Location implements Serializable {
private transient static final long serialVersionUID = 1L;
public double latitude;
public double longitude;
public String location;
}
|
Python
|
UTF-8
| 3,807
| 3.515625
| 4
|
[] |
no_license
|
#! /usr/bin/env python
"""
USAGE: summarizeData.py <mean_output_file> <stdDev_output_file> <all_input_files>
EXAMPLE: summarizeData.py mean.dat dev.dat data_*.dat
This script takes a list of files <all_input_files> that must all have the same shape
and headers starting with '#' (or no headers) and compute the average of each entry
over all files {e.g. mean[i][j] = Average(file01[i][j], file02[i][j], ...)}. It also
computes the standard deviation in the same fashion. Therefore, the output has the same
shape as the input.
Written by: Henrique S. Xavier -- hsxavier@if.usp.br -- 2015-10-16
Strongly based on:
http://stackoverflow.com/questions/12963446/how-to-calculate-the-average-of-several-dat-files-using-python
"""
from contextlib import contextmanager
from itertools import imap, izip
from glob import iglob
from math import sqrt
from sys import exit, argv
# Docstring output:
if len(argv) < 1 + 3:
print(__doc__)
exit(1)
@contextmanager
def multi_file_manager(files, mode='rt'):
files = [open(file, mode) for file in files]
yield files
for file in files:
file.close()
# generator function to read and yield each value from a file
def read_values(file):
for line in file:
if not line.startswith("#"): # skip comments.
for value in imap(float, line.split()): # might only need 'int' here
yield value
# enumerate multiple egual length iterables simultaneously as (i. n0, n1, ...)
def multi_enumerate(start, *iterables):
# returns generator
return ((n,)+t for n, t in enumerate(izip(*iterables), start))
# Beggining of the main code:
argv.pop(0) # First argument is the code itself.
meanfile = argv.pop(0) # Second is the file output for the means.
devfile = argv.pop(0) # Third is the file output for the standard deviations.
# Remaining are the files that will be averaged over.
# Run code:
with multi_file_manager(argv) as datfiles:
num_files = len(datfiles)
if num_files < 2:
print 'Less than 2 .dat files were found to process, terminating.'
sys.exit(1)
# determine number of rows and cols from first file
temp = [line.split() for line in datfiles[0]]
while (temp[0][0].startswith("#")==True): temp.pop(0)
num_rows = len(temp)
num_cols = len(temp[0])
del temp # no longer needed
datfiles[0].seek(0) # rewind first file
print 'Found {0} .dat files, each {1} rows x {2} cols'.format(num_files, num_rows, num_cols)
print 'Will write their means to', meanfile, 'and their deviations to', devfile
means = [] # initialize
sigmas = [] # standard deviations
generators = [read_values(file) for file in datfiles]
for j in xrange(num_rows): # main loop
for i in xrange(num_cols):
values = map(next, generators) # next cell value from each file
mean = float(sum(values)) / num_files
means.append(mean)
means_diff_sq = imap(lambda value: (value-mean)**2, values)
sigma = sqrt(sum(means_diff_sq) / (num_files-1)) # Corrected to give unbiased sample standard deviation.
sigmas.append(sigma)
print 'Calculating means and deviations...'
with open(meanfile, 'wt') as averages:
with open(devfile, 'wt') as deviations:
for i, mean, sigma in multi_enumerate(0, means, sigmas):
averages.write('{0:.8e}'.format(mean))
deviations.write('{0:.8e}'.format(sigma))
if i % num_cols != num_cols-1: # not last column?
averages.write(' ') # delimiter between values on line
deviations.write(' ')
else:
averages.write('\n')
deviations.write('\n')
print 'done.'
print
|
Python
|
UTF-8
| 637
| 2.953125
| 3
|
[] |
no_license
|
# coding=UTF-8
import banques_db
class BanquesMain:
def __init__(self):
self.database = banques_db.DataBase()
def start(self):
while True:
print('1.修改数据')
print('2.查询数据')
print('3.关闭连接')
flag = int(input('请选择操作 -->'))
if flag == 1:
self.database.change_data()
if flag == 2:
self.database.query_data()
if flag == 3:
self.database.close_connect()
break
if __name__ == '__main__':
banques = BanquesMain()
banques.start()
|
Rust
|
UTF-8
| 1,425
| 3.703125
| 4
|
[] |
no_license
|
//
// EPITECH PROJECT, 2018
// rust-talk
// File description:
// 2-types
//
// Here are some Rust types in action.
fn main() {
// This is a '&str'
let static_str = "ℵ ∑ ½ ౽ ⅋ ! 🚀 🚀";
println!("&str:\t\t\t{:?}", static_str);
// This is an allocated 'String'
let owned_str = String::from("The 💻 says: 'Hello, world ! 🎉 🎉'");
println!("String:\t\t\t{:?}", owned_str);
// This is an 'i32' storing 12
let x = 12;
println!("i32:\t\t\t{:?}", x);
// This is an 'u32' storing 53
let y = 53u32;
println!("u32:\t\t\t{:?}", y);
// This is a tuple: (i32, i32)
let tuple = (4, 2);
println!("tuple:\t\t\t{:?}", tuple);
// This is a static array: [i32;3]
let arr = [1, 2, 3];
println!("[i32;3]:\t\t{:?}", arr);
// This is an owned dynamic array: Vec<i32>
let vector = vec![4, 5, 6];
println!("Vec<i32>:\t\t{:?}", vector);
// This is an enum called Option<T> with Some(T) and None being its variants
let opt1: Option<i32> = Some(5);
let opt2: Option<i32> = None;
println!("Option<i32>:\t\t{:?}\t{:?}", opt1, opt2);
// This is an enum called Result<T, E> with Ok(T) and Err(E) being its variants
let ret1: Result<i32, &str> = Ok(5);
let ret2: Result<i32, &str> = Err("Pas d'idées");
println!("Result<i32, &str>:\t{:?}\t{:?}", ret1, ret2);
// '_' means 'drop the value'
let _ = 42;
}
|
Java
|
UTF-8
| 2,741
| 2.390625
| 2
|
[] |
no_license
|
package bootup.assignment.inventory.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import bootup.assignment.inventory.config.ExternalPropertyConfig;
import bootup.assignment.inventory.exception.BlockedProductException;
import bootup.assignment.inventory.exception.WebApplicationException;
import bootup.assignment.inventory.model.Products;
import bootup.assignment.inventory.repository.ProductsRepository;
@Service
@CacheConfig(cacheNames={"products"})
@Transactional
public class ProductsService {
@Autowired
private ProductsRepository productsRepository;
@Autowired
ExternalPropertyConfig externalPropertyConfig;
//find product by Product ID
@Cacheable("products")
public Products findProductByID(String productId) throws WebApplicationException {
Products product = productsRepository.findProductsByid(productId);
if (null == product) {
throw new WebApplicationException("Product not found for this id ::" + productId);
} else {
return product;
}
}
// Create operation
public Products createProduct(Products products) {
List<Products> blockedProduct = externalPropertyConfig.getBanned();
for(Products eachblockedProduct: blockedProduct) {
if(products.getProductcategory().equalsIgnoreCase(eachblockedProduct.getProductcategory())
&&
products.getProductname().equalsIgnoreCase(eachblockedProduct.getProductname())){
throw new BlockedProductException("This Product is not allowed, falls under Blocked Product Category");
}
}
return productsRepository.save(products);
}
// Retrieve operation
public List<Products> getAllProducts() {
List<Products> productList = productsRepository.findAll();
if (null == productList) {
throw new WebApplicationException("No Product found");
} else {
return productList;
}
}
// Update Operation
public Products updateProductByID(Products product) {
Products availableproduct = findProductByID(product.getId());
availableproduct.setProductcategory(product.getProductcategory());
availableproduct.setProductname(product.getProductname());
availableproduct.setProductPrice(product.getProductPrice());
return productsRepository.save(availableproduct);
}
// Delete Operation
public void deleteProductByID(String productId) {
Products availableproduct = findProductByID(productId);
productsRepository.delete(availableproduct);
}
}
|
Java
|
UTF-8
| 281
| 1.5625
| 2
|
[] |
no_license
|
package com.virtusa.view;
public class AdminView {
public void mainAdminView() {
System.out.println("=======Admin View======");
}
public void showLoginFailure() {
// TODO Auto-generated method stub
System.out.println("password or adminId incorrect");
}
}
|
Markdown
|
UTF-8
| 1,816
| 2.78125
| 3
|
[] |
no_license
|
## Why did you do this?
Frustrated with manually creating a devstack deployment each day, I figured I'd invest a little time now to save a lot later. This is the fruit of my labor.
### Assumptions
You have a DigitalOcean account with an [auth Token](https://cloud.digitalocean.com/settings/applications) handy.
You have [tugboat](https://github.com/pearkes/tugboat) installed and configured. Setup is very easy, just run `tugboat authorize` and you're halfway there.
### Quick config
After setting up tugboat, make sure to set a default SSH key. You can do this by running `tugboat keys`.
```
Name: tutum-70159d08-bfe8-44de-b0a1-4ce0d2dd9682, (id: 1529470), fingerprint: c4:b0:f2:b0:a7:9f:89:d0:c5:ae:b5:5c:f3:de:a0:69
Name: DO-webserver, (id: 1532126), fingerprint: 37:75:95:7d:93:4f:e0:fd:01:4a:ba:e4:2e:be:6d:c7
```
I want to use DO-webserver in the output above, so my key id is `1532126`. Open up `~/.tugboat` and change `ssh_key` to the key id you retrieved.
## Running the tool
Running the tool is dead easy. Just two steps.
_DON'T use a shebang, caused a bug in my experience_
1. `python deploy_stack.py`
2. Wait for droplet to be created
3. Run the output command
### Example output
You should see a set of three-ish commands to run, like in the output below. The only difference should be IP address.
```
Run this: ssh root@162.243.229.80 'bash -s' < stack_setup.sh
Then ssh root@162.243.229.80
then cd /usr/local/src/devstack && su stack
and finally: ./stack.sh
```
**Typical runtime**: Typical execution time for the `./stack.sh` command is between 1000 to 1400 seconds (16 - 23.5 mins)
Feel free to inspect both scripts to make sure you know what you're installing.
This script does _not_ setup the DD Agent, as my custom Agent download script passes in the API key to my personal account.
|
PHP
|
UTF-8
| 5,010
| 2.796875
| 3
|
[
"MIT",
"GPL-2.0-or-later",
"GPL-1.0-or-later",
"GPL-2.0-only"
] |
permissive
|
<?php
/**
* Abstracts information about a file into a view parameter object.
*/
class Loco_mvc_FileParams extends Loco_mvc_ViewParams {
/**
* File reference from which to take live properties.
* @var Loco_fs_File
*/
private $file;
/**
* Print property as a number of bytes in larger denominations
*/
public static function renderBytes( $n ){
$i = 0;
$dp = 0;
while( $n >= 1024 ){
$i++;
$dp++;
$n /= 1024;
}
$s = number_format( $n, $dp, '.', ',' );
// trim trailing zeros from decimal places
$a = explode('.',$s);
if( isset($a[1]) ){
$s = $a[0];
$d = trim($a[1],'0') and $s .= '.'.$d;
}
$units = array( ' bytes', ' KB', ' MB', ' GB', ' TB' );
$s .= $units[$i];
return $s;
}
/**
* @return Loco_mvc_FileParams
*/
public static function create( Loco_fs_File $file ) {
return new Loco_mvc_FileParams( array(), $file );
}
/**
* Override does lazy property initialization
*/
public function __construct( array $props = array(), Loco_fs_File $file ){
parent::__construct( array (
'name' => '',
'path' => '',
'relpath' => '',
'reltime' => '',
'bytes' => 0,
'size' => '',
'imode' => '',
'smode' => '',
'owner' => '',
'group' => '',
) + $props );
$this->file = $file;
}
/**
* {@inheritdoc}
* Override to get live information from file object
*/
public function offsetGet( $prop ){
$getter = array( $this, '_get_'.$prop );
if( is_callable($getter) ){
return call_user_func( $getter );
}
return parent::offsetGet($prop);
}
/**
* {@inheritdoc}
* Override to ensure all properties populated
*/
public function getArrayCopy(){
$a = array();
foreach( $this as $prop => $dflt ){
$a[$prop] = $this[$prop];
}
return $a;
}
/**
* @return string
*/
private function _get_name(){
return $this->file->basename();
}
/**
* @return string
*/
private function _get_path(){
return $this->file->getPath();
}
/**
* @return string
*/
private function _get_relpath(){
$base = loco_constant('WP_CONTENT_DIR');
return $this->file->getRelativePath($base);
}
/**
* Using slightly modified version of WordPress's Human time differencing
* + Added "Just now" when in the last 30 seconds
* TODO possibly replace with custom function that includes "Yesterday" etc..
*/
private function _get_reltime(){
$time = $this->has('mtime') ? $this['mtime'] : $this->file->modified();
$time_diff = time() - $time;
// use same time format as posts listing when in future or more than a day ago
if( $time_diff < 0 || $time_diff >= 86400 ){
return date_i18n( __('Y/m/d','default'), $time );
}
if( $time_diff < 30 ){
// translators: relative time when something happened in the last 30 seconds
return __('Just now','loco-translate');
}
return sprintf( __('%s ago','default'), human_time_diff($time) );
}
/**
* @return int
*/
private function _get_bytes(){
return $this->file->size();
}
/**
* @return string
*/
private function _get_size(){
return self::renderBytes( $this->_get_bytes() );
}
/**
* Get octal file mode
* @return string
*/
private function _get_imode(){
$mode = new Loco_fs_FileMode( $this->file->mode() );
return (string) $mode;
}
/**
* Get rwx file mode
* @return string
*/
private function _get_smode(){
$mode = new Loco_fs_FileMode( $this->file->mode() );
return $mode->format();
}
/**
* Get file owner name
* @return string
*/
private function _get_owner(){
if( ( $uid = $this->file->uid() ) && function_exists('posix_getpwuid') && ( $a = posix_getpwuid($uid) ) ){
return $a['name'];
}
return sprintf('%u',$uid);
}
/**
* Get group owner name
* @return string
*/
private function _get_group(){
if( ( $gid = $this->file->gid() ) && function_exists('posix_getpwuid') && ( $a = posix_getgrgid($gid) ) ){
return $a['name'];
}
return sprintf('%u',$gid);
}
/**
* Print pseudo console line
*/
public function ls(){
$this->e('smode');
echo ' ';
$this->e('owner');
echo ':';
$this->e('group');
echo ' ';
$this->e('relpath');
return '';
}
}
|
Markdown
|
UTF-8
| 27,506
| 2.546875
| 3
|
[] |
no_license
|
### Useful shortcuts
Use `Cmd-N` in gradle file to search for dependency first and then add.
### Kotlin with Gradle
https://www.youtube.com/watch?v=KN-_q3ss4l0
### Key classes/Interfaces:
1. Script Interace - represents the `build.gradle` file instance (https://docs.gradle.org/current/dsl/org.gradle.api.Script.html)
2. Project Interface - represents a project via `build.gradle`.
3. Gradle Interface.
4. Settings Interface
5. Task Interface
6. Action Interface
### Project evaluation events
1. `beforeEvaluate`
2. `afterEvaluate`
### Task graph events
1. `whenTaskAdded`
2. `whenReady`
3. `beforeTask`
4. `afterTask`
### Gradle FileCollection
A `FileCollection` represents a collection of file system locations which you can query in certain ways. A file collection is can be used to define a classpath, or a set of source files, or to add files to an archive.
There are no methods on this interface that allow the contents of the collection to be modified. However, there are a number of sub-interfaces, such as `ConfigurableFileCollection` that allow changes to be made.
A file collection may contain task outputs. The file collection tracks not just a set of files, but also the tasks that produce those files. When a file collection is used as a task input property, Gradle will take care of automatically adding dependencies between the consuming task and the producing tasks.
### Script interface
You always have `logger` available in your build script.
`apply`: Configures the delegate object for this script using plugins or scripts. The given closure is used to configure an ObjectConfigurationAction which is then used to configure the delegate object.
`build.gradle` build script delegates to project Object.
`settings.gradle` build script delegates to Seggings Object which in turn has access to bunch of Project objects.
`Gradle`: TOp level object. - Can be used in files like `init.gradle` where no other context like Project etc. has started yet. https://docs.gradle.org/current/dsl/org.gradle.api.invocation.Gradle.html#org.gradle.api.invocation.Gradle:gradle
Project and SEttings object have access to the gradle object.
### gradle domain object
Lives on the project.
Can be accessed in script like this:
`project.gradle.someMethods`.
### Gradle Task
A Task represents a single atomic piece of work for a build, such as compiling classes or generating javadoc.
A Task contains a list of actions to be performed
You can also use the task keyword in your build file:
The task configure closure has access to the task. One can do
things like configure task description etc. in the configure closure.
```
task myTask
task myTask { configure closure }
task myTask(type: SomeType)
task myTask(type: SomeType) { configure closure }
```
```groovy
task Hello {
// sets property of the task
description "This is a description"
}
println Hello.descrition
```
If task already exists in scope, you can also configure just using
their name and closure
e.g.
```
taskName {
println "this task's name is $name"
description "What a new description"
}
```
Each task has a name, which can be used to refer to the task within its owning project, and a fully qualified path, which is unique across all tasks in all projects. The path is the concatenation of the owning project's path and the task's name
A Task has 4 'scopes' for properties. You can access these properties by name from the build file or by calling the property(String) method. You can change the value of these properties by calling the setProperty(String, Object) method.
1. The Task object itself. This includes any property getters and setters declared by the Task implementation class. The properties of this scope are readable or writable based on the presence of the corresponding getter and setter methods.
2. The extensions added to the task by plugins. Each extension is available as a read-only property with the same name as the extension.
3. The convention properties added to the task by plugins. A plugin can add properties and methods to a task through the task's Convention object. The properties of this scope may be readable or writable, depending on the convention objects.
4. The extra properties of the task. Each task object maintains a map of additional properties. These are arbitrary name -> value pairs which you can use to dynamically add properties to a task object. Once defined, the properties of this scope are readable and writable.
### Gradle configurations
A `Configuration` represents a group/scope of artifacts and their dependencies.
e.g. `compile` configuration, or `implementation` configuration.
Configuration is an instance of a `FileCollection` that contains all dependencies (see also `getAllDependencies()`) but not artifacts. If you want to refer to the artifacts declared in this configuration please use `getArtifacts()` or `getAllArtifacts()`.
Configurations are a fundamental part of dependency resolution in Gradle. In the context of dependency resolution, it is useful to distinguish between a consumer and a producer. Along these lines, configurations have at least 3 different roles:
1. to declare dependencies
2. as a consumer, to resolve a set of dependencies to files
3. as a producer, to expose artifacts and their dependencies for consumption by other projects (such consumable configurations usually represent the variants the producer offers to its consumers)
Configuration role can be resolved can be consumed
Bucket of dependencies false false
Resolve for certain usage true false
Exposed to consumers false true
Legacy, don’t us true true
A configuration that can be resolved is a configuration for which we can compute a dependency graph, because it contains all the necessary information for resolution to happen.
That is to say we’re going to compute a dependency graph, resolve the components in the graph, and eventually get artifacts.
A configuration which has `canBeResolved` set to false is not meant to be resolved. Such a configuration is there only to declare dependencies. The reason is that depending on the usage (compile classpath, runtime classpath), it can resolve to different graphs. It is an error to try to resolve a configuration which has `canBeResolved` set to false. To some extent, this is similar to an abstract class (`canBeResolved=false`) which is not supposed to be instantiated, and a concrete class extending the abstract class (`canBeResolved=true`). A resolvable configuration will extend at least one non-resolvable configuration (and may extend more than one).
### Gradle plugins
Applying a plugin means actually executing the plugin’s `Plugin.apply(T)` on the Project you want to enhance with the plugin. Applying plugins is idempotent. That is, you can safely apply any plugin multiple times without side effects.
There are two general types of plugins in Gradle, `script plugins` and `binary plugins`.
`Script plugins`: Script plugins are additional build scripts that further configure the build and usually implement a declarative approach to manipulating the build. They are typically used within a build although they can be externalized and accessed from a remote location.
```groovy
/*
Script plugins are automatically resolved and can be applied from a script on the local filesystem or at a remote location.
*/
apply from: 'other.gradle'
```
`Binary plugins`: Binary plugins are classes that implement the Plugin interface and adopt a programmatic approach to manipulating the build. Binary plugins can reside within a build script, within the project hierarchy or externally in a plugin jar. **You apply plugins by their plugin id, which is a globally unique identifier, or name, for plugins**
You apply plugins by their plugin `id`, which is a globally unique identifier, or name, for plugins. Core Gradle plugins are special in that they provide short names, such as 'java' for the core JavaPlugin.
```groovy
plugins {
id 'java'
}
plugins {
id 'com.jfrog.bintray' version '0.4.1'
}
```
A plugin often starts out as a script plugin (because they are easy to write) and then, as the code becomes more valuable, it’s migrated to a binary plugin that can be easily tested and shared between multiple projects or organizations.
Applying a plugin means actually executing the plugin’s `Plugin.apply(T)` on the Project you want to enhance with the plugin. Applying plugins is idempotent. That is, you can safely apply any plugin multiple times without side effects.
#### Convention plugin
More often that not, projects end up in one of these situations:
1. Many random `*.gradle(.kts)` scripts that not everyone understands.
2. Very complicated `subprojects` and `allprojects` blocks.
3. A `buildSrc` directory that houses much of the build logic. (not great because it invalidates build cache every time you make changes to anything inside it, effectively causing a clean build with every change)
Convention Plugins are Gradle’s way of sharing your build logic
between submodules and addressing the above concerns. - https://docs.gradle.org/current/samples/sample_convention_plugins.html
#### Java Plugin
has useful tasks like `build`, `clean`, `test`.
Build artifacts are placed under `build` directory.
Expects convention like `src/main/java` for prod/app code,
`src/test/java` for test code which form what is known as SourceSet.
#### Extra task properties
You can add your own properties to a task. To add a property named myProperty, set ext.myProperty to an initial value. From that point on, the property can be read and set like a predefined task property.
```groovy
task myTask {
ext.myProperty = "myValue"
}
task printTaskProperties {
doLast {
println myTask.myProperty
}
}
```
```sh
> gradle -q printTaskProperties
myValue
```
#### TaskContainer
A `TaskContainer` is responsible for managing a set of `Task` instances.
You can obtain a `TaskContainer` instance by calling `Project.getTasks()`, or using the tasks property in your build script.
#### Task Actions
A `Task` is made up of a sequence of `Action` objects. When the task is executed, each of the actions is executed in turn, by calling `Action.execute(T)`. You can add actions to a task by calling `doFirst(Action)` or `doLast(Action)`.
#### Task dependencies and execution
Callback available is `whenReady`.
`project.gradle.taskGraph.allTasks` is only ready after `whenReady`, because Task graph is populated in configuration phase.
Here is the correctway:
```groovy
project.gradle.taskGraph.whenReady {
taskGraph ->
println "whenReady closure cb!"
println taskGraph.allTasks
}
```
Another callbacks are `TaskGraph.beforeTask` and `TaskGraph.afterTask` which are called before and after every task. This is allowed to use during config phase, no need for whenReady.
`TaskGraph` has other useful propeties like
`allTasks` and `hasTask(taskName)` etc. which are recommended to use inside whenReady only.
```groovy
task doStartProcess {
doLast {
println "$name - Now starting process - OK"
}
}
task doStep2 {
doLast {
println "$name - Performed doStep2 OK"
}
}
task doSomethingInTheMiddle {
doLast {
println "$name - performed middleStep OK"
}
}
task doFinished (dependsOn: ['doSomethingInTheMiddle', 'doStep2']) {
doLast {
println "$name performed DONE OK"
}
}
println ">>>> ${project.tasks.findAll { task -> task.name.startsWith('do') } }"
if (project.hasProperty('doSomethingDependsOnDoStep2')) { // conditional task dependency
doSomethingInTheMiddle.dependsOn(doStartProcess, tasks.findAll { task -> task.name.startsWith('doStep2')})
}
```
### ScriptHandler
A ScriptHandler allows you to manage the compilation and execution of a build script. You can declare the classpath used to compile and execute a build script. This classpath is also used to load the plugins which the build script uses.
You can obtain a ScriptHandler instance using `Project.getBuildscript()` or `Script.getBuildscript()`.
### Gradle project
Project object is the default context in the build.gradle file.
There is 1 to 1 relationship between a gradle project and a build.gradle file.
Anything that is not defined in a buildscript is delegated to project object.
Standard properties include :
1. project - the Project instance
2. name - name of project directory
3. path - absolute path of project
4. description - string description of project
5. projectDir - the File dir containing buildscript
6. buildDir - projectDir/build
7. group,version - strings specifying group and version.
extra properties can be added in an ext block
e.g.
``` gradle
ext {
emailNotification="build@master.org"
}
```
### What is .gradle directory for?
For incremental build support partial builds (cached build related stuff), it is ok to delete it if needed.
### What is local.properties file for?
gradle gets the info from this file to locate the android sdk.
### What is gradle wrapper?
gradle wrapper is extra scripts along with project that manage the task of installing gradle to machine if it is not present. This is the recommended way to make your gradle project and should be commited to source control.
### What are gradle repositories?
Repositories are places to look for artifacts, or places to publish artifacts. They can be mainly of two types
1. Local file based - flatDir (less recommended)
2. Local repository based - local maven
3. external repository based - mavencentral or Jcenter.(highly recommended)
### How are dependencies grouped in gradle?
Gradle dependency groups are also known as 'configuration' which are mainly: compile, runtime, testCompile and testRuntime
### Gradle Dependency Configuraiton
Every dependency declared for a Gradle project applies to a specific scope.
For example some dependencies should be used for compiling source code whereas others only need to be available at runtime. Gradle represents the scope of a dependency with the help of a Configuration.
Some examples are: `testRuntime`, `implementation` etc.
### Well known configurations
#### `implementation`
The dependencies required to compile the production source of the project which are not part of the API exposed by the project. For example the project uses Hibernate for its internal persistence layer implementation.
#### `api`
The dependencies required to compile the production source of the project which are part of the API exposed by the project. For example the project uses Guava and exposes public interfaces with Guava classes in their method signatures.
#### `testImplementation`
The dependencies required to compile and run the test source of the project. For example the project decided to write test code with the test framework JUnit.
### How many types of dependency does gradle have?
1. external - living in a repository
e.g.
``` gradle
compile 'com.google.guava:guava:18.0
```
2. file based - dependency on files (e.g. jar files) living in a folder
e.g.
``` gradle
compile fileTree(dir: 'libs', include: '*.jar')
```
3. project based - a dependency on a gradle project (one that contains a build.gradle)
e.g.
``` gradle
compile project('sisterproject')
```
### How are transitive dependency conflict resolved in gradle?
By default gradle resolves conflict by using newest version.
### Multi project builds
By multi-project, we mean using other modules which have a build.gradle file hence the name multi-project build instead of mult-module build since there are multiple build.gradle files.
To define a multi project build you need to make a settings.gradle file.
By default android starts with a multi-project build in a freshly created application, with a sub-project corresponding to app/build.gradle
#### How many types of tasks are there?
There are two types of tasks:
1. Typed tasks // do not use doLast follow documentation of typed tasks instead.
2. Adhot tasks (ones with doLast in them)
### How gradle tasks work?
Note: just defining a task won't run it by itself, you have to put it somewhere in the build-pipline via dependsOn or explicitly run it from command line.
Before a task is executed for the first time, Gradle takes a snapshot of the inputs. This snapshot contains the paths of input files and a hash of the contents of each file. Gradle then executes the task. If the task completes successfully, Gradle takes a snapshot of the outputs. This snapshot contains the set of output files and a hash of the contents of each file. Gradle persists both snapshots for the next time the task is executed.
Each time after that, before the task is executed, Gradle takes a new snapshot of the inputs and outputs. If the new snapshots are the same as the previous snapshots, Gradle assumes that the outputs are up to date and skips the task. If they are not the same, Gradle executes the task. Gradle persists both snapshots for the next time the task is executed.
Gradle also considers the code of the task as part of the inputs to the task. When a task, its actions, or its dependencies change between executions, Gradle considers the task as out-of-date
### Gradle build lifecycle
All `.gradle` files under `$USER_HOME_DIR/.gradle/init.d` will be executed first.
If you setup some `ext` properties in these gradle files, they are available to all the projects etc. e.g. you can define a `timestamp` an other shared global util methods.
1. Initialization - settings.gradle and/or init.gradle runs - determination of projects to be taking part in
the build. Project instances created for each of the projects.
2. Configuration - build.gradle runs, You will be able to see `Configure Project:` on cli, task dependency resolved
3. Execution - task actions are run according to dependency graph
afterEvaluate {
}
is a useful debugging place that executes after configuration but before exection to inspect state.
### What is ext in gradle builds?
ext is shorthand for project.ext, and is used to define extra properties for the project object. (It's also possible to define extra properties for many other objects.) When reading an extra property, the ext. is omitted (e.g. println project.springVersion or println springVersion).
### What is the role of gradle.properties file?
populate properties to a project just like an ext block does, but if ext block is present with same property names, than ext block will take more priority/weightage over properties in gradle.properties.
A bunch of key-value pairs on each line, like an `ini` file, something similar to setting
env variables for your project.
Remember all gradle property values are read in as strings, so need to explicitly convert to intger wherver needed.
e.g
```properties
// gradle.properties
VERSION_CODE=2
```
```groovy
//build.gradle
android {
defaultConfig {
versionCode project.VERSION_CODE.toInteger()
}
}
```
### Where can gradle properties come from?
The can come from (last one wins/overrides previous ones):
1. `<prooject-root>/gradle.properties`
2. `<user-home>/gradle.properties`
3. command line using `-D` or `-P`
4. within code itself (via `project.prop=val` or `ext.prop=val` or `project.ext.prop=val`)
Gradle doesn’t provide any information on the source of a property.
Use `SomeObject.hasProperty(propname)` to avoid runtime exceptions.
Setting a project property via a system property
`org.gradle.project.foo=bar`
Setting a project property via an environment variable
`ORG_GRADLE_PROJECT_foo=bar`
### What is a gradle plugin?
Gradle plugin is just reusable peice of build logic, usually tasks and extensions to configure plugins/tasks.
Two ways to apply them:
1. by class name e.g. `apply plugin: GreetPlugin`
2. by plugin dsl based on `id` e.g.
```groovy
plugins {
id 'my-plugin'
}
```
### What is most common convention for java builds in gradle?
sources in src/main/java where src lives in project directory(same level as build.gradle)
and build outputs in
build/ dir.
### What are build types and product flavors/variants in gradle?
build types are usually developer centric e.g. debug, release
where as product flavors/variants are visible to end users
e.g. free/paid etc.
We can add our own build types using a buildTypes block e.g.
``` gradle
android {
buildTypes {
staging
}
}
```
The dimensionality is in particular order
:
1. src/test/androidTest
2. productFlavor
3. buildTypes
4. otherTypes
e.g.
mainFreeDebugMdpi
or
testPaidReleaseHdpi etc.
### gradle function syntax specifics
Now we will go through different ways to call method which accepts closure:
``` gradle
method accepts 1 parameter - closure
myMethod(myClosure)
if method accepts only 1 parameter - parentheses can be omitted
myMethod myClosure
I can create in-line closure
myMethod {println 'Hello World'}
method accepts 2 parameters
myMethod(arg1, myClosure)
or the same as '4', but closure is in-line
myMethod(arg1, { println 'Hello World' })
if last parameter is closure - it can be moved out of parentheses
myMethod(arg1) { println 'Hello World' }
At this point I really have to point your attention to example #3 and #6. Doesn't it remind you something from gradle scripts?
```
Summary : Each closure has a delegate object, which groovy uses to lookup (free)variable & method references, this is usally known as environment, context etc. in other functional languages, where usually it is lexical, but in groovy it can be explicitly set.
### Writing your own plugin
https://www.youtube.com/watch?v=LPzBVtwGxlo&list=RDCMUCVHFbqXqoYvEWM1Ddxl0QDg&index=8
https://www.youtube.com/watch?v=TfdiiYHWFTw
https://www.youtube.com/watch?v=dLERr-MNPQo
Usually you will :
1. create tasks of tis plugin
2. Create extensions
3. hook this plugins task to build chain (if you want to implicitly hook tasks).
`buildSrc` way: Create a new directory known as `buildSrc` where you put your custom tasks/plugins code. This project is automatically included in build.
standalone project way: publish a standalone project and then apply via id, this way we must import plugin as dependency or via `includeBuild`, or via `pluginManagement`.
#### Defining plugin via class (in groovy) and applied via 'apply'
```groovy
class MyPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
// do something with the project, maybe add some tasks that correspond to MyPlugin?
project.task("playme") {
doLast {
println "played something::"
}
}
}
}
```
another one
```groovy
// build.gradle
class GreetingPlugin implements Plugin<Project> {
void apply(Project project) {
project.task('hello') {
doLast {
println 'Hello from the GreetingPlugin'
}
}
}
}
// Apply the plugin
apply plugin: GreetingPlugin // applying plugin by class name
```
#### Making plugins configurable
Most plugins offer some configuration options for build scripts and other plugins to use to customize how the plugin works. **Plugins do this using extension objects**.
The Gradle `Project` has an associated `ExtensionContainer` object that contains all the settings and properties for the plugins that have been applied to the project.
**An extension object is simply an object with Java Bean properties that represent the configuration.**
```groovy
abstract class GreetingPluginExtension {
abstract Property<String> getMessage()
GreetingPluginExtension() {
message.convention('Hello from GreetingPlugin')
}
}
class GreetingPlugin implements Plugin<Project> {
void apply(Project project) {
// Add the 'greeting' extension object
def extension = project.extensions.create('greeting', GreetingPluginExtension)
// Add a task that uses configuration from the extension object
project.task('hello') {
doLast {
println extension.message.get()
}
}
}
}
apply plugin: GreetingPlugin
// Configure the extension
greeting.message = 'Hi from Gradle'
```
### buildSrc
A directory in your code where you can move all common build logic (e.g. tasks definition etc) and
share this build logic between many modules.
### Gradle custom plugin as standalone project
we can publish it and share it with others.
Use `java-gradle-plugin` for development assistance of gradle plugins.
For this particular project, one will need following gradle build file: `build.gradle`:
```groovy
plugins {
id 'java-gradle-plugin' // development purposes, use groovy-gradle-plugin if project in groovy
id 'maven-publish' // to publish
}
gradlePlugin {
plugins {
simplePlugin { // what is this?
id = 'org.example.greeting' // id defined here explicitly
implementationClass = 'org.example.GreetingPlugin' // gradle needs this to find class for given id
}
}
}
```
specify plugin-id: Your plugin id should be a combination of components that reflect namespace (a reasonable pointer to you or your organization) and the name of the plugin it provides.
If you are interested in publishing your plugin to be used by the wider Gradle community, **you can publish it to the Gradle Plugin Portal**.
If you have published your plugin to custom non-standard location, not the gradle plugin portal then `pluginManagement` block will be needed in `settings.gradle` of the consuming application.
### Precompiled script plugins
Script plugins are basically just plain old Gradle build scripts with a different name.
Precompiled script plugins are compiled into class files and packaged into a jar.
**For all intents and purposes, they are binary plugins and can be applied by plugin ID, tested and published as binary plugins**
To apply a precompiled script plugin, you need to know its `ID which is derived from the plugin script’s filename (minus the .gradle extension).`
For example, the script `src/main/groovy/java-library-convention.gradle` would have a plugin ID of `java-library-convention`.
Likewise, `src/main/groovy/my.java-library-convention.gradle` would result in a plugin ID of `my.java-library-convention`
In addition to plugins written as standalone projects, Gradle also allows you to provide build logic written in either Groovy or Kotlin DSLs as precompiled script plugins. You write these as `*.gradle` files in `src/main/groovy` directory or `*.gradle.kts` files in `src/main/kotlin` directory.
An example of how to have this:
1. create a `buildSrc` project
2. This project's `build.gradle` must contain a dev plugin: `groovy-gradle-plugin`
3. Create a file: `buildSrc/src/main/groovy/java-library-convention.gradle`.
4. Contents of `java-library-convention.gradle`:
```groovy
/**
Note that this will actually apply the plugins to the main project, i.e. the one that applies the precompiled script plugin */
plugins {
id 'java-library'
id 'checkstyle'
}
java {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
checkstyle {
maxWarnings = 0
// ...
}
tasks.withType(JavaCompile) {
options.warnings = true
// ...
}
dependencies {
testImplementation("junit:junit:4.13")
// ...
}
```
5. finally use this custom plugin by id i.e. filename minus (.gradle)
IN other projects:
```groovy
plugins {
id 'java-library-convention'
}
```
|
Java
|
UTF-8
| 2,863
| 1.835938
| 2
|
[] |
no_license
|
package org.wf.dp.dniprorada.engine.task;
import java.util.ArrayList;
import java.util.List;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.form.StartFormData;
import org.activiti.redis.model.ByteArrayMultipartFile;
import org.activiti.redis.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.wf.dp.dniprorada.base.model.AbstractModelTask;
import org.wf.dp.dniprorada.model.BuilderAtachModel;
/**
*
* @author inna
*
*/
@Component("fileTaskUpload")
public class FileTaskUpload extends AbstractModelTask implements JavaDelegate {
static final transient Logger LOG = LoggerFactory
.getLogger(FileTaskUpload.class);
public static final String BUILDER_ATACH_MODEL_LIST = "builderAtachModel";
@Autowired
RedisService redisService;
@Override
public void execute(DelegateExecution execution) throws Exception {
StartFormData startformData = execution.getEngineServices()
.getFormService()
.getStartFormData(execution.getProcessDefinitionId());
List<String> filedTypeFile = getListFieldCastomTypeFile(startformData);
List<String> listValueKeys = getValueFieldWithCastomTypeFile(execution,
filedTypeFile);
List<BuilderAtachModel> listModel = new ArrayList<BuilderAtachModel>();
if (!listValueKeys.isEmpty()) {
for (String keyRedis : listValueKeys) {
if (keyRedis != null && !keyRedis.isEmpty()) {
byte[] byteFile = getRedisService().getAttachments(keyRedis);
ByteArrayMultipartFile contentMultipartFile = getByteArrayMultipartFileFromRedis(byteFile);
if (contentMultipartFile != null) {
String outFilename = null;
try {
outFilename = new String(contentMultipartFile
.getOriginalFilename().getBytes("ISO-8859-1"), "UTF-8");
} catch (java.io.UnsupportedEncodingException e) {
throw new ActivitiException(e.getMessage(), e);
}
BuilderAtachModel builderAtachModel = new BuilderAtachModel();
builderAtachModel
.setByteToStringContent(contentByteToString(contentMultipartFile
.getBytes()));
builderAtachModel.setContentType(contentMultipartFile
.getContentType());
builderAtachModel.setExp(contentMultipartFile.getExp());
builderAtachModel
.setOriginalFilename(outFilename);
builderAtachModel.setName(contentMultipartFile
.getName());
listModel.add(builderAtachModel);
}
}
}
}
if (!listModel.isEmpty()) {
execution.setVariable(BUILDER_ATACH_MODEL_LIST, listModel);
}
}
public RedisService getRedisService() {
return redisService;
}
}
|
Java
|
UTF-8
| 909
| 3.21875
| 3
|
[] |
no_license
|
import java.util.Random;
public class Asteroid extends SpaceObject implements Destroy {
private char classOfAsteroid;
public char getClassOfAsteroid() {
return classOfAsteroid;
}
public void setClassOfAsteroid(char classOfAsteroid) {
this.classOfAsteroid = classOfAsteroid;
}
public void toBeDestroyed() {
System.out.println("Asteroid is destroyed");
}
public void toOrbiting() {
System.out.println("Asteroid is orbiting");
}
@Override
public String toString() {
return "Asteroid{" +
"classOfAsteroid=" + classOfAsteroid +
'}';
}
public void generateRandomAsteroid() {
Random asteroidRandom = new Random();
char[] classArray = {'a', 'b', 'c', 'd'};
int charVar = asteroidRandom.nextInt(3);
this.setClassOfAsteroid(classArray[charVar]);
}
}
|
Java
|
UTF-8
| 24,355
| 2.203125
| 2
|
[] |
no_license
|
package com.yzh.smartsmoking.activity;
/**
* Created by appadmin on 2017/8/30.
* 设置页面
*/
//public class SettingActivity extends BaseActivity implements View.OnClickListener {
// private HeaderRightImageView header_activity_setting;
// private LinearLayout ll_setting_power, ll_daily_mouth;
// private TextView tv_setting_power, tv_daily_mouth;
//
// private AlertDialog powerSetDialog, planMouthDialog;
// private TextView tvStepCancel, tvStepSure;
// private TextView tvPlanMouthCancel, tvPlanMouthSure;
//
// private SelectView selectview_current_power;
//
// private ListView lv_power_setting; //功率设置自定义ListView
// private PowerSettingAdapter powerSettingAdapter;
// private List<String> powerValueList = new ArrayList<>();
// private String[] strs = {"5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"};
// private int powerClickPosition = -1;
//
// private byte[] setPowerValue = new byte[4];
// private boolean needRead = false;
//
// private byte[] getPowerValue = {(byte) 0xf2,0x04,0x00,0x01,0x01, (byte) 0xf6};
//
// public byte[] startSmoke = {(byte) 0xf2,0x01,0x00,0x01,0x01, (byte) 0xf3};
// public byte[] stopSmoke = {(byte) 0xf2,0x01,0x00,0x01,0x00, (byte) 0xf2};
//
//
// private SelfListview lv_plan_mouth; //计划吸烟口数 设置自定义ListView
// private PlanMouthAdapter planMouthAdapter;
// private List<String> planMouthList = new ArrayList<>();
// private String[] mouthstrs = {"50", "100", "200"};
// private int planMouthClickPosition = -1;
//
// OutputStream mOutputStream;
// InputStream mInputStream;
// SerialPort sp;
// // SendThread mSendThread;
// ReadThread mReadThread;
//
// @Override
// protected int getActivityContentId() {
// return R.layout.activity_setting;
// }
//
// @Override
// protected void initView() {
// header_activity_setting = findViewByIds(R.id.header_activity_setting);
// ll_setting_power = findViewByIds(R.id.ll_setting_power);
// ll_setting_power.setOnClickListener(this);
// ll_daily_mouth = findViewByIds(R.id.ll_daily_mouth);
// ll_daily_mouth.setOnClickListener(this);
// tv_setting_power = findViewByIds(R.id.tv_setting_power);
// tv_setting_power.setText(PreferenceData.loadPowerValue(context) + " " + getResources().getString(R.string.smoke_power_unit));
// tv_daily_mouth = findViewByIds(R.id.tv_daily_mouth);
// tv_daily_mouth.setText(PreferenceData.loadCpbCountNum(context) + " " + getResources().getString(R.string.mouth));
// selectview_current_power = findViewByIds(R.id.selectview_current_power);
// selectview_current_power.setOnClickListener(this);
//
//// sp = getSerialPort();
//// mOutputStream = sp.getOutputStream();
//// mInputStream = sp.getInputStream();
//
// mReadThread = new ReadThread();
// mReadThread.start();
//
//
// powerSetDialog = new AlertDialog.Builder(context).setView(R.layout.dialog_power_setting).create();
// planMouthDialog = new AlertDialog.Builder(context).setView(R.layout.dialog_plan_mouth).create();
// if (powerValueList.size() > 0) {
// powerValueList.clear();
// }
// if (planMouthList.size() > 0) {
// planMouthList.clear();
// }
// //功率设置数据源
// for (int i = 0; i < strs.length; i++) {
// powerValueList.add(strs[i]);
// }
//
// //吸烟口数数据源
// for (int i = 0; i < mouthstrs.length; i++) {
// planMouthList.add(mouthstrs[i]);
// }
//
// }
//
// @Override
// protected void initEvent() {
// header_activity_setting.setOnHeaderClickListener(new HeaderRightImageView.clickHeaderListener() {
// @Override
// public void onClickLeftIcon() {
// finish();
// }
//
// @Override
// public void onClickRightIcon(View view) {
//
// }
// });
// }
//
// @Override
// protected void loadDatas() {
//
// }
//
// @Override
// public void onClick(View v) {
// switch (v.getId()) {
// case R.id.ll_setting_power:
// showPowerSettingDialog();
// break;
//
// case R.id.ll_daily_mouth:
//// onSmokingMouthPicker();
// showPlanMouthDialog();
// break;
//
// case R.id.selectview_current_power:
//// needRead = true;
//// writeSmokeData(getPowerValue);
// break;
// }
// }
//
//
// //show出 每天吸烟口数的Dialog
// private void showPlanMouthDialog() {
// planMouthDialog.show();
// //设置dialog的样式属性
// Window dialogView = planMouthDialog.getWindow();
// int width = getResources().getDisplayMetrics().widthPixels;
// WindowManager.LayoutParams lp = dialogView.getAttributes();
//// dialogView.setBackgroundDrawableResource(android.R.color.transparent);
//// dialogView.setBackgroundDrawable(ContextCompat.getDrawable(context,R.color.transparent));
// dialogView.setBackgroundDrawable(new BitmapDrawable());
// lp.width = width - 160;
// lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
// // lp.height = height / 3;
// lp.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER;
// //lp.x = 100;
//// lp.y = -300;
// dialogView.setAttributes(lp);
//
// lv_plan_mouth = (SelfListview) planMouthDialog.findViewById(R.id.lv_plan_mouth_num);
// planMouthAdapter = new PlanMouthAdapter(context);
// lv_plan_mouth.setAdapter(planMouthAdapter);
// planMouthAdapter.setDatas(planMouthList);
//
//
// tvPlanMouthCancel = (TextView) planMouthDialog.findViewById(R.id.tv_dlg_plan_mouth_cancel);
// tvPlanMouthSure = (TextView) planMouthDialog.findViewById(R.id.tv_dlg_plan_mouth_sure);
//
// lv_plan_mouth.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// planMouthClickPosition = position;
// planMouthAdapter.setSelectItem(position);
// planMouthAdapter.notifyDataSetChanged();
// }
// });
//
// tvPlanMouthCancel.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// planMouthDialog.dismiss();
// }
// });
// tvPlanMouthSure.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// //(关闭)确定
// if (planMouthClickPosition != -1) {
// tv_daily_mouth.setText(planMouthList.get(planMouthClickPosition) + " " + getResources().getString(R.string.mouth));
// if (Integer.parseInt(planMouthList.get(planMouthClickPosition)) != PreferenceData.loadCpbCountNum(context)) {
//// int va = Integer.parseInt(planMouthList.get(planMouthClickPosition));
//// int va2 = PreferenceData.loadCpbCountNum(context);
// PreferenceData.saveCpbCountNum(context, Integer.parseInt(planMouthList.get(planMouthClickPosition)));
//
// EventBusMsg eventBusMsg = new EventBusMsg();
// eventBusMsg.setMsgType(EventBusMsg.MSG_REFRESH_CQB_VALUE);
// EventBus.getDefault().post(eventBusMsg);
//
//
// }
//
// planMouthDialog.dismiss();
// } else {
// ToastUtils.showTextToast(context, getResources().getString(R.string.toast_plan_mouth));
// }
//
// }
// });
// planMouthDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
// @Override
// public void onDismiss(DialogInterface dialog) {
// if (planMouthClickPosition != -1) {
// planMouthClickPosition = -1;
// }
// }
// });
// }
//
// //show出 功率设置的Dialog
// private void showPowerSettingDialog() {
// powerSetDialog.show();
// //设置dialog的样式属性
// Window dialogView = powerSetDialog.getWindow();
// int width = getResources().getDisplayMetrics().widthPixels;
// WindowManager.LayoutParams lp = dialogView.getAttributes();
//// dialogView.setBackgroundDrawableResource(android.R.color.transparent);
//// dialogView.setBackgroundDrawable(ContextCompat.getDrawable(context,R.color.transparent));
// dialogView.setBackgroundDrawable(new BitmapDrawable());
// lp.width = width - 160;
// lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
// // lp.height = height / 3;
// lp.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER;
// //lp.x = 100;
//// lp.y = -300;
// dialogView.setAttributes(lp);
//
// lv_power_setting = (ListView) powerSetDialog.findViewById(R.id.lv_power_setting);
// powerSettingAdapter = new PowerSettingAdapter(context);
// lv_power_setting.setAdapter(powerSettingAdapter);
// powerSettingAdapter.setDatas(powerValueList);
//
//
// tvStepCancel = (TextView) powerSetDialog.findViewById(R.id.tv_dlg_step_cancel);
// tvStepSure = (TextView) powerSetDialog.findViewById(R.id.tv_dlg_step_sure);
//
// lv_power_setting.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// powerClickPosition = position;
// powerSettingAdapter.setSelectItem(position);
// powerSettingAdapter.notifyDataSetChanged();
// }
// });
//
// tvStepCancel.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// powerSetDialog.dismiss();
// }
// });
// tvStepSure.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// //(关闭)确定
// if (powerClickPosition != -1) {
//// tv_setting_power.setText(powerValueList.get(powerClickPosition) + " " + getResources().getString(R.string.smoke_power_unit));
// int powerValue = Integer.parseInt(powerValueList.get(powerClickPosition));
// if (powerValue != PreferenceData.loadPowerValue(context)) {
//// PreferenceData.savePowerValue(context, Integer.parseInt(powerValueList.get(powerClickPosition)));
//
//// EventBusMsg eventBusMsg = new EventBusMsg();
//// eventBusMsg.setMsgType(EventBusMsg.MSG_REFRESH_POWER_VALUE);
//// EventBus.getDefault().post(eventBusMsg);
//
// String s = Integer.toHexString(powerValue);
// if (s.length() == 1) {
// s = "0" + s;
// }
// byte[] bytes1 = FormatTransfer.hexStringToBytes(s);
//// setPowerValue[0] = (byte) 0xf2;
// setPowerValue[0] = 0x02;
// setPowerValue[1] = 0x00;
// setPowerValue[2] = 0x01;
// setPowerValue[3] = bytes1[0];
//
//
// byte[] btPowerValue = new byte[6];
// System.arraycopy(setPowerValue, 0, btPowerValue, 1, setPowerValue.length);
//
// byte[] encryptValue = getEncryptValue(setPowerValue);
// btPowerValue[0] = (byte) 0xf2;
// btPowerValue[5] = encryptValue[encryptValue.length - 1]; //将异或数放在数组的第6位
//
//// needRead = true;
// writeSmokeData(btPowerValue);
//
//// mSendThread = new SendThread();
//// mSendThread.start();
// }
//
// powerSetDialog.dismiss();
// } else {
// ToastUtils.showTextToast(context, getResources().getString(R.string.toast_power_choice));
// }
// }
// });
// powerSetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
// @Override
// public void onDismiss(DialogInterface dialog) {
// if (powerClickPosition != -1) {
// powerClickPosition = -1;
// }
// }
// });
// }
//
// private void writeSmokeData(byte[] smokeData) {
// try {
// needRead = true;
// mOutputStream.write(smokeData);
// try {
// Thread.sleep(500);
// sendSmokeData(getPowerValue); //获取功率值
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// } catch (IOException e) {
// e.printStackTrace();
// }
//// for (int i = 0; i < smokeData.length; i++) {
//// try {
//// mOutputStream.write(smokeData[i]);
//// } catch (IOException e) {
//// e.printStackTrace();
//// }
//// }
// }
//
// private void sendSmokeData(byte[] getPowerData) {
// try {
// needRead = true;
// mOutputStream.write(getPowerData);//获取功率值
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
//
//// public String m_strBaud = "";
//// public String m_strPort = "";
//
// public SerialPort getSerialPort() {
// if (sp == null) {
//
//// String str = "/dev/ttyMT1";
// String str = "/dev/ttyS1";
// int i = 115200;
//// int i = 57600;
//// m_strPort = str;
//// m_strBaud = i + "";
// if ((str.length() == 0) || (i == -1))
// throw new InvalidParameterException();
// try {
// sp = new SerialPort(new File(str), i, 0);
// } catch (SecurityException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// return sp;
// }
//
//
//// private class ReadThread extends Thread {
//// @Override
//// public void run() {
//// super.run();
//// try {
//// while (needRead) {
//// if (mInputStream == null)
//// return;
//// int count = 6;
//// byte[] buffer = new byte[count];//4位帧控制,第4位是帧长度,
//// int availableCount = 0;
//// int offset;
//// if (mInputStream.available() >= 4) {
//// int nContnetCount;
//// mInputStream.read(buffer, 0, 1);
//// if (buffer[0] != (byte) 0xF2) // header is not correct, abandoned
//// {
//// continue;
//// } else {
//// mInputStream.read(buffer, 0, 2);
//// if (buffer[0] != (byte) 0xF2) {
//// if (buffer[0] == (byte) 0xF2 && buffer[1] == (byte) 0x04) {
//// mInputStream.read(buffer, 0, 2);
//// nContnetCount = (int) (buffer[1]) + 3;
//// offset = 5;
//// } else {
//// continue;
//// }
//// } else {
//// mInputStream.read(buffer, 0, 1);
//// nContnetCount = (int) (buffer[0]) + 3;
//// offset = 4;
//// }
////
//// }
//// if (nContnetCount <= 0) {
//// continue;
//// }
////
//// byte[] bufferContent = new byte[nContnetCount];//4位帧控制,第4位是帧长度,3位帧校验,其他为帧数据长度
//// while (availableCount < nContnetCount + offset) {
//// availableCount = mInputStream.available();
//// }
//// mInputStream.read(bufferContent, 0, nContnetCount);
////
//// onDataReceived(bufferContent, nContnetCount);
//// }
//// Thread.sleep(10);
//// }
//// } catch (Exception e) {
//// e.printStackTrace();
//// }
////
//// }
//// }
//
//
//// private class SendThread extends Thread {
//// @Override
//// public void run() {
//// super.run();
////// byte[] bCommand = new byte[]{0x25, 0x01, 0x01, 0x00};
//// int powerValue = PreferenceData.loadPowerValue(context);
//// byte[] bCommand = new byte[15];
//// bCommand[0] = (byte) 0xf2;
//// bCommand[1] = 0x31;
//// bCommand[2] = 0x00;
//// bCommand[3] = 0x0b;
//// bCommand[4] = 0x01;
////// byte[] bCommand = new byte[]{(byte)0xF2, 0x31, 0x00, 0x0b, 0x01, (byte) (powerValue*10), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//// byte[] powerBytes = FormatTransfer.toHH((short) (powerValue * 10));
//// System.arraycopy(powerBytes, 0, bCommand, 5, powerBytes.length); //将功率算出放在第6,第7位
////
////
//// byte[] byt = new byte[16];
//// System.arraycopy(bCommand, 0, byt, 0, bCommand.length);
////
//// byte[] encryptValue = getEncryptValue(bCommand);
//// byt[15] = encryptValue[encryptValue.length - 1]; //将异或数放在数组的第16位
////
//// try {
//// mOutputStream.write(byt);
//// } catch (IOException e) {
//// e.printStackTrace();
//// }
////
//// }
//// }
//
//
// private class ReadThread extends Thread {
// @Override
// public void run() {
// super.run();
//// while (!isInterrupted()) {
//// ReadSerialData();
//// }
// while (!isInterrupted()){
// if (needRead) {
// ReadSerialData();
// }
// }
// }
// }
//
//
// private int j = 0;
// private void ReadSerialData() {
// int size;
// try {
// byte[] buffer = new byte[]{0, 0, 0, 0, 0, 0};
// if (mInputStream == null)
// return;
//
// /*
// * if (i == 5) { i = 0; } while (i < 5) { buffer[i] = (byte)
// * mInputStream.read(); i++; }
// */
// //Log.d("zhantaiming", "11111==");
// while (j < 1) {
// buffer[j] = (byte) mInputStream.read();
// //Log.d("zhantaiming", "11111=="+dumpBytes(buffer[j],1));
//
// if (((buffer[j] & 0xff)) != 0XF2) {
// return;
// }
// j++;
// }
// while (j < 2) {
// buffer[j] = (byte) mInputStream.read();
// //Log.d("zhantaiming", "11111=="+dumpBytes(buffer[j],1));
//
// if (((int) (buffer[j] & 0xff)) != 0X05) {
// return;
// }
// j++;
// }
// while (j < 6) {
// buffer[j] = (byte) mInputStream.read();
// //Log.d("zhantaiming", "11111==");
// j++;
// }
//
// if (j > 0)
// onDataReceived(buffer, 6);
// else {
// j = 0;
// return;
// }
//
// j = 0;
//
//
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// }
//
//// private void onDataReceived(byte[] buffer, int size) {
////
//// String str = FormatTransfer.BytesToString(buffer, size);
//// byte[] byrssi = new byte[]{buffer[2]};
//// Integer.parseInt(FormatTransfer.BytesToString(byrssi).trim(), 16);
////
//// byte[] bytes = new byte[]{buffer[4], buffer[5], buffer[6], buffer[7]};
//// final long cardNo = FormatTransfer.bytesToLong(bytes);
//
//// }
//
//
// private void onDataReceived(final byte[] buffer, final int size) {
//
// runOnUiThread(new Runnable() {
//
// public void run() {
//
// byte[] currentpower = new byte[1];
// currentpower[0] = buffer[4];
// int lenght = currentpower.length;
// String powerValue = dumpBytes(currentpower, lenght);
//
// selectview_current_power.setContent("当前功率" + " " + powerValue + "W");
//
// PreferenceData.savePowerValue(context, Integer.parseInt(powerValue));
// tv_setting_power.setText(PreferenceData.loadPowerValue(context) + " " + getResources().getString(R.string.smoke_power_unit));
//
//
// EventBusMsg eventBusMsg = new EventBusMsg();
// eventBusMsg.setMsgType(EventBusMsg.MSG_REFRESH_POWER_VALUE);
// EventBus.getDefault().post(eventBusMsg);
//
// needRead = false;
//
// }
// });
// }
//
// public String dumpBytes(byte[] bytes, int size) {
// int i;
// StringBuffer sb = new StringBuffer();
// String s;
// for (i = 0; i < size; i++) {
// /*
// * if (i % 32 == 0 && i != 0) { sb.append(" \n "); }
// */
// int data = (int) (bytes[i] & 0xff);
// //s = Integer.toHexString(data);
// s = Integer.toString(data);
// //if (s.length() < 2) {
// // s = "0" + s;
// //}
// /*
// * if (s.length() > 2) { s = s.substring(s.length() - 2); }
// */
// sb.append(s);
// }
// return sb.toString();
// }
//
//
// //循环异或加密
// public byte[] getEncryptValue(byte[] bytes) {
// if (bytes == null) {
// return null;
// }
// int len = bytes.length;
// int key = 0xF2;
// for (int i = 0; i < len; i++) {
// bytes[i] = (byte) (bytes[i] ^ key);
// key = bytes[i];
// }
// return bytes;
// }
//
//// private class SendSettingThread extends Thread {
//// @Override
//// public void run() {
//// super.run();
//// byte b = FormatTransfer.toLH(regionNum)[0];
//// byte[] bCommand = new byte[]{0x29, 0x00, 0x01, b};
//// sendFilterData(bCommand);
//// }
//// }
//
// public void closeSerialPort() {
// if (this.sp != null) {
// this.sp.close();
// this.sp = null;
// }
// }
//
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// if (powerValueList != null) {
// powerValueList.clear();
// }
//
// if (planMouthList != null) {
// planMouthList.clear();
// }
//
//
// if (mReadThread != null) {
// mReadThread.interrupt();
// closeSerialPort();
// }
//// if (mSendThread != null) {
//// mSendThread.interrupt();
//// }
//
// }
//}
|
Python
|
UTF-8
| 151
| 3.90625
| 4
|
[] |
no_license
|
num=int(input("Enter the number "))
reverse=0
while num>0:
remainder=num%10
reverse=(reverse*10)+remainder
num=num//10
print(str(reverse))
|
PHP
|
UTF-8
| 2,422
| 2.890625
| 3
|
[] |
no_license
|
<?php
/**
* Trans Class
* Created by Warner Infinity
* Author Jules Warner
*/
class WILang
{
function __construct()
{
$this->WIdb = WIdb::getInstance();
}
public static function all($jsonEncode = true) {
// determine lanuage
$language = self::getLanguage();
//echo $language;
// get translation for determined language
$trans = WILang::getTrans($language);
if ( $jsonEncode )
return json_encode($trans);
else
return $trans;
}
public static function get($key ) //, $bindings = array()
{
// determine language
$language = self::getLanguage();
$result = $this->WIdb->select("SELECT * FROM `wi_trans` WHERE `keyword`=:key",
array(
"key" => $key
));
if($result[0] > 0)
return $result[0]['translation'];
else
return '';
}
public static function setLanguage($language)
{
// check if language is valid
if ( self::isValidLanguage($language) ) {
//set language cookie to 1 year
setcookie('wi_lang', $language, time() + 60 * 60 * 24 * 365, '/');
// update session
WISession::set('wi_lang', $language);
//refresh the page
header('Location: ' . $_SERVER['PHP_SELF']);
}
}
public static function getLanguage()
{
// check if cookie exist and language value in cookie is valid
if ( isset ( $_COOKIE['wi_lang'] ) && self::isValidLanguage ( $_COOKIE['wi_lang'] ) )
return $_COOKIE['wi_lang']; // return lang from cookie
else
return WISession::get('wi_lang', DEFAULT_LANGUAGE);
}
private static function getTrans($language)
{
if ( ! self::isValidLanguage($language) )
die('Language file doesn\'t exist!');
else {
$result = $this->WIdb->select("SELECT * FROM `wi_trans` WHERE `lang` = :file",
array(
"file" => $language
));
foreach ($result as $key => $value) {
echo '"' .$value['keyword'] .'"=>"' . $value['translation'] . '",';
}
}
}
private static function getFile($language)
{
$result = $this->WIdb->select("SELECT * FROM `wi_lang` WHERE `lang` = :file",
array(
"file" => $language
));
if ($result[0] > 0)
return $result[0]['lang'];
else
return null;
}
private static function isValidLanguage($lang)
{
$file = self::getFile($lang);
if($file == "null")
return false;
else
return true;
}
}
|
C#
|
UTF-8
| 2,261
| 2.53125
| 3
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/* Used to define the type of node */
public enum NodeType {
movie = 0,
budget = 1,
genre = 2,
productionCompany = 3,
data = 4,
homepage = 5,
id = 6,
keywords = 7,
originalLanguage = 8,
originalTitle = 9,
overview = 10,
popularity = 11,
productionCompanies = 12,
productionCountries = 13,
releaseDate = 14,
revenue = 15,
runtime = 16,
spokenLanguages = 17,
status = 18,
tagline = 19,
voteAverage = 20,
voteCount = 21,
custom = 22,
// Feel free to add more to this list. ~Brandon
}
public static class NodeTypeMethods {
private static Color[] colors = {
new Color(128f/255f, 128f/255f, 128f/255f), // Documentary
new Color(255f/255f, 255f/255f, 025f/255f), // Crime
new Color(128f/255f, 128f/255f, 000f/255f), // History
new Color(245f/255f, 130f/255f, 048f/255f), // Family
new Color(230f/255f, 190f/255f, 255f/255f), // Mystery
new Color(240f/255f, 050f/255f, 230f/255f), // Comedy
new Color(000f/255f, 130f/255f, 200f/255f), // Animation
new Color(000f/255f, 000f/255f, 000f/255f), // None
new Color(210f/255f, 245f/255f, 060f/255f), // Thriller
new Color(070f/255f, 240f/255f, 240f/255f), // Action
new Color(000f/255f, 000f/255f, 128f/255f), // Science Fiction
new Color(230f/255f, 025f/255f, 075f/255f), // Horror
new Color(000f/255f, 128f/255f, 128f/255f), // Adventure
new Color(250f/255f, 190f/255f, 190f/255f), // Romance
new Color(170f/255f, 170f/255f, 040f/255f), // Western
new Color(255f/255f, 250f/255f, 200f/255f), // TVMovie
new Color(145f/255f, 030f/255f, 180f/255f), // Music
new Color(255f/255f, 215f/255f, 180f/255f), // Drama
new Color(170f/255f, 255f/255f, 195f/255f), // Foriegn
new Color(000f/255f, 000f/255f, 000f/255f), // None
new Color(060f/255f, 180f/255f, 075f/255f), // Fantasy
new Color(128f/255f, 000f/255f, 000f/255f), // War
new Color(123f/255f, 1f, 1f)
};
public static Color getColor(this NodeType t) {
return colors[(int) t];
}
}
|
C#
|
UTF-8
| 9,101
| 3.046875
| 3
|
[] |
no_license
|
using System;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Numerics;
namespace FFTTools
{
/// <summary>
/// FFT((f,g)) = FFT(fxg') = FFT(f)*FFT(g)' = FFT(f)*BFT(g)
/// (a*f+b*g,h) = a*(f,h)+b*(g,h)
/// (f,g)=(g,f)'
/// </summary>
public class ScalarBuilder : BuilderBase, IBuilder
{
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
}
public Bitmap ToBitmap(Bitmap source)
{
throw new NotImplementedException();
}
/// <summary>
/// Calculate function self-scalar values
/// </summary>
/// <param name="f">Input values</param>
/// <param name="ff">Output values</param>
public static void Scalar(double[] f, double[] ff)
{
int length = ff.Length;
double[] doubles = f.Concat(Enumerable.Repeat(0.0, length - f.Length)).ToArray();
Complex[] complex = doubles.Select(x => new Complex(x, 0)).ToArray();
Fourier(complex, FourierDirection.Forward);
complex = complex.Select(x => x*Complex.Conjugate(x)/length).ToArray();
Fourier(complex, FourierDirection.Backward);
doubles = complex.Select(x => x.Real).ToArray();
Array.Copy(doubles, 0, ff, 0, length);
}
/// <summary>
/// Calculate function self-scalar values
/// </summary>
/// <param name="f">Input values</param>
/// <param name="ff">Output values</param>
public static void Scalar(Complex[] f, Complex[] ff)
{
int length = ff.Length;
Complex[] complex = f.Concat(Enumerable.Repeat(Complex.Zero, length - f.Length)).ToArray();
Fourier(complex, FourierDirection.Forward);
complex = complex.Select(x => x*Complex.Conjugate(x)/length).ToArray();
Fourier(complex, FourierDirection.Backward);
Array.Copy(complex, 0, ff, 0, length);
}
/// <summary>
/// Calculate scalar values
/// </summary>
/// <param name="f">Input values</param>
/// <param name="g">Input values</param>
/// <param name="fg">Output values</param>
public static void Scalar(double[] f, double[] g, double[] fg)
{
int length = fg.Length;
double[] doubles = f.Concat(Enumerable.Repeat(0.0, length - f.Length)).ToArray();
Complex[] complex = doubles.Select(x => new Complex(x, 0)).ToArray();
Fourier(complex, FourierDirection.Forward);
doubles = g.Concat(Enumerable.Repeat(0.0, length - g.Length)).ToArray();
Complex[] complex1 = doubles.Select(x => new Complex(x, 0)).ToArray();
Fourier(complex1, FourierDirection.Backward);
int index = 0;
foreach (Complex value in complex1)
complex[index++] *= value/length;
Fourier(complex, FourierDirection.Backward);
doubles = complex.Select(x => x.Real).ToArray();
Array.Copy(doubles, 0, fg, 0, length);
}
/// <summary>
/// Calculate scalar values
/// </summary>
/// <param name="f">Input values</param>
/// <param name="g">Input values</param>
/// <param name="fg">Output values</param>
public static void Scalar(Complex[] f, Complex[] g, Complex[] fg)
{
int length = fg.Length;
Complex[] complex = f.Concat(Enumerable.Repeat(Complex.Zero, length - f.Length)).ToArray();
Fourier(complex, FourierDirection.Forward);
Complex[] complex1 = g.Concat(Enumerable.Repeat(Complex.Zero, length - g.Length)).ToArray();
Fourier(complex1, FourierDirection.Backward);
int index = 0;
foreach (Complex value in complex1)
complex[index++] *= value/length;
Fourier(complex, FourierDirection.Backward);
Array.Copy(complex, 0, fg, 0, length);
}
/// <summary>
/// Calculate scalar values
/// </summary>
/// <param name="n0">Array size</param>
/// <param name="n1">Array size</param>
/// <param name="n2">Array size</param>
/// <param name="f">Input values</param>
/// <param name="g">Input values</param>
/// <param name="fg">Output values</param>
public static void Scalar(int n0, int n1, int n2, double[] f, double[] g, double[] fg)
{
Debug.Assert(fg.Length == n0*n1*n2);
Debug.Assert(f.Length == fg.Length);
Debug.Assert(g.Length == fg.Length);
int length = fg.Length;
double[] doubles = f.ToArray();
Complex[] complex = doubles.Select(x => new Complex(x, 0)).ToArray();
Fourier(n0, n1, n2, complex, FourierDirection.Forward);
doubles = g.ToArray();
Complex[] complex1 = doubles.Select(x => new Complex(x, 0)).ToArray();
Fourier(n0, n1, n2, complex1, FourierDirection.Backward);
int index = 0;
foreach (Complex value in complex1)
complex[index++] *= value/length;
Fourier(n0, n1, n2, complex, FourierDirection.Backward);
doubles = complex.Select(x => x.Real).ToArray();
Array.Copy(doubles, 0, fg, 0, length);
}
/// <summary>
/// Calculate scalar values
/// </summary>
/// <param name="n0">Array size</param>
/// <param name="n1">Array size</param>
/// <param name="f">Input values</param>
/// <param name="g">Input values</param>
/// <param name="fg">Output values</param>
public static void Scalar(int n0, int n1, double[] f, double[] g, double[] fg)
{
Debug.Assert(fg.Length == n0*n1);
Debug.Assert(f.Length == fg.Length);
Debug.Assert(g.Length == fg.Length);
int length = fg.Length;
double[] doubles = f.ToArray();
Complex[] complex = doubles.Select(x => new Complex(x, 0)).ToArray();
Fourier(n0, n1, complex, FourierDirection.Forward);
doubles = g.ToArray();
Complex[] complex1 = doubles.Select(x => new Complex(x, 0)).ToArray();
Fourier(n0, n1, complex1, FourierDirection.Backward);
int index = 0;
foreach (Complex value in complex1)
complex[index++] *= value/length;
Fourier(n0, n1, complex, FourierDirection.Backward);
doubles = complex.Select(x => x.Real).ToArray();
Array.Copy(doubles, 0, fg, 0, length);
}
/// <summary>
/// Calculate scalar values
/// </summary>
/// <param name="n0">Array size</param>
/// <param name="n1">Array size</param>
/// <param name="f">Input values</param>
/// <param name="g">Input values</param>
/// <param name="fg">Output values</param>
public static void Scalar(int n0, int n1, Complex[] f, Complex[] g, Complex[] fg)
{
Debug.Assert(fg.Length == n0*n1);
Debug.Assert(f.Length == fg.Length);
Debug.Assert(g.Length == fg.Length);
int length = fg.Length;
Complex[] complex = f.ToArray();
Fourier(n0, n1, complex, FourierDirection.Forward);
Complex[] complex1 = g.ToArray();
Fourier(n0, n1, complex1, FourierDirection.Backward);
int index = 0;
foreach (Complex value in complex1)
complex[index++] *= value/length;
Fourier(n0, n1, complex, FourierDirection.Backward);
Array.Copy(complex, 0, fg, 0, length);
}
/// <summary>
/// Calculate scalar values
/// </summary>
/// <param name="n0">Array size</param>
/// <param name="n1">Array size</param>
/// <param name="n2">Array size</param>
/// <param name="f">Input values</param>
/// <param name="g">Input values</param>
/// <param name="fg">Output values</param>
public static void Scalar(int n0, int n1, int n2, Complex[] f, Complex[] g, Complex[] fg)
{
Debug.Assert(fg.Length == n0*n1*n2);
Debug.Assert(f.Length == fg.Length);
Debug.Assert(g.Length == fg.Length);
int length = fg.Length;
Complex[] complex = f.ToArray();
Fourier(n0, n1, n2, complex, FourierDirection.Forward);
Complex[] complex1 = g.ToArray();
Fourier(n0, n1, n2, complex1, FourierDirection.Backward);
int index = 0;
foreach (Complex value in complex1)
complex[index++] *= value/length;
Fourier(n0, n1, n2, complex, FourierDirection.Backward);
Array.Copy(complex, 0, fg, 0, length);
}
}
}
|
PHP
|
UTF-8
| 331
| 2.8125
| 3
|
[] |
no_license
|
<?php
class Celsus_Data_Formatter_Json implements Celsus_Data_Formatter_Interface {
/**
* Returns the data formatted as Json.
*
* @param Celsus_Data_Interface $object
* @return string
*/
public static function format(Celsus_Data_Interface $object) {
return Zend_Json::encode($object->toArray());
}
}
|
Java
|
UTF-8
| 1,693
| 1.875
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2022. Bernard Bou
*/
package org.sqlunet.browser;
import android.view.View;
import org.hamcrest.Matcher;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.test.espresso.IdlingRegistry;
import androidx.test.espresso.IdlingResource;
import androidx.test.espresso.matcher.ViewMatchers;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.withEffectiveVisibility;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
public class WaitUntil extends BaseWaitUntil
{
// private static final String TAG = WaitUntil.class.getSimpleName();
public WaitUntil(final Matcher<View> viewMatcher)
{
super(viewMatcher);
}
@Override
public boolean isIdleNow()
{
View view = getView(this.viewMatcher);
boolean idle = view == null || view.isShown();
if (idle && this.resourceCallback != null)
{
this.resourceCallback.onTransitionToIdle();
}
return idle;
}
@NonNull
@Override
public String getName()
{
return this + this.viewMatcher.toString();
}
public static void waitViewShown(@NonNull final Matcher<View> matcher)
{
final IdlingResource idlingResource = new WaitUntil(matcher);
try
{
IdlingRegistry.getInstance().register(idlingResource);
//onView(matcher).check(matches(isDisplayed()));
onView(matcher).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));
}
finally
{
IdlingRegistry.getInstance().unregister(idlingResource);
}
}
public static void shown(@IdRes final int viewId)
{
waitViewShown(withId(viewId));
}
}
|
JavaScript
|
UTF-8
| 17,452
| 2.640625
| 3
|
[] |
no_license
|
/* Coded with love by Igloo team. */
$(".toast").toast();
////////// Server URL //////////
var server_url = "http://localhost:8080";
var search_url = server_url + "/api/invoice/get?";
////////// Global VARs //////////
var currentPageGlobal = 1; // Current invoices page
var selectedInvoiceId; // Selected invoice
var selectedInvoicesIds = []; // Selected invoices array
var selectedId; // Used on edit method
////////// Selection ///////////
function addToSelected(event) {
var row = event.currentTarget.closest("tr");
var id = row.querySelector(".idIndicator").innerHTML;
if (selectedInvoicesIds.includes(id)) {
selectedInvoicesIds.splice(selectedInvoicesIds.indexOf(id), 1);
} else {
selectedInvoicesIds.push(id);
}
if (selectedInvoicesIds.length > 0) {
document.querySelector("#batchDeleteButton").disabled = false;
document.querySelector("#batchDeleteButton").className = "btn btn-add btn-lg btn-block filterText ";
} else {
document.querySelector("#batchDeleteButton").disabled = true;
document.querySelector("#batchDeleteButton").className = "btn btn-del btn-lg btn-block filterText ";
}
}
////////// Pagination //////////
function nextPage() {
var finalRequest = "";
currentPage = parseInt(currentPageGlobal);
if (currentPage > 0) {
var nextPage = currentPage + 1;
if (search_url.indexOf("&") != -1) {
search_url = search_url.split("&page")[0];
var auxUrl = search_url;
finalRequest = auxUrl + "&page=" + nextPage;
} else {
search_url = search_url.split("page")[0];
var auxUrl = search_url;
finalRequest = auxUrl + "page=" + nextPage;
}
fetchRequest(finalRequest, null);
currentPageGlobal = nextPage;
updatePages(nextPage);
}
}
function prevPage() {
var finalRequest = "";
currentPage = parseInt(currentPageGlobal);
if (currentPage > 0) {
var prevPage = currentPage - 1;
if (prevPage < 1) {
var prevPage = currentPage;
}
if (search_url.indexOf("&") != -1) {
search_url = search_url.split("&page")[0];
var auxUrl = search_url;
finalRequest = auxUrl + "&page=" + prevPage;
} else {
search_url = search_url.split("page")[0];
var auxUrl = search_url;
finalRequest = auxUrl + "page=" + prevPage;
}
fetchRequest(finalRequest, null);
currentPageGlobal = prevPage;
updatePages(prevPage);
}
}
function updatePages(currentPage) {
currentPageInt = parseInt(currentPage);
var pageIndicators = document.querySelector("#paginationControls");
pageIndicators.querySelector("#currentPageItem").innerHTML = currentPageInt;
pageIndicators.querySelector("#currentPageItem").style.color = "#59bec9";
}
////////// Fetch //////////
function fetchRequest(finalRequest, toast, globalSearch) {
if (globalSearch) {
search_url = finalRequest;
console.log("Search url:" + search_url);
}
console.log("Fetch request to: " + finalRequest);
fetch(finalRequest)
.then((r) => r.json())
.then((invoices) => {
cleanTable();
fillTable(invoices);
if (toast != null) {
$(document).ready(function () {
{
$(toast).toast("show");
}
});
}
});
resetSelectedList();
}
////////// Utilities //////////
function buttonFn(event, action, sortTerm, sortMethod, resetPage) {
var aux = document.querySelectorAll(".lateralMenuAux");
console.log(aux);
for (var i = 0; i < aux.length; i++) {
console.log(aux[i].style.color);
aux[i].style.color = "rgb(255, 255, 255)";
}
if (event != null) {
var rowButton = event.currentTarget.closest(".row");
var ico = rowButton.querySelector("i");
var lab = rowButton.querySelector("label");
if (ico.style.color == "rgb(89, 190, 201)" && lab.style.color == "rgb(89, 190, 201)") {
} else if (ico.style.color == "rgb(255, 255, 255)" && lab.style.color == "rgb(255, 255, 255)") {
ico.style.color = "rgb(89, 190, 201)";
lab.style.color = "rgb(89, 190, 201)";
}
}
getInvoices(action, sortTerm, sortMethod, resetPage);
}
function resetSelectedList() {
selectedInvoicesIds = [];
}
function unHideCreationForm() {
document.querySelector("#creationForm").style.display = "";
}
function hideCreationForm() {
document.querySelector("#creationForm").style.display = "none";
}
function unHideEditForm() {
document.querySelector("#editForm").style.display = "";
}
function hideEditForm() {
document.querySelector("#editForm").style.display = "none";
}
function clearEditForm() {
document.querySelector("input[name=preTaxEdited]").value = "";
document.querySelector("select[name=clientIdEdited]").value = "1";
document.querySelector("select[name=statusIdEdited]").value = "1";
document.querySelector("select[name=paymentStatusIdEdited]").value = "1";
document.querySelector("select[name=sectorIdEdited]").value = "1";
}
function clearCreationForm() {
document.querySelector("input[name=preTax]").value = "";
document.querySelector("select[name=clientId]").value = "1";
document.querySelector("select[name=statusId]").value = "1";
document.querySelector("select[name=paymentStatusId]").value = "1";
document.querySelector("select[name=sectorId]").value = "1";
}
function cleanTable() {
document.querySelector("#invoiceList").innerHTML = "";
}
/////////////////////////////////
////////// CREATE form //////////
function showCreateForm() {
hideEditForm();
if (document.querySelector("#creationForm").style.display == "none") {
unHideCreationForm();
} else {
hideCreationForm();
}
}
function createInvoice() {
hideCreationForm();
hideEditForm();
unHideCreationForm();
// Request Definition.
var request = server_url + "/api/invoice/add?";
var finalRequest;
// Get invoice atributes.
var preTax = document.querySelector("input[name=preTax]").value;
if (preTax > 0) {
} else {
preTax = 0;
}
var clientId = document.querySelector("select[name=clientId]").value;
var statusId = document.querySelector("select[name=statusId]").value;
var paymentStatusId = document.querySelector("select[name=paymentStatusId]").value;
var sectorId = document.querySelector("select[name=sectorId]").value;
var creationRequest =
request +
"preTax=" +
preTax +
"&clientId=" +
clientId +
"§orId=" +
sectorId +
"&statusId=" +
statusId +
"&paymentStatusId=" +
paymentStatusId;
finalRequest = creationRequest;
var auxUrl = search_url;
auxUrl = auxUrl.split("?");
if (auxUrl[1].length > 0) {
finalRequest = finalRequest + "&page=" + currentPageGlobal + "&" + auxUrl[1];
} else {
finalRequest = finalRequest + "&page=" + currentPageGlobal;
}
fetchRequest(finalRequest, "#createToast");
clearCreationForm();
hideCreationForm();
}
///////////////////////////////
////////// EDIT form //////////
function showEditForm(event) {
hideCreationForm();
hideEditForm();
unHideEditForm();
// Find selected Invoice ID
var selectedInvoiceRow = event.currentTarget.closest("tr");
selectedInvoiceId = selectedInvoiceRow.querySelector(".idIndicator").innerHTML;
selectedId = selectedInvoiceId;
// Fetch request.
fetch("/api/invoice/find?id=" + selectedInvoiceId)
.then((r) => r.json())
.then((invoiceToEdit) => {
console.log("Selected invoice: ", invoiceToEdit);
// Get invoice old atributes.
document.querySelector("input[name=preTaxEdited]").value = invoiceToEdit.preTax;
document.querySelector("select[name=clientIdEdited]").getElementsByTagName("option")[
invoiceToEdit.client.id - 1
].selected = "selected";
console.log(document.querySelector("select[name=statusIdEdited]").getElementsByTagName("option"));
document.querySelector("select[name=statusIdEdited]").getElementsByTagName("option")[
invoiceToEdit.status.id - 1
].selected = "selected";
document.querySelector("select[name=paymentStatusIdEdited]").getElementsByTagName("option")[
invoiceToEdit.payment.id - 1
].selected = "selected";
document.querySelector("select[name=sectorIdEdited]").getElementsByTagName("option")[
invoiceToEdit.sector.id - 1
].selected = "selected";
});
}
function editInvoice() {
var selectedInvoiceRow = selectedId;
// Request Definition.
var request = server_url + "/api/invoice/add?id=" + selectedInvoiceRow + "&";
var finalRequest;
// Get invoice new atributes.
var preTax = document.querySelector("input[name=preTaxEdited]").value;
if (preTax > 0) {
} else {
preTax = 0;
}
var clientId = document.querySelector("select[name=clientIdEdited]").value;
var statusId = document.querySelector("select[name=statusIdEdited]").value;
var paymentStatusId = document.querySelector("select[name=paymentStatusIdEdited]").value;
var sectorId = document.querySelector("select[name=sectorIdEdited]").value;
var editRequest =
request +
"preTax=" +
preTax +
"&clientId=" +
clientId +
"§orId=" +
sectorId +
"&statusId=" +
statusId +
"&paymentStatusId=" +
paymentStatusId;
finalRequest = editRequest;
var auxUrl = search_url;
auxUrl = auxUrl.split("?");
if (auxUrl[1].length > 0) {
finalRequest = finalRequest + "&page=" + currentPageGlobal + "&" + auxUrl[1];
} else {
finalRequest = finalRequest + "&page=" + currentPageGlobal;
}
// Fetch request.
console.log(finalRequest);
fetchRequest(finalRequest, "#editToast", false);
clearEditForm();
hideEditForm();
}
////////////////////////////////
////////// Method GET //////////
function getInvoices(action, sortTerm, sortMethod, resetPage) {
if (resetPage) {
currentPageGlobal = 1;
let currentPage = currentPageGlobal;
updatePages(currentPage);
}
// Request Definition.
var request = server_url + "/api/invoice/get";
var finalRequest;
// Action selector
switch (action) {
case "sort": // Sort request
// Sort Definition.
sortRequest = request + "?action=sort&";
// Request Parameters.
finalRequest = sortRequest + "option=" + sortMethod + "&" + "term=" + sortTerm;
break;
case "searchClient": // Search by request client
// Search Definition.
var searchRequest = request + "?action=search&";
// Request Parameter.
var searchTerm = document.querySelector("#searchTerm").value;
finalRequest = searchRequest + "option=client&term=" + searchTerm;
break;
default:
// Simple get all request
finalRequest = request;
}
// Fetch request.
fetchRequest(finalRequest, null, true);
}
///////////////////////////////////
////////// Method DELETE //////////
function markForDelete(event) {
console.log("Selecting invoice");
var selectedInvoiceRow = event.currentTarget.closest("tr");
selectedInvoiceId = selectedInvoiceRow.querySelector(".idIndicator").innerHTML;
console.log("Selected order: " + selectedInvoiceId);
}
function deleteInvoice() {
if (selectedInvoiceId == null) {
console.log("Error");
} else {
// Request Definition.
var request = server_url + "/api/invoice/delete?";
var finalRequest = "";
// Find selected Invoice ID
var deleteRequest = request + "id=" + selectedInvoiceId;
finalRequest = deleteRequest;
var auxUrl = search_url;
auxUrl = auxUrl.split("?");
if (auxUrl[1].length > 0) {
finalRequest = finalRequest + "&page=" + currentPageGlobal + "&" + auxUrl[1];
} else {
finalRequest = finalRequest + "&page=" + currentPageGlobal;
}
console.log(finalRequest);
fetchRequest(finalRequest, "#deleteToast", false);
selectedInvoiceId = null;
}
}
/////////////////////////////////////////
////////// Method Batch DELETE //////////
function batchDelete() {
if (selectedInvoicesIds.length > 0) {
// Request Definition.
var request = server_url + "/api/invoice/delete?";
var finalRequest = "";
// Find selected Invoice ID
var deleteRequest = request + "id=" + selectedInvoicesIds.join(",");
finalRequest = deleteRequest;
var auxUrl = search_url;
auxUrl = auxUrl.split("?");
if (auxUrl[1].length > 0) {
finalRequest = finalRequest + "&page=" + currentPageGlobal + "&" + auxUrl[1];
} else {
finalRequest = finalRequest + "&page=" + currentPageGlobal;
}
console.log("Batch delete " + finalRequest);
fetchRequest(finalRequest, "#deleteToast", false);
selectedInvoicesIds = [];
document.querySelector("#batchDeleteButton").disabled = true;
document.querySelector("#batchDeleteButton").className = "btn btn-del btn-lg btn-block filterText ";
}
}
///////////////////////////////////////
////////// Method Fill Table //////////
function fillTable(invoices) {
if (invoices.length == 0) {
currentPageGlobal = currentPageGlobal - 1;
document.querySelector("#nextPage").disabled = true;
var afterTableContainer = document.querySelector("#afterTableContainer");
afterTableContainer.innerHTML = "";
var afterTableContainer = document.querySelector("#afterTableContainer");
var noMoreResultAlert = document.createElement("div");
noMoreResultAlert.className = "alert alert-dark";
noMoreResultAlert.role = "alert alert";
noMoreResultAlert.innerHTML = "No more results to show";
afterTableContainer.appendChild(noMoreResultAlert);
} else {
var afterTableContainer = document.querySelector("#afterTableContainer");
afterTableContainer.innerHTML = "";
document.querySelector("#nextPage").disabled = false;
}
for (i in invoices) {
// Row
var row = document.createElement("tr");
// Selection Column
var selectionCol = document.createElement("td");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.addEventListener("change", function (event) {
addToSelected(event);
});
selectionCol.appendChild(checkbox);
row.appendChild(selectionCol);
// ID Column
var idCol = document.createElement("td");
idCol.className = "filterTextDark idIndicator";
idCol.innerHTML = invoices[i].id;
row.appendChild(idCol);
// Creation Date Column
var creationDateCol = document.createElement("td");
creationDateCol.className = "filterTextDark";
creationDateCol.innerHTML = invoices[i].creationDate;
row.appendChild(creationDateCol);
// Due Date Column
var dueDateCol = document.createElement("td");
dueDateCol.className = "filterTextDark";
dueDateCol.innerHTML = invoices[i].dueDate;
row.appendChild(dueDateCol);
// Sector Column
var sectorCol = document.createElement("td");
sectorCol.className = "filterTextDark";
sectorCol.innerHTML = invoices[i].sector.name;
row.appendChild(sectorCol);
// Client Column
var clientCol = document.createElement("td");
clientCol.className = "filterTextDark";
clientCol.innerHTML = invoices[i].client.firstName + " " + invoices[i].client.lastName;
row.appendChild(clientCol);
// Pre Tax Amount Column
var preTaxCol = document.createElement("td");
preTaxCol.className = "filterTextDark";
preTaxCol.style.textAlign="right"
preTaxCol.innerHTML = invoices[i].preTax + '€';
row.appendChild(preTaxCol);
// After Tax Amount Column
var afterTaxCol = document.createElement("td");
afterTaxCol.className = "filterTextDark";
afterTaxCol.style.textAlign="right"
afterTaxCol.innerHTML = invoices[i].afterTax + '€';
row.appendChild(afterTaxCol);
// Status Column
var paymentStatusCol = document.createElement("td");
paymentStatusCol.className = "filterTextDark";
paymentStatusCol.innerHTML = invoices[i].payment.name;
row.appendChild(paymentStatusCol);
// Payment Status Column
var statusCol = document.createElement("td");
statusCol.className = "filterTextDark";
statusCol.innerHTML = invoices[i].status.name;
row.appendChild(statusCol);
// Actions Column
var actionsCol = document.createElement("td");
actionsCol.className = "filterTextDark";
var buttogroup = document.createElement("div");
buttogroup.className = "btn-group";
buttogroup.role = "group";
var editbutton = document.createElement("button");
editbutton.type = "button";
editbutton.className = "btn btn-secondary";
editbutton.addEventListener("click", function (event) {
showEditForm(event);
});
var editIcon = document.createElement("i");
editIcon.className = "fas fa-edit";
editbutton.appendChild(editIcon);
buttogroup.appendChild(editbutton);
var deleteButton = document.createElement("button");
deleteButton.type = "button";
deleteButton.className = "btn btn-secondary deleteButton";
var deleteIcon = document.createElement("i");
deleteIcon.className = "fas fa-trash-alt";
deleteButton.addEventListener("click", function (event) {
markForDelete(event);
});
deleteButton.setAttribute("data-target", "#deleteModal");
deleteButton.setAttribute("data-toggle", "modal");
deleteButton.appendChild(deleteIcon);
buttogroup.appendChild(deleteButton);
actionsCol.appendChild(buttogroup);
row.appendChild(actionsCol);
document.querySelector("#invoiceList").appendChild(row);
}
/* $(".deleteButton").attr("data-target", "#deleteModal");
$(".deleteButton").attr("data-toggle", "modal"); J-QUERY DEBE ESTAR YA EN EL DOM*/
}
|
C++
|
UTF-8
| 1,708
| 2.796875
| 3
|
[] |
no_license
|
#include "OffsetGenerator.h"
#include "TwoArray.h"
#include <benchmark/benchmark.h>
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <random>
#include <vector>
template <int32_t S, typename G>
void TwoArray(benchmark::State& state)
{
using value_type = typename Codility::TwoArray<S>::value_type;
Codility::TwoArray<S> question;
std::size_t size = state.range(0);
std::vector<value_type> input(size, 0);
// generate access pattern
std::vector<size_t> offsets;
offsets.resize(size);
G::generate(offsets);
// std::for_each(std::begin(offsets), std::end(offsets),
// [](size_t value) { std::cout << value << std::endl; });
// std::cout << std::endl;
int32_t index = 0;
for (auto _ : state) {
::benchmark::DoNotOptimize(question.solution(input, offsets[index]));
index++;
index %= size;
}
}
BENCHMARK_TEMPLATE(TwoArray, 1, OffsetGenerator<GeneratorType::Random>)
->RangeMultiplier(2)
->Range(1 << 14, 1 << 24);
BENCHMARK_TEMPLATE(TwoArray, 1, OffsetGenerator<GeneratorType::Ascending>)
->RangeMultiplier(2)
->Range(1 << 14, 1 << 24);
BENCHMARK_TEMPLATE(TwoArray, 1, OffsetGenerator<GeneratorType::Descending>)
->RangeMultiplier(2)
->Range(1 << 14, 1 << 24);
BENCHMARK_TEMPLATE(TwoArray, 1, OffsetGenerator<GeneratorType::AscendingWithOffset>)
->RangeMultiplier(2)
->Range(1 << 14, 1 << 24);
BENCHMARK_TEMPLATE(TwoArray, 1, OffsetGenerator<GeneratorType::Sawtooth1>)
->RangeMultiplier(2)
->Range(1 << 14, 1 << 24);
BENCHMARK_TEMPLATE(TwoArray, 1, OffsetGenerator<GeneratorType::Sawtooth2>)
->RangeMultiplier(2)
->Range(1 << 14, 1 << 24);
|
Python
|
UTF-8
| 151
| 2.546875
| 3
|
[] |
no_license
|
a=int(input())
b=int(input())
c=int(input())
x=str(a*b*c)
L=[0]*10
print(x)
for i in range (len(x)):
L[ int(x[i]) ]+=1
#150 266 427 3102000200
|
C
|
UTF-8
| 5,221
| 2.90625
| 3
|
[] |
no_license
|
#include "libtests.h"
int test_count = 0, failcount = 0, check_type = 0;
void set_check_type (int type)
{
assert ((type == SOFT_CHECK) || (type == HARD_CHECK));
check_type = type;
}
bool is_well_formatted (char * line)
{
regex_t regex;
size_t s = 0;
regmatch_t * r = NULL;
if (regcomp (®ex, "[:alnum:]*:[:alnum:]*", REG_NEWLINE|REG_NOSUB)) {
/* Compilation failed, let us return success */
return TRUE;
}
if (regexec (®ex, line, s, r, 0)) {
return FALSE;
} else {
return TRUE;
}
}
bool get_single_entry (FILE * fp)
{
assert ((FILE *) -1 != fp);
char * line = calloc (sizeof (char), 2 * NAMELEN);
size_t dummy = 0;
ssize_t read;
// char buf_old [NAMELEN] = "", buf_exp [NAMELEN] = "";
if ((read = getline (&line, &dummy, fp)) != -1) {
char *ptr;
int i = 0;
if (*line == '#') {
/* Ignore comment lines */
bufs.buf_old[0] = '#';
return IGNORE;
}
if ( !is_well_formatted (line) ) {
bufs.buf_old[0] = '#';
return IGNORE;
}
d_printf ("-----------------------------------------\n");
d_printf ("Got %s len = %d\n", line, strlen (line));
if ((ptr = strchr (line, '\n')) != NULL)
*ptr = '\0';
ptr = line;
/* Clear buffers from last iteration */
for (i = 0; i < NAMELEN; i++) {
bufs.buf_old [i] = bufs.buf_exp [i] = 0;
}
i = 0;
while (*ptr && *ptr != ':') {
bufs.buf_old [i] = *ptr;
i++;
ptr++;
}
ptr++; /* Skip over the colon*/
i = 0;
while (*ptr) {
bufs.buf_exp [i] = *ptr;
ptr++;
i++;
}
free (line);
return TRUE;
} else {
/* End of file */
free (line);
return FALSE;
}
}
int check (char * filename)
{
assert (filename);
FILE * fp = fopen (filename, "r");
if (NULL == fp) {
return FILE_NOT_FOUND_ERR;
}
bool ret;
while (((ret = get_single_entry (fp)) == TRUE) || (ret == IGNORE)) {
if (bufs.buf_old [0] == '#') {
/* Ignore comment line */
continue;
}
test_count ++;
d_printf ("buf_old = [%s] buf_exp = [%s]\n", bufs.buf_old, bufs.buf_exp);
d_printf ("Running test #%d, input name is [%s]\n", test_count, bufs.buf_old);
/* Now, run the check */
char * actual_result = new_name (bufs.buf_old);
if (0 == strcmp (actual_result, bufs.buf_exp)) {
continue;
} else {
failcount++;
if (check_type == SOFT_CHECK) {
fprintf (stderr, "Expected new name: [%s], Actual : [%s]\n",
bufs.buf_exp, actual_result);
} else {
assert (failcount == 1);
fprintf (stderr, "Expected new name: %s, Actual : %s\n",
bufs.buf_exp, actual_result);
fprintf (stderr, "%d/%d tests passed\n", (test_count - 1), test_count);
exit (-1);
}
}
}
d_printf ("%d strings found\n", test_count);
fclose (fp);
return test_count;
}
int test_libcleanup (int verbose)
{
int ret = check (TEST_DATA_FILE);
if (ret == FILE_NOT_FOUND_ERR) {
fprintf (stderr, "Failed to open test data file\n");
}
if (verbose) {
printf ("%d/%d tests passed\n", (test_count - failcount), test_count);
}
return -failcount;
}
int test_cleanup_tool (int verbose)
{
FILE * fp = fopen (TEST_DATA_FILE, "r");
if (NULL == fp) {
return -1;
}
bool ret;
char cmd [NAMELEN + 8]; /* 8 is strlen ("touch ./") */
if (-1 == mkdir ("test-dir", 0755)) {
fclose (fp);
perror ("Could not create test temporary directory");
return -1;
}
if (-1 == chdir ("test-dir")) {
perror ("Could not change to test temporary directory");
fclose (fp);
system ("rm -rf test-dir");
return -1;
}
while (((ret = get_single_entry (fp)) == TRUE) || (ret == IGNORE)) {
if (bufs.buf_old [0] == '#') {
/* Ignore comment line */
continue;
}
test_count ++;
sprintf (cmd, "touch ./");
strcat (cmd, bufs.buf_old);
strcat (cmd, "\0");
d_printf ("buf_old = [%s] buf_exp = [%s]\n", bufs.buf_old, bufs.buf_exp);
d_printf (cmd);
/* FIXME: Use of system() looks shabby, perhaps undeservedly so */
system (cmd);
system ("../cleanup -q");
struct stat statbuf;
if (-1 == stat (bufs.buf_exp, &statbuf)) {
failcount++;
d_printf ("Did not find expected file with new name %s\n", bufs.buf_exp);
if (check_type == HARD_CHECK) {
break;
} else {
/* continue */
}
}
}
if (verbose) {
printf ("%d/%d tests passed\n", (test_count - failcount), test_count);
}
chdir ("..");
system ("rm -r test-dir");
fclose (fp);
return -failcount;
}
|
TypeScript
|
UTF-8
| 1,168
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
/**
* @fileOverview cookie-based storage, 依赖js-cookie, 支持JSON对象直接存储
* @author Max
**/
import Cookies = require('cookies');
const INITIAL_DATA_NAMESPACE = 'initialData';
export default {
['$set'](key: string, obj: any) {
let initialDataObj = Cookies.getJSON(INITIAL_DATA_NAMESPACE) || {};
initialDataObj[key] = obj;
Cookies.set(INITIAL_DATA_NAMESPACE, JSON.stringify(initialDataObj), {expires: 7, path: '/'});
},
['$get'](key: string) {
let initialDataObj = Cookies.getJSON(INITIAL_DATA_NAMESPACE) || {};
return initialDataObj[key];
},
['$remove'](key: string) {
let initialDataObj = Cookies.getJSON(INITIAL_DATA_NAMESPACE) || {};
delete initialDataObj[key];
Cookies.set(INITIAL_DATA_NAMESPACE, JSON.stringify(initialDataObj), {expires: 7, path: '/'});
},
['set'](key: string, obj: any) {
Cookies.set(key, JSON.stringify(obj), {expires: 7, path: '/'});
},
['get'](key: string) {
return Cookies.getJSON(key);
},
['remove'](key: string) {
Cookies.remove(key, {path: '/'});
}
};
|
C++
|
GB18030
| 3,187
| 2.625
| 3
|
[] |
no_license
|
#include "DataAnalysis.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonDocument>
QJsonObject DataAnalysis::objectFromMsginfo(MsgInfo & msg)
{
QJsonObject msgJson;
msgJson.insert("address", msg.address);
msgJson.insert("from", msg.from);
msgJson.insert("msg", msg.msg);
msgJson.insert("msgType", msg.msgType);
msgJson.insert("port", msg.port);
msgJson.insert("to", msg.to);
return msgJson;
}
QJsonObject DataAnalysis::objectFromUserInfo(UserInfo & user)
{
QJsonObject userJson;
userJson.insert("id", user.id);
userJson.insert("name", user.name);
userJson.insert("sign", user.sign);
return userJson;
}
QByteArray DataAnalysis::byteFromMsgInfo(MsgInfo & msg)
{
QJsonObject msgJson = DataAnalysis::objectFromMsginfo(msg);
QJsonObject json;
json.insert("msgInfo", msgJson);
QJsonDocument document;
document.setObject(json);
return document.toJson();
}
QByteArray DataAnalysis::byteFromMsgInfoAdUserInfo(MsgInfo & msg, UserInfo & user)
{
QJsonObject msgJson = DataAnalysis::objectFromMsginfo(msg);
QJsonObject userJson = DataAnalysis::objectFromUserInfo(user);
QJsonObject json;
json.insert("msgInfo", msgJson);
json.insert("userInfo", userJson);
QJsonDocument document;
document.setObject(json);
return document.toJson();
}
MsgInfo DataAnalysis::msgFromJsonByte(const QByteArray & byte)
{
QJsonParseError jsonError;
QJsonDocument doucment = QJsonDocument::fromJson(byte,&jsonError);
if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
{ // δ
QJsonObject object = doucment.object();
if (object.contains("msgInfo"))
{
QJsonValue value = object.value("msgInfo");
if (value.isObject())
{
QJsonObject obj = value.toObject();
MsgInfo info;
info.address = obj.value("address").toString();
info.from = obj.value("from").toString();
info.to = obj.value("to").toString();
info.msg = obj.value("msg").toString();
info.msgType = obj.value("msgType").toInt();
info.port = obj.value("port").toInt();
return info;
}
}
}
return MsgInfo();
}
UserInfo DataAnalysis::userFromJsonByte(const QByteArray & byte)
{
QJsonParseError jsonError;
QJsonDocument doucment = QJsonDocument::fromJson(byte, &jsonError);
if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError))
{ // δ
QJsonObject object = doucment.object();
if (object.contains("userInfo"))
{
QJsonValue value = object.value("userInfo");
if (value.isObject())
{
QJsonObject obj = value.toObject();
UserInfo info;
info.id = obj.value("id").toString();
info.name = obj.value("name").toString();
info.sign = obj.value("sign").toString();
return info;
}
}
}
return UserInfo();
}
|
C++
|
UTF-8
| 4,179
| 3.234375
| 3
|
[] |
no_license
|
//
// InputParser.cpp
// Group 9
//
//
#include "InputParser.hpp"
InputParser::InputParser()
{
}
bool InputParser::isRule(string factOrRule)
{
char nextChar;
std::string st;
unsigned int i = 0;
while(i < factOrRule.length())
{
nextChar = factOrRule[i++];
if(nextChar == '(' )
return false; //if there are parantheses, this is a fact, not a rule
}
//if no ( were found, user is trying to drop a rule.
return true;
}
std::vector<std::string> InputParser::tokenize(std::string& s, unordered_map<string, pair<string, string>>& factParams) //this method is used for tokenizing a string for inserting a rule
{
std::vector<std::string> parsedString;
char nextChar;
std::string st;
unsigned int i = 0;
int j = 0; //keeps track of which word was just added so we can link predicates to variables, i.e Father to $X, $Y
while(i < s.length())
{
nextChar = s[i++];
if(nextChar == ' ' )
continue; //ignore whitespace
else if( nextChar == '(') //when parsing rules, parantheses are considered in a different way than when parsing facts
{
if (!st.length()) //do not add blank strings
continue;
parsedString.push_back(st);
j++;
st.erase(); //reset st so we can get next parsed element
pair<string, string> currFactParams;
while(nextChar != ')')
{
nextChar = s[i++];
while(nextChar != ',' && nextChar != ')')
{
if(nextChar != ' ')
st += nextChar;
nextChar = s[i++];
}
if(currFactParams.first == "")
currFactParams.first = st[1];
else
currFactParams.second = st[1];//extract only the Varibale, ignore the $ internally
st.erase();
}
factParams[parsedString[j-1]] = currFactParams; //previous element has the factParams tied to them
}
if(nextChar == ')' || nextChar == ':' || nextChar == '-')
{
st.erase(); //reset st so we can get next parsed element
continue;
}
st += nextChar;
}
return parsedString;
}
std::vector<std::string> InputParser::tokenize(std::string& s) //when only given string, this is used for tokenizing a FACT
{
std::vector<std::string> parsedString;
char nextChar;
std::string st;
unsigned int i = 0;
while(i < s.length())
{
nextChar = s[i++];
if(nextChar == ' ' )
continue; //ignore whitespace
if(nextChar == ',' || nextChar == '(' || nextChar == ')' || nextChar == ':' || nextChar == '-')
{
if (!st.length()) //do not add blank strings
continue;
parsedString.push_back(st);
st.erase(); //reset st so we can get next parsed element
continue;
}
st += nextChar;
}
if (st.length()) //do not add blank strings. This final push_back to the parsedString vector is for when the user wants to add new facts based on the results of a query
parsedString.push_back(st);
return parsedString;
}
void InputParser::printPair(vector<pair<string, string>> v, std::pair<string, string> varNames)
{
//if the query was filtered, update output accordingly. We know query is filtered when varName is blank
if(varNames.first != "")
varNames.first.append(":");
if(varNames.second != "")
varNames.second.append(":");
for(auto r: v)
{
if(varNames.first[1] != ':')
r.first = "";
if(varNames.second[1] != ':')
r.second = "";
cout << varNames.first << r.first << '\t' << varNames.second << r.second << endl;
}
}
|
C++
|
UTF-8
| 2,357
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
/********************************************************************
created: 2014/08/21
filename: ApkFileStream.h
author: Crazii
purpose:
*********************************************************************/
#ifndef __Blade_ApkFileStream_h__
#define __Blade_ApkFileStream_h__
#include <BladePlatform.h>
#if BLADE_PLATFORM == BLADE_PLATFORM_ANDROID
#include <interface/public/file/IStream.h>
#include <ctime>
#include <unistd.h>
#include <fcntl.h>
namespace Blade
{
struct ApkFileEntry : public ResourceAllocatable
{
TString mName;
int64 mOffset;
int64 mSize;
std::time_t mCTime;
std::time_t mATime;
std::time_t mMTime;
};
class ApkFileStream : public IStream, public Allocatable
{
public:
ApkFileStream(ApkFileEntry* entry, int apkFD, Lock* fileLock);
~ApkFileStream();
/************************************************************************/
/* IStream interface */
/************************************************************************/
/** @brief get the stream name: path of the stream */
virtual const TString& getName()
{
return mEntry != NULL ? mEntry->mName : TString::EMPTY;
}
/** @brief */
virtual bool isValid() const
{
return mEntry != NULL && mFD != -1;
}
/** @brief */
virtual void close()
{
mEntry = NULL;
mFD = -1;
mOffset = 0;
if( mFileLock != NULL )
{
mFileLock->unlock();
mFileLock = NULL;
}
}
/** @brief */
virtual Off seek(EStreamPos origin, Off off);
/** @brief */
virtual Off tell() const;
/** @brief */
virtual bool eof() const;
/** @brief */
virtual Size readData(void* destBuffer,Size size);
/** @brief */
virtual Size writeData(const void* /*srcBuffer*/,Size /*size*/) {return 0;}
/** @brief */
virtual Size getSize() const
{
return mEntry != NULL ? mEntry->mSize : 0;
}
/** @brief */
virtual int getAccesMode() const {return AM_READ;}
/** @brief */
virtual void flush(bool /*hardFlush = false*/) {}
/** @brief */
virtual bool truncate(Size /*size*/) {return false;}
protected:
ApkFileEntry* mEntry;
int mFD;
Off mOffset;
Lock* mFileLock;
};
}//namespace Blade
#endif //BLADE_PLATFORM == BLADE_PLATFORM_ANDROID
#endif // __Blade_ApkFileStream_h__
|
Ruby
|
UTF-8
| 849
| 2.53125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
OptionValue.class_eval do
validates_numericality_of :price, :allow_nil => true
validates_numericality_of :weight, :allow_nil => true
validates_numericality_of :width, :allow_nil => true
validates_numericality_of :height, :allow_nil => true
validates_numericality_of :depth, :allow_nil => true
after_update :adjust_variant_modifiers
def adjust_variant_modifiers
updated_attributes = [:price, :weight, :width, :height, :depth].select { |x| self.send(:"#{x}_changed?") }
# make sure variants have a product!
variants.joins(:product).each do |variant|
updated_values = updated_attributes.inject({}) { |mem, attribute| mem[attribute] = variant.send(:"calculate_#{attribute}"); mem }
variant.update_attributes(updated_values) unless updated_values.blank?
end unless updated_attributes.blank?
end
end
|
Python
|
UTF-8
| 2,583
| 2.8125
| 3
|
[] |
no_license
|
# Boosting parse output
from matplotlib import pyplot as plt
import numpy as np
#diabetes
title='\nBoosting Diabetes Dataset\n'
print 'Plotting ' + title
# min num 2
min2_validation = [.690875, .707635, .713222, .718808, .731844, .722533, .724395, .72067]
# min2_training = [.862197, .862197, .862197, .862197, .862197, .862197, .862197, .862197]
num_iter = [10, 20, 30, 40, 50, 60, 70, 100]
# min num 3
min3_validation = [.713222, .716946, .726257, .72067, .72067, .72067, .72067, .72067]
# min3_training = [.903166, .903166, 903166, .903166, .903166, .903166, .903166, 903166]
# min num 4
min4_validation = [0.709, .709497, .703911, .711359, .709497, .707635, .707635, .707635]
# min4_training = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
# min num 10
min10_validation = [.715084, .715084, .715084, .715084, .715084, .715084, .715084, .715084]
# min10_training = [.959032, .985102, .985102,.985102, .959032, .985102, .985102,.985102]
# min num 24
min24_validation = [.724395, .724395, .724395, .724395, .724395, .724395, .724395, .724395]
# min24_training = [.826816, .826816, .826816, .826816, .826816, .826816, .826816, .826816]
# min num 250
plot1 = plt.figure(1)
ax = plot1.add_subplot(111)
plot1.subplots_adjust(top=0.85)
ax.set_title('axes title')
ax.set_xlabel('number of iterations')
ax.set_ylabel('accuracy')
plt.plot(num_iter, min2_validation, linewidth=2.0, label = 'min2 validation ')
plt.plot(num_iter, min3_validation, linewidth=2.0, label = 'min3 validation ')
plt.plot(num_iter, min4_validation, linewidth=2.0, label = 'min4 validation ')
plt.ylim(0.675, 0.775)
plt.legend()
plt.title(title)
plot1.show()
#wine
title='\nBoosting Wine Dataset\n'
print 'Plotting ' + title
num_iter = [10, 20, 30, 40, 50, 60, 70, 100]
min1_validation = [.627005, .648294, .649752, .648002, .64946, .649169, .65296, .657918]
min2_validation = [.634879, .639253, .64392, .646836, .656168, .655293, .652377, .65296]
min3_validation = [.62788, .637212, .643045, .647711, .654127, .647711, .654127, .65296]
print len(min1_validation)
print len(min2_training)
print len(num_iter)
plot2 = plt.figure(2)
ax = plot2.add_subplot(111)
plot2.subplots_adjust(top=0.85)
ax.set_title('axes title')
ax.set_xlabel('number of iterations')
ax.set_ylabel('accuracy')
plt.plot(num_iter, min1_validation, linewidth=2.0, label = 'min1 validation ')
plt.plot(num_iter, min2_validation, linewidth=2.0, label = 'min2 validation ')
plt.plot(num_iter, min3_validation, linewidth=2.0, label = 'min3 validation ')
plt.ylim(0.6, 0.7)
plt.legend()
plt.title(title)
plot2.show()
raw_input() #keeps plots alive
|
Java
|
UTF-8
| 17,652
| 1.953125
| 2
|
[] |
no_license
|
package com.cnfantasia.server.domainbase.revenueApply.entity;
/* import java.io.Serializable;*/
import java.math.BigInteger;
import java.lang.String;
import java.lang.Integer;
import java.lang.Double;
import com.cnfantasia.server.domain.pub.BaseEntity;
/**
* 描述:(提款申请记录) 实体类
*
* @version 1.00
* @author null
*
*/
/*
public class RevenueApply implements Serializable{
*/
public class RevenueApply extends BaseEntity{
private static final long serialVersionUID = 1L;
/** */
private BigInteger id;
/** 提款单号 */
private String applyNo;
/** 财务提款申请Id */
private BigInteger revApplyFinanceId;
/** 可见类型 */
private Integer visibleType;
/** 所属最小粒度角色类型 */
private Integer miniRoleType;
/** 所属最小粒度角色Id */
private BigInteger miniRoleId;
/** 提款对象类型 */
private Integer goalType;
/** 添加记录的渠道,DictConstants.channelSub */
private Integer channel;
/** 提款申请人omsUserId */
private BigInteger applyUserId;
/** 提款申请时间 */
private String applyTime;
/** 提款开始时间 */
private String goalStartTime;
/** 提款结束时间 */
private String goalEndTime;
/** 提款总额 */
private Double totalAmount;
/** 提款状态 */
private Integer tkStatus;
/** 操作类型 */
private Integer optType;
/** 提款成功时间 */
private String tkSuccTime;
/** 对象名称 */
private String roleName;
/** 手机号 */
private String bPhone;
/** 联系人姓名 */
private String bConnectName;
/** 银行卡号 */
private String bBankNo;
/** 开户支行 */
private String bBankName;
/** 开卡支行 */
private String accountName;
/** 开卡支行 */
private String bankBranch;
/** 支行所在省 */
private String bankProvince;
/** 支行所在市 */
private String bankCity;
/** 平台补贴额 */
private Double amountPtbt;
/** 用户实际实缴 */
private Double amountUsrReal;
/** EAS报销单(付款单)单号 */
private String easBillNumbers;
/** 审核时间 */
private String auditTime;
/** 审核状态 */
private Integer auditStatus;
/** 结算申请备注 */
private String applyNote;
/** 审核说明 */
private String handlerNote;
/** 供应商ID */
private BigInteger tEbuySupplyMerchantFk;
/** 供应商合作模式 */
private Integer revenueType;
/** 佣金比率 */
private Double revenueRate;
/** EAS已付金额 */
private Double easPayedAmount;
/** 小区id */
private BigInteger tGbId;
/** 物业管理处t_property_management表id */
private BigInteger tPropertyManagementFId;
public RevenueApply(){
}
public RevenueApply(RevenueApply arg){
this.id = arg.getId();
this.applyNo = arg.getApplyNo();
this.revApplyFinanceId = arg.getRevApplyFinanceId();
this.visibleType = arg.getVisibleType();
this.miniRoleType = arg.getMiniRoleType();
this.miniRoleId = arg.getMiniRoleId();
this.goalType = arg.getGoalType();
this.channel = arg.getChannel();
this.applyUserId = arg.getApplyUserId();
this.applyTime = arg.getApplyTime();
this.goalStartTime = arg.getGoalStartTime();
this.goalEndTime = arg.getGoalEndTime();
this.totalAmount = arg.getTotalAmount();
this.tkStatus = arg.getTkStatus();
this.optType = arg.getOptType();
this.tkSuccTime = arg.getTkSuccTime();
this.sys0AddTime = arg.getSys0AddTime();
this.sys0UpdTime = arg.getSys0UpdTime();
this.sys0DelTime = arg.getSys0DelTime();
this.sys0AddUser = arg.getSys0AddUser();
this.sys0UpdUser = arg.getSys0UpdUser();
this.sys0DelUser = arg.getSys0DelUser();
this.sys0DelState = arg.getSys0DelState();
this.roleName = arg.getRoleName();
this.bPhone = arg.getbPhone();
this.bConnectName = arg.getbConnectName();
this.bBankNo = arg.getbBankNo();
this.bBankName = arg.getbBankName();
this.accountName = arg.getAccountName();
this.bankBranch = arg.getBankBranch();
this.bankProvince = arg.getBankProvince();
this.bankCity = arg.getBankCity();
this.amountPtbt = arg.getAmountPtbt();
this.amountUsrReal = arg.getAmountUsrReal();
this.easBillNumbers = arg.getEasBillNumbers();
this.auditTime = arg.getAuditTime();
this.auditStatus = arg.getAuditStatus();
this.applyNote = arg.getApplyNote();
this.handlerNote = arg.getHandlerNote();
this.tEbuySupplyMerchantFk = arg.gettEbuySupplyMerchantFk();
this.revenueType = arg.getRevenueType();
this.revenueRate = arg.getRevenueRate();
this.easPayedAmount = arg.getEasPayedAmount();
this.tGbId = arg.gettGbId();
this.tPropertyManagementFId = arg.gettPropertyManagementFId();
}
/**
*
* @param id
* @param applyNo 提款单号
* @param revApplyFinanceId 财务提款申请Id
* @param visibleType 可见类型
* @param miniRoleType 所属最小粒度角色类型
* @param miniRoleId 所属最小粒度角色Id
* @param goalType 提款对象类型
* @param channel 添加记录的渠道,DictConstants.channelSub
* @param applyUserId 提款申请人omsUserId
* @param applyTime 提款申请时间
* @param goalStartTime 提款开始时间
* @param goalEndTime 提款结束时间
* @param totalAmount 提款总额
* @param tkStatus 提款状态
* @param optType 操作类型
* @param tkSuccTime 提款成功时间
* @param sys0AddTime 新增时间
* @param sys0UpdTime 更新时间
* @param sys0DelTime 删除时间
* @param sys0AddUser 新增者
* @param sys0UpdUser 修改者
* @param sys0DelUser 删除者
* @param sys0DelState 记录状态
* @param roleName 对象名称
* @param bPhone 手机号
* @param bConnectName 联系人姓名
* @param bBankNo 银行卡号
* @param bBankName 开户支行
* @param accountName 开卡支行
* @param bankBranch 开卡支行
* @param bankProvince 支行所在省
* @param bankCity 支行所在市
* @param amountPtbt 平台补贴额
* @param amountUsrReal 用户实际实缴
* @param easBillNumbers EAS报销单(付款单)单号
* @param auditTime 审核时间
* @param auditStatus 审核状态
* @param applyNote 结算申请备注
* @param handlerNote 审核说明
* @param tEbuySupplyMerchantFk 供应商ID
* @param revenueType 供应商合作模式
* @param revenueRate 佣金比率
* @param easPayedAmount EAS已付金额
* @param tGbId 小区id
* @param tPropertyManagementFId 物业管理处t_property_management表id
*/
public RevenueApply(BigInteger id,String applyNo,BigInteger revApplyFinanceId,Integer visibleType,Integer miniRoleType,BigInteger miniRoleId,Integer goalType,Integer channel,BigInteger applyUserId,String applyTime,String goalStartTime,String goalEndTime,Double totalAmount,Integer tkStatus,Integer optType,String tkSuccTime,String sys0AddTime,String sys0UpdTime,String sys0DelTime,BigInteger sys0AddUser,BigInteger sys0UpdUser,BigInteger sys0DelUser,Integer sys0DelState,String roleName,String bPhone,String bConnectName,String bBankNo,String bBankName,String accountName,String bankBranch,String bankProvince,String bankCity,Double amountPtbt,Double amountUsrReal,String easBillNumbers,String auditTime,Integer auditStatus,String applyNote,String handlerNote,BigInteger tEbuySupplyMerchantFk,Integer revenueType,Double revenueRate,Double easPayedAmount,BigInteger tGbId,BigInteger tPropertyManagementFId){
this.id = id;
this.applyNo = applyNo;
this.revApplyFinanceId = revApplyFinanceId;
this.visibleType = visibleType;
this.miniRoleType = miniRoleType;
this.miniRoleId = miniRoleId;
this.goalType = goalType;
this.channel = channel;
this.applyUserId = applyUserId;
this.applyTime = applyTime;
this.goalStartTime = goalStartTime;
this.goalEndTime = goalEndTime;
this.totalAmount = totalAmount;
this.tkStatus = tkStatus;
this.optType = optType;
this.tkSuccTime = tkSuccTime;
this.sys0AddTime = sys0AddTime;
this.sys0UpdTime = sys0UpdTime;
this.sys0DelTime = sys0DelTime;
this.sys0AddUser = sys0AddUser;
this.sys0UpdUser = sys0UpdUser;
this.sys0DelUser = sys0DelUser;
this.sys0DelState = sys0DelState;
this.roleName = roleName;
this.bPhone = bPhone;
this.bConnectName = bConnectName;
this.bBankNo = bBankNo;
this.bBankName = bBankName;
this.accountName = accountName;
this.bankBranch = bankBranch;
this.bankProvince = bankProvince;
this.bankCity = bankCity;
this.amountPtbt = amountPtbt;
this.amountUsrReal = amountUsrReal;
this.easBillNumbers = easBillNumbers;
this.auditTime = auditTime;
this.auditStatus = auditStatus;
this.applyNote = applyNote;
this.handlerNote = handlerNote;
this.tEbuySupplyMerchantFk = tEbuySupplyMerchantFk;
this.revenueType = revenueType;
this.revenueRate = revenueRate;
this.easPayedAmount = easPayedAmount;
this.tGbId = tGbId;
this.tPropertyManagementFId = tPropertyManagementFId;
}
@Override
public String toString() {
StringBuffer sbf = new StringBuffer();
sbf.append("id=").append(id).append(";");
sbf.append("applyNo=").append(applyNo).append(";");
sbf.append("revApplyFinanceId=").append(revApplyFinanceId).append(";");
sbf.append("visibleType=").append(visibleType).append(";");
sbf.append("miniRoleType=").append(miniRoleType).append(";");
sbf.append("miniRoleId=").append(miniRoleId).append(";");
sbf.append("goalType=").append(goalType).append(";");
sbf.append("channel=").append(channel).append(";");
sbf.append("applyUserId=").append(applyUserId).append(";");
sbf.append("applyTime=").append(applyTime).append(";");
sbf.append("goalStartTime=").append(goalStartTime).append(";");
sbf.append("goalEndTime=").append(goalEndTime).append(";");
sbf.append("totalAmount=").append(totalAmount).append(";");
sbf.append("tkStatus=").append(tkStatus).append(";");
sbf.append("optType=").append(optType).append(";");
sbf.append("tkSuccTime=").append(tkSuccTime).append(";");
sbf.append("sys0AddTime=").append(sys0AddTime).append(";");
sbf.append("sys0UpdTime=").append(sys0UpdTime).append(";");
sbf.append("sys0DelTime=").append(sys0DelTime).append(";");
sbf.append("sys0AddUser=").append(sys0AddUser).append(";");
sbf.append("sys0UpdUser=").append(sys0UpdUser).append(";");
sbf.append("sys0DelUser=").append(sys0DelUser).append(";");
sbf.append("sys0DelState=").append(sys0DelState).append(";");
sbf.append("roleName=").append(roleName).append(";");
sbf.append("bPhone=").append(bPhone).append(";");
sbf.append("bConnectName=").append(bConnectName).append(";");
sbf.append("bBankNo=").append(bBankNo).append(";");
sbf.append("bBankName=").append(bBankName).append(";");
sbf.append("accountName=").append(accountName).append(";");
sbf.append("bankBranch=").append(bankBranch).append(";");
sbf.append("bankProvince=").append(bankProvince).append(";");
sbf.append("bankCity=").append(bankCity).append(";");
sbf.append("amountPtbt=").append(amountPtbt).append(";");
sbf.append("amountUsrReal=").append(amountUsrReal).append(";");
sbf.append("easBillNumbers=").append(easBillNumbers).append(";");
sbf.append("auditTime=").append(auditTime).append(";");
sbf.append("auditStatus=").append(auditStatus).append(";");
sbf.append("applyNote=").append(applyNote).append(";");
sbf.append("handlerNote=").append(handlerNote).append(";");
sbf.append("tEbuySupplyMerchantFk=").append(tEbuySupplyMerchantFk).append(";");
sbf.append("revenueType=").append(revenueType).append(";");
sbf.append("revenueRate=").append(revenueRate).append(";");
sbf.append("easPayedAmount=").append(easPayedAmount).append(";");
sbf.append("tGbId=").append(tGbId).append(";");
sbf.append("tPropertyManagementFId=").append(tPropertyManagementFId).append(";");
return sbf.toString();
}
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public String getApplyNo() {
return applyNo;
}
public void setApplyNo(String applyNo) {
this.applyNo = applyNo;
}
public BigInteger getRevApplyFinanceId() {
return revApplyFinanceId;
}
public void setRevApplyFinanceId(BigInteger revApplyFinanceId) {
this.revApplyFinanceId = revApplyFinanceId;
}
public Integer getVisibleType() {
return visibleType;
}
public void setVisibleType(Integer visibleType) {
this.visibleType = visibleType;
}
public Integer getMiniRoleType() {
return miniRoleType;
}
public void setMiniRoleType(Integer miniRoleType) {
this.miniRoleType = miniRoleType;
}
public BigInteger getMiniRoleId() {
return miniRoleId;
}
public void setMiniRoleId(BigInteger miniRoleId) {
this.miniRoleId = miniRoleId;
}
public Integer getGoalType() {
return goalType;
}
public void setGoalType(Integer goalType) {
this.goalType = goalType;
}
public Integer getChannel() {
return channel;
}
public void setChannel(Integer channel) {
this.channel = channel;
}
public BigInteger getApplyUserId() {
return applyUserId;
}
public void setApplyUserId(BigInteger applyUserId) {
this.applyUserId = applyUserId;
}
public String getApplyTime() {
return applyTime;
}
public void setApplyTime(String applyTime) {
this.applyTime = applyTime;
}
public String getGoalStartTime() {
return goalStartTime;
}
public void setGoalStartTime(String goalStartTime) {
this.goalStartTime = goalStartTime;
}
public String getGoalEndTime() {
return goalEndTime;
}
public void setGoalEndTime(String goalEndTime) {
this.goalEndTime = goalEndTime;
}
public Double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(Double totalAmount) {
this.totalAmount = totalAmount;
}
public Integer getTkStatus() {
return tkStatus;
}
public void setTkStatus(Integer tkStatus) {
this.tkStatus = tkStatus;
}
public Integer getOptType() {
return optType;
}
public void setOptType(Integer optType) {
this.optType = optType;
}
public String getTkSuccTime() {
return tkSuccTime;
}
public void setTkSuccTime(String tkSuccTime) {
this.tkSuccTime = tkSuccTime;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getbPhone() {
return bPhone;
}
public void setbPhone(String bPhone) {
this.bPhone = bPhone;
}
public String getbConnectName() {
return bConnectName;
}
public void setbConnectName(String bConnectName) {
this.bConnectName = bConnectName;
}
public String getbBankNo() {
return bBankNo;
}
public void setbBankNo(String bBankNo) {
this.bBankNo = bBankNo;
}
public String getbBankName() {
return bBankName;
}
public void setbBankName(String bBankName) {
this.bBankName = bBankName;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getBankBranch() {
return bankBranch;
}
public void setBankBranch(String bankBranch) {
this.bankBranch = bankBranch;
}
public String getBankProvince() {
return bankProvince;
}
public void setBankProvince(String bankProvince) {
this.bankProvince = bankProvince;
}
public String getBankCity() {
return bankCity;
}
public void setBankCity(String bankCity) {
this.bankCity = bankCity;
}
public Double getAmountPtbt() {
return amountPtbt;
}
public void setAmountPtbt(Double amountPtbt) {
this.amountPtbt = amountPtbt;
}
public Double getAmountUsrReal() {
return amountUsrReal;
}
public void setAmountUsrReal(Double amountUsrReal) {
this.amountUsrReal = amountUsrReal;
}
public String getEasBillNumbers() {
return easBillNumbers;
}
public void setEasBillNumbers(String easBillNumbers) {
this.easBillNumbers = easBillNumbers;
}
public String getAuditTime() {
return auditTime;
}
public void setAuditTime(String auditTime) {
this.auditTime = auditTime;
}
public Integer getAuditStatus() {
return auditStatus;
}
public void setAuditStatus(Integer auditStatus) {
this.auditStatus = auditStatus;
}
public String getApplyNote() {
return applyNote;
}
public void setApplyNote(String applyNote) {
this.applyNote = applyNote;
}
public String getHandlerNote() {
return handlerNote;
}
public void setHandlerNote(String handlerNote) {
this.handlerNote = handlerNote;
}
public BigInteger gettEbuySupplyMerchantFk() {
return tEbuySupplyMerchantFk;
}
public void settEbuySupplyMerchantFk(BigInteger tEbuySupplyMerchantFk) {
this.tEbuySupplyMerchantFk = tEbuySupplyMerchantFk;
}
public Integer getRevenueType() {
return revenueType;
}
public void setRevenueType(Integer revenueType) {
this.revenueType = revenueType;
}
public Double getRevenueRate() {
return revenueRate;
}
public void setRevenueRate(Double revenueRate) {
this.revenueRate = revenueRate;
}
public Double getEasPayedAmount() {
return easPayedAmount;
}
public void setEasPayedAmount(Double easPayedAmount) {
this.easPayedAmount = easPayedAmount;
}
public BigInteger gettGbId() {
return tGbId;
}
public void settGbId(BigInteger tGbId) {
this.tGbId = tGbId;
}
public BigInteger gettPropertyManagementFId() {
return tPropertyManagementFId;
}
public void settPropertyManagementFId(BigInteger tPropertyManagementFId) {
this.tPropertyManagementFId = tPropertyManagementFId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RevenueApply other = (RevenueApply) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
Java
|
UTF-8
| 5,575
| 1.953125
| 2
|
[] |
no_license
|
package com.prettyyes.user.api.netXutils;
import com.alibaba.fastjson.JSON;
import com.hornen.logger.Logger;
import com.prettyyes.user.api.NetReqCallback;
import com.prettyyes.user.app.account.ACache;
import com.prettyyes.user.app.base.BaseApplication;
import com.prettyyes.user.core.utils.AppUtil;
import com.prettyyes.user.core.utils.LogUtil;
import com.umeng.socialize.sina.message.BaseResponse;
import org.xutils.common.util.MD5;
import java.io.File;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import static com.prettyyes.user.AppConfig.getUrl;
/**
* Created by Hornen on 15/9/21.
*/
public abstract class BaseRequest<T> {
public final String TAG = getClass().getName();
private final static String SECRET_KEY = "UKOWEB802N";
private ACache mACache;
public BaseRequest() {
mACache = ACache.get(BaseApplication.getAppContext());
}
private String generalCacheKey() {
Map<String, String> newMap = new HashMap<>();
newMap.putAll(getStringParams());
newMap.put("a", getAction());
newMap.put("g", getGroup());
newMap.put("m", getModule());
return MD5.md5(JSON.toJSONString(newMap));
}
protected boolean needCache() {
return false;
}
public String getCache(String key) {
return mACache.getAsString(key);
}
public void removeCache(String key) {
mACache.remove(key);
}
public void putCache(String key, String data) {
mACache.put(key, data, 30 * ACache.TIME_DAY);
}
private String generalSignature(Map<String, String> params) {
TreeMap<String, String> treeMap = new TreeMap<String, String>(params);
StringBuilder builder = new StringBuilder(SECRET_KEY);
for (Map.Entry<String, String> entry : treeMap.entrySet()) {
builder.append(entry.getKey());
builder.append(entry.getValue());
}
builder.append(SECRET_KEY);
return MD5.md5(builder.toString()).toUpperCase(Locale.US);
}
/**
* do post request
*
* @param callback
*/
public void post(NetReqCallback<T> callback) {
// NetReqCallback netReqCallback = setReqCallback(callback);
// if (netReqCallback == null)
// return;
try {
HttpAccess.getInstance().postAsyn(getPostUrl(), setParams(), setType(), callback, needCache());
} catch (Exception e) {
e.printStackTrace();
callback.apiRequestFail(e.getMessage(), getMethod());
}
}
public void postFile(ProgressCallback progressCallback) {
try {
HttpAccess.getInstance().upLoadFileAsyn(getPostUrl(), setParams(),file_path , progressCallback);
} catch (Exception e) {
e.printStackTrace();
progressCallback.onFail(e.toString(), e.toString());
}
}
public void get(final NetReqCallback<T> callback) {
try {
HttpAccess.getInstance().getAsyn(getPostUrl(), setType(), callback);
} catch (Exception e) {
e.printStackTrace();
callback.apiRequestFail(e.getMessage(), getMethod());
}
}
protected String method;
public BaseRequest<T> setMethod(String method) {
this.method = method;
return this;
}
public String getMethod() {
return method;
}
protected String getAction() {
return "";
}
protected String getGroup() {
Logger.d("getGroup not override");
return "interface";
}
protected String getModule() {
Logger.d("getModule not override");
return "meifou";
}
protected Map<String, String> getStringParams() {
Logger.d("getStringParams not override");
return new HashMap<String, String>();
}
protected Map<String, File> getFileParams() {
Logger.d("getFileParams not override");
return null;
}
protected Class<? extends BaseResponse> getResponseClass() {
Logger.d("getResponseClass not override");
return BaseResponse.class;
}
public abstract String setExtraUrl();
public String getPostUrl() {
return getUrl() + setExtraUrl();
}
public HashMap<String, Object> arrayMap = new HashMap<>();
public HashMap<String, Object> setParams() {
arrayMap.put("method", getMethod());
arrayMap.put("idfa", AppUtil.getIdfa());
arrayMap.put("channel", AppUtil.getAppChannel());
arrayMap.put("uuid", BaseApplication.UUID);
arrayMap.put("version", AppUtil.getVersionName());
arrayMap.put("api_url", getPostUrl());
return arrayMap;
}
public Type setType() {
Type genType = this.getClass().getGenericSuperclass();
LogUtil.i(TAG, "genType" + genType);
final Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
Type resultType = new ParameterizedType() {
@Override
public Type[] getActualTypeArguments() {
return new Type[]{params[0]};
}
@Override
public Type getOwnerType() {
return null;
}
@Override
public Type getRawType() {
return ApiResContent.class;
}
};
LogUtil.i(TAG, "resultType" + resultType);
return resultType;
}
public String file_path;
}
|
Java
|
UTF-8
| 1,712
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
package com.arinerron.forux.core;
import java.util.Iterator;
import java.util.HashMap;
import org.json.JSONObject;
public class Settings {
private Game game = null;
private JSONObject settings = null;
protected Settings(Game game) {
this.game = game;
this.loadDefaults();
}
public void loadDefaults() {
try {
this.settings = new JSONObject(this.getGame().getResourceManager().readFile(this.getGame().getResourceManager().getConfigurationFile()));
} catch(Exception e) {
this.getGame().getLogger().error(e);
}
}
public void saveDefaults() {
try {
this.getGame().getResourceManager().writeFile(this.getGame().getResourceManager().getConfigurationFile(), this.settings.toString(4));
} catch(Exception e) {
this.getGame().getLogger().error(e);
}
}
public void set(String key, Object val) {
this.settings.put(key, val);
}
public String getSettings() {
return this.settings.toString(4);
}
public Object get(String key) {
return settings.get(key);
}
public String getString(String key) {
return "" + this.get(key);
}
public int getInt(String key) {
return Integer.parseInt(this.getString(key));
}
public float getFloat(String key) {
return Float.parseFloat(this.getString(key));
}
public double getDouble(String key) {
return Double.parseDouble(this.getString(key));
}
public boolean getBoolean(String key) {
return Boolean.parseBoolean(this.getString(key));
}
public Game getGame() {
return this.game;
}
}
|
PHP
|
UTF-8
| 7,437
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
<?php
declare(strict_types=1);
namespace Domain\Models;
use App\Repositories\CompanyRepository;
use App\Services\DomainCollection;
final class Company extends DomainModel
{
/** @var int */
private $id;
/** @var string */
private $name;
/** @var string */
private $kana;
/** @var PostalCode */
private $postalCode;
/** @var string */
private $address;
/** @var string */
private $building;
/** @var string */
private $tel;
/** @var string */
private $fax;
/** @var Email */
private $email;
/** @var Count */
private $userLimit;
/** @var Datetime */
private $startsAt;
/** @var Datetime */
private $endsAt;
/** @var Datetime */
private $createdAt;
/** @var Datetime */
private $updatedAt;
/** @var Datetime */
private $deletedAt;
/** @var int */
private $planId;
/** @var int */
private $prefectureId;
/**
* @param CompanyRepository|null $repo
* @return void
*/
public function __construct(CompanyRepository $repo = null)
{
$this->repo = is_null($repo) ? new CompanyRepository : $repo;
}
/**
* @return int|null
*/
public function id(): ?int
{
return $this->id;
}
/**
* @return string|null
*/
public function name(): ?string
{
return $this->name;
}
/**
* @return string|null
*/
public function kana(): ?string
{
return $this->kana;
}
/**
* @return PostalCode|null
*/
public function postalCode(): ?PostalCode
{
return $this->postalCode;
}
/**
* @return string|null
*/
public function address(): ?string
{
return $this->address;
}
/**
* @return string|null
*/
public function building(): ?string
{
return $this->building;
}
/**
* @return string|null
*/
public function tel(): ?string
{
return $this->tel;
}
/**
* @return string|null
*/
public function fax(): ?string
{
return $this->fax;
}
/**
* @return Email|null
*/
public function email(): ?Email
{
return $this->email;
}
/**
* @return Count|null
*/
public function userLimit(): ?Count
{
return $this->userLimit;
}
/**
* @return Datetime|null
*/
public function startsAt(): ?Datetime
{
return $this->startsAt;
}
/**
* @return Datetime|null
*/
public function endsAt(): ?Datetime
{
return $this->endsAt;
}
/**
* @return Datetime|null
*/
public function createdAt(): ?Datetime
{
return $this->createdAt;
}
/**
* @return Datetime|null
*/
public function updatedAt(): ?Datetime
{
return $this->updatedAt;
}
/**
* @return Datetime|null
*/
public function deletedAt(): ?Datetime
{
return $this->deletedAt;
}
/**
* @return int|null
*/
public function planId(): ?int
{
return $this->planId;
}
/**
* @return Plan|null
*/
public function plan(): ?Plan
{
return $this->repo->plan();
}
/**
* @return int|null
*/
public function prefectureId(): ?int
{
return $this->prefectureId;
}
/**
* @return Prefecture|null
*/
public function prefecture(): ?Prefecture
{
return $this->repo->prefecture();
}
/**
* @param array $args
* @return DomainCollection
*/
public function customers(array $args = []): DomainCollection
{
return $this->repo->customers($args);
}
/**
* @param array $args
* @return DomainCollection
*/
public function stores(array $args = []): DomainCollection
{
return $this->repo->stores($args);
}
/**
* @param array $args
* @return DomainCollection
*/
public function tags(array $args = []): DomainCollection
{
return $this->repo->tags($args);
}
/**
* @param array $args
* @return DomainCollection
*/
public function users(array $args = []): DomainCollection
{
return $this->repo->users($args);
}
/**
* @param CompanyRepository $repo
* @return self
*/
public static function of(CompanyRepository $repo): self
{
return (new self($repo))->propertiesByArray($repo->attributesToArray());
}
/**
* @param array $args
* @return self
*/
public static function ofByArray(array $args = []): self
{
return (new self(new CompanyRepository))->propertiesByArray($args);
}
/**
* @param array $args
* @return self
*/
protected function propertiesByArray(array $args = []): self
{
$args = collect($args);
if ($args->has($key = 'id')) {
$this->{$camel = camel_case($key)} = $args->get($key);
}
if ($args->has($key = 'name')) {
$this->{$camel = camel_case($key)} = $args->get($key);
}
if ($args->has($key = 'kana')) {
$this->{$camel = camel_case($key)} = $args->get($key);
}
if ($args->has($key = 'postal_code')) {
$this->{$camel = camel_case($key)} = is_null($args->get($key)) ? null : PostalCode::of($args->get($key));
}
if ($args->has($key = 'address')) {
$this->{$camel = camel_case($key)} = $args->get($key);
}
if ($args->has($key = 'building')) {
$this->{$camel = camel_case($key)} = $args->get($key);
}
if ($args->has($key = 'tel')) {
$this->{$camel = camel_case($key)} = $args->get($key);
}
if ($args->has($key = 'fax')) {
$this->{$camel = camel_case($key)} = $args->get($key);
}
if ($args->has($key = 'email')) {
$this->{$camel = camel_case($key)} = is_null($args->get($key)) ? null : Email::of($args->get($key));
}
if ($args->has($key = 'user_limit')) {
$this->{$camel = camel_case($key)} = Count::of($args->get($key));
}
if ($args->has($key = 'starts_at')) {
$this->{$camel = camel_case($key)} = is_null($args->get($key)) ? null : Datetime::of($args->get($key));
}
if ($args->has($key = 'ends_at')) {
$this->{$camel = camel_case($key)} = is_null($args->get($key)) ? null : Datetime::of($args->get($key));
}
if ($args->has($key = 'created_at')) {
$this->{$camel = camel_case($key)} = is_null($args->get($key)) ? null : Datetime::of($args->get($key));
}
if ($args->has($key = 'updated_at')) {
$this->{$camel = camel_case($key)} = is_null($args->get($key)) ? null : Datetime::of($args->get($key));
}
if ($args->has($key = 'deleted_at')) {
$this->{$camel = camel_case($key)} = is_null($args->get($key)) ? null : Datetime::of($args->get($key));
}
if ($args->has($key = 'plan_id')) {
$this->{$camel = camel_case($key)} = $args->get($key);
}
if ($args->has($key = 'prefecture_id')) {
$this->{$camel = camel_case($key)} = $args->get($key);
}
return $this;
}
}
|
Markdown
|
UTF-8
| 8,981
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
---
id: 589
title: Open Source Education
date: 2010-04-08T08:14:59+00:00
author: Miles Berry
layout: post
comments: true
guid: http://milesberry.net/?p=589
permalink: /2010/04/open-source-education/
image:
feature: 100315.jpg
categories:
- Curriculum
- Open Source
---
<p class="rteindent1" style="padding-left: 30px;">
<em>My ‘provocation paper’ for the recent <a href="http://opensourceschools.org.uk">Open Source Schools</a> think tank.</em>
</p>
Open source or software freedom isn’t simply another way of procuring software, it’s more a state of mind, a particular attitude to technology. Of course, you _can_ just treat it as a cheap way of getting high quality, robust code, and there’s certainly no requirement to grow a beard, wear sandals or drink real ale in order to install open source applications. However, the philosophies that lie at the core of open source as a movement are important, and, I think have much to offer to education more generally; furthermore, open source approaches to development can apply to things even more important than software, such as curriculum resources, school policies and even the curriculum itself. This brief paper seeks to explore some of these areas.
<!--more-->There are strong parallels between an open source approach to software development and some educational theory. Piaget, Montessouri, Froebel and Dewey all placed emphases, to varying extents, on the importance of play, exploration and direct experience; qualities which will not be unfamiliar to those developing open source software. Vygotsky’s social constructivism argues that meaning is something developed through conversation with others, anticipating the importance of efficient and effective communication in the development of open source projects involving more than a sole developer. Papert’s notion of constructionism, in which knowledge comes to be embodied in the development of shared, public artifacts continues to be of importance in computing education, and is the pedagogic approach that has underpinned Moodle’s phenomenal development as an open source VLE.
So what does an open source approach to education look like? ‘Access to the source code’ surely implies a willingness to adopt transparent approaches in education, in which freedom of information requests about school curricula, schemes of work and policies are never needed, as these, and perhaps other, documents are shared as a matter of routine with all of a school’s stakeholders – thus not only is collaborative planning made possible amongst the teaching team, but pupils and parents too have access to lesson plans, enabling them to read ahead and to become something closer to partners in the educational process. Similarly, such openness would suggest, as a default position, a willingness to share pupils’ work and pupils’ data as widely as appropriate, with children’s work on the school website or blog and an enthusiastic approach to the parental engagement agenda.
This equivalent of ‘access to the source code’ of education is pretty much necessary if teachers are to be empowered as professionally autonomous and accountable, and if pupils are to be empowered as independent learners, each taking their full share of the responsibility for the learning that takes place in their classes. The opportunities to take control over the ‘what’ and ‘how’ of learning, and perhaps to start addressing the ‘why’ of education, provide many opportunities for a radical step change from the present top-down approach, as we’ve seen on many occasions with open source software development, most clearly with the open nature of the Internet. This provides teachers, and other stakeholders, with the opportunity, or even responsibility to engage in creative, innovative ‘tinkering’ with the education in their classes, and to collaborate with others in sharing this practice:
<p class="rteindent1" style="padding-left: 30px;">
<em>The ‘tinkering’ teacher is an individualised embryo of institutional knowledge creation. When such tinkering becomes more systematic, more collective and explicitly managed, it is transformed into knowledge creation” (Hargreaves, 1999)</em>
</p>
The ‘four freedoms’ of the [free software definition](http://www.gnu.org/philosophy/free-sw.html) would have even more radical consequences when applied to education: _the freedom to run the program for any purpose_, implies, I think, not only an education without charge, but also one which built on the principle of children developing the critical and cognitive skills to think things through for themselves, rather than accepting political, religious or cultural dogmas – something akin to the rational autonomy that can be seen as an overarching aim for education; _the freedom to study how the program works and change it to make it do as you wish_, would, if applied to education, mean that personalisation would have to be taken seriously, in ‘choice and voice’ terms, not merely as alternative modes of presentation or assessment, it would mean students having a real say in what and how they learn; _the freedom to redistribute copies_ would firstly imply an end to schools keeping their curriculum and resources to themselves, moving towards a position in which publicly funded schemes of work and materials are readily available to any who would wish to make use of them; this would be extended by the fourth freedom, _the freedom to distribute modified copes to others_ to produce a culture of genuine collaboration and partnership between teachers and their schools.
The communities of practice which grow up around open source projects could have much in common with the networks and communities of educational, curricular and pedagogic ‘developers’ which school leaders and teachers have the potential to become, if given the necessary encouragement, opportunities and freedom. Loose communities of teachers working together to develop educational resources, schemes of work or other educational innovation would foster creativity, ownership, and the legitimate peripheral participation [ref] necessary for professional development, as well as being a highly cost effective way of producing some great educational benefits over and beyond education technology. As Hargreaves (1999) has it:
<p class="rteindent1" style="padding-left: 30px;">
<em>“Transfer is difficult to achieve for it involves far more than telling or simply providing information… This is most easily achieved when a teacher tinkers with information derived from another’s professional practice.”</em>
</p>
In practical terms, what’s needed now is a shift away from Crown Copyright schemes of work, National Strategies and glossy commercial schemes and resources to local or distributed networks of teachers, technologists and pupils working together to produce the ‘public knowledge artefacts’ which embody their understanding of their subjects and of pedagogy, and which can be freely adapted and re-used by those working in similar, or widely different schools elsewhere. Rather than spending public funds on commercial schemes, consultants and developers, why not fund just a few cover periods, or pay a little overtime, for teachers and their colleagues to work together to develop these materials for their pupils and for others’?
Just as the Internet made it possible for worldwide communities of developers to work on open source code together, so the web provides at least some of the mechanisms for collaboration on open content: we have a whole host of creative commons licenses to choose between; [wikibooks](http://en.wikibooks.org/wiki/Main_Page), [wikijunior](http://en.wikibooks.org/wiki/Wikijunior) and [curriki](http://www.curriki.org) have made a fine start to the collaborative development of online texts and learning materials; web 2.0 repositories like slideshare, flickr and blip.tv provide support for creative commons licensed content; and many universities are starting to share their content openly, including at least [some materials from the Open University](http://labspace.open.ac.uk/) here. I’m optimistic that the [National Digital Resource Bank](http://www.ndrb.org.uk/) will encourage local authorities, schools and teachers to share materials, [Vital’s Open Course Movement](http://www.vital.ac.uk/community/mod/ouwiki/view.php?id=138&page=The+Open+Course+Movement) approach to some of their ICT CPD courses bodes very well, as does their default Creative Commons licensing. Perhaps even more impressive is the willingness with which teachers engage with collaborative projects happening beyond institutional boundaries such Tom Barrett’s [Curriculum Catalyst](http://edte.ch/blog/the-curriculum-catalyst/), Doug Belshaw’s [Move Me On](http://dougbelshaw.com/blog/2009/12/21/movemeon-book-now-available/) and the [TeachMeets](http://www.teachmeet.org.uk/).
|
Python
|
UTF-8
| 9,270
| 2.59375
| 3
|
[] |
no_license
|
import numpy as np
from aux import Generic
def fit_h(xs, y, wdws_d, order, method, params, return_model=False):
if method == 'built-in':
# sklearn built-in method
model = params['model']
wdw_lens = [wdws_d[x_name][1] - wdws_d[x_name][0] for x_name in order]
x_xtd = make_extended_predictor_matrix(
vs=xs, windows=wdws_d, order=order)
valid = np.all(~np.isnan(x_xtd), axis=1) & (~np.isnan(y))
if np.sum(valid) <= x_xtd.shape[1] + 1:
print('Not enough valid data points.')
hs = {
x_name: np.nan * np.zeros(wdw_len)
for x_name, wdw_len in zip(order, wdw_lens)}
icpt = np.nan
y_hat = np.nan * np.zeros(len(y))
r2 = np.nan
else:
rgr = model()
rgr.fit(x_xtd[valid], y[valid])
# get concatenated filters
h_xtd = rgr.coef_.copy()
# get individual filters
hs_split = np.split(h_xtd, np.cumsum(wdw_lens)[:-1])
hs = {x_name: h for x_name, h in zip(order, hs_split)}
icpt = rgr.intercept_
y_hat = np.nan * np.zeros(len(y))
y_hat[valid] = rgr.predict(x_xtd[valid])
r2 = rgr.score(x_xtd[valid], y[valid])
elif method == 'wiener':
raise NotImplementedError('Weiner fitting not implemented yet.')
else:
raise ValueError('Method not recognized.')
if return_model:
return hs, icpt, y_hat, r2, rgr
else:
return hs, icpt, y_hat, r2
def fit_h_train_test(
trial, x_names, y_name, wdws, train_len, test_len,
method, params, C, allow_nans=False):
"""
Fit a filter mapping one trial variable to another.
:return:
FitResult object with attributes:
trial_name
x_names
y_name
wdws
wdws_dsct
train
test
t
xs
y
r2_train
y_hat_train
r2_test
y_hat_test
t_h
h
"""
# get variables of interest
## 1D array
t = getattr(trial.dl, 't')
## dict of 1D arrays with variable names as keys
xs = {x_name: getattr(trial.dl, x_name) for x_name in x_names}
## 1D array
y = getattr(trial.dl, y_name)
## number of time steps
n_t = len(t)
# discretize moving window size
## dict of 2-element integer tuples with variable name as keys
wdws_d = {
x_name: (int(round(wdw[0] / C.DT)), int(round(wdw[1] / C.DT)))
for x_name, wdw in wdws.items()
}
# make filter time vectors
## dict of 1D arrays with variable names as keys
t_hs = {
x_name: np.arange(*wdw_d) * C.DT
for x_name, wdw_d in wdws_d.items()
}
if test_len:
# discretize training and test lengths
train_len_d = int(round(train_len / C.DT))
test_len_d = int(round(test_len / C.DT))
chunk_len_d = train_len_d + test_len_d
# extract training chunks from data
## get start and end points such that filter windows have no nans
valid_start = max(np.max([-wdw_d[0] for wdw_d in wdws_d.values()]), 0)
valid_end = min(np.min([n_t-wdw_d[1]+1 for wdw_d in wdws_d.values()]), n_t)
if not allow_nans:
# make sure there are no NaNs
for x in xs.values():
assert np.all(~np.isnan(x[valid_start:valid_end]))
assert np.all(~np.isnan(y[valid_start:valid_end]))
n_valid = valid_end - valid_start
n_chunks = int((n_valid + test_len_d) / chunk_len_d)
train = np.zeros(n_t, bool)
test = np.zeros(n_t, bool)
# TO BECOME: list of dicts of 1D arrays with variable names for keys
x_chunks = []
# TO BECOME: 2D array
y_chunks = np.nan * np.zeros((n_chunks, train_len_d))
# fill in "chunks"
for chunk_ctr in range(n_chunks):
chunk_start = valid_start + (chunk_ctr * chunk_len_d)
chunk_end = chunk_start + train_len_d
x_chunks.append(
{x_name: x[chunk_start:chunk_end] for x_name, x in xs.items()})
y_chunks[chunk_ctr, :] = y[chunk_start:chunk_end]
train[chunk_start:chunk_end] = True
test[chunk_end:chunk_end + test_len_d] = True
# fit filters for each chunk
hs = {x_name: [] for x_name in x_names}
icpts = np.nan * np.zeros(n_chunks)
for chunk_ctr, (x_chunk, y_chunk) in enumerate(zip(x_chunks, y_chunks)):
hs_chunk, icpt = fit_h(
x_chunk, y_chunk, wdws_d, x_names, method, params)
for x_name in x_names:
hs[x_name].append(hs_chunk[x_name])
icpts[chunk_ctr] = icpt
hs_mean = {x_name: np.nanmean(hs_, 0) for x_name, hs_ in hs.items()}
icpt_mean = np.nanmean(icpts, 0)
# calculate R2 on test data
x_xtd = make_extended_predictor_matrix(
vs=xs, windows=wdws_d, order=x_names)
h_mean_xtd = np.concatenate([hs_mean[x_name] for x_name in x_names])
y_hat = x_xtd.dot(h_mean_xtd) + icpt_mean
y_hat_train = np.nan * np.zeros(n_t)
y_hat_train[train] = y_hat[train]
y_hat_test = np.nan * np.zeros(n_t)
y_hat_test[test] = y_hat[test]
r2_train = calc_r2(y, y_hat_train)
r2_test = calc_r2(y, y_hat_test)
else:
print('Not splitting into test/training data.')
hs_mean, icpt_mean = fit_h(xs, y, wdws_d, x_names, method, params)
# make predictions on full dataset
x_xtd = make_extended_predictor_matrix(
vs=xs, windows=wdws_d, order=x_names)
h_mean_xtd = np.concatenate([hs_mean[x_name] for x_name in x_names])
y_hat_train = x_xtd.dot(h_mean_xtd) + icpt_mean
y_hat_test = np.nan * np.zeros(y_hat_train.shape)
r2_train = calc_r2(y, y_hat_train)
r2_test = np.nan
train = np.ones(n_t, bool)
test = np.zeros(n_t, bool)
fit_result_dict = {
'trial_name': trial.name,
'x_names': x_names,
'y_name': y_name,
'wdws': wdws,
'wdws_d': wdws_d,
'train': train,
'test': test,
'train_len': train_len,
'test_len': test_len,
't': t,
'xs': xs,
'y': y,
't_hs': t_hs,
'r2_train': r2_train,
'r2_test': r2_test,
'y_hat_train': y_hat_train,
'y_hat_test': y_hat_test,
'hs': hs_mean,
'icpt': icpt_mean,
}
return Generic(**fit_result_dict)
def make_extended_predictor_matrix(vs, windows, order):
"""
Make a predictor matrix that includes offsets at multiple time points.
For example, if vs has 2 keys 'a' and 'b', windows is {'a': (-1, 1),
'b': (-1, 2)}, and order = ['a', 'b'], then result rows will look like:
[v['a'][t-1], v['a'][t], v['b'][t-1], v['b'][t], v['b'][t+1]]
:param vs: dict of 1-D array of predictors
:param windows: dict of (start, end) time point tuples, rel. to time point of
prediction, e.g., negative for time points before time point of
prediction
:param order: order to add predictors to final matrix in
:return: extended predictor matrix, which has shape
(n, (windows[0][1]-windows[0][0]) + (windows[1][1]-windows[1][0]) + ...)
"""
if not np.all([w[1] - w[0] >= 0 for w in windows.values()]):
raise ValueError('Windows must all be non-negative.')
n = len(list(vs.values())[0])
if not np.all([v.ndim == 1 and len(v) == n for v in vs.values()]):
raise ValueError(
'All values in "vs" must be 1-D arrays of the same length.')
# make extended predictor array
vs_extd = []
# loop over predictor variables
for key in order:
start, end = windows[key]
# make empty predictor matrix
v_ = np.nan * np.zeros((n, end-start))
# loop over offsets
for col_ctr, offset in enumerate(range(start, end)):
# fill in predictors offset by specified amount
if offset < 0:
v_[-offset:, col_ctr] = vs[key][:offset]
elif offset == 0:
v_[:, col_ctr] = vs[key][:]
elif offset > 0:
v_[:-offset, col_ctr] = vs[key][offset:]
# add offset predictors to list
vs_extd.append(v_)
# return full predictor matrix
return np.concatenate(vs_extd, axis=1)
def calc_r2(y, y_hat):
"""
Calculate an R^2 value between a true value
and a prediction.
"""
valid = (~np.isnan(y)) & (~np.isnan(y_hat))
if valid.sum() == 0:
return np.nan
else:
u = np.sum((y[valid] - y_hat[valid]) ** 2)
v = np.sum((y[valid] - y_hat[valid].mean()) ** 2)
return 1 - (u/v)
|
JavaScript
|
UTF-8
| 1,164
| 2.703125
| 3
|
[] |
no_license
|
module.exports =
{
getDagTotal: function(dag_begin, dag_eind, pauze)
{
dag_begin = this.trim(dag_begin);
dag_eind = this.trim(dag_eind);
pauze = this.trim(pauze);
var dateBegin = new Date("01/01/2017 " + dag_begin);
var dateEind = new Date("01/01/2017 " + dag_eind);
if (dateEind < dateBegin)
{
dateEind = new Date("01/02/2017 " + dag_eind);
}
var difference = new Date(dateEind.getTime() - dateBegin.getTime());
var pauzeTime = new Date("01/01/2017 " + pauze);
var hours = difference.getHours() - pauzeTime.getHours();
var minutes = difference.getMinutes() - pauzeTime.getMinutes();
if (minutes < 0)
{
minutes = 60 + minutes;
hours -= 1;
}
if (hours < 0)
{
hours = 0;
}
return (hours > 10 ? hours : "0" + hours) + ":" + (minutes > 10 ? minutes : "0" + minutes);
},
trim: function(time)
{
if (time.length > 5)
{
return time.substr(0,5);
}
return time;
}
}
|
Python
|
UTF-8
| 2,956
| 2.59375
| 3
|
[] |
no_license
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import os
get_ipython().magic('matplotlib inline')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.preprocessing import LabelBinarizer, LabelEncoder
from sklearn.metrics import confusion_matrix
from tensorflow.contrib.keras.python import keras
from tensorflow.contrib.keras.python.keras.models import Sequential
from tensorflow.contrib.keras.python.keras.layers import Dense, Activation, Dropout
from tensorflow.contrib.keras.python.keras.preprocessing import text, sequence
from tensorflow.contrib.keras.python.keras import utils
import glob
import pandas as pd
body=[]
all_files = glob.glob('spam_data/0*.txt')
for fileName in all_files:
file = open(fileName, encoding = "ISO-8859-1")
body.append(file.read())
file.close()
body_file = pd.DataFrame(data = body,columns = ['post'])
body_file
label_file = pd.read_csv('spam_data/labels.txt',header = None,delimiter=" ",names=["label",'Name'])
label_file
body_file["post"]
train_size = int(len(body_file) * .5)
print ("Train size: %d" % train_size)
print ("Test size: %d" % (len(body_file) - train_size))
train_posts = body_file['post'][:train_size]
train_tags = label_file['label'][:train_size]
test_posts = body_file['post'][train_size:]
test_tags = label_file['label'][train_size:]
train_posts
len(train_posts), len(train_tags)
len(test_posts), len(test_tags)
max_words = 10
tokenize = text.Tokenizer(num_words=max_words, char_level=False)
tokenize.fit_on_texts(train_posts) # only fit on train
text = "the"
tokenize.texts_to_matrix([text])
x_train = tokenize.texts_to_matrix(train_posts)
x_test = tokenize.texts_to_matrix(test_posts)
print(tokenize.word_index)
encoder = LabelEncoder()
encoder.fit(train_tags)
y_train = encoder.transform(train_tags)
y_test = encoder.transform(test_tags)
np.max(y_train) + 1
num_classes = np.max(y_train) + 1
y_train = utils.to_categorical(y_train, num_classes)
y_test = utils.to_categorical(y_test, num_classes)
print('x_train shape :', x_train.shape)
print('x_test shape :', x_test.shape)
print('y_train shape :', y_train.shape)
print('y_test shape :', y_test.shape)
batch_size = 32
epochs = 5
model = Sequential()
model.add(Dense(512, input_shape=(max_words,)))
model.add(Activation('relu'))
model.add(Dense(num_classes))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
history = model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_split=0.1)
score = model.evaluate(x_test, y_test,
batch_size=batch_size, verbose=1)
print('Test score:', score[0])
print('Test accuracy:', score[1])
y_train
|
Java
|
ISO-8859-1
| 1,315
| 2.71875
| 3
|
[] |
no_license
|
package cartes.effets;
import partie.autres.personnage.Personnage;
import partie.partie.Partie;
public class Degats_heros_adverse extends Degats {
/**
* Classe reprsentant l'effet dgts_hros_adverse qui inflige des dgats au hros dont ce n'est pas
* le tour
* Hrite de dgats.
*
* @author GRESSET Nathan
* @author GRINWALD Louis
*
* @see Degats
*/
private Partie partie;
public Degats_heros_adverse(String description, String nom, String type, int nbDegats, Partie partie) {
super(description, nom, type, nbDegats);
this.partie = partie;
}
public Partie getPartie() {
return partie;
}
public void setPartie(Partie partie) {
this.partie = partie;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Degats_heros_adverse other = (Degats_heros_adverse) obj;
if (partie == null) {
if (other.partie != null)
return false;
} else if (!partie.equals(other.partie))
return false;
return true;
}
@Override
public boolean isCiblable() {
return false;
}
@Override
public void activer(Personnage p) {
partie.getJoueurQuiJouePas().getHeros().prendreDegats(getNbDegats());
}
}
|
Java
|
UTF-8
| 2,716
| 2.265625
| 2
|
[] |
no_license
|
package com.example.subhadiproy.imageslider;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.smarteist.autoimageslider.DefaultSliderView;
import com.smarteist.autoimageslider.IndicatorAnimations;
import com.smarteist.autoimageslider.SliderLayout;
import com.smarteist.autoimageslider.SliderView;
public class MainActivity extends AppCompatActivity {
private SliderLayout sliderLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
sliderLayout = (SliderLayout)findViewById(R.id.imageSlider);
sliderLayout.setIndicatorAnimation(IndicatorAnimations.FILL);
sliderLayout.setScrollTimeInSec(1);
setSliderViews();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, news.class);
startActivity(i);
}
});
}
private void setSliderViews(){
for(int i=0;i<=3;i++){
DefaultSliderView sliderView = new DefaultSliderView(this);
switch (i){
case 0:
sliderView.setImageDrawable(R.drawable.image_1);
sliderView.setDescription("One");
break;
case 1:
sliderView.setImageDrawable(R.drawable.image_2);
sliderView.setDescription("Two");
break;
case 2:
sliderView.setImageDrawable(R.drawable.image_3);
sliderView.setDescription("Three");
break;
case 3:
sliderView.setImageDrawable(R.drawable.image_4);
sliderView.setDescription("Four");
break;
}
sliderView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
sliderView.setDescription("setDescription" +(i+1));
final int finalI = i;
sliderView.setOnSliderClickListener(new SliderView.OnSliderClickListener() {
@Override
public void onSliderClick(SliderView sliderView) {
Toast.makeText(MainActivity.this, "Toast", Toast.LENGTH_SHORT).show();
}
});
sliderLayout.addSliderView(sliderView);
}
}
}
|
Markdown
|
UTF-8
| 701
| 2.515625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
Configuration script
=====================
This script enable the creation of a zip archive containing the pages of the volume/chapter being feed to it.
The script can either handle a single archive in the current active directory, or several of them by considering any directory in the active directory as containing a chapter, and will create archives whose name will be guessed as 'Chapitre_$nameOfDirectory'
Basically, name your directories as the # of the chapter and you're good to go.
Be carefull, the script will rename pages according to its internal logic (pageNumber.ext) and will add a config.dat
===
I plan to rewrite it in a better looking UI but don't really have the time lately :X
|
C++
|
UTF-8
| 1,255
| 2.859375
| 3
|
[] |
no_license
|
#include "Inventory.h"
#include "GameObject.h"
#include <iostream>
#include "KeyActivator.h"
#include "KeyTarget.h"
#include "FixedKeyTarget.h"
Inventory::Inventory()
{
}
Inventory::~Inventory()
{
}
bool Inventory::hasKey()
{
return key != nullptr;
}
GameObject * Inventory::getKey()
{
return key;
}
void Inventory::setKey(GameObject * key)
{
if (key != nullptr && !hasKey()) {
std::cout << "Picked up key for keyHole " << key->getComponent<KeyActivator>()->keyHoleID << std::endl;
this->key = key;
GameObject * hand = this->gameObject->transform.children[0]->children[1]->gameObject;
hand->addChild(key);
key->transform.setPosition(0.0f, 0.0f, 0.0f);
FixedKeyTarget * fixedKeyTarget = key->getComponent<FixedKeyTarget>();
KeyTarget * keyTarget = key->getComponent<KeyTarget>();
if (fixedKeyTarget != nullptr) {
fixedKeyTarget->pickedUp = true;
}
else if (keyTarget != nullptr) {
keyTarget->pickedUp = true;
}
}
}
void Inventory::removeKey() {
if (this->key != nullptr) {
std::cout << "removing key from inventory" << std::endl;
GameObject * hand = this->gameObject->transform.children[0]->children[1]->gameObject;
hand->removeChild(key);
((GameObject *)this->key)->destroy();
this->key = nullptr;
}
}
|
Java
|
UTF-8
| 1,844
| 2.875
| 3
|
[] |
no_license
|
/*
* This class is part of the book "iText in Action - 2nd Edition"
* written by Bruno Lowagie (ISBN: 9781935182610)
* For more info, go to: http://itextpdf.com/examples/
* This example only works with the AGPL version of iText.
*/
package part1.chapter05;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
public class Hero3 extends Hero1 {
/** The resulting PDF file. */
public static final String RESULT = "results/part1/chapter05/hero3.pdf";
/**
* Creates a PDF document.
* @param filename the path to the new PDF document
* @throws DocumentException
* @throws IOException
*/
public void createPdf(String filename) throws IOException, DocumentException {
// step 1
Document document = new Document(PageSize.A4);
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
Rectangle art = new Rectangle(50, 50, 545, 792);
writer.setBoxSize("art", art);
// step 3
document.open();
// step 4
PdfContentByte content = writer.getDirectContent();
PdfTemplate template = createTemplate(content, PageSize.A4, 1);
content.addTemplate(template, 0, 0);
// step 5
document.close();
}
/**
* Main method.
* @param args no arguments needed
* @throws DocumentException
* @throws IOException
*/
public static void main(String[] args)
throws IOException, DocumentException {
new Hero3().createPdf(RESULT);
}
}
|
Python
|
UTF-8
| 482
| 3.984375
| 4
|
[] |
no_license
|
#全局作用域
#全局变量:函数外部定义的变量,叫做全局变量
#局部变量:在函数内部定义的变量,仅限函数内部可以使用,函数外部无法使用
def add(a,b):
#局部作用域
c=a+b
return c
#不能直接使用c
#TODO:局部变量不能在全局作用域获取
c=add(4,5)
print(c)
#TODO:局部作用域可以使用全局变量
C=6
def minus(a,b):
d=a+b
print(d-c)
return d-c
minus(3,7)
|
Swift
|
UTF-8
| 2,351
| 2.734375
| 3
|
[] |
no_license
|
//
// SampleViewController.swift
// hackGSU
//
// Created by Viraj Shah on 10/3/16.
// Copyright © 2016 hackGSU. All rights reserved.
//
import UIKit
class SampleViewController: UITableViewController{
override func viewDidLoad() {
super.viewDidLoad()
projects.append(["Project 1: Storm Viewer", "Constants and variables, UITableView, UIImageView, FileManager, storyboards"])
projects.append(["Project 2: Guess the Flag", "@2x and @3x images, asset catalogs, integers, doubles, floats, operators (+= and -=), UIButton, enums, CALayer, UIColor, random numbers, actions, string interpolation, UIAlertController"])
projects.append(["Project 3: Social Media", "UIBarButtonItem, UIActivityViewController, the Social framework, URL"])
projects.append(["Project 4: Easy Browser", "loadView(), WKWebView, delegation, classes and structs, URLRequest, UIToolbar, UIProgressView., key-value observing"])
projects.append(["Project 5: Word Scramble", "Closures, method return values, booleans, NSRange"])
projects.append(["Project 6: Auto Layout", "Get to grips with Auto Layout using practical examples and code"])
projects.append(["Project 7: Whitehouse Petitions", "JSON, Data, UITabBarController"])
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
let cellId = "cellId"
var projects = [[String]]()
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return projects.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let project = projects[indexPath.row]
cell.textLabel?.text = "\(project[0]): \(project[1])"
return cell
}
}
|
JavaScript
|
UTF-8
| 1,302
| 2.546875
| 3
|
[] |
no_license
|
function render() {
// Additional params including the callback, the rest of the params will
// come from the page-level configuration.
var additionalParams = {
'callback': signinCallback
};
// Attach a click listener to a button to trigger the flow.
var signinButton = document.getElementById('signinButton');
signinButton.addEventListener('click', function() {
gapi.auth.signIn(additionalParams); // Will use page level configuration
});
}
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
$.post("accessToken.php",authResult.access_token).always(function(){
location.reload(); //lehe refreshimiseks
});
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
$(document).ready(function(){
$("#signoutButton").click(function(){
$.post("logout.php").always(function(){
location.assign("index.php");
});
});
});
|
C++
|
UTF-8
| 1,412
| 3.515625
| 4
|
[] |
no_license
|
//
// complexConstructorClass.cpp
// c++new
//
// Created by 彭涧 on 2021/4/24.
//
#include "complexConstructorClass.hpp"
// 结论:调用构造函数和析构函数时按相反的顺序执行
// 函数参数使用对象的引用不产生副本,推荐使用引用
// 复制构造函数
PointC::PointC(const PointC& b) {
x = b.x;
y = b.y;
cout << "PointC Copy Initializing: " << x << " , " << y << endl;
}
PointD::PointD(const PointD& b) {
x = b.x;
y = b.y;
cout << "PointD Copy Initializing: " << x << " , " << y << endl;
}
void complexDisplay (PointC p) {
p.show();
}
void complexDisplay2 (PointC &p) {
p.show();
}
void complexDisplay (PointD p) {
p.show();
}
void complexDisplay2 (PointD &p) {
p.show();
}
PointC getPointC(int a, int b){
PointC A(a, b);
return A;
}
void testComplexConstructroClass() {
PointC A(42,35); // 产生 A 对象
// 第一次调用复制构造函数
PointC B(A); // (1) 用 A 初始化 B
PointC C(58, 94); // 产生 C 对象
PointD D(10, 10);
cout << " ---- called complesDisplay(A) ---- " << endl;
complexDisplay(D); // 对象 B 作为参数
cout << " ---- Next ... ----" << endl;
complexDisplay2(D);
cout << " ---- call G = getPointC() ---- " << endl;
C = getPointC(1001, 1001);
complexDisplay2(C);
cout << " ---- over ----" << endl;
}
|
SQL
|
UTF-8
| 1,367
| 2.6875
| 3
|
[] |
no_license
|
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50612
Source Host : localhost:3306
Source Database : shop_1808
Target Server Type : MYSQL
Target Server Version : 50612
File Encoding : 65001
Date: 2018-09-29 16:37:23
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for shop_user
-- ----------------------------
DROP TABLE IF EXISTS `shop_user`;
CREATE TABLE `shop_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(20) NOT NULL,
`mark` varchar(100) DEFAULT NULL,
`ps` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of shop_user
-- ----------------------------
INSERT INTO `shop_user` VALUES ('2', 'xixi', '123', '1', null);
INSERT INTO `shop_user` VALUES ('6', '亚索', '12e', '3', null);
INSERT INTO `shop_user` VALUES ('7', 'pppp', '12e', '3', null);
INSERT INTO `shop_user` VALUES ('8', 'xixi2', '12e', '1', null);
INSERT INTO `shop_user` VALUES ('13', 'qudou', '11_11_22', '1', null);
INSERT INTO `shop_user` VALUES ('34', 'q', '123', null, '自动注册');
INSERT INTO `shop_user` VALUES ('52', '李青', '123', null, null);
INSERT INTO `shop_user` VALUES ('53', '李青2', '123', null, null);
|
Markdown
|
UTF-8
| 2,896
| 3.21875
| 3
|
[] |
no_license
|
# hawkfly-domain-dockerfiles
Docker images and docker-compose files for some basic scenarios in which the hawkular is used for monitoring the WildFly servers managed as a domain. You may want to use the simple CLI tool called [hawkinit](https://github.com/Jiri-Kremser/hawkinit) to spawn the containers.
[](https://travis-ci.org/Jiri-Kremser/hawkinit)
## Usage
1. choose a scenario
`cd scenarios/1-host/mid-size`
1. run it
`docker-compose up`
## Scenarios
#### default
This creates the domain mode consisting of two server groups and three servers, the third server isn't started automatically. This scenario is the default domain mode when running the domain.sh with the servers declared in the default `host.xml` and groups in the default `domain.xml`
#### simple
This scenario and the following ones drop the default groups (as described ^) and servers and creates a new ones. Simple scenario has one server group called `my-group` and one server called `s`. ([cli init script](https://github.com/Jiri-Kremser/hawkfly-domain-dockerfiles/blob/master/images/master/01-small-domain/init/01-create-domain.cli))
#### mid-size
There are three pre-created server groups called `group1-3` and one server in each group called `s1-3`. ([cli init script](https://github.com/Jiri-Kremser/hawkfly-domain-dockerfiles/blob/master/images/master/02-mid-size-domain/init/01-create-domain.cli))
#### ha
There is only one server group called `ha-group` and two servers called `s1` and `s2`. Servers run with the `ha` profile so they should be clustered if the auto-discovery went well. ([cli init script](https://github.com/Jiri-Kremser/hawkfly-domain-dockerfiles/blob/master/images/master/03-ha-domain/init/01-create-domain.cli))
#### mixed
This scenario has two server groups. Thi first one is the same as in the `ha` scenario, i.e. the two clustered servers and the second one is the `normal-group` that has the `default` profile and two servers in it. ([cli scripts](https://github.com/Jiri-Kremser/hawkfly-domain-dockerfiles/tree/master/images/master/04-mixed-domain/init))
### 1 host vs n hosts
The `1 host` directory spawns a WildFly running on one host with some pre-created stuff, while the `n host` directory runs one server as the domain controller (master) and n hosts as slaves. By default the n is 1, but it can be easily increased by `docker-compose scale hawkfly-domain-{scenario}-slave=n`. Slaves connect to master with predefined credentials and can create also additional servers. Example of creating the additional server is [here](https://github.com/Jiri-Kremser/hawkfly-domain-dockerfiles/blob/master/scenarios/n-hosts/simple/docker-compose.yml#L23). It says: create two servers that should be part of the `my-group` group. The server names are created automatically from the slave's hostname.
|
SQL
|
UTF-8
| 1,402
| 3.671875
| 4
|
[] |
no_license
|
/* This is the old artifact */
/* Create adequate documentation starting here */
/* Make new database for Arkham Horror: The Board Game Third Edition, make timeouts */
USE messaging;
INSERT INTO person(person_id,first_name,last_name)
VALUES (20, "Clara", "Kellermann-Bryant");
/* Make new tables for the new database */
ALTER TABLE person ADD hair_color VARCHAR(25) NOT NULL; /* Properly define variables to be clear*/
UPDATE person
SET hair_color = 5
WHERE person_id = 2
LIMIT 5;
DELETE FROM person /* Use prepared statements for preventing SQL injections */
WHERE
first_name = "Diana"
AND
last_name = "Taurasi"
CREATE TABLE image (
image_id INT(8) UNISIGNED NOT NULL auto_increment, /* Eliminate redundant variables */
image_name VARCHAR(50) NOT NULL,
PRIMARY KEY (image_id)
) AUTO_INCREMENT = 1;
CREATE TABLE message_image ( /* Create properly nested logic constructs */
image_id INT(8) NOT NULL,
message_id INT(8) NOT NULL,
PRIMARY KEY (image_id, message_id)
) AUTO_INCREMENT = 1;
CREATE TABLE hello (
hello_id INT(8) NOT NULL auto_increment,
hello_name VARCHAR(62) NOT NULL,
PRIMARY KEY (hello_id)
) AUTO_INCREMENT = 1;
/*This is used as a demonstration of functionality */
CREATE TABLE horror (
horror_id INT(8) NOT NULL auto_increment,
horror_name VARCHAR(62) NOT NULL,
PRIMARY KEY (hello_id)
) AUTO_INCREMENT = 1;
|
Java
|
UTF-8
| 307
| 1.570313
| 2
|
[] |
no_license
|
/*
* The copyright of this file belongs to Koninklijke Philips N.V., 2019.
*/
package com.philips.casestudy2.springalertingsystem.service;
import com.philips.casestudy2.springalertingsystem.domain.PatientVitals;
public interface VitalValidationServiceForErrors {
String validateVitalsData(PatientVitals[] sample);
}
|
Markdown
|
UTF-8
| 889
| 2.78125
| 3
|
[] |
no_license
|
# 100daysofpython
## 100 days of code: Focusing on Python
The goal is to do 100 days of Python code to level up from novice +.
Starting by using Automate the Boring Stuff as a starting guide and then integrating projects.
## Things I'd like to learn:
1. Get better with loops
2. Work with more dicts/lists do more advanced loop
3. Better understanding on classes, init and magic methods
4. Learn web UI's and reg UI
5. Learn data analytic tools
## Exemptions on days:
The only time a day is allowed to be missed is if Rita and I go out of town and I don't bring a computer. If a day is missed due to this, the days must be made up as soon as possible.
## Keeping Track!
At the top of every file add a title and a day count:
> ##### ABS- Page ## <Project title>
> ##### Day x of 100
Here it notes ABS (Automate the Boring Stuff)- Page Number for reference and Project or test name.
|
Python
|
UTF-8
| 1,613
| 2.875
| 3
|
[] |
no_license
|
import json
map_list = dict({1: "缺少招生群助手", 2: "缺少话术助手", 4: "机器人心跳不正常", 8: "近似满员", 32: "群二维码过期", 64: "满员", 128: "二维码分享者中不在群中"})
map_json = json.dump(map_list, fp=(',', ":"))
print(map_json)
def state_explode_list(a):
a_explore = []
for n, _one in enumerate(str(bin(a)).replace('0b', '')):
if _one == '1':
x_bin_str = _one + ''.join(['0'] * (len(str(bin(a)).replace('0b', '')) - n - 1))
a_explore.append(int(x_bin_str, 2))
return a_explore
def state_explode_map(a, map_json):
map_list = dict({1: "缺少招生群助手", 2: "缺少话术助手", 4: "机器人心跳不正常", 8: "近似满员", 32: "群二维码过期", 64: "满员", 128: "二维码分享者中不在群中"})
a_explore = {}
for n, _one in enumerate(str(bin(a)).replace('0b', '')):
if _one == '1':
x_bin_str = _one + ''.join(['0'] * (len(str(bin(a)).replace('0b', '')) - n - 1))
a_explore[int(x_bin_str, 2)] = map_list[int(x_bin_str, 2)]
return a_explore
bb = [0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 32, 33, 34, 35, 36, 38, 40, 64, 66, 67, 70, 72, 74, 128, 129, 130, 131,
133,
135, 136, 137, 139, 161, 163, 167, 169, 171, 200]
for b in bb:
print(b, state_explode_list(b))
print('-' * 100)
a = 163
print(int('11111111', 2))
print(map_list)
# print(a & 4 == 2)
print(map_list[2])
print(1 | 2)
print(1 | 4)
# print(bin(a))
print(str(bin(a)).replace('0b', ''))
for i in map_list.keys():
print(str(bin(i)).replace('0b', ''), map_list[i])
|
Markdown
|
UTF-8
| 4,979
| 2.5625
| 3
|
[] |
no_license
|
# Article L322-6
Lorsque l'objet de l'association foncière urbaine autorisée ou constituée d'office porte sur des travaux spécifiés au 1° et
au 6° de l'article L. 322-2, l'association :
a) Détermine les bâtiments ou les ouvrages dont le remembrement nécessite soit la destruction soit le changement de l'usage
éventuellement après réparation, aménagement ou transformation.
L'acte amiable portant cession d'un bâtiment ou d'un ouvrage à l'association produit les mêmes effets que l'acte de cession
amiable en matière d'expropriation en ce qui concerne l'extinction des droits réels et personnels ; à défaut d'accord amiable
des propriétaires sur leur cession, ces bâtiments ou ouvrages font l'objet d'une expropriation dans les conditions fixées par
le code de l'expropriation pour cause d'utilité publique ;
b) Etablit le projet de remembrement et en saisit l'autorité administrative qui, après avoir vérifié sa compatibilité avec la
réglementation de l'urbanisme, le soumet à une enquête publique réalisée conformément au code de l'expropriation pour cause
d'utilité publique.
Après enquête publique, l'autorité administrative prononce les transferts et attributions de propriété. L'acte de l'autorité
administrative impose, en tant que de besoin, des prescriptions propres à l'opération, en complément de la réglementation
d'urbanisme applicable à la zone considérée. Ces prescriptions font partie du dossier soumis à l'enquête.
L'arrêté de l'autorité administrative éteint par lui-même et à sa date, pour les immeubles qu'il concerne, les servitudes
ainsi que les droits réels conférés aux preneurs par les baux à construction et les baux emphytéotiques, moyennant indemnité
due par l'association foncière urbaine et fixée, à défaut d'accord amiable, comme en matière d'expropriation. Cet arrêté
produit les mêmes effets à l'égard des autres droits réels. Toutefois, ces droits peuvent être reportés sur les immeubles ou
droits indivis de propriété après remembrement et conservent l'ordre qu'ils avaient sur les immeubles qu'ils grevaient
antérieurement à condition que leur publicité soit renouvelée dans les formes et délais qui seront fixés par décret ; ils
s'exercent éventuellement sur les soultes.
L'arrêté de l'autorité administrative met fin dans les mêmes conditions aux contrats de louage dont ces immeubles étaient
l'objet. Si le bail éteint était soumis aux dispositions du chapitre V du titre IV du livre Ier du code de commerce,
l'association foncière urbaine devra au preneur une indemnité calculée selon les règles fixées par ces dispositions à moins
qu'elle ne préfère lui offrir le bail d'un local équivalant à celui dont la jouissance lui a été retirée. En ce qui concerne
les locaux d'habitation ou professionnels, quelle que soit la nature du titre d'occupation, le droit au relogement est exercé
comme en matière d'expropriation.
La juridiction prévue à l'article L. 311-5 du code de l'expropriation pour cause d'utilité publique est compétente pour
statuer sur les contestations relatives à l'évaluation des parcelles remembrées. Elle statue aussi sur les contestations
soulevées à l'occasion du remembrement et afférentes aux privilèges, hypothèques et autres droits réels.
La décision motivée prise par l'organe compétent de l'association foncière urbaine est notifiée aux intéressés qui disposent
d'un délai de deux mois pour saisir la juridiction.
Faute d'avoir saisi la juridiction dans ce délai, les intéressés sont réputés avoir accepté l'évaluation des parcelles
remembrées et avoir renoncé à toutes contestations relatives aux privilèges, hypothèques et autres droits réels.
La notification susvisée doit, à peine de nullité, contenir l'indication du délai et reproduire, en caractères apparents, les
dispositions de l'alinéa précédent.
Les dispositions du deuxième alinéa a) de l'article L. 322-7 sont, le cas échéant, applicables aux associations foncières
urbaines dont l'objet porte sur des travaux spécifiés au 6° de l'article L. 322-2.
**Liens relatifs à cet article**
_Modifié par_:
- ORDONNANCE n°2014-1345 du 6 novembre 2014 - art. 5
_Cité par_:
- Code de l'urbanisme - art. L322-15 (V)
- Code de l'urbanisme - art. L322-7 (V)
- Code de l'urbanisme - art. R*322-10 (V)
- Code de l'urbanisme - art. R*322-11 (V)
- Code de l'urbanisme - art. R*322-13 (V)
- Code de l'urbanisme - art. R*322-19 (V)
- Code de l'urbanisme - art. R*322-20 (VD)
- Code de l'urbanisme - art. R*322-21 (VD)
- Code de l'urbanisme - art. R*322-26 (M)
- Code de l'urbanisme - art. R*322-27 (M)
- Code de l'urbanisme - art. R*322-30 (M)
- Code de l'urbanisme - art. R*322-8-1 (V)
- Code de l'urbanisme - art. R322-34 (Ab)
_Cite_:
- Code de l'urbanisme - art. L322-2
- Code de l'expropriation pour cause d'utilité publique - art. L311-5
|
Python
|
UTF-8
| 261
| 3.375
| 3
|
[] |
no_license
|
# Program that calculate the sales prediction
# 12 June 2017
# CTI-110 M2T1 - Sales Prediction
# Radhames Flete Perez
sales = int(input("Enter the projected amount of total sales.\n"))
Aprofit = sales*0.23
print("The Profict made from :",sales,"are:",Aprofit)
|
Java
|
UHC
| 1,308
| 2.6875
| 3
|
[] |
no_license
|
package OneToOneWIthBidirectional;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class TestOneToOneBidirectional {
private static SessionFactory sessionFactory;
public static void main(String[] args) {
sessionFactory = new Configuration().configure().buildSessionFactory();
BiPerson person1 = new BiPerson();
person1.setFirstName("Yechan");
person1.setLastName("Park");
BiLicense license1 = new BiLicense();
license1.setLicenseNumber("123456");
license1.setIssue_date(new Date());
license1.setPerson(person1);
person1.setLicense(license1);
BiPerson person2 = new BiPerson();
person2.setFirstName("Alice");
person2.setLastName("Lee");
BiLicense license2 = new BiLicense();
license2.setLicenseNumber("78910");
license2.setIssue_date(new Date());
license2.setPerson(person2);
person2.setLicense(license2);
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
// parent BiPersonü ϸ child BiLicenseü (CASCADE)
session.save(person1);
session.save(person2);
tx.commit();
session.close();
}
}
|
Ruby
|
UTF-8
| 1,541
| 4.25
| 4
|
[
"MIT"
] |
permissive
|
# Smallest Integer
# I worked on this challenge [by myself].
# smallest_integer is a method that takes an array of integers as its input
# and returns the smallest integer in the array
#
# +list_of_nums+ is an array of integers
# smallest_integer(list_of_nums) should return the smallest integer in +list_of_nums+
#
# If +list_of_nums+ is empty the method should return nil
# Your Solution Below
#def smallest_integer(list_of_nums)
# list_of_nums = list_of_nums.sort
# p list_of_nums[0]
#
#end
#def smallest_integer(list_of_nums)
# array = []
# list_of_nums.each |x , y| do
# if x < y
# array << x
# end
# end
# p array[0]
#end
=begin
def smallest_integer(list_of_nums)
array =[]
x = list_of_nums.length
i = 0
while i < x
if list_of_nums[i] < list_of_nums[(i + 1)]
array << list_of_nums[i]
end
i += 1
end
p array[0]
end
def smallest_integer(list_of_nums)
i = 0
j = i + 1
while i < (list_of_nums-1)
if list_of_nums[i] > list_of_nums[j]
y = list_of_nums[i]
z = list_of_nums[j]
list_of_nums[i] = z
list_of_nums[j] = y
i=0
else
i += 1
end
end
print list_of_nums
p list_of_nums[0]
end
smallest_integer([6,9,4,14,3,100])
#smallest_integer([])
=end
def smallest_integer(list_of_nums)
array =[]
array[0] = list_of_nums[0]
i = 0
while i < list_of_nums.length
if array[0] > list_of_nums[i]
array[0] = list_of_nums[i]
end
i += 1
end
p array[0]
end
smallest_integer([6,9,4,14,3,100])
smallest_integer([])
|
Java
|
UTF-8
| 3,959
| 2.15625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.proyectoCFIP.controller;
import com.proyectoCFIP.entities.TipoMaquinaConfecciones;
import com.proyectoCFIP.sessions.TipoMaquinaConfeccionesFacade;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
/**
*
* @author Junior Cabal
*/
@ManagedBean
@SessionScoped
public class TipoMaquinaConfeccionesController implements Serializable{
@EJB
private TipoMaquinaConfeccionesFacade tipoMaquinaConfeccionesFacade;
private TipoMaquinaConfecciones tipoMaquinaConfeccionesActual;
private List<TipoMaquinaConfecciones> tipoMaquinaConfeccionesList;
public TipoMaquinaConfeccionesController() {
}
public TipoMaquinaConfeccionesFacade getTipoMaquinaConfeccionesFacade() {
return tipoMaquinaConfeccionesFacade;
}
public void setTipoMaquinaConfeccionesFacade(TipoMaquinaConfeccionesFacade tipoMaquinaConfeccionesFacade) {
this.tipoMaquinaConfeccionesFacade = tipoMaquinaConfeccionesFacade;
}
public TipoMaquinaConfecciones getTipoMaquinaConfeccionesActual() {
return tipoMaquinaConfeccionesActual;
}
public void setTipoMaquinaConfeccionesActual(TipoMaquinaConfecciones tipoMaquinaConfeccionesActual) {
this.tipoMaquinaConfeccionesActual = tipoMaquinaConfeccionesActual;
}
public List<TipoMaquinaConfecciones> getTipoMaquinaConfeccionesList() {
return tipoMaquinaConfeccionesList = getTipoMaquinaConfeccionesFacade().findAll();
}
public void setTipoMaquinaConfeccionesList(List<TipoMaquinaConfecciones> tipoMaquinaConfeccionesList) {
this.tipoMaquinaConfeccionesList = tipoMaquinaConfeccionesList;
}
public TipoMaquinaConfecciones getTipoMaquinaConfecciones(java.lang.Integer id) {
return getTipoMaquinaConfeccionesFacade().find(id);
}
@FacesConverter(forClass = TipoMaquinaConfecciones.class, value="tipoMaquinaConfeccionesConverter")
public static class TipoMaquinaConfeccionesControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
TipoMaquinaConfeccionesController controller = (TipoMaquinaConfeccionesController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "tipoMaquinaConfeccionesController");
return controller.getTipoMaquinaConfecciones(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof TipoMaquinaConfecciones) {
TipoMaquinaConfecciones o = (TipoMaquinaConfecciones) object;
return getStringKey(o.getIdTipoMaquinaConfecciones());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + TipoMaquinaConfecciones.class.getName());
}
}
}
}
|
PHP
|
UTF-8
| 778
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use DB;
class BlankCart
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$userid = $request->session()->get('userid');
$totalItemInCart = DB::table('shopping_cart')->where('UserId', $userid)->get();
//return dd($totalItemInCart);
if (count($totalItemInCart) == 0) {
return redirect('/user/blankcart');
} else {
//$request->session()->flash('cartBlank', 'Your Cart is Empty! Add Book In Your Cart');
return $next($request);
}
}
}
|
Java
|
UTF-8
| 1,497
| 3.234375
| 3
|
[] |
no_license
|
// Rory Sweeney - 18342673
package CT417_Assignment1;
import java.util.ArrayList;
import java.util.List;
public class Module {
// Class Attributes
private String name, moduleID;
public List<Student> moduleStudents = new ArrayList<Student>();
public List<Course> moduleCourses = new ArrayList<Course>();
public Module(String name, String moduleID) {
this.name = name;
this.moduleID = moduleID;
}
// Getter Methods
public String getName() {
return name;
}
public String getModuleID() {
return moduleID;
}
public List<Student> getStudents(){
return moduleStudents;
}
public List<Course> getCourses(){
return moduleCourses;
}
// Setter Methods
public void setName(String name) {
this.name = name;
}
public void setModuleID(String moduleID) {
this.moduleID = moduleID;
}
// Student & Course Utility Methods
public void addStudent(Student s) {
if(!moduleStudents.contains(s))
{
moduleStudents.add(s);
s.addModule(this);
}
}
public void addCourse(Course c) {
if(!moduleCourses.contains(c))
{
moduleCourses.add(c);
c.addModule(this);
}
}
public void removeStudent(Student s) {
if(moduleStudents.contains(s))
{
moduleStudents.remove(s);
s.studentModules.remove(this);
}
}
public void removeCourse(Course c) {
if(moduleCourses.contains(c))
{
moduleCourses.remove(c);
c.courseModules.remove(this);
}
}
@Override
public String toString() {
return "\n"+name+"\n"+moduleID+"\n";
}
}
|
Python
|
UTF-8
| 11,392
| 3.1875
| 3
|
[] |
no_license
|
import characters
import objects
import fights
import random
import copy
"""from a dictionnary, let's initialize the instances
foes, attacks and objects using from 0 to all arguments"""
def create_foe(foe_name,level=None):
caracterisation_foe=copy.deepcopy(characters.foes[foe_name])
if level!=None:
if level<caracterisation_foe[0][0]:
level=caracterisation_foe[0][0]
elif level>caracterisation_foe[0][1]:
level=caracterisation_foe[0][1]
else:
level=random.randint(caracterisation_foe[0][0],caracterisation_foe[0][1])
value_of_abilities=level*4
# we now make the repartition of abilitiy values
value_of_ability_min=0
value_of_ability_max=0
for increment in range (6):
value_of_ability_min+=caracterisation_foe[1][increment][0]
value_of_ability_max+=caracterisation_foe[1][increment][1]
for increment in range(6):
value_for_this_ability=random.randint(caracterisation_foe[1][increment][0],caracterisation_foe[1][increment][1])
if value_of_abilities-value_for_this_ability>value_of_ability_max:
value_for_this_ability=caracterisation_foe[1][increment][1]
elif value_of_abilities-value_for_this_ability<value_of_ability_min:
value_for_this_ability=caracterisation_foe[1][increment][0]
value_of_ability_min-=caracterisation_foe[1][increment][0]
value_of_ability_max-=caracterisation_foe[1][increment][1]
value_of_abilities-=value_for_this_ability
caracterisation_foe[1][increment]=value_for_this_ability
abilities=caracterisation_foe[1]
# add other characteristics
max_life_points=80+25*abilities[0]
max_mana_points=14+6*abilities[4]
max_stamina_points=16+3*abilities[2]
foe_name=foe_name.split()
name=foe_name[0]
# let's now create the instance
foe=characters.Foe(name,max_life_points,max_life_points,max_mana_points,max_mana_points,
max_stamina_points,max_stamina_points,level,None)
foe.change_strength(abilities[0])
foe.change_agility(abilities[1])
foe.change_endurance(abilities[2])
foe.change_intelligence(abilities[3])
foe.change_will(abilities[4])
foe.change_luck(abilities[5])
# let's now equip the foe with pieces of armour
if foe_name[1]=='low':
category_of_foe='light'
elif foe_name[1]=='medium':
category_of_foe='medium'
elif foe_name[1]=='high':
category_of_foe='heavy'
choice_of_elements=random.randint(1,22)
if choice_of_elements<2:
number_elements_of_armour=1
elif choice_of_elements<5:
number_elements_of_armour=2
elif choice_of_elements<14:
number_elements_of_armour=3
elif choice_of_elements<20:
number_elements_of_armour=4
else:
number_elements_of_armour=5
while True:
torso_equipment=create_armour(category_of_foe,'torso')
foe.add_in_inventory(torso_equipment)
torso_equipment.equip_armour(foe)
number_elements_of_armour-=1
if number_elements_of_armour==0:
break
leg_equipment=create_armour(category_of_foe,'leg')
foe.add_in_inventory(leg_equipment)
leg_equipment.equip_armour(foe)
number_elements_of_armour-=1
if number_elements_of_armour==0:
break
foot_equipment=create_armour(category_of_foe,'foot')
foe.add_in_inventory(foot_equipment)
foot_equipment.equip_armour(foe)
number_elements_of_armour-=1
if number_elements_of_armour==0:
break
arm_equipment=create_armour(category_of_foe,'arm')
foe.add_in_inventory(arm_equipment)
arm_equipment.equip_armour(foe)
number_elements_of_armour-=1
if number_elements_of_armour==0:
break
head_equipment=create_armour(category_of_foe,'head')
foe.add_in_inventory(head_equipment)
head_equipment.equip_armour(foe)
number_elements_of_armour-=1
if number_elements_of_armour==0:
break
# let's give a weapon to the foe
weapon=create_weapon(category_of_foe)
foe.add_in_inventory(weapon)
weapon.equip_weapon(foe)
# now let's put loots in its inventory
foe.gold=random.randint(0,15)
number_of_objects=random.randint(0,4)
for i in range(number_of_objects):
choice_of_object=random.randint(0,9)
if choice_of_object==0:
new_object=create_weapon()
foe.add_in_inventory(new_object)
elif choice_of_object==1:
new_object=create_armour()
foe.add_in_inventory(new_object)
else:
new_object=create_consumable()
foe.add_in_inventory(new_object)
# let's add the set of skills and attacks of this foe
if foe_name[1]=='low':
number_of_healing_spells=random.randint(0,1)
elif foe_name[1]=='medium':
create_set_of_attacks(foe)
create_set_of_spells(foe)
number_of_healing_spells=random.randint(0,3)
elif foe_name[1]=='high':
create_set_of_attacks(foe)
create_set_of_attacks(foe)
create_set_of_spells(foe)
create_set_of_spells(foe)
number_of_healing_spells=random.randint(0,5)
create_set_of_attacks(foe)
create_set_of_spells(foe)
create_set_of_spells(foe,number_of_healing_spells,'healing')
return foe
def create_armour(category_of_armour=None,type_of_armour=None):
if category_of_armour==None:
category_of_armours=("light","medium","heavy")
choice_of_category=random.randint(0,len(category_of_armours)-1)
category_of_armour=category_of_armours[choice_of_category]
if type_of_armour==None:
type_of_armours=("head","arm","torso","leg","foot")
choice_of_type=random.randint(0,len(type_of_armours)-1)
type_of_armour=type_of_armours[choice_of_type]
armour_key="{} {}".format(category_of_armour,type_of_armour)
caracterisation_armour=copy.deepcopy(objects.armours[armour_key])
choice_of_armour=random.randint(0,len(caracterisation_armour)-1)
armour_chosen=caracterisation_armour[choice_of_armour]
name=armour_chosen[0]
weight=armour_chosen[1]
protection=random.randint(armour_chosen[2][0],armour_chosen[2][1])
if category_of_armour=='light':
strength_min=0
endurance_min=0
elif category_of_armour=='medium':
strength_min=2
endurance_min=3
elif category_of_armour=='heavy':
strength_min=4
endurance_min=6
return objects.Armour(name,weight,type_of_armour,protection,
strength_min,endurance_min)
def create_weapon(category_of_weapon=None,range_of_weapon=None):
if category_of_weapon==None:
category_of_weapons=("light","medium","heavy")
choice_of_category=random.randint(0,len(category_of_weapons)-1)
category_of_weapon=category_of_weapons[choice_of_category]
if range_of_weapon==None:
range_of_weapons=['mele','distance']
choice_of_range=random.randint(0,len(range_of_weapons)-1)
range_of_weapon=range_of_weapons[choice_of_range]
weapon_key="{} {}".format(category_of_weapon,range_of_weapon)
caracterisation_weapon=copy.deepcopy(objects.weapons[weapon_key])
choice_of_weapon=random.randint(0,len(caracterisation_weapon)-1)
weapon_chosen=caracterisation_weapon[choice_of_weapon]
name=weapon_chosen[0]
weight=weapon_chosen[1]
min_attack=random.randint(weapon_chosen[2][0][0],weapon_chosen[2][0][1])
max_attack=random.randint(weapon_chosen[2][1][0],weapon_chosen[2][1][1])
damage_range=[min_attack,max_attack]
if range_of_weapon=='mele':
distance=1
intelligence_min=0
if category_of_weapon=='light':
strength_min=1
agility_min=0
elif category_of_weapon=='medium':
strength_min=3
agility_min=2
elif category_of_weapon=='heavy':
strength_min=6
agility_min=4
elif range_of_weapon=='distance':
distance=25
strength_min=0
if category_of_weapon=='light':
agility_min=1
intelligence_min=0
elif category_of_weapon=='medium':
agility_min=3
intelligence_min=2
elif category_of_weapon=='heavy':
agility_min=6
intelligence_min=4
return objects.Weapon(name,weight,distance,damage_range,
strength_min,agility_min,intelligence_min)
def create_consumable(consumable_type=None,side_effect=None):
if consumable_type==None:
choice_of_consumable=random.randint(0,8)
if choice_of_consumable==0:
consumable_type='health potion'
elif choice_of_consumable==1:
consumable_type='mana potion'
elif choice_of_consumable==2:
consumable_type='stamina potion'
else:
consumable_type='food'
if consumable_type=='health potion':
life_points_gained=random.randint(1,6)*25
weight=life_points_gained/100
return objects.Potion("health potion ({})".format(life_points_gained),
weight,life_points_gained,0,0)
if consumable_type=='mana potion':
mana_points_gained=random.randint(1,6)*10
weight=mana_points_gained/40
return objects.Potion("mana potion ({})".format(mana_points_gained),
weight,0,mana_points_gained,0)
if consumable_type=='stamina potion':
stamina_points_gained=random.randint(1,6)*3
weight=stamina_points_gained/12
return objects.Potion("stamina potion ({})".format(stamina_points_gained),
weight,0,0,stamina_points_gained)
if consumable_type=='food':
life_points_gained=random.randint(1,4)*5
weight=life_points_gained/20
if side_effect==None:
gain_lose=random.randint(0,4)
if gain_lose==0:
gain_lose='gain'
else:
gain_lose='lose'
effect=['strength','agility','endurance','intelligence','will','luck',
'max_life_points','max_mana_points','max_stamina_points']
choice_of_effect=random.randint(0,len(effect)-1)
effect_chosen=effect[choice_of_effect]
value_of_effect=random.randint(1,3)
if effect_chosen=="max_life_points":
value_of_effect=value_of_effect*15
elif effect_chosen=="max_mana_points":
value_of_effect=value_of_effect*10
elif effect_chosen=="max_stamina_points":
value_of_effect=value_of_effect*3
number_of_rounds=random.randint(1,5)
side_effect="{} {} {} for {} round(s)".format(gain_lose,value_of_effect,
effect_chosen,number_of_rounds)
name=objects.foods[random.randint(0,len(objects.foods)-1)]
return objects.Food(name,weight,life_points_gained,side_effect)
def create_set_of_spells(character,number_of_spells=None,category_of_spells=None):
if number_of_spells==None:
number_of_spells=random.randint(0,3)
spells_left=0
while spells_left <number_of_spells:
if category_of_spells==None:
no_category=True
category_of_spells=fights.type_of_spells[random.randint(0,len(fights.type_of_spells)-1)]
else:
no_category=False
new_spells=copy.deepcopy(fights.spells[category_of_spells])
number_spells_initial=len(character.list_of_spells)
new_spell_index=0
if category_of_spells=='healing':
for increment in range(number_of_spells):
character.add_healing_spell(new_spells[increment])
else:
while len(character.list_of_spells)==number_spells_initial:
if new_spell_index==len(new_spells):
spells_left-=1
category_of_spells=None
break
character.add_spell(new_spells[new_spell_index])
new_spell_index+=1
if no_category:
category_of_spells=None
spells_left+=1
def create_set_of_attacks(character,number_of_attacks=None,category_of_attacks=None):
if number_of_attacks==None:
number_of_attacks=random.randint(0,3)
attacks_left=0
while attacks_left <number_of_attacks:
if category_of_attacks==None:
no_category=True
category_of_attacks=fights.type_of_attacks[random.randint(0,len(fights.type_of_attacks)-1)]
else:
no_category=False
new_attacks=copy.deepcopy(fights.alternative_attacks[category_of_attacks])
number_attacks_initial=len(character.list_of_attacks)
new_attack_index=0
while len(character.list_of_attacks)==number_attacks_initial:
if new_attack_index==len(new_attacks):
attacks_left-=1
category_of_attacks=None
break
character.add_attack(new_attacks[new_attack_index])
new_attack_index+=1
if no_category:
category_of_attacks=None
attacks_left+=1
|
Java
|
UTF-8
| 16,269
| 1.914063
| 2
|
[] |
no_license
|
package com.courseracapstone.android.accountsetup;
import java.net.SocketTimeoutException;
import org.apache.http.conn.ConnectTimeoutException;
import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import com.courseracapstone.android.LoginActivity;
import com.courseracapstone.android.R;
import com.courseracapstone.common.PotlatchConstants;
/**
* The Authenticator activity.
* Called by the Authenticator and in charge of identifying the user.
*
* @author xxx xxx - heavily modified from example by udinic
*/
public class AuthenticatorActivity extends AccountAuthenticatorActivity {
private final String LOG_TAG = "Potlatch-"+getClass().getSimpleName();
// arguments to call this activity with
public final static String ARG_ACCOUNT_TYPE = "ACCOUNT_TYPE";
public final static String ARG_AUTH_TYPE = "AUTH_TYPE";
public final static String ARG_ACCOUNT_NAME = "ACCOUNT_NAME";
public final static String ARG_IS_ADDING_NEW_ACCOUNT = "IS_ADDING_ACCOUNT";
public static final String ARG_SERVER = "SERVER_NAME";
public static final String ARG_IS_ADMIN = "IS_ADMIN";
public static final String KEY_ERROR_MESSAGE = "ERR_MSG";
public final static String PARAM_USER_PASS = "USER_PASS";
private AccountManager mAccountManager;
private String mAuthTokenType;
private PotlatchServerAuthenticate mServerAuthenticate;
private boolean mIsAddingNewAccount;
private boolean mIsAdmin;
private String mServer;
private EditText mAccountNameVw;
private EditText mServerDomainVw;
private CheckBox mLinkExisting;
private CheckBox mUseDev;
private CheckBox mChooseTester;
private EditText mPasswordVw;
private EditText mRepeatPasswordVw;
private CheckBox mAdminVw;
private String mCurrentAccountName;
private Spinner mDevAccNameSpinner;
private ImageButton mSubmit;
private ProgressBar mProgressBar;
private Button mChangeUserBtn;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.potlatch_login);
Log.d(LOG_TAG, "onCreate");
getActionBar().setDisplayUseLogoEnabled(true);
mServerAuthenticate = new PotlatchServerAuthenticate(this);
mAccountManager = AccountManager.get(getBaseContext());
mIsAddingNewAccount = getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false);
mIsAdmin = getIntent().getBooleanExtra(ARG_IS_ADMIN, false);
mServer = getIntent().getStringExtra(ARG_SERVER);
mCurrentAccountName = getIntent().getStringExtra(ARG_ACCOUNT_NAME);
mAuthTokenType = getIntent().getStringExtra(ARG_AUTH_TYPE);
if (mAuthTokenType == null)
mAuthTokenType = PotlatchAccountConstants.AUTHTOKEN_TYPE_POTLATCH;
mAccountNameVw = (EditText)findViewById(R.id.accountName);
if (mCurrentAccountName != null) {
mAccountNameVw.setText(mCurrentAccountName);
}
mSubmit = (ImageButton) findViewById(R.id.fabbutton);
mSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
submit();
}
});
OnCheckedChangeListener checkChangeListener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.equals(mChooseTester) && !isChecked) {
mAdminVw.setChecked(false);
}
layoutViews();
}
};
mUseDev = (CheckBox) findViewById(R.id.useDev);
mUseDev.setOnCheckedChangeListener(checkChangeListener);
mLinkExisting = (CheckBox) findViewById(R.id.linkExisting);
mLinkExisting.setOnCheckedChangeListener(checkChangeListener);
mChooseTester = (CheckBox) findViewById(R.id.chooseTestUser);
mChooseTester.setOnCheckedChangeListener(checkChangeListener);
mAdminVw = (CheckBox) findViewById(R.id.isDevAdmin);
mDevAccNameSpinner = (Spinner) findViewById(R.id.accountNameSpinner);
mDevAccNameSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
mAdminVw.setChecked(
PotlatchAccountConstants.DEV_ADMIN_ACCOUNT_USER
.equals(parent.getItemAtPosition(pos).toString()));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
// other fields
mServerDomainVw = (EditText)findViewById(R.id.serverDomain);
mPasswordVw = (EditText)findViewById(R.id.accountPassword);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
mRepeatPasswordVw = (EditText)findViewById(R.id.accountRepeatPassword);
// password change
if (!mIsAddingNewAccount) {
mChangeUserBtn = (Button) findViewById(R.id.chooseFromExisting);
mChangeUserBtn.setVisibility(View.VISIBLE);
mChangeUserBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(LOG_TAG, "choose another user");
Intent i = new Intent(AuthenticatorActivity.this, LoginActivity.class);
i.putExtra(PotlatchAccountConstants.PROMPT_FOR_LOGIN, true);
startActivity(i);
// don't allow a back press to navigate back here
finish();
}
});
}
layoutViews();
}
/**
* Called during onCreate() and also when the use development server checkbox is clicked
* @param useDev
*/
protected void layoutViews() {
boolean useDev = mUseDev.isChecked();
Resources res = getResources();
// show the current setup
if (mIsAddingNewAccount) {
if (mLinkExisting.isChecked() || mChooseTester.isChecked()) {
mRepeatPasswordVw.setVisibility(View.GONE);
}
else {
mRepeatPasswordVw.setVisibility(View.VISIBLE);
}
if (useDev) {
mServerDomainVw.setHint(res.getString(R.string.login_dev_server_hint));
mAdminVw.setVisibility(View.VISIBLE);
mChooseTester.setVisibility(View.VISIBLE);
if (mChooseTester.isChecked()) {
mPasswordVw.setVisibility(View.GONE);
mAccountNameVw.setVisibility(View.GONE);
mDevAccNameSpinner.setVisibility(View.VISIBLE);
mAdminVw.setEnabled(false);
mAdminVw.setChecked(
PotlatchAccountConstants.DEV_ADMIN_ACCOUNT_USER
.equals(mDevAccNameSpinner.getSelectedItem().toString()));
}
else {
mPasswordVw.setVisibility(View.VISIBLE);
mAccountNameVw.setVisibility(View.VISIBLE);
mDevAccNameSpinner.setVisibility(View.GONE);
mAdminVw.setEnabled(true);
}
// nothing entered in dev server yet, help out with the one we have
// in keystore
if (TextUtils.isEmpty(mServerDomainVw.getText())) {
mServerDomainVw.setText(R.string.dev_server_we_know_about);
}
}
else {
mServerDomainVw.setHint(res.getString(R.string.login_server_domain_hint));
mAccountNameVw.setVisibility(View.VISIBLE);
mAdminVw.setVisibility(View.GONE);
mDevAccNameSpinner.setVisibility(View.GONE);
mChooseTester.setVisibility(View.GONE);
}
}
else {
// only the current setup and password is required
getActionBar().setTitle(R.string.password_change_title);
mLinkExisting.setVisibility(View.GONE);
mUseDev.setVisibility(View.GONE);
mRepeatPasswordVw.setVisibility(View.GONE);
mServerDomainVw.setEnabled(false);
mServerDomainVw.setText(mServer);
mAccountNameVw.setEnabled(false);
mAdminVw.setVisibility(View.GONE);
// mAdminVw.setChecked(mIsAdmin);
mDevAccNameSpinner.setVisibility(View.GONE);
mChooseTester.setVisibility(View.GONE);
}
}
/**
* Called to disable the buttons whenever one of them is pressed
* and to re-enable if there's a user cancellation that brings them back
* @param enabled
*/
private void setButtons(boolean enabled) {
mSubmit.setEnabled(enabled);
if (mChangeUserBtn != null) {
mChangeUserBtn.setEnabled(enabled);
}
mProgressBar.setVisibility(enabled ? View.INVISIBLE : View.VISIBLE);
}
/**
* Assemble the values from the various fields and kick off the async task
* that will attempt to get an auth token
*/
public void submit() {
final String server = mServerDomainVw.getText().toString();
String username = null;
String password = null;
username = mAccountNameVw.getText().toString();
password = mPasswordVw.getText().toString();
if (mUseDev.isChecked() && mChooseTester.isChecked()) {
// use dev settings
username = mDevAccNameSpinner.getSelectedItem().toString();
password = mAdminVw.isChecked()
? PotlatchAccountConstants.DEV_ADMIN_ACCOUNT_PWD
: PotlatchAccountConstants.DEV_USER_ACCOUNT_PWD;
}
else {
// user entered values
username = mAccountNameVw.getText().toString();
password = mPasswordVw.getText().toString();
}
// validate the input before go on
final Resources res = getResources();
if (TextUtils.isEmpty(server) || TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
Toast.makeText(this, res.getString(R.string.login_submit_valid_error)
, Toast.LENGTH_SHORT).show();
return;
}
if (mIsAddingNewAccount && !mLinkExisting.isChecked() && !mChooseTester.isChecked()
&& !password.equals(mRepeatPasswordVw.getText().toString())) {
Toast.makeText(this, res.getString(R.string.login_submit_passwords_error)
, Toast.LENGTH_SHORT).show();
return;
}
else if (mIsAddingNewAccount) {
// make sure the account name isn't already used on this device
Account[] accounts = mAccountManager.getAccountsByType(PotlatchAccountConstants.ACCOUNT_TYPE);
for (Account a : accounts) {
if (a.name.equals(username)) {
Toast.makeText(this, res.getString(R.string.login_submit_dupe_name_error,
mAccountManager.getUserData(a,
PotlatchAccountConstants.ACCOUNT_SERVER_KEY))
, Toast.LENGTH_SHORT).show();
return;
}
}
}
// prevent further presses
setButtons(false);
final String userName = username;
final String userPass = password;
final String accountType = getIntent().getStringExtra(ARG_ACCOUNT_TYPE);
final String tokenUrl = "https://"+server+PotlatchConstants.TOKEN_PATH;
final boolean isAdmin = mIsAdmin || (mUseDev.isChecked() && mAdminVw.isChecked());
new AsyncTask<String, Void, Intent>() {
@Override
protected Intent doInBackground(String... params) {
Log.d(LOG_TAG, "Start authenticating");
String authtoken = null;
Bundle data = new Bundle();
try {
// make sure can connect
if (!validateServer(tokenUrl, res)) {
throw new Exception("validateServer error");
}
if (mIsAddingNewAccount && !mLinkExisting.isChecked() && !mChooseTester.isChecked()) {
String signUpUrl = "https://"+server+PotlatchConstants.POTLATCH_SIGN_UP_PATH;
authtoken = mServerAuthenticate.userSignUp(signUpUrl, tokenUrl,
userName, userPass, mAuthTokenType, isAdmin);
}
else {
authtoken = mServerAuthenticate.userSignIn(tokenUrl,
userName, userPass, mAuthTokenType, isAdmin);
}
Log.d(LOG_TAG, "returned with authtoken="+authtoken);
data.putString(AccountManager.KEY_ACCOUNT_NAME, userName);
data.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType);
data.putString(AccountManager.KEY_AUTHTOKEN, authtoken);
data.putString(PotlatchAccountConstants.CURRENT_AUTHTOKEN_KEY, authtoken);
data.putString(PARAM_USER_PASS, userPass);
data.putString(PotlatchAccountConstants.ACCOUNT_SERVER_KEY, server);
data.putBoolean(PotlatchAccountConstants.ADMIN_ACCOUNT_FLAG_KEY, isAdmin);
} catch (ConnectTimeoutException | SocketTimeoutException e) {
Log.w(LOG_TAG, "failed to get authtoken: timed out");
data.putString(KEY_ERROR_MESSAGE, res.getString(R.string.login_submit_connect_error));
}
catch (Exception e) {
Log.e(LOG_TAG, "failed to get authtoken", e);
data.putString(KEY_ERROR_MESSAGE, e.getMessage());
}
final Intent res = new Intent();
res.putExtras(data);
return res;
}
@Override
protected void onPostExecute(Intent intent) {
if (intent.hasExtra(KEY_ERROR_MESSAGE)) {
Toast.makeText(getBaseContext(), intent.getStringExtra(KEY_ERROR_MESSAGE), Toast.LENGTH_SHORT).show();
// allow retry
setButtons(true);
}
else {
finishLogin(intent);
}
}
}.execute();
}
private boolean validateServer(final String server, Resources res) throws Exception {
// validate the server, not so easy, but at least remove obvious errors
if (server.contains(" ") || server.contains(",") || server.contains("..")
|| server.startsWith(".") || server.endsWith(".")
|| server.startsWith(":") || server.endsWith(":")) {
return false;
}
else {
return true;
}
}
private void finishLogin(Intent intent) {
Log.d(LOG_TAG, "finishLogin");
String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
if (mIsAddingNewAccount) {
Log.d(LOG_TAG, "new account, addAccountExplicitly");
String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
String authtokenType = mAuthTokenType;
// Creating the account on the device and setting the auth token we got
// (Not setting the auth token will cause another call to the server to authenticate the user)
Bundle userData = new Bundle();
userData.putString(PotlatchAccountConstants.ACCOUNT_SERVER_KEY
, intent.getStringExtra(PotlatchAccountConstants.ACCOUNT_SERVER_KEY));
userData.putString(PotlatchAccountConstants.ADMIN_ACCOUNT_FLAG_KEY
, Boolean.toString(
intent.getBooleanExtra(PotlatchAccountConstants.ADMIN_ACCOUNT_FLAG_KEY, false)));
mAccountManager.addAccountExplicitly(account, accountPassword, userData);
mAccountManager.setAuthToken(account, authtokenType, authtoken);
}
else {
Log.d(LOG_TAG, "not new account, setPassword");
mAccountManager.setPassword(account, accountPassword);
}
setAccountAuthenticatorResult(intent.getExtras());
setResult(RESULT_OK, intent);
finish();
}
}
|
C++
|
UTF-8
| 2,511
| 3.75
| 4
|
[] |
no_license
|
/**
一、构造函数和析构函数的构造规则
1、派生类可以不定义构造函数的情况 当具有下述情况之一时,派生类可以不定义构造函数。 基类没有定义任何
构造函数。 基类具有缺省参数的构造函数。 基类具有无参构造函数。 2、派生类必须定义构造函数的情况 当
基类或成员对象所属类只含有带参数的构造函数时,即使派生类本身没有数据成员要初始化,它也必须定义构造
函数,并以构造函数初始化列表的方式向基类和成员对象的构造函数传递参数,以实现基类子对象和成员对象的
初始化。 3、派生类的构造函数只负责直接基类的初始化
C++语言标准有一条规则:如果派生类的基类同时也是另外一个类的派生类,则每个派生类只负责它的直接基类的
构造函数调用。 这条规则表明当派生类的直接基类只有带参数的构造函数,但没有默认构造函数时(包括缺省参
数和无参构造函数),它必须在构造函数的初始化列表中调用其直接基类的构造函数,并向基类的构造函数传递
参数,以实现派生类对象中的基类子对象的初始化。 这条规则有一个例外情况,当派生类存在虚基类时,所有
虚基类都由最后的派生类负责初始化。
总结: (1)当有多个基类时,将按照它们在继承方式中的声明次序调用,与它们在构造函数初始化列表中的次
序无关。当基类A本身又是另一个类B的派生类时,则先调用基类B的构造函数,再调用基类A的构造函数。
(2)当有多个对象成员时,将按它们在派生类中的声明次序调用,与它们在构造函数初始化列表中的次序无关。
(3)当构造函数初始化列表中的基类和对象成员的构造函数调用完成之后,才执行派生类构造函数体中的程序代码。
*/
//当同时存在直接基类和间接基类时,每个派生类只负责其直接基类的构造。
#include <iostream>
using namespace std;
class A {
int x;
public:
A(int aa) {
x = aa;
cout << "Constructing A" << endl;
}
~A() { cout << "Destructing A" << endl; }
};
class B :public A {
public:
B(int x) :A(x) { cout << "Constructing B" << endl; }
};
class C :public B {
public:
C(int y) :B(y) { cout << "Constructing C" << endl; }
};
/**
int main() {
C c(1);
return 0;
}*/
/**
Constructing A
Constructing B
Constructing C
Destructing A
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.