language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
C++
|
UTF-8
| 4,881 | 2.9375 | 3 |
[] |
no_license
|
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <iomanip>
#include "School.h"
#include "Student.h"
#include "AttendanceRecord.h"
#include "Course.h"
#include "Date.h"
using namespace std;
void School::addStudents(string filename) {
ifstream ifs(filename);
if (!ifs.is_open()) {
cout << "Unable to open file: " << filename << endl;
return;
}
while (!ifs.eof()) {
string line;
getline(ifs, line);
istringstream ss(line);
string uin;
getline(ss, uin, ',');
string name;
getline(ss, name);
if (!ss.fail()) {
students.push_back(Student(uin, name));
}
}
}
void School::listStudents(){
if(students.size() == 0){
cout << "No Students" << endl;
}
else{
for(int i = 0; i < students.size() ; ++i){
cout << students[i].get_id() << "," << students[i].get_name() << endl;
}
}
}
void School::addCourses(std::string filename) {
ifstream ifs(filename);
if(!ifs.is_open()) {
cout << "Unable to open file: " << filename << endl;
return;
}
string line;
//while (!ifs.eof()) {
while(getline(ifs, line)) {
//cout << "READING: " << line << endl;
istringstream ss(line);
string course_id;
getline(ss, course_id, ',');
string shour;
string smin;
getline(ss, shour, ':');
getline(ss, smin, ',');
int hour1 = stoi(shour);
int min1 = stoi(smin);
string ehour;
string emin;
getline(ss, ehour, ':');
getline(ss, emin, ',');
int hour2 = stoi(ehour);
int min2 = stoi(emin);
string courses_temp;
getline(ss, courses_temp);
/*
while(getline(ss, courses_temp, ',')){
if(courses_temp.find(" and") == 0){
courses_temp = courses_temp.substr(courses_temp.find(" and")+4);
}
if (!ss.fail()) {
courses.push_back(Course(course_id, courses_temp, Date(hour1,min1,0), Date(hour2,min2,0)));
}
cout << "courses: " << courses_temp << endl;
}
*/
if (!ss.fail()) {
courses.push_back(Course(course_id, courses_temp, Date(hour1,min1), Date(hour2,min2)));
}
//ss.clear();
//ss.str("");
}
}
void School::listCourses(){
if(courses.size() == 0){
cout << "No Courses" << endl;
}
else{
for(int i = 0; i < courses.size() ; ++i){
cout << setfill ('0') << setw (2);
cout << courses[i].getID() << "," << setfill ('0') << setw (2) << (courses[i].getStartTime()).getHour() << ":" << setfill ('0') << setw (2) << (courses[i].getStartTime()).getMin() <<
","<< setfill ('0') << setw (2) << (courses[i].getEndTime()).getHour() << ":" << setfill ('0') << setw (2) << (courses[i].getEndTime()).getMin() << "," << courses[i].getTitle() << endl;
}
}
}
void School::addAttendanceData(std::string filename){
ifstream ifs(filename);
if (!ifs.is_open()) {
cout << "Unable to open file: " << filename << endl;
return;
}
string line;
while (getline(ifs, line)) {
istringstream ss(line);
string year;
getline(ss, year, '-');
int year1 = stoi(year);
string month;
getline(ss, month, '-');
int month1 = stoi(month);
string day;
getline(ss, day, ' ');
int day1= stoi(day);
string hour;
getline(ss, hour, ':');
int hour1 = stoi(hour);
string min;
getline(ss, min, ':');
int min1 = stoi(min);
string sec;
getline(ss, sec, ',');
int sec1 = stoi(sec);
string course_id;
getline(ss, course_id, ',');
string student_id;
getline(ss, student_id);
if (!ss.fail()) {
// 1. Find course c in courses
// 2. once you've found the course, invoke its addAttendanceRecord member function
for(int i = 0; i < courses.size(); ++i){
if(courses[i].getID() == course_id){
courses[i].addAttendanceRecord(AttendanceRecord(course_id, student_id, Date(year1, month1, day1, hour1, min1, sec1)));
}
// in courses class vector<AttendanceRecord> attendanceRecords;
}
//c.addAttendanceRecord(AttendanceRecord(course_id, student_id, Date(year1, month1, day1, hour1, min1, sec1)));
}
}
}
void School::outputCourseAttendance(std::string course_id){
if(courses.size() == 0){
cout << "No Records" << endl;
}
else{
for(int i = 0; i < courses.size() ; ++i){
//cout << courses[i].getID() << "/"<< course_id << endl;
if(courses[i].getID() == course_id){
courses[i].outputAttendance();
}
}
}
}
void School::outputStudentAttendance(std::string student_id, std::string course_id){
bool isValidCourse = false;
if(courses.size() == 0){
cout << "No Records" << endl;
}
else{
for(int i = 0; i < courses.size() ; ++i){
if(courses[i].getID() == course_id){
isValidCourse = true;
courses[i].outputAttendance(student_id);
}
}
if(isValidCourse == false){
cout << "No Records" << endl;
}
}
}
|
Markdown
|
UTF-8
| 1,462 | 2.84375 | 3 |
[] |
no_license
|
# liri-real
Description: LIRI is like iPhone's SIRI. However, while SIRI is a Speech Interpretation and Recognition Interface, LIRI is a Language Interpretation and Recognition Interface. LIRI will be a command line node app that takes in parameters and gives you back data.
### Instructions
##### When user types in
*movie-this *userinput*
This will output the following information to your terminal/bash window:
*Title of the movie.
*Year the movie came out.
*IMDB Rating of the movie.
* Rotten Tomatoes Rating of the movie.
* Country where the movie was produced.
* Language of the movie.
* Plot of the movie.
* Unordered sub-list.
* Actors in the movie.
concert-this *userinput*
* This will search the Bands in Town Artist Events API (`"https://rest.bandsintown.com/artists/" + artist + "/events?app_id=codingbootcamp"`) for an artist and render the following information about each event to the terminal:
* Name of the venue
* Venue location
* Date of the Event (use moment to format this as "MM/DD/YYYY")
spotify-this *userinput*
* This will show the following information about the song in your terminal/bash window
* Artist(s)
* The song's name
* A preview link of the song from Spotify
* The album that the song is from
My snippet*
|
C++
|
UTF-8
| 1,204 | 2.703125 | 3 |
[] |
no_license
|
/*
reality, be rent!
synapse, break!
Van!shment Th!s World !!
*/
#include <bits/stdc++.h>
using namespace std;
int a[24], n;
vector<int> v;
bool vst[1 << 12][24];
bool dfs(int mask, int rem, int i) {
if (i == n) {
if (mask == 1 << (n - 1)) return rem == 0;
return false;
}
if (vst[mask][rem]) return false;
vst[mask][rem] = true;
if (a[i] != 2 && rem >= a[i] - 1 && dfs(mask | (1 << i), rem - a[i] + 1, i + 1)) return true;
int sub, j, sum, need;
for (sub = mask; sub > 0; sub = (sub - 1) & mask) {
sum = 0, need = 0;
for (j = 0; j < n; ++j) if ((sub >> j) & 1) sum += a[j];
if (sum < a[i] - 1) need = a[i] - 1 - sum;
if (need + sum != a[i] - 1) continue;
if (need > rem) continue;
if (need + __builtin_popcount(sub) == 1) continue;
if (dfs((mask ^ sub) | (1 << i), rem - need, i + 1)) return true;
}
return false;
}
int main() {
int m, i;
scanf("%d", &m);
for (i = 0; i < m; ++i) scanf("%d", a + i);
if (m == 1 && a[0] == 1) {
puts("YES");
return 0;
}
sort(a, a + m);
for (i = 0; i < m; ++i) if (a[i] != 1) v.push_back(a[i]);
n = v.size();
for (i = 0; i < n; ++i) a[i] = v[i];
if (dfs(0, m - v.size(), 0)) puts("YES");
else puts("NO");
return 0;
}
|
Java
|
UTF-8
| 2,581 | 1.945313 | 2 |
[] |
no_license
|
package com.buddha.icbi.pojo.member;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.buddha.component.common.bean.mybatis.PojoModel;
import com.buddha.icbi.pojo.company.CompanyInfo;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
*
* 收藏名片信息-数据库实体对象
*
* #############################################################################
*
* CopyRight (C) 2018 ShenZhen FoXiQingNian Information Technology Co.Ltd All
* Rights Reserved.<br />
* 本软件由深圳市佛系青年互联网科技设计开发;未经本公司正式书面同意或授权,<br />
* 其他任何个人、公司不得使用、复制、传播、修改或商业使用。 <br />
* #############################################################################
*
*
*
* @作者 系统生成
* @时间 2018-12-03
* @版权 深圳市佛系青年互联网科技有限公司(www.fxqn.xin)
*/
@TableName("member_collection")
@Data
@EqualsAndHashCode(callSuper = true)
public class MemberCollection extends PojoModel<MemberCollection> {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.UUID)
private String id;
/**
* 公司id
*/
@TableField("company_id")
private String companyId;
/**
* 会员id
*/
@TableField("member_id")
private String memberId;
/**
* 会员真实头像
*/
@TableField("member_real_avatar")
private String memberRealAvatar;
/**
* 会员真实姓名
*/
@TableField("member_real_name")
private String memberRealName;
/**
* 是否删除 1-整除 2-删除
*/
@TableField("is_del")
private Integer isDel;
/**
* 收藏人id
*/
@TableField("create_id")
private String createId;
/**
* 收藏人昵称
*/
@TableField("create_nick_name")
private String createNickName;
/**
* 收藏时间
*/
@TableField("create_time")
private Date createTime;
@Override
protected Serializable pkVal() {
return this.id;
}
//#############数据库之外属性##########################
/**
* 公司信息
*/
@TableField(exist = false)
private CompanyInfo companyInfo;
//##############END################################
}
|
JavaScript
|
UTF-8
| 253 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
//eslint-disable-next-line no-console
export async function profileAsync( message, callback, logger = console.log ) {
const
time = performance.now(),
result = await callback()
logger( message, performance.now() - time )
return result
}
|
Python
|
UTF-8
| 4,745 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
from direct.showbase.ShowBase import ShowBase
from panda3d.core import loadPrcFileData, BitMask32, Vec3
from panda3d.core import CollisionTraverser, CollisionNode
from panda3d.core import CollisionHandlerQueue, CollisionRay
# from panda3d.core import OrthographicLens
config_vars = """
win-size 1280 720
show-frame-rate-meter 1
"""
loadPrcFileData("", config_vars)
HIGHLIGHT = (0, 1, 1, 1)
WHITE = (1, 1, 1, 1)
class IsometricGame(ShowBase):
def __init__(self):
super().__init__()
self.set_background_color(0, 0, 0, 1)
# set the camera to the correct position to create an isometric view
self.cam.setPos(0, -6, 0) # set cam global position
self.cam.setR(45) # set cam global Roll rotation
self.cam.setP(self.cam, 65) # set cam local Pitch rotation
self.cam.setPos(self.cam, self.cam.getPos() + Vec3(0, 0, -4)) # set cam local position
# load the 3D models
self.plane = self.loader.loadModel("egg-models/plane")
self.tex1 = self.loader.loadTexture("egg-models/tex/brick-c.jpg")
self.plane.setTexture(self.tex1)
self.cube = self.loader.loadModel("models/box")
self.cube.setPos(0, -1, 0)
self.cube.reparentTo(self.render)
# create an empty node path
self.my_map = self.render.attachNewNode("iso-map")
# fill the empty node path with grid tiles
self.create_map(10, 10)
# collision detection objects - traverser, handler, node, ray
self.picker = CollisionTraverser()
self.queue = CollisionHandlerQueue()
picker_node = CollisionNode('picker-node')
picker_node.setFromCollideMask(BitMask32.bit(1))
picker_np = self.cam.attachNewNode(picker_node)
self.picker_ray = CollisionRay()
picker_node.addSolid(self.picker_ray)
self.picker.addCollider(picker_np, self.queue)
# self.picker.showCollisions(self.render)
self.taskMgr.add(self.mouse_task, 'mouse-task')
self.hit = False
# accepting keyboard input events, and binding the move method
self.accept("arrow_left", self.move, ["left"])
self.accept("arrow_right", self.move, ["right"])
self.accept("arrow_up", self.move, ["up"])
self.accept("arrow_down", self.move, ["down"])
# If you want to use orthographic projection:
# on top of this file just import the following: from panda3d.core import OrthographicLens
# Than uncomment the code below.
# lens = OrthographicLens()
# lens.setFilmSize(16, 9)
# lens.setNearFar(-50, 50)
# self.cam.node().setLens(lens)
def move(self, direction):
""" Moves the cube on the grid. """
if direction == "left":
self.cube.setPos(self.cube.getPos() + Vec3(-1, 0, 0))
elif direction == "right":
self.cube.setPos(self.cube.getPos() + Vec3(1, 0, 0))
elif direction == "up":
self.cube.setPos(self.cube.getPos() + Vec3(0, 0, 1))
elif direction == "down":
self.cube.setPos(self.cube.getPos() + Vec3(0, 0, -1))
def mouse_task(self, task):
""" Checks the mouse position and detects mouse hover. """
if self.hit is not False:
# print(self.hit)
self.my_map.getChild(self.hit).setColor(WHITE)
self.hit = False
if self.mouseWatcherNode.hasMouse():
m_pos = self.mouseWatcherNode.getMouse()
# cast a ray, and traverse tha map to detect which tile was hit by the ray
self.picker_ray.setFromLens(self.camNode, m_pos.getX(), m_pos.getY())
self.picker.traverse(self.my_map)
if self.queue.getNumEntries() > 0:
# if we have hits, sort the hits so that the closest is first, and highlight that node
self.queue.sortEntries()
tile = self.queue.getEntry(0).getIntoNodePath().getNode(2) # getNode(2)->tile node, at index 2
tile_index = int(tile.getName().split("-")[1])
self.my_map.getChild(tile_index).setColor(HIGHLIGHT)
self.hit = tile_index
return task.cont
def create_map(self, width, height):
""" Creates a 2D grid of of tiles. """
counter = 0
for z in range(height):
for x in range(width):
tile = self.my_map.attachNewNode("tile-" + str(counter))
tile.setPos(x, 0, z)
self.plane.instanceTo(tile) # first we have to create an instance, after this we can set the BitMask
tile.find("**/pPlane1").node().setIntoCollideMask(BitMask32.bit(1))
counter += 1
game = IsometricGame()
game.run()
|
C#
|
UTF-8
| 910 | 3.15625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
namespace FactoryPattern.Factory
{
class PointSampleString : ISampleString
{
private static PointSampleString PointSample; // multi-thread durumlarda volatile da eklenebilir
// private static object CntrolObj = new object();
private PointSampleString()
{
}
public static ISampleString CreateInstance()
{
if (PointSample == null)
{
//lock (CntrolObj) // multi-thread durumlarda eklenir
//{
//if (PointSample == null)
//{
PointSample = new PointSampleString();
//}
//}
}
return PointSample;
}
public string GetSampleString()
{
return "10,20";
}
}
}
|
C++
|
UTF-8
| 429 | 2.90625 | 3 |
[
"Unlicense"
] |
permissive
|
#include <iostream>
void answer(unsigned v)
{
std::cout << v << '\n';
}
void solve(unsigned x)
{
const unsigned d = x % 10;
unsigned k = d * 10;
k -= 4 * (x < 1111);
k -= 3 * (x < 111);
k -= 2 * (x < 11);
answer(k);
}
void test_case()
{
unsigned x;
std::cin >> x;
solve(x);
}
int main()
{
size_t t;
std::cin >> t;
while (t-- > 0)
test_case();
return 0;
}
|
Java
|
UTF-8
| 251 | 2.484375 | 2 |
[] |
no_license
|
package multi_thread.Chapter2.manySynMethodsInClass;
public class ThreadB extends Thread
{
private Service s;
public ThreadB(Service s)
{
this.s = s;
}
@Override
public void run()
{
s.service1();
}
}
|
Python
|
UTF-8
| 632 | 3.140625 | 3 |
[] |
no_license
|
import re
def solution(new_id):
# 1단계
new_id = new_id.lower()
# 2단계
new_id = re.sub('[^a-z\d\-\_\.]','',new_id)
# 3단계
while '..' in new_id:
new_id = new_id.replace('..','.')
# 4단계
if new_id:
if new_id[0] == '.':
new_id = new_id[1:]
if new_id:
if new_id[-1] == '.':
new_id = new_id[:-1]
# 5단계
else:
new_id = 'a'
# 6단계
new_id = new_id[:15]
if new_id[-1] == '.':
new_id = new_id[:-1]
# 7단계
while len(new_id) <= 2:
new_id += new_id[-1]
return new_id
|
JavaScript
|
UTF-8
| 533 | 3.40625 | 3 |
[] |
no_license
|
/**
* Maja Miarecki codility solution
* https://app.codility.com/programmers/lessons/1-iterations/
*/
function solution(N) {
const arr = N.toString(2).split('');
const max = arr.length;
let result = 0;
let temp = 0;
for (let i = 0; i < max; i++) {
const current = arr[i];
const previous = arr[i - 1];
if (current === '0' && (previous === '1' || temp)) {
temp ++;
} else if (previous === '0' && current === '1') {
result = temp > result ? temp : result;
temp = 0;
}
}
return result;
}
|
Java
|
UTF-8
| 5,848 | 2.25 | 2 |
[] |
no_license
|
package com.springboot.service.impl;
import com.springboot.exception.GlobalException;
import com.springboot.mapper.UserMapper;
import com.springboot.model.User;
import com.springboot.model.UserAttention;
import com.springboot.result.CodeMsg;
import com.springboot.service.UserService;
import com.springboot.utils.SHA1;
import java.util.HashMap;
import java.util.List;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisCluster;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private JedisCluster jedisCluster;
public List<User> getUsers() {
return this.userMapper.getUsers();
}
@Transactional(propagation = Propagation.REQUIRED)
public HashMap<String, Object> addUser(JSONObject param) {
HashMap<String, Object> map = new HashMap();
try {
User u = new User();
u.setName("wangwu");
u.setPassword("123456");
this.userMapper.insertSelective(u);
} catch (Exception e) {
e.printStackTrace();
throw new GlobalException(CodeMsg.ACCESS_LIMIT_REACHED);
}
return map;
}
public HashMap<String, Object> sendRegister(JSONObject param) {
HashMap<String, Object> map = new HashMap();
map.put("success", Integer.valueOf(0));
if (param.containsKey("phone")) {
User record = new User();
record.setPhone(param.getString("phone"));
if (this.userMapper.selectByKey(record) == null) {
map.put("success", 1);
} else {
map.put("tips", "手机号已经被注册啦!");
}
} else {
map.put("tips", "数据格式错误");
}
return map;
}
@Transactional(propagation = Propagation.REQUIRED)
public HashMap<String, Object> validRegister(JSONObject param) {
HashMap<String, Object> map = new HashMap();
int success = 0;
boolean isValid = true;
User u = new User();
u.setPhone(param.getString("phone"));
u.setPassword(SHA1.sha1(param.getString("password")));
this.userMapper.insert(u);
if (isValid) {
success = 1;
}
map.put("user", u);
map.put("success", success);
return map;
}
public HashMap<String, Object> login(JSONObject param) {
HashMap<String, Object> map = new HashMap();
int success = 0;
User u = new User();
u.setPhone(param.getString("phone"));
u.setPassword(SHA1.sha1(param.getString("password")));
User user = this.userMapper.selectByKey(u);
if (user != null) {
success = 1;
map.put("user", user);
}
map.put("success", success);
return map;
}
public HashMap<String, Object> getAttention(JSONObject param) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("data", this.userMapper.getUserAttention(param.getString("userId")));
map.put("success", 1);
return map;
}
public HashMap<String, Object> updateUser(JSONObject param) {
HashMap<String, Object> map = new HashMap();
User user = new User();
user.setId(Integer.valueOf(param.getInt("id")));
if (param.containsKey("name")) {
user.setName(param.getString("name"));
}
if (param.containsKey("description")) {
user.setDescription(param.getString("description"));
}
if (param.containsKey("sex")) {
user.setSex(Integer.valueOf(param.getInt("sex")));
}
if (param.containsKey("birthday")) {
user.setBirthday(param.getString("birthday"));
}
if (param.containsKey("photo")) {
user.setPhoto(param.getString("photo"));
}
this.userMapper.updateByPrimaryKey(user);
map.put("success", 1);
return map;
}
public HashMap<String, Object> updateUserPassword(JSONObject param) {
HashMap<String, Object> map = new HashMap();
User user = new User();
if (param.containsKey("id")) {
user.setId(Integer.valueOf(param.getInt("id")));
}
if (param.containsKey("name")) {
user.setName(param.getString("name"));
}
if (param.containsKey("description")) {
user.setDescription(param.getString("description"));
}
if (param.containsKey("sex")) {
user.setSex(Integer.valueOf(param.getInt("sex")));
}
if (param.containsKey("phone")) {
user.setPhone(param.getString("phone"));
}
if (param.containsKey("password")) {
user.setPassword(SHA1.sha1(param.getString("password")));
}
this.userMapper.updateByPrimaryKey(user);
map.put("success", 1);
return map;
}
public HashMap<String, Object> validRegisterTWO(JSONObject param) {
return null;
}
public HashMap<String, Object> addAttention(JSONObject param) {
HashMap<String, Object> map = new HashMap();
UserAttention at = new UserAttention();
at.setAttentionId(Integer.valueOf(param.getInt("attentionId")));
at.setUserId(Integer.valueOf(param.getInt("userId")));
if (param.getInt("type") == 1) {
this.userMapper.insertUserAttention(at);
this.userMapper.updateAttentionCount(param.getInt("userId"));
}
if (param.getInt("type") == 2) {
this.userMapper.deleteUserAttention(at);
this.userMapper.updateAttentionCountCut(param.getInt("userId"));
}
map.put("success", 1);
return map;
}
public HashMap<String, Object> findAttention(JSONObject param) {
HashMap<String, Object> map = new HashMap();
UserAttention at = new UserAttention();
at.setAttentionId(Integer.valueOf(param.getInt("attentionId")));
at.setUserId(Integer.valueOf(param.getInt("userId")));
map.put("user", this.userMapper.findUserAttention(at));
map.put("success", 1);
return map;
}
@Override
public HashMap<String, Object> finUserById(JSONObject paramJSONObject) {
HashMap<String, Object> map = new HashMap();
User user = new User();
user.setId(paramJSONObject.getInt("userId"));
map.put("user", this.userMapper.selectByKey(user));
map.put("success", 1);
return map;
}
}
|
C++
|
UTF-8
| 727 | 3.25 | 3 |
[] |
no_license
|
#include <vector>
#include <queue>
#include <limits>
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
std::vector<int> res;
std::queue<TreeNode*> q;
if (root) q.push(root);
while (!q.empty()) {
int size = q.size();
int max = std::numeric_limits<int>::min();
for (int i = 0; i < size; ++i) {
TreeNode* node = q.front();
q.pop();
if (max < node->val) max = node->val;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
res.push_back(max);
}
return res;
}
};
|
SQL
|
UTF-8
| 1,949 | 2.90625 | 3 |
[] |
no_license
|
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Versión del servidor: 10.4.8-MariaDB - mariadb.org binary distribution
-- SO del servidor: Win64
-- HeidiSQL Versión: 10.2.0.5599
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Volcando estructura de base de datos para proyecto_python2
CREATE DATABASE IF NOT EXISTS `proyecto_python2` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `proyecto_python2`;
-- Volcando estructura para tabla proyecto_python2.proyecto2
CREATE TABLE IF NOT EXISTS `proyecto2` (
`nombreequipos` varchar(50) DEFAULT NULL,
`puntuacion` int(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- Volcando datos para la tabla proyecto_python2.proyecto2: ~16 rows (aproximadamente)
/*!40000 ALTER TABLE `proyecto2` DISABLE KEYS */;
INSERT IGNORE INTO `proyecto2` (`nombreequipos`, `puntuacion`) VALUES
('FC Barcelona Femenino', 13),
('Deportivo de La Coruña Femenino', 13),
('Atlético de Madrid Femenino', 12),
('EDF Logroño', 10),
('Madrid CFF', 9),
('Valencia CF Femenino', 8),
('Real Sociedad Femenino', 8),
('Levante UD Femenino', 7),
('Rayo Vallecano Femenino', 7),
('Athletic Club Femenino', 6),
('UD Granadilla Femenino', 5),
('Real Betis Féminas', 4),
('Tacon', 4),
('Sevilla Femenino', 3),
('Sporting Huelva Femenino', 3),
('Espanyol Femenino', 1);
/*!40000 ALTER TABLE `proyecto2` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
dbdb
|
C++
|
UTF-8
| 552 | 2.671875 | 3 |
[] |
no_license
|
// NamaFile BUffaloMilk.h
#ifndef BUFFALOMILK_H
#define BUFFALOMILK_H
#include "FarmProduct.h"
// Kelas BuffaloMilk adalah kelas dari susu kerbau yang bisa didapat pemain saat program dijalankan
class BuffaloMilk : public FarmProduct{
private:
static string className;
static int n; //Mengembalikan jumlah dari BuffaloMilk yang dimiliki oleh pemain
static int price; //Mengembalikan harga dari BuffaloMilk saat penjualan
public:
string getClassName();
int getPrice(); // mengembalikan harga buffalomeat jika terjual
};
#endif
|
C#
|
UTF-8
| 1,796 | 2.71875 | 3 |
[] |
no_license
|
using System.Data.SqlClient;
using System;
using System.Configuration;
namespace DAOS.LayerDao
{
public abstract class Dao
{
protected SqlConnection cn; //mantém a conexão com o bd
protected SqlCommand cmd; // executa instruções de procedures
protected SqlDataReader reader; // consultas - modo conectado
protected SqlDataAdapter da; //Consultas modo desconectado
protected String conexao = ConfigurationManager.ConnectionStrings["SchoolDB"].ConnectionString;
// protected String conexao = ConfigurationManager.ConnectionStrings["DES"].ConnectionString;
// protected String conexao = ConfigurationManager.AppSettings.Keys[1].ToString();
//protected String conexao = ConfigurationManager.ConnectionStrings[FunctionsGen.GetEnvironmentVariableServerPre].ConnectionString;
public Dao()
{
SchoolDao scdao = new SchoolDao();
try
{
cn = new SqlConnection(conexao);
cmd = new SqlCommand();
da = new SqlDataAdapter();
}
catch (Exception ex)
{
throw ex;
}
}
public void OpenConnection()
{
SchoolDao scdao = new SchoolDao();
try
{
scdao.GravaLog("Abrindo conexão");
cn.Open();
cmd.Connection = cn;
}
catch (Exception ex)
{
throw ex;
}
}
public void ClosedConnection()
{
if (cn.State == System.Data.ConnectionState.Open)
{
cn.Close();
}
}
}
}
|
Python
|
UTF-8
| 548 | 3.546875 | 4 |
[] |
no_license
|
'''
for i in range(2,10):
for j in range(1,10):
print(i, '*', j, '=', i*j, end= ' ')
print('')
'''
'''
for i in range(1,10):
for j in range(2,10):
print('%d * %d =' %(j,i),(j*i), end= ' ')
print('')
'''
'''
a = ['one', 'two', 'hi', '^^']
result = []
for num in a:
result.append(num)
print(result)
'''
'''
a = [1, 2, 3, 4]
result = []
for num in a:
if num % 2 ==0:
result.append(num * 3)
print(result)
'''
'''
a = [1, 2, 3, 4]
result = [num * 3 for num in a if num % 2 == 0]
print(result)
'''
|
C++
|
UTF-8
| 9,706 | 2.75 | 3 |
[] |
no_license
|
/**
C++ client example using sockets
*/
#include<iostream> //cout
#include<stdio.h> //printf
#include<string.h> //strlen
#include<string> //string
#include<sys/socket.h> //socket
#include<arpa/inet.h> //inet_addr
#include<netdb.h> //hostent
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include "ros/ros.h"
#include "tekscan_client/fingertips_calib_data.h"
#include "tekscan_client/GetPressureMap.h"
#include <math.h>
using namespace std;
using namespace boost;
/**
TCP Client class
*/
class tcp_client
{
private:
int sock;
std::string address;
int port;
struct sockaddr_in server;
public:
tcp_client();
bool conn(string, int);
bool send_data(string data);
string receive(int);
char* receive_byte_array(int);
};
tcp_client::tcp_client()
{
sock = -1;
port = 0;
address = "";
}
/**
Connect to a host on a certain port number
*/
bool tcp_client::conn(string address , int port)
{
//create socket if it is not already created
if(sock == -1)
{
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
perror("Could not create socket");
}
cout<<"Socket created\n";
}
else { /* OK , nothing */ }
//setup address structure
if(inet_addr(address.c_str()) == -1)
{
struct hostent *he;
struct in_addr **addr_list;
//resolve the hostname, its not an ip address
if ( (he = gethostbyname( address.c_str() ) ) == NULL)
{
//gethostbyname failed
herror("gethostbyname");
cout<<"Failed to resolve hostname\n";
return false;
}
//Cast the h_addr_list to in_addr , since h_addr_list also has the ip address in long format only
addr_list = (struct in_addr **) he->h_addr_list;
for(int i = 0; addr_list[i] != NULL; i++)
{
//strcpy(ip , inet_ntoa(*addr_list[i]) );
server.sin_addr = *addr_list[i];
cout<<address<<" resolved to "<<inet_ntoa(*addr_list[i])<<endl;
break;
}
}
//plain ip address
else
{
server.sin_addr.s_addr = inet_addr( address.c_str() );
}
server.sin_family = AF_INET;
server.sin_port = htons( port );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
cout<<"Connected\n";
return true;
}
/**
Send data to the connected host
*/
bool tcp_client::send_data(string data)
{
//Send some data
if( send(sock , data.c_str() , strlen( data.c_str() ) , 0) < 0)
{
perror("Send failed : ");
return false;
}
cout<<"Data send\n";
return true;
}
/**
Receive data from the connected host
*/
string tcp_client::receive(int size=512)
{
char buffer[size];
string reply;
//Receive a reply from the server
if( recv(sock , buffer , sizeof(buffer) , 0) < 0)
{
puts("recv failed");
}
reply = buffer;
return reply;
}
tcp_client c;
bool pressure_service(tekscan_client::GetPressureMap::Request &req, tekscan_client::GetPressureMap::Response &res)
{
std::vector<int> ftips_values(80);
std::vector<float> ftips_calib_values(80);
std::vector<float> finger_total_pressure(5);
std::vector<float> finger_forces(5);
std::vector<float> fi_(16);
std::vector<float> forces_deviation(5);
int value, pos;
float sum_deviation;
c.send_data("TIPSCALDATA");
//receive and echo reply
//cout<<"----------------------------\n\n";
string response = c.receive(1024);
// formatear respuesta
std::replace( response.begin(), response.end(), ',', '.'); // replace all ',' to '.'
// Convertir a array int[] o float[]
char_separator<char> sep(" ");
tokenizer<char_separator<char> > tokens(response, sep);
pos=0;
int aux_pos = 0;
int map_pos = 0;
BOOST_FOREACH (const string& t, tokens) {
if(pos<=79){
ftips_calib_values.at(pos) = atof (t.c_str());
// mostrar por pantalla
if( pos == 0) printf("Thumb: \n");
else if (pos == 16) printf("First finger: \n");
else if (pos == 32) printf("Middle finger: \n");
else if (pos == 48) printf("Ring finger: \n");
else if (pos == 64) printf("Little finger: \n");
printf("%f ",ftips_calib_values.at(pos));
if( pos <= 15) res.th_values[map_pos] = ftips_calib_values.at(pos);
else if (pos <= 31) res.ff_values[map_pos] = ftips_calib_values.at(pos);
else if (pos <= 47) res.mf_values[map_pos] = ftips_calib_values.at(pos);
else if (pos <= 63) res.rf_values[map_pos] = ftips_calib_values.at(pos);
else if (pos <= 79) res.lf_values[map_pos] = ftips_calib_values.at(pos);
aux_pos+=1;
map_pos+=1;
pos+=1;
if (aux_pos == 4){ printf("\n \n"); aux_pos=0;}
if (map_pos == 16){ map_pos=0;}
}
}
// Obtener fuerza aplicada, y centroide de la fuerza aplicada para cada dedo
//float superficie = 2.03; // cm cuadrados 1.4 x 1.4
float superficie = 2.56; // cm cuadrados 1.6 x 1.6
//float superficie = 2.89; // cm cuadrados 1.7 x 1.7
float force = 0.0;
// Thumb
for(int finger=0; finger<5; finger++){
if (finger == 0){
float th_pressure_sum = 0;
for(int pos=0; pos<16; pos++){
th_pressure_sum += res.th_values[pos];
fi_[pos] = res.th_values[pos] * (2.56 / 16); // F (N) = p (N*cm2)*s (cm2) ; s = Superficie_total / num_celdas
force += fi_[pos];
}
//force = superficie * (th_pressure_sum / 16);
// actualizar mensaje /pressure_map
res.applied_force[0] = force;
res.total_pressure[0] = th_pressure_sum;
// calcular desviación tipica
sum_deviation = 0;
for(int pos=0; pos<16; pos++){
sum_deviation += pow( (fi_[pos] - (force/16)),2);
}
res.force_deviation[0] = (float) sqrt(sum_deviation/15);
}
// First finger
if (finger == 1){
float ff_pressure_sum = 0;
force = 0;
for(int pos=0; pos<16; pos++){
ff_pressure_sum += res.ff_values[pos];
fi_[pos] = res.ff_values[pos] * (2.56 / 16); // F = p*s ; s = Superficie_total / num_celdas
force += fi_[pos];
}
//force = superficie * (ff_pressure_sum / 16);
// actualizar mensaje /pressure_map
res.applied_force[1] = force;
res.total_pressure[1] = ff_pressure_sum;
// calcular desviación tipica
sum_deviation = 0;
for(int pos=0; pos<16; pos++){
sum_deviation += pow( (fi_[pos] - (force/16)),2);
}
res.force_deviation[1] = (float) sqrt(sum_deviation/15);
}
// middle finger
if (finger == 2){
float mf_pressure_sum = 0;
force = 0;
for(int pos=0; pos<16; pos++){
mf_pressure_sum += res.mf_values[pos];
fi_[pos] = res.mf_values[pos] * (2.56 / 16); // F = p*s ; s = Superficie_total / num_celdas
force += fi_[pos];
}
//force = superficie * (mf_pressure_sum / 16);
// actualizar mensaje /pressure_map
res.applied_force[2] = force;
res.total_pressure[2] = mf_pressure_sum;
// calcular desviación tipica
sum_deviation = 0;
for(int pos=0; pos<16; pos++){
sum_deviation += pow( (fi_[pos] - (force/16)),2);
}
res.force_deviation[2] = (float) sqrt(sum_deviation/15);
}
// ring finger
if (finger == 3){
float rf_pressure_sum = 0;
force = 0;
for(int pos=0; pos<16; pos++){
rf_pressure_sum += res.rf_values[pos];
fi_[pos] = res.rf_values[pos] * (2.56 / 16); // F = p*s ; s = Superficie_total / num_celdas
force += fi_[pos];
}
//force = superficie * (rf_pressure_sum /16);
// actualizar mensaje /pressure_map
res.applied_force[3] = force;
res.total_pressure[3] = rf_pressure_sum;
// calcular desviación tipica
sum_deviation = 0;
for(int pos=0; pos<16; pos++){
sum_deviation += pow( (fi_[pos] - (force/16)),2);
}
res.force_deviation[3] = (float) sqrt(sum_deviation/15);
}
// little finger
if (finger == 4){
float lf_pressure_sum = 0;
force = 0;
for(int pos=0; pos<16; pos++){
lf_pressure_sum += res.lf_values[pos];
fi_[pos] = res.lf_values[pos] * (2.56 / 16); // F = p*s ; s = Superficie_total / num_celdas
force += fi_[pos];
}
//force = superficie * (lf_pressure_sum / 16);
// actualizar mensaje /pressure_map
res.applied_force[4] = force;
res.total_pressure[4] = lf_pressure_sum;
// calcular desviación tipica
sum_deviation = 0;
for(int pos=0; pos<16; pos++){
sum_deviation += pow( (fi_[pos] - (force/16)),2);
}
res.force_deviation[4] = (float) sqrt(sum_deviation/15);
}
}
}
int main(int argc , char *argv[])
{
/**
* Definir nodo publisher
*
*/
ros::init(argc, argv, "pressure_map_service");
ros::NodeHandle n;
ros::Publisher pressure_pub = n.advertise<tekscan_client::fingertips_calib_data>("pressure_map",1000);
ros::ServiceServer service = n.advertiseService("GetPressureMap", pressure_service);
// Conexion a servidor tekscan server
string host;
string opc;
host = "172.18.34.134";
//connect to host
c.conn(host , 13000);
ros::spin();
return 0;
}
|
JavaScript
|
UTF-8
| 1,051 | 3.234375 | 3 |
[] |
no_license
|
var backtick = "Angular"; //backtick symbol example
console.log(backtick);
var dubqu = "mean"; //double quotes string example
console.log(dubqu);
var squots = 'mern'; //single quote string ex
console.log(squots);
var dec = 101; //decimal no
console.log(dec);
var doub = 1020.20; //double no
console.log(doub);
var hexa = 0xac; //hexadecimal no
console.log(hexa);
var oct = 81; //octal no
console.log(oct);
var bin = 011101; //binary no
console.log(bin);
var fulName = 'angular,1235,10.205'; //any datatype ex
console.log(fulName);
var stats = true; //boolean data type ex
console.log(stats);
var arEg = [10, 20, 30, 40, 50]; //arry with squre bracket
var genArr = [60, 70, 80, 90, 100]; //generic array
arEg.forEach(function (element, index) {
console.log(element, genArr[index]);
});
var tbln = "employee"; //var key ex
var uname = "admin"; //const keywor ex
var pass = "admin123";
var sqlQ = "select * from " + tbln + " where uname='" + uname + "'and pass='" + pass + "'"; //demonstration of $ symbol for accesing variable
console.log(sqlQ);
|
Markdown
|
UTF-8
| 2,053 | 2.546875 | 3 |
[] |
no_license
|
<img src="http://i.imgur.com/4Sh8rBx.png" width="900">
<br><a href="http://www.youtube.com/watch?v=IFpPBQsTcFo&feature=youtu.be" rel="nofollow" target="_blank">Youtube.</a>
**So what does it do?**
I find it handy for keeping track of my decks and tweaking them, experimenting with deck ideas, keeping track of my collection, and seeing what I don't have in a set. It has a comprehensive query system and a search bar for looking by name, tribal, keyword.
**Notable features:**
- Deck Notes
- Random card draw (in full version)
- Deck value and collection value is tracked.
- But my favorite is that it outputs your deck into the raw text format for tappedout.com so you can share decks fairly easily with your friends / whomever.
**Take Note:**
- Card prices are old and not currently connected via the web.
- Demo only contains about 200 cards. So only a few starting with A.
- Querying through all cards is a little slow right now and something I will optimize so stick to "my cards" for best results.
- While functional, swing doesn't exactly look too great on windows.
- Also for unknown reasons some cards may be french.
Windows <a href="https://dl.dropboxusercontent.com/s/79iwezw9q6nf9k3/WindowsDemo.zip?dl=1&token_hash=AAFoeYnTwoT6TbSsW0Qehqm3-fLbQ1quPoNfb90cHJjSag">
demo</a> | <a href="https://dl.dropboxusercontent.com/s/fpeg9z28seyafrq/VCO.zip?dl=1&token_hash=AAE3i-QXBQRjgTLeCf8KyhdPN5F50TdTWP-FEbiUi4JOsA">
Full</a>
- Unpack and move the VCO folder to your home directory (C:\Users\yourName).
- Click on the jar (You can move this to your desktop).
Mac <a href="https://dl.dropboxusercont ent.com/s/g4e9r90k1lsmeeh/Demo.zip?dl=1&token_hash=AAF-1OewSQhskTMSAzYapn_0-Kj0qhNKaJ2Zp0bRb2Mtqw">
demo</a> | <a href="https://dl-web.dropbox.com/get/VCO.zip?w=AACM9uKaoz7t9jwWAYN-qN8Bbni_fsRUZwDvVCSj5H7vhQ&dl=1">
Full.</a>
- Same as above but if on desktop, the folder will automatically move to your home folder when you first click the jar.
**Hotkeys:** (Check "deck build mode" or "sideboard" to add cards to respective tables.)
- Enter = add card
- \ = remove card
- ] = card to sideboard
- [ = sideboard to deck
|
TypeScript
|
UTF-8
| 1,862 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
import { Component, OnInit } from '@angular/core';
import { Quote} from '../quote';
@Component({
selector: 'app-quote',
templateUrl: './quote.component.html',
styleUrls: ['./quote.component.css']
})
export class QuoteComponent implements OnInit {
deleteQuote(isComplete, index){
if (isComplete) {
let toDelete = confirm(`Are you sure you want to delete ${this.quote[index].name}?`)
if (toDelete){
this.quote.splice(index,1)
}
else{
alert('Thank you for leaving your quote!!!.')
}
}
}
quote: Quote[] = [
new Quote(1, "People Who Are Crazy Enough To Think They Can Change The World,Are One Who Do. Author-Rob Siltanen", "",new Date(2019,1,1)),
new Quote(2, "Entrepreneurs Are Great At Dealing With Uncertainty And Also Very Good At Minimizing Risk. That’s The Classic Entrepreneur. Author-Mohnish Pabrai","",new Date(2019,4,14)),
new Quote(3, "Imagine Your Life Is Perfect In Every Respect; What Would It Look Like?. Author-Brian Tracy","",new Date(2019,9,2)),
new Quote(4, "Security Is Mostly A Superstition. Life Is Either A Daring Adventure Or Nothing. Author-Helen Keller","",new Date(2018,6,2)),
new Quote(5, "What You Lack In Talent Can Be Made Up With Desire, Hustle And Giving 110% All The Time. Author-Don Zimmer","",new Date(2018,3,4)),
new Quote(6, "Do not let what you can not do interfare with what you can do. Author-Samwel.A.Rangili","",new Date(2020,4,2)),
];
toggleDetails(index){
this.quote[index].showDescription = !this.quote[index].showDescription;
}
completeQuote(isComplete, index){
if (isComplete) {
this.quote.splice(index,1);
}
}
addNewQuote(quote){
let quoteLength = this.quote.length;
quote.id = quoteLength+1;
quote.completeDate = new Date(quote.completeDate)
this.quote.push(quote)
}
constructor() { }
ngOnInit() {
}
}
|
C#
|
UTF-8
| 2,838 | 3.109375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace RPGPlatformerEngine
{
/// <summary>
/// This class represents an item icon in the inventory.
/// </summary>
public class InventoryItem : GameObject
{
int quantity = 1;
string name = "";
/// <summary>
/// The name of the item
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// The quantity of the item.
/// </summary>
public int Quantity
{
get { return quantity; }
set { quantity = value; }
}
/// <summary>
/// Create a new item object.
/// </summary>
/// <param name="itemName">The name of the item and the name of the texture file.</param>
public InventoryItem(string itemName)
{
Name = itemName;
texture = TextureManager.SetTexture("Items/" + itemName);
}
/// <summary>
/// Create a new item object.
/// </summary>
/// <param name="itemName">The name of the item/</param>
/// <param name="itemTexture">The texture of the item</param>
public InventoryItem(string itemName,Texture2D itemTexture)
{
name = itemName;
texture = itemTexture;
}
/// <summary>
/// A Copy constructor.
/// </summary>
/// <param name="other">The other Item object to copy from.</param>
public InventoryItem(InventoryItem other)
{
name = other.Name;
texture = other.Texture;
}
/// <summary>
/// Updates the inventory item.
/// </summary>
public override void Update()
{
base.Update();
if (Hover())
OnHover();
else
Normal();
}
/// <summary>
/// Checks if two items are the same
/// </summary>
/// <param name="other">The other item to check with.</param>
/// <returns>True if this item equals to the other item.</returns>
public bool Equals(InventoryItem other)
{
return name == other.name && texture == other.texture;
}
private void Normal()
{
scale = 1;
}
private void OnHover()
{
scale += 0.02f;
if (scale >= 1.1f)
scale = 1.1f;
}
private bool Hover()
{
return Input.MouseRectangle.Intersects(BoundBox);
}
}
}
|
Markdown
|
UTF-8
| 9,890 | 3.125 | 3 |
[
"Apache-2.0"
] |
permissive
|
ictlyh Translating
Writing a Linux Debugger Part 6: Source-level stepping
============================================================
A couple of posts ago we learned about DWARF information and how it lets us relate the machine code to the high-level source. This time we’ll be putting this knowledge into practice by adding source-level stepping to our debugger.
* * *
### Series index
These links will go live as the rest of the posts are released.
1. [Setup][1]
2. [Breakpoints][2]
3. [Registers and memory][3]
4. [Elves and dwarves][4]
5. [Source and signals][5]
6. [Source-level stepping][6]
7. Source-level breakpoints
8. Stack unwinding
9. Reading variables
10. Next steps
* * *
### Exposing instruction-level stepping
But we’re getting ahead of ourselves. First let’s expose instruction-level single stepping through the user interface. I decided to split it between a `single_step_instruction` which can be used by other parts of the code, and a `single_step_instruction_with_breakpoint_check` which ensures that any breakpoints are disabled and re-enabled.
```
void debugger::single_step_instruction() {
ptrace(PTRACE_SINGLESTEP, m_pid, nullptr, nullptr);
wait_for_signal();
}
void debugger::single_step_instruction_with_breakpoint_check() {
//first, check to see if we need to disable and enable a breakpoint
if (m_breakpoints.count(get_pc())) {
step_over_breakpoint();
}
else {
single_step_instruction();
}
}
```
As usual, another command gets lumped into our `handle_command` function:
```
else if(is_prefix(command, "stepi")) {
single_step_instruction_with_breakpoint_check();
auto line_entry = get_line_entry_from_pc(get_pc());
print_source(line_entry->file->path, line_entry->line);
}
```
With these functions added we can begin to implement our source-level stepping functions.
* * *
### Implementing the steps
We’re going to write very simple versions of these functions, but real debuggers tend to have the concept of a _thread plan_ which encapsulates all of the stepping information. For example, a debugger might have some complex logic to determine breakpoint sites, then have some callback which determines whether or not the step operation has completed. This is a lot of infrastructure to get in place, so we’ll just take a naive approach. We might end up accidentally stepping over breakpoints, but you can spend some time getting all the details right if you like.
For `step_out`, we’ll just set a breakpoint at the return address of the function and continue. I don’t want to get into the details of stack unwinding yet – that’ll come in a later part – but it suffices to say for now that the return address is stored 8 bytes after the start of a stack frame. So we’ll just read the frame pointer and read a word of memory at the relevant address:
```
void debugger::step_out() {
auto frame_pointer = get_register_value(m_pid, reg::rbp);
auto return_address = read_memory(frame_pointer+8);
bool should_remove_breakpoint = false;
if (!m_breakpoints.count(return_address)) {
set_breakpoint_at_address(return_address);
should_remove_breakpoint = true;
}
continue_execution();
if (should_remove_breakpoint) {
remove_breakpoint(return_address);
}
}
```
`remove_breakpoint` is a little helper function:
```
void debugger::remove_breakpoint(std::intptr_t addr) {
if (m_breakpoints.at(addr).is_enabled()) {
m_breakpoints.at(addr).disable();
}
m_breakpoints.erase(addr);
}
```
Next is `step_in`. A simple algorithm is to just keep on stepping over instructions until we get to a new line.
```
void debugger::step_in() {
auto line = get_line_entry_from_pc(get_pc())->line;
while (get_line_entry_from_pc(get_pc())->line == line) {
single_step_instruction_with_breakpoint_check();
}
auto line_entry = get_line_entry_from_pc(get_pc());
print_source(line_entry->file->path, line_entry->line);
}
```
`step_over` is the most difficult of the three for us. Conceptually, the solution is to just set a breakpoint at the next source line, but what is the next source line? It might not be the one directly succeeding the current line, as we could be in a loop, or some conditional construct. Real debuggers will often examine what instruction is being executed and work out all of the possible branch targets, then set breakpoints on all of them. I’d rather not implement or integrate an x86 instruction emulator for such a small project, so we’ll need to come up with a simpler solution. A couple of horrible options are to just keep stepping until we’re at a new line in the current function, or to just set a breakpoint at every line in the current function. The former would be ridiculously inefficient if we’re stepping over a function call, as we’d need to single step through every single instruction in that call graph, so I’ll go for the second solution.
```
void debugger::step_over() {
auto func = get_function_from_pc(get_pc());
auto func_entry = at_low_pc(func);
auto func_end = at_high_pc(func);
auto line = get_line_entry_from_pc(func_entry);
auto start_line = get_line_entry_from_pc(get_pc());
std::vector<std::intptr_t> to_delete{};
while (line->address < func_end) {
if (line->address != start_line->address && !m_breakpoints.count(line->address)) {
set_breakpoint_at_address(line->address);
to_delete.push_back(line->address);
}
++line;
}
auto frame_pointer = get_register_value(m_pid, reg::rbp);
auto return_address = read_memory(frame_pointer+8);
if (!m_breakpoints.count(return_address)) {
set_breakpoint_at_address(return_address);
to_delete.push_back(return_address);
}
continue_execution();
for (auto addr : to_delete) {
remove_breakpoint(addr);
}
}
```
This function is a bit more complex, so I’ll break it down a bit.
```
auto func = get_function_from_pc(get_pc());
auto func_entry = at_low_pc(func);
auto func_end = at_high_pc(func);
```
`at_low_pc` and `at_high_pc` are functions from `libelfin` which will get us the low and high PC values for the given function DIE.
```
auto line = get_line_entry_from_pc(func_entry);
auto start_line = get_line_entry_from_pc(get_pc());
std::vector<std::intptr_t> breakpoints_to_remove{};
while (line->address < func_end) {
if (line->address != start_line->address && !m_breakpoints.count(line->address)) {
set_breakpoint_at_address(line->address);
breakpoints_to_remove.push_back(line->address);
}
++line;
}
```
We’ll need to remove any breakpoints we set so that they don’t leak out of our step function, so we keep track of them in a `std::vector`. To set all the breakpoints, we loop over the line table entries until we hit one which is outside the range of our function. For each one, we make sure that it’s not the line we are currently on, and that there’s not already a breakpoint set at that location.
```
auto frame_pointer = get_register_value(m_pid, reg::rbp);
auto return_address = read_memory(frame_pointer+8);
if (!m_breakpoints.count(return_address)) {
set_breakpoint_at_address(return_address);
to_delete.push_back(return_address);
}
```
Here we are setting a breakpoint on the return address of the function, just like in `step_out`.
```
continue_execution();
for (auto addr : to_delete) {
remove_breakpoint(addr);
}
```
Finally, we continue until one of those breakpoints has been hit, then remove all the temporary breakpoints we set.
It ain’t pretty, but it’ll do for now.
Of course, we also need to add this new functionality to our UI:
```
else if(is_prefix(command, "step")) {
step_in();
}
else if(is_prefix(command, "next")) {
step_over();
}
else if(is_prefix(command, "finish")) {
step_out();
}
```
* * *
### Testing it out
I tested out my implementation with a simple program which calls a bunch of different functions:
```
void a() {
int foo = 1;
}
void b() {
int foo = 2;
a();
}
void c() {
int foo = 3;
b();
}
void d() {
int foo = 4;
c();
}
void e() {
int foo = 5;
d();
}
void f() {
int foo = 6;
e();
}
int main() {
f();
}
```
You should be able to set a breakpoint on the address of `main` and then in, over, and out all over the program. Expect things to break if you try to step out of `main` or into some dynamically linked library.
You can find the code for this post [here][7]. Next time we’ll use our newfound DWARF expertise to implement source-level breakpoints.
--------------------------------------------------------------------------------
via: https://blog.tartanllama.xyz/c++/2017/05/06/writing-a-linux-debugger-dwarf-step/
作者:[TartanLlama ][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://www.twitter.com/TartanLlama
[1]:https://blog.tartanllama.xyz/2017/03/21/writing-a-linux-debugger-setup/
[2]:https://blog.tartanllama.xyz/c++/2017/03/24/writing-a-linux-debugger-breakpoints/
[3]:https://blog.tartanllama.xyz/c++/2017/03/31/writing-a-linux-debugger-registers/
[4]:https://blog.tartanllama.xyz/c++/2017/04/05/writing-a-linux-debugger-elf-dwarf/
[5]:https://blog.tartanllama.xyz/c++/2017/04/24/writing-a-linux-debugger-source-signal/
[6]:https://blog.tartanllama.xyz/c++/2017/05/06/writing-a-linux-debugger-dwarf-step/
[7]:https://github.com/TartanLlama/minidbg/tree/tut_dwarf_step
|
Java
|
UTF-8
| 4,085 | 2.375 | 2 |
[] |
no_license
|
package pro.grain.admin.service;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.ScoreSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import pro.grain.admin.domain.District;
import pro.grain.admin.repository.DistrictRepository;
import pro.grain.admin.repository.search.DistrictSearchRepository;
import pro.grain.admin.service.dto.DistrictDTO;
import pro.grain.admin.service.mapper.DistrictMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* Service Implementation for managing District.
*/
@Service
@Transactional
public class DistrictService {
private final Logger log = LoggerFactory.getLogger(DistrictService.class);
@Inject
private DistrictRepository districtRepository;
@Inject
private DistrictMapper districtMapper;
@Inject
private DistrictSearchRepository districtSearchRepository;
/**
* Save a district.
*
* @param districtDTO the entity to save
* @return the persisted entity
*/
public DistrictDTO save(DistrictDTO districtDTO) {
log.debug("Request to save District : {}", districtDTO);
District district = districtMapper.districtDTOToDistrict(districtDTO);
district = districtRepository.save(district);
DistrictDTO result = districtMapper.districtToDistrictDTO(district);
districtSearchRepository.save(district);
return result;
}
/**
* Get all the districts.
*
* @param pageable the pagination information
* @return the list of entities
*/
@Transactional(readOnly = true)
public Page<DistrictDTO> findAll(Pageable pageable) {
log.debug("Request to get all Districts");
Page<District> result = districtRepository.findAll(pageable);
return result.map(district -> districtMapper.districtToDistrictDTO(district));
}
/**
* Get one district by id.
*
* @param id the id of the entity
* @return the entity
*/
@Transactional(readOnly = true)
public DistrictDTO findOne(Long id) {
log.debug("Request to get District : {}", id);
District district = districtRepository.findOne(id);
DistrictDTO districtDTO = districtMapper.districtToDistrictDTO(district);
return districtDTO;
}
/**
* Delete the district by id.
*
* @param id the id of the entity
*/
public void delete(Long id) {
log.debug("Request to delete District : {}", id);
districtRepository.delete(id);
districtSearchRepository.delete(id);
}
/**
* Search for the district corresponding to the query.
*
* @param query the query of the search
* @return the list of entities
*/
@Transactional(readOnly = true)
public Page<DistrictDTO> search(String query, Pageable pageable) {
log.debug("Request to search for a page of Districts for query {}", query);
QueryBuilder myQuery = boolQuery().should(
queryStringQuery("*" + query + "*").analyzeWildcard(true).
field("name"));
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(myQuery)
.withSort(
new ScoreSortBuilder()
.order(SortOrder.ASC)
)
.withPageable(pageable)
.build();
log.debug("My Query: " + searchQuery);
Page<District> result = districtSearchRepository.search(searchQuery);
return result.map(districtMapper::districtToDistrictDTO);
}
}
|
PHP
|
UTF-8
| 4,726 | 2.71875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2016/9/30
* Time: 11:35
*/
namespace app\models;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
/**
* Class Article
* @package app\modules\models
* 分类模型
*/
class Category extends ActiveRecord
{
/**
* @return string
* 设置数据表
*/
public static function tableName()
{
return '{{%category}}';
}
public function attributeLabels()
{
return [
'title'=>'分类名称',
'parent_id'=>'上级分类',
];
}
/**
* @return array
* 设置验证规则
*/
public function rules()
{
return [
['parent_id', 'required', 'message' => '上级分类不能为空'],
['title', 'required', 'message' => '分类不能为空'],
['title', 'string', 'min' => 2, 'max' => 10, 'tooShort' => '分类不能少于2位', 'tooLong' => '分类不能大于10位'],
];
}
/**
* @param $data
* @return bool
* 添加模型数据
*/
public function add($data)
{
if ($this->load($data) && $this->validate()) {
// $this->create_time = time();
//这里需要注意的是前面有验证的,那么添加的时候不需要在验证,传false即可
if ($this->save(false)) {
return true;
}
return false;
}
return false;
}
/**
* @param $data
* @return bool
* 更新模型数据
*/
public function edit($data)
{
if ($this->load($data) && $this->validate()) {
// $this->update_time = time();
//这里需要注意的是前面有验证的,那么添加的时候不需要在验证,传false即可
if ($this->save(false)) {
return true;
}
return false;
}
return false;
}
// 添加之前或者更新之前的操作
public function beforeSave($insert)
{
//判断父类是否存在
if (parent::beforeSave($insert)) {
$time = time();
//判断是否是添加操作
if ($this->isNewRecord) {
$this->create_time = $time;
}
// //更新操作
// $this->update_time = $time;
return true;
}
return false;
}
public function getCategory()
{
$category = self::find()->all();
// $category = ArrayHelper::toArray($category);
return $category;
}
public function getTree($category, $parent_id = 0)
{
$tree = [];
foreach ($category as $value) {
if ($value['parent_id'] == $parent_id) {
$tree[] = $value;
$tree = array_merge($tree, $this->getTree($category, $value['id']));
}
}
return $tree;
}
public function setPrefix($data, $p = "|-----")
{
$tree = [];
$num = 1;
$prefix = [0 => 1];
while($val = current($data)) {
$key = key($data);
if ($key > 0) {
if ($data[$key - 1]['parent_id'] != $val['parent_id']) {
$num ++;
}
}
if (array_key_exists($val['parent_id'], $prefix)) {
$num = $prefix[$val['parent_id']];
}
$val['title'] = str_repeat($p, $num).$val['title'];
$prefix[$val['parent_id']] = $num;
$tree[] = $val;
next($data);
}
return $tree;
}
public function getOptions()
{
$data = $this->getCategory();
$tree = $this->getTree($data);
$tree = $this->setPrefix($tree);
$options = ['添加顶级分类'];
foreach($tree as $cate) {
$options[$cate['id']] = $cate['title'];
}
return $options;
}
public function getTreeList()
{
$data = $this->getCategory();
$tree = $this->getTree($data);
$lists = $this->setPrefix($tree);
return $lists;
}
/*******************************获取前台数据********************************************************/
public function getMenu()
{
$top = self::find()->where('parent_id = :parent_id',[':parent_id'=>0])->orderBy('create_time asc')->asArray()->all();
$data = [];
foreach ($top as $k=>$category)
{
$category['child'] = self::find()->where('parent_id = :parent_id',[':parent_id'=>$category['id']])->limit(10)->asArray()->all();
$data[$k] = $category;
}
return $data;
}
}
|
C++
|
UTF-8
| 820 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
#ifndef GRAPHITE_VCFHEADER_H
#define GRAPHITE_VCFHEADER_H
#include "IHeader.h"
#include <memory>
#include <vector>
#include <string>
namespace graphite
{
class IAlignmentReader;
class VCFHeader : public IHeader
{
public:
typedef std::shared_ptr< VCFHeader > SharedPtr;
VCFHeader();
~VCFHeader();
void addHeaderLine(const std::string& headerLine) override;
std::string getHeader() override;
void registerReferencePath(const std::string& referencePath);
void registerSample(std::shared_ptr< Sample > samplePtr) override;
std::vector< std::shared_ptr< Sample > > getSamplePtrs() override { return m_sample_ptrs; }
private:
std::string m_reference_path;
std::vector< std::string > m_header_lines;
std::vector< std::shared_ptr< Sample > > m_sample_ptrs;
};
}
#endif //GRAPHITE_VCFHEADER_H
|
Markdown
|
UTF-8
| 992 | 3.25 | 3 |
[] |
no_license
|
# earth_venus_orbit
Simulate the orbit of Earth and Venus, plot the relative position of them.
The purpose of the project is to show the position of the Earth and the Venus, and what can it draw if we connect Earth and Venus consecutively.
# Usage
A C script, earthVSvenus.c, is used to generate the date needed for plot.
Compile the C script with a C compiler, and then run the compiled executible program. The program takes two command arguments:
1) the time(in days) gap, an integer, eg, 5 or 10;
2) the name of output file, which contains all the simulated data.
With the output file, an R script is used to visualize the data - plotPlanet.R.
The R script takes one command argument - the file name of simulated data.
Before using R to visualize the data, make sure you have installed R package - "berryFunctions".
# Examples
```bash
$ clang earthVSvenus.c -o my_program
$ ./my_program 10 data_10days.txt
# using R code for visualization
$ Rscript plotPlanet.R data_10days.txt
```
|
TypeScript
|
UTF-8
| 313 | 2.6875 | 3 |
[] |
no_license
|
import { _curry1 } from './internal/_curry'
function camelCase(str: string): string {
str = ('' + str).trim()
if (!str.length) return str
return str
.replace(/[-_]+([\S])/g, (_, char) => char.toUpperCase())
.replace(/^([A-Z])/, (_, char) => char.toLowerCase())
}
export default _curry1(camelCase)
|
PHP
|
UTF-8
| 1,346 | 2.71875 | 3 |
[] |
no_license
|
<?php
class Enums {
public function __construct(){}
static function string($e) {
$GLOBALS['%s']->push("Enums::string");
$__hx__spos = $GLOBALS['%s']->length;
$cons = Type::enumConstructor($e);
$params = (new _hx_array(array()));
{
$_g = 0;
$_g1 = Type::enumParameters($e);
while($_g < $_g1->length) {
$param = $_g1[$_g];
++$_g;
$params->push(Dynamics::string($param));
unset($param);
}
}
{
$tmp = _hx_string_or_null($cons) . _hx_string_or_null((Enums_0($cons, $e, $params)));
$GLOBALS['%s']->pop();
return $tmp;
}
$GLOBALS['%s']->pop();
}
static function compare($a, $b) {
$GLOBALS['%s']->push("Enums::compare");
$__hx__spos = $GLOBALS['%s']->length;
$v = null;
if(($v = Enums_1($a, $b, $v) - Enums_2($a, $b, $v)) !== 0) {
$GLOBALS['%s']->pop();
return $v;
}
{
$tmp = Arrays::compare(Type::enumParameters($a), Type::enumParameters($b));
$GLOBALS['%s']->pop();
return $tmp;
}
$GLOBALS['%s']->pop();
}
function __toString() { return 'Enums'; }
}
function Enums_0(&$cons, &$e, &$params) {
if($params->length === 0) {
return "";
} else {
return "(" . _hx_string_or_null($params->join(", ")) . ")";
}
}
function Enums_1(&$a, &$b, &$v) {
{
$e = $a;
return $e->index;
}
}
function Enums_2(&$a, &$b, &$v) {
{
$e1 = $b;
return $e1->index;
}
}
|
JavaScript
|
UTF-8
| 6,894 | 2.6875 | 3 |
[] |
no_license
|
var oracleUrl = "historicdata/";
function toggleColor(element, classAttribute) {
$(element).toggleClass(classAttribute);
}
function trimAndStripString(str) {
var result = str.trim();
result = result.replaceAll("%20", " ");
result = trimChar(result, ')');
result = trimChar(result, '(');
if (result.indexOf("(") > 0) {
result = result.substring(result.indexOf("(") + 1);
}
return result;
}
function trimChar(string, charToRemove) {
while (string.charAt(0) == charToRemove) {
string = string.substring(1);
}
while (string.charAt(string.length - 1) == charToRemove) {
string = string.substring(0, string.length - 1);
}
return string;
}
$(document).ready(function () {
console.log("history data page");
var queryString = window.location.search;
filterAndDrawBets(queryString);
$("#filter").click(function () {
var player1Title = $("#player1Title").val();
var player2Title = $("#player2Title").val();
var sport = $("#sportSelect").val();
console.log(player1Title + "|" + player2Title + "|" + sport + "|")
var queryString = "player1Title=" + player1Title + "&player2Title=" + player2Title + "&sport=" + sport;
console.log(queryString);
filterAndDrawBets(queryString);
});
function filterAndDrawBets(params) {
const rootElem = $("#historic");
rootElem.empty();
if (!params.startsWith("?")) {
params = "?" + params;
}
params = params.replace("%20", " ");
const players = [];
$.get(oracleUrl + params, function (data) {
var historicData = data.data;
for (var titleDateTimeKey in historicData) {
var itemString = "<div class='betInfo'><b>" + titleDateTimeKey + "</b>";
var boldTitle = "";
var player1Title = "";
var player2Title = "";
if (titleDateTimeKey.indexOf(",") >= 0) {
var titlePart = titleDateTimeKey.split(",");
var splitter = "-";
if (titlePart[0].indexOf(" - ") >= 0) {
splitter = " - ";
}
if (titlePart[0].indexOf(splitter) >= 0) {
player1Title = titlePart[0].split(splitter)[0];
if (player1Title.startsWith("(")) {
//this situation is because titleDateTikeKey looks like '(Dubyna Ihor - Maltsev Denys,2022-02-13T23:29:58.781)'
player1Title = player1Title.substring(1);
}
player2Title = titlePart[0].split(splitter)[1];
boldTitle = "<span ondblclick='toggleColor(this, \"red\")' onclick='toggleColor(this, \"green\")'>"
+ "<a href='?player1Title=" + trimAndStripString(player1Title) + "'>link</a>"
+ player1Title + "</span>" +
"-<span ondblclick='toggleColor(this, \"red\")' onclick='toggleColor(this, \"green\")'>"
+ "<a href='?player2Title=" + trimAndStripString(player2Title) + "'>link</a>"
+ player2Title + "</span>";
boldTitle += titleDateTimeKey.split(",")[1];
}
}
if (boldTitle.length > 0) {
itemString = "<div class='betInfo'><b>" + boldTitle + "</b>";
}
var lastScore = "";
for (var syncItem in historicData[titleDateTimeKey]) {
if (itemString.indexOf("|") < 0) {
//retrieve initial odds:
itemString += "<span class='bolder'>" + historicData[titleDateTimeKey][syncItem].coef1 + "," +
historicData[titleDateTimeKey][syncItem].coef2 + "</span>";
}
//here add scores
lastScore = historicData[titleDateTimeKey][syncItem].score;
itemString += "<span>" + historicData[titleDateTimeKey][syncItem].score + "| </span>";
}
itemString += "</div>";
rootElem.append(itemString);
if (!containsPlayer(players, player1Title)) {
players.push(player1Title + gameColor(lastScore, 1));
} else {
for (let i = 0; i < players.length; i++) {
if(players[i].startsWith(player1Title)){
players[i] = players[i] + gameColor(lastScore, 1);
}
}
}
if (!containsPlayer(players, player2Title)) {
players.push(player2Title + gameColor(lastScore, 2));
} else {
for (let i = 0; i < players.length; i++) {
if(players[i].startsWith(player2Title)){
players[i] = players[i] + gameColor(lastScore, 2);
}
}
}
}
drawPlayers(players);
});
}
function drawPlayers(players) {
console.log("draw players colors" + players)
var counter = 1;
$("#players").empty();
for (let player of players) {
$("#players").append("<div>" + counter + ")" + player + "</div>")
counter++;
}
}
function containsPlayer(players, title) {
for (let player of players) {
if (player.startsWith(title)) {
return true;
}
}
return false;
}
/**
* score in form '3 11 8 4 6 10 1 2'
*/
function gameColor(score, playerPosition) {
var scoreParts = score.split(" ");
scoreParts = scoreParts.map((elem)=> parseInt(elem));
var length = scoreParts.length;
if(length < 6) {
return "<b>■</b>";
}
if (scoreParts[length - 1] == "2" && scoreParts[length - 3] >= 8 &&
scoreParts[length - 3] > scoreParts[length - 4]) {
//situation where player2 WIN
if (playerPosition == 2) {
return "<b class='green-color'>■</b>";
} else {
return "<b class='red-color'>■</b>";
}
}
if (scoreParts[length - 2] == "2" && scoreParts[length - 4] >= 8 &&
scoreParts[length - 4] > scoreParts[length - 3]) {
//situation where player1 WIN
if (playerPosition == 1) {
return "<b class='green-color'>■</b>";
} else {
return "<b class='red-color'>■</b>";
}
}
return "<b>■</b>";
}
})
|
Java
|
UTF-8
| 800 | 1.84375 | 2 |
[] |
no_license
|
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.yourcompany.struts.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
public class SupprimerInvForm extends ActionForm {
private int codeInv ;
public int getCodeInv() {
return codeInv;
}
public void setCodeInv(int codeInv) {
this.codeInv = codeInv;
}
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
}
}
|
Markdown
|
UTF-8
| 1,009 | 2.71875 | 3 |
[] |
no_license
|
# Ansible-Kubernetes-Role
Just Clone the Respositroy to Set up Kubernetes Cluster in Ubuntu OS
## Installation
```bash
git clone https://github.com/Raghavendra17N/Ansible-Kubernates-Role.git
ansible-playbook k8s.yml
```
## Setting Up Inventory and k8s.yml
##### Set the Inventory with host and user
```bash
[k8s_master]
master ansible_ssh_host=[HostIP/hostname] ansible_user=[user name]
[k8s_worker]
node ansible_ssh_host=[HostIP/hostname] ansible_user=[user name]
```
##### Configure the k8s.yml with user
```bash
---
- hosts: all
remote_user: [user]
become: true
roles:
- Kubernetes
```
## Create the Group Vars in /etc/ansible/group_vars
#### Each file for each group[k8s_master and k8s_worker]
k8s_master group file
```bash
---
Kubernetes: master
```
k8s_worker group file
```bash
---
Kubernetes: node
```
## Usage
```bash
ansible-playbook k8s.yml
```
## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
|
C#
|
UTF-8
| 914 | 3.015625 | 3 |
[] |
no_license
|
using Classes.Enums;
using Classes.Vehicles;
using Entities.Enums;
using Entities.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
namespace Entities.Vehicles
{
public class Bike : BaseVehicle, IBike
{
public Bike(string model, int manufacturedYear, string color)
: base(VehicleType.Bike, FuelType.Not_Fueled, model, manufacturedYear, color, 2)
{
}
public void DoStunts()
{
Console.WriteLine("Flips.. Wheelies.. Jumps!");
}
public override void IsDriveable()
{
Console.WriteLine($"You cannot ride the {Model} on the open road! Only on bike tracks!");
}
public override void VehicleInfo()
{
Console.WriteLine($"Vehicle: {TypeOfVehicle}\nModel: {Model}\nYear: {ManufacturedYear}\nColor: {Color}");
}
}
}
|
Python
|
UTF-8
| 3,715 | 2.59375 | 3 |
[] |
no_license
|
# -*- coding:utf-8 -*-
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import mnist
import time
import os
log_dir = 'D:/learning/Python_learning/Python/\
TensorFlow/my_codes/mnist_complete/log/'
data_dir = 'D:/learning/Python_learning/Python/\
TensorFlow/my_codes/mnist_complete/MNIST_data/'
input_size = 28 * 28
label_classes = 10
def generate_placeholder(batch_size, input_size):
input_holder = tf.placeholder(
tf.float32, shape=(batch_size, input_size)
)
label_holder = tf.placeholder(
tf.int32, shape=(batch_size)
)
return input_holder, label_holder
def fill_feed_dict(
data_set, input_holder, label_holder, batch_size
):
input_feed, label_feed = data_set.next_batch(batch_size)
feed_dict = {
input_holder: input_feed,
label_holder: label_feed,
}
return feed_dict
def do_eval(
sess, eval_correct, input_holder,
label_holder, data_set, batch_size
):
true_count = 0
steps_per_epoch = data_set.num_examples // batch_size
num_examples = steps_per_epoch * batch_size
for step in range(steps_per_epoch):
feed_dict = fill_feed_dict(
data_set, input_holder, label_holder, batch_size
)
true_count += sess.run(eval_correct, feed_dict=feed_dict)
precision = float(true_count) / num_examples
print(
'Num examples: %d Num correct: %d Precision @ 1: %0.04f' %
(num_examples, true_count, precision)
)
def run_training():
data_sets = input_data.read_data_sets(data_dir)
with tf.Graph().as_default():
input_holder, label_holder = generate_placeholder(50, input_size)
logits = mnist.inference(
input_holder, input_size, 128, 32, label_classes
)
loss = mnist.loss(logits, label_holder)
train_op = mnist.training(loss, 0.01)
eval_correct = mnist.evaluation(logits, label_holder)
summary = tf.summary.merge_all()
init = tf.global_variables_initializer()
saver = tf.train.Saver()
sess = tf.Session()
summary_writer = tf.summary.FileWriter(log_dir, sess.graph)
sess.run(init)
for step in range(2000):
start_time = time.time()
feed_dict = fill_feed_dict(
data_sets.train, input_holder, label_holder, 50
)
_, loss_value = sess.run(
[train_op, loss], feed_dict=feed_dict
)
duration = time.time() - start_time
if step % 100 == 0:
print('Step %d: loss = %.2f (%.3f sec)' % (
step, loss_value, duration
))
summary_str = sess.run(summary, feed_dict=feed_dict)
summary_writer.add_summary(summary_str, step)
summary_writer.flush()
if (step + 1) % 1000 == 0 or (step + 1) == 2000:
checkpoint_file = os.path.join(log_dir, 'model.ckpt')
saver.save(sess, checkpoint_file, global_step=step)
print('Training Data Eval:')
do_eval(
sess, eval_correct, input_holder,
label_holder, data_sets.train, 50
)
print('Validation Data Eval:')
do_eval(
sess, eval_correct, input_holder,
label_holder, data_sets.validation, 50
)
print('Test Data Eval:')
do_eval(
sess, eval_correct, input_holder,
label_holder, data_sets.test, 50
)
def main():
run_training()
if __name__ == '__main__':
main()
|
JavaScript
|
UTF-8
| 940 | 2.515625 | 3 |
[] |
no_license
|
/*
The application supports for downloading a specific
network source code and then archive it into
compressed-file.
*/
const async = require('async')
const exec = require('child_process').exec
const path = require('path')
const _ = require('lodash')
const fs = require('fs')
const dataPath = path.join(__dirname, 'data')
let configFiles = {
dev: 'dev.json',
test: 'test.json',
pro: 'prod.json',
}
let configContent = {}
async.forEachOf(configFiles, (value, key, callback) => {
fs.readFile(path.join(dataPath, value), 'utf8', (err, data) => {
if(err) return callback(err)
try {
configContent[key] = JSON.parse(data)
} catch (e) {
callback(e)
}
callback()
})
}, (err) => {
if (err) {
console.error(err.message)
}
_.forIn(configContent, (value, key) => {
console.log(`${key}: ${JSON.stringify(value)}`)
} )
})
|
C++
|
UTF-8
| 664 | 2.671875 | 3 |
[] |
no_license
|
//
// EPITECH PROJECT, 2018
// gomoku
// File description:
// board
//
#pragma once
#define N 0
#define NE 1
#define E 2
#define SE 3
#define S 4
#define SO 5
#define O 6
#define NO 7
class Cell;
class Board
{
public:
Board();
~Board();
public:
bool setSize(int boardSize);
bool setCell(int x, int y, int value);
int winner() const;
int getNbPieces() const;
void reset();
void display() const;
int getCell(int x, int y) const;
int getSize() const;
private:
void createBoard();
void checkWin(int x, int y, int id);
bool isValidCoord(int x, int y) const;
void printBorder() const;
private:
int _boardSize;
int _winner;
Cell **_board;
};
|
Python
|
UTF-8
| 645 | 4.21875 | 4 |
[] |
no_license
|
def divisible_by_three(num):
return is_divisible_by(num, 3)
def divisible_by_five(num):
return is_divisible_by(num, 5)
def is_divisible_by(number, divisor):
return number % divisor == 0
def generate_fizzbuzz_string_or_number(number):
output_message = ''
if (divisible_by_three(number)):
output_message += 'fizz'
if (divisible_by_five(number)):
output_message += 'buzz'
return output_message or number
def play_fizzbuzz(range_start_point, range_end_point):
for number in range(range_start_point, range_end_point):
print(generate_fizzbuzz_string_or_number(number))
play_fizzbuzz(1,100)
|
Java
|
UTF-8
| 12,578 | 1.976563 | 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 br.edu.ifms.loja.usuario.view;
import br.edu.ifms.loja.app.components.ComboBoxUFCidade;
import java.awt.BorderLayout;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
/**
*
* @author djgiu
*/
public class UsuarioFormulario extends javax.swing.JPanel {
/**
* Creates new form UsuarioFormulario
*/
private ComboBoxUFCidade comboBoxUFCidade;
public UsuarioFormulario() {
initComponents();
comboBoxUFCidade = new ComboBoxUFCidade();
painelComboBox.setLayout(new BorderLayout());
painelComboBox.add(comboBoxUFCidade, BorderLayout.CENTER);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
campoNome = new javax.swing.JTextField();
campoCPF = new javax.swing.JTextField();
campoEmail = new javax.swing.JTextField();
campoSenha = new javax.swing.JPasswordField();
campoPapel = new javax.swing.JTextField();
campoBairro = new javax.swing.JTextField();
campoRua = new javax.swing.JTextField();
campoNumero = new javax.swing.JTextField();
campoCEP = new javax.swing.JTextField();
painelComboBox = new javax.swing.JPanel();
jLabel1.setText("Nome:");
jLabel2.setText("CPF:");
jLabel3.setText("Email:");
jLabel4.setText("Senha:");
jLabel5.setText("Papel:");
jLabel6.setText("Bairro:");
jLabel7.setText("Rua:");
jLabel8.setText("Numero:");
jLabel9.setText("CEP:");
campoSenha.setText("jPasswordField1");
javax.swing.GroupLayout painelComboBoxLayout = new javax.swing.GroupLayout(painelComboBox);
painelComboBox.setLayout(painelComboBoxLayout);
painelComboBoxLayout.setHorizontalGroup(
painelComboBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
painelComboBoxLayout.setVerticalGroup(
painelComboBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 12, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(painelComboBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(jLabel5))
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(campoPapel, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(campoCPF, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(campoSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(campoEmail)
.addComponent(campoNome, javax.swing.GroupLayout.Alignment.LEADING)))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(campoNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(campoBairro)
.addGap(26, 26, 26)
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(campoCEP, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel7)
.addGap(35, 35, 35)
.addComponent(campoRua)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(campoCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(campoSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(campoPapel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(campoEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(campoRua, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(campoNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)
.addComponent(campoBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9)
.addComponent(campoCEP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(painelComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField campoBairro;
private javax.swing.JTextField campoCEP;
private javax.swing.JTextField campoCPF;
private javax.swing.JTextField campoEmail;
private javax.swing.JTextField campoNome;
private javax.swing.JTextField campoNumero;
private javax.swing.JTextField campoPapel;
private javax.swing.JTextField campoRua;
private javax.swing.JPasswordField campoSenha;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel painelComboBox;
// End of variables declaration//GEN-END:variables
public JTextField getCampoBairro() {
return campoBairro;
}
public void setCampoBairro(JTextField campoBairro) {
this.campoBairro = campoBairro;
}
public JTextField getCampoCEP() {
return campoCEP;
}
public void setCampoCEP(JTextField campoCEP) {
this.campoCEP = campoCEP;
}
public JTextField getCampoCPF() {
return campoCPF;
}
public void setCampoCPF(JTextField campoCPF) {
this.campoCPF = campoCPF;
}
public JTextField getCampoEmail() {
return campoEmail;
}
public void setCampoEmail(JTextField campoEmail) {
this.campoEmail = campoEmail;
}
public JTextField getCampoNome() {
return campoNome;
}
public void setCampoNome(JTextField campoNome) {
this.campoNome = campoNome;
}
public JTextField getCampoNumero() {
return campoNumero;
}
public void setCampoNumero(JTextField campoNumero) {
this.campoNumero = campoNumero;
}
public JTextField getCampoPapel() {
return campoPapel;
}
public void setCampoPapel(JTextField campoPapel) {
this.campoPapel = campoPapel;
}
public JTextField getCampoRua() {
return campoRua;
}
public void setCampoRua(JTextField campoRua) {
this.campoRua = campoRua;
}
public JPasswordField getCampoSenha() {
return campoSenha;
}
public void setCampoSenha(JPasswordField campoSenha) {
this.campoSenha = campoSenha;
}
public ComboBoxUFCidade getComboBoxUFCidade() {
return comboBoxUFCidade;
}
public void setComboBoxUFCidade(ComboBoxUFCidade comboBoxUFCidade) {
this.comboBoxUFCidade = comboBoxUFCidade;
}
}
|
C++
|
UTF-8
| 11,927 | 2.84375 | 3 |
[] |
no_license
|
#ifndef BUTTON_H_INCLUDED
#define BUTTON_H_INCLUDED
#include <stdio.h>
#include <string>
#include "SDLincludes.h"
#include "easyShapes.h"
class button
{
private:
SDL_Texture *buttonTexture;
SDL_Texture *textTexture;
SDL_Renderer *rendererCopy;
TTF_Font *font;
shape buttonBox;
public:
button();
button(SDL_Texture *buttonTextureIn);
button(SDL_Renderer *rendererIn);
button(SDL_Renderer *rendererIn, string tempText);
button(SDL_Renderer *rendererIn, string tempText,int xIn, int yIn,int wIn,int hIn);
void setRenderer(SDL_Renderer *rendererIn);
void setWidth(int wIn);
void setHeight(int hIn);
void setX(int xIn);
void setY(int yIn);
void setPos(int xIn, int yIn);
void setText(string textIn);
bool setFont(string fontChoice);
void setTextColor(Uint8 rIn, Uint8 gIn, Uint8 bIn);
void setButtonColor(Uint8 rIn, Uint8 gIn, Uint8 bIn);
void setFontSize(int size);
void setButtonTexture(SDL_Texture *buttonTextureIn);
bool isClicked(int x, int y);
bool draw();
bool draw(SDL_Renderer *rendererIn);
string text;
SDL_Color textColor;
SDL_Rect textBox;
};
//Defualt constructor. button is at (0,0) with calibri font by default
//Unable to draw without a renderer passed in at draw time or before hand
//default text is "button"
button::button()
{
if(!TTF_WasInit())
{
if(TTF_Init() < 0)
{
printf("TTF_Init() failed: %s\n", TTF_GetError());
}
}
buttonTexture = NULL;
font = TTF_OpenFont( "../resources/fonts/calibri.ttf", 500);
if(font == NULL)
printf("font not found!!\n");
text = "button";
textBox = {0, 0, 5, 5};
textColor = {0, 0, 0};
buttonBox.setColor(255, 0, 0);
rendererCopy = NULL;
}
//Initialize button with a texture for pretty buttons
//with pictures instead of text
button::button(SDL_Texture *buttonTextureIn)
{
if(!TTF_WasInit())
{
if(TTF_Init() < 0)
{
printf("TTF_Init() failed: %s\n", TTF_GetError());
}
}
buttonTexture = buttonTextureIn;
font = TTF_OpenFont( "../resources/fonts/calibri.ttf", 500);
if(font == NULL)
printf("font not found!!\n");
text = "button";
textBox = { 0, 0, 5, 5};
textColor = { 0, 0, 0 };
buttonBox.setColor(255, 0, 0);
rendererCopy = NULL;
}
//Initialize button with renderer so that draw can be called
button::button(SDL_Renderer *rendererIn)
{
if(!TTF_WasInit())
{
if(TTF_Init() < 0)
{
printf("TTF_Init() failed: %s\n", TTF_GetError());
}
}
buttonTexture = NULL;
font = TTF_OpenFont( "../resources/fonts/calibri.ttf", 500);
if(font == NULL)
printf("font not found!!\n");
text = "button";
textBox = { 0, 0, 5, 5};
textColor = { 0, 0, 0 };
buttonBox.setColor(255, 0, 0);
rendererCopy = rendererIn;
SDL_Surface* textSurface = TTF_RenderText_Solid(font, text.c_str(), textColor);
if(textSurface == NULL )
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
textTexture = SDL_CreateTextureFromSurface(rendererCopy, textSurface );
if(textTexture == NULL )
{
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
}
SDL_SetTextureColorMod(textTexture, textColor.r, textColor.g, textColor.b);
SDL_FreeSurface(textSurface);
}
//Initialize button with renderer and text to display
button::button(SDL_Renderer *rendererIn, string tempText)
{
if(!TTF_WasInit())
{
if(TTF_Init() < 0)
{
printf("TTF_Init() failed: %s\n", TTF_GetError());
}
}
buttonTexture = NULL;
font = TTF_OpenFont( "../resources/fonts/calibri.ttf", 500);
if(font == NULL)
printf("font not found!!\n");
text = tempText;
textBox = { 0, 0, 5, 5};
buttonBox.setColor(255, 0, 0);
rendererCopy = rendererIn;
SDL_Surface* textSurface = TTF_RenderText_Solid(font, text.c_str(), textColor);
if(textSurface == NULL )
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
textTexture = SDL_CreateTextureFromSurface(rendererCopy, textSurface );
if(textTexture == NULL )
{
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
}
SDL_SetTextureColorMod(textTexture, textColor.r, textColor.g, textColor.b);
SDL_FreeSurface(textSurface);
}
//Initialize button with renderer, text to display, position, and demisions
button::button(SDL_Renderer *rendererIn, string tempText,int xIn, int yIn,int wIn,int hIn)
{
if(!TTF_WasInit())
{
if(TTF_Init() < 0)
{
printf("TTF_Init() failed: %s\n", TTF_GetError());
}
}
buttonTexture = NULL;
font = TTF_OpenFont( "../resources/fonts/calibri.ttf", 500);
if(font == NULL)
printf("font not found!!\n");
text = tempText;
textBox = { xIn, yIn, wIn, hIn};
buttonBox.box.x = xIn;
buttonBox.box.y = yIn;
buttonBox.box.w = wIn;
buttonBox.box.h = hIn;
textColor = {0, 0, 0};
buttonBox.setColor(255, 0, 0);
rendererCopy = rendererIn;
SDL_Surface* textSurface = TTF_RenderText_Solid(font, text.c_str(), textColor);
if(textSurface == NULL )
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
SDL_DestroyTexture(textTexture);
textTexture = SDL_CreateTextureFromSurface(rendererCopy, textSurface );
if(textTexture == NULL )
{
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
}
SDL_SetTextureColorMod(textTexture, textColor.r, textColor.g, textColor.b);
SDL_FreeSurface(textSurface);
}
//Function to set renderer for button after being declared
void button::setRenderer(SDL_Renderer *rendererIn)
{
rendererCopy = rendererIn;
buttonBox.setRenderer(rendererCopy);
SDL_Surface* textSurface = TTF_RenderText_Solid(font, text.c_str(), textColor);
if(textSurface == NULL )
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
textTexture = SDL_CreateTextureFromSurface(rendererCopy, textSurface );
if(textTexture == NULL )
{
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
}
SDL_SetTextureColorMod(textTexture, textColor.r, textColor.g, textColor.b);
SDL_FreeSurface(textSurface);
}
//Set width of button, pretty simple
void button::setWidth(int wIn)
{
textBox.w = wIn;
buttonBox.box.w = wIn;
}
//Set height of button, pretty simple
void button::setHeight(int hIn)
{
textBox.h = hIn;
buttonBox.box.h = hIn;
}
//Set x position of button
void button::setX(int xIn)
{
textBox.x = xIn;
buttonBox.box.x = xIn;
}
//Set y position of button
void button::setY(int yIn)
{
textBox.y = yIn;
buttonBox.box.y = yIn;
}
//Set the position of the button in terms of x and y
void button::setPos(int xIn, int yIn)
{
textBox.x = xIn;
buttonBox.box.x = xIn;
textBox.y = yIn;
buttonBox.box.y = yIn;
}
//Set the text for the button to display
void button::setText(string textIn)
{
text = textIn;
if(rendererCopy == NULL)
return;
SDL_Surface* textSurface = TTF_RenderText_Solid(font, text.c_str(), textColor);
if(textSurface == NULL )
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
textTexture = SDL_CreateTextureFromSurface(rendererCopy, textSurface );
if(textTexture == NULL )
{
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
}
SDL_SetTextureColorMod(textTexture, textColor.r, textColor.g, textColor.b);
SDL_FreeSurface(textSurface);
}
//Sets the font the button will use, sets to default font "calibri"
//if it fails and returns false
bool button::setFont(string fontChoice)
{
fontChoice = "../resources/fonts/" + fontChoice + ".ttf";
font = TTF_OpenFont(fontChoice.c_str() , 500);
if(font == NULL)
{
printf("font not found, using default font!!\n");
font = TTF_OpenFont( "../resources/fonts/calibri.ttf", 500);
if(font == NULL)
printf("default font not found!!\n");
return false;
}
if(rendererCopy == NULL)
return true;
SDL_Surface* textSurface = TTF_RenderText_Solid(font, text.c_str(), textColor);
if(textSurface == NULL )
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
textTexture = SDL_CreateTextureFromSurface(rendererCopy, textSurface );
if(textTexture == NULL )
{
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
}
SDL_SetTextureColorMod(textTexture, textColor.r, textColor.g, textColor.b);
SDL_FreeSurface(textSurface);
return true;
}
//sets the RBG based color for the text of the button
void button::setTextColor(Uint8 rIn, Uint8 gIn, Uint8 bIn)
{
textColor = {rIn, gIn, bIn};
if(rendererCopy == NULL)
return;
SDL_Surface* textSurface = TTF_RenderText_Solid(font, text.c_str(), textColor);
if(textSurface == NULL )
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
textTexture = SDL_CreateTextureFromSurface(rendererCopy, textSurface );
if(textTexture == NULL )
{
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
}
SDL_SetTextureColorMod(textTexture, textColor.r, textColor.g, textColor.b);
SDL_FreeSurface(textSurface);
}
//Sets the color for the button itself
void button::setButtonColor(Uint8 rIn, Uint8 gIn, Uint8 bIn)
{
buttonBox.setColor(rIn, gIn, bIn);
}
//Sets the size of the font used. large numbers suggested
void button::setFontSize(int size)
{
font = TTF_OpenFont( "../resources/fonts/calibri.ttf", size);
if(rendererCopy == NULL)
return;
SDL_Surface* textSurface = TTF_RenderText_Solid(font, text.c_str(), textColor);
if(textSurface == NULL )
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
textTexture = SDL_CreateTextureFromSurface(rendererCopy, textSurface );
if(textTexture == NULL )
{
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
}
SDL_SetTextureColorMod(textTexture, textColor.r, textColor.g, textColor.b);
SDL_FreeSurface(textSurface);
}
//Returns true if x and y passed in are within the button
bool button::isClicked(int x, int y)
{
if(x > textBox.x && x < (textBox.x + textBox.w))
if(y > textBox.y && y < (textBox.y + textBox.h))
return true;
return false;
}
//Sets the buttons texture. Using this will take the place of
//The text and colored box
void button::setButtonTexture(SDL_Texture *buttonTextureIn)
{
buttonTexture = buttonTextureIn;
}
//function to draw button if renderer has been assigned to
//the button. If no renderer was set, function returns false
bool button::draw()
{
if(rendererCopy == NULL)
return false;
if(buttonTexture == NULL)
{
buttonBox.drawSquare();
SDL_RenderCopyEx(rendererCopy, textTexture, NULL, &textBox, 0.0, NULL, SDL_FLIP_NONE);
return true;
}
else
{
SDL_RenderCopyEx(rendererCopy, buttonTexture, NULL, &textBox, 0.0, NULL, SDL_FLIP_NONE);
return true;
}
}
//Function to draw button onto any renderer passed in.
bool button::draw(SDL_Renderer *rendererIn)
{
if(buttonTexture == NULL)
{
buttonBox.drawSquare(rendererIn);
SDL_RenderCopyEx(rendererIn, textTexture, NULL, &textBox, 0.0, NULL, SDL_FLIP_NONE);
return true;
}
else
{
SDL_RenderCopyEx(rendererIn, buttonTexture, NULL, &textBox, 0.0, NULL, SDL_FLIP_NONE);
return true;
}
}
#endif
|
Java
|
UTF-8
| 2,071 | 1.828125 | 2 |
[] |
no_license
|
package com.mmall.service;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.mmall.dto.SysMenuDto;
import com.mmall.dto.SysUserInfoDto;
import com.mmall.model.Response.Result;
import com.mmall.model.*;
import com.mmall.model.params.UserInfoExpressParm;
import com.mmall.model.params.UserInfoServiceParm;
import com.mmall.model.params.UserPasswordParam;
import java.util.List;
import java.util.Map;
/**
* <p>
* 服务类
* </p>
*
* @author hyc
* @since 2018-09-15
*/
public interface SysUserService extends IService<SysUser> {
/**
* 获取菜单
* @param user
* @param platId
* @return
*/
Result<List<SysMenuDto>> findAllMenuByUser(SysUserInfo user,Integer platId);
/**
* 登录
* @param username
* @param password
* @return
*/
Result<AuthInfo<SysUserInfo>> login(String username, String password);
/**
* fn注册
* @return
*/
Result fnRegister(UserInfoExpressParm user,SysUserInfo parent,Integer fnId);
/**
* 获取快递公司列表
* @param user
* @return
*/
Result getCompanys(SysUserInfo user,Page ipage);
/**
* 冻结
* @param id
* @return
*/
Result frozen(Integer id);
/**
* 删除
* @param id
* @return
*/
Result deleteUser(Integer id);
/**
* 修改信息
* @param user
* @return
*/
Result updateExpress(UserInfoServiceParm user);
/**
* 获取自己的个人信息
* @param user
* @return
*/
Result<Map<String,Object>> getUserInfo(SysUserInfo user);
/**
*获取验证码
* @param phone
* @return
*/
Result getCode(String phone) throws ClientException;
/**
* 验证码修改密码
* @param user
* @param code
* @return
*/
Result updateUserPassword(SysUserInfo user, String code, UserPasswordParam userPasswordParam);
}
|
C#
|
UTF-8
| 5,602 | 3.171875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 도서_관리_닷넷프레임 {
public partial class Form2 : Form {
Form1 form1;
public Form2() {
InitializeComponent();
}
public Form2(Form1 _form1) {
InitializeComponent();
form1 = _form1;
Text = "도서 관리";
dataGridView1.DataSource = DataManager.Books;
/* 속성을 통해 코드 삽입하는 방법 외에 이미 디자이너에 생성되어있는 함수에 접근하는 방식
dataGridView1.CurrentCellChanged += DataGridView1_CurrentCellChanged; */
button1.Click += ( sender, e ) => { /* 추가 */
if ( textBox1.Text.Trim() == "" ) {
MessageBox.Show("추가하려는 책의 Isbn을 입력해주세요.");
}
else {
try {
// textBox1.Text가 Books에 있으면 이미 존재
if ( DataManager.Books.Exists(x => x.Isbn == textBox1.Text) ) {
MessageBox.Show("이미 존재하는 도서입니다");
}
else {
// 새 책의 정보를 객체에 저장
Book book = new Book() {
Isbn = textBox1.Text,
Name = textBox2.Text,
Publisher = textBox3.Text,
Page = int.Parse(textBox4.Text)
};
// 새 책의 정보가 담긴 객체를 리스트에 추가
DataManager.Books.Add(book);
// 새로 고침
dataGridView1.DataSource = null;
dataGridView1.DataSource = DataManager.Books;
// 파일에 저장
DataManager.Save();
form1.ViewRefresh(1);
MessageBox.Show("새 책\n" +
"ISBN : \"" + book.Isbn + "\"\n"
+ "도서 이름 : \"" + book.Name + "\"을/를 추가했습니다.");
}
}
catch (Exception err) { /* Exists의 ArgumentNullException 처리를 위한 구문 */ }
}
};
button2.Click += ( sender, e ) => { /* 수정 */
if ( textBox1.Text.Trim() == "" ) {
MessageBox.Show("수정하려는 책의 Isbn을 입력해주세요.");
}
else {
try {
Book book = DataManager.Books.Single(x => x.Isbn == textBox1.Text);
book.Name = textBox2.Text;
book.Publisher = textBox3.Text;
book.Page = int.Parse(textBox4.Text);
dataGridView1.DataSource = null;
dataGridView1.DataSource = DataManager.Books;
DataManager.Save();
form1.ViewRefresh(1);
MessageBox.Show("\"" + book.Isbn + "\"의 정보를 수정했습니다.");
}
catch ( Exception err ) {
MessageBox.Show("존재하지 않는 도서입니다.");
}
}
};
}
/*private void DataGridView1_CurrentCellChanged( object sender, EventArgs e ) {
try {
Book book = dataGridView1.CurrentRow.DataBoundItem as Book;
textBox1.Text = book.Isbn;
}
catch (Exception err) {}
}*/
private void dataGridView1_CurrentCellChanged( object sender, EventArgs e ) {
try {
Book book = dataGridView1.CurrentRow.DataBoundItem as Book;
textBox1.Text = book.Isbn;
textBox2.Text = book.Name;
textBox3.Text = book.Publisher;
textBox4.Text = book.Page.ToString();
}
catch ( Exception error ) { }
}
private void button3_Click( object sender, EventArgs e ) { /* 삭제 */
if(textBox1.Text.Trim() == "" ) {
MessageBox.Show("삭제하려는 책의 Isbn을 입력해주세요.");
}
else {
try {
// Books에서 textBox1에 해당되는 Book 검색 후 삭제
Book book = DataManager.Books.Single(x => x.Isbn == textBox1.Text);
DataManager.Books.Remove(book);
// 새로고침
dataGridView1.DataSource = null;
dataGridView1.DataSource = DataManager.Books;
// 파일에 저장
DataManager.Save();
form1.ViewRefresh(1);
MessageBox.Show("ISBN : \"" + book.Isbn + "\"\n"
+ "도서 이름 : \"" + book.Name + "\"을/를 삭제했습니다.");
}
catch (Exception err) {
MessageBox.Show("존재하지 않는 책입니다.");
}
}
}
}
}
|
Java
|
UTF-8
| 929 | 3.21875 | 3 |
[] |
no_license
|
package zadanie.pkg1.pkg2;
import java.util.Scanner;
import static java.lang.Math.*;
public class Zadanie12 {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Wpisz tutaj rozmiar swojej tablicy");
int Rozmiar = scanner.nextInt();
double[] tab1 = new double[Rozmiar];
for (int L = 0; L < Rozmiar; L++)
{
System.out.println("Tutaj wpisz liczbe "+L+" ");
tab1[L] = scanner.nextInt();
}
for (double T : tab1)
{
{
System.out.println(T);
}
} System.out.println("Wypisane liczby koniec");
}
}
|
Java
|
UTF-8
| 6,502 | 4.03125 | 4 |
[] |
no_license
|
package proj5mazesolver;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* MazeSolver Class:
* A MazeSolver object prompts for a width and height of a character maze and
* then for all characters in said maze, separated by whitespace.
* Prints out every solution to the maze, with the path taken denoted by p's.
* Solves character mazes
* with one exit and one starting position, denoted by 'e' and 'b'
* respectively, and paths denoted by 0's. (Mazes that do not conform to
* these standards have no guarantee of being properly solved.)
*
* EXAMPLE MAZE: 5 X 5
* 1 1 1 1 1
* b 0 1 0 1
* 1 0 1 0 e
* 0 0 0 0 1
* 1 1 1 1 1
* @author Laura Josuweit
*/
public class MazeSolver
{
private int cols;
private int rows;
private char[][] maze;
//starting position co-ordinates
private int bRow;
private int bCol;
/**
* CONSTRUCTOR
* Will ask user to enter two integers for the size of the maze,
* then prompt them to enter each character of the maze separated by
* whitespace. Fills the maze attribute with the maze characters provided,
* and finds the starting position, setting bRow and bCol to the co-ords
* of the 'b' in the maze.
* If dimensions are not entered properly, defaults to 5x5 maze.
*/
public MazeSolver()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the height and width of your maze, "
+ "as integers, separated by whitespace:");
try
{
this.rows = scan.nextInt();
this.cols = scan.nextInt();
}
catch(InputMismatchException ex)
{
System.out.println("Error: maze width and height not properly "
+ "entered. Inititalizing maze as 5x5.");
scan.nextLine();//clears out the bad input
this.rows = 5;
this.cols = 5;
}
this.maze = new char[rows][cols];
//prompt for maze
System.out.println("Enter a character for each section of the maze,"
+ " separated by a whitespace character:");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{//if the user does not put white space between their character
//entries, it will only take the first character as input.
//In other words, when the user gives you a string instead
//of a character, we only use the first character in that
//string as our input.
String c = scan.next();
maze[i][j] = c.charAt(0);
}
}
//find our starting position
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if(maze[i][j] == 'b')
{
bRow = i;
bCol = j;
}
}
}
}
/**
* Prints the maze.
*/
public void printMaze()
{
System.out.println("");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
System.out.print(maze[i][j]+" ");
System.out.println("");
}
}
/**
* Starts solving the maze;
* Simply calls the recursive solveFromPosition function below with the
* co-ords of the maze's beginning.
* (Also replaces the 'b' where we started, since it might be taken over
* by path in the recursive solveFromPosition method.)
*
* This way, the user can ask for the maze to be solved without needing
* to know where to start.
*/
public void solve()
{
solveFromPosition(bRow, bCol);
maze[bRow][bCol] = 'b';
}
/**
* Recursive method with bactracking that finds and prints out each
* path that leads to the end of the maze. Sets a P where it has walked.
* Might overwrite the b marking the path beginning; b is replaced in
* the solve() method that calls this one, just in case.
* (Never overrides the 'e' of the maze's exit.)
* @param row row co-ordinate of our current maze position.
* @param col column co-ordinate of our current maze position.
*/
private void solveFromPosition(int row, int col)
{
//check maze bounds to make sure we don't try to go in a direction
//outside the bounds of the maze array
boolean canGoUp = false;
boolean canGoDown = false;
boolean canGoLeft = false;
boolean canGoRight = false;
if(row != rows - 1)
canGoDown = true;
if(row != 0)
canGoUp = true;
if(col != cols - 1)
canGoRight = true;
if(col != 0)
canGoLeft = true;
//base case: check if we are adjacent to the exit.
if((canGoUp && maze[row - 1][col] == 'e') ||
(canGoDown && maze[row + 1][col] == 'e') ||
(canGoLeft && maze[row][col - 1] == 'e') ||
(canGoRight && maze[row][col + 1] == 'e'))
{
//we found our way out wooooo
maze[row][col] = 'P';
//replace 'b' of path start that got overridden by path.
maze[bRow][bCol] = 'b';
printMaze();
maze[row][col] = '0';
}
else
{
if(canGoUp && maze[row - 1][col] == '0')
{//p for path
maze[row][col] = 'P';
solveFromPosition(row - 1, col);
maze[row][col] = '0';
}
if(canGoDown && maze[row + 1][col] == '0')
{
maze[row][col] = 'P';
solveFromPosition(row + 1, col);
maze[row][col] = '0';
}
if(canGoLeft && maze[row][col - 1] == '0')
{
maze[row][col] = 'P';
solveFromPosition(row, col - 1);
maze[row][col] = '0';
}
if(canGoRight && maze[row][col + 1] == '0')
{
maze[row][col] = 'P';
solveFromPosition(row, col + 1);
maze[row][col] = '0';
}
}
}
}
|
Python
|
UTF-8
| 679 | 3.09375 | 3 |
[] |
no_license
|
import os
import re
def main():
file = open("input", "r")
array = [[0 for y in range(1000)] for x in range(1000)]
elfs = [True for x in range(1412)]
for line in file:
elf_id, fromx, fromy, tox, toy = [
int(x) for x in re.findall("[0-9]+", line)]
for x in range(fromx, fromx+tox):
for y in range(fromy, fromy+toy):
if array[x][y] == 0:
array[x][y] = elf_id
else:
elfs[elf_id] = False
elfs[array[x][y]] = False
file.close()
for x in range(1, 1412):
if elfs[x]:
print(x)
return
main()
|
Python
|
UTF-8
| 1,108 | 2.953125 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# from http://www.lucainvernizzi.net/blog/2015/02/12/extracting-urls-from-network-traffic-in-just-9-python-lines-with-scapy-http/
# requires https://github.com/invernizzi/scapy-http
from scapy.all import IP, sniff
from scapy.layers import http
from pprint import pprint
def process_intercept(origin, dsthost, dstpath, dstmethod):
print "*"*69
print '\n{0} just requested a {1} {2}{3}'.format(origin, dstmethod, dsthost, dstpath)
def process_tcp_packet(packet):
'''
Processes a TCP packet, and if it contains an HTTP request, it prints it.
'''
if not packet.haslayer(http.HTTPRequest):
# This packet doesn't contain an HTTP request so we skip it
return
http_layer = packet.getlayer(http.HTTPRequest)
ip_layer = packet.getlayer(IP)
#print "*"*69
#pprint(ip_layer.fields)
#pprint(http_layer.fields)
process_intercept(ip_layer.fields['src'], http_layer.fields['Host'], http_layer.fields['Path'], http_layer.fields['Method'])
# Start sniffing the network.
sniff(iface='wlan0', filter='tcp port 80', prn=process_tcp_packet)
|
Java
|
UTF-8
| 8,081 | 2.078125 | 2 |
[] |
no_license
|
package com.alarmnotification.mobimon;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.util.HashMap;
import Object.GlobalContants;
import Object.Equipment;
import Object.DBHelper;
import Object.ShareScreenshot;
public class HomeActivity extends AppCompatActivity implements View.OnClickListener, DialogInterface.OnClickListener {
private ImageButton[] navs;
private ProgressBar hpBar;
private HashMap<Integer, ImageView> petParts;
private Handler hpTick;
private Runnable hpDrop;
private int curHp;
private PendingIntent alarmIntent;
private boolean alarmState;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
alarmState = GlobalContants.SET_ALARM_ENABLED;
int[] navIds = new int[] { R.id.petNav, R.id.bagNav, R.id.feedingNav, R.id.fightNav, R.id.shareNav};
this.navs = new ImageButton[navIds.length];
for (int i = 0, len = navIds.length; i < len; i++) {
this.navs[i] = (ImageButton)this.findViewById(navIds[i]);
this.navs[i].setOnClickListener(this);
}
this.hpBar = (ProgressBar)findViewById(R.id.hpBar_home);
int[] petPartIds = this.getPetPartIds();
this.petParts = new HashMap<>();
for (int i = 0, len = petPartIds.length; i < len; i++) {
this.petParts.put(petPartIds[i], (ImageView)this.findViewById(petPartIds[i]));
}
//setImageViewSet();
hpTick = new Handler();
hpDrop = new Runnable() {
@Override
public void run() {
if (--curHp <= 0) {
resetGame();
} else {
hpTick.postDelayed(this, GlobalContants.HP_DROP_INTERVAL);
hpBar.setProgress(curHp);
}
}
};
Context context = getApplicationContext();
Intent intent = new Intent(context, HungerReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, GlobalContants.HUNGER_ALARM, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private int[] getPetPartIds() {
return new int[] { R.id.head_home, R.id.body_home, R.id.foot_home, R.id.wing_home };
}
private void calculateFromLastTime() {
SharedPreferences data = getSharedPreferences(GlobalContants.USER_PREF, MODE_PRIVATE);
long cur = System.currentTimeMillis();
long startTime = data.getLong(GlobalContants.START_TIME, 0);
curHp = data.getInt(GlobalContants.CUR_HP, 100);
curHp -= (cur - startTime) / GlobalContants.HP_DROP_INTERVAL - (data.getLong(GlobalContants.LAST_ACTIVE, 0) - startTime) / GlobalContants.HP_DROP_INTERVAL;
if (curHp <= 0) {
resetGame();
} else {
long timeLeft = GlobalContants.HP_DROP_INTERVAL - (cur - startTime) % GlobalContants.HP_DROP_INTERVAL;
hpBar.setProgress(curHp);
hpTick.postDelayed(hpDrop, timeLeft);
}
}
private void resetGame() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Xin lỗi!")
.setMessage("Thú cưng của bạn đã chết đói. Bạn sẽ quay trở về khởi điểm, tất cả vật phẩm đã mất. Bạn sẽ nuôi một thú cưng mới, đừng để thú của bạn chết đói lần nữa!")
.setPositiveButton("Tôi đã hiểu", this)
.setCancelable(false);
AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
private void setImageViewSet() {
Context context = getApplicationContext();
int[] petPartIds = getPetPartIds();
DBHelper dbHelper = new DBHelper(context);
Equipment[] temp = new Equipment[] { dbHelper.getCurrentHead(), dbHelper.getCurrentBody(), dbHelper.getCurrentFoot(), dbHelper.getCurrentWing() };
for (int i = 0, len = petPartIds.length; i < len; i++) {
temp[i].addLargeImageToImageView(petParts.get(petPartIds[i]), context);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.petNav:
this.goToActivity(PetActivity.class);
break;
case R.id.bagNav:
goToActivity(BagActivity.class);
break;
case R.id.feedingNav:
this.goToActivity(FeedingActivity.class);
break;
case R.id.fightNav:
break;
case R.id.shareNav:
new ShareScreenshot(this, R.id.home_wrapper).shareImage();
break;
}
}
private void goToActivity(Class<? extends Activity> clazz) {
Intent intent = new Intent(this.getApplicationContext(), clazz);
setAlarm();
startActivity(intent);
}
@Override
protected void onResume() {
super.onResume();
setImageViewSet();
calculateFromLastTime();
AlarmManager alarmMgr = (AlarmManager)getApplicationContext().getSystemService(ALARM_SERVICE);
if (alarmMgr!= null) {
alarmMgr.cancel(alarmIntent);
alarmState = GlobalContants.SET_ALARM_DISABLED;
}
}
@Override
protected void onStop() {
super.onStop();
setAlarm();
}
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences data = getSharedPreferences(GlobalContants.USER_PREF, MODE_PRIVATE);
data.edit()
.putLong(GlobalContants.START_TIME, System.currentTimeMillis())
.putInt(GlobalContants.MONEY, 200)
.commit();
try {
new DBHelper(getApplicationContext()).copyDataBase();
} catch (Exception ex) {
throw new RuntimeException();
}
curHp = 100;
hpBar.setProgress(curHp);
hpTick.postDelayed(hpDrop, GlobalContants.HP_DROP_INTERVAL);
setImageViewSet();
}
private void setAlarm() {
if (alarmState == GlobalContants.SET_ALARM_DISABLED) {
hpTick.removeCallbacks(hpDrop);
long cur = System.currentTimeMillis();
int healthState = GlobalContants.FULL_HEALTH;
SharedPreferences data = getSharedPreferences(GlobalContants.USER_PREF, MODE_PRIVATE);
long timeLeft = GlobalContants.HP_DROP_INTERVAL - (cur - data.getLong(GlobalContants.START_TIME, 0)) % GlobalContants.HP_DROP_INTERVAL;
if (curHp > 50) {
timeLeft += (curHp - 51) * GlobalContants.HP_DROP_INTERVAL;
} else if (curHp > 20){
timeLeft += (curHp - 21) * GlobalContants.HP_DROP_INTERVAL;
healthState = GlobalContants.HALF_HEALTH;
} else {
timeLeft += (curHp - 1) * GlobalContants.HP_DROP_INTERVAL;
healthState = GlobalContants.NO_HEALTH;
}
data.edit()
.putLong(GlobalContants.LAST_ACTIVE, cur)
.putInt(GlobalContants.CUR_HP, curHp)
.putInt(GlobalContants.HEALTH_STATE, healthState)
.commit();
((AlarmManager)getApplicationContext().getSystemService(ALARM_SERVICE)).set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + timeLeft, alarmIntent);
alarmState = GlobalContants.SET_ALARM_ENABLED;
}
}
}
|
Java
|
UTF-8
| 626 | 2.171875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.danny.blog.dao;
import com.danny.blog.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
int deleteByPrimaryKey(String userId);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(String userId);
/**
* 根据ID更新用户信息
* @param record
* @return
*/
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
/**
* 根据用户名查询用户信息
* @param userName
* @return
*/
User selectByUserName(String userName);
}
|
Markdown
|
UTF-8
| 7,204 | 2.6875 | 3 |
[] |
no_license
|
********
**Council Bill Number: 112419**
********
AN ORDINANCE relating to the organization of the legislative branch of City government; creating within the legislative branch a new department titled the Office of the City Auditor and removing the Office of the City Auditor from the Legislative Department; creating a new position titled Executive Manager - City Auditor and creating a new salary band; and amending Section 3.40.010 of the Seattle Municipal Code.
**Status:** Retired 2000
**Date introduced/referred to committee:** October 12, 1998
**Committee:** Budget
**Sponsor:** CHOE
**Index Terms:** LEGISLATIVE-DEPARTMENT, AUDITOR, GOVERNMENTAL-REORGANIZATION
**Fiscal Note:**_(No fiscal note available at this time)_
********
**Text**
```
AN ORDINANCE relating to the organization of the legislative branch of City government; creating within the legislative branch a new department titled the Office of the City Auditor and removing the Office of the City Auditor from the Legislative Department; creating a new position titled Executive Manager - City Auditor and creating a new salary band; and amending Section 3.40.010 of the Seattle Municipal Code.
WHEREAS, Article III, Section 1 of the City Charter provides that the Legislative Authority may create, consolidate, and reorganize departments, divisions, and offices of City government; and
WHEREAS, the Legislative Authority of the City has determined that it is in the best interests of the City that the Office of the City Auditor become a separate Department within the Legislative Branch; NOW, THEREFORE,
BE IT ORDAINED BY THE CITY OF SEATTLE AS FOLLOWS:
Section Department Created. Effective January 1, 1999, Subsection 3.40.010(A) of the Seattle Municipal Code is amended as follows:
3.40.010. City Auditor -- Duties -- Appointment
A. There is ~~established~~createdwithin the ~~L~~legislative branch of city government a ~~D~~department, ~~an~~to be called the~~o~~Office of the City Auditor, to perform the duties provided in Article VIII, Section 2 of the City Charter. The City Auditor shall have a term of six (6) years, and shall be appointed by the Chair of the Finance Committee, subject to confirmation by a majority of the City Council, and may be removed for cause by a majority of the City Council.
Section Office abolished - Functions, duties, personnel, and assets transferred. Effective January 1, 1999, the Office of the City Auditor within the Legislative Department is abolished. The Office of the City Auditor created as a department within the legislative branch by this ordinance shall succeed to the functions and duties of the office of the City Auditor within the Legislative Department under Article VIII, Section 2 of the City Charter, Chapter 3.40 of the Seattle Municipal Code, and under any other chapters or ordinances related to audits conducted by the City Auditor. Any position designated in the 1999 Position List adopted by Ordinance ______________ (C.B. 112354) that has an equivalent position in the 1998 Position List adopted by Ordinance #118819 shall be filled on January 1, 1999 by the person working in that position on December 31, 1998. All assets of the Office of the City Auditor while it was part of the Legislative Department are transferred to the new department. All references elsewhere to the Office of the City Auditor, shall, from and after January 1, 1999, be deemed to refer to the department created by this ordinance, except that historical references to the Office of the City Auditor in the Legislative Department, as evidenced by their context, shall remain unchanged.
Section Exempt Position Created.
A. Effective January 1, 1999, there is created a new position, exempt under Article XVI, Section 3 of the Seattle City Charter, titled Executive Manager - City Auditor, to be head of the department created by this ordinance. The position of Executive Manager - Legislative (Position 024220) is abrogated as of January 1, 1999.
B. Effective January 1, 1999, a new salary band is established for Executive Manager - City Auditor, with a minimum rate of Fifty-Six Thousand Eight Hundred Twenty Seven Dollars ($56,827) and a maximum rate of One Hundred Thirty-Four Thousand Nine Hundred Seventy Dollars ($134,970). The appointing authority shall have the discretion to pay incumbents in this position a base salary anywhere within the band, in accordance with placement criteria approved by the appointing authority. The appointing authority shall adjust the salary band at least biennially based on an assessment of the labor market(s) in which the Office of City Auditor competes for employees. The appointing authority has the discretion to adjust the base salary by a percentage change equivilent to the biennial market adjutsment.
C. The Executive Manager - City Auditor is not eligible for performance pay.
MISCELLANEOUS PROVISIONS
Section It is the express intent of the City Council that, in the event a subsequent ordinance refers to a position or office that was abolished by this ordinance, that reference shall be deemed to be to the new office or position created by this ordinance, and shall not be construed to resurrect the old position or office unless it expressly so provides by reference to this ordinance.
Section It is the express intent of the City Council that, in the event a subsequent ordinance refers to or amends a section or subsection of the Seattle Municipal Code amended or recodified herein, but the later ordinance fails to account for the change made by this ordinance, the two sets of amendments should be given effect together if at all possible.
Section The President of the City Council shall have the power to make all administrative decisions necessary to carry out the intent of this ordinance.
Section The several provisions of this ordinance are declared to be separate and severable and the invalidity of any clause, sentence paragraph, subdivision, section, or portion of this ordinance, or the invalidity of the application thereof to any person or circumstance, shall not affect the validity of the remainder of this ordinance of the validity of its application to other persons or circumstances.
Section Any act consistent with the authority and prior to the effective date of this ordinance is hereby ratified and confirmed.
Section This ordinance shall take effect and be in force thirty (30) days from and after its approval by the Mayor, but if not approved and returned by the Mayor within ten (10) days after presentation, it shall take effect as provided by Municipal Code Section 1.04.020.
Passed by the City Council the _____ day of ____________, 1998, and signed by me in open session in authentication of its passage this _____ day of _________________, 1998.
_____________________________________
President _______ of the City Council
Approved by me this _____ day of _________________, 1998.
___________________________________________
Mayor
Filed by me this _____ day of ____________________, 1998.
___________________________________________
City Clerk
(Seal)
SLG: gh October 7, 1998 0-AUDIT2.DOC (Ver. 4)
```
|
Shell
|
UTF-8
| 1,026 | 3.15625 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/bash
# Update all packages
sudo apt-get update && \
sudo apt-get upgrade -y && \
sudo apt-get dist-upgrade -y && \
sudo apt autoremove -y && \
# Install applications to install Docker & Add snap support
sudo apt-get install apt-transport-https ca-certificates curl software-properties-common snapd && \
# Add the docker repository
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - && \
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable" && \
# Install docker
sudo apt-get update && \
sudo apt-get install docker-ce && \
sudo systemctl enable docker && \
# Add ability to run docker without sudo
sudo usermod -aG docker ${USER} && \
su - ${USER} && \
# Install PHPStorm & Spotify through snaps
sudo snap install phpstorm --classic && \
sudo snap install spotify && \
# Add update command to .bashrc
echo "alias update='sudo apt-get update && sudo apt-get upgrade -y && sudo apt-get dist-upgrade -y && sudo apt autoremove -y'" >> ~/.bashrc
|
Java
|
UTF-8
| 336 | 1.859375 | 2 |
[] |
no_license
|
package com.controlcenter.homerestipa.provider;
import org.glassfish.hk2.api.Factory;
/**
* Created by david on 17/12/16.
*/
public class RestServiceProvicer implements Factory<RestServices> {
public RestServices provide() {
return RestServiceFactory.getInstance();
}
public void dispose(RestServices dcs0) {}
}
|
Python
|
UTF-8
| 779 | 2.671875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
class CrackBuilder(object):
'''
Base class to crack builders. Crack builder types(as dynamic or fixed) has
to subclass this class and implement at least all methods.
'''
def __init__(self, type_alias):
self.type_alias = type_alias
def make_crack(self, start_point, final_point, parameters={}, nodes=[]):
'''
@parameters This is extra parameters not given by the program GUI. We
assume the majority of the parameters are given by the 3D program GUI,
then, you modify these parameters directly in the program GUI and then
the crack is updated automatically. DO NOT PUT HERE PARAMETERS ALREADY
GIVEN BY THE 3D PROGRAM. For the shake of cleanliness.
'''
pass
|
C++
|
UTF-8
| 1,433 | 3.78125 | 4 |
[] |
no_license
|
#include "FrogJmp.h"
/*
A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its target.
Write a function:
int solution(int X, int Y, int D);
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
For example, given:
X = 10
Y = 85
D = 30
the function should return 3, because the frog will be positioned as follows:
after the first jump, at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
Write an efficient algorithm for the following assumptions:
X, Y and D are integers within the range [1..1,000,000,000];
X ≤ Y.
Copyright 2009–2018 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
*/
int FJsolution(int X, int Y, int D) {
// write your code in C++14 (g++ 6.2.0)
if (Y < X)
return 0;
int step = (Y - X) / D;
return ++step;
}
int FJsolution2(int X, int Y, int D) {
// write your code in C++14 (g++ 6.2.0)
if (Y < X || Y == X)
return 0;
int distance = Y - X;
if (distance % D == 0)
return distance / D;
else
return (distance / D) + 1;
}
|
Java
|
UTF-8
| 189 | 1.890625 | 2 |
[
"MIT"
] |
permissive
|
package org.kpax.foom.domain;
/**
* @author Eugen Covaci {@literal eugen.covaci.q@gmail.com}
* Created on 9/3/2019
*/
public interface Step {
void execute();
StepContext context();
Step next();
}
|
Java
|
UTF-8
| 2,129 | 2.375 | 2 |
[] |
no_license
|
package com.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.bean.Register;
import com.dao.RegisterController;
public class RegisterServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String a = request.getParameter("emailId");
String b =request.getParameter("password");
long c =Long.parseLong(request.getParameter("contact"));
Register register = new Register();
SessionFactory sessionFactory = null;
Session session = null;
HttpSession s = request.getSession();
PrintWriter out = response.getWriter();
if(b.equals(request.getParameter("confirmPassword"))){
/*RegisterController rc = new RegisterController(a, b, c);
rc.main(null);*/
if(b.equals(request.getParameter("confirmPassword"))){
register.setEmailId(a);
register.setContact(c);
register.setPassword(b);
sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
session.save(register);
session.getTransaction().commit();
s.setAttribute("name", "yes");
System.out.println((String)s.getAttribute("name"));
response.sendRedirect("home.jsp");
}
else{
out.print("Pasword and Repeat password did'nt matched");
}
/*RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}
else{
out.println("Credentials did'nt matched");
RequestDispatcher rd = request.getRequestDispatcher("signup.jsp");
rd.include(request, response);
}
*/
session.close();
}
}
}
|
Python
|
UTF-8
| 114 | 2.703125 | 3 |
[] |
no_license
|
def calcula_aumento(s):
n= 0
if s > 1.250:
n = s * 1.1
else:
n = s * 1.15
return n
|
Java
|
UTF-8
| 2,328 | 2.25 | 2 |
[] |
no_license
|
package com.kafka.producer.api;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.kafka.producer.domain.LibraryEvent;
import com.kafka.producer.domain.LibraryEventType;
import com.kafka.producer.producer.LibraryEventProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping("/v1/libraryevents")
@Slf4j
public class LibraryEventApi {
private LibraryEventProducer eventProducer;
public LibraryEventApi(LibraryEventProducer eventProducer) {
this.eventProducer = eventProducer;
}
@PostMapping
public ResponseEntity<LibraryEvent> create(@RequestBody @Valid LibraryEvent libraryEvent) throws JsonProcessingException {
// invoke kafka async producer
/*log.info("sendLibraryEventAsync start");
eventProducer.sendLibraryEventAsync(libraryEvent);
log.info("sendLibraryEventAsync end");*/
// invoke kafka async producer
/*log.info("sendLibraryEventSync start");
eventProducer.sendLibraryEventSync(libraryEvent);
log.info("sendLibraryEventSync end");*/
// invoke kafka async producer
libraryEvent.setLibraryEventType(LibraryEventType.NEW);
eventProducer.sendLibraryEventAsyncUsingProducerRecord(libraryEvent);
// return
return ResponseEntity.status(HttpStatus.CREATED).body(libraryEvent);
}
@PutMapping
public ResponseEntity<?> update(@RequestBody LibraryEvent libraryEvent) throws JsonProcessingException {
if (libraryEvent.getLibraryEventId()==null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Please pass LibraryEventID");
}
libraryEvent.setLibraryEventType(LibraryEventType.UPDATE);
eventProducer.sendLibraryEventAsyncUsingProducerRecord(libraryEvent);
// return
return ResponseEntity.status(HttpStatus.OK).body(libraryEvent);
}
}
|
Markdown
|
UTF-8
| 1,512 | 2.546875 | 3 |
[] |
no_license
|
# IP Security Camera System
Many IP security cameras offer RTSP video feeds for remote viewing. In order to run analytic software and other tools the user must obtain data from the camera in this manner. Additionally, it would be beneficial to view the video feed within a browser instead of using a proprietary piece of software.
The solution I've provided below allows the user to install FFMPEG, a popular media tool for conversion, and then host the RTSP stream within the browser.
# Install
1. brew install ffmpeg --with-libquvi --with-libvorbis --with-libvpx
2. Install Apache
3. Test "localhost" in your browser.
4. Configure IP camera to broadcast an RTSP stream. Obtain the URL.
5. Test the RTSP URL stream.
6. Move the FFSERVER configuration file to /etc/
7. Run the Media Server:
```ffserver -f /etc/ffserver.conf```
8. Obtain the RTSP Stream and Save it to the Feed.FFM File
```ffmpeg -v debug -i rtsp://<RTSP_IP_ADDRESS>:<PORT> -c:v copy http://localhost:8090/feed.ffm```
9. Overwrite Apache's "index.html" with the "index.html" from this repository.
10. Navigate your browser to '''http://localhost:8090/status.html''' to see the status of the data coming from your IP camera to the media server.
11. If data is being received, go ahead and navigate to "localhost". Check your video feed.
12. Add both the media server and RTSP streams to the boot commands of your respective system.
# Troubleshoot
If you're having a problem installing, please PM me and I"ll do my best to help you.
|
Java
|
UTF-8
| 2,658 | 2.25 | 2 |
[] |
no_license
|
package springtest.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springtest.exceptions.IncorrectHashException;
import springtest.model.Company;
import springtest.model.Coupon;
import springtest.model.Customer;
import springtest.repository.CompanyRepository;
import springtest.repository.CouponRepository;
import springtest.repository.CustomerRepository;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class ShopServiceImpl implements ShopService {
private CustomerRepository customerRepository;
private CompanyRepository companyRepository;
private CouponRepository couponRepository;
@Autowired
public void setCustomerRepository(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
@Autowired
public void setCompanyRepository(CompanyRepository companyRepository) {
this.companyRepository = companyRepository;
}
@Autowired
public void setCouponRepository(CouponRepository couponRepository) {
this.couponRepository = couponRepository;
}
@Override
public List<Company> getAllCompanies(String hash) throws IncorrectHashException {
if (this.customerRepository.findByHash(hash) != null) {
return this.companyRepository.findAll();
}
throw new IncorrectHashException("Авторизуйтесь, чтобы выполнить запрос!!!");
}
@Override
public List<Coupon> getCoupons(String hash) throws IncorrectHashException {
if ( this.customerRepository.findByHash(hash) != null) {
return this.couponRepository.findAll().stream().filter(coupon -> coupon.getAmount() > 0).collect(Collectors.toList());
}
throw new IncorrectHashException("Авторизуйтесь, чтобы выполнить запрос!!!");
}
public Coupon getCoupon(String hash, Long id) throws IncorrectHashException {
if (this.customerRepository.findByHash(hash) != null) {
return this.couponRepository.findById(id).orElse(null);
}
throw new IncorrectHashException("Авторизуйтесь, чтобы выполнить запрос!!!");
}
@Override
public Company getCompany(String hash, Long id) throws IncorrectHashException {
if (this.customerRepository.findByHash(hash) != null) {
return this.companyRepository.findById(id).orElse(null);
}
throw new IncorrectHashException("Авторизуйтесь, чтобы выполнить запрос!!!");
}
}
|
PHP
|
UTF-8
| 493 | 2.75 | 3 |
[] |
no_license
|
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>PT3-4 output</title>
</head>
<body>
<?php
$userA = 'allan';
$userB = 'bill';
$passA = '1234';
$passB = '5678';
if ($_POST['user'] == $userA && $passA == $_POST['pass'])
{
echo '登入成功!Hi, Allan';
}
elseif ($userB == $_POST['user'] && $_POST['pass'] == $passB)
{
echo '登入成功!Hi, Bill';
}
else
{
echo '登入失敗!';
}
?>
</body>
</html>
|
SQL
|
UTF-8
| 150 | 2.5625 | 3 |
[] |
no_license
|
alter table `article_read_log` change `articleId` `articleSlug` bigint(20) default null;
create INDEX idx_artSlug on `article_read_log` (articleSlug);
|
JavaScript
|
UTF-8
| 1,798 | 2.875 | 3 |
[] |
no_license
|
// reduxsauce: serve para facilitar a criação de ducks
import { createReducer, createActions } from 'reduxsauce';
import Immutable from 'seamless-immutable';
// reduxsauce podemos criar os Types e os Creatprs na mesma função
const { Types, Creators } = createActions({
// passa o nome das actions
setPodcastRequest: ['podcast', 'episodeId'],
setPodcastSuccess: ['podcast'],
setCurrent: ['id'],
play: null,
pause: null,
next: null,
prev: null,
reset: null,
});
// Types: {LOAD_REQUEST, LOAD_SUCCESS, LOAD_FAILURE}
// Creators:
/*
loadRequest: () => ({ type: LOAD_REQUEST })
loadSuccess: () => ({ type: LOAD_REQUEST, data })
loadFailure: () => ({ type: LOAD_REQUEST })
*/
// aqui não precisa passar o payload
export const PlayerTypes = Types;
export default Creators;
// initial state
// Immutable: faz com que a variavel INITIAL_STATE imutavel. Garante que o valor não seja alterado
export const INITIAL_STATE = Immutable({
podcast: null,
current: null,
playing: false,
});
// Reducer
// essa função vai retornar tipo um switch case
export const reducer = createReducer(INITIAL_STATE, {
// merge: função do Immutable
// como o state é imutabel, não precisa copiar todo o estado novamente para ele retronar,
// é só usar o merge e passar o valor que quer alterar
// action type na esquerda e o que vai acontecer na direita
[Types.SET_PODCAST_SUCCESS]: (state, action) => state.merge({ podcast: action.podcast, current: action.podcast.tracks[0].id }),
[Types.SET_CURRENT]: (state, action) => state.merge({ current: action.id }),
[Types.PLAY]: state => state.merge({ playing: true }),
[Types.PAUSE]: state => state.merge({ playing: false }),
[Types.RESET]: state => state.merge({ podcast: null, current: null, playing: false }),
});
|
Java
|
UTF-8
| 1,561 | 2.609375 | 3 |
[] |
no_license
|
package org.jiwan.hibernatetutorial.dto;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
@Entity
@Table(name="USER_DETAILS")
public class UserDetails {
@Id
private int userId;
//Ignores the UserName field and is not stored in database
@Transient
private String userName;
//Implements hi-bernate to SQL default data type conversion.
@Basic
private String address;
//Only DATE is extracted from current date.
@Temporal(TemporalType.DATE)
private Date dateJoined;
//To allow database to store large objects CLOB or BLOB.
@Lob
private String description;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getDateJoined() {
return dateJoined;
}
public void setDateJoined(Date dateJoined) {
this.dateJoined = dateJoined;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
|
Markdown
|
UTF-8
| 450 | 3.421875 | 3 |
[] |
no_license
|
# highest--and--lowest--number
highest and lowest number in array using c
#include<studio.h>
int main()
{
int i,max,min,size;
printf("enter size of array");
scanf("%d",&size);
printf("enter elements in array:");
for(i=0;i<size;i++)
{
scant("%d",&arr[i]);
}
max=arr[0];
min=arr[0];
for(i=1;i<size;i++)
{
if(arr[i]>max)
{max=arr[i];
}
}
if(arr[i]<min)
{
min=arr[i];
}
printf("maximum element=%d\n",max);
printf("minimum element=%d\n",min);
return 0;
}
|
SQL
|
UTF-8
| 291 | 3.609375 | 4 |
[] |
no_license
|
--What is the cost after discount for each order? Discounts should be applied as a percentage off.
SELECT o.OrderID, o.OrderDate, sum(od.Quantity * od.UnitPrice * (1 - Discount)) as OrderPrice
FROM Orders o
join [Order Details] od
on od.OrderID = o.OrderID
GROUP BY o.OrderID, o.OrderDate
|
PHP
|
UTF-8
| 495 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* This install script download scripts needed for examples
*
* php -f install.php
*/
$install = array(
'jquery.js' => 'http://code.jquery.com/jquery-1.8.3.js',
);
foreach ($install as $script => $url) {
$data = @file_get_contents($url);
if (!$data) {
echo 'Error: could not download file ' . $url . "\n";
}
elseif (!@file_put_contents($script, $data)) {
echo 'Error: could not save file ' . $script . "\n";
}
else {
echo 'Ok: installed file ' . $script . "\n";
}
}
|
JavaScript
|
UTF-8
| 3,394 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
function Node(label, amount, color)
{
this.label = label;
this.amount = amount;
this.color = color;
this.children = new Array();
}
//Ca sert a rien a part faire joli
function addEx(node, nb)
{
for (var i = 0; i < nb - 1; i++)
node.children.push(new Node('Exercice ' + (i + 1), 100/nb, vis4color.fromHex(node.color).lightness('*'+(1+Math.random()*.5)).x));
var bilan = new Node("Bilan", 100/nb, vis4color.fromHex(node.color).lightness('*'+(1+Math.random()*.5)).x);
bilan.link = "./Mini-jeux/index.html"
node.children.push(bilan);
}
$(function() {
var root = new Node('CameLearn', 75, vis4color.fromHSL(34.5, .7, .6).x);
// root.taxonomy = BubbleTree.Styles.Cofog; //Je sais pas comment ca marche..
root.children.push(new Node('Nombres et calculs', 25, vis4color.fromHSL(0, .7, .5).x));
root.children[0].children.push(new Node('Numérotation décimale', 25, vis4color.fromHex(root.children[0].color).lightness('*'+(.5+Math.random()*.5)).x));
root.children[0].children.push(new Node('Addition', 25, vis4color.fromHex(root.children[0].color).lightness('*'+(.5+Math.random()*.5)).x));
root.children[0].children.push(new Node('Soustraction', 25, vis4color.fromHex(root.children[0].color).lightness('*'+(.5+Math.random()*.5)).x));
root.children[0].children.push(new Node('Multiplication', 25, vis4color.fromHex(root.children[0].color).lightness('*'+(.5+Math.random()*.5)).x));
//Ca sert a rien a part faire joli
addEx(root.children[0].children[0], 1);
addEx(root.children[0].children[1], 4);
addEx(root.children[0].children[2], 3);
addEx(root.children[0].children[3], 8);
root.children.push(new Node('Géométrie', 25, vis4color.fromHSL(220, .7, .5).x));
root.children[1].children.push(new Node('Carré', 30, vis4color.fromHex(root.children[1].color).lightness('*'+(.5+Math.random()*.5)).x));
root.children[1].children.push(new Node('Triangle', 30, vis4color.fromHex(root.children[1].color).lightness('*'+(.5+Math.random()*.5)).x));
root.children[1].children.push(new Node('Cercle', 40, vis4color.fromHex(root.children[1].color).lightness('*'+(.5+Math.random()*.5)).x));
//Ca sert a rien a part faire joli
addEx(root.children[1].children[0], 5);
addEx(root.children[1].children[1], 3);
addEx(root.children[1].children[2], 6);
root.children.push(new Node('Grandeurs et mesures', 25, vis4color.fromHSL(120, .7, .5).x));
root.children[2].children.push(new Node('Unites de mesure', 33, vis4color.fromHex(root.children[2].color).lightness('*'+(.5+Math.random()*.5)).x));
root.children[2].children.push(new Node('Problemes', 33, vis4color.fromHex(root.children[2].color).lightness('*'+(.5+Math.random()*.5)).x));
root.children[2].children.push(new Node('Prochain niveau', 33, vis4color.fromHex(root.children[2].color).lightness('*'+(.5+Math.random()*.5)).x));
//Ca sert a rien a part faire joli
addEx(root.children[2].children[0], 2);
addEx(root.children[2].children[1], 3);
addEx(root.children[2].children[2], 4);
new BubbleTree({
data: root,
sortBy: 'label',
container: '.bubbletree',
bubbleType: 'icon',
bubbleStyles: {
'cofog-1': BubbleTree.Styles.Cofog,
'cofog-2': BubbleTree.Styles.Cofog,
'cofog-3': BubbleTree.Styles.Cofog
}
});
});
|
PHP
|
UTF-8
| 998 | 2.65625 | 3 |
[] |
no_license
|
<?php
namespace Nuxia\Bundle\NuxiaBundle\Twig;
use Symfony\Component\DependencyInjection\Container;
/**
* This extension allows you to camelize (ExampleString) and to underscore (example_string) strings from twig templates.
*
* @author Yannick Snobbert <yannick.snobbert@gmail.com>
*/
class CaseExtension extends \Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getFilters()
{
return [
new \Twig_SimpleFilter('camelize', [$this, 'camelize']),
new \Twig_SimpleFilter('underscore', [$this, 'underscore']),
];
}
/**
* @param string $text
*
* @return string
*/
public function camelize($text)
{
return Container::camelize($text);
}
/**
* @param string $text
*
* @return string
*/
public function underscore($text)
{
return Container::underscore($text);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'case';
}
}
|
C#
|
UTF-8
| 2,028 | 3.171875 | 3 |
[] |
no_license
|
namespace BridgeBeloteLogic.CardDealing
{
using System.Collections.Generic;
using System.Linq;
public static class Rules
{
private static readonly List<BeloteCards> CardsThatCount;
private static readonly List<BeloteCards> AllBelotCards;
static Rules()
{
CardsThatCount = new List<BeloteCards> { BeloteCards.Nine, BeloteCards.Ten, BeloteCards.Jack, BeloteCards.Queen, BeloteCards.King, BeloteCards.Ace };
AllBelotCards = new List<BeloteCards> { BeloteCards.Seven, BeloteCards.Eight, BeloteCards.Nine, BeloteCards.Ten, BeloteCards.Jack, BeloteCards.Queen, BeloteCards.King, BeloteCards.Ace };
}
public static bool FourOfAKindCheck(List<List<Card>> allCardsDealt)
{
foreach (var cardThatCounts in CardsThatCount)
{
if (allCardsDealt.Any(p => p.All(q => q.BelotCard == cardThatCounts)))
{
return true;
}
}
return false;
}
public static bool LongSequencesCheck(List<List<Card>> allCardsDealt, int maxLengthDiscard)
{
var skip = 0;
while (true)
{
var sequence = AllBelotCards.Skip(skip++).Take(maxLengthDiscard).ToList();
if (sequence.Count < maxLengthDiscard)
{
return false;
}
foreach (var cardsDealt in allCardsDealt)
{
var sameSuitCards = cardsDealt.GroupBy(p => p.Suit, p => p.BelotCard, (key, value) => new { Key = key, SuitCards = value.ToList() });
foreach (var suitCardsDealt in sameSuitCards)
{
if (suitCardsDealt.SuitCards.Intersect(sequence).Count() == maxLengthDiscard)
{
return true;
}
}
}
}
}
}
}
|
Python
|
UTF-8
| 5,782 | 2.78125 | 3 |
[] |
no_license
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
User interface for demonstration of max-tree and area open filter.
Implementation
C. Meyer
"""
import sys
import numpy as np
import qimage2ndarray
# Qt5 includes
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QFileDialog
from PyQt5.QtWidgets import QWidget, QLabel, QSlider, QSpinBox
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout
from PyQt5.QtGui import QPixmap
from PyQt5 import QtCore
# MaMPy includes
# Utilities
from utils import image_read
# Max-Tree Berger
from max_tree import maxtree, area_filter, contrast_filter
class MaMPyGUIDemoMaxTree(QMainWindow):
# default size of GUI
xsize = 800
ysize = 600
# Images Attributes
imageSrc = None
# Initialisation of the class
def __init__(self):
super().__init__()
self.initUI()
# Initialisation of the user interface.
def initUI(self):
# Image Label Source
self.imageLabelSrc = QLabel()
self.imageLabelSrc.setAlignment(QtCore.Qt.AlignCenter)
# Image Label Result 1
self.imageLabelRes1 = QLabel()
self.imageLabelRes1.setAlignment(QtCore.Qt.AlignCenter)
# Image Label Result 2
self.imageLabelRes2 = QLabel()
self.imageLabelRes2.setAlignment(QtCore.Qt.AlignCenter)
# Area Threshold Slider
self.areaThresholdSlider = QSlider(QtCore.Qt.Horizontal)
self.areaThresholdSlider.setRange(0, 1)
self.areaThresholdSlider.valueChanged.connect(self.areaThresholdSliderChanged)
# Area Threshold Spinbox
self.areaThresholdSpinbox = QSpinBox()
self.areaThresholdSpinbox.setRange(0, 1)
self.areaThresholdSpinbox.valueChanged.connect(self.areaThresholdSpinboxChanged)
# Layout
self.imageLabelLayout = QHBoxLayout()
self.thresholdLayout = QHBoxLayout()
self.imageLabelLayout.addWidget(self.imageLabelSrc)
self.imageLabelLayout.addWidget(self.imageLabelRes1)
self.imageLabelLayout.addWidget(self.imageLabelRes2)
self.imageLabelLayoutWidget = QWidget()
self.imageLabelLayoutWidget.setLayout(self.imageLabelLayout)
self.thresholdLayout.addWidget(self.areaThresholdSlider)
self.thresholdLayout.addWidget(self.areaThresholdSpinbox)
self.thresholdLayoutWidget = QWidget()
self.thresholdLayoutWidget.setLayout(self.thresholdLayout)
self.mainLayout = QVBoxLayout()
self.mainLayout.addWidget(self.imageLabelLayoutWidget)
self.mainLayout.addWidget(self.thresholdLayoutWidget)
# Main Widget
self.window = QWidget()
self.window.setLayout(self.mainLayout)
# Set Central Widget
self.setCentralWidget(self.window)
# Actions
# Open File
openFile = QAction('Open', self)
openFile.setShortcut('Ctrl+O')
openFile.triggered.connect(self.openImageDialog)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(openFile)
# Center Window
xbase = (app.desktop().screenGeometry().width() - self.xsize) / 2
ybase = (app.desktop().screenGeometry().height() - self.ysize) / 2
# Window Property
self.setGeometry(xbase, ybase, self.xsize, self.ysize)
self.setWindowTitle('MaMPy Max-Tree demo')
self.show()
def resizeEvent(self, event):
self.xsize = event.size().width()
self.ysize = event.size().height()
self.updateImages()
QMainWindow.resizeEvent(self, event)
def areaThresholdSliderChanged(self, event):
self.areaThresholdSpinbox.setValue(self.areaThresholdSlider.value())
self.updateImages()
def areaThresholdSpinboxChanged(self, event):
self.areaThresholdSlider.setValue(self.areaThresholdSpinbox.value())
self.updateImages()
def openImageDialog(self):
filename = QFileDialog.getOpenFileName(self, "Open file", None, 'Image Files (*.png *.jpg *.bmp)')
if filename[0]:
# Read the image
self.imageSrc = image_read(filename[0])
self.maxtree = maxtree(self.imageSrc)
# Update slider and spinbox in the image resolution range
self.areaThresholdSlider.setRange(0, (self.imageSrc.shape[0] * self.imageSrc.shape[1]))
self.areaThresholdSpinbox.setRange(0, (self.imageSrc.shape[0] * self.imageSrc.shape[1]))
# Update the image label
self.updateImages()
def updateImages(self):
# Check if an image is loaded
if self.imageSrc is None:
return
# Image Source
pixmapSrc = QPixmap(qimage2ndarray.array2qimage(self.imageSrc))
pixmapSrc = pixmapSrc.scaled((self.xsize / 3) - 50, self.ysize - 50, QtCore.Qt.KeepAspectRatio)
self.imageLabelSrc.setPixmap(pixmapSrc)
# Image Result
self.imageRes1 = area_filter(input=self.imageSrc, threshold=max(1,self.areaThresholdSpinbox.value()), maxtree_p_s=self.maxtree)
pixmapRes1 = QPixmap(qimage2ndarray.array2qimage(self.imageRes1))
pixmapRes1 = pixmapRes1.scaled((self.xsize / 3) - 50, self.ysize - 50, QtCore.Qt.KeepAspectRatio)
self.imageRes2 = contrast_filter(input=self.imageSrc, threshold=max(1,self.areaThresholdSpinbox.value()), maxtree_p_s=self.maxtree)
pixmapRes2 = QPixmap(qimage2ndarray.array2qimage(self.imageRes2))
pixmapRes2 = pixmapRes2.scaled((self.xsize / 3) - 50, self.ysize - 50, QtCore.Qt.KeepAspectRatio)
self.imageLabelRes1.setPixmap(pixmapRes1)
self.imageLabelRes2.setPixmap(pixmapRes2)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MaMPyGUIDemoMaxTree()
sys.exit(app.exec_())
|
Markdown
|
UTF-8
| 6,587 | 3.390625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
---
title: "How to survive as a programmer"
date: 2018-10-30
permalink: /posts/2018/10/how-to-survive-as-programmer/
tags:
excerpt: Programming is fun and here are some tips gathered over 18 years of programming experience on how to survive (and excel) as a programmer
---

> Everybody in this country should learn to program a computer...
> because it teaches you how to think
>
>> <cite>Steve Jobs</cite>
I have always enjoyed writing code and I still do. I think it is not because I am good at it, but it is such a challenge. One of the first program which I wrote was, when I was in grade five, was to find if a given word is a [palindrome](https://en.wikipedia.org/wiki/Palindrome) or not and after that I have written thousands of lines of code.
As much as I enjoy programming, I must in all honesty admit that I am a mediocre programmer who has always found a way to get to the big payoff. Today I am going to share some experiences which I have gained over past eighteen years of on how you can survive in this industry even if you are not some rockstar developer
## A developer must wear many hats
Programmer is but one of the many roles of a developer; you often have to wear the following hats as well:
+ Analyst
+ Designer
+ Planner
+ Programmer
+ Coordinator
+ Tester
+ Documenter
+ Support technician
+ Operational Engineer
Even with my less than stellar programming skills, I am very successful as a developer. The following is how I survived to make the best of my average coding skills:
### You don't have to be programming encyclopaedia
You don't have to remember everything, you just need to be **AWARE** that there's such function or such class or such feature.
I fail to remember a lot of the things. Like functions and methods from the standard library, arguments positions, package names, boilerplate code and so on.
So, I have to google it. And I do it on a daily basis. I also reuse code from old projects. Sometimes I even copy-paste answers from StackOverflow or Github. However, the trick to survive here is to be smart and make your own judgement of what is good and what is not. Ensure that you fully understand what you copy and that there are no vulnerabilities in it.
Build a mental library of where (and not how) you have solved a similar issue.
### Analysis & Design
> First, solve the problem. Then, write the code.
>> John Johnson
You must be able to solve the problem before you tell a computer to solve it. And the best way to check if you can solve the problem is model the problem using classic style of pen and paper. Once you are confident that the model works, then take a pause and get it reviewed by someone. Try to see if some person can understand your solution (model), because if a human cannot understand it chances are very less that a machine can. That's where reviews form such an important role in application development.
Only after the solution is very clear between you and your peers start writing code.
_Sometimes things will not be clear during design time and you just have to start writing code to make things clear. That is perfectly ok. It is just that you are writing code to prove something or make somethings clear. But this should happen by design_
### Beware of Fortunate happenstance
The strategy of _**Just write code and it will get done**_ doesn't work in real world. Just like in a game of chess you play and suddenly discover that you have given yourself the opportunity for checkmate in two moves. This is not how programming should be done.
All software will have bugs there is no denying that. As a programmer I need to reduce the bugs to acceptable levels. A programmer will have to ensure that there are no obvious bugs. You can protect in multiple ways
+ Testing is the first thing, main thing and the only thing. Start from Unit tests and move up to Integration tests. There is no such thing to say how many lines of test are enough, but one measure I use is that, if you change some code and your existing tests don't fail then there is something to have second look at.
+ Always use Continous Integration and Continous Deployment. First thing you do before you start any development activity is to setup a CI/CD environment. No coding should begin without CI.
+ Get it reviewed, may be more than once. Important thing about review is, it should be done in small batches. No reviewer will like to review hundreds of file. Try to create small pull requests (comprising changes to not more than 5-6 files)
+ Ensure it runs on all environments. It is very common to hear that code works on my machine. With advance in technologies like containerization and virtualization it should be very easy to test if your code works on any and every environment
### Perseverance
Never give up. Always believe you can accomplish any programming task. Be pragmatic and take stock of things. If things are not going your way, be brave to take some tough decisions which might include re-writing from scratch.
### Requirements
I have seen many programmers with the mindset waiting to write code till you get a complete, accurate and concrete list of the system requirements up-front. Let me tell you in my experience I have never seen a concrete set of system requirements.
As a programmer you should be able to start your role with minimalistic set of requirements with full knowledge that they would change in future. Having this thread running in back of your mind will make you question yourself at every stage of development. Keep asking yourself
+ _"What will happen to my code if this requirement changes?"_
+ _"Can I extend my code to incorporate new features if added in future?_
+ _"What will be the impact on other systems if my code change?_
### Continuous learning
A career in programming is like running on a treadmill. Just as on a moving treadmill you try to stop you will fall, so in this field of technology if you stop to learn new things you will fall off. Learning is essential to career of a programmer. If we want to survive we constantly need to learn how to get better, every single day
## Conclusion
I am not condoning mediocrity; you should always do your best in whatever you do — including programming. What I want to say is you don't have to be a whiz-bang programmer to be a great developer. The elitist belief that only superb programmers can write "sophisticated code" is not true. I have followed the practises above and I am sure by doing the same every programmer can be capable of producing high-quality code.
|
Java
|
UTF-8
| 11,308 | 2.28125 | 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 pcap4eje14;
/**
*
* @author Homar
*/
public class empresa extends javax.swing.JFrame {
/**
* Creates new form empresa
*/
public empresa() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
v1 = new javax.swing.JTextField();
v2 = new javax.swing.JTextField();
v3 = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
l1 = new javax.swing.JLabel();
l2 = new javax.swing.JLabel();
l3 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
salario = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Ventas por vendedor");
jLabel2.setText("Vendedor 1:");
jLabel3.setText("Vendedor 2:");
jLabel4.setText("Vendedor 3:");
jLabel5.setText("Ventas");
jLabel6.setText("Salario");
jLabel10.setText("Salario de cada departamento");
jButton1.setText("OK");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)))
.addGroup(layout.createSequentialGroup()
.addGap(92, 92, 92)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(v1, javax.swing.GroupLayout.DEFAULT_SIZE, 63, Short.MAX_VALUE)
.addComponent(v2)
.addComponent(v3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(l1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(l2, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(l3, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6)))))
.addGap(89, 89, 89))
.addGroup(layout.createSequentialGroup()
.addGap(118, 118, 118)
.addComponent(jLabel10)
.addContainerGap(138, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(141, 141, 141)
.addComponent(salario, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(l1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(v1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(v2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(l2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(v3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(l3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel10)
.addGap(18, 18, 18)
.addComponent(salario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(20, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
double vd1, vd2, vd3, salar, totven, porvent, salar1, salar2, salar3;
try{
vd1 = Double.parseDouble(v1.getText());
vd2 = Double.parseDouble(v2.getText());
vd3 = Double.parseDouble(v3.getText());
salar = (int) Double.parseDouble(salario.getText());
totven = vd1 + vd2 + vd3 ;
porvent = 0.33 * totven;
if (vd1 > porvent) {
salar1 = salar + (0.2 * salar);
}else{
salar1=salar;
}
if (vd2 > porvent){
salar2 = salar + (0.2 * salar);
}else{
salar2 = salar;
}
if (vd3 > porvent){
salar3 = salar + (0.2 * salar);
}else{
salar3 = salar;
}
l1.setText(String.valueOf(salar1));
l2.setText(String.valueOf(salar2));
l3.setText(String.valueOf(salar3));
}
catch( Exception errordato) {
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(empresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(empresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(empresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(empresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new empresa().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel l1;
private javax.swing.JLabel l2;
private javax.swing.JLabel l3;
private javax.swing.JTextField salario;
private javax.swing.JTextField v1;
private javax.swing.JTextField v2;
private javax.swing.JTextField v3;
// End of variables declaration//GEN-END:variables
}
|
JavaScript
|
UTF-8
| 4,416 | 2.6875 | 3 |
[] |
no_license
|
import React, { Component } from 'react';
//status needs to be considered
//need to ensure validation is proper on handleSubmit
//debate if data dump on modal close should be handled here
//fix handleSubmitForm
//fix componentDidMount
class JobForm extends Component {
constructor() {
super();
this.state = {
jobFormData: {
company: '',
position: '',
status: false,
contact_name: '',
contact_email: '',
contact_phone: '',
},
editing: false,
formError: false,
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmitForm = this.handleSubmitForm.bind(this);
}
componentDidMount() {
if(this.props.currentJob) {
const { company, position, status, contact_name, contact_email, contact_phone } = this.props.currentJob
this.setState({
jobFormData: {
company,
position,
status,
contact_name,
contact_email,
contact_phone,
},
editing: true,
formError: false,
});
}
}
handleChange(ev) {
ev.preventDefault();
const { name, value } = ev.target;
this.setState(prevState => ({
jobFormData: {
...prevState.jobFormData,
[name]: value,
}
}))
}
async handleSubmitForm(ev) {
//this needs to validate for editing or creating and do the proper action accordingly
ev.preventDefault();
const { company, position } = this.state.jobFormData;
if(company && position) {
const resp = await this.props.submitForm(this.state.jobFormData);
if(resp) {
this.setState({
jobFormData: {
company: '',
position: '',
status: '',
contact_name: '',
contact_email: '',
contact_phone: '',
},
editing: false,
});
this.props.toggleModal();
} else {
console.log('something went wrong');
}
} else {
this.setState({
formError: true,
})
}
}
render() {
const { company, position, status, contact_name, contact_email, contact_phone } = this.state.jobFormData;
return (
<div className="job-form-outer">
<div className="job-form-inner">
<div className="job-form-subheader">
<div className="job-close-modal-button" onClick={(ev) => {
ev.preventDefault();
this.props.toggleModal()
}}>X</div>
<h1 className="job-form-title">{this.state.editing ? 'Edit Job Form' : 'Create Job Form'}</h1>
<div className="job-form-subtitle">(*indicate a require field)</div>
</div>
<form className="job-form" onSubmit={this.handleSubmitForm}>
<label>*Company:</label>
<input
type='text'
name='company'
value={company}
onChange={this.handleChange} /><br/>
<label>*Position:</label>
<input
type='text'
name='position'
value={position}
onChange={this.handleChange} /><br/>
<label>Status:</label>
<select
name="status"
value={status}
onChange={this.handleChange}>
<option value={false}>Passive</option>
<option value={true}>Active</option>
</select><br/>
<label>Contact Name:</label>
<input
type='text'
name='contact_name'
value={contact_name}
onChange={this.handleChange} /><br/>
<label>Contact Email:</label>
<input
type='text'
name='contact_email'
value={contact_email}
onChange={this.handleChange} /><br/>
<label>Contact Phone:</label>
<input
type='text'
name='contact_phone'
value={contact_phone}
onChange={this.handleChange} /><br/>
<input
type='submit'
value={this.state.editing ? 'Edit Your Job' : 'Create a New Job'} />
</form>
{ this.state.formError && <div className="job-form-error-message">Please fill all required fields.</div>}
</div>
</div>
)
}
}
export default JobForm
|
Markdown
|
UTF-8
| 741 | 2.546875 | 3 |
[] |
no_license
|
# Comments service
This application was generated using http://start.vertx.io
## Requirements
Running the application locally you need Java 1.8.
You also might need to give execution permissions to the mvn wrapper ./mvnw
## Running (with docker)
1. Build (fat) jar with `./mvnw clean package`
2. Create data volume for mongo: `docker volume create comments-data-dev`
2. run `docker-compose up`
3. grpc server is running on port 3001
## Developing
When using intellij open this folder as the project root to get java support right away.
After making changes to proto file, packaging (`./mvnw clean package`) should compile the protofiles.
To launch tests:
`./mvnw clean test`
Simply running locally:
`./mvnw clean compile exec:java`
|
C#
|
UTF-8
| 2,032 | 3.171875 | 3 |
[
"MIT"
] |
permissive
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
namespace System.Drawing.Printing;
/// <summary>
/// Retrieves the resolution supported by a printer.
/// </summary>
public partial class PrinterResolution
{
private int _x;
private int _y;
private PrinterResolutionKind _kind;
/// <summary>
/// Initializes a new instance of the <see cref='PrinterResolution'/> class with default properties.
/// </summary>
public PrinterResolution()
{
_kind = PrinterResolutionKind.Custom;
}
internal PrinterResolution(PrinterResolutionKind kind, int x, int y)
{
_kind = kind;
_x = x;
_y = y;
}
/// <summary>
/// Gets a value indicating the kind of printer resolution.
/// </summary>
public PrinterResolutionKind Kind
{
get => _kind;
set
{
if (value < PrinterResolutionKind.High || value > PrinterResolutionKind.Custom)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(PrinterResolutionKind));
}
_kind = value;
}
}
/// <summary>
/// Gets the printer resolution in the horizontal direction, in dots per inch.
/// </summary>
public int X
{
get => _x;
set => _x = value;
}
/// <summary>
/// Gets the printer resolution in the vertical direction, in dots per inch.
/// </summary>
public int Y
{
get => _y;
set => _y = value;
}
/// <summary>
/// Provides some interesting information about the PrinterResolution in String form.
/// </summary>
public override string ToString()
{
if (_kind != PrinterResolutionKind.Custom)
{
return $"[PrinterResolution {Kind}]";
}
return FormattableString.Invariant($"[PrinterResolution X={X} Y={Y}]");
}
}
|
JavaScript
|
UTF-8
| 3,599 | 3.328125 | 3 |
[] |
no_license
|
//INPUT
const gameBoard = document.getElementById('game-board');
document.getElementById('formInput').addEventListener('submit',submitForm);
function submitForm(e){
e.preventDefault();
//clear reset
gameBoard.innerHTML = '';
let axeX = getInputVal('axeX');
let axeY = getInputVal('axeY');
let xAspi = getInputVal('xAspi');
let yAspi = getInputVal('yAspi');
let ori = getInputVal('ori');
let ins = getInputVal('ins');
let charsIns = ins.split('');
//change taille
gameBoard.style.gridTemplateColumns = `repeat( ${+axeX}, 1fr)`;
gameBoard.style.gridTemplateRows = `repeat( ${+axeY}, 1fr)`;
//clear Form
document.getElementById('formInput').reset();
// initilisation
const initAspi = [{ x: +xAspi, y: +yAspi, d: ori }];
const aspiContent = [{ x: +xAspi, y: +yAspi, d: ori }];
const Instructions = charsIns;
// function update
const update = () => {
for(let i = 0; i <= Instructions .length - 1; i++){
getInputDirection(Instructions [i]);
initAspi[0].x += inputDirection.x;
initAspi[0].y += inputDirection.y;
initAspi[0].d = inputDirection.d;
aspiContent.push({x: initAspi[0].x, y: initAspi[0].y, d: initAspi[0].d });
}
console.log('Instruction',Instructions )
//console.log(aspiContent);
draw(gameBoard);
console.log('Check position finale:',aspiContent[Instructions.length])
}
// function dessiner
const draw = (gameBoard) => {
for(let i=0; i < Instructions .length + 1; i++){
setTimeout(() => {
const snakeElement = document.createElement('div');
snakeElement.style.gridRowStart = -aspiContent[i].y;
snakeElement.style.gridColumnStart = aspiContent[i].x;
snakeElement.classList.add('aspirateur');
snakeElement.classList.add('show');
gameBoard.appendChild(snakeElement);
setTimeout(() => {
snakeElement.classList.remove('show');
}, 500);
console.log('Etap ',i,aspiContent[i]);
}, i*1000);
}
}
update();
}
// Change direction
function getInputVal(id){
return document.getElementById(id).value;
}
let inputDirection = { x: 0, y: 0, d: 'N' };
const getInputDirection = (Instructions ) =>{
let copyInputDirection = inputDirection;
switch(Instructions ){
case 'A':
if (copyInputDirection.d == 'N'){
inputDirection = { x: 0, y: +1, d: 'N' };
}
if (copyInputDirection.d == 'E'){
inputDirection = { x: +1, y: 0, d: 'E' };
}
if (copyInputDirection.d == "S"){
inputDirection = { x: 0, y: -1, d: 'S' };
}
if (copyInputDirection.d == 'W'){
inputDirection = { x: -1, y: 0, d: 'W' };
}
break;
case 'G':
if (copyInputDirection.d == 'N'){
inputDirection = { x: 0, y: 0, d: 'W' };
}
if (copyInputDirection.d == 'E'){
inputDirection = { x: 0, y: 0, d: 'N' };
}
if (copyInputDirection.d == 'S'){
inputDirection = { x: 0, y: 0, d: 'E' };
}
if (copyInputDirection.d == 'W'){
inputDirection = { x: 0, y: 0, d: 'S' };
}
break;
case 'D':
if (copyInputDirection.d == 'N'){
inputDirection = { x: 0, y: 0, d : 'E' };
}
if (copyInputDirection.d == 'E'){
inputDirection = { x: 0, y: 0, d: 'S' };
}
if (copyInputDirection.d == 'S'){
inputDirection = { x: 0, y: 0, d: 'W' };
}
if (copyInputDirection.d == 'W'){
inputDirection = { x: 0, y: 0, d: 'N' };
}
break;
}
return inputDirection;
}
|
Ruby
|
UTF-8
| 1,144 | 2.828125 | 3 |
[] |
no_license
|
class Message
attr_accessor :subject,:priority,:body,:from,:to
def initialize(log)
@log = log
end
def subject=(value)
@subject = value
end
def subject
"#{self.priority} - #{@subject}"
end
def deliver
Pony.mail(:to => @to, :from => @from, :subject => subject, :body => @body)
@log.info "message sent to #{@to} ok !"
end
end
class Beacon
LOG_FILE = "tmp/beacon.log"
CONF= "conf/beacon.conf"
def initialize()
@log = Logger.new(LOG_FILE)
end
def emails()
File.read(CONF).split("\n")
end
def deliver(subject,priority,description)
begin
emails.each do |email|
email_message = Message.new(@log)
email_message.priority = priority
email_message.subject = subject
email_message.body = description
email_message.from = "noreply@automationstack.bskyb.com"
email_message.to = email
email_message.deliver
end
return true
rescue Exception => e
@log.info "failed to send emails because #{e.to_s}"
return false
end
end
end
|
Python
|
UTF-8
| 2,734 | 2.671875 | 3 |
[] |
no_license
|
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy import TweepError
import sys
import logging
# Import twitter keys and tokens
from .config import *
# Import listener
from .tools.tweet_listener import TweetStreamListener
from .tools.tweet_api import TweetApiSearch
class TweetSearch():
def __init__(self,index):
self.index = index
def run(self,texto_buscar):
"""Pipelines"""
logging.basicConfig(level=logging.ERROR)
# Obtain the input topics of your interests
if (texto_buscar is None or texto_buscar == ""):
return
topics = [texto_buscar.lower()]
'''
if len(sys.argv) == 1:
# Default topics
topics = []
else:
for topic in sys.argv[1:]:
topics.append(topic)
'''
# Change this if you're not happy with the index and type names
index = "tweets-sentiment_"+self.index
doc_type = "new-tweet"
print("==> Topics", topics)
print("==> Index: {}, doc type: {}".format(index, doc_type))
print("==> Start searchTweets...")
search = TweetApiSearch(index, doc_type, google_api_key, consumer_key, consumer_secret, access_token, access_token_secret)
search.searchTweets(topics, 1000)
print("==> Start retrieving tweets...")
# Create instance of the tweepy tweet stream listener
listener = TweetStreamListener(index, doc_type, topics, google_api_key=google_api_key)
# Set twitter keys/tokens
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
# Set the program to restart automatically in case of errors
while True:
try:
# Search twitter for topics of your interests
print("--> Itetate")
stream = Stream(auth, listener)
stream.filter(track=topics)
except KeyboardInterrupt:
# To stop the program
stream.disconnect()
print("==> Stop")
raise
except TweepError as e:
if e.reason[0]['code'] == "420":
print("error 420")
time.sleep(200)
continue
except stream.ConnectionError as e:
print (" error: ", e.message)
time.sleep(200)
continue
except stream.AuthenticationError as e:
print (" error: ", e.message)
raise
except:
print("main - Error inesperado:", sys.exc_info()[0])
raise
|
Java
|
UTF-8
| 1,327 | 2.5625 | 3 |
[] |
no_license
|
package viewstar.doubleauth.demo.entity;
import lombok.Data;
public class ResultUtil {
public static ResponseMessage success(Object object) {
ResponseMessage responseMessage = new ResponseMessage();
responseMessage.setErrorCode(ResultEnum.SUCCESS.getCode());
responseMessage.setErrorMsg(ResultEnum.SUCCESS.getMsg());
responseMessage.setData(object);
return responseMessage;
}
/**
* 操作成功不返回消息
* @return
*/
public static ResponseMessage success() {
return success(null);
}
/**
* 操作失败返回的消息
* @param code
* @param msg
* @return
*/
public static ResponseMessage error(int code,String msg) {
ResponseMessage responseMessage = new ResponseMessage();
responseMessage.setErrorCode(code);
responseMessage.setErrorMsg(msg);
return responseMessage;
}
/**
* 操作失败返回消息,对error的重载
* @param resultEnum
* @return
*/
public static ResponseMessage error(ResultEnum resultEnum){
ResponseMessage responseMessage = new ResponseMessage();
responseMessage.setErrorCode(resultEnum.getCode());
responseMessage.setErrorMsg(resultEnum.getMsg());
return responseMessage;
}
}
|
C++
|
UTF-8
| 967 | 2.8125 | 3 |
[] |
no_license
|
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
if (triangle.empty()) return 0;
int dp[triangle.back().size()];
dp[0] = triangle[0][0];
for (int i = 0; i < triangle.size(); i++) {
int last = 0;
for (int j = 0; j < triangle[i].size(); j++) {
if (j == 0) {
last = triangle[i][j] + dp[j];
}
else if (j == triangle[i].size() - 1) {
dp[j] = triangle[i][j] + dp[j - 1];
dp[j - 1] = last;
}
else {
int v = triangle[i][j] + min(dp[j], dp[j - 1]);
dp[j - 1] = last;
last = v;
}
}
}
int v = numeric_limits<int>::max();
for (int i = 0; i < triangle.back().size(); i++) {
v = min(v, dp[i]);
}
return v;
}
};
|
Python
|
UTF-8
| 9,528 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
import hashlib
import pickle
import re
import socket
import ssl
from .compat import get_charset
from .compat import HTTPError
from .compat import OrderedDict
from .compat import Request
from .compat import urlencode
from .compat import URLError
from .compat import urlopen
try:
import simplejson as json
try:
InvalidJson = json.JSONDecodeError
except AttributeError:
InvalidJson = ValueError
except ImportError:
import json
InvalidJson = ValueError
from micawber.exceptions import InvalidResponseException
from micawber.exceptions import ProviderException
from micawber.exceptions import ProviderNotFoundException
class Provider(object):
socket_timeout = 3.0
user_agent = 'python-micawber'
def __init__(self, endpoint, **kwargs):
self.endpoint = endpoint
self.base_params = {'format': 'json'}
self.base_params.update(kwargs)
def fetch(self, url):
socket.setdefaulttimeout(self.socket_timeout)
req = Request(url, headers={'User-Agent': self.user_agent})
try:
resp = fetch(req)
except URLError:
return False
except HTTPError:
return False
except socket.timeout:
return False
except ssl.SSLError:
return False
return resp
def encode_params(self, url, **extra_params):
params = dict(self.base_params)
params.update(extra_params)
params['url'] = url
return urlencode(sorted(params.items()))
def request(self, url, **extra_params):
encoded_params = self.encode_params(url, **extra_params)
endpoint_url = self.endpoint
if '?' in endpoint_url:
endpoint_url = '%s&%s' % (endpoint_url.rstrip('&'), encoded_params)
else:
endpoint_url = '%s?%s' % (endpoint_url, encoded_params)
response = self.fetch(endpoint_url)
if response:
return self.handle_response(response, url)
else:
raise ProviderException('Error fetching "%s"' % endpoint_url)
def handle_response(self, response, url):
try:
json_data = json.loads(response)
except InvalidJson as exc:
try:
msg = exc.message
except AttributeError:
msg = exc.args[0]
raise InvalidResponseException(msg)
if 'url' not in json_data:
json_data['url'] = url
if 'title' not in json_data:
json_data['title'] = json_data['url']
return json_data
def make_key(*args, **kwargs):
return hashlib.md5(pickle.dumps((args, kwargs))).hexdigest()
def url_cache(fn):
def inner(self, url, **params):
if self.cache:
key = make_key(url, params)
data = self.cache.get(key)
if not data:
data = fn(self, url, **params)
self.cache.set(key, data)
return data
return fn(self, url, **params)
return inner
def fetch(request):
resp = urlopen(request)
if resp.code < 200 or resp.code >= 300:
return False
# by RFC, default HTTP charset is ISO-8859-1
charset = get_charset(resp) or 'iso-8859-1'
content = resp.read().decode(charset)
resp.close()
return content
class ProviderRegistry(object):
def __init__(self, cache=None):
self._registry = OrderedDict()
self.cache = cache
def register(self, regex, provider):
self._registry[regex] = provider
def unregister(self, regex):
del self._registry[regex]
def __iter__(self):
return iter(reversed(list(self._registry.items())))
def provider_for_url(self, url):
for regex, provider in self:
if re.match(regex, url):
return provider
@url_cache
def request(self, url, **params):
provider = self.provider_for_url(url)
if provider:
return provider.request(url, **params)
raise ProviderNotFoundException('Provider not found for "%s"' % url)
def bootstrap_basic(cache=None, registry=None):
# complements of oembed.com#section7
pr = registry or ProviderRegistry(cache)
# b
pr.register('http://blip.tv/\S+', Provider('http://blip.tv/oembed'))
# c
pr.register('http://chirb.it/\S+', Provider('http://chirb.it/oembed.json'))
pr.register('https://www.circuitlab.com/circuit/\S+', Provider('https://www.circuitlab.com/circuit/oembed'))
pr.register('http://www.collegehumor.com/video/\S+', Provider('http://www.collegehumor.com/oembed.json'))
# d
pr.register('https?://(www\.)?dailymotion\.com/\S+', Provider('http://www.dailymotion.com/services/oembed'))
# f
pr.register('https?://\S*?flickr.com/\S+', Provider('https://www.flickr.com/services/oembed/'))
pr.register('https?://flic\.kr/\S*', Provider('https://www.flickr.com/services/oembed/'))
pr.register('https?://(www\.)?funnyordie\.com/videos/\S+', Provider('http://www.funnyordie.com/oembed'))
# g
pr.register(r'https?://gist.github.com/\S*', Provider('https://github.com/api/oembed'))
# h
pr.register('http://www.hulu.com/watch/\S+', Provider('http://www.hulu.com/api/oembed.json'))
# i
pr.register('http://www.ifixit.com/Guide/View/\S+', Provider('http://www.ifixit.com/Embed'))
pr.register('http://\S*imgur\.com/\S+', Provider('http://api.imgur.com/oembed')),
pr.register('https?://instagr(\.am|am\.com)/p/\S+', Provider('http://api.instagram.com/oembed'))
# j
pr.register('http://www.jest.com/(video|embed)/\S+', Provider('http://www.jest.com/oembed.json'))
# m
pr.register('http://www.mobypicture.com/user/\S*?/view/\S*', Provider('http://api.mobypicture.com/oEmbed'))
pr.register('http://moby.to/\S*', Provider('http://api.mobypicture.com/oEmbed'))
# p
pr.register('http://i\S*.photobucket.com/albums/\S+', Provider('http://photobucket.com/oembed'))
pr.register('http://gi\S*.photobucket.com/groups/\S+', Provider('http://photobucket.com/oembed'))
pr.register('http://www.polleverywhere.com/(polls|multiple_choice_polls|free_text_polls)/\S+', Provider('http://www.polleverywhere.com/services/oembed/'))
pr.register('https?://(.+\.)?polldaddy\.com/\S*', Provider('http://polldaddy.com/oembed/'))
# q
pr.register('http://qik.com/video/\S+', Provider('http://qik.com/api/oembed.json'))
# r
pr.register('http://\S*.revision3.com/\S+', Provider('http://revision3.com/api/oembed/'))
# s
pr.register('http://www.slideshare.net/[^\/]+/\S+', Provider('http://www.slideshare.net/api/oembed/2'))
pr.register('http://slidesha\.re/\S*', Provider('http://www.slideshare.net/api/oembed/2'))
pr.register('http://\S*.smugmug.com/\S*', Provider('http://api.smugmug.com/services/oembed/'))
pr.register('https://\S*?soundcloud.com/\S+', Provider('http://soundcloud.com/oembed'))
pr.register('https?://speakerdeck\.com/\S*', Provider('https://speakerdeck.com/oembed.json')),
pr.register('https?://(www\.)?scribd\.com/\S*', Provider('http://www.scribd.com/services/oembed'))
# t
pr.register('https?://(www\.)?twitter.com/\S+/status(es)?/\S+', Provider('https://api.twitter.com/1/statuses/oembed.json'))
# v
pr.register('http://\S*.viddler.com/\S*', Provider('http://lab.viddler.com/services/oembed/'))
pr.register('http://vimeo.com/\S+', Provider('http://vimeo.com/api/oembed.json'))
pr.register('https://vimeo.com/\S+', Provider('https://vimeo.com/api/oembed.json'))
# y
pr.register('http://(\S*.)?youtu(\.be/|be\.com/watch)\S+', Provider('http://www.youtube.com/oembed'))
pr.register('https://(\S*.)?youtu(\.be/|be\.com/watch)\S+', Provider('http://www.youtube.com/oembed?scheme=https&'))
pr.register('http://(\S*\.)?yfrog\.com/\S*', Provider('http://www.yfrog.com/api/oembed'))
# w
pr.register('http://\S+.wordpress.com/\S+', Provider('http://public-api.wordpress.com/oembed/'))
pr.register('https?://wordpress.tv/\S+', Provider('http://wordpress.tv/oembed/'))
return pr
def bootstrap_embedly(cache=None, registry=None, **params):
endpoint = 'http://api.embed.ly/1/oembed'
schema_url = 'http://api.embed.ly/1/services/python'
pr = registry or ProviderRegistry(cache)
# fetch the schema
contents = fetch(schema_url)
json_data = json.loads(contents)
for provider_meta in json_data:
for regex in provider_meta['regex']:
pr.register(regex, Provider(endpoint, **params))
return pr
def bootstrap_noembed(cache=None, registry=None, **params):
endpoint = 'http://noembed.com/embed'
schema_url = 'http://noembed.com/providers'
pr = registry or ProviderRegistry(cache)
# fetch the schema
contents = fetch(schema_url)
json_data = json.loads(contents)
for provider_meta in json_data:
for regex in provider_meta['patterns']:
pr.register(regex, Provider(endpoint, **params))
return pr
def bootstrap_oembedio(cache=None, registry=None, **params):
endpoint = 'http://oembed.io/api'
schema_url = 'http://oembed.io/providers'
pr = registry or ProviderRegistry(cache)
# fetch the schema
contents = fetch(schema_url)
json_data = json.loads(contents)
for provider_meta in json_data:
regex = provider_meta['s']
if not regex.startswith('http'):
regex = 'https?://(?:www\.)?' + regex
pr.register(regex, Provider(endpoint, **params))
return pr
|
Java
|
UTF-8
| 2,455 | 3.671875 | 4 |
[] |
no_license
|
/**
* Created by Artem_Mikhalevitch on 5/15/15.
*/
public class SeamCarver {
/**
* Given image.
*/
private Picture picture;
/**
* Constructor. Create a seam carver object based on the given picture.
*
* @param source picture
*/
public SeamCarver(Picture source) {
this.picture = source;
}
/**
* Current picture.
*
* @return current picture
*/
public Picture picture() {
return picture;
}
/**
* Width of current picture.
*
* @return width of current picture
*/
public int width() {
return picture.width();
}
/**
* Height of current picture.
*
* @return height of current picture
*/
public int height() {
return picture.height();
}
/**
* Energy of pixel at column x and row y.
*
* @return energy of pixel at column x and row y
*/
public double energy(int x, int y) {
validate(x, y);
throw new UnsupportedOperationException();
}
/**
* Sequence of indices for horizontal seam.
*
* @return sequence of indices for horizontal seam
*/
public int[] findHorizontalSeam() {
throw new UnsupportedOperationException();
}
/**
* Sequence of indices for vertical seam.
*
* @return sequence of indices for vertical seam.
*/
public int[] findVerticalSeam() {
throw new UnsupportedOperationException();
}
/**
* Remove horizontal seam from current picture/
*/
public void removeHorizontalSeam(int[] seam) {
this.validate(seam);
throw new UnsupportedOperationException();
}
/**
* Remove vertical seam from current picture/
*/
public void removeVerticalSeam(int[] seam) {
this.validate(seam);
throw new UnsupportedOperationException();
}
/**
* Checks for null.
*
* @throws NullPointerException
*/
private void validate(int[] seam) {
if (seam == null) {
throw new NullPointerException();
}
//todo validate for IllegalArgumentException
}
/**
* Checks for valid coordinates.
*
* @throws NullPointerException
*/
private void validate(int x, int y) {
if (x >= picture.width() || y >= picture.height()) {
throw new IndexOutOfBoundsException();
}
}
}
|
Java
|
UTF-8
| 265 | 2.53125 | 3 |
[] |
no_license
|
import java.io.FileWriter;
public class Sys {
Sys(Object x) {
System.out.println(x);
}
public static void print(Object x) {
System.out.print(x);
}
public static void println(Object x) {
System.out.println(x);
}
}
|
Java
|
UTF-8
| 1,676 | 3.28125 | 3 |
[] |
no_license
|
package hust.cs.javacourse.search.index.impl;
import hust.cs.javacourse.search.index.AbstractTerm;
import hust.cs.javacourse.search.index.AbstractTermTuple;
import java.util.Objects;
/**
* <pre>
* TermTuple是所有AbstractTermTuple抽象类的派生实现子类.
* 一个TermTuple对象为三元组(单词,出现频率,出现的当前位置).
* 当解析一个文档时,每解析到一个单词,应该产生一个三元组,其中freq始终为1(因为单词出现了一次).
* </pre>
*
*
*/
public class TermTuple extends AbstractTermTuple {
/**
* 缺省构造
*/
public TermTuple(){};
/**
* 有参构造函数
* @param term term
* @param curPos curPos
*/
public TermTuple(AbstractTerm term, int curPos){
this.term = term;
this.curPos = curPos;
}
/**
* 判断二个三元组内容是否相同
* @param obj :要比较的另外一个三元组
* @return 如果内容相等(三个属性内容都相等)返回true,否则返回false
*/
@Override
public boolean equals(Object obj) {
if(obj instanceof TermTuple){
return this.curPos == ((TermTuple)obj).curPos
&& Objects.equals(this.term,((TermTuple) obj).term);
}
return false;
}
/**
* 获得三元组的字符串表示
* @return : 三元组的字符串表示
*/
@Override
public String toString(){
StringBuffer buf = new StringBuffer();
buf.append( "{ term:"+term);
buf.append(",freq:"+freq);
buf.append(",curPos:"+curPos+" }\n");
return buf.toString();
}
}
|
Java
|
UTF-8
| 905 | 2.859375 | 3 |
[] |
no_license
|
package jp.co.careritz.service;
import jp.co.careritz.entity.currency.ICurrency;
import jp.co.careritz.entity.currency.impl.FiftyYen;
import jp.co.careritz.entity.currency.impl.FiveHundredYen;
import jp.co.careritz.entity.currency.impl.OneHundredYen;
import jp.co.careritz.entity.currency.impl.TenYen;
import jp.co.careritz.entity.currency.impl.ThousandYen;
public class CurrencyFactory {
public static ICurrency create(final Integer val) {
switch (val) {
case 10:
return new TenYen();
case 50:
return new FiftyYen();
case 100:
return new OneHundredYen();
case 500:
return new FiveHundredYen();
case 1000:
return new ThousandYen();
default:
throw new IllegalArgumentException("Create Currency Error.");
}
}
}
|
PHP
|
UTF-8
| 372 | 3.046875 | 3 |
[] |
no_license
|
<?php
/*
include ou iclude_once:
- O arquivo vai funcionar mesmo que existe algum erro.
*/
//include "inc/exemplo-01.php";
/*
require ou require_once:
- O arquivo deve obrigatóriamente existir e estar funcionando
corretamente.
*/
require_once "inc/exemplo-01.php";
require_once "inc/exemplo-01.php";
$resultado = somar(10, 3);
echo $resultado;
?>
|
C++
|
UTF-8
| 3,161 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
#include "papelaria.h"
#include "ui_papelaria.h"
Papelaria::Papelaria(QWidget *parent) :
QWidget(parent),
ui(new Ui::Papelaria)
{
ui->setupUi(this);
/*
* Cria conexão com banco de dados sqlite.
*----
* OBS..: enqunto rodando o app pela IDE,
* ele será iniciado um diretório acima.
* Ex:
* Será executado aqui | mas ele está
* 1 | aqui 2
* [...\Rascunhos\build-Aula20-Desktop_Qt_5_7_0_MinGW_32bit-Release\]release\
*
* Neste caso você deve por o .db neste diretório (1).
* Você podo alterar esse comportamento em
* Projects -> Build | (Run) -> Working Directory.
*
*/
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("Papelaria.db");
// tenta abrir conexão
if(! db.open()) {
QMessageBox::critical(this, "Erro no Banco de Dados", db.lastError().text(), QMessageBox::Cancel);
qApp->exit(-1);
} else {
// seta o objeto modelo
QSqlTableModel *model = new QSqlTableModel(this, db);
// seta a tabela
model->setTable("empregado");
ui->tableView->setModel(model);
// seleciona os dados da tabela
model->select();
}
}
Papelaria::~Papelaria()
{
delete ui;
}
// Botão "Inserir"
void Papelaria::on_pushButton_2_clicked()
{
if(ui->spinBox->text().isEmpty() || ui->lineEdit->text().isEmpty()
|| ui->doubleSpinBox->text().isEmpty())
QMessageBox::warning(this, "Atenção", "Dados Inválidos!");
else
{
#define BIND_WITH_INDEX
#ifdef BIND_WITH_INDEX
QSqlQuery qry("INSERT INTO empregado VALUES (?, ?, ?)", db);
qry.bindValue(0, ui->spinBox->value());
qry.bindValue(1, ui->lineEdit->text());
qry.bindValue(2, ui->doubleSpinBox->value());
#else
QSqlQuery qry("INSERT INTO empregado values(:id, :nome, :salario)", db);
qry.bindValue(":id", ui->spinBox->value());
qry.bindValue(":nome", ui->lineEdit->text());
qry.bindValue(":salario", ui->doubleSpinBox->value());
#endif
if(qry.exec())
QMessageBox::information(this, "Sucesso", "Query executado com sucesso!");
else
QMessageBox::warning(this, "Fracasso", "Query fracassou:<br><b>" + qry.lastError().text());
}
// atualiza a tabela
// OBS..: qobject_cast<R *>(T *) faz casts entre classes herdeiras de QOject
qobject_cast<QSqlTableModel *>(ui->tableView->model())->select();
}
// seta um ID aleatório
void Papelaria::on_pushButton_clicked()
{
ui->spinBox->setValue(getRandomID());
}
// obtem um número aleatório de 1000 até 9999
unsigned int Papelaria::getRandomID() const
{
static RandomEngine eng(std::time(nullptr));
static Random rnd(1000, 9999);
return rnd(eng);
}
void Papelaria::on_pushButton_3_clicked()
{
qApp->quit();
}
void Papelaria::on_pushButton_4_clicked()
{
qApp->aboutQt();
}
|
Java
|
UTF-8
| 657 | 2.59375 | 3 |
[] |
no_license
|
package com.mattkula.guesswhom.data.models;
import com.google.gson.annotations.Expose;
import java.io.Serializable;
/**
* Created by matt on 2/9/14.
*/
public class Answer implements Serializable, Comparable<Answer>{
public Answer(String name, String fb_id) {
this.name = name;
this.fb_id = fb_id;
}
@Expose
public String name;
@Expose
public String fb_id;
@Expose
public int position;
@Override
public int compareTo(Answer answer) {
if(this.position > answer.position)
return 1;
if(this.position < answer.position)
return -1;
return 0;
}
}
|
Python
|
UTF-8
| 940 | 3.828125 | 4 |
[] |
no_license
|
"""
scoring.py
----------
This module implements methods that help in the similarity scoring.
"""
def score(data, tag_a, tag_b):
""" This method returns the similarity score between two tags
based on 'Jaccard Index' method.
param: data(dict): 'tag' based bookmarks data
param: tag_a(string): a tag to compare
param: tag_b(string): another tag to compare with
"""
set_a = set(data[tag_a])
set_b = set(data[tag_b])
num = set_a.intersection(set_b)
den = set_a.union(set_b)
return (len(num) * 1.0) / len(den)
def rank(data, tag):
""" This method returns tags ordered by similarity scores with respect to
the 'tag'.
param: data(dict): 'tag' based bookmarks data
param: tag(string): the tag, whose similar tags we're searching for
"""
scores = [(score(data, tag, tag_), tag_) for tag_ in data if tag_ != tag]
scores.sort()
scores.reverse()
return scores
|
Java
|
UTF-8
| 305 | 2.015625 | 2 |
[] |
no_license
|
package monsterstack.io.partner.domain;
import lombok.Data;
@Data
public class GroupEntryOpportunity {
private Group group;
private Integer slotNumber;
public GroupEntryOpportunity(Group group, Integer slotNumber) {
this.group = group;
this.slotNumber = slotNumber;
}
}
|
Markdown
|
UTF-8
| 5,989 | 3.25 | 3 |
[] |
no_license
|
autoscale: true
# Form Submission & POST Requests
---
## What We Know So Far
* We can pass data to Express by using the URL as arguments
* The POST and PUT http method types are meant for creating and altering entities, respectively
* Using these arguments, we could put them in to SQL queries or other functions
* So how do we put all of this together?
---
## Bringing Back the `<form>` Element
* You should remember the `<input>` and `<form>` elements from previous lessons
* These handle user input and submission to the server, respectively
* The reason that a form, by default, refreshes the page when you hit enter / click a button is making a GET request with the input's data
* GET request parameters are sent either in the path, or in the query
---
## A `<form>` Example (html)

---
## A `<form>` Example (node)
* We then have access to those query parameters in Express, for use as variables (i.e. in this login function)
```js
// Render the login form
app.get("/search", function(req, res) {
let results = [];
// If they submitted the search, get results for rendering
if (req.query.query) {
results = getSearchResults(req.query.query);
}
res.render("search", {
result: results,
});
});
```
_The `getSearchResults` function here is a made up example, don't worry about what it does._
---
## Form Configuration via Attributes
* The form by default submits all of its inputs in a GET request as ?name=value to the current path
* We can change which path it submits to using the `action="/some/path"` attribute
* We can change the GET to a POST using the `method="post"` attribute (No PUT or DELETE)
*
```html
<form action="/login" method="post">
<input name="username" type="text"/>
<input name="password" type="password"/>
<button formmethod="post">
Submit
</button>
</form>
```
---
## Handling POST Requests
* Now that we can change the method from GET to POST, we should be using that when we want to create a new entity, rather than add some arguments to a GET
* However, POST requests send their data using the **body**, not the query parameters
* This is so that it can send complex data types that aren't limited by fitting in a URL
* This also keeps sensitive information (like a password) out of the URL, and hidden away
* But in order to handle body requests, we need to configure Express to use them
* Afterwards, they'll be available in `req.body`, just like `query` and `param`.
---
## Handling POST Requests (code)
```bash
# Install the body-parser module
npm install --save body-parser
```
```js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
// Configure your app to correctly interpret POST
// request bodies. The urlencoded one handles HTML
// <form> POSTs. The json one handles jQuery POSTs.
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
// Login endpoint expects username and
// password in the request's body
app.post("/login", function(req, res) {
if (login(req.body.username, req.body.password)) {
res.redirect("/home");
} else {
res.status(403).render("/login", {
error: "Incorrect username or password",
});
}
});
```
---
## Form Configuration via Buttons
* The `<button>` element can also add arguments using the `name` and `value` attributes, just like inputs
* You can also override the form's action and method with `formaction` and `formmethod`
* That way, one form can have two different actions based on which button is pressed
```html
<!-- edit-blog.ejs -->
<form action="/blog/<%- post.id %>" action="post">
<input name="title" type="text" value="<%- post.title %>"/>
<textarea name="content" value="<%- post.content %>"/>
<button name="save" value="1">Save</button>
<button name="delete" value="1">Delete</button>
</form>
```
```js
// app.js
app.post("/blog/:id", function(req, res) {
if (req.body.delete) {
deleteBlogPost(req.params.id);
}
else {
saveBlogPost(req.params.id, req.body.title, req.body.content);
}
});
```
---
## Succesful Redirects
* Often times when a form submit goes well, we want to take the user somewhere else
* Express will allow you to do this using `res.redirect("/new/path")`
* You can also add some query parameters if you want to indicate what happened
```js
app.post("/save", function() {
res.redirect("/home?saved=1");
});
app.get("/home", function(req, res) {
let notice = "";
if (req.query.saved) {
notice = "Save succesful!"
}
res.render("home", {
// Rendered somewhere in the template
notice: notice,
});
});
```
---
## Unsuccesful Submits
* On the flip side, sometimes things go wrong in a form submission
* Maybe a user forgot a field, put too much text, or tried to put letters in a number field
* In this case, we usually want to re-render the form, but with an error message displayed
```js
app.post("/conversation", function(req, res) {
if (req.body.message) {
// Redirect them back to app.get("/conversation")
res.redirect("/conversation?sent=1");
}
else {
// Re-render the conversation with an error message
res.render("conversation", {
error: "Message is required",
});
}
});
```
---
## Exercise: Make a Bulletin Board Form
* Using the Bulletin Board database and code we wrote from the previous class, let's make a form to submit to it
* Create a new template for the form page, and add the necessary elements to it
* Make a `post` Express route that can handle the form submission
* Send the parameters from the POST request to the function for making a new bulletin board post
* If the post is saved succesfully, redirect them back to the list page with a saved message
* If the post had errors (title too long, missing text) re-render the form with an error message
---
# Additional Reading
* [MDN's <form> element docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
* [MDN's <button> element docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button)
|
JavaScript
|
UTF-8
| 546 | 3.3125 | 3 |
[
"MIT"
] |
permissive
|
const produto = new Object
produto.nome = 'cadeira'
produto['marca do produto'] = 'Generica'
produto.preco = 220
console.log(produto)
delete produto.preco
delete produto['marca do produto']
console.log(produto)
const carro = {
modelo: 'A4',
valor: 89000,
proprietario: {
nome: 'Mateus',
idade: 21
},
calcularValorDoSeguro() {
//...
}
}
console.log(carro)
carro.proprietario.nome = 'Ronaldo'
carro.proprietario.idade = 48
console.log(carro)
delete carro.calcularValorDoSeguro
console.log(carro)
|
Shell
|
UTF-8
| 1,564 | 3.65625 | 4 |
[] |
no_license
|
#!/bin/bash
#结果储存文件夹
res="Result"
#过滤出值的个数
NUM=$1
#mdp文件,步骤数
STEEP = $2
#修改mdp文件
python modif.py md.mdp
#是否已存在Rsult文件夹
if [ -e ${res} ]
then
echo "开始运行"
else
echo "创建目录"${res}
mkdir ${res}
echo "创建完成,开始运行"
fi
for file in `ls mol2`; do
file_new="mol2/"${file}
python ./acpype.py -i ${file_new}
prefix=${file%.*2}
DIR=${prefix}.acpype
cd ${res}
echo "进入目录"${res}
mv ../${DIR} .
if [ -e ${prefix} ]; then
cd ${prefix}
echo "进入目录"${prefix}
else
mkdir ${prefix}
cd ${prefix}
echo "进入目录"${prefix}
fi
echo "运行Gromacs程序"
#Gromacs预处理命令
gmx grompp -f ../../md.mdp -c ../${DIR}"/"${prefix}_GMX.gro -p ../${DIR}"/"${prefix}_GMX.top -o ${prefix}.tpr
#正式运行MD
gmx mdrun -v -deffnm ${prefix}
#从轨迹文件中提取稳定构象帧
gmx trjconv -f ${prefix}.xtc -o ${prefix}_struc.xtc -dt 200
gmx eneconv -f ${prefix}.edr -o ${prefix}_struc.edr -dt 200
#提取稳定构象能量值及其对应帧数
echo "Total-Energy" | gmx energy -f ${prefix}_struc.edr -o ${prefix}_struc_edr.xvg
#运行过滤脚本
python ../../filter_edr.py -i ${prefix}_struc_edr.xvg -n ${NUM} -o yes -t ${prefix}.tpr -x ${prefix}.xtc
#清理文件
echo "需要清理文件吗?yes/no"
read -t 20 clea
if [ $clea -eq "yes" ]; then
rm ${prefix}.edr ${prefix}.xtc ${prefix}.tpr ${prefix}.cpt ${prefix}.log
echo "文件已清理"
else
echo "没有清理文件"
fi
echo "返回初始目录"
cd ../../
done
|
Markdown
|
UTF-8
| 455 | 3.203125 | 3 |
[] |
no_license
|
## Example 1
## Ok
```haskell
oddSquareSum :: Integer
oddSquareSum = sum (takeWhile (<10000) (filter odd (map (^2) [1..])))
```
## Ok
```haskell
oddSquareSum :: Integer
oddSquareSum = sum . takeWhile (<10000) . filter odd . map (^2) $ [1..]
```
## Better
```haskell
oddSquareSum :: Integer
oddSquareSum =
let oddSquares = filter odd $ map (^2) [1..]
belowLimit = takeWhile (<10000) oddSquares
in sum belowLimit
```
```haskell
```
|
Java
|
UTF-8
| 695 | 1.773438 | 2 |
[] |
no_license
|
package com.inhe.mdm.service;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
import com.inhe.build.result.PageBean;
import com.inhe.mdm.model.MdmAmLine;
import com.inhe.mdm.model.VtMdmAmLine;
public interface IMdmAmLineService {
public PageBean<VtMdmAmLine> queryList(VtMdmAmLine param, int pageNo, int pageSize);
public boolean insert(MdmAmLine mdmAmLine);
public boolean update(MdmAmLine mdmAmLine);
public VtMdmAmLine detail(VtMdmAmLine mdmAmLine);
public Boolean delete(MdmAmLine mdmAmLine);
public boolean switchType(MdmAmLine mdmAmLine);
public JSONObject upload(MultipartFile file, MdmAmLine mdmAmLine) throws Exception;
}
|
Python
|
UTF-8
| 3,660 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
import requests
from checks import AgentCheck
from dateutil import parser
class ObservatoryCheck(AgentCheck):
@staticmethod
def compose_tags(api_response, hostname):
tags = []
interesting_keys = [
'scan_id',
'grade',
'likelihood_indicator'
]
for key in interesting_keys:
tags.append('%s:%s' % (key, api_response[key]))
tags.append('hostname:%s' % hostname)
return tags
@staticmethod
def grade_to_dec(grade):
grade_map = {
'A+': 12,
'A': 11,
'A-': 10,
'B+': 9,
'B': 8,
'B-': 7,
'C+': 6,
'C': 5,
'C-': 4,
'D+': 3,
'D': 2,
'D-': 1,
'F': 0
}
return grade_map[grade] if grade in grade_map else 0
@staticmethod
def is_scan_ready(response):
return 'state' in response and response['state'] == "FINISHED"
def check(self, instance):
if 'host' not in instance:
self.log.error('Skipping instance, no host found.')
return
host = instance['host']
default_timeout = self.init_config.get('default_timeout', 5)
timeout = float(instance.get('timeout', default_timeout))
instance_tags = instance.get('tags', [])
is_hidden = instance.get('hidden', False)
api_url = instance.get('api_url', 'https://http-observatory.security.mozilla.org/api/v1')
response = self.scan(api_url=api_url, host=host, timeout=timeout, hidden=is_hidden)
if not self.is_scan_ready(response):
self.log.info('Observatory scan of %s is not finished yet, '
'skipping reporting until it is complete.' % host)
return
tags = self.compose_tags(response, host) + instance_tags
self.report_metrics(response, tags)
self.log.info('Host %s Observatory score is %s' % (host, response['grade']))
def report_metrics(self, response, tags):
keys = [
'tests_quantity',
'tests_passed',
'tests_failed',
'score'
]
for key in keys:
self.gauge('mozilla.observatory.http.%s' % key, response[key], tags=tags)
self.gauge('mozilla.observatory.http.grade', self.grade_to_dec(response['grade']), tags=tags)
self.gauge('mozilla.observatory.http.score', response['score'], tags=tags)
duration = self.get_scan_duration(response['start_time'], response['end_time'])
self.gauge('mozilla.observatory.http.scan_duration', duration, tags=tags)
@staticmethod
def get_scan_duration(start, end):
start = parser.parse(start)
end = parser.parse(end)
duration = end - start
return duration.total_seconds()
def scan(self, api_url, host, timeout, hidden=False):
url = "%s/analyze" % api_url
r = requests.post(url, params={'host': host, hidden: hidden}, timeout=timeout)
if r.status_code != 200:
self.log.error('URL %s responded with status code %s, unable to continue.' % (url, r.status_code))
return
json = r.json()
return json
if __name__ == '__main__':
check, instances = ObservatoryCheck.from_yaml('/etc/dd-agent/conf.d/observatory.yaml')
for instance in instances:
print "\nRunning the check against host: %s" % (instance['host'])
check.check(instance)
if check.has_events():
print 'Events: %s' % (check.get_events())
print 'Metrics: %s' % (check.get_metrics())
|
Java
|
UTF-8
| 2,815 | 2.125 | 2 |
[] |
no_license
|
package com.example.jimi.mystroke.tasks;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import com.example.jimi.mystroke.AppDatabase;
import com.example.jimi.mystroke.Globals;
import com.example.jimi.mystroke.models.ExerciseImage;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import static android.content.ContentValues.TAG;
/**
* Created by jimi on 17/03/2018.
* TODO is this needed?
*/
public class DownloadImagesTask extends AsyncTask<String, Void, List<Bitmap>> {
private AppDatabase appDatabase;
private AsyncResponse asyncResponse;
public final static int var = 19;
public DownloadImagesTask(Context context, AsyncResponse asyncResponse) {
appDatabase = AppDatabase.getDatabase(context);
this.asyncResponse = asyncResponse;
}
@Override
protected List<Bitmap> doInBackground(String... ids) {
/*HttpURLConnection con = null;
List<Bitmap> bitmaps = new ArrayList<Bitmap>();
try {
String urlString = Globals.getInstance().getFileDispUrl().concat(Globals.getInstance().getLoadImageFD());
for (String id : ids) {
String fullText = "";
urlString += "?i=" + id;
URL url = new URL(urlString);
con = (HttpURLConnection) url.openConnection();
InputStream is = new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
do {
line = br.readLine();
fullText += line;
} while (line != null);
JSONObject jsonObject = new JSONObject(fullText);
jsonObject = (JSONObject) jsonObject.get("success");
byte[] bytes = Base64.decode(fullText, Base64.DEFAULT);
bitmaps.add(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return null;
} finally {
if(con != null) {
con.disconnect();
}
}
if(!bitmaps.isEmpty()) {
return bitmaps;
} else {
return null;
}*/
return null;
}
@Override
protected void onPostExecute(List<Bitmap> bitmaps) {
asyncResponse.respond(var, bitmaps);
}
}
|
Python
|
UTF-8
| 1,994 | 2.515625 | 3 |
[] |
no_license
|
"""First attempt at GHZ states with Viktor
"""
##------------------PREAMBLE-------------------##
from stdlib import data_loader
#data handling
from stdlib import FitTemplate, fit_lorentzian
#fitting
from stdlib import PlotTemplate
#plotting
import numpy as np
import matplotlib.pyplot as plt
#packages
##------------------PARAMETERS--------------------##
data_dir = "X:\\measurements\\trics_data\\2021-02-24\\"
savedir = "C:\\Users\\James\\OneDrive - OnTheHub - The University of Oxford\\phd\\images\\2021-02-24-Wavepacket\\"
folders = ["151615/", "151912/"]
filenames = ["APD1.txt", "APD2.txt"]
data_objects = data_loader(filenames, folders, data_dir, data_column=1)
#PMT data objects
pt = PlotTemplate((1,1))
ax = pt.generate_figure()
##------------------ANALYSIS--------------------##
##=================##
#Rabi frequency extraction
d1 = data_objects[0][1]
freq1 = d1.df['transitions.DP_393_3.frequency']
probs1 = d1.df[' APD(sum)']
ax.plot(freq1, probs1, c = pt.colours[0])
d3 = data_objects[1][1]
d3.df = d3.df.iloc[range(40, 60)]
freq3 = d3.df['transitions.DP_393_3.frequency']
probs3 = d3.df[' APD(sum)']
# plt.plot(probs3)
# plt.show()
# exit()
ax.plot(freq3, probs3, c = pt.colours[1])
probs1 = probs1.to_numpy()
freq1 = freq1.to_numpy()
probs3 = probs3.to_numpy()
freq3 = freq3.to_numpy()
ft = FitTemplate(fit_lorentzian)
ft.parameters.add("A", 0.01)
ft.parameters.add("Gamma", 0.1)
ft.parameters.add("x_0", 324)
ft.do_minimisation(freq1, probs1)
ft.print_fit_result()
params = ft.get_opt_parameters()
ft.plot_fit(freq1, probs1, ax = ax, c = pt.colours[0], label = "High Power {}".format(round(params['x_0'],2)))
ft.do_minimisation(freq3, probs3)
ft.print_fit_result()
params = ft.get_opt_parameters()
ft.plot_fit(freq3, probs3, ax = ax, c = pt.colours[1], label = "Low Power {}".format(round(params['x_0'],2)))
ax.set_title("Raman Spectrum")
ax.set_xlabel("Frequency")
ax.set_ylabel("Photon Probability")
plt.savefig(savedir + "RamanSpectrum.png")
plt.show()
|
C#
|
UTF-8
| 1,881 | 2.953125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace FilesServer.Package
{
/// <summary>
/// Klasa metod komunikacji
/// </summary>
public class ComunicateFunctions
{
/// <summary>
/// Funkcja wysyłająca komunikaty poprzez Socket
/// </summary>
/// <param name="address">Adres zdalnego komputera</param>
/// <param name="port">Port na zdalnym komputerze</param>
/// <returns>Zwraca odebrany pakiet</returns>
public NetPackage SendPackageBySocket(string address, int port, NetPackage packageSend, string dirName)
{
NetPackage receivedPackage = null;
try
{
IPAddress[] ipAddress = Dns.GetHostAddresses(address);
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], port);
using (Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
clientSock.SendTimeout = 300000; //infinite //clientSock.SendTimeout = 300000;
clientSock.Connect(ipEnd);
#region Send request
SendReceiveFunctions.SendNetPackage2(packageSend, clientSock);
#endregion
#region Read respond
receivedPackage = SendReceiveFunctions.ReceiveNetPackage2(clientSock, dirName);
#endregion
clientSock.Disconnect(true);
}
}
catch(Exception ex)
{
receivedPackage = new NetPackage();
receivedPackage.StringData = ex.ToString();
}
return receivedPackage;
}
}
}
|
Markdown
|
UTF-8
| 3,010 | 3.3125 | 3 |
[] |
no_license
|
### (上)
1.在终端` username@hostname$ `或` root@hostname # `,\$表示普通用户,#表示管理员用户 root。
2.shell 脚本通常以 shebang[[1\]](https://gitbook.cn/gitchat/geekbook/5b1f6242fb19f86e62cae899/topic/5b1fabc852823b7111033699#note1) 起始:` #!/bin/bash `
shebang 是一个文本行,其中`#!`位于解释器路径之前。/bin/bash 是 Bash 的解释器命令路径。bash 将以`#`符号开头的行视为注释。脚本中只有第一行可以使用 shebang 来定义解释该脚本所使用的解释器。
3.脚本的执行方式有两种:
(1) 将脚本名作为命令行参数:
```
bash myScript.sh
```
(2) 授予脚本执行权限,将其变为可执行文件:
```
chmod 755 myScript.sh
./myScript.sh.
```
如果将脚本作为`bash`的命令行参数来运行,那么就用不着使用 shebang 了。可以利用 shebang 来实现脚本的独立运行。可执行脚本使用 shebang 之后的解释器路径来解释脚本。
使用`chmod`命令赋予脚本可执行权限:
```
$ chmod a+x sample.sh
```
该命令使得所有用户可以按照下列方式执行该脚本:
```
$ ./sample.sh #./表示当前目录
```
或者
```
$ /home/path/sample.sh #使用脚本的完整路径
```
内核会读取脚本的首行并注意到 shebang 为`#!/bin/bash`。它会识别出`/bin/bash`并执行该脚本:
```
$ /bin/bash sample.sh
```
4.echo的单引号和双引号的区别?
(1)单引号和不加引号是一样的效果
(2)单引号不会对特殊字符解释
5.设置输出字体颜色
文本颜色是由对应的色彩码来描述的。其中包括:重置=0,黑色=30,红色=31,绿色=32,黄色=33,蓝色=34,洋红=35,青色=36,白色=37。
要打印彩色文本,可输入如下命令:
```
echo -e "\e[1;31m This is red text \e[0m"
```
其中`\e[1;31m`是一个转义字符串,可以将颜色设为红色,`\e[0m`将颜色重新置回。只需要将`31`替换成想要的色彩码就可以了。
对于彩色背景,经常使用的颜色码是:重置=0,黑色=40,红色=41,绿色=42,黄色=43,蓝色=44,洋红=45,青色=46,白色=47。
要设置彩色背景的话,可输入如下命令:
```
echo -e "\e[1;42m Green Background \e[0m"
```
这些例子中包含了一些转义序列。可以使用`man console_codes`来查看相关文档。
注:
[[1\]](https://gitbook.cn/gitchat/geekbook/5b1f6242fb19f86e62cae899/topic/5b1fabc852823b7111033699#note1) shebang 这个词其实是两个字符名称(sharp-bang)的简写。在 Unix 的行话里,用 sharp 或 hash(有时候是 mesh)来称呼字符“`#`”,用 bang 来称呼惊叹号“`!`”,因而 shebang 合起来就代表了这两个字符。详情请参考http://en.wikipedia.org/wiki/Shebang_(Unix)。(注:书中脚注均为译者注。)
[[2\]](https://gitbook.cn/gitchat/geekbook/5b1f6242fb19f86e62cae899/topic/5b1fabc852823b7111033699#note1) shell 不执行脚本中的任何注释部分。
|
Markdown
|
UTF-8
| 808 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
# mflooc
Predicting The Most Dangerous Areas For Flood Disasters Using NASA EarthData Many areas around the world are affected by flood and other water related disasters due to rise in earths temperature, climate change and many other factors. Most of these risky areas are in a zone called the 10m Low Elevation Zone. But there are too many areas in this zone. So non-profit organizations can not help all of them. We analyse the mortality risk, population density, economic damage, frequency and distribution of flood occurrences and various other data to find out and categorize the most risky areas in the 10m Low Elevation Zone. Then we present the results visually and in an easily accessible application, So that any related authority can easily find out the areas that require their help the most.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.