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
| 870 | 3.203125 | 3 |
[] |
no_license
|
// In a new Windows Forms Application, drop a GroupBox with a ComboBox and a CheckBox inside
// Then drop a TextBox outside the ComboBox. Then copy-paste.
// this goes somewhere in your project
public static class handlerClass
{
public static string ControlChanged(Control whatChanged)
{
return whatChanged.Name;
}
}
// And then you go like this in the Load event of the GroupBox container
void Form1_Load(object sender, EventArgs args)
{
foreach (Control c in groupBox1.Controls)
{
if (c is ComboBox)
(c as ComboBox).SelectedValueChanged += (s, e) => { textBox1.Text = handlerClass.Handle(c); };
if (c is CheckBox)
(c as CheckBox).CheckedChanged += (s, e) => { textBox1.Text = handlerClass.Handle(c); }; }
}
}
|
Python
|
UTF-8
| 7,638 | 2.6875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 17 17:35:51 2014
@author:Kristof Govaerts
Biomedical MRI Unit
KU Leuven
u0091609
Container class and functions for blood vessel analysis. Initiating an instance
of the VesselSkeleton class allows you to easily run various functions and
visualize graphs.
"""
import os
import nibabel as nib
import pylab as pl
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from ReadInput import *
import math
class VesselSkeleton:
def __init__(self, name, tEXT='_VesselPars', thresh=0):
self.name=name
Img=nib.load(name+'.img')
self.img=np.squeeze(Img.get_data())
if thresh!=0:
self.img[self.img!=96]=0 #imageJ stores longest most efficient path at value 96 (not 255). Go figure.
else:
self.avthickness=np.mean(self.img[self.img>0])
self.affine=Img.get_affine()
self.start=list_values(read_line('StartPoint=', name+tEXT))
self.end=list_values(read_line('EndPoint=', name+tEXT))
self.res=list_values(read_line('Resolution=', name+tEXT))
self.world_pos=list_values(read_line('WorldPos=', name+tEXT))
self.total_thickness=list_values(read_line('MeanThickness=', name+tEXT))[0]
self.total_stdev=list_values(read_line('ThicknessVariance=', name+tEXT))[0]
def tortuosity(self):
self.pts=im_to_points(self.img)
self.coords=pts_to_coords(self.pts, self.res, self.world_pos)
tdist, edist, fraction, points=curve_length(tuple(map(tuple, self.coords)), start=None, end=None, return_pts=True)
edist=dist(points[0], points[-1]) #comment out if needed?
tort=tdist/edist
self.points=points
return tort, tdist, edist, fraction, points
def save_tracked_pts(self):
tp=(np.array(self.points)-self.world_pos)/self.res
t_array=np.zeros(self.img.shape)
for i in range(len(tp)):
t_array[tuple(tp[i].astype('int'))]=i+1
tpname=self.name+'_points.nii'
tpim=nib.Nifti1Image(t_array, self.affine)
nib.save(tpim, tpname)
print "Tracked points saved in", tpname
def plot2D(self, dim=0, plot_traveled=True):
'''Plots a 2D projection ofthe vessel as points on a scatterplot.'''
if plot_traveled:
pts=np.array(self.points)
else:
pts=self.coords
c=[0,1,2]
c.pop(dim)
pl.plot(pts[:,c[0]], pts[:,c[1]], '-o')
wp1,wp2=self.world_pos[c[0]], self.world_pos[c[1]]
pl.xlim(wp1,self.res[c[0]]*self.img.shape[c[0]]+wp1)
pl.ylim(wp2,self.res[c[1]]*self.img.shape[c[1]]+wp2)
l=['x','y','z']
l.pop(dim)
pl.xlabel=l[0]
pl.ylabel=l[1]
def plot3D(self):
fig=pl.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(self.coords[:,0],self.coords[:,1],self.coords[:,2], '-o', c='b')
wp1,wp2,wp3=self.world_pos
ax.set_xlim(wp1,self.res[0]*self.img.shape[0]+wp1)
ax.set_ylim(wp2,self.res[1]*self.img.shape[1]+wp2)
ax.set_zlim(wp3,self.res[2]*self.img.shape[2]+wp3)
pl.show()
def im_to_points(im):
'''Converts a binary image to a list of points.'''
a,b,c=np.where(im>0)
return zip(a,b,c)
def pts_to_coords(pts, res, world_pos):
'''Converts a list of points to a list of world coordinates.'''
return np.array(pts) * res + world_pos
def dist(a,b):
'''Returns the Euclidian distance between two points.'''
if len(a) != len(b):
raise ValueError('Input points have an inequal number of coordinates.')
d=[(b[i] - a[i])**2 for i in range(len(a))]
return np.sqrt(sum(d))
def find_closest(point, pointlist):
'''Finds the closest point in a given point list to the input point.'''
d=np.inf
for p in pointlist:
nd=dist(point, p)
if nd<d:
d=nd
closest=p
return closest
def curve_length(pointlist, start=None, end=None, return_pts=False):
'''Traverses all points in a list and measures the cumulative length of
the lines connecting each point and its closest neighbour. The endpoint is
given as a boundary so that the algorithm knows when to stop. Tortuosity
values can get very large if spurious points past the end point are included.
Inputs:
pointlist: List or array of x,y,z coordinates. Can be matrix indices or world coordinates.
start: Tuple of x,y,z coordinates of start point. Algorithm starts here.
end: Tuple of x,y,z coordinates of end point. Algorithm terminates here.
return_pts: Returns a list of all points traversed (in order) if True.
Outputs:
cum_dist: Length of the curve tracked through the input points.
eucl_dist: Euclidian distance between start and end points.
fraction_traversed: Fraction of points in the list that were used. If
this fraction is low, there were many points past
the end point and there may have been errors.
points: (optional): Ordered list of all points that were used.'''
plist=list(pointlist)#copy list
if start == None:
minpoint=np.array(pointlist)[:,2].argmin()
cpoint=plist[minpoint]
else:
cpoint=start
if end == None:
endpoint=np.array(pointlist)[:,2].argmax()
end=plist[endpoint]
plist.append(end)
s=np.array(cpoint)
cum_dist=0
points=[]
for x in range(len(plist)):
repeat=False
point=find_closest(cpoint, plist)
fraction_traversed=float(len(points))/(float(len(pointlist)))
d=dist(cpoint, point)
if fraction_traversed > .90 and d >= dist(cpoint, s):
break
cum_dist+=d
if point == end:
break
if return_pts:
points.append(cpoint)
cpoint=plist.pop(plist.index(point))
eucl_dist=dist(points[0], points[-1])
outs=(cum_dist, eucl_dist, fraction_traversed)
if return_pts:
outs+=tuple([points])
return outs
def curvature(a,b,c):
'''cosine rule: AC**2=AB**2 + BC**2 -2*AB*BC*cos(alpha)
acos((AC**2-AB**2-BC**2)/-2*AB*BC)'''
a=tuple(a)
b=tuple(b)
c=tuple(c)
d=(dist(a,c)**2-dist(a,b)**2-dist(b,c)**2)/(-2*dist(a,b)*dist(b,c))
if d <= -1.0:
c=math.pi/2
else:
c=math.acos(d)
return math.pi - c
def cumul_curvature(pointlist, start, end):
global p1,p2,p3
plist=list(pointlist)#copy list
plist.append(end)
p1=plist.pop(plist.index(find_closest(start, plist)))
p2=plist.pop(plist.index(find_closest(p1, plist)))
cum_curv=0
points=[]
for x in range(len(plist)):
p3=plist.pop(plist.index(find_closest(p2, plist)))
if p3 == end:
break
p3=np.array(p3)
print curvature(p1,p2,p3)
cum_curv+=curvature(p1,p2,p3)
p1=np.array(p2)
p2=np.array(p3)
eucl_dist=dist(start, p3)
outs=(cum_curv, eucl_dist)
return outs
def main():
os.chdir('C:\Users\u0091609\Desktop\TS_Stroke_Sham_BFC\LMCA\Skeleton')
v=VesselSkeleton('BFCTS_stroke_sham_32b_ed1_6_1_BM_M4_FS_LMCA')
a,b,c,d,e=v.tortuosity()
v.plot3D()
if __name__ == '__main__':
main()
|
C++
|
UTF-8
| 1,982 | 2.625 | 3 |
[] |
no_license
|
#include "hero.h"
#include <iostream>
#include "mainwindow.h"
#include <QTransform>
#include "opponent.h"
#include <QApplication>
#include <QGraphicsTextItem>
Hero::Hero(int role, int id, const QString &name, int x, int y, int healthPercentage, int magicPercentage):Tile(x, y, 0)
{
this->_id = id;
this->_role = role;
this->_healthBar = new StatusBar(StatusBar::HealthBar, this);
this->_healthBar->setTransform(QTransform().translate(0, -12));
this->_healthBar->setPercentage(healthPercentage);
this->_magicBar = new StatusBar(StatusBar::MagicBar, this);
this->_magicBar->setTransform(QTransform().translate(0, -5));
this->_magicBar->setPercentage(magicPercentage);
this->setPos(this->getXPos() * SCALE_FACTOR, this->getYPos() * SCALE_FACTOR);
if (role == PLAYER_ROLE_MAGE) {
this->setPixmap(QPixmap(":/world/angry-bird-yellow-icon.png"));
} else if (role == PLAYER_ROLE_PRIEST) {
this->setPixmap(QPixmap(":/world/angry-bird-green-icon.png"));
} else if (role == PLAYER_ROLE_WORRIOR) {
this->setPixmap(QPixmap(":/world/angry-bird-icon.png"));
}
//set up the name label
_nameLabel = new QGraphicsTextItem(name,this);
_nameLabel->setDefaultTextColor(QColor(255, 0, 0));
QFont font;
font.setBold(true);
_nameLabel->setFont(font);
_nameLabel->setTransform(QTransform().translate(0, 24));
}
Hero::~Hero()
{
qDebug() << "dtor of Hero";
delete _nameLabel;
delete _healthBar;
delete _magicBar;
}
void Hero::setWorld(WorldView *world)
{
this->_world = world;
this->_magic.setWorld(world);
}
HeroMagic &Hero::getMagic()
{
return _magic;
}
void Hero::setHealthPercentage(int percentage)
{
this->_healthBar->setPercentage(percentage);
}
void Hero::setMagicPercentage(int percentage)
{
this->_magicBar->setPercentage(percentage);
}
int Hero::getRole() const
{
return _role;
}
int Hero::getId()
{
return _id;
}
|
PHP
|
UTF-8
| 22,521 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
/**
* CodeGen short summary.
*
* CodeGen description.
*
* @version 1.0
* @author Jasim.Uddin
*/
require_once('JwtUtil.php');
require_once('StringBuilder.php');
class CodeGen
{
//private $navList;
private $mControllers;
private $layoutControllers;
private $componentsCSS;
public $app;
public $root="./";
public $defaultNavigation="";
public $has_template_authorization=FALSE;
public function __construct($jwtApp=null){
$this->app=$jwtApp;
$this->componentsCSS= new StringBuilder();
$this->layoutControllers=array();
$this->mControllers=array();
}
public function CreateItem($name, $mode)
{
JwtUtil::makeDirectory($this->root."Scripts");
JwtUtil::makeDirectory($this->root."Scripts/Components");
JwtUtil::makeDirectory($this->root."Scripts/Directives");
JwtUtil::makeDirectory($this->root."Scripts/Modules");
$path = $this->root;
switch ($mode)
{
case "Widgets":
$path .= "Scripts/Components/" . $name;
JwtUtil::makeDirectory($path);
$path = $this->root . "Scripts/Components/$name/$name"."Ctrl.js";
JwtUtil::putContent($path, $this->getEmptyController($name));
$path = $this->root . "Scripts/Components/$name/$name" . "Svc.js";
JwtUtil::putContent($path, $this->getEmptyService($name));
$path = $this->root . "Scripts/Components/$name/$name" . ".html";
JwtUtil::putContent($path, "<h3>widget Name : {{vm.title}}</h3>");
break;
case "Components":
$path .= "Scripts/Directives/" . $name;
JwtUtil::makeDirectory($path);
$path = $this->root ."Scripts/Directives/$name/$name" . ".js";
JwtUtil::putContent($path, $this->getEmptyDirective($name));
$path = $this->root ."Scripts/Directives/$name/$name" . ".html";
JwtUtil::putContent($path, "<b>Hello world</b>");
$path = $this->root . "Scripts/Directives/$name/$name" . ".css";
JwtUtil::putContent($path, "/*css goes here*/");
break;
case "Modules":
if ($name == "app") return;
$path .= "Scripts/Modules/" . $name;
JwtUtil::makeDirectory($path);
$path = $this->root . "Scripts/Modules/$name/$name" . ".js";
JwtUtil::putContent($path, $this->getEmptyModule($name));
break;
}
return " mamma kam oia geche";
}
public function execute(){
JwtUtil::makeDirectory($this->root."Scripts");
JwtUtil::makeDirectory($this->root."Scripts/Components");
JwtUtil::makeDirectory($this->root."Scripts/Layouts");
$sb=new StringBuilder();
$sb->appendLine()
->append("export default function config(stateprovider, routeProvider){");
if(!JwtUtil::IsNullOrEmptyString($this->defaultNavigation))
{
$sb->appendLine()->appendTab()
->appendFormat( "routeProvider.otherwise('%s');", $this->defaultNavigation)
->appendLine();
}
$this->setLayout($sb);
$this->setNavigation($sb);
$sb->appendLine()
->append("}")
->appendLine()
->append("config.\$inject=['\$stateProvider', '\$urlRouterProvider'];")
->appendLine();
JwtUtil::putContent($this->root . "Scripts/config.js", $sb->toString());
$this->genAllControllers();
$this->genAllServices();
$this->genAppDirectives();
$dir = JwtUtil::getSubDirectories($this->root . "Scripts/Modules");
foreach ($dir as $name)
{
if (JwtUtil::fileExists($this->root. "Scripts/Modules/$name/$name.css", $name, $name))
{
$this->componentsCSS->append("@import '../Scripts/Modules/$name/$name.css';")
->appendLine();
}
}
JwtUtil::putContent($this->root . "Content/components.css", $this->componentsCSS->toString());
}
private function setLayout($sb){
foreach ($this->app->Layouts as $layout)
{
JwtUtil::makeDirectory( $this->root . "Scripts/Layouts/" . $layout['LayoutName']);
$sb->appendLine()
->appendTab()
->appendFormat("stateprovider.state('%s'", $this->getStateName($layout))
->append(",{abstract:true,")
->appendFormat("url:'/%s'", $layout['LayoutName']);
$PathString =$this->root . "Scripts/Layouts/".$layout['LayoutName']."/".$layout['LayoutName'].".html";
if (!JwtUtil::fileExists($PathString))
{
JwtUtil::putContent($PathString, "<h3>Layout Name :". $layout['LayoutName']. "</h3><div ui-view></div>");
}
$sb->append(",templateUrl:" . $this->getTemplatePath("'Scripts/Layouts/".$layout['LayoutName']."/".$layout['LayoutName'].".html'", $layout['LayoutName'] . "__LAYOUT__"));
$PathString = $this->root . sprintf("Scripts/Layouts/%s/%sCtrl.js", $layout['LayoutName'],$layout['LayoutName']);
if (!JwtUtil::fileExists($PathString))
{
JwtUtil::putContent($PathString, $this->getEmptyControllerForLayout($layout['LayoutName']));
}
$sb->appendFormat(",controller:'%sCtrl as vm'", $layout['LayoutName']);
$this->layoutControllers[]=$layout['LayoutName'];
$sb->append("});");
}
}
private function getParamName($p)
{
if (JwtUtil::startsWith($p,"/:")){ return $p;}
if (JwtUtil::startsWith($p,":")) return '/' . $p;
return "/:" . $p;
}
private function setNavigation($sb){
$sb->appendLine();
if(!isset($this->app->Navigations)){return;}
foreach ($this->app->Navigations as $item)
{
$createNew = false;
if (!JwtUtil::folderExists( $this->root . "Scripts/Components/" . $item['WidgetName']))
{
$createNew = true;
}
JwtUtil::makeDirectory($this->root . "Scripts/Components/" . $item['WidgetName']);
$sb->appendLine()->appendTab();
$sb->appendFormat("stateprovider.state('%s'", $this->getNavigationStateName($item));
$sb->append(",{");
$sb->appendFormat("url:'/%s%s'", $item['NavigationName'], JwtUtil::IsNullOrEmptyString($item['ParamName']) ? "" : $this->getParamName($item['ParamName']));
$view = $item['Views'];
if (isset($view) && count($view)>0)
{
$sb->append(",views:{");
$isFirst = true;
foreach ($view as $item2)
{
if ($isFirst)
$sb->append("'" . $item2['ViewName'] . "':{");
else
$sb->append(",'" . $item2['ViewName'] . "':{");
if (!JwtUtil::IsNullOrEmptyString($item2['WidgetName']))
{
$PathString = $this->root . sprintf("Scripts/Components/%s/%s.html", $item2['WidgetName'],$item2['WidgetName']);
if (!JwtUtil::fileExists($PathString))
{
JwtUtil::putContent($PathString, "<h3>widget Name : {{vm.title}}</h3>");
}
$sb->append("templateUrl:" . $this->getTemplatePath(sprintf("'Scripts/Components/%s/%s.html'", $item2['WidgetName'],$item2['WidgetName']), $item2['WidgetName']));
$this->mControllers[]=$item2['WidgetName'];
$PathString = $this->root . sprintf("Scripts/Components/%s/%sCtrl.js", $item2['WidgetName'], $item2['WidgetName']);
if (JwtUtil::fileExists($PathString))
{
$sb->appendFormat(",controller:'%sCtrl as vm'", $item2['WidgetName']);
}
}
$sb->append("}");
$isFirst = false;
}
$sb->append("}");
}
if (!JwtUtil::IsNullOrEmptyString($item['WidgetName']))
{
if ($createNew)
{
$PathString = $this->root . sprintf("Scripts/Components/%s/%s.html", $item['WidgetName'], $item['WidgetName']);
JwtUtil::putContent($PathString, "<h3>widget Name : {{vm.title}}</h3>");
$PathString = $this->root . sprintf("Scripts/Components/%s/%sCtrl.js", $item['WidgetName'], $item['WidgetName']);
JwtUtil::putContent($PathString, $this->getEmptyController($item['WidgetName']));
$PathString = $this->root . sprintf("Scripts/Components/%s/%sSvc.js", $item['WidgetName'], $item['WidgetName']);
JwtUtil::putContent($PathString,$this->getEmptyService($item['WidgetName']));
}
$PathString =$this->root . sprintf("Scripts/Components/%s/%s.html", $item['WidgetName'], $item['WidgetName']);
if (JwtUtil::fileExists($PathString))
{
$sb->append(",templateUrl:" . $this->getTemplatePath(sprintf("'Scripts/Components/%s/%s.html'", $item['WidgetName'], $item['WidgetName']), $item['WidgetName']));
}
$PathString = $this->root . sprintf("Scripts/Components/%s/%sCtrl.js", $item['WidgetName'], $item['WidgetName']);
if (JwtUtil::fileExists($PathString))
{
$sb->appendFormat(",controller:'%sCtrl as vm'", $item['WidgetName']);
}
$this->mControllers[]=$item['WidgetName'];
}
$sb->Append("});");
}
}
private function genAllControllers(){
$list = array_unique($this->mControllers);
$sb = new StringBuilder();
$directoryName = "Components";
foreach ($list as $item)
{
if (JwtUtil::fileExists($this->root .sprintf("Scripts/Components/%s/%sCtrl.js", $item, $item)))
{
$sb->AppendLine();
$sb->AppendFormat("import %s from 'Scripts/%s/%s/%sCtrl.js';", $item, $directoryName, $item, $item);
}
}
$list =array_unique($this->layoutControllers);
$directoryName = "Layouts";
foreach ($list as $item)
{
if (JwtUtil::fileExists($this->root . sprintf("Scripts/Layouts/%s/%sCtrl.js", $item, $item)))
{
$sb->appendLine();
$sb->appendFormat("import %s from 'Scripts/%s/%s/%sCtrl.js';", $item, $directoryName, $item, $item);
}
}
$sb->appendLine();
$sb->appendLine();
$sb->appendFormat("var moduleName='%s.controllers';", $this->app->Name);
$sb->appendLine();
$sb->appendLine();
$sb->append("angular.module(moduleName,[])");
$list = array_unique($this->mControllers);
foreach ($list as $item)
{
if (JwtUtil::fileExists($this->root . sprintf("Scripts/Components/%s/%sCtrl.js", $item, $item)))
{
$sb->appendLine();
$sb->appendFormat(".controller('%sCtrl', %s)", $item, $item);
}
if (JwtUtil::fileExists(sprintf($this->root . "Scripts/Components/%s/%s.css", $item, $item)))
{
$this->componentsCSS->appendFormat("@import '../Scripts/Components/%s/%s.css';", $item, $item);
$this->componentsCSS->appendLine();
}
}
$list = array_unique($this->layoutControllers);
foreach ($list as $item)
{
if (JwtUtil::fileExists($this->root . sprintf("Scripts/Layouts/%s/%sCtrl.js", $item, $item)))
{
$sb->appendLine();
$sb->appendFormat(".controller('%sCtrl', %s)", $item, $item);
}
if (JwtUtil::fileExists(sprintf($this->root . "Scripts/Layouts/%s/%s.css", $item, $item)))
{
$this->componentsCSS->appendFormat("@import '../Scripts/Layouts/%s/%s.css';", $item, $item);
$this->componentsCSS->appendLine();
}
}
$sb->append(";");
$sb->appendLine();
$sb->appendLine();
$sb->append("export default moduleName;");
JwtUtil::putContent($this->root . "Scripts/app.controllers.js", $sb->toString());
}
private function genAllServices(){
$list = array_unique($this->mControllers);
$sb = new StringBuilder();
$directoryName = "Components";
foreach ($list as $item)
{
if (JwtUtil::fileExists($this->root . sprintf("Scripts/Components/%s/%sSvc.js", $item,$item)))
{
$sb->appendLine();
$sb->appendFormat("import %s from 'Scripts/%s/%s/%sSvc.js';", $item, $directoryName,$item,$item);
}
}
$list =array_unique($this->layoutControllers);
$directoryName = "Layouts";
foreach ($list as $item)
{
if (JwtUtil::fileExists($this->root . sprintf("Scripts/Layouts/%s/%sSvc.js", $item, $item)))
{
$sb->appendLine();
$sb->appendFormat("import %s from 'Scripts/%s/%s/%sSvc.js';", $item, $directoryName,$item,$item);
}
}
$sb->appendLine();
$sb->appendLine();
$sb->appendFormat("var moduleName='%s.services';", $this->app->Name);
$sb->appendLine();
$sb->appendLine();
$sb->append("angular.module(moduleName,[])");
$list =array_unique($this->mControllers);
foreach ($list as $item)
{
if (JwtUtil::fileExists($this->root . sprintf("Scripts/Components/%s/%sSvc.js", $item, $item)))
{
$sb->appendLine();
$sb->appendFormat(".factory('%sSvc', %s)", $item, $item);
}
}
$list =array_unique($this->layoutControllers);
foreach ($list as $item)
{
if (JwtUtil::fileExists($this->root . sprintf("Scripts/Layouts/%s/%sSvc.js", $item, $item)))
{
$sb->appendLine();
$sb->appendFormat(".factory('%sSvc', %s)", $item, $item);
}
}
$sb->append(";");
$sb->appendLine();
$sb->appendLine();
$sb->append("export default moduleName;");
JwtUtil::putContent($this->root . "Scripts/app.services.js", $sb->toString());
}
private function genAppDirectives(){
$dir = JwtUtil::getSubDirectories($this->root . "Scripts/Directives");
$import1 = new StringBuilder();
$builder = new StringBuilder();
foreach ($dir as $item)
{
$import1->appendFormat("import %s from 'Scripts/Directives/%s/%s.js';", $item,$item,$item);
$import1->appendLine();
$builder->appendFormat(".directive('%s', %s.builder)", $item, $item);
$builder->appendLine();
if (JwtUtil::fileExists(sprintf($this->root. "Scripts/Directives/%s/%s.css", $item, $item)))
{
$this->componentsCSS->appendFormat("@import '../Scripts/Directives/%s/%s.css';", $item, $item);
$this->componentsCSS->appendLine();
}
}
$res = new StringBuilder();
$res->append($import1->toString());
$res->appendLine();
$res->appendLine();
$res->appendFormat("var moduleName='%s.Directives';", $this->app->Name);
$res->appendLine();
$res->appendLine();
$res->append("angular.module(moduleName, [])");
$res->appendLine();
$res->append($builder->toString());
$res->append(";");
$res->appendLine();
$res->appendLine();
$res->append("export default moduleName;");
JwtUtil::putContent($this->root . "Scripts/app.directives.js", $res->toString());
}
private function getEmptyModule($name)
{
$res = new StringBuilder();
$res->append("//import sample from 'Scripts/Modules/$name/sample.js';");
$res->appendLine();
$res->appendLine();
$res->append("var moduleName='$name'; ");
$res->appendLine();
$res->append("angular.module(moduleName, []);");
$res->appendLine();
$res->append("export default moduleName;");
$res->appendLine();
return $res->toString();
}
private function getEmptyController($name)
{
$sb = new StringBuilder();
$sb->append("import BaseCtrl from 'Scripts/Base/BaseCtrl.js';");
$sb->appendLine();
$sb->appendLine();
$sb->appendFormat("class %sCtrl extends BaseCtrl", $name);
$sb->appendLine();
$sb->append("{");
$sb->appendLine()->appendTab()->append("constructor(scope, svc){");
$sb->appendLine()->appendTab2()->append( "super(scope);");
$sb->appendLine()->appendTab2()->append("this.svc = svc;");
$sb->appendLine()->appendTab2()->appendFormat("this.title='%s';", $name);
$sb->appendLine()->appendTab()->append("}");
$sb->appendLine();
$sb->append("}");
$sb->appendLine()->appendFormat( "%sCtrl.\$inject=['\$scope', '%sSvc'];", $name, $name);
$sb->appendLine()->appendFormat( "export default %sCtrl;", $name);
return $sb->toString();
}
private function getEmptyControllerForLayout($name){
$sb = new StringBuilder();
$sb->appendFormat("class %sCtrl", $name);
$sb->appendLine();
$sb->append("{");
$sb->appendLine()->appendTab()->append("constructor(){");
$sb->appendLine()->appendTab2()->appendFormat("this.title='%s';", $name);
$sb->appendLine()->appendTab()->append("}");
$sb->appendLine();
$sb->append("}");
$sb->appendLine()->appendFormat("export default %sCtrl;", $name);
return $sb->toString();
}
private function getEmptyService($name)
{
$sb = new StringBuilder();
$sb->append("import BaseSvc from 'Scripts/Base/BaseSvc.js';");
$sb->appendLine();
$sb->appendLine();
$sb->appendFormat("class %sSvc extends BaseSvc", $name);
$sb->appendLine();
$sb->append("{");
$sb->appendLine()->appendTab()->append("constructor(http){");
$sb->appendLine()->appendTab2()->append("super(http);");
$sb->appendLine()->appendTab2()->append("this.http= http;");
$sb->appendLine()->appendTab()->append("}");
$sb->appendLine();
$cname = ucfirst($name);
$sb->appendTab()->appendFormat("static %sFactory(http)", $cname);
$sb->appendTab()->append( "{");
$sb->appendLine();
$sb->appendTab2()->appendFormat( "return new %sSvc(http);", $name);
$sb->appendLine()->appendTab()->append( "}");
$sb->appendLine()->append("}");
$sb->appendLine()->appendFormat( "%sSvc.%sFactory.\$inject=['\$http'];", $name, $cname);
$sb->appendLine()->appendFormat( "export default %sSvc.%sFactory;", $name, $cname);
return $sb->toString();
}
public function getEmptyDirective($name)
{
$sb = new StringBuilder();
$sb->append("class " . $name);
$sb->appendLine();
$sb->append("{");
$sb->appendLine()->appendTab()->append("constructor(){");
$sb->appendLine()->appendTab2()->append( "this.restrict='E';");
$sb->appendLine()->appendTab2()->append("this.templateUrl='Scripts/Directives/$name/$name.html';");
$sb->appendLine()->appendTab()->append("}");
$sb->appendLine();
$sb->appendTab()->append( "static builder()");
$sb->appendTab()->append( "{");
$sb->appendLine();
$sb->appendTab2()->append("return new $name();");
$sb->appendLine();
$sb->appendTab()->append( "}");
$sb->appendLine();
$sb->append("}");
$sb->appendLine()->append("export default $name;");
return $sb->toString();
}
private function getTemplatePath($tentativePath, $wigenName)
{
if ($this->has_template_authorization)
{
return "'api/tools/tpl/".$wigenName."'" ;
}
return $tentativePath;
}
private function array_find($arr, $fieldName, $layoutName){
foreach($arr as $item){
if($item[$fieldName]==$layoutName){
return $item;
}
}
return null;
}
private function getStateName($layout)
{
$nameList =array();
$nameList[]=$layout['LayoutName'];
while (isset($layout) && !JwtUtil::IsNullOrEmptyString($layout['Extend']))
{
$layout =$this->array_find($this->app->Layouts, 'LayoutName', $layout['Extend']);
if(isset($layout)){
$nameList[]=$layout['LayoutName'];
}
}
return implode(".", array_reverse($nameList));
}
private function getNavigationStateName($navigation)
{
$nameList = array();
$nameList[]=$navigation['NavigationName'];
$layout = null;
if (!JwtUtil::IsNullOrEmptyString($navigation['HasLayout']))
{
$layout =$this->array_find($this->app->Layouts, 'LayoutName', $navigation['HasLayout']);
if(isset($layout)){
$nameList[]=$layout['LayoutName'];
while (!JwtUtil::IsNullOrEmptyString($layout['Extend']))
{
$layout =$this->array_find($this->app->Layouts, 'LayoutName', $layout['Extend']);
if(isset($layout)){
$nameList[]=$layout['LayoutName'];
}
}
}
}
return implode(".", array_reverse($nameList));
}
}
|
Markdown
|
UTF-8
| 12,518 | 3.03125 | 3 |
[] |
no_license
|
Iii. the Sun and the Moon
=========================
"He it is Who appointed the Sun a splendour and the Moon a light, and
measured for her stages, that ye might know the number of the years, and
the reckoning. Allah created not (all) that save in truth. He detaileth
the revelations for people who have knowledge." Quran (10:5)
"And We appoint the night and the day two portents. Then We make dark
the portent of the night, and We make the portent of the day
sight-giving, that ye may seek bounty from your Lord, and that ye may
know the computation of the years, and the reckoning; and everything
have We expounded with a clear expounding." Quran (17:12)
The Universality of Islam can be established by referring to the Quran,
as it speaks about heavenly bodies. Focusing on the Solar system, the
Creator tells in the Quran that:
"He created the Sun and the Moon, so we learn how to enumerate the
years and reckoning."
Thus, the alteration of the day and the night and the seasons of the
year must all be in conformity with Allah's plan. In nature, the light
that is reflected on the Moon depends on the rays of the Sun's light.
Right. Mathematically, there must be a linear correlation between the
Lunar and the Solar years, or: y = mx + b
where: y: dependent variable - Lunar (Hijri) year, x: independent
variable - Solar (Gregorian) year, and, b, m : constants.
In the chapter of the Cave, Allah gives m = 309/300 = 1.03 (the
slope).
Quran's chapter of the Elephant marked the birthday of the Prophet -
which corresponded to 571 A.D (the intercept).
Knowing that the Prophet migrated from Mecca to Madinah at the age of
53, one can determine b = - 639. Thus:
y = 1.03x - 639
Example: put x = 2008 into this equation to get 1429.
Proof: The author of the Quran is none but Allah - the exalted
Creator.
The Prophet Muhammad could never make such a discovery, given the fact
that illiteracy was prevailing in the Arabia Peninsula at his time. In
the city of Mecca, where he was born, people were either wood cutters,
or shepherd, or merchants. A few were poets. But, none was expert in
Physics or Astrology. It was only in the past century when man put his
step on the Moon, and learned that its mean distance from the planet
Earth is 384,400 Km.
It is pertinent to cite another wondrous revelation that captured the
attention of a number of disbelievers and made them return to Islam.
Here is the verse:
"The hour drew nigh and the moon was rent in twain." Quran (54:1)
Therefore it is important to stress that the Muslims are not Moon
worshippers. Unfortunately, this is a stereotype which is very prevalent
in the Western media to portray Islam with a negative brush. Islam is
the true religion which the Creator has sent to the entire humanity. The
Muslims' motto is: the One Creator Who has sent the One true message to
the One human family.
According to some tradition5, Lunar and Solar eclipses in the month of
Ramadhan may herald the coming of the Mahdi. Leaving aside the birth of
the tailed comet Helley for other studies, the 1981 and 1982 Lunar and
Solar Eclipses in the month Ramadhan have already occurred. But, their
occurrence was in the reverse order of what another more authentic
Hadith stipulates:
The author of \\'eqdud-durar\\' in section one, chapter four narrates
from \\'al-fatan\\' of hafiz abu-abdullah na\\'eem-ibn-hemmad and he,
from yazid-ibn-khalil asadi who said: \\'I was in the presence of Imam
Muhammad Baqir (a.s.). He mentioned two of the signs which would occur
before the emergence of Mahdi and which has not yet been witnessed
(right from the time of fall of Adam till now). One sign is this that
there shall occur an eclipse of the Sun on 15th of Ramadhan and the Moon
too shall be eclipsed at the end of Ramadhan.
A person said: \\'O son of messenger of Allah! It is not as you say.
Rather the Sun will be eclipsed at the end of the month of Ramadhan and
the Moon will be eclipsed during the middle of the month. Imam Baqir
(a.s.) said: the One who says these words is knowing better (than you)
that right from the time of Adam\\'s fall till today these two signs
have not occurred.
The author of es\\'aaf-ul-raghaben\\' too has narrated the same
tradition.
**IV. Light and Darkness**
The Quran declares that we categorically have two worlds: the Seen;
and, the Unseen. When light projects on material objects, man's naked
eyes can see them. It is probably for this reason that Allah breathed
His spirit (or essence which can be construed as an invisible light)
into the clay upon Adam's creation. Reasonably, the Prophet set a
requirement for the Moon sighting: witnessing the Crescent by the naked
eyes. Thus witnessing becomes a source of certainty - not the
speculative computational models.
Distinguishing different kinds of light, the Quran calls the Sun as
Siraj (i.e. a lamp which usually generates the light that is familiar to
us). The Moon, on the other hand, is called Noor - which is a mere
indication of the reflected light on its surface to the planet Earth.
Remember the dependency of the Moon's light on the Sun's.
"And for the moon We have appointed mansions till she return like an
old shrivelled palm-leaf.." Quran (36:39)
In this verse, Allah says that He is the One Who has predestined the
Moon's (monthly) stations, changing it from a full Moon until it looks
like an old arch of a palm-tree leaf. Removing the barrier between the
two worlds and demonstrating His control of everything in existence,
Allah also states that He manages the affairs on Earth from the Heaven,
in a day which is equivalent to 1000 years of that you count
(enumerate).
Ironically, the Quran had spoken about the relativity (theory) some
1200 years before the birth of Albert Einstein. Historically, the Arabs
used to use the units of time to indicate to long distances travelled.
Here, if you substitute the 1000 years by the intended distance
travelled by the Moon as it revolves around the Earth 12,000 times and
divide that distance by 1 day converted to seconds, you get:
Speed of light = distance travelled by the Moon in 1000 years/(24x3600)
= 299748 Km/s.
This speed of light was adopted in a Scientific Conference in Paris, in
1984.
Similar to the concept of minor, middle, and major resurrections, here
I submit: Physics (realm of the Physical world); and, Metaphysics I,
Metaphysics II to refer to two worlds in the Unseen. The Physical world,
for being material in nature, is being experienced by the majority of
the children of Adam. For man's ignorance about the other worlds (which
are spiritual in nature), very many generations of human beings do not
know what they have missed.
Seeing is believing, the adage goes. But with what eyes? True: the
naked eyes only see the material objects. For investigating tiny
particulate matters (or distant heavenly planets), the scientists have
utilized powerful microscopes. High resolution cameras can picture even
the nuclei of living and pathological cells. One is not sure where to
place the lie detectors, when the occupants of the Oval office lie with
impunity.
After the recent technological breakthroughs, we started believing many
things which we can not normally see by our naked eyes. Wireless
communication was a dream a few decades ago. The Quran talks about
Joseph's dream in seeing the Sun, the Moon, and 11 stars bowing down to
him. A dream which came true a few decades later, as the Quran
reports.
Other points in Metaphysics I can be derived from Joseph's chapter and
other chapters in the Quran. Here, I only state the strong sense of
smelling of Israel (Jacob - Joseph's father) and recovering his sight
after throwing Joseph's shirt on his face.
To the materialistic Children of Israel who out of envy threw their
half-brother Joseph in a deep well and caused too much anguish for their
old father, Jacob said:
"I expose my distress and anguish only unto Allah, and I know from
Allah that which ye know not." Quran (12:86)
"Then, when the bearer of glad tidings came, he laid it on his face and
he became a seer once more.. He said: Said I not unto you that I know
from Allah that which ye know not?" Quran (12:96)
The Quran exhorts mankind to believe in the Day of Judgment. This day
is equivalent to 50,000 Earthy years! Once again, Allah's words can be
viewed on three levels: lower (worldly, for the majority to understand);
higher (Metaphysics I, for the prophets to know); and, Superior
(Metaphysics II, for the Imams to relate to).
This categorization is an oversimplification to express spiritual
experiences in layman's language. In other words, a tiny object loses
its gross material nature when it moves at the speed of light. Thus, we
can examine the various kinds of waves, including the electromagnetic
waves which constitute the rays of light. This light is visible to our
eyes.
Examination of subatomic particular reactions leads to the measurement
of: Alpha particles; Beta particles; and, Gamma Rays - which are
invisible electromagnetic waves. Mass-energy balance leads to other
emissions. Co-60 has been used for sterilization by Gamma radiation.
Dentists normally use X-Ray machines for diagnoses.. Hospitals utilize
Ultrasound detectors to discover the foetus's gender. Lately, with the
heightened security concerns, new detectors were developed for detecting
explosives from 25m distance.
Why then the majority of the human beings do not believe in the Creator
Who describes Himself in such a lower, worldly vocabulary:
"Allah is the Light of the heavens and the earth. The similitude of His
light is as a niche wherein is a lamp. The lamp is in a glass. The glass
is as it were a shining star. (This lamp is) kindled from a blessed
tree, an olive neither of the East nor of the West, whose oil would
almost glow forth (of itself) though no fire touched it. Light upon
light. Allah guideth unto His light whom He will. And Allah speaketh to
mankind in allegories, for Allah is Knower of all things." Quran
(24:35)
In the physical world, darkness occurs when layers of material prevent
the penetration of rays of light. A good example is what marine
biologists experience in deep seas. When Yonus (Joanna) angrily left his
town, he suddenly found himself in three layers of darkness: the night;
the deep sea; and, the whale's belly.
The Quran presents another interesting case, which is indicative
towards Allah as the Creator:
He created you from one being, then from that (being) He made its mate;
and He hath provided for you of cattle eight kinds. He created you in
the wombs of your mothers, creation after creation, in a threefold
gloom. Such is Allah, your Lord. His is the Sovereignty. There is no
Allah save Him. How then are ye turned away? Quran (39:6)
In the spiritual world, it is man's heart which receives the rays of
guidance from Allah. Upon sinning, this heart will be covered with
layers of what looks like "rusts" - which are impermeable to any
spiritual enlightenment. The Quran calls the hearts of those who
insistently indulge in sins, without considering repentance, as being
"sealed." According to the Prophet, only constant, sincere repentance
can remove such rusts.
In the first chapter of the Quran, there is an interesting analogy
between the physical darkness and the spiritual one.
As discussed somewhere else6, the (written) Quran is the lower word of
Allah - it is only a silent book. Recitation of Allah's words brings
humility to the believers' hearts and makes them ready to receive the
guidance. The rightful Imam is the light of Allah who guides the pious
towards the straight path. For knowing the intended meanings of Allah's
final revelation, the Imam's light pierces through every darkness to
dispel it.
The Quran encourages every Muslim to become a Mo'min - a true believer.
Then by responding to the call "Oh you who believe," the believers are
perhaps moved to become pious - Mutaqeen. Only the latter group can find
guidance from the Quran. Believing in the Unseen constitutes an integral
part of the belief of the latter group, as the Quran declares in its
very first chapter. Imam Mahdi is part of the Unseen. His path is
therefore the Straight Path.
The interconnection between the Quran and the Imam is inseparable. One
leads to the other. Without being an infallible, already-guided, the
Mahdi can not provide any guidance to others. His occultation is just
part of the Unseen world. His presence in the hearts of the pious looks
like the shinning Sun which is being obscured by little clouds.
|
C++
|
UTF-8
| 745 | 3.453125 | 3 |
[] |
no_license
|
#include <cstdio>
#include <cstring>
using namespace std;
int lookpup[100] = { -1 };
int fibTopDown(int n) {
if (lookpup[n] == -1) {
if (n <= 1)
lookpup[n] = n;
else
lookpup[n] = fibTopDown(n - 1) + fibTopDown(n - 2);
}
return lookpup[n];
}
int fibBottomUp(int n) {
int table[n + 1];
table[0] = 0;
table[1] = 1;
for (int index = 2; index <= n; index++) {
table[index] = table[index - 1] + table[index - 2];
}
return table[n];
}
int main(int argc, char **argv) {
memset(lookpup, 0xFF, sizeof(lookpup));
printf("Fibonacci 40th: %d by top down\n", fibTopDown(40));
printf("Fibonacci 40th: %d by bottom up\n", fibBottomUp(40));
return 0;
}
|
Java
|
UTF-8
| 499 | 1.867188 | 2 |
[] |
no_license
|
package com.scut.knowbook.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.scut.knowbook.model.Son_comments;
import com.scut.knowbook.model.User;
public interface ISonCommentsService{
public Son_comments findById(Long id);
public Son_comments save(Son_comments comments);
public void delete(Son_comments son_comments);
public Page<Son_comments> findByCommentsId(Long commentsId,Pageable pageable);
}
|
C#
|
UTF-8
| 653 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Runtime.InteropServices;
namespace BrainfuckSharp.Cli
{
class Program
{
static void Main(string[] args)
{
var memory = new byte[1024];
while (TryReadLine(out var line))
{
try
{
var script = Brainfuck.Compile(line);
script.Invoke(memory, Console.In, Console.Out);
}
catch (BrainfuckException err)
{
Console.Error.WriteLine($"Parser Exception: {err.Message}");
}
}
}
static bool TryReadLine(out string line)
{
line = Console.ReadLine();
return !string.IsNullOrEmpty(line);
}
}
}
|
C
|
UTF-8
| 1,461 | 3.015625 | 3 |
[
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"BSD-2-Clause",
"MIT"
] |
permissive
|
/* bwsolid.c
*
* 16-May-2008 Initial write: Ting Zhao
*/
#include <stdlib.h>
#include <stdio.h>
#include <utilities.h>
#include <string.h>
#include "tz_error.h"
#include "tz_stack_lib.h"
#include "tz_stack_bwmorph.h"
/*
* bwsolid - make objects in a binary stack more solid
*
* bwsolid [-mf value] infile -o outfile
*/
int main(int argc, char *argv[])
{
static char *Spec[] = {"[-mf <int>]",
" <image:string>",
" -o <string>",
NULL};
Process_Arguments(argc, argv, Spec, 1);
char *image_file = Get_String_Arg("image");
Stack *stack = Read_Stack(image_file);
Stack *clear_stack = NULL;
if (Is_Arg_Matched("-mf")) {
printf("Majority filtering ...\n");
int mnbr = Get_Int_Arg("-mf");
clear_stack = Stack_Majority_Filter_R(stack, NULL, 26, mnbr);
Kill_Stack(stack);
} else {
clear_stack = stack;
}
printf("Dilating ...\n");
Struct_Element *se = Make_Cuboid_Se(3, 3, 3);
Stack *dilate_stack = Stack_Dilate(clear_stack, NULL, se);
Kill_Stack(clear_stack);
/*
printf("Hole filling ...\n");
Stack *fill_stack = Stack_Fill_Hole_N(dilate_stack, NULL, 1, 4, NULL);
Kill_Stack(dilate_stack);
*/
Stack *fill_stack = dilate_stack;
printf("Eroding ...\n");
Stack *mask = Stack_Erode_Fast(fill_stack, NULL, se);
Kill_Stack(fill_stack);
char *out_file = Get_String_Arg("-o");
Write_Stack(out_file, mask);
printf("%s created.\n", out_file);
Kill_Stack(mask);
return 0;
}
|
JavaScript
|
UTF-8
| 4,161 | 2.828125 | 3 |
[
"Apache-2.0"
] |
permissive
|
import { CONNECTION_TYPES, ADB_COMMANDS, ADB_SUBCOMMANDS } from './constants';
import _ from 'underscore';
const ADB_HEADER_LENGTH = 24;
function crc (buf) {
if (!buf) return 0;
let crcResult = 0;
// this loop doesn't want to be a let item of object loop
for (let i = 0; i < buf.length; i++) {
crcResult = (crcResult + buf[i]) & 0xFFFFFFFF;
}
return crcResult;
}
// generates a message according to the ADB packet specifications
// noTte that we don't append the actual data payload to the message
// unless we're on tcp, and if you want to pass no payload use ""
function generateMessage (cmd, arg1, arg2, payload, connectionType) {
// default connectionType to usb since tha's what we expect
// the connection to be most of the time
connectionType = typeof connectionType !== 'undefined' ? connectionType
: CONNECTION_TYPES.USB;
// cmd needs to be an ADB command
if (_.contains(_.values(ADB_COMMANDS), cmd) === false) {
throw new Error("generateMessage: invalid command type");
}
// connection type can only be USB or TCP
if (_.contains(_.values(CONNECTION_TYPES), connectionType) === false) {
throw new Error("generateMessage: invalid connection type");
}
if (_.isNumber(payload)) {
payload = payload.toString();
}
let payloadBuffer = !Buffer.isBuffer(payload) ? new Buffer(payload)
: payload;
let msgLength = ADB_HEADER_LENGTH;
// only allocate space for data payload if we're going to fill that field
if (connectionType === CONNECTION_TYPES.TCP) {
msgLength = msgLength + payloadBuffer.length;
}
let message = new Buffer(msgLength);
message.writeUInt32LE(cmd, 0);
message.writeUInt32LE(arg1, 4);
message.writeUInt32LE(arg2, 8);
if (payload !== null) {
message.writeUInt32LE(payloadBuffer.length, 12);
message.writeUInt32LE(crc(payloadBuffer), 16);
}
let magic = 0xFFFFFFFF - cmd;
message.writeUInt32LE(magic, 20);
//connection type TCP
if (connectionType === CONNECTION_TYPES.TCP) {
payloadBuffer.copy(message, 24);
}
return message;
}
// block console logging when tests are being run
function logExceptOnTest (string) {
if (process.env.NODE_ENV !== 'test') {
console.log(string);
}
}
// select a device from the list of available devices by serial number
function selectBySerialNumber (devices, serialNumber) {
for (let device of devices) {
if (serialNumber === device.serialNumber) {
return device;
}
}
throw new Error("No device available with the serial number: ", serialNumber);
}
// takes a buffer from an inputEndpoint read and
// creates the packet structure from the data
function packetFromBuffer (buf) {
//set the fields we are guaranteed to have
let packet = {
"command": buf.readUInt32LE(0)
, "arg1": buf.readUInt32LE(4)
, "arg2": buf.readUInt32LE(8)
, "dataLen": buf.readUInt32LE(12)
, "dataCrc": buf.readUInt32LE(16)
, "magic": buf.readUInt32LE(20)
};
if (packet.dataLen > 0) {
packet.data = buf.slice(24, (24 + packet.dataLen));
}
return packet;
}
// takes a file path (seperated by /'s') and gets the file name from
// the end of the path, returns the file name
function getFileName (path) {
let splitArray = path.split("/");
return splitArray[splitArray.length - 1];
}
// copy the actual file data out of the mess of ADB protocol information
function parseFileData (rawData) {
let currentPosition = 0;
let fileData = new Buffer("");
while (true) {
// get the length (DATA<length>) so we know how much to copy
let length = rawData.readUInt32LE(currentPosition + 4);
currentPosition += 8;
let chunk = new Buffer(length);
rawData.copy(chunk, 0, currentPosition, currentPosition + length);
currentPosition += length;
fileData = Buffer.concat([fileData, chunk]);
if (rawData.readUInt32LE(currentPosition) === ADB_SUBCOMMANDS.CMD_DONE) {
break;
}
}
return fileData;
}
export { generateMessage, packetFromBuffer
, selectBySerialNumber, getFileName
, parseFileData, logExceptOnTest };
|
Java
|
UTF-8
| 7,888 | 1.546875 | 2 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
/*******************************************************************************
* Copyright © 2012-2015 eBay Software Foundation
* This program is dual licensed under the MIT and Apache 2.0 licenses.
* Please see LICENSE for more information.
*******************************************************************************/
package com.ebay.jetstream.event.support;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import com.ebay.jetstream.common.ShutDownable;
import com.ebay.jetstream.counter.LongCounter;
import com.ebay.jetstream.counter.LongEWMACounter;
import com.ebay.jetstream.event.BatchResponse;
import com.ebay.jetstream.event.BatchSource;
import com.ebay.jetstream.event.BatchSourceCommand;
import com.ebay.jetstream.event.EventException;
import com.ebay.jetstream.event.EventMetaInfo;
import com.ebay.jetstream.event.JetstreamEvent;
import com.ebay.jetstream.event.advice.Advice;
import com.ebay.jetstream.event.processor.BatchEventProcessor;
import com.ebay.jetstream.event.support.channel.PipelineFlowControl;
import com.ebay.jetstream.management.Management;
import com.ebay.jetstream.messaging.MessageServiceTimer;
import com.ebay.jetstream.notification.AlertListener;
import com.ebay.jetstream.notification.AlertListener.AlertStrength;
import com.ebay.jetstream.spring.beans.factory.BeanChangeAware;
import com.ebay.jetstream.xmlser.Hidden;
/**
* @author weifang, xiaojuwu1
*
*/
public abstract class AbstractBatchEventProcessor extends
AbstractBatchEventSource implements BatchEventProcessor,
ApplicationListener, ApplicationEventPublisherAware, InitializingBean,
BeanNameAware, BeanChangeAware, ShutDownable {
protected enum ProcessorOperationState {
PAUSE, RESUME
}
protected final AtomicBoolean m_isPaused = new AtomicBoolean(false);
private final LongCounter m_totalEventsReceived = new LongCounter();
private final LongEWMACounter m_eventsReceivedPerSec = new LongEWMACounter(
60, MessageServiceTimer.sInstance().getTimer());
private final LongCounter m_totalEventsSent = new LongCounter();
private final LongEWMACounter m_eventsSentPerSec = new LongEWMACounter(60,
MessageServiceTimer.sInstance().getTimer());
private final LongCounter m_totalEventsDropped = new LongCounter();
private final LongCounter m_pauseCount = new LongCounter();
private final LongCounter m_resumeCount = new LongCounter();
private final PipelineFlowControl m_pipelineflowcontroller = new PipelineFlowControl(
this);
private AlertListener m_alertListener;
protected Advice m_adviceListener = null;
@Hidden
public Advice getAdviceListener() {
return m_adviceListener;
}
public void setAdviceListener(Advice adviceListener) {
this.m_adviceListener = adviceListener;
}
@Hidden
public AlertListener getAlertListener() {
return m_alertListener;
}
public void setAlertListener(AlertListener alertListener) {
this.m_alertListener = alertListener;
}
public PipelineFlowControl getPipelineflowcontroller() {
return m_pipelineflowcontroller;
}
@Override
public long getEventsReceivedPerSec() {
return m_eventsReceivedPerSec.get();
}
@Override
public long getEventsSentPerSec() {
return m_eventsSentPerSec.get();
}
@Override
public long getTotalEventsDropped() {
return m_totalEventsDropped.get();
}
@Override
public long getTotalEventsReceived() {
return m_totalEventsReceived.get();
}
@Override
public long getTotalEventsSent() {
return m_totalEventsSent.get();
}
@Override
public long getTotalPauseCount() {
return m_pauseCount.get();
}
@Override
public long getTotalResumeCount() {
return m_resumeCount.get();
}
public void incrementEventDroppedCounter() {
m_totalEventsDropped.increment();
}
public void incrementEventDroppedCounter(long lNumber) {
m_totalEventsDropped.addAndGet(lNumber);
}
public void incrementEventRecievedCounter() {
m_totalEventsReceived.increment();
m_eventsReceivedPerSec.increment();
}
public void incrementEventRecievedCounter(long lNumber) {
m_totalEventsReceived.addAndGet(lNumber);
m_eventsReceivedPerSec.add(lNumber);
}
public void incrementEventSentCounter() {
m_totalEventsSent.increment();
m_eventsSentPerSec.increment();
}
public void incrementEventSentCounter(long lNumber) {
m_totalEventsSent.addAndGet(lNumber);
m_eventsSentPerSec.add(lNumber);
}
public void incrementPauseCounter() {
m_pauseCount.increment();
}
public void incrementResumeCounter() {
m_resumeCount.increment();
}
protected void resetCounters() {
m_totalEventsReceived.reset();
m_eventsReceivedPerSec.reset();
m_totalEventsSent.reset();
m_eventsSentPerSec.reset();
m_totalEventsDropped.reset();
}
@Override
public void setApplicationEventPublisher(
ApplicationEventPublisher applicationEventPublisher) {
m_pipelineflowcontroller
.setApplicationEventPublisher(applicationEventPublisher);
}
protected void changeState(ProcessorOperationState state) {
switch (state) {
case PAUSE:
if (!m_isPaused.get()) {
m_isPaused.set(true);
incrementPauseCounter();
getPipelineflowcontroller().pause();
}
break;
case RESUME:
if (m_isPaused.get()) {
m_isPaused.set(false);
incrementResumeCounter();
getPipelineflowcontroller().resume();
}
break;
}
}
protected boolean isPaused() {
return m_isPaused.get();
}
protected void postAlert(String msg, AlertStrength strength) {
if (m_alertListener != null) {
m_alertListener.sendAlert(this.getBeanName(), msg, strength);
}
}
@Override
public void sendEvents(Collection<JetstreamEvent> events, EventMetaInfo meta)
throws EventException {
BatchSourceCommand action = meta.getAction();
BatchResponse res = null;
switch (action) {
case OnNextBatch:
res = onNextBatch(meta.getBatchSource(), events);
break;
case OnBatchProcessed:
onBatchProcessed(meta.getBatchSource());
break;
case OnException:
res = onException(meta.getBatchSource(), meta.getException());
break;
case OnIdle:
res = onIdle(meta.getBatchSource());
break;
case OnStreamTermination:
res = onStreamTermination(meta.getBatchSource());
break;
default:
throw new IllegalArgumentException("Illegal batch sink action.");
}
meta.setBatchResponse(res);
}
/*
* (non-Javadoc)
*
* @see
* com.ebay.jetstream.event.EventSink#sendEvent(com.ebay.jetstream.event
* .JetstreamEvent)
*/
@Override
public void sendEvent(JetstreamEvent event) throws EventException {
throw new EventException("Unsupported operation");
}
/*
* (non-Javadoc)
*
* @see com.ebay.jetstream.common.ShutDownable#getPendingEvents()
*/
@Override
public int getPendingEvents() {
return 0;
}
@Override
public void afterPropertiesSet() throws Exception {
Management.addBean(getBeanName(), this);
init();
}
public abstract void init() throws Exception;
public abstract BatchResponse onNextBatch(BatchSource source,
Collection<JetstreamEvent> events) throws EventException;
public abstract void onBatchProcessed(BatchSource source);
public abstract BatchResponse onStreamTermination(BatchSource source)
throws EventException;
public abstract BatchResponse onException(BatchSource source, Exception ex);
public abstract BatchResponse onIdle(BatchSource source);
}
|
Shell
|
UTF-8
| 380 | 3.265625 | 3 |
[] |
no_license
|
#this file is for dividing videos into frames.
#!/bin/bash
$cmd=""
while IFS='' read -r line || [[ -n "$line" ]]; do
echo $line
IFS='-' read -ra tmp<<<"$line"
l1=`expr ${tmp[1]} - 20`
l2=`expr ${tmp[0]} - ${tmp[1]} + 40`
echo ${l1}
cmd="$cmd && sudo ffmpeg -ss ${l1} -i {$2} -t ${l2} -vf fps=1 {$3}/${l1}_%d.jpg"
done < "$1"
cmd=${cmd:3}
echo $cmd
|
Markdown
|
UTF-8
| 1,324 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
# Challenge4_Repo
Challenge 4 Repository
# User Story
Role: Quantitative analyst for a FinTech investing platform
Goal: This platform aims to offer clients a one-stop online investment solution for their retirement portfolios that’s both inexpensive and high quality.
Reason: To keep the costs low, through the use of algorithms to build each client's portfolio. The algorithms choose from various investment styles and options.
# General information about the analysis
The Fintech analyst is tasked with evaluating four new investment options for inclusion in the client portfolios. The anlyst will need to determine the fund with the most investment potential based on key risk-management metrics: the daily returns, standard deviations, Sharpe ratios, and betas.
# Technology
Jupyter notebook that contains data preparation, analysis, and visualizations for key risk and return metrics.
GitHub repository
Python
## libraries used in the analysis
• A single DataFrame imported from a CSV file that has a DateTimeIndex.
## Analysis
## Acceptance Criteria
Evaluate four new investment options for inclusion in the client portfolios
Determine the fund with the most investment potential based on key risk-management metrics: the daily returns, standard deviations, Sharpe ratios, and betas.
|
Java
|
UTF-8
| 17,526 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package stew6;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.stream.*;
import javax.script.*;
import minestra.text.*;
import net.argius.stew.*;
import stew6.io.*;
import stew6.ui.*;
/**
* Command Processor.
*/
final class CommandProcessor {
private static Logger log = Logger.getLogger(CommandProcessor.class);
private static final ResourceSheaf res = App.res.derive().withClass(Command.class);
private static final String HYPHEN_E = "-e";
private final Environment env;
private final OutputProcessor op;
CommandProcessor(Environment env) {
this.env = env;
this.op = env.getOutputProcessor();
}
/**
* Invokes this command.
* @param parameterString
* @return whether this application continues or not
*/
boolean invoke(String parameterString) {
if (parameterString.replaceFirst("^\\s+", "").startsWith(HYPHEN_E)) {
final int offset = parameterString.indexOf(HYPHEN_E) + 2;
try {
for (String s : parameterString.substring(offset).split(HYPHEN_E)) {
op.output(" >> " + s);
if (!invokeWithErrorHandling(s)) {
outputMessage("w.exit-not-available-in-sequencial-command");
}
}
} catch (CommandException ex) {
env.setExitStatus(1);
op.output(res.format("e.serial-execution-interrupted", ex.getMessage()));
}
return true;
} else {
try {
return invokeWithErrorHandling(parameterString);
} catch (CommandException ex) {
// ignore Exception
env.setExitStatus(1);
return true;
}
}
}
boolean invokeWithErrorHandling(String parameterString) throws CommandException {
Parameter p = new Parameter(parameterString);
final String commandName = p.at(0);
try {
return process(commandName, new Parameter(parameterString));
} catch (UsageException ex) {
outputMessage("e.usage", commandName, ex.getMessage());
} catch (DynamicLoadingException ex) {
log.error(ex);
outputMessage("e.not-found", commandName);
} catch (CommandException ex) {
log.error(ex);
Throwable cause = ex.getCause();
String message = (cause == null) ? ex.getMessage() : cause.getMessage();
outputMessage("e.command", message);
} catch (IOException ex) {
log.error(ex);
outputMessage("e.command", ex.getMessage());
} catch (SQLException ex) {
log.error(ex);
SQLException parent = ex;
while (true) {
SQLException sqle = parent.getNextException();
if (sqle == null || sqle == parent) {
break;
}
log.error(sqle, "------ SQLException.getNextException ------");
parent = sqle;
}
outputMessage("e.database", ex.getMessage());
} catch (UnsupportedOperationException ex) {
log.warn(ex);
outputMessage("e.unsupported", ex.getMessage());
} catch (RuntimeException ex) {
log.error(ex);
String msg = ex.getMessage();
if (msg == null || msg.trim().isEmpty()) {
outputMessage("e.runtime-without-message", ex);
} else {
outputMessage("e.runtime", msg);
}
} catch (Throwable th) {
log.fatal(th);
outputMessage("e.fatal", th.getMessage());
}
try {
@SuppressWarnings("resource")
Connection conn = env.getCurrentConnection();
if (conn != null) {
if (conn.isClosed()) {
log.info("connection is already closed");
disconnect();
}
}
} catch (SQLException ex) {
log.warn(ex);
}
throw new CommandException(parameterString);
}
@SuppressWarnings("resource")
private boolean process(String commandName, Parameter p) throws IOException, SQLException {
assert commandName != null;
// do nothing if blank
if (commandName.length() == 0) {
return true;
}
// exit
if (commandName.equalsIgnoreCase("exit")) {
disconnect();
outputMessage("i.exit");
return false;
}
// connect
if (commandName.equalsIgnoreCase("connect") || commandName.equalsIgnoreCase("-c")) {
connect(p);
return true;
}
// from file
if (commandName.equals("-f")) {
if (!p.has(1)) {
throw new UsageException(res.s("usage.-f"));
}
final File file = FileUtilities.resolve(env.getCurrentDirectory(), p.at(1));
final String abspath = file.getAbsolutePath();
if (log.isDebugEnabled()) {
log.debug("absolute path = [%s]", abspath);
}
if (!file.isFile()) {
outputMessage("e.file-not-exists", abspath);
throw new UsageException(res.s("usage.-f"));
}
log.debug("-f %s", file.getAbsolutePath());
invoke(String.format("%s%s", FileUtilities.readAllBytesAsString(file), p.after(2)));
return true;
}
// script
if (commandName.equals("-s")) {
if (!p.has(1)) {
throw new UsageException(res.s("usage.-s"));
}
final String p1 = p.at(1);
if (p1.equals(".")) {
env.initializeScriptContext();
outputMessage("i.script-context-initialized");
return true;
}
final File file;
if (p1.contains(".")) { // by extension
file = FileUtilities.resolve(env.getCurrentDirectory(), p1);
if (!file.exists() || !file.isFile()) {
outputMessage("e.file-not-exists", p1);
return true;
}
log.debug("script file: %s", file.getAbsolutePath());
} else { // by name
file = null;
log.debug("script name: %s", p1);
}
ScriptEngine engine = (file == null) ? new ScriptEngineManager().getEngineByName(p1)
: new ScriptEngineManager().getEngineByExtension(FileUtilities.getExtension(file));
if (engine == null) {
outputMessage("e.unsupported", p1);
return true;
}
engine.setContext(env.getScriptContext());
engine.put("connection", env.getCurrentConnection());
engine.put("conn", env.getCurrentConnection());
engine.put("patameter", p);
engine.put("p", p);
engine.put("outputProcessor", op);
engine.put("op", op);
try {
if (file == null) {
engine.put(ScriptEngine.FILENAME, null);
engine.eval(p.after(2));
} else {
engine.put(ScriptEngine.FILENAME, file.getAbsolutePath());
try (Reader r = new FileReader(file)) {
engine.eval(r);
}
}
} catch (Exception ex) {
throw new CommandException(ex);
}
return true;
}
// alias
AliasMap aliasMap = env.getAliasMap();
if (commandName.equalsIgnoreCase("alias") || commandName.equalsIgnoreCase("unalias")) {
aliasMap.reload();
if (commandName.equalsIgnoreCase("alias")) {
if (p.has(2)) {
final String keyword = p.at(1);
if (isUsableKeywordForAlias(keyword)) {
outputMessage("w.unusable-keyword-for-alias", keyword);
return true;
}
aliasMap.setValue(keyword, p.after(2));
aliasMap.save();
} else if (p.has(1)) {
final String keyword = p.at(1);
if (isUsableKeywordForAlias(keyword)) {
outputMessage("w.unusable-keyword-for-alias", keyword);
return true;
}
if (aliasMap.containsKey(keyword)) {
outputMessage("i.dump-alias", keyword, aliasMap.getValue(keyword));
}
} else {
if (aliasMap.isEmpty()) {
outputMessage("i.noalias");
} else {
for (final String key : new TreeSet<>(aliasMap.keys())) {
outputMessage("i.dump-alias", key, aliasMap.getValue(key));
}
}
}
} else if (commandName.equalsIgnoreCase("unalias")) {
if (p.has(1)) {
aliasMap.remove(p.at(1));
aliasMap.save();
} else {
throw new UsageException(res.s("usage.unalias"));
}
}
return true;
} else if (aliasMap.containsKey(commandName)) {
final String command = aliasMap.expand(commandName, p);
op.output(" >> " + command);
invoke(command);
return true;
}
// cd
if (commandName.equalsIgnoreCase("cd")) {
if (!p.has(1)) {
throw new UsageException(res.s("usage.cd"));
}
File olddir = env.getCurrentDirectory();
final String path = p.at(1);
final File dir = new File(path);
final File newdir = ((dir.isAbsolute()) ? dir : new File(olddir, path)).getCanonicalFile();
if (!newdir.isDirectory()) {
outputMessage("e.dir-not-exists", newdir);
return true;
}
env.setCurrentDirectory(newdir);
outputMessage("i.directory-changed", olddir.getAbsolutePath(), newdir.getAbsolutePath());
return true;
}
// at
if (commandName.equals("@")) {
final String currentDirectory = env.getCurrentDirectory().getAbsolutePath();
final String systemDirectory = App.getSystemDirectory().getAbsolutePath();
op.output(String.format("current dir : %s", currentDirectory));
op.output(String.format("system dir : %s", systemDirectory));
return true;
}
// report -
if (commandName.equals("-")) {
return invoke("report -");
}
// runtime information
if (commandName.equals("?")) {
if (p.has(1)) {
Stream.of(p.asArray()).skip(1)
.map(x -> x + "=" + Optional.ofNullable(System.getProperty(x))
.map(y -> String.format("[%s]", y)).orElse("undefined"))
.forEachOrdered(op::output);
} else {
op.output(String.format("JRE : %s %s", System.getProperty("java.runtime.name"),
System.getProperty("java.runtime.version")));
op.output(String.format("OS : %s (osver=%s)", System.getProperty("os.name"),
System.getProperty("os.version")));
op.output(String.format("Locale : %s", Locale.getDefault()));
}
return true;
}
// connection
Connection conn = env.getCurrentConnection();
if (conn == null) {
outputMessage("e.not-connect");
} else if (commandName.equalsIgnoreCase("disconnect") || commandName.equalsIgnoreCase("-d")) {
disconnect();
outputMessage("i.disconnected");
} else if (commandName.equalsIgnoreCase("commit")) {
conn.commit();
outputMessage("i.committed");
} else if (commandName.equalsIgnoreCase("rollback")) {
conn.rollback();
outputMessage("i.rollbacked");
} else {
executeDynamicCommand(commandName, conn, p);
}
return true;
}
private static boolean isUsableKeywordForAlias(String keyword) {
return keyword != null && keyword.matches("(?i)-.*|exit|alias|unalias");
}
private void connect(Parameter p) throws SQLException {
log.info("connect start");
disconnect();
final String id = p.at(1);
Connector connector;
if (!p.has(1)) {
connector = AnonymousConnector.getConnector(id, p.at(2), p.at(3));
} else if (id.indexOf('@') >= 0) {
connector = AnonymousConnector.getConnector(id);
} else {
connector = env.getConnectorMap().getConnector(id);
}
if (connector != null) {
env.establishConnection(connector);
} else {
outputMessage("e.no-connector", id);
}
log.info("connect end");
}
private void disconnect() {
log.debug("disconnect start");
try {
env.releaseConnection();
} catch (SQLException ex) {
outputMessage("w.connection-closed-abnormally");
}
log.debug("disconnect end");
}
private void executeDynamicCommand(String commandName, Connection conn, Parameter p) {
assert commandName != null && !commandName.contains(" ");
final String fqcn;
if (commandName.indexOf('.') > 0) {
fqcn = commandName;
} else {
fqcn = App.rootPackageName + ".command." + commandName.substring(0, 1).toUpperCase()
+ commandName.substring(1).toLowerCase();
}
Class<? extends Command> c;
try {
c = DynamicLoader.loadClass(fqcn);
} catch (DynamicLoadingException ex) {
c = Command.mayReturnResultSet(p.asString()) ? Select.class : UpdateAndOthers.class;
}
try (Command command = DynamicLoader.newInstance(c)) {
Connector connector = env.getCurrentConnector();
if (connector.isReadOnly() && !command.isReadOnly()) {
outputMessage("e.readonly");
return;
}
command.setEnvironment(env);
log.info("command: %s start", command);
log.debug(p);
command.initialize();
command.execute(conn, p);
log.info("command: %s end", command);
}
}
/**
* Outputs message.
* @param id message-id (resource)
* @param args
* @throws CommandException
*/
void outputMessage(String id, Object... args) throws CommandException {
op.output(res.format(id, args));
}
/**
* SQL statement command.
*/
abstract static class RawSQL extends Command {
@Override
public final void execute(Connection conn, Parameter p) throws CommandException {
final String rawString = p.asString();
try (Statement stmt = prepareStatement(conn, rawString)) {
execute(stmt, rawString);
} catch (SQLException ex) {
throw new CommandException(ex);
}
}
protected abstract void execute(Statement stmt, String sql) throws SQLException;
}
/**
* Select statement command.
*/
static final class Select extends RawSQL {
public Select() {
// empty
}
@Override
public boolean isReadOnly() {
return true;
}
@Override
public void execute(Statement stmt, String rawString) throws SQLException {
final long startTime = System.currentTimeMillis();
try (ResultSet rs = executeQuery(stmt, rawString)) {
outputMessage("i.response-time", (System.currentTimeMillis() - startTime) / 1000f);
@SuppressWarnings("resource")
ResultSetReference ref = new ResultSetReference(rs, rawString);
output(ref);
outputMessage("i.selected", ref.getRecordCount());
}
}
}
/**
* Update statement (contains all SQL excepted a Select SQL) command.
*/
static final class UpdateAndOthers extends RawSQL {
public UpdateAndOthers() {
// empty
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
protected void execute(Statement stmt, String sql) throws SQLException {
final int updatedCount = executeUpdate(stmt, sql);
final String msgId;
if (sql.matches("(?i)\\s*UPDATE.*")) {
msgId = "i.updated";
} else if (sql.matches("(?i)\\\\s*INSERT.*")) {
msgId = "i.inserted";
} else if (sql.matches("(?i)\\\\s*DELETE.*")) {
msgId = "i.deleted";
} else {
msgId = "i.proceeded";
}
outputMessage(msgId, updatedCount);
}
}
}
|
Markdown
|
UTF-8
| 2,639 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
# XLSGenerator
Es una clase generadora de archivos XLS a partir de una matriz asociativa unidimensional, esto tiene la flexibilidad de poder utilizarse no solo para descargar archivos si no también para presentar tablas de datos.
### Instalación 🚀
```bash
$ composer require ligne/xls-generator
```
### Usos 📚
**Para el ejemplo usaremos este array de 5 usuarios.**
```php
$array = array(
0 =>
array(
'id' => 1,
'name' => 'Leanne Graham',
'username' => 'Bret',
'email' => 'Sincere@april.biz',
'phone' => '1-770-736-8031 x56442',
'website' => 'hildegard.org',
),
1 =>
array(
'id' => 2,
'name' => 'Ervin Howell',
'username' => 'Antonette',
'email' => 'Shanna@melissa.tv',
'phone' => '010-692-6593 x09125',
'website' => 'anastasia.net',
),
2 =>
array(
'id' => 3,
'name' => 'Clementine Bauch',
'username' => 'Samantha',
'email' => 'Nathan@yesenia.net',
'phone' => '1-463-123-4447',
'website' => 'ramiro.info',
),
3 =>
array(
'id' => 4,
'name' => 'Patricia Lebsack',
'username' => 'Karianne',
'email' => 'Julianne.OConner@kory.org',
'phone' => '493-170-9623 x156',
'website' => 'kale.biz',
),
4 =>
array(
'id' => 5,
'name' => 'Chelsey Dietrich',
'username' => 'Kamren',
'email' => 'Lucio_Hettinger@annie.ca',
'phone' => '(254)954-1289',
'website' => 'demarco.info',
),
5 =>
array(
'id' => 6,
'name' => 'Mrs. Dennis Schulist',
'username' => 'Leopoldo_Corkery',
'email' => 'Karley_Dach@jasper.info',
'phone' => '1-477-935-8478 x6430',
'website' => 'ola.org',
)
);
```
**Uso basico:**
```php
use Ligne\XlsGenerator;
//...
$xls = new XlsGenerator($array);
var_dump($xls->getXls());
```
**Resultado 👓**
[](https://i.imgur.com/9HBIpuj.png)
**Opciones; ⚙**
El constructor de la clase también recibe ciertas opciones que te permiten decidir que obtener;
`array $content: `Arreglo asociativa unidimensional
`array $omit_fields = array():` Arreglo con nombres de campos que requiera omitir,
`bool $downloable = false:` Si se desea que se descargue como archivo xls
`bool $hasHeader = true: `Si tiene encabezados para incluirlos (Estos son los indices de la del arreglo)
**Ejemplo:**
En este ejemplo omitiremos el campo `phone`
```php
$xls = new XlsGenerator($array,['phone'],false,true);
var_dump($xls->getXls());
```
**Resultado 👓**
[](https://i.imgur.com/n8rZ1z4.png)
Cualquier sugerencia siempre es bien recibida.
|
Java
|
UTF-8
| 1,506 | 1.867188 | 2 |
[] |
no_license
|
package com.hwua.mall.controller;
import com.alibaba.fastjson.JSONObject;
import com.hwua.commom.dao.OrderMapper;
import com.hwua.mall.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("comment")
public class CommentController {
@Autowired
private OrderService orderService;
@RequestMapping("feedback-list")
public String feedback_list(Map map){
List<Map> list = orderService.queryAll();
map.put("list",list);
return "feedback-list";
}
@RequestMapping("/comment_del")
public String comment_del(Integer id){
System.out.println("**********commId = " + id);
int i = orderService.comment_del(id);
return "redirect:/comment/feedback-list";
}
@ResponseBody
@RequestMapping(value = "/commentF" , produces = "application/json;charset=UTF-8")
public String commentF(String id){
System.out.println("id******* = " + id);
int i = orderService.setCommentF(id);
JSONObject jsonObject = new JSONObject();
return jsonObject.toJSONString();
}
@RequestMapping("/datadel")
public String datadel(){
int i = orderService.setDatadel();
return "redirect:/comment/feedback-list";
}
}
|
Ruby
|
UTF-8
| 668 | 3.359375 | 3 |
[] |
no_license
|
require_relative 'person'
class Student < Person
attr_accessor :student_card, :interests, :is_graduated
def initialize access_card, name, interests = [], *args
super access_card, name
@interests = interests
@student_number = rand(666)
@is_graduated = false
@args = args
self.class.all << self
end
@students = []
class << self
attr_accessor :students
def count
@students.count
end
def all
@students
end
end
def who_am_i
self
end
def graduated?
is_graduated
end
def graduate!
is_graduated = true
end
end
|
Shell
|
UTF-8
| 271 | 2.75 | 3 |
[] |
no_license
|
#!/bin/bash
# this checks to see if files created by Airserver's first run exist on a user account.
# if not, it will launch Airserver
if ! test -f ~/Library/Preferences/com.pratikkumar.airserver-mac.plist; then /Applications/AirServer.app/Contents/MacOS/AirServer
fi
|
Java
|
UTF-8
| 199 | 1.765625 | 2 |
[] |
no_license
|
package com.senior.test.litepaymentservice.share.model;
/**
* Franchise card values.
*
* @author <a href='carlos.suarez@payu.com'>Carlos Eduardo Suárez Silvestre</a>
*/
public enum FranchiseCard {
VISA,
AMEX,
MASTERCARD,
DINNER
}
|
TypeScript
|
UTF-8
| 4,009 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
import { marker, markerIndex } from './marker'
import { Part, AttrPart, PropPart, EventPart, NodePart } from './part'
import { Context } from './context'
import { isMarker } from './is'
import { cleanDofStr, insertAfter } from './dom'
import { UpdatableElement } from './component'
import { NotUpdatableELementError } from './error'
import { DoAble } from './do'
import { StyleClip } from './style'
export const range = document.createRange()
/**
* https://www.measurethat.net/Benchmarks/ShowResult/100437
* createContextualFragment vs innerHTML
*/
export function createInstance(this: ShallowClip) {
return new Clip(
range.createContextualFragment(this.do(getShaHtml)),
this.vals.length
)
}
export function getVals(this: ShallowClip) {
return this.vals
}
export function getShaHtml(this: ShallowClip) {
return cleanDofStr(this.strs.join(marker))
}
export function getContexts(this: ShallowClip) {
return this.contexts
}
export class ShallowClip extends DoAble<ShallowClip> {
protected readonly strs: TemplateStringsArray
protected readonly vals: ReadonlyArray<unknown>
protected contexts?: Set<Context<object>>
protected style?: StyleClip
protected key?: unknown
constructor(strs: TemplateStringsArray, vals: unknown[]) {
super()
this.vals = vals
this.strs = strs
}
useContext(contexts: Context<object>[]) {
if (!this.contexts) {
this.contexts = new Set()
}
contexts.forEach((c) => this.contexts!.add(c))
return this
}
useStyle(style: StyleClip) {
this.style = style
return this
}
useKey(key: unknown) {
this.key = key
return this
}
}
export class Clip {
parts: Part[]
partCount: number
dof: DocumentFragment
constructor(dof: DocumentFragment, partCount: number) {
this.dof = dof
this.parts = new Array<Part>()
this.partCount = partCount
attachParts(this)
}
tryUpdate(vals: ReadonlyArray<unknown>) {
this.parts.forEach((part, index) => part.setValue(vals[index]))
}
}
export function attachParts(clip: Clip) {
const walker = document.createTreeWalker(clip.dof, 133)
const length = clip.partCount
let count = 0
while (count < length) {
walker.nextNode()
const cur = walker.currentNode
if (cur === null) {
break
}
if (cur instanceof Element) {
const attrs = cur.attributes
const { length } = attrs
for (let i = 0; i < length; i++) {
const name = attrs[i].name
const prefix = name[0]
if (
prefix === '.' ||
(prefix === ':' && isMarker(attrs[i].value)) ||
prefix === '@'
) {
const bindName = name.slice(1)
switch (prefix) {
case '.':
clip.parts.push(
new AttrPart(count, {
node: cur,
name: bindName
})
)
break
case ':':
if (cur instanceof UpdatableElement) {
clip.parts.push(
new PropPart(count, {
node: cur,
name: bindName
})
)
} else {
throw NotUpdatableELementError(cur.localName)
}
break
case '@':
clip.parts.push(
new EventPart(count, {
node: cur,
name: bindName
})
)
break
}
// console.log(cur)
count++
}
}
} else if (cur instanceof Comment) {
if (cur.data === `{{${markerIndex}}}`) {
const tail = new Comment(cur.data)
insertAfter(cur.parentNode!, tail, cur)
clip.parts.push(
new NodePart(
count,
{
startNode: cur,
endNode: tail
},
'node'
)
)
count++
walker.nextNode()
}
}
}
}
|
Markdown
|
UTF-8
| 896 | 2.546875 | 3 |
[] |
no_license
|
以下代码经过测试通过,系统centos 6.3
## 一、匹配或
sed 匹配100_1000或bigger_1000
```
sed -n '/100_1000\|bigger_1000/p' 20160220
sed -n '/\(100_1000\|bigger_1000\)/p' 20160220
```
awk匹配100_1000或bigger_1000
默认是$0匹配,所以写不写均可
```
awk '/100_1000/||/bigger_1000/{print $0}' 20160220 | head
awk '$0~/100_1000/||/bigger_1000/{print $0}' 20160220 | head
```
grep匹配100_1000或bigger_1000 -E选项表示扩展的正则表达式
```
grep -E '(100_1000|bigger_1000)' 20160220 | head
```
## 二、匹配与
sed匹配与
```
sed -n '/19000/{/100_1000/p}' 20160220 | head
```
awk匹配与
```
awk '/19000/&&/100_1000/{print $0}' 20160220 | head
awk '$0~/19000/&&/100_1000/{print $0}' 20160220 | head
```
grep匹配与
```
grep -E '(19000.*100_1000|100_1000.*19000)' 20160220 | head
```
|
Python
|
UTF-8
| 10,332 | 3.0625 | 3 |
[] |
no_license
|
import datetime
import pytz
import scipy
import numpy as np
import math
def calcLogR(data, delta=1):
"""
Calculates the log return of stock data over given time period.
The return is calculated over delta, where default delta = 1 weeks.
Data must be in format: dateTime, OHCLV.
Gaps in data for weekends and holidays (when NASDAQ is not in session)
are ignored when calculating the log returns. For example, this means
that in the calculations, Friday immediately precedes Monday, without
any gaps for Saturday or Sunday in-between.
This differs from the previous function, in that the delta is calculated
through the data without respect to the actual dates of the data. For
example, this means that for delta=1d, then the log return is calculated
from the prior value in the list, NOT necessarily from the prior day, as
weekends and holidays are skipped.
"""
EST = pytz.timezone("America/New_York")
logReturns = []
for i in range(delta, len(data)):
now = data[i]
prior = data[i-delta]
#dt
dt = now[0]
#calc log return as float:
logO = math.log10(now[1]/prior[1])
logH = math.log10(now[2]/prior[2])
logL = math.log10(now[3]/prior[3])
logC = math.log10(now[4]/prior[4])
logV = math.log10(now[5]/prior[5]) if now[5] >= 0 and prior[5] >= 0 else -1.0
print("log return open: "+str(logO)+", mapped to date: "+str(now[0]))
logReturns.append((dt.replace(tzinfo=EST), logO, logH, logL, logC, logV))
return logReturns
def ave(data):
aves = []
sum = data[0][1]
num = 1
for i in range(1, len(data)):
dt = data[i][0]
lastDt = data[i-1][0]
if dt.year == lastDt.year and dt.month == lastDt.month and dt.day == lastDt.day:
if data[i][1] != 0:
sum += data[i][1]
num += 1
else:
mean = sum / num
aves.append([lastDt, mean])
sum = data[i][1]
num = 1
#for the final one not counted
mean = sum / num
aves.append([data[len(data)-1][0], mean])
return aves
def calcSum(data):
sums = []
num = 1
for i in range(1, len(data)):
dt = data[i][0]
lastDt = data[i-1][0]
if dt.year == lastDt.year and dt.month == lastDt.month and dt.day == lastDt.day:
num += 1
else:
sums.append([lastDt, num])
num = 1
#for the final one not counted
sums.append([data[len(data)-1][0], num])
return sums
def ave2(startDt, endDt, data, zeros=True):
aves = []
days = _dayIter(startDt, endDt, datetime.timedelta(days=1))
days = list(days)[1:]
EST = pytz.timezone("America/New_York")
for day in days:
day = day.replace(tzinfo=EST)
priorDay = day - datetime.timedelta(days=1)
priorDay = priorDay.replace(tzinfo=EST)
day = day.replace(hour=16, minute=0)
priorDay = priorDay.replace(hour=16, minute=0)
sum = 0.0
num = 0
for line in data:
dt = line[0]
if dt > priorDay and dt <= day:
#sum += line[1] if line[1] > 0 else 2*line[1] #TEST TO SEE IF WEIGHTING NEGS MAKES MORE ACCURATE
sum += line[1]
num += 1
mean = sum / float(num) if num != 0 else 0
aves.append([day, mean])
sum = 0.0
num = 0
if not zeros:
i = 0
while True:
if i == len(aves):
break
elif -0.0005 < aves[i][1] < 0.0005:
aves.pop(i)
i -= 1
i += 1
return aves
def calcSum2(startDt, endDt, data):
sums = []
days = _dayIter(startDt, endDt, datetime.timedelta(days=1))
days = days[1:]
for day in days:
priorDay = day - datetime.timedelta(days=1)
day.replace(hour=16, minute=0)
priorDay.replace(hour=16, minute=0)
num = 0
for line in data:
dt = line[0]
if dt > priorDay and dt <= day:
num += 1
sums.append([day.date, num])
num = 0
return sums
def calcLSRL(x, y):
"""Calculates LSRL (a.k.a. OLS) in form: a + bx."""
#required for calcs below:
meanx = np.mean(x)
meany = np.mean(y)
#n & df
n = len(x)
df = n-2
#LSRL in form: a + bx
b_numerator = sum([(x[i] - meanx)*(y[i] - meany) for i in range(n)])
b_denominator = sum([(x[i] - meanx)**2 for i in range(n)])
b = b_numerator/b_denominator
a = meany - b*meanx
#R^2
SSres = sum([(y[i] - (a + b*x[i]))**2 for i in range(n)])
SStot = sum([(y[i] - meany)**2 for i in range(n)])
Rsqr = 1 - (SSres/SStot)
#R
R = math.sqrt(Rsqr)
#Standard error.
se_numerator = math.sqrt(SSres / (n-2))
se_denominator = math.sqrt(b_denominator)
se = se_numerator/se_denominator
#t score.
t = b/se
return a, b, n, df, Rsqr, R, se, t
def calcResids(x, y, LSRL):
a, b, n, df, Rsqr, R, se, t = LSRL
data = zip(x, y)
resids = []
for point in data:
xi = point[0]
yi = point[1]
yhat = a + b*xi
resid = yi - yhat
resids.append(resid)
return resids
def confInter(LSRL, alpha=0.05):
a, b, n, df, Rsqr, R, se, t = LSRL
critical = 1.96
me = critical*se
low = b - me
high = b + me
return (low, high)
def cov(x, y):
"""Returns covariance, which is equal to: E[xy] - E[x]E[y]."""
#where E[] is the expected value, a.k.a. the mean.
product = []
for i in range(len(x)):
product.append(x[i]*y[i])
meanp = np.mean(product)
meanx = np.mean(x)
meany = np.mean(y)
cov = meanp - meanx*meany
return cov
def R(x, y):
"""
Returns Pearson's correlation coeff between x and y.
This is equal to cov(x,y)/sqrt(var(x)var(y)).
"""
covar = cov(x, y)
varX = np.var(x)
varY = np.var(y)
Rcoeff = covar / math.sqrt(varX*varY)
return Rcoeff
def laggedRFunc(tsY, tsX, maxLag):
"""
Calculates and returns the correlation between the X time series
and Y time series, up to and including max lag.
Returns list of R's, in pairs of (lag, R).
The lag is performed on the tsX series, to determine if lagged values
of the tsX series have effect upon the tsY series.
"""
coeffs = []
#lag=0 (i.e. R=1)
Rcoeff = R(tsY, tsX)
coeffs.append([0, Rcoeff])
#other lags
for lag in range(1, maxLag+1):
ts = tsY[lag:]
lagts = tsX[:-lag]
Rcoeff = R(ts, lagts)
coeffs.append([lag, Rcoeff])
return coeffs
def ljungBox(x, y, maxLag):
if len(x) != len(y): return []
coeffs = laggedRFunc(y, x, maxLag)
n = len(x)
coeffs[0].append("none")
coeffs[0].append("none")
for lag in range(1, maxLag+1):
frac = 0.0
for k in range(1, lag+1):
frac += (coeffs[k][1]**2 / (n-k))
Q = frac*n*(n+2)
pval = scipy.stats.chi2.sf(Q, lag)
coeffs[lag].append(Q)
coeffs[lag].append(pval)
return coeffs
def pair(logR, exog, rsent, trend, lag=0):
"""
Pairs together the log return data and number of article data based on date.
"""
pairs = []
for lr in logR:
lDt = lr[0].date()
for e in exog:
eDt = e[0].date()-datetime.timedelta(days=lag)
if lDt == eDt:
o = lr[1]
h = lr[2]
l = lr[3]
c = lr[4]
v = lr[5]
ex = e[1]
pairs.append([lDt, o, h, l, c, v, ex])
break
for p in pairs:
pDt = p[0]
for r in rsent:
rDt = r[0].date()-datetime.timedelta(days=lag)
if pDt == rDt:
p.append(r[1])
break
for p in pairs:
pDt = p[0]
for t in trend:
tDt = t[0].date()-datetime.timedelta(days=lag)
if pDt == tDt:
p.append(t[1])
break
return pairs
def weightRank(articles, rankWeights):
lastDate = datetime.date.today()
for a in articles:
date = a[0].date
if date != lastDate:
num = 0
print a[2] #or [4], depending on the sent scheme
wr = a[2] * rankWeights[num]
a.append(wr)
lastDate = date
else:
num += 1
num = 5 if num > 5 else num
wr = a[2] * rankWeights[num]
a.append(wr)
lastDate = date
return articles
def diff(data, numDiff=1):
"""
Differences time series ts numDiff number of times.
If numDiff > 1, then performs difference between each
two consecutive points numDiff times. The difference is
assigned to the datetime of the latter of each consecutive
pair of points.
dt is the corresponding datetimes for this series (x)
ts is the time series values (y)
"""
dt, ts = zip(*data)
for x in range(numDiff):
new_dt = dt[1:]
new_ts = []
for i in range(1, len(ts)):
d = ts[i] - ts[i-1]
new_ts.append(d)
dt = new_dt
ts = new_ts
diff_data = zip(dt, ts)
for i in range(len(diff_data)):
diff_data[i] = list(diff_data[i])
return diff_data
def discrete(x, y):
"""
Quantizes the standard LSRL procedure to pos and neg.
"""
#x>0 y>0
xPosYPos = 0
xPosYNeg = 0
xNegYPos = 0
xNegYNeg = 0
for i in range(len(x)):
if x[i] > 0 and y[i] > 0:
xPosYPos += 1
elif x[i] > 0 and y[i] < 0:
xPosYNeg += 1
elif x[i] < 0 and y[i] > 0:
xNegYPos += 1
elif x[i] < 0 and y[i] < 0:
xNegYNeg += 1
#prob of getting y=pos given that x=pos
yPosGivenXPos = xPosYPos / float(xPosYPos+xPosYNeg) if float(xPosYPos+xPosYNeg) > 0 else 0
#prob of getting y=neg given that x=neg
yNegGivenXNeg = xNegYNeg / float(xNegYNeg+xNegYPos) if float(xNegYNeg+xNegYPos) > 0 else 0
#prob of getting y=neg given that x=neg
yPosGivenXNeg = xNegYPos / float(xNegYNeg+xNegYPos) if float(xNegYNeg+xNegYPos) > 0 else 0
#prob of getting y=neg given that x=neg
yNegGivenXPos = xPosYNeg / float(xPosYNeg+xPosYPos) if float(xPosYNeg+xPosYPos) > 0 else 0
print("Probability of y>0 given x>0: "+str(yPosGivenXPos))
print("Probability of y<0 given x<0: "+str(yNegGivenXNeg))
print("")
print("Probability of y<0 given x>0: "+str(yNegGivenXPos))
print("Probability of y>0 given x<0: "+str(yPosGivenXNeg))
def _dayIter(start, end, delta):
"""
Returns datetimes from [start, end) for use in iteration.
"""
current = start
while current < end:
yield current
current += delta
def ma(data, period=20):
"""
Calculates the moving average of the timeseries ts.
"""
dt, ts = zip(*data)
new_dt = []
new_ts = []
for i in range(period, len(ts)):
sum = 0
for j in range(i-period, i):
sum += ts[j]
ave = sum/period
new_dt.append(dt[i])
new_ts.append(ave)
new_data = [new_dt, new_ts]
new_data = zip(*new_data)
return new_data
def median(data, period=20):
"""
Calculates the moving average of the timeseries ts.
"""
dt, ts = zip(*data)
new_dt = []
new_ts = []
for i in range(period, len(ts)):
sub = []
for j in range(i-period, i):
sub.append(ts[j])
med = np.median(sub)
new_dt.append(dt[i])
new_ts.append(med)
new_data = [new_dt, new_ts]
new_data = zip(*new_data)
return new_data
def onlyLargeReturns(data, pd=5):
final = []
for i in range(pd, len(data)):
past = data[i-pd:i]
dt, o, h, l, c, v = zip(*past)
m = np.mean(c)
s = np.std(c)
if abs(data[i][4] - m) >= s:
final.append(data[i])
return final
|
PHP
|
UTF-8
| 645 | 3.0625 | 3 |
[] |
no_license
|
<?php
interface Export {
public function export();
}
class Json implements Export {
public function export()
{
return json_encode([__FUNCTION__]);
}
}
class Xml implements Export {
public function export()
{
return 'XML';
}
}
class PlainText implements Export {
public function export()
{
return 'Plain Text';
}
}
class Client {
private $exp;
public function __construct(Export $exp)
{
$this->exp = $exp;
}
public function doExport()
{
return $this->exp->export();
}
}
$client = new Client(new Json());
print $client->doExport();
|
JavaScript
|
UTF-8
| 4,357 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
import * as HumanGuiStrategy from './HumanGuiStrategy.js';
import * as HumanCliStrategy from './HumanCliStrategy.js';
import * as ComputerStrategy from './ComputerStrategy.js';
import * as HumanRemoteStrategy from './HumanRemoteStrategy.js';
import * as Timer from './util/Timer.js';
import * as Settings from './util/Settings.js';
/**
* Player can be a human or a computer type
* Its strategy will be updated according its type
*
* a Strategy must looks like:
* {
* isHuman
* Promise selectColumn(model) //the promise is resolved when the player choose a column. The promise return the choosen column number
* interrupt()
* }
*
*/
class Player {
/**
*
* @param {*} config if a String then it will be the name of the player else
* {
* key :'' // to identify the player
* name : '' // name of the player
* color : '' // color of the player
* }
* @param {*} settings : isHuman, level
*/
constructor(config, settings){
this.settings = Settings.init(settings);
let isHuman = this.settings.listen('isHuman', (newval)=>{
this.$changeStrategy(newval);
this.timer.enable(config.timerEnabled && newval);
}, false);
this.settings.listen('level', (newval)=>{
this.strategy.depth = newval;
}, 3);
this.timer = new Timer.Timer(config.timerEnabled && isHuman);
this.nextPlayer = null;
this.isCurrentPlayer = false;
//color
this.suspended = false;
this.$changeStrategy(isHuman);
if (typeof config == "string"){
this.name = config;
this.key = config;
}else{
Object.assign(this, config);
}
}
$changeStrategy(isHuman){
if ( isHuman ){
if (this.remoteManager){
this.strategy = new HumanRemoteStrategy.HumanRemoteStrategy();
}else if (this.board){
this.strategy = new HumanGuiStrategy.HumanGuiStrategy(this.board);
}else{
this.strategy = new HumanCliStrategy.HumanCliStrategy();
}
}else{
this.strategy = new ComputerStrategy.ComputerStrategy(this, this.settings.level);
}
}
isHuman(){
return this.strategy.isHuman;
}
isRemote(){
return this.strategy.isRemote;
}
/**human need a board to play with a GUI */
setBoard(board){
this.board = board;
//update strategy with the new board
this.$changeStrategy(this.isHuman());
}
/**
* Set the player as remote.
*
* @param {*} remoteManager used to communicate with the remote player. if null the player will be local
*/
setRemote(remoteManager, model){
if (this.remoteManager != remoteManager){
this.remoteManager = remoteManager;
this.$changeStrategy(true);
if (remoteManager) this.strategy.init(remoteManager, model);
}
}
/**
* Call by the app when the player is the current player and should play
*
* @param {*} model
* @returns a Promise with the choosen column number
*/
selectColumn(model){
this.timer.resume();
return this.strategy.selectColumn(model)
.finally(()=>{
this.timer.suspend();
});
}
/**
* this player become the curent player and 'otherPlayer' will be the next
* initialize players in order to both players to know who is the next one
* @param {*} otherPlayer
*/
initPlayer(otherPlayer){
this.nextPlayer = otherPlayer;
otherPlayer.nextPlayer = this;
this.isCurrentPlayer = true;
otherPlayer.isCurrentPlayer = false;
this.timer.reset();
otherPlayer.timer.reset();
}
/**
*
*/
switchToNextPlayer(){
if (! this.isCurrentPlayer) console.error("The player", this.name, "is not the current one. switchToNextPlayer() must not be called")
this.isCurrentPlayer = false;
this.nextPlayer.isCurrentPlayer = true;
return this.nextPlayer;
}
/** interrupt a player while playing
*/
interrupt(){
this.strategy.interrupt();
}
}
export {Player};
|
C
|
UTF-8
| 741 | 2.65625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include "include/choice.h"
#include "include/comp_mode.h"
#include <stdlib.h>
#include "include/menu.h"
#include "include/rating.h"
void choice_comp(Profile *profile)
{
int number;
printf(" Your next step:\n\n");
printf(" 1) return to the menu 2) see rating\n\n");
printf(" Your choice: ");
scanf("%d", &number);
scanf("%*[^\n]");
if (number == 1)
{
system("clear");
fast_intro(1);
//menu();
}
else
{
if (number == 2)
{
output();
}
else
{
system("clear");
printf("Error! Enter 1 or 2\n\n");
choice_comp(profile);
}
}
}
|
Python
|
UTF-8
| 1,913 | 2.75 | 3 |
[] |
no_license
|
import ast
import json
from pyspark import SparkContext, SparkConf
from pyspark.rdd import RDD
from pyspark.streaming import StreamingContext
path = '../done_data/type/type_by_year.json'
def open_result():
try:
result = open(path, 'r', encoding='utf-8')
type_dict = json.load(result)
result.close()
except Exception as e:
type_dict = {}
return type_dict
# 把读入的字符串line处理成列表
def getList(line):
date_disposition = line.split(';')
date_disposition[0] = date_disposition[0][0:4]
date_disposition[1] = date_disposition[1].replace("'", "")
return date_disposition
def writeFile(rdd: RDD):
num = rdd.count()
if num > 0:
result_dic = open_result()
print(result_dic)
rdd_c = rdd.collect()
lst = ast.literal_eval(str(rdd_c))
for item in lst:
key = item[0]
value = item[1]
if str(key).replace("'", '') in result_dic.keys():
result_dic[str(key).replace("'", '')] = result_dic[str(key).replace("'", '')] + value
else:
result_dic[str(key).replace("'", '')] = value
result = open(path, 'w', encoding='utf-8')
result.write(json.dumps(result_dic).encode('gb18030').decode('unicode_escape'))
result.close()
def start():
conf = SparkConf()
conf.setAppName('TestDStream3')
conf.setMaster('local')
sc = SparkContext(conf=conf)
ssc = StreamingContext(sc, 3)
lines = ssc.textFileStream('../cleaned_data/type')
print(lines)
single = lines.map(getList)
# date_disposition: 发表日期-性向 RDD
date_disposition = single \
.filter(lambda x: len(x[1]) > 0) \
.map(lambda x: ((x[0][0:4], x[1]), 1)) \
.reduceByKey(lambda x, y: x + y) \
.foreachRDD(lambda x: writeFile(x))
ssc.start()
ssc.awaitTermination()
|
Java
|
UTF-8
| 272 | 2.875 | 3 |
[] |
no_license
|
package mementopattern;
public class Record{
String state = null;
public Record(String state){
this.state = state;
}
public String getState(){
return state;
}
public void setState(String state){
this.state = state;
}
}
|
Ruby
|
UTF-8
| 1,460 | 3.078125 | 3 |
[] |
no_license
|
def parse_tag(string)
tag = {}
# save tag after < character
tag_type = string.match(/<(\w+)(?:>| )/)
# saves either side of an equal sign
attributes = string.scan(/(\w+)\s*=\s*['"](.*?)['"]/)
#options
options = string.scan(/\s*(\w)\s*[^=]/)
tag[:type] = tag_type[1]
attributes.each do |attribute|
tag[attribute[0].to_sym] = attribute[1]
end
tag
end
# p tag = parse_tag("<p class=\"foo bar\" id='baz' src = 'hello' repeat>")
# p tag = parse_tag("<img src='http://www.example.com' title = 'funny things' repeat>")
# p tag = parse_tag("<div> div text before <p> p text </p> <div> more div text </div> div text after</div>"
)
Node = Struct.new(:data, :children, :parent)
def parser_script(string)
make_node
iterate through string
tag = []
when < is hit,
go up one level if next char is /
start pushing to tag
when > is hit, stop pushing to tag
send tag to tag_parser
create parsed_tag Node
send node to tree_builder
make_node(children)
end
end
split string into array of tags (opening and closing)
create root node from first tag (data=tag, parent nil children nil)
set root node as current_node
if closing_tag, current_node = current_node.parent
node = Node.new(tag, parent = current_node, children=nil)
current_node.children << node
html_string = "<div> div text before <p> p text </p> <div> more div text </div> div text after</div>"
|
Java
|
UTF-8
| 1,078 | 2 | 2 |
[
"Apache-2.0"
] |
permissive
|
package test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.alibaba.fastjson.JSON;
import com.my.springboot.demo.SpringBootDemoApplication;
import com.my.springboot.demo.dao.StudentMapper;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootDemoApplication.class)
public class StudentMapperTest {
@Autowired
StudentMapper studentMapper;
@Test
public void testSelectStudent() throws Exception {
System.out.println("----------------------------------------------------------------"+"StudentMapperTest.testSelectStudent()" +"----------------------------------------------------------------");
// System.out.println(JSON.toJSONString(studentMapper.selectStudent(21000L)));
System.out.println(JSON.toJSONString(studentMapper.selectStudentsByClass(11000L)));
// System.out.println(JSON.toJSONString(studentMapper.selectStudentExtra(21000L)));
}
}
|
JavaScript
|
UTF-8
| 1,248 | 2.9375 | 3 |
[] |
no_license
|
app11.directive("player", function() {
// Create a directive object
var directive = {};
// Define that we are using an element directive instead of
// a A: attribute, C: class, or M: comment
// I covered how to apply as an attribute previously
// I normally only apply as elements or attributes because
// it is easy to figure out where the directive was applied.
directive.restrict = 'E';
// The template is filled with the data and replaces the element
directive.template = "{{player.name}} had a {{player.avg}} AVG with {{player.hr}} homeruns and a {{player.obp}} OBP";
// Scope defines what is unique about each element
directive.scope = { player: "=name" };
// compile is called during the initialization phase
directive.compile = function(element, attributes){
// The link function receives the scope, the element The
// directive is associated with and that elements
// attributes. Here we can handle events on that element
var linkFunc = function($scope, element, attributes){
element.bind('click', function() {
element.html('Barry disappeared');
});
}
return linkFunc;
}
return directive;
});
|
Java
|
UTF-8
| 13,784 | 3.515625 | 4 |
[
"MIT-Modern-Variant"
] |
permissive
|
package nachos.threads;
import nachos.machine.*;
import java.util.HashMap;
/**
* A <i>Rendezvous</i> allows threads to synchronously exchange values.
*/
public class Rendezvous {
/**
* Allocate a new Rendezvous.
*/
private nachos.threads.Lock lock;
private HashMap<Integer, Integer> tag_val;
private HashMap<Integer, nachos.threads.Condition> tag_con;
public Rendezvous () {
lock = new nachos.threads.Lock();
tag_val = new HashMap<Integer, Integer>();
tag_con = new HashMap<Integer, nachos.threads.Condition>();
}
/**
* Synchronously exchange a value with another thread. The first
* thread A (with value X) to exhange will block waiting for
* another thread B (with value Y). When thread B arrives, it
* will unblock A and the threads will exchange values: value Y
* will be returned to thread A, and value X will be returned to
* thread B.
*
* Different integer tags are used as different, parallel
* synchronization points (i.e., threads synchronizing at
* different tags do not interact with each other). The same tag
* can also be used repeatedly for multiple exchanges.
*
* @param tag the synchronization tag.
* @param value the integer to exchange.
*/
public int exchange (int tag, int value) {
lock.acquire();
// System.out.println("Exchanging... thread_id = " + nachos.threads.KThread.currentThread().getName());
boolean is_exchanged = true;
if (!tag_val.containsKey(tag)) {
is_exchanged = true;
tag_val.put(tag, value);
Condition con = new Condition(lock);
tag_con.put(tag, con);
con.sleep();
}
else {
is_exchanged = false;
Condition con = tag_con.get(tag);
con.wake();
}
int val = tag_val.get(tag);
tag_val.put(tag, value);
// System.out.println("Thread_id: " + nachos.threads.KThread.currentThread().getName() + ", is_exchanged: " + is_exchanged);
if (is_exchanged) {
tag_val.remove(tag);
tag_con.remove(tag);
}
lock.release();
return val;
}
// Test case starting here ...
public static void testCase1() {
System.out.println("\n**********Rendezvous TESTCASE 1**********");
System.out.println("Exchange returns the exchanged values from the threads properly.");
final Rendezvous p = new Rendezvous();
KThread t1 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 1;
System.out.println("Thread " + KThread.currentThread().getName() + ", original value: " + val);
int ans = p.exchange (tag, val);
Lib.assertTrue (ans == 2, "Expecting " + 2 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", received value " + ans);
}
});
t1.setName("t1");
KThread t2 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 2;
System.out.println("Thread " + KThread.currentThread().getName() + ", original value: " + val);
int ans = p.exchange (tag, val);
Lib.assertTrue (ans == 1, "Expecting " + 1 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", received " + ans);
}
});
t2.setName("t2");
t1.fork();
t2.fork();
t1.join();
t2.join();
}
public static void testCase2() {
System.out.println("**********Rendezvous TESTCASE 2**********");
System.out.println("many threads can call exchange on the same tag, and exchange will correctly pair them up and exchange their values.");
final Rendezvous p = new Rendezvous();
KThread t1 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 1;
System.out.println("Thread " + KThread.currentThread().getName() + ", original value: " + val);
int ans = p.exchange (tag, val);
Lib.assertTrue (ans == 2, "Expecting " + 2 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", received value: " + ans);
}
});
t1.setName("t1");
KThread t2 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 2;
System.out.println("Thread " + KThread.currentThread().getName() + ", original value: " + val);
int ans = p.exchange (tag, val);
Lib.assertTrue (ans == 1, "Expecting " + 1 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", received value: " + ans);
}
});
t2.setName("t2");
KThread t3 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 3;
System.out.println("Thread " + KThread.currentThread().getName() + ", original value: " + val);
int ans = p.exchange (tag, val);
Lib.assertTrue (ans == 4, "Expecting " + 4 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", received value: " + ans);
}
});
t3.setName("t3");
KThread t4 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 4;
System.out.println("Thread " + KThread.currentThread().getName() + ", original value: " + val);
int ans = p.exchange (tag, val);
Lib.assertTrue (ans == 3, "Expecting " + 3 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", received value: " + ans);
}
});
t4.setName("t4");
t1.fork();
t2.fork();
t1.join();
t2.join();
t3.fork();
t4.fork();
t3.join();
t4.join();
}
public static void testCase3() {
System.out.println("**********Rendezvous TESTCASE 3**********");
System.out.println("Threads exchanging values on different tags operate independently of each other.");
final Rendezvous p = new Rendezvous();
KThread t1 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 1;
System.out.println("Thread " + KThread.currentThread().getName() + ", tag: 0" + ", original value: " + val);
int ans = p.exchange (tag, val);
Lib.assertTrue (ans == 3, "Expecting " + 3 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", tag: 0" + ", received value: " + ans);
}
});
t1.setName("t1");
KThread t2 = new KThread( new Runnable () {
public void run() {
int tag = 1;
int val = 2;
System.out.println("Thread " + KThread.currentThread().getName() + ", tag: 1" + ", original value: " + val);
int ans = p.exchange (tag, val);
Lib.assertTrue (ans == 4, "Expecting " + 4 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", tag: 1" + ", received value: " + ans);
}
});
t2.setName("t2");
KThread t3 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 3;
System.out.println("Thread " + KThread.currentThread().getName() + ", tag: 0" + ", original value: " + val);
int ans = p.exchange (tag, val);
Lib.assertTrue (ans == 1, "Expecting " + 1 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", tag: 0" + ", received value: " + ans);
}
});
t3.setName("t3");
KThread t4 = new KThread( new Runnable () {
public void run() {
int tag = 1;
int val = 4;
System.out.println("Thread " + KThread.currentThread().getName() + ", tag: 1" + ", original value: " + val);
int ans = p.exchange (tag, val);
Lib.assertTrue (ans == 2, "Expecting " + 2 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", tag: 1" + ", received value: " + ans);
}
});
t4.setName("t4");
t1.fork();
t2.fork();
t3.fork();
t4.fork();
t1.join();
t2.join();
t3.join();
t4.join();
}
public static void testCase4() {
System.out.println("**********Rendezvous TESTCASE 4**********");
System.out.println("Threads exchanging values on different instances of Rendezvous operate independently of each other.");
final Rendezvous p1 = new Rendezvous();
final Rendezvous p2 = new Rendezvous();
KThread t1 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 1;
System.out.println("Thread " + KThread.currentThread().getName() + ", instance: 1" + ", original value: " + val);
int ans = p1.exchange (tag, val);
Lib.assertTrue (ans == 3, "Expecting " + 3 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", instance: 1" + ", received value: " + ans);
}
});
t1.setName("t1");
KThread t2 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 2;
System.out.println("Thread " + KThread.currentThread().getName() + ", instance: 2" + ", original value: " + val);
int ans = p2.exchange (tag, val);
Lib.assertTrue (ans == 4, "Expecting " + 4 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", instance: 2" + ", received value: " + ans);
}
});
t2.setName("t2");
KThread t3 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 3;
System.out.println("Thread " + KThread.currentThread().getName() + ", instance: 1" + ", original value: " + val);
int ans = p1.exchange (tag, val);
Lib.assertTrue (ans == 1, "Expecting " + 1 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", instance: 1" + ", received value: " + ans);
}
});
t3.setName("t3");
KThread t4 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 4;
System.out.println("Thread " + KThread.currentThread().getName() + ", instance: 2" + ", original value: " + val);
int ans = p2.exchange (tag, val);
Lib.assertTrue (ans == 2, "Expecting " + 2 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", instance: 2" + ", received value: " + ans);
}
});
t4.setName("t4");
t1.fork();
t2.fork();
t3.fork();
t4.fork();
t1.join();
t2.join();
t3.join();
t4.join();
}
public static void testCase5() {
System.out.println("\n**********Rendezvous TESTCASE 5**********");
System.out.println("A thread only returns from exchange when another thread synchronizes with it.");
final Rendezvous p = new Rendezvous();
KThread t1 = new KThread( new Runnable () {
public void run() {
int tag = 0;
int val = 1;
System.out.println("Thread " + KThread.currentThread().getName() + ", tag: 0" + ", original value: " + val);
int ans = p.exchange (tag, val);
// Lib.assertTrue (ans == 2, "Expecting " + 1 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", tag: 0" + ", received value " + ans);
}
});
t1.setName("t1");
KThread t2 = new KThread( new Runnable () {
public void run() {
int tag = 1;
int val = 2;
System.out.println("Thread " + KThread.currentThread().getName() + ", tag: 1" + ", original value: " + val);
int ans = p.exchange (tag, val);
// Lib.assertTrue (ans == 1, "Expecting " + 1 + ", but received: " + ans);
System.out.println("Thread " + KThread.currentThread().getName() + ", tag: 1" + ", received " + ans);
}
});
t2.setName("t2");
t1.fork();
t2.fork();
t1.join();
t2.join();
}
public static void selfTest() {
System.out.println("\n**********Start Rendezvous Testing**********");
testCase1();
testCase2();
testCase3();
testCase4();
// testCase5();
}
}
|
C++
|
UTF-8
| 1,593 | 2.703125 | 3 |
[
"BSL-1.0"
] |
permissive
|
/*
* TEXT LAYOUT
* Copyright © 2018+ Ángel Rodríguez Ballesteros
*
* Distributed under the Boost Software License, version 1.0
* See documents/LICENSE.TXT or www.boost.org/LICENSE_1_0.txt
*
* angel.rodriguez@esne.edu
*
* C1802030140
*/
#include <basics/Text_Layout>
namespace basics
{
Text_Layout::Text_Layout(const Raster_Font & font, const std::wstring & text)
:
width (0.f),
height(0.f)
{
Raster_Font::Metrics metrics = font.get_metrics ();
glyphs.reserve (text.length ());
float current_x = 0;
float current_y = -metrics.line_height;
float line_width = 0;
for (auto & c : text)
{
if (c == L'\n')
{
if (current_x > width) width = current_x;
current_x = 0.f;
current_y -= metrics.line_height;
}
else
{
const Raster_Font::Character * character = font.get_character (uint32_t(c));
if (character)
{
glyphs.emplace_back
(
character->slice,
Point2f{ current_x + character->offset[0], current_y + metrics.line_height - character->offset[1] },
Size2f { character->slice->width, character->slice->height }
);
if (current_x == 0.f) height += metrics.line_height;
current_x += character->advance;
}
}
}
if (current_x > width) width = current_x;
}
}
|
Java
|
UTF-8
| 1,792 | 2.921875 | 3 |
[] |
no_license
|
package com.ms.encryptsharing.dsa;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
public class DSAGenerator {
/**
* 生成公钥文件和私钥文件
*/
public static void generate() {
generate(DSACommons.DEFAULT_SEED, DSACommons.PUBLIC_KEY_FILE, DSACommons.PRIVATE_KEY_FILE);
}
/**
* 生成公钥文件和私钥文件
*
* @param seed
* 种子
* @param publicKeyFile
* 公钥文件
* @param privateKeyFile
* 私钥文件
*/
public static void generate(String seed, String publicKeyFile, String privateKeyFile) {
// 生成公钥和私钥
KeyPairGenerator keygen;
try {
keygen = KeyPairGenerator.getInstance(DSACommons.KEY_ALGORITHM);
// 初始化随机产生器
SecureRandom secureRandom = new SecureRandom();
secureRandom.setSeed(seed.getBytes());
keygen.initialize(1024, secureRandom);
KeyPair keys = keygen.genKeyPair();
PublicKey pubkey = keys.getPublic();
PrivateKey prikey = keys.getPrivate();
// 分别保存在myprikey.dat和mypubkey.dat中,以便下次不在生成
java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(
new java.io.FileOutputStream(privateKeyFile));
out.writeObject(prikey);
out.close();
out = new java.io.ObjectOutputStream(new java.io.FileOutputStream(publicKeyFile));
out.writeObject(pubkey);
out.close();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
Swift
|
UTF-8
| 4,496 | 2.875 | 3 |
[] |
no_license
|
//
// JSONParser.swift
// GitHubiOSAPI
//
// Created by Melaniia Hulianovych on 4/13/17.
// Copyright © 2017 Melaniia Hulianovych. All rights reserved.
//
import Foundation
import UIKit
class JSONParser {
func parseUserInfo(withdata data: NSDictionary) -> User {
let user = User()
if let name = data["name"] {
user.name = name as! String
}
if let login = data["login"] {
user.login = login as! String
}
if let avatarURL = data["avatar_url"] {
user.avatarURL = avatarURL as! String
}
if let created = data["created_at"] {
user.created = created as! String
}
if let followers = data["followers"] {
user.followers = followers as! Int
}
if let following = data["following"] {
user.following = following as! Int
}
if let publicRepo = data["public_repos"] {
user.publicRepo = publicRepo as! Int
}
return user
}
func parseRepositories(fromArray array:NSArray) -> [Repository] {
var repositories = [Repository]()
for dic in array {
let repo = parseRepo(withDict: dic as! NSDictionary)
DataSource.shared.user.starsCount += repo.starsCount
repositories.append(repo)
}
return repositories
}
func parseRepo(withDict dict: NSDictionary) -> Repository {
let repo = Repository()
if let name = dict["name"] {
repo.repoName = name as! String
}
if let language = dict["language"] {
repo.language = language as! String
}
if let id = dict["id"] {
repo.id = id as! Int
}
if let forkedFrom = dict["fork"] {
repo.forkedFrom = forkedFrom as! Bool
}
if let forks = dict["forks"] {
repo.forks = forks as! Int
}
if let description = dict["description"] as? String {
repo.description = description
}
if let forks = dict["forks_count"] {
repo.forks = forks as! Int
}
if let watchers = dict["watchers_count"] {
repo.watchers = watchers as! Int
}
if let starsCount = dict["stargazers_count"] {
repo.starsCount = starsCount as! Int
}
if let updated = dict["updated_at"] as? String {
repo.lastUpdate = df.date(from: updated)
}
return repo
}
func parseAuthor(fromDic dic:NSDictionary, intoCommit commit:Commit) -> Commit {
if let committer = dic["committer"] {
if let name = (committer as! NSDictionary)["name"] {
commit.author = name as! String
}
if let date = (committer as! NSDictionary)["date"] as? String {
commit.cratedDate = df.date(from: date)!
}
}
if let message = dic["message"] {
commit.message = message as! String
}
return commit
}
func parseCommits(fromArray array: NSArray) ->[Commit] {
var commits = [Commit]()
for item in array {
let commit = Commit()
if let comAv = (item as! NSDictionary)["commiter"] as? NSDictionary{
if let avatar = comAv["avatar_url"] as? String {
commit.authorAvatar = avatar
}
}
if let com = (item as! NSDictionary)["commit"] {
commits.append(parseAuthor(fromDic: com as! NSDictionary, intoCommit: commit))
}
}
return commits
}
}
class User {
var name = ""
var login = ""
var created: String!
var avatarURL = ""
var followers: Int = 0
var following: Int = 0
var publicRepo = 0
var starsCount = 0
}
class Repository {
var repoName: String = ""
var language: String = ""
var id: Int!
var forkedFrom = false
var forks = 0
var description = ""
var watchers = 0
var starsCount = 0
var lastUpdate: Date!
var commits = [Commit]()
}
class Commit {
var author = ""
var authorAvatar = ""
var cratedDate = Date()
var message = ""
var imageForAvatar: UIImage?
}
let df : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter
}()
|
Python
|
UTF-8
| 1,773 | 3.703125 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
# @Time : 2020/9/17 11:16 下午
# @Author : ddz
# 01 背包
# 描述:
# 有N件物品和一个容量为V的背包。
# 第i件物品的体积是vi,价值是wi。
# 求解将哪些物品装入背包,可使这些物品的总体积不超过背包流量,且总价值最大。
def backpack01(n, v, goods):
# 思路一:二维动态规划
# f[i][j] 前 i 个物品,体积为 j 的情况下,总价值最大
# 递推公式:
# 1. 不选第 i 个物品 f[i][j] = f[i-1][j]
# 2. 选第 i 个物品 f[i][j] = f[i-1][j-v[i]] + w[i]
# 初始化,先全部赋值为0,这样至少体积为0或者不选任何物品的时候是满足要求
# dp = [[0 for i in range(v + 1)] for j in range(n + 1)]
#
# for i in range(1, n + 1):
# for j in range(1, v + 1):
# dp[i][j] = dp[i - 1][j] # 第i个物品不选
# if j >= goods[i - 1][0]: # 判断背包容量是不是大于第i件物品的体积
# # 在选和不选的情况中选出最大值
# dp[i][j] = max(dp[i][j], dp[i - 1][j - goods[i - 1][0]] + goods[i - 1][1])
#
# print(dp[-1][-1])
# 优化思路一:一维动态规划
# 根据二维动态规划可以看出,f[i] 只与f[i-1]相关。
# 因此状态转移方程为:dp[i] = max(dp[i] , dp[i-v[i]]+w[i])
# 注意:这个必须要从后面遍历,不然状态 dp[i-v[i]] 就会改变,就不是dp[i-1][i-v[i]] 了
dp = [0 for i in range(v + 1)]
# dp[j] 代表体积为 j 的情况下,总价值最大
for i in range(n):
for j in range(v, -1, -1): # 从后往前
if j >= goods[i][0]:
dp[j] = max(dp[j], dp[j - goods[i][0]] + goods[i][1])
print(dp[-1])
|
Java
|
UTF-8
| 47,671 | 1.804688 | 2 |
[
"MIT"
] |
permissive
|
package com.ruoyi.project.deveagent.usertrapos.service.impl;
import com.ruoyi.common.constant.SysTableNameConstant;
import com.ruoyi.common.constant.TypeStatusConstant;
import com.ruoyi.common.utils.BasicSerivce;
import com.ruoyi.common.utils.json.NetJsonUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.string.StringUtil;
import com.ruoyi.common.utils.string.TrimUtil;
import com.ruoyi.common.utils.time.TimeUtil;
import com.ruoyi.project.deveagent.syspos.mapper.AgentSysTraditionalPosInfoMapper;
import com.ruoyi.project.deveagent.syspospolicy.service.SysPosPolicyServiceImpl;
import com.ruoyi.project.deveagent.user.mapper.AgentUserInfoMapper;
import com.ruoyi.project.deveagent.usertrapos.domain.AgentSelectUserTraditionalPosInfo;
import com.ruoyi.project.deveagent.usertrapos.domain.AgentUserTraditionalPosInfo;
import com.ruoyi.project.deveagent.usertrapos.mapper.AgentUserEPosInfoMapper;
import com.ruoyi.project.deveagent.usertrapos.mapper.AgentUserTraditionalPosInfoMapper;
import com.ruoyi.project.deveagent.usertrapos.service.AgentUserEPosInfoService;
import com.ruoyi.project.deveagent.usertrapos.service.AgentUserTraditionalPosInfoService;
import com.ruoyi.project.develop.common.domain.R;
import com.ruoyi.project.develop.common.domain.R.Type;
import com.ruoyi.project.devemana.param.mapper.ManaSysEditMapper;
import com.ruoyi.project.devemana.param.mapper.ManaSysParamRateMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 代理====》用户传统POS信息管理
* @author Administrator
*
*/
@Service
public class AgentUserEPosInfoServiceImpl extends BasicSerivce implements AgentUserEPosInfoService {
@Autowired
private ManaSysEditMapper manaSysEditMapper;
@Autowired
private AgentUserEPosInfoMapper agentUserEPosInfoMapper;
@Autowired
private AgentUserTraditionalPosInfoMapper agentUserTraditionalPosInfoMapper;
@Autowired
private AgentUserInfoMapper agentUserInfoMapper;
@Autowired
private ManaSysParamRateMapper manaSysParamRateMapper;
@Autowired
private AgentSysTraditionalPosInfoMapper agentSysTraditionalPosInfoMapper;
@Autowired
private SysPosPolicyServiceImpl sysPosPolicyService;
/**
* 查询用户传统POS信息列表
*/
@Override
public List<Map<String, Object>> getAgentUserTraditionalPosInfoList(Map<String, Object> params) {
MapChainParams(params);
return agentUserEPosInfoMapper.getAgentUserTraditionalPosInfoList(params);
}
/**
* 导出用户传统POS信息列表
*/
@Override
public List<AgentUserTraditionalPosInfo> selectAgentUserTraditionalPosInfoList(Map<String, Object> params) {
MapChainParams(params);
return agentUserEPosInfoMapper.selectAgentUserTraditionalPosInfoList(params);
}
/**
* 导入用户传统POS数据
*/
@Override
public R importAgentUserTraditionalPosInfoList(List<AgentUserTraditionalPosInfo> agentuserTraditionalPosInfoList,
String user_id) {
if(!ShiroUtils.getSysUser().isAuth()) {
return R.error(Type.WARN, "身份信息未认证,不能操作");
}
if (StringUtil.isNull(agentuserTraditionalPosInfoList) || agentuserTraditionalPosInfoList.size() == 0){
return R.error(Type.WARN, "导入用户传统POS数据不能为空!");
}
//校验是否是一级代理用户并且实名认证
Map<String, Object> params = new HashMap<>();
params.put("user_id", user_id);//用户编号
params.put("manager_id", ShiroUtils.getUserId());//代理编号
Map<String, Object> userMap = agentUserInfoMapper.getAgentFirstAgentUserInfo(params);
if(userMap==null) {
return R.error(Type.WARN, "只能给属于自己的一级代理分配POS机");
}
if(!TypeStatusConstant.user_info_auth_status_09.equals(userMap.get("auth_status").toString())) {
return R.error(Type.WARN, "该用户未实名认证,不能分配POS机");
}
int success_num = 0;//成功数量
int failure_num = 0;//失败数量
String failure_msg = "";//失败消息
for(int i=0;i<agentuserTraditionalPosInfoList.size();i++) {
//依次导入每一个传统POS机信息
agentuserTraditionalPosInfoList.get(i).setUser_id(user_id);//用户编号
R result = SpringUtils.getAopProxy(this).importAgentUserTraditionalPosInfo(agentuserTraditionalPosInfoList.get(i),i);
if(Type.SUCCESS.value.equals(result.get("code").toString())) {
success_num++;
}else {
failure_num++;
failure_msg = failure_msg+"<br/>"+result.get("msg").toString();
}
}
if(failure_num>0) {
failure_msg = "导入结果:成功"+success_num+"条,失败"+failure_num+"条<br/>失败信息如下:<br/>"+failure_msg;
}else {
failure_msg = "导入结果:成功"+success_num+"条,失败"+failure_num+"条";
}
return R.ok(failure_msg);
}
/**
* 导入单条数据
* @param agentUserTraditionalPosInfo
* @param m
* @return
*/
public R importAgentUserTraditionalPosInfo(AgentUserTraditionalPosInfo agentUserTraditionalPosInfo, int m) {
try {
agentUserTraditionalPosInfo = (AgentUserTraditionalPosInfo) TrimUtil.trimObject(agentUserTraditionalPosInfo);
if(StringUtils.isEmpty(agentUserTraditionalPosInfo.getSn())) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:设备号(机器编号)必填");
}
if(StringUtils.isEmpty(agentUserTraditionalPosInfo.getCard_settle_price())) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:刷卡结算底价必填");
}
if(StringUtils.isEmpty(agentUserTraditionalPosInfo.getCard_settle_price_vip())) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:VIP刷卡结算底价必填");
}
if(StringUtils.isEmpty(agentUserTraditionalPosInfo.getCloud_settle_price())) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:云闪付结算底价必填 ");
}
if(StringUtils.isEmpty(agentUserTraditionalPosInfo.getWeixin_settle_price())) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:微信结算底价必填");
}
if(StringUtils.isEmpty(agentUserTraditionalPosInfo.getZhifubao_settle_price())) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:支付宝结算底价必填 ");
}
if(StringUtils.isEmpty(agentUserTraditionalPosInfo.getSingle_profit_rate())) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:单笔分润比例(%)必填");
}
if(StringUtils.isEmpty(agentUserTraditionalPosInfo.getCash_back_rate())) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:返现比例(%)必填");
}
if(StringUtils.isEmpty(agentUserTraditionalPosInfo.getMer_cap_fee())) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:封顶费必填 ");
}
//(1)查询刷卡结算底价参数是否有效
List<Map<String, Object>> sysParamRateList1 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_2,agentUserTraditionalPosInfo.getCard_settle_price());
if(sysParamRateList1.size()<=0) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:刷卡结算底价数值异常");
}
//(2)查询云闪付结算底价参数是否有效
List<Map<String, Object>> sysParamRateList2 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_3,agentUserTraditionalPosInfo.getCloud_settle_price());
if(sysParamRateList2.size()<=0) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:云闪付结算底价数值异常");
}
//(3)查询微信结算底价参数是否有效
List<Map<String, Object>> sysParamRateList3 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_5,agentUserTraditionalPosInfo.getWeixin_settle_price());
if(sysParamRateList3.size()<=0) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:微信结算底价数值异常");
}
//(4)查询支付宝结算底价参数是否有效
List<Map<String, Object>> sysParamRateList4 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_7,agentUserTraditionalPosInfo.getZhifubao_settle_price());
if(sysParamRateList4.size()<=0) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:支付宝结算底价数值异常");
}
//(5)查询单笔分润比例参数是否有效
List<Map<String, Object>> sysParamRateList5 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_9,agentUserTraditionalPosInfo.getSingle_profit_rate());
if(sysParamRateList5.size()<=0) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:单笔分润比例(%)数值异常");
}
//(6)查询返现比例参数是否有效
List<Map<String, Object>> sysParamRateList6 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_10,agentUserTraditionalPosInfo.getCash_back_rate());
if(sysParamRateList6.size()<=0) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:返现比例(%)数值异常");
}
//(7)查询封顶费参数是否有效
List<Map<String, Object>> sysParamRateList7 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_11,agentUserTraditionalPosInfo.getMer_cap_fee());
if(sysParamRateList7.size()<=0) {
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:封顶费数值异常");
}
int i=0;
String cre_date = TimeUtil.getDayString();//创建日期
String cre_time = TimeUtil.getTimeString();//创建时间
//(8)更新该系统POS机的分配状态
Map<String, Object> sysTraditionalPosMap = new HashMap<String, Object>();
sysTraditionalPosMap.put("old_dis_status", TypeStatusConstant.sys_pos_info_dis_status_0);//旧状态:未分配
sysTraditionalPosMap.put("new_dis_status", TypeStatusConstant.sys_pos_info_dis_status_1);//旧状态:已分配
sysTraditionalPosMap.put("manager_id", ShiroUtils.getUserId());//代理编号
sysTraditionalPosMap.put("sn", agentUserTraditionalPosInfo.getSn());//设备号(机器编号)
sysTraditionalPosMap.put("update_by", ShiroUtils.getLoginName());//代理编号
sysTraditionalPosMap.put("up_date", cre_date);//更新日期
sysTraditionalPosMap.put("up_time", cre_time);//更新时间
i = agentSysTraditionalPosInfoMapper.updateAgentSysTraditionalPosInfoDisStatus(sysTraditionalPosMap);
if(i != 1) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:系统传统POS分配状态更新失败");
}
//(9)查询是否已经存在该用户和传统POS的关系
Map<String, Object> userTraditionalPosMap = agentUserEPosInfoMapper.getAgentUserTraditionalPosInfo(agentUserTraditionalPosInfo);
//(10)处理关系
agentUserTraditionalPosInfo.setCre_date(cre_date);//更新日期
agentUserTraditionalPosInfo.setCre_time(TimeUtil.getTimeString());//更新时间
agentUserTraditionalPosInfo.setCreate_by(ShiroUtils.getLoginName());//创建人
agentUserTraditionalPosInfo.setState_status(TypeStatusConstant.user_pos_info_state_status_1);//归属状态:直属
agentUserTraditionalPosInfo.setDel(TypeStatusConstant.user_pos_info_del_0);//删除状态:未删除
if(userTraditionalPosMap!=null) {
//已存在,更新该关系的信息
agentUserTraditionalPosInfo.setId(Integer.parseInt(userTraditionalPosMap.get("id").toString()));
i = agentUserEPosInfoMapper.updateAgentUserTraditionalPosInfoByDis(agentUserTraditionalPosInfo);
if(i != 1) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:用户传统POS关系更新失败");
}
}else {
i = agentUserEPosInfoMapper.addAgentUserTraditionalPosInfoByDis(agentUserTraditionalPosInfo);
if(i != 1) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return R.error(Type.WARN, "第"+(m+1)+"条数据导入失败:用户传统POS关系建立失败");
}
}
return R.ok("操作成功");
} catch (Exception e) {
e.printStackTrace();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return R.error(Type.ERROR, "第"+(m+1)+"条数据导入失败:数据导入异常");
}
}
/**
* 导出可分配的传统pos导入模板
*/
@Override
public List<AgentSelectUserTraditionalPosInfo> selectAgentNoDisSysTraditionalPosInfoList(
Map<String, Object> params) {
params.put("manager_id", ShiroUtils.getUserId());
return agentSysTraditionalPosInfoMapper.selectAgentNoDisSysTraditionalPosInfoList(params);
}
/**
* 新增保存用户传统POS机信息
*/
@Override
public R addAgentUserTraditionalPosInfo(Map<String, Object> params) {
// if(!ShiroUtils.getSysUser().isAuth()) {
// return R.error(Type.WARN, "身份信息未认证,不能操作");
// }
if(StringUtils.isEmpty(StringUtil.getMapValue(params, "remark"))) {
return R.error(Type.WARN, "操作备注不能为空");
}
//校验是否是一级代理用户并且实名认证
params.put("manager_id", getShiroUserInfo().getManager_id());//代理编号
Map<String, Object> userMap = agentUserInfoMapper.getAgentFirstAgentUserInfo(params);
if(userMap==null) {
return R.error(Type.WARN, "只能给属于自己的一级代理分配POS机");
}
if(!TypeStatusConstant.user_info_auth_status_09.equals(userMap.get("auth_status").toString())) {
return R.error(Type.WARN, "该用户未实名认证,不能分配POS机");
}
//(1)查询刷卡结算底价参数是否有效
List<Map<String, Object>> sysParamRateList1 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_2,StringUtil.getMapValue(params, "card_settle_price"));
if(sysParamRateList1.size()<=0) {
return R.error(Type.WARN, "刷卡结算底价数值异常");
}
//(2)查询云闪付结算底价参数是否有效
List<Map<String, Object>> sysParamRateList2 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_3,StringUtil.getMapValue(params, "cloud_settle_price"));
if(sysParamRateList2.size()<=0) {
return R.error(Type.WARN, "云闪付结算底价数值异常");
}
//(3)查询微信结算底价参数是否有效
List<Map<String, Object>> sysParamRateList3 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_5,StringUtil.getMapValue(params, "weixin_settle_price"));
if(sysParamRateList3.size()<=0) {
return R.error(Type.WARN, "微信结算底价数值异常");
}
//(4)查询支付宝结算底价参数是否有效
List<Map<String, Object>> sysParamRateList4 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_7,StringUtil.getMapValue(params, "zhifubao_settle_price"));
if(sysParamRateList4.size()<=0) {
return R.error(Type.WARN, "支付宝结算底价数值异常");
}
//(5)查询单笔分润比例参数是否有效
List<Map<String, Object>> sysParamRateList5 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_9,StringUtil.getMapValue(params, "single_profit_rate"));
if(sysParamRateList5.size()<=0) {
return R.error(Type.WARN, "单笔分润比例(%)数值异常");
}
//(6)查询返现比例参数是否有效
List<Map<String, Object>> sysParamRateList6 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_10,StringUtil.getMapValue(params, "cash_back_rate"));
if(sysParamRateList6.size()<=0) {
return R.error(Type.WARN, "返现比例(%)数值异常");
}
//(7)查询封顶费参数是否有效
List<Map<String, Object>> sysParamRateList7 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_11,StringUtil.getMapValue(params, "mer_cap_fee"));
if(sysParamRateList7.size()<=0) {
return R.error(Type.WARN, "封顶费数值异常");
}
//(8)查询刷卡结算底价参数是否有效
List<Map<String, Object>> sysParamRateList8 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_2,StringUtil.getMapValue(params, "card_settle_price_vip"));
if(sysParamRateList8.size()<=0) {
return R.error(Type.WARN, "VIP刷卡结算底价数值异常");
}
//用户传统POS机对象
AgentUserTraditionalPosInfo agentUserTraditionalPosInfo = new AgentUserTraditionalPosInfo();
agentUserTraditionalPosInfo.setUser_id(params.get("user_id").toString());//用编号
agentUserTraditionalPosInfo.setCard_settle_price(params.get("card_settle_price").toString());//刷卡结算底价
agentUserTraditionalPosInfo.setCloud_settle_price(params.get("cloud_settle_price").toString());//云闪付结算底价
agentUserTraditionalPosInfo.setWeixin_settle_price(params.get("weixin_settle_price").toString());//微信结算底价
agentUserTraditionalPosInfo.setZhifubao_settle_price(params.get("zhifubao_settle_price").toString());//支付宝结算底价
agentUserTraditionalPosInfo.setSingle_profit_rate(params.get("single_profit_rate").toString());//单笔分润比例
agentUserTraditionalPosInfo.setCash_back_rate(params.get("cash_back_rate").toString());//返现比例
agentUserTraditionalPosInfo.setMer_cap_fee(params.get("mer_cap_fee").toString());//封顶费
agentUserTraditionalPosInfo.setRemark(params.get("remark").toString());//备注
//add begin byqh 201912
agentUserTraditionalPosInfo.setCard_settle_price_vip(params.get("card_settle_price_vip").toString());
agentUserTraditionalPosInfo.setCloud_settle_price_vip(params.get("cloud_settle_price_vip").toString());
agentUserTraditionalPosInfo.setWeixin_settle_price_vip(params.get("weixin_settle_price_vip").toString());
agentUserTraditionalPosInfo.setZhifubao_settle_price_vip(params.get("zhifubao_settle_price_vip").toString());
agentUserTraditionalPosInfo.setIs_reward(params.get("is_reward").toString());
agentUserTraditionalPosInfo.setIs_reward1(params.get("is_reward1").toString());
//add end byqh 201912
if(TypeStatusConstant.sys_add_type_1.equals(StringUtil.getMapValue(params, "add_type"))) {
//add byqh 201912
// sysPosPolicyService.insertPolicySNInfo(String.valueOf(params.get("policy")),params.get("pos_sns").toString(),params.get("user_id").toString(),"epos");
//批量处理
return this.batchAddAgentUserTraditionalPosInfo(agentUserTraditionalPosInfo, params);
}else if(TypeStatusConstant.sys_add_type_2.equals(StringUtil.getMapValue(params, "add_type"))) {
//自增处理
return this.autoAddAgentUserTraditionalPosInfo(agentUserTraditionalPosInfo, params);
}else {
return R.error(Type.WARN, "新增类型异常");
}
}
/***
*选中POS分配给代理保存操作byqh update byqh 201912
* @param params
* @return
*/
@Override
@Transactional
public R addSubAgentUserTraditionalPosInfo(Map<String, Object> params) {
if(!ShiroUtils.getSysUser().isAuth()) {
return R.error(Type.WARN, "身份信息未认证,不能操作");
}
if(StringUtils.isEmpty(StringUtil.getMapValue(params, "remark"))) {
return R.error(Type.WARN, "操作备注不能为空");
}
//校验是否是一级代理用户并且实名认证
params.put("manager_id", ShiroUtils.getUserId());//代理编号
Map<String, Object> userMap = agentUserInfoMapper.getAgentFirstAgentUserInfo(params);
if(userMap==null) {
return R.error(Type.WARN, "只能给属于自己的一级代理分配POS机");
}
if(!TypeStatusConstant.user_info_auth_status_09.equals(userMap.get("auth_status").toString())) {
return R.error(Type.WARN, "该用户未实名认证,不能分配POS机");
}
//(1)查询刷卡结算底价参数是否有效
List<Map<String, Object>> sysParamRateList1 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_2,StringUtil.getMapValue(params, "card_settle_price"));
if(sysParamRateList1.size()<=0) {
return R.error(Type.WARN, "刷卡结算底价数值异常");
}
//(2)查询云闪付结算底价参数是否有效
List<Map<String, Object>> sysParamRateList2 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_3,StringUtil.getMapValue(params, "cloud_settle_price"));
if(sysParamRateList2.size()<=0) {
return R.error(Type.WARN, "云闪付结算底价数值异常");
}
//(3)查询微信结算底价参数是否有效
List<Map<String, Object>> sysParamRateList3 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_5,StringUtil.getMapValue(params, "weixin_settle_price"));
if(sysParamRateList3.size()<=0) {
return R.error(Type.WARN, "微信结算底价数值异常");
}
//(4)查询支付宝结算底价参数是否有效
List<Map<String, Object>> sysParamRateList4 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_7,StringUtil.getMapValue(params, "zhifubao_settle_price"));
if(sysParamRateList4.size()<=0) {
return R.error(Type.WARN, "支付宝结算底价数值异常");
}
//(5)查询单笔分润比例参数是否有效
List<Map<String, Object>> sysParamRateList5 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_9,StringUtil.getMapValue(params, "single_profit_rate"));
if(sysParamRateList5.size()<=0) {
return R.error(Type.WARN, "单笔分润比例(%)数值异常");
}
//(6)查询返现比例参数是否有效
List<Map<String, Object>> sysParamRateList6 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_10,StringUtil.getMapValue(params, "cash_back_rate"));
if(sysParamRateList6.size()<=0) {
return R.error(Type.WARN, "返现比例(%)数值异常");
}
//(7)查询封顶费参数是否有效
List<Map<String, Object>> sysParamRateList7 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_11,StringUtil.getMapValue(params, "mer_cap_fee"));
if(sysParamRateList7.size()<=0) {
return R.error(Type.WARN, "封顶费数值异常");
}
//(8)查询刷卡结算底价参数是否有效
List<Map<String, Object>> sysParamRateList8 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_2,StringUtil.getMapValue(params, "card_settle_price_vip"));
if(sysParamRateList8.size()<=0) {
return R.error(Type.WARN, "VIP刷卡结算底价数值异常");
}
Map<String, Object> baseMposInfo = agentUserEPosInfoMapper.getAgentUserTraditionalPosInfoById(params.get("user_pos_id").toString());
Double original_card_settle_price = Double.parseDouble(baseMposInfo.get("card_settle_price").toString());
Double original_cloud_settle_price = Double.parseDouble(baseMposInfo.get("cloud_settle_price").toString());
Double current_card_settle_price = Double.parseDouble(StringUtil.getMapValue(params, "card_settle_price"));
Double current_cloud_settle_price = Double.parseDouble(StringUtil.getMapValue(params, "cloud_settle_price"));
Double original_weixin_settle_price = Double.parseDouble(baseMposInfo.get("weixin_settle_price").toString());
Double original_zhifubao_settle_price = Double.parseDouble(baseMposInfo.get("zhifubao_settle_price").toString());
Double current_weixin_settle_price = Double.parseDouble(StringUtil.getMapValue(params, "weixin_settle_price"));
Double current_zhifubao_settle_price = Double.parseDouble(StringUtil.getMapValue(params, "zhifubao_settle_price"));
Double original_single_profit_rate = Double.parseDouble(baseMposInfo.get("single_profit_rate").toString());
Double original_cash_back_rate = Double.parseDouble(baseMposInfo.get("cash_back_rate").toString());
Double current_single_profit_rate = Double.parseDouble(StringUtil.getMapValue(params, "single_profit_rate"));
Double current_cash_back_rate = Double.parseDouble(StringUtil.getMapValue(params, "cash_back_rate"));
//add begin byqh 201912
Double original_card_settle_price_vip = Double.parseDouble(baseMposInfo.get("card_settle_price_vip").toString());
Double original_cloud_settle_price_vip = Double.parseDouble(baseMposInfo.get("cloud_settle_price_vip").toString());
Double current_card_settle_price_vip = Double.parseDouble(StringUtil.getMapValue(params, "card_settle_price_vip"));
Double current_cloud_settle_price_vip = Double.parseDouble(StringUtil.getMapValue(params, "cloud_settle_price_vip"));
Double original_weixin_settle_price_vip = Double.parseDouble(baseMposInfo.get("weixin_settle_price_vip").toString());
Double original_zhifubao_settle_price_vip = Double.parseDouble(baseMposInfo.get("zhifubao_settle_price_vip").toString());
Double current_weixin_settle_price_vip = Double.parseDouble(StringUtil.getMapValue(params, "weixin_settle_price_vip"));
Double current_zhifubao_settle_price_vip = Double.parseDouble(StringUtil.getMapValue(params, "zhifubao_settle_price_vip"));
//add end byqh 201912
Double original_mer_cap_fee = Double.parseDouble(baseMposInfo.get("mer_cap_fee").toString());
Double current_mer_cap_fee = Double.parseDouble(StringUtil.getMapValue(params, "mer_cap_fee"));
if(current_card_settle_price<original_card_settle_price){
return R.error(Type.WARN, "刷卡结算底价不能低于"+original_card_settle_price);
}
if(current_cloud_settle_price<original_cloud_settle_price){
return R.error(Type.WARN, "云闪付结算底价不能低于"+original_cloud_settle_price);
}
if(current_weixin_settle_price<original_weixin_settle_price){
return R.error(Type.WARN, "微信结算底价不能低于"+original_weixin_settle_price);
}
if(current_zhifubao_settle_price<original_zhifubao_settle_price){
return R.error(Type.WARN, "支付宝结算不能低于"+original_zhifubao_settle_price);
}
//add begin byqh 201912
if(current_card_settle_price_vip<original_card_settle_price_vip){
return R.error(Type.WARN, "刷卡结算底价不能低于"+original_card_settle_price_vip);
}
if(current_cloud_settle_price_vip<original_cloud_settle_price_vip){
return R.error(Type.WARN, "云闪付结算底价不能低于"+original_cloud_settle_price_vip);
}
if(current_weixin_settle_price_vip<original_weixin_settle_price_vip){
return R.error(Type.WARN, "微信结算底价不能低于"+original_weixin_settle_price_vip);
}
if(current_zhifubao_settle_price_vip<original_zhifubao_settle_price_vip){
return R.error(Type.WARN, "支付宝结算不能低于"+original_zhifubao_settle_price_vip);
}
//add end byqh 201912
if(current_single_profit_rate>original_single_profit_rate){
return R.error(Type.WARN, "单笔分润比例不能高于"+original_single_profit_rate);
}
if(current_cash_back_rate>original_cash_back_rate){
return R.error(Type.WARN, "返现比例不能高于"+original_cash_back_rate);
}
if(current_mer_cap_fee<original_mer_cap_fee){
return R.error(Type.WARN, "封顶费不能低于"+original_mer_cap_fee);
}
String cre_date = TimeUtil.getDayString();//创建日期
String cre_time = TimeUtil.getTimeString();//创建时间
//1.更新该系统POS机的分配状态
Map<String, Object> sysTraditionalMap = new HashMap<String, Object>();
sysTraditionalMap.put("new_dis_status", TypeStatusConstant.sys_pos_info_dis_status_1);//旧状态:已分配
sysTraditionalMap.put("manager_id", getShiroUserInfo().getManager_id());//代理编号
sysTraditionalMap.put("sn", params.get("pos_sns").toString());//设备号(机器编号)
sysTraditionalMap.put("update_by", ShiroUtils.getLoginName());//代理编号
sysTraditionalMap.put("up_date", cre_date);//更新日期
sysTraditionalMap.put("up_time", cre_time);//更新时间
sysTraditionalMap.put("remark", params.get("remark").toString());//操作备注
int i = agentSysTraditionalPosInfoMapper.updateSubAgentSysTraditionalPosInfoDisStatus(sysTraditionalMap);
if(i != 1) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return R.error(Type.WARN, "设备号(机器编号)"+params.get("pos_sns").toString()+"新增失败:系统传统POS分配状态更新失败");
}
//3.更新直属关系和上下级关系
Map<String, Object> userTraditionalMap = new HashMap<String, Object>();
userTraditionalMap.put("user_pos_id",params.get("user_pos_id").toString());
userTraditionalMap.put("state_status",TypeStatusConstant.user_pos_info_state_status_0);
userTraditionalMap.put("update_by",ShiroUtils.getLoginName());
userTraditionalMap.put("up_date",cre_date);
userTraditionalMap.put("up_time",cre_time);
agentUserEPosInfoMapper.updateAgentUserTraditionalPosInfo(userTraditionalMap);
//4.更新POS用户的刷卡结算底价,云闪付结算底价,单笔分润比例,返现比例
//用户传统POS机对象
AgentUserTraditionalPosInfo agentUserTraditionalPosInfo = new AgentUserTraditionalPosInfo();
agentUserTraditionalPosInfo.setSn(params.get("pos_sns").toString());
agentUserTraditionalPosInfo.setUser_id(params.get("subAgent").toString());//用编号
agentUserTraditionalPosInfo.setCard_settle_price(params.get("card_settle_price").toString());//刷卡结算底价
agentUserTraditionalPosInfo.setCloud_settle_price(params.get("cloud_settle_price").toString());//云闪付结算底价
agentUserTraditionalPosInfo.setWeixin_settle_price(params.get("weixin_settle_price").toString());//微信结算底价
agentUserTraditionalPosInfo.setZhifubao_settle_price(params.get("zhifubao_settle_price").toString());//支付宝结算底价
//add begin byqh 201912
agentUserTraditionalPosInfo.setCard_settle_price_vip(params.get("card_settle_price_vip").toString());//刷卡结算底价
agentUserTraditionalPosInfo.setCloud_settle_price_vip(params.get("cloud_settle_price_vip").toString());//云闪付结算底价
agentUserTraditionalPosInfo.setWeixin_settle_price_vip(params.get("weixin_settle_price_vip").toString());//微信结算底价
agentUserTraditionalPosInfo.setZhifubao_settle_price_vip(params.get("zhifubao_settle_price_vip").toString());//支付宝结算底价
//add end byqh 201912
agentUserTraditionalPosInfo.setSingle_profit_rate(params.get("single_profit_rate").toString());//单笔分润比例
agentUserTraditionalPosInfo.setCash_back_rate(params.get("cash_back_rate").toString());//返现比例
agentUserTraditionalPosInfo.setMer_cap_fee(params.get("mer_cap_fee").toString());//封顶费
agentUserTraditionalPosInfo.setState_status(TypeStatusConstant.user_pos_info_state_status_1);//归属状态改为直属
agentUserTraditionalPosInfo.setDel(TypeStatusConstant.user_pos_info_del_0);//删除状态改为0
agentUserTraditionalPosInfo.setRemark(params.get("remark").toString());//备注
agentUserTraditionalPosInfo.setCreate_by(ShiroUtils.getLoginName());
agentUserTraditionalPosInfo.setCre_date(cre_date);
agentUserTraditionalPosInfo.setCre_time(cre_time);
agentUserEPosInfoMapper.addAgentUserTraditionalPosInfoByDis(agentUserTraditionalPosInfo);
return R.ok("操作成功");
}
/**
* 批量自增处理保存用户传统POS机信息
* @param agentUserTraditionalPosInfo
* @param params
* @return
*/
private R batchAddAgentUserTraditionalPosInfo(AgentUserTraditionalPosInfo agentUserTraditionalPosInfo,
Map<String, Object> params) {
int success_num = 0;//成功数量
int failure_num = 0;//失败数量
String failure_msg = "";//失败消息
//拼接id转换成long型数组
String[] pos_sns = params.get("pos_sns").toString().split(";");
for(int i=0;i<pos_sns.length;i++) {
agentUserTraditionalPosInfo.setSn(pos_sns[i]);
R result = SpringUtils.getAopProxy(this).addSingleAgentUserTraditionalPosInfo(agentUserTraditionalPosInfo);
if(Type.SUCCESS.value.equals(result.get("code").toString())) {
success_num++;
}else {
failure_num++;
failure_msg = failure_msg+"<br/>"+result.get("msg").toString();
}
}
if(failure_num>0) {
failure_msg = "操作结果:成功"+success_num+"条,失败"+failure_num+"条<br/>失败信息如下:<br/>"+failure_msg;
}else {
failure_msg = "操作结果:成功"+success_num+"条,失败"+failure_num+"条";
}
return R.ok(failure_msg);
}
/**
* 添加单个用户传统POS机信息
* @param agentUserTraditionalPosInfo
* @return
*/
@Transactional
public R addSingleAgentUserTraditionalPosInfo(AgentUserTraditionalPosInfo agentUserTraditionalPosInfo) {
try {
//校验结算低价byqh202006
AgentUserTraditionalPosInfo allot = new AgentUserTraditionalPosInfo();
allot.setSn(agentUserTraditionalPosInfo.getSn());
allot.setUser_id(String.valueOf(getShiroUserInfo().getId()));
Map<String, Object> basePrice = agentUserEPosInfoMapper.getAgentUserTraditionalPosInfo(allot);
String card_settle_price = String.valueOf(basePrice.get("card_settle_price"));
String card_settle_price_vip = String.valueOf(basePrice.get("card_settle_price_vip"));
String cloud_settle_price = String.valueOf(basePrice.get("cloud_settle_price"));
String weixin_settle_price = String.valueOf(basePrice.get("weixin_settle_price"));
String zhifubao_settle_price = String.valueOf(basePrice.get("zhifubao_settle_price"));
String mer_cap_fee = String.valueOf(basePrice.get("mer_cap_fee"));
String single_profit_rate = String.valueOf(basePrice.get("single_profit_rate"));
String cash_back_rate = String.valueOf(basePrice.get("cash_back_rate"));
if(Double.parseDouble(agentUserTraditionalPosInfo.getCard_settle_price())<Double.parseDouble(card_settle_price)){
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"刷卡结算底价不能低于"+card_settle_price);
}
if(Double.parseDouble(agentUserTraditionalPosInfo.getCloud_settle_price())<Double.parseDouble(cloud_settle_price)){
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"云闪付结算底价不能低于"+cloud_settle_price);
}
if(Double.parseDouble(agentUserTraditionalPosInfo.getCard_settle_price_vip())<Double.parseDouble(card_settle_price_vip)){
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"VIP秒到(商圈)刷卡结算底价不能低于"+card_settle_price_vip);
}
if(Double.parseDouble(agentUserTraditionalPosInfo.getWeixin_settle_price())<Double.parseDouble(weixin_settle_price)){
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"微信结算底价不能低于"+weixin_settle_price);
}
if(Double.parseDouble(agentUserTraditionalPosInfo.getZhifubao_settle_price())<Double.parseDouble(zhifubao_settle_price)){
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"支付宝结算底价不能低于"+zhifubao_settle_price);
}
if(Double.parseDouble(agentUserTraditionalPosInfo.getMer_cap_fee())<Double.parseDouble(mer_cap_fee)){
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"封顶费不能低于"+mer_cap_fee);
}
if(Double.parseDouble(agentUserTraditionalPosInfo.getSingle_profit_rate())<Double.parseDouble(single_profit_rate)){
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"单笔分润比例不能低于"+single_profit_rate);
}
if(Double.parseDouble(agentUserTraditionalPosInfo.getCash_back_rate())>Double.parseDouble(cash_back_rate)){
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"返现比例不能高于"+cash_back_rate);
}
//校验结算低价byqh202006
int i=0;
String cre_date = TimeUtil.getDayString();//创建日期
String cre_time = TimeUtil.getTimeString();//创建时间
//(3)更新该系统POS机的分配状态
Map<String, Object> sysTraditionalPosMap = new HashMap<String, Object>();
sysTraditionalPosMap.put("old_dis_status", TypeStatusConstant.sys_pos_info_dis_status_0);//旧状态:未分配
sysTraditionalPosMap.put("new_dis_status", TypeStatusConstant.sys_pos_info_dis_status_1);//旧状态:已分配
sysTraditionalPosMap.put("manager_id", getShiroUserInfo().getManager_id());//代理编号
sysTraditionalPosMap.put("sn", agentUserTraditionalPosInfo.getSn());//设备号(机器编号)
sysTraditionalPosMap.put("update_by", ShiroUtils.getLoginName());//代理编号
sysTraditionalPosMap.put("up_date", cre_date);//更新日期
sysTraditionalPosMap.put("up_time", cre_time);//更新时间
sysTraditionalPosMap.put("remark", agentUserTraditionalPosInfo.getRemark());//操作备注
// i = agentSysTraditionalPosInfoMapper.updateAgentSysTraditionalPosInfoDisStatus(sysTraditionalPosMap);
// if(i != 1) {
// TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
// return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"新增失败:系统传统POS分配状态更新失败");
// }
//(4)查询是否已经存在该用户和传统POS的关系
Map<String, Object> userTraditionalPosMap = agentUserEPosInfoMapper.getAgentUserTraditionalPosInfo(agentUserTraditionalPosInfo);
//(5)处理关系
agentUserTraditionalPosInfo.setCre_date(cre_date);//更新日期
agentUserTraditionalPosInfo.setCre_time(TimeUtil.getTimeString());//更新时间
agentUserTraditionalPosInfo.setCreate_by(ShiroUtils.getLoginName());//创建人
agentUserTraditionalPosInfo.setState_status(TypeStatusConstant.user_pos_info_state_status_1);//归属状态:直属
agentUserTraditionalPosInfo.setDel(TypeStatusConstant.user_pos_info_del_0);//删除状态:未删除
if(userTraditionalPosMap!=null) {
//已存在,更新该关系的信息
agentUserTraditionalPosInfo.setId(Integer.parseInt(userTraditionalPosMap.get("id").toString()));
i = agentUserTraditionalPosInfoMapper.updateAgentUserState0BySNUID(agentUserTraditionalPosInfo.getSn(),String.valueOf(getShiroUserInfo().getId()));
if(i != 1) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"新增失败:归属关系修改失败");
}
i = agentUserEPosInfoMapper.updateAgentUserTraditionalPosInfoByDis(agentUserTraditionalPosInfo);
if(i != 1) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"新增失败:用户传统POS关系更新失败");
}
}else {
i = agentUserTraditionalPosInfoMapper.updateAgentUserState0BySNUID(agentUserTraditionalPosInfo.getSn(),String.valueOf(getShiroUserInfo().getId()));
if(i != 1) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"新增失败:归属关系修改失败");
}
i = agentUserEPosInfoMapper.addAgentUserTraditionalPosInfoByDis(agentUserTraditionalPosInfo);
if(i != 1) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"新增失败:用户传统POS关系建立失败");
}
}
if("0".equals(agentUserTraditionalPosInfo.getIs_reward())){
agentUserTraditionalPosInfoMapper.updateIsReWard0BySNUID(agentUserTraditionalPosInfo.getSn(),getShiroUserInfo().getId());
}
if(agentUserTraditionalPosInfo.getIs_reward1()!=null && !"".equals(agentUserTraditionalPosInfo.getIs_reward1())){
String[] policyArray = agentUserTraditionalPosInfo.getIs_reward1().split(";");
for(String policy : policyArray){
if(policy!=null && !"".equals(policy)){
agentUserTraditionalPosInfoMapper.updateIsReWard1BySNUID(policy,agentUserTraditionalPosInfo.getSn(),String.valueOf(getShiroUserInfo().getId()));
}
}
}
return R.ok("操作成功");
} catch (Exception e) {
e.printStackTrace();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return R.error(Type.WARN, "设备号(机器编号)"+agentUserTraditionalPosInfo.getSn()+"新增异常");
}
}
/**
* 自增处理用户传统POS机信息
* @param agentUserTraditionalPosInfo
* @param params
* @return
*/
private R autoAddAgentUserTraditionalPosInfo(AgentUserTraditionalPosInfo agentUserTraditionalPosInfo,
Map<String, Object> params) {
if(StringUtils.isEmpty(StringUtil.getMapValue(params, "pos_start"))) {
return R.error(Type.WARN, "设备号(机器编号)起始数值异常");
}
if(StringUtils.isEmpty(StringUtil.getMapValue(params, "pos_num"))) {
return R.error(Type.WARN, "POS机数量数值异常");
}
//POS机设备号(机器编号)起始号
String pos_start = params.get("pos_start").toString();
//连号录入数据(默认后6位),获取连续的机型号
int pos_num = Integer.parseInt(params.get("pos_num").toString());//POS机数量
if(pos_num<=0) {
return R.error(Type.WARN, "POS机数量数值异常");
}
int success_num = 0;//成功数量
int failure_num = 0;//失败数量
String failure_msg = "";//失败消息
for(int i=0; i<pos_num; i++){
agentUserTraditionalPosInfo.setSn(pos_start);
//add byqh 201912
// sysPosPolicyService.insertPolicySNInfo(String.valueOf(params.get("policy")),pos_start,params.get("user_id").toString(),"TraditionalPOS");
R result = SpringUtils.getAopProxy(this).addSingleAgentUserTraditionalPosInfo(agentUserTraditionalPosInfo);
if(Type.SUCCESS.value.equals(result.get("code").toString())) {
success_num++;
}else {
failure_num++;
failure_msg = failure_msg+"<br/>"+result.get("msg").toString();
}
pos_start = StringUtil.addOneForTen(pos_start);
}
if(failure_num>0) {
failure_msg = "操作结果:成功"+success_num+"条,失败"+failure_num+"条<br/>失败信息如下:<br/>"+failure_msg;
}else {
failure_msg = "操作结果:成功"+success_num+"条,失败"+failure_num+"条";
}
return R.ok(failure_msg);
}
/**
* 根据编号查询用户传统POS信息
*/
@Override
public Map<String, Object> getAgentUserTraditionalPosInfoById(String id) {
return agentUserEPosInfoMapper.getAgentUserTraditionalPosInfoById(id);
}
/**
* 修改用户传统POS机信息
*/
@Override
public R editAgentUserTraditionalPosInfo(Map<String, Object> params) {
try {
if(!ShiroUtils.getSysUser().isAuth()) {
return R.error(Type.WARN, "身份信息未认证,不能操作");
}
if(StringUtils.isEmpty(StringUtil.getMapValue(params, "remark"))) {
return R.error(Type.WARN, "操作备注不能为空");
}
//(1)查询刷卡结算底价参数是否有效
List<Map<String, Object>> sysParamRateList1 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_2,StringUtil.getMapValue(params, "card_settle_price"));
if(sysParamRateList1.size()<=0) {
return R.error(Type.WARN, "刷卡结算底价数值异常");
}
//(2)查询云闪付结算底价参数是否有效
List<Map<String, Object>> sysParamRateList2 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_3,StringUtil.getMapValue(params, "cloud_settle_price"));
if(sysParamRateList2.size()<=0) {
return R.error(Type.WARN, "云闪付结算底价数值异常");
}
//(3)查询微信结算底价参数是否有效
List<Map<String, Object>> sysParamRateList3 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_5,StringUtil.getMapValue(params, "weixin_settle_price"));
if(sysParamRateList3.size()<=0) {
return R.error(Type.WARN, "微信结算底价数值异常");
}
//(4)查询支付宝结算底价参数是否有效
List<Map<String, Object>> sysParamRateList4 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_7,StringUtil.getMapValue(params, "zhifubao_settle_price"));
if(sysParamRateList4.size()<=0) {
return R.error(Type.WARN, "支付宝结算底价数值异常");
}
//(5)查询单笔分润比例参数是否有效
List<Map<String, Object>> sysParamRateList5 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_9,StringUtil.getMapValue(params, "single_profit_rate"));
if(sysParamRateList5.size()<=0) {
return R.error(Type.WARN, "单笔分润比例(%)数值异常");
}
//(6)查询返现比例参数是否有效
List<Map<String, Object>> sysParamRateList6 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_10,StringUtil.getMapValue(params, "cash_back_rate"));
if(sysParamRateList6.size()<=0) {
return R.error(Type.WARN, "返现比例(%)数值异常");
}
//(7)查询封顶费参数是否有效
List<Map<String, Object>> sysParamRateList7 = manaSysParamRateMapper.getManaSysParamRateIsValid(TypeStatusConstant.sys_param_rate_type_11,StringUtil.getMapValue(params, "mer_cap_fee"));
if(sysParamRateList7.size()<=0) {
return R.error(Type.WARN, "封顶费数值异常");
}
int i=0;
//(5)查询old参数信息
Map<String, Object> oldValue = agentUserEPosInfoMapper.getAgentUserTraditionalPosInfoById(params.get("user_pos_id").toString());
//(6)更新用户传统POS信息
params.put("up_date", TimeUtil.getDayString());//更新日期
params.put("up_time", TimeUtil.getTimeString());//更新时间
params.put("update_by", ShiroUtils.getLoginName());//创建人
i = agentUserEPosInfoMapper.updateAgentUserTraditionalPosInfo(params);
if(i != 1) {
return R.error(Type.WARN, "系统传统POS信息更新失败");
}
//(7)查询new参数信息
Map<String, Object> newValue = agentUserEPosInfoMapper.getAgentUserTraditionalPosInfoById(params.get("user_pos_id").toString());
//(8)记录修改记录
params.put("table_name", SysTableNameConstant.t_user_traditional_pos_info);
params.put("old_value", NetJsonUtils.mapToJson1(oldValue));
params.put("new_value", NetJsonUtils.mapToJson1(newValue));
i = manaSysEditMapper.addManaSysEdit(params);
if(i != 1) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return R.error(Type.WARN, "修改记录记录失败");
}
return R.ok("操作成功");
} catch (Exception e) {
e.printStackTrace();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return R.error(Type.ERROR, "操作异常");
}
}
/***
* 查询一级代理的子代理byqh
* @param user_id
* @return
*/
@Override
public List<Map<String, Object>> selectSubAgentInfo(String user_id) {
return agentUserEPosInfoMapper.selectSubAgentInfo(user_id);
}
}
|
Java
|
UTF-8
| 10,049 | 2.28125 | 2 |
[] |
no_license
|
package com.example.atif.todolist;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class NewTaskActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Calendar myCalendar = Calendar.getInstance();
EditText editDueDate;
EditText editDueTime;
EditText editTitle;
EditText editDescription;
CheckBox notificationBox;
String type;
String title;
String description;
String dueDate;
String dueTime;
String checkbox;
int calYear;
int calMonth;
int calDay;
int calHour;
int calMinute;
private DatabaseReference mDatabase;
DatePickerDialog.OnDateSetListener date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_task);
//Toolbar header created. Activity title set.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("New Task");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//EditText views connected by ID.
editTitle = (EditText) findViewById(R.id.title);
editDescription = (EditText) findViewById(R.id.description);
//Database Reference is set.
mDatabase = FirebaseDatabase.getInstance().getReference("Tasks");
//Floating Action Button listener is set.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//User inputs of task titles,description,duedate,and duetimes are saved.
title = editTitle.getText().toString();
description = editDescription.getText().toString();
dueDate = editDueDate.getText().toString();
dueTime = editDueTime.getText().toString();
//If condition used to enforce all text fields have been filed out.
//If satisfied, saveTask method is run.
if (title.isEmpty() || description.isEmpty() || dueDate.isEmpty() || dueTime.isEmpty()) {
Toast.makeText(NewTaskActivity.this, "Please complete all fields!", Toast.LENGTH_SHORT).show();
} else {
saveTask();
}
}
});
//Date dialog is created on click of the due date text field.
editDueDate = (EditText) findViewById(R.id.duedate);
editDueDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DatePickerDialog(NewTaskActivity.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
//Values selected from date picker dialogs are set and saved.
date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
calYear = year;
calMonth = monthOfYear;
calDay = dayOfMonth;
updateLabel();
}
};
//On click listener is set on Due time text field .
editDueTime = (EditText) findViewById(R.id.duetime);
editDueTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Current device time is retrieved.
Calendar mCurrentTime = Calendar.getInstance();
int hour = mCurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mCurrentTime.get(Calendar.MINUTE);
//TimePicker dialog is created and displayed.
TimePickerDialog mTimePicker = new TimePickerDialog(NewTaskActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
editDueTime.setText(selectedHour + ":" + selectedMinute);
calHour = selectedHour;
calMinute = selectedMinute;
}
}
, hour, minute, false);
mTimePicker.show();
}
});
//Spinner is created to differentiate what type of task is being created.
//Array adapter is filled with values from string resource file.
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.task_options, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
//Notification Checkbox is created. It is set to default. If checked checkbox is stored as true.
notificationBox = (CheckBox) findViewById(R.id.checkbox);
checkbox = "false";
notificationBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (notificationBox.isChecked()) {
checkbox = "true";
} else {
checkbox = "false";
}
}
});
}
//Date is formatted to simple date time format.
private void updateLabel() {
String myFormat = "MM/dd/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
editDueDate.setText(sdf.format(myCalendar.getTime()));
}
// An item was selected from Spinner. It is stored in a string variable.
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
type = parent.getSelectedItem().toString();
}
//Toast displayed if no item from spinner is selected. Not in use.
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(NewTaskActivity.this, "No category has been selected!", Toast.LENGTH_SHORT).show();
}
//New task is created.
public void saveTask() {
//Task model created
Task newTask = new Task();
//All inputs entered by users is set and saved into newTask object.
newTask.setTitle(title);
newTask.setDescription(description);
newTask.setDueDate(dueDate);
newTask.setDueTime(dueTime);
newTask.setType(type);
newTask.setReminder(checkbox);
//newTask Hashmap is written to database with unique key value.
//Database reference is set to "Tasks" node. New Task is created.
String key = mDatabase.push().getKey();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put(key, newTask);
mDatabase.updateChildren(childUpdates, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
finish();
}
}
});
//If notification checkbox is set to true, AlarmManager is created which triggers a local notification
if (checkbox.equals("true")) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//New intent is created and title/description extras are sent to be displayed in notification.
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.putExtra("title", title);
notificationIntent.putExtra("description", description);
notificationIntent.addCategory("android.intent.category.DEFAULT");
//Pending Intent is created, which triggers the notificationIntent
PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Alarm manager triggers the pending intent, which device reached time specified by user input while choosing due date and time.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, calYear);
cal.set(Calendar.MONTH, calMonth);
cal.set(Calendar.DAY_OF_MONTH, calDay);
cal.set(Calendar.HOUR_OF_DAY, calHour);
cal.set(Calendar.MINUTE, calMinute);
cal.set(Calendar.SECOND, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);
}
}
}
|
Java
|
UTF-8
| 2,074 | 2.15625 | 2 |
[] |
no_license
|
package pro.jianbing.aboutme.controller.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pro.jianbing.aboutme.common.controller.BaseController;
import pro.jianbing.aboutme.common.dto.BaseResult;
import pro.jianbing.aboutme.entity.Knowledge;
import pro.jianbing.aboutme.entity.User;
import pro.jianbing.aboutme.service.KnowledgeService;
import java.time.LocalDateTime;
/**
* @author DefaultAccount
*/
@RequestMapping("knowledge")
@Controller
public class KnowledgeController extends BaseController {
private final
KnowledgeService knowledgeService;
@Autowired
public KnowledgeController(KnowledgeService knowledgeService) {
this.knowledgeService = knowledgeService;
}
@GetMapping("")
public String knowledge(){
return "knowledge";
}
@GetMapping("get")
@ResponseBody
public BaseResult get(Model model){
BaseResult baseResult;
try {
User user = getUser();
String knowledge = knowledgeService.getByUserId(user.getId());
model.addAttribute("knowledge",knowledge);
baseResult = BaseResult.success("",knowledge);
} catch (Exception e) {
e.printStackTrace();
baseResult = BaseResult.systemError();
}
return baseResult;
}
@PostMapping("save")
@ResponseBody
public BaseResult save(Knowledge knowledge){
BaseResult baseResult;
try {
knowledge.setIp(getIpByRequest());
knowledge.setEditTime(LocalDateTime.now());
knowledge.setUserId(getUser().getId());
Integer result = knowledgeService.save(knowledge);
baseResult = result>0?BaseResult.success(SAVE_SUCCESS):BaseResult.fail(SAVE_FAIL);
} catch (Exception e) {
e.printStackTrace();
baseResult = BaseResult.systemError();
}
return baseResult;
}
}
|
C#
|
UTF-8
| 11,824 | 2.625 | 3 |
[] |
no_license
|
/*
* 由SharpDevelop创建。
* 用户: Administrator
* 日期: 2015/3/27
* 时间: 16:02
*
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Threading;
using System.Linq;
using System.Media;
namespace 五子棋
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
PictureBox[,] wuziqiPictureBox = new PictureBox[15, 15];//新建一个15乘以15的PICTUREBOX
int[,] victory = new int[15, 15];//用于判断胜负的二维数组,只能为0,1,2代表没下棋,白棋,黑棋
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
int x,y;
for(x=0;x<=14;x++)
for(y=0;y<=14;y++)//画PICTUREBOX
{
wuziqiPictureBox[x,y]=new PictureBox();
wuziqiPictureBox[x,y].Location=new Point(35+x*30,5+y*30);//左上角坐标
wuziqiPictureBox[x,y].Size=new Size(30,30);//长宽
wuziqiPictureBox[x,y].BackColor=Color.Transparent;
wuziqiPictureBox[x,y].SizeMode=PictureBoxSizeMode.CenterImage;
wuziqiPictureBox[x,y].Visible=false;
panel1.Controls.Add(wuziqiPictureBox[x,y]);
}
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
void Panel1Paint(object sender, PaintEventArgs e)//新建panel
{
label2.BackColor=Color.Transparent;
panel1.BackColor=Color.Transparent;
Pen pen=new Pen(Color. Blue,2);//定义画笔
Graphics g=panel1.CreateGraphics();//画线
int i,n,m;
n=50;
m=20;
for(i=1;i<=15;i++)
{
g.DrawLine(pen,n,20,n,440);
n=n+30;
}
for(i=1;i<=15;i++)
{
g.DrawLine(pen,50,m,470,m);
m=m+30;
}
Pen pen1=new Pen(new SolidBrush(Color.Black),0.5f);
Rectangle rg=new Rectangle(135,105,10,10);//定义矩形
Rectangle rg1=new Rectangle(135,345,10,10);
Rectangle rg2=new Rectangle(255,225,10,10);
Rectangle rg3=new Rectangle(375,105,10,10);
Rectangle rg4=new Rectangle(375,345,10,10);
g.DrawEllipse(pen1,rg);//画椭圆
g.DrawEllipse(pen1,rg1);
g.DrawEllipse(pen1,rg2);
g.DrawEllipse(pen1,rg3);
g.DrawEllipse(pen1,rg4);
g.FillEllipse (new SolidBrush (Color .Black) ,rg);//填充颜色
g.FillEllipse (new SolidBrush (Color .Black) ,rg1);
g.FillEllipse (new SolidBrush (Color .Black) ,rg2);
g.FillEllipse (new SolidBrush (Color .Black) ,rg3);
g.FillEllipse (new SolidBrush (Color .Black) ,rg4);
g.Flush ();//清空缓存
}
void Button3Click(object sender, EventArgs e)//关闭
{
Application.Exit();
}
int i = 0;//控制谁先下棋,0代表黑棋,1代表白棋
struct zuobiao { public
int c, d;}//用于存储下棋的位置
zuobiao[] xy = new zuobiao[300];//定义来存储下棋位置的数组
int step=1;//记录步数
int l=1;//控制函数开关
void Button2Click(object sender, EventArgs e)//黑棋先
{
l=0;//控制是否可以落子,0时可以落子
i=0;
button2.Visible =false;
button4.Visible =false;
}
void Button4Click(object sender, EventArgs e)//白棋先
{
l=0;
i=1;
button4.Visible =false;
button2.Visible =false;
}
void Panel1MouseDown(object sender, MouseEventArgs e)
{
int r=30;//棋子宽度
if(l==0){if(e.X>=485||e.X<35||e.Y<5||e.Y>=455)label2.Text="落子错误";//限定只能在棋盘内落子
else{{
int m=(int)((e.X-15)/30)*30+20-r/2;//获取横坐标
int n=(int)((e.Y+45)/30)*30+35-r/2;//获取纵坐标
}
int a, b;
a = (e.X - 35) / 30;//把坐标值转换为数组的位置
b = (e.Y - 5) / 30;
int k;//判断胜负k=1就胜利
if (i == 0)//下黑子
{
wuziqiPictureBox[a, b].ImageLocation = "D:\\五子棋\\五子棋\\tupian\\heiqi.png";
wuziqiPictureBox[a, b].Visible = true;
victory[a, b] = 1;//在victory数组中记录这个点下了黑子
SoundPlayer music =new SoundPlayer(@"D:\五子棋\五子棋\tupian\棋子落下.wav");
music.Play ();
label2.Text="请白子下";
for (int h = 1; h <= 1; h++)//判断胜负
{
k = judge1(a, b); if (k == 1) {l=1; pictureBox1.Visible = true; pictureBox1.ImageLocation="D:\\五子棋\\五子棋\\tupian\\黑棋win.jpg"; break; }
k = judge2(a, b); if (k == 1) { l=1;pictureBox1.Visible = true; pictureBox1.ImageLocation="D:\\五子棋\\五子棋\\tupian\\黑棋win.jpg"; break; }
k = judge3(a, b); if (k == 1) { l=1;pictureBox1.Visible = true; pictureBox1.ImageLocation="D:\\五子棋\\五子棋\\tupian\\黑棋win.jpg"; break; }
k = judge4(a, b); if (k == 1) { l=1;pictureBox1.Visible = true; pictureBox1.ImageLocation="D:\\五子棋\\五子棋\\tupian\\黑棋win.jpg"; break; }
}
}
if (i == 1)//白棋下
{
wuziqiPictureBox[a, b].ImageLocation = "D:\\五子棋\\五子棋\\tupian\\baiqi.png";
wuziqiPictureBox[a, b].Visible = true;
victory[a, b] = 2;
label2.Text="请黑子下";
SoundPlayer music1 =new SoundPlayer(@"D:\五子棋\五子棋\tupian\棋子落下.wav");
music1.Play ();
for (int h = 1; h <= 1; h++)
{
k = judge1(a, b); if (k == 1) {l=1; pictureBox1.Visible = true; pictureBox1.ImageLocation="D:\\五子棋\\五子棋\\tupian\\白棋win.jpg"; break; }
k = judge2(a, b); if (k == 1) {l=1; pictureBox1.Visible = true; pictureBox1.ImageLocation="D:\\五子棋\\五子棋\\tupian\\白棋win.jpg"; break; }
k = judge3(a, b); if (k == 1) {l=1; pictureBox1.Visible = true; pictureBox1.ImageLocation="D:\\五子棋\\五子棋\\tupian\\白棋win.jpg"; break; }
k = judge4(a, b); if (k == 1) {l=1; pictureBox1.Visible = true; pictureBox1.ImageLocation="D:\\五子棋\\五子棋\\tupian\\白棋win.jpg"; break; }
}
}
if (i == 0) i = 1;//黑白子转换
else i = 0;
xy[step].c=a;xy[step].d=b;//记录这步下的位置
step++;}}
}
private void huiqi_Click(object sender, EventArgs e)//悔棋
{
if(l==0){if (step >= 1)//限制悔棋不能超出范围
{
step--;//回到上一步的操作
wuziqiPictureBox[xy[step].c, xy[step].d].Visible = false;
victory[xy[step].c, xy[step].d] = 0;
if (i == 0){ i = 1;label2.Text="请白子下";}
else {i = 0;label2.Text="请黑子下";}
}}
}
//判断胜负
int judge1(int x,int y)
{
int p = 1, q, h, X, Y;
q = victory[x, y];
X = x; Y = y;
for (h = 0; h <= 4; h++)
{
if (Y > 0 && Y <= 14)
{
Y--;
if (victory[X, Y] == q) p++;
}
else break;
if (victory[X, Y] != q) break;
}
Y = y;
for (h = 0; h <= 4; h++)
{
if (Y >= 0 && Y < 14)
{
int c;
c = victory[X, Y];
Y++;
if (victory[X, Y] == q) p++;
}
else break;
if (victory[X, Y] != q) break;
}
if (p >= 5) return 1;
else return 0;
}
int judge2 (int x,int y)
{
int p = 1, q, h, X, Y;
q = victory[x, y];
X = x; Y = y;
for (h = 0; h <= 4; h++)
{
if (X > 0 && X <= 14)
{
X--;
if (victory[X, Y] == q) p++;
}
else break;
if (victory[X, Y] != q) break;
}
X = x;
for (h = 0; h <= 4; h++)
{
if (X >= 0 && X < 14)
{
X++;
if (victory[X, Y] == q) p++;
}
else break;
if (victory[X, Y] != q) break;
}
if (p >= 5) return 1;
else return 0;
}
int judge3(int x,int y)
{
int p = 1, q, h, X, Y;
q = victory[x, y];
X = x; Y = y;
for (h = 0; h <= 4; h++)
{
if (X > 0 && X <= 14 && Y > 0 && Y <= 14)
{
X--;
Y--;
if (victory[X, Y] == q) p++;
}
else break;
if (victory[X, Y] != q) break;
}
X = x; Y = y;
for (h = 0; h <= 4; h++)
{
if (X >= 0 && X < 14 && Y >= 0 && Y < 14)
{
X++;
Y++;
if (victory[X, Y] == q) p++;
}
else break;
if (victory[X, Y] != q) break;
}
if (p >= 5) return 1;
else return 0;
}
int judge4(int x,int y)
{
int p = 1, q, h, X, Y;
q = victory[x, y];
X = x; Y = y;
for (h = 0; h <= 4; h++)
{
if (X > 0 && X <= 14 && Y >= 0 && Y < 14)
{
X--;
Y++;
if (victory[X, Y] == q) p++;
}
else break;
if (victory[X, Y] != q) break;
}
X = x; Y = y;
for (h = 0; h <= 4; h++)
{
if (X >= 0 && X < 14 && Y > 0 && Y <= 14)
{
X++;
Y--;
if (victory[X, Y] == q) p++;
}
else break;
if (victory[X, Y] != q) break;
}
if (p >= 5) return 1;
else return 0;
}
private void kaishi_Click(object sender, EventArgs e)//开始按钮,判断谁先,清空数组
{
int p, q;
button4 .Visible =true;
button2 .Visible =true;
pictureBox1.Visible = false;
for (p = 0; p < 15; p++)
for (q = 0; q < 15; q++)
victory[p, q] = 0;
for (p = 0; p <15; p++)
for (q = 0; q < 15; q++)
wuziqiPictureBox[p, q].Visible = false;
}
private void label2_Click(object sender, EventArgs e)
{
}
void Button1Click(object sender, EventArgs e)//返回主界面
{
Form f=new Form1();
this.Visible=false;
f.Show();
}
void MainFormLoad(object sender, EventArgs e)//显示胜利的图片不可见
{
pictureBox1.Visible=false;
}
void PictureBox1Click(object sender, EventArgs e)
{
}
void Label2Click(object sender, EventArgs e)
{
}
}
}
|
Go
|
UTF-8
| 3,303 | 3.03125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
package sqlmock
import (
"database/sql/driver"
"errors"
"fmt"
"testing"
)
type void struct{}
func (void) Print(...interface{}) {}
type converter struct{}
func (c *converter) ConvertValue(v interface{}) (driver.Value, error) {
return nil, errors.New("converter disabled")
}
func ExampleNew() {
db, mock, err := New()
if err != nil {
fmt.Println("expected no error, but got:", err)
return
}
defer db.Close()
// now we can expect operations performed on db
mock.ExpectBegin().WillReturnError(fmt.Errorf("an error will occur on db.Begin() call"))
}
func TestShouldOpenConnectionIssue15(t *testing.T) {
db, mock, err := New()
if err != nil {
t.Errorf("expected no error, but got: %s", err)
}
if len(pool.conns) != 1 {
t.Errorf("expected 1 connection in pool, but there is: %d", len(pool.conns))
}
smock, _ := mock.(*sqlmock)
if smock.opened != 1 {
t.Errorf("expected 1 connection on mock to be opened, but there is: %d", smock.opened)
}
// defer so the rows gets closed first
defer func() {
if smock.opened != 0 {
t.Errorf("expected no connections on mock to be opened, but there is: %d", smock.opened)
}
}()
mock.ExpectQuery("SELECT").WillReturnRows(NewRows([]string{"one", "two"}).AddRow("val1", "val2"))
rows, err := db.Query("SELECT")
if err != nil {
t.Errorf("unexpected error: %s", err)
}
defer rows.Close()
mock.ExpectExec("UPDATE").WillReturnResult(NewResult(1, 1))
if _, err = db.Exec("UPDATE"); err != nil {
t.Errorf("unexpected error: %s", err)
}
// now there should be two connections open
if smock.opened != 2 {
t.Errorf("expected 2 connection on mock to be opened, but there is: %d", smock.opened)
}
mock.ExpectClose()
if err = db.Close(); err != nil {
t.Errorf("expected no error on close, but got: %s", err)
}
// one is still reserved for rows
if smock.opened != 1 {
t.Errorf("expected 1 connection on mock to be still reserved for rows, but there is: %d", smock.opened)
}
}
func TestTwoOpenConnectionsOnTheSameDSN(t *testing.T) {
db, mock, err := New()
if err != nil {
t.Errorf("expected no error, but got: %s", err)
}
db2, mock2, err := New()
if err != nil {
t.Errorf("expected no error, but got: %s", err)
}
if len(pool.conns) != 2 {
t.Errorf("expected 2 connection in pool, but there is: %d", len(pool.conns))
}
if db == db2 {
t.Errorf("expected not the same database instance, but it is the same")
}
if mock == mock2 {
t.Errorf("expected not the same mock instance, but it is the same")
}
}
func TestWithOptions(t *testing.T) {
c := &converter{}
_, mock, err := New(ValueConverterOption(c))
if err != nil {
t.Errorf("expected no error, but got: %s", err)
}
smock, _ := mock.(*sqlmock)
if smock.converter.(*converter) != c {
t.Errorf("expected a custom converter to be set")
}
}
func TestWrongDSN(t *testing.T) {
t.Parallel()
db, _, _ := New()
defer db.Close()
if _, err := db.Driver().Open("wrong_dsn"); err == nil {
t.Error("expected error on Open")
}
}
func TestNewDSN(t *testing.T) {
if _, _, err := NewWithDSN("sqlmock_db_99"); err != nil {
t.Errorf("expected no error on NewWithDSN, but got: %s", err)
}
}
func TestDuplicateNewDSN(t *testing.T) {
if _, _, err := NewWithDSN("sqlmock_db_1"); err == nil {
t.Error("expected error on NewWithDSN")
}
}
|
TypeScript
|
UTF-8
| 3,761 | 2.84375 | 3 |
[] |
no_license
|
export interface IimageStock {
stock: priceAndEntities;
retraitemants: {
FNP: elementData[];
CCA: elementData[];
};
}
export interface IimageStockFinal extends IimageStock {
achats: elementData[];
ventes: elementData[];
}
interface elementData {
name: string;
entities: number;
priceTotal: number;
}
interface priceAndEntities {
priceTotal: number;
entityTotal: number;
}
export default class Inventaire {
private image_initial: IimageStock;
private image_final: IimageStockFinal;
constructor(image_initial: IimageStock, image_final: IimageStockFinal) {
this.image_initial = image_initial;
this.image_final = image_final;
}
public getResults() {
return {
stocks: {
initial: this.image_initial.stock,
final: this.image_final.stock,
},
variationPrixStock: this.getVariationPrixStock(),
retraitements: {
initial: this.image_initial.retraitemants,
final: this.image_final.retraitemants,
result: this.getRetraitement_c(),
},
achats: {
data: this.image_final.achats,
result: this.getSumOfElements(this.image_final.achats),
},
ventes: {
data: this.image_final.ventes,
result: this.getSumOfElements(this.image_final.ventes),
},
finalStockValues: this.getStockFinalValues(),
diffStockFinalCardiff: this.getDiffStockFinalCardiff(),
};
}
private getVariationPrixStock(): number {
return (
this.image_initial.stock.priceTotal - this.image_final.stock.priceTotal
);
}
private getRetraitement_c(): priceAndEntities {
const FNP_initial = this.image_initial.retraitemants.FNP;
const CCA_initial = this.image_initial.retraitemants.CCA;
const FNP_final = this.image_final.retraitemants.FNP;
const CCA_final = this.image_final.retraitemants.CCA;
return {
priceTotal:
this.sumElementsPrice(CCA_initial) +
this.sumElementsPrice(FNP_final) -
this.sumElementsPrice(FNP_initial) -
this.sumElementsPrice(CCA_final),
entityTotal:
this.sumElementsEntities(CCA_initial) +
this.sumElementsEntities(FNP_final) -
this.sumElementsEntities(FNP_initial) -
this.sumElementsEntities(CCA_final),
};
}
private getAchats_c(): priceAndEntities {
return {
priceTotal:
this.sumElementsPrice(this.image_final.achats) +
this.getRetraitement_c().priceTotal,
entityTotal:
this.sumElementsEntities(this.image_final.achats) +
this.getRetraitement_c().entityTotal,
};
}
private getStockFinalValues(): priceAndEntities {
return {
priceTotal:
this.getAchats_c().priceTotal -
this.sumElementsPrice(this.image_final.ventes) +
this.image_initial.stock.priceTotal,
entityTotal:
this.getAchats_c().entityTotal -
this.sumElementsEntities(this.image_final.ventes) +
this.image_initial.stock.entityTotal,
};
}
private getDiffStockFinalCardiff(): priceAndEntities {
const stockFinalValues = this.getStockFinalValues();
return {
priceTotal:
this.image_final.stock.priceTotal - stockFinalValues.priceTotal,
entityTotal:
this.image_final.stock.entityTotal - stockFinalValues.entityTotal,
};
}
private getSumOfElements(data: elementData[]): priceAndEntities {
return {
priceTotal: this.sumElementsPrice(data),
entityTotal: this.sumElementsEntities(data),
};
}
private sumElementsPrice(data: elementData[]): number {
return data.reduce((x, n) => x + n.priceTotal, 0);
}
private sumElementsEntities(data: elementData[]): number {
return data.reduce((x, n) => x + n.entities, 0);
}
}
|
Swift
|
UTF-8
| 537 | 2.828125 | 3 |
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
let strin = String(format: "nesto %d hfshdj %d", 123, 12)
let z = 5435
let nesto = String(format : "http://adserver.iprom.net/adserver7/Click?z=%d;ad=140886;m=RTL;sid=vijesti_hr;ssid=novosti;flash=0;rdr=http%3A%2F%2Fwww%2Eiprom%2Eeu;kw=;tm=1484727217", z)
let nesto2 = "http://adserver.iprom.net/adserver7/Click?z=\(z);ad=140886;m=RTL;sid=vijesti_hr;ssid=novosti;flash=0;rdr=http%3A%2F%2Fwww%2Eiprom%2Eeu;kw=;tm=1484727217"
print(nesto)
|
Java
|
UTF-8
| 8,248 | 2.796875 | 3 |
[] |
no_license
|
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
//import java.io.FileOutputStream;
//import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main
{
public static KaiSevenIndex[] Index_kaiSeven;
public static int EndOfKaiSevenIndex;
public static int TheLastNewsNo;
public static String[][] NewsMappingTable;
public static void main(String[] args)
{
long StarTime = System.currentTimeMillis();
Scanner LevelTwoDataInput = null;
try
{
LevelTwoDataInput = new Scanner(new FileInputStream("KaiSevenIndexData-Level-Two.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("input file error!");
System.exit(0);
}
TheLastNewsNo = LevelTwoDataInput.nextInt();
LevelTwoDataInput.nextLine();
EndOfKaiSevenIndex = LevelTwoDataInput.nextInt();
LevelTwoDataInput.nextLine();
LevelTwoDataInput.nextLine();
Index_kaiSeven = new KaiSevenIndex[EndOfKaiSevenIndex + 1];
buildKaiSevenIndex(LevelTwoDataInput);
LevelTwoDataInput.close();
// inspectionBuildKaiSevenIndex();
NewsMappingTable = new String[EndOfKaiSevenIndex + 1][3];
buildNewsMappingTable();
long EndTime = System.currentTimeMillis();
double TotalTime = (EndTime - StarTime) / 1000.0;
System.out.println("It takes " + TotalTime + " sec to build KaiSevenIndex and NewsMappingTable");
SearchEngineWindow SearchEngine = new SearchEngineWindow();
SearchEngine.setLocation(400, 50);
SearchEngine.setVisible(true);
}
public static void buildKaiSevenIndex(Scanner Input)
{
String TempKeyWord = null;
int TempRelativePageNum;
int TempDestinationPageNo;
int TempPositionNum;
int TempPositionNo;
for(int i = 1; i <= EndOfKaiSevenIndex; i++)
{
TempKeyWord = Input.nextLine();
TempRelativePageNum = Input.nextInt();
Input.nextLine();
Index_kaiSeven[i] = new KaiSevenIndex(TempKeyWord, TempRelativePageNum);
Index_kaiSeven[i].setRelativePageNum(TempRelativePageNum);
for(int j=0; j <= TempRelativePageNum - 1; j++)
{
TempDestinationPageNo = Input.nextInt();
TempPositionNum = Input.nextInt();
Index_kaiSeven[i].structorPositionOfDestinationPage(j, TempPositionNum);
Index_kaiSeven[i].setDestinationPageIndexOn(TempDestinationPageNo, j);
Index_kaiSeven[i].setPositionNumForDestinationIndexOn(j, TempPositionNum);
for(int k=2; k <= TempPositionNum + 1; k++)
{
TempPositionNo = Input.nextInt();
Index_kaiSeven[i].setPositionNoForDestinationPageIndexOn(j, k, TempPositionNo);
}
Input.nextLine();
}
Input.nextLine();
}
}
public static void buildNewsMappingTable()
{
Scanner NewsMappingDataInput = null;
try
{
NewsMappingDataInput = new Scanner(new FileInputStream("NewsMappingTable.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("input data error");
System.exit(0);
}
int Index = 1;
while(NewsMappingDataInput.hasNextLine())
{
NewsMappingTable[Index][0] = NewsMappingDataInput.nextLine();
NewsMappingTable[Index][1] = NewsMappingDataInput.nextLine();
NewsMappingTable[Index][2] = NewsMappingDataInput.nextLine();
NewsMappingDataInput.nextLine();
Index++;
}
NewsMappingDataInput.close();
}
public static KaiSevenStringLinkListNode linearSearch(String[] theKeywordSet)
{
Scanner LinearSearchInput = null;
try
{
LinearSearchInput = new Scanner(new FileInputStream("News.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("input data error");
System.exit(0);
}
int KeywordNum = theKeywordSet.length;
boolean[] isHit = new boolean[KeywordNum];
for(int i=0; i < KeywordNum; i++)
isHit[i] = false;
boolean isTotalHit = true;
String TempHandlingLine1 = null;
String TempHandlingLine2 = null;
StringTokenizer HandlingLine = null;
String HandlingToken = null;
// String WhatIsDelimiter_1 = " .,':?!\"()"
String WhatIsDelimiter_2 = " .,':?!\"()-$`@#%&/;=_0123456789*+";
KaiSevenStringLinkListNode StartNode = new KaiSevenStringLinkListNode();
KaiSevenStringLinkListNode EndNode = StartNode;
int NewsNo = 1;
while(LinearSearchInput.hasNextLine())
{
TempHandlingLine1 = LinearSearchInput.nextLine();
TempHandlingLine2 = LinearSearchInput.nextLine();
for(int i=0; i < KeywordNum; i++)
{
String hitKeyword = theKeywordSet[i];
HandlingLine = new StringTokenizer(TempHandlingLine1, WhatIsDelimiter_2);
while(HandlingLine.hasMoreTokens())
{
HandlingToken = HandlingLine.nextToken();
if(HandlingToken.equals(hitKeyword))
{
isHit[i] = true;
break;
}
}
if(isHit[i])
continue;
HandlingLine = new StringTokenizer(TempHandlingLine2, WhatIsDelimiter_2);
while(HandlingLine.hasMoreTokens())
{
HandlingToken = HandlingLine.nextToken();
if(HandlingToken.equals(hitKeyword))
{
isHit[i] = true;
break;
}
}
if(isHit[i])
continue;
else
break;
}
for(int i=0; i < KeywordNum; i++)
if(!isHit[i])
{
isTotalHit = false;
break;
}
LinearSearchInput.nextLine();
LinearSearchInput.nextLine();
LinearSearchInput.nextLine();
LinearSearchInput.nextLine();
LinearSearchInput.nextLine();
LinearSearchInput.nextLine();
if(isTotalHit)
{
String[] theHitPageInformation = NewsMappingTable[NewsNo];
EndNode.increaseNextStringNode(theHitPageInformation);
EndNode = EndNode.getNextStringNode();
}
for(int i=0; i < KeywordNum; i++)
isHit[i] = false;
isTotalHit = true;
NewsNo++;
}
LinearSearchInput.close();
return StartNode;
}
public static KaiSevenStringLinkListNode binarySearch(String[] theKeywordSet)
{
String hitKeyword = theKeywordSet[0];
int front = 1;
int rear = EndOfKaiSevenIndex;
int middle = 0;
int theHitIndex = 0;
boolean isHit = false;
while(front <= rear)
{
middle = (front + rear) / 2;
if(Index_kaiSeven[middle].getKeyWord().equals(hitKeyword))
{
theHitIndex = middle;
isHit = true;
break;
}
else
{
if(Index_kaiSeven[middle].getKeyWord().compareTo(hitKeyword)<0)
front = middle + 1;
else
rear = middle -1;
}
}
if(!isHit)
theHitIndex = (-front);
KaiSevenStringLinkListNode StartNode = new KaiSevenStringLinkListNode();
KaiSevenStringLinkListNode EndNode = StartNode;
if(theHitIndex < 0)
return StartNode;
int theHitPageNo;
int theHitPageNum = Index_kaiSeven[theHitIndex].getRelativePageNum();
for(int i=0; i < theHitPageNum; i++)
{
theHitPageNo = Index_kaiSeven[theHitIndex].getDestinationPageIndexOn(i);
String[] theHitPageInformation = NewsMappingTable[theHitPageNo];
EndNode.increaseNextStringNode(theHitPageInformation);
EndNode = EndNode.getNextStringNode();
}
return StartNode;
}
/*
private static void inspectionBuildKaiSevenIndex()
{
PrintWriter InspectionDataOutput = null;
try
{
InspectionDataOutput = new PrintWriter(new FileOutputStream("KaiSevenIndexData-Test.txt"));
}
catch(FileNotFoundException e)
{
System.out.print("onput data error!");
System.exit(0);
}
InspectionDataOutput.println(TheLastNewsNo);
InspectionDataOutput.println(EndOfKaiSevenIndex);
InspectionDataOutput.println();
int TempForHitPageNum;
int TempForHitPageNo;
int TempPositionNumForHitPageNo;
for(int i=1; i<=EndOfKaiSevenIndex; i++)
{
InspectionDataOutput.println(Index_kaiSeven[i].getKeyWord());
TempForHitPageNum = Index_kaiSeven[i].getRelativePageNum();
InspectionDataOutput.println(TempForHitPageNum);
for(int j=0; j<TempForHitPageNum; j++)
{
TempForHitPageNo = Index_kaiSeven[i].getDestinationPageIndexOn(j);
InspectionDataOutput.print(TempForHitPageNo + " ");
TempPositionNumForHitPageNo = Index_kaiSeven[i].getPositionNumIndexOn(j);
InspectionDataOutput.print(TempPositionNumForHitPageNo + " ");
for(int k=2; k<=TempPositionNumForHitPageNo+1; k++)
{
InspectionDataOutput.print(Index_kaiSeven[i].getPositionNoIndexOn(j, k) + " ");
}
InspectionDataOutput.println();
}
InspectionDataOutput.println();
}
InspectionDataOutput.close();
}
*/
}
|
Swift
|
UTF-8
| 363 | 2.515625 | 3 |
[] |
no_license
|
//
// DomainConvertible.swift
//
//
// Created by 이광용 on 2020/12/04.
//
import CoreData
protocol DomainConvertible: NSFetchRequestResult {
associatedtype DomainType
func asDomain() throws -> DomainType
static func fetchRequest() -> NSFetchRequest<Self>
}
enum DomainConvertError: Error {
case convertingIsFailed
}
|
C++
|
UTF-8
| 1,893 | 2.921875 | 3 |
[] |
no_license
|
#include "MapSearchNode.h"
#include "Mappa.h"
#include "Personaggio.h"
bool MapSearchNode::IsSameState( MapSearchNode &rhs )
{
return (x == rhs.x) && (y == rhs.y);
}
void MapSearchNode::PrintNodeInfo()
{
Personaggio::Instance()->setPers(x*80,y*80);
//Mappa::Instance()->setLvlmap(x,y);
cout << "Node position:(" << x << "," << y << ")" << std::endl;
}
float MapSearchNode::GoalDistanceEstimate( MapSearchNode &nodeGoal )
{
return std::abs(x - nodeGoal.x) + std::abs(y - nodeGoal.y);
}
bool MapSearchNode::IsGoal( MapSearchNode &nodeGoal )
{
return (x == nodeGoal.x) && (y == nodeGoal.y);
}
bool MapSearchNode::GetSuccessors( AStarSearch<MapSearchNode> *astarsearch, MapSearchNode *parent_node )
{
int parent_x = -1;
int parent_y = -1;
if( parent_node )
{
parent_x = parent_node->x;
parent_y = parent_node->y;
}
MapSearchNode NewNode;
if( (Mappa::Instance()->getMap( x-1, y ) < 9)
&& !((parent_x == x-1) && (parent_y == y))
)
{
NewNode = MapSearchNode(x-1, y);
astarsearch->AddSuccessor( NewNode );
}
if( (Mappa::Instance()->getMap( x, y-1 ) < 9)
&& !((parent_x == x) && (parent_y == y-1))
)
{
NewNode = MapSearchNode( x, y-1);
astarsearch->AddSuccessor( NewNode );
}
if( (Mappa::Instance()->getMap( x+1, y ) < 9)
&& !((parent_x == x+1) && (parent_y == y))
)
{
NewNode = MapSearchNode( x+1, y);
astarsearch->AddSuccessor( NewNode );
}
if( (Mappa::Instance()->getMap( x, y+1 ) < 9)
&& !((parent_x == x) && (parent_y == y+1))
)
{
NewNode = MapSearchNode( x, y+1);
astarsearch->AddSuccessor( NewNode );
}
return true;
}
float MapSearchNode::GetCost( MapSearchNode &successor )
{
return (float) Mappa::Instance()->getMap( x, y );
}
|
C++
|
UTF-8
| 1,470 | 3.0625 | 3 |
[] |
no_license
|
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
int n=preorder.size();
if(n==0) return NULL;
int rootVal=preorder[0];
TreeNode *curr=new TreeNode(rootVal);
auto rit=find(inorder.begin(),inorder.end(),rootVal);
auto lIn0=inorder.begin(), lInN=rit, rIn0=next(rit), rInN=inorder.end();
auto lPr0=next(preorder.begin()), lPrN=next(lPr0,distance(lIn0,lInN)),
rPr0=lPrN, rPrN=preorder.end();
curr->left=buildTree(lPr0,lPrN,lIn0,lInN);
curr->right=buildTree(rPr0,rPrN,rIn0,rInN);
return curr;
}
TreeNode *buildTree(vector<int>::iterator pr0, vector<int>::iterator prN,
vector<int>::iterator in0, vector<int>::iterator inN) {
if(in0<inN) {
int rootVal=*pr0;
TreeNode *curr=new TreeNode(rootVal);
auto rit=find(in0,inN,rootVal);
auto lIn0=in0, lInN=rit, rIn0=next(rit), rInN=inN;
auto lPr0=next(pr0), lPrN=next(lPr0,distance(lIn0,lInN)),
rPr0=lPrN, rPrN=prN;
curr->left=buildTree(lPr0,lPrN,lIn0,lInN);
curr->right=buildTree(rPr0,rPrN,rIn0,rInN);
} else return NULL;
}
};
|
C
|
UTF-8
| 427 | 3.46875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <string.h>
int main()
{
char str[20];
while (scanf("%s",str)!=EOF)
{
int i;
int num=0;
int count=0;
for (i=0;i<=11;i++)
{
if (str[i]!='-')
{
int temp=str[i]-'0';
num=num+(++count)*temp;
}
}
int ans = num % 11;
if (ans==str[12]-'0')
printf("Right\n");
else
{
for (i=0;i<=11;i++)
printf("%c",str[i]);
printf("%d\n",ans);
}
}
return 0;
}
|
Markdown
|
UTF-8
| 913 | 3.1875 | 3 |
[] |
no_license
|
# The-Android-App-Market-on-Google-Play
Introduction.
Mobile apps are everywhere. They are easy to create and can be lucrative. Because of these two factors, more and more apps are being developed. This project is a comprehensive analysis of the Android app market by comparing over ten thousand apps in Google Play across different categories. Insights in the data help to devise strategies to drive growth and retention.
Project Description.
This project lets you apply the skills from Data Manipulating with pandas.
The data for this project was from DataCamp.
Project Tasks.
1. Google Play Store apps and reviews
2. Data cleaning
3. Correcting data types
4. Exploring app categories
5. Distribution of app ratings
6. Size and price of an app
7. Relation between app category and app price
8. Filter out "junk" apps
9. Popularity of paid apps vs free apps
10. Sentiment analysis of user reviews
|
Python
|
UTF-8
| 1,255 | 3.546875 | 4 |
[] |
no_license
|
# -----------------------------------------------------------------------------
# Copyright (c) 2015, Nicolas P. Rougier. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------------------------
# Imports
import matplotlib.pyplot as plt
import numpy as np
# 创建一个 8 * 6 点(point)的图,并设置分辨率为 80
plt.figure(figsize=(8,6), dpi=100)
# 创建一个新的 1 * 1 的子图,接下来的图样绘制在其中的第 1 块(也是唯一的一块)
plt.subplot(111)
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)
# 绘制余弦曲线,使用蓝色的、连续的、宽度为 1 (像素)的实线
plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-")
# 绘制正弦曲线,使用绿色的、连续的、宽度为 1 (像素)的虚线
plt.plot(X, S, color="green", linewidth=1.0, linestyle=":")
# 设置 x 轴范围
plt.xlim(-4.0,4.0)
# 设置 x轴 记号
plt.xticks(np.linspace(-4,4,9,endpoint=True))
# 设置 y 轴范围
plt.ylim(-1.0,1.0)
# 设置 y轴 记号
plt.yticks(np.linspace(-1,1,5,endpoint=True))
#保存图片到当前目录下
plt.savefig("exercice_2.png",dpi=72)
plt.show()
|
Java
|
UTF-8
| 1,303 | 2.171875 | 2 |
[] |
no_license
|
package com.unit.zxl.interceptor;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
/*
* 登录拦截器
*/
public class LoginInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
// TODO Auto-generated method stub
}
/*
* 登录验证
*
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object arg2) throws Exception {
if(request.getSession().getAttribute("userName")!=null){
return true;
} else if(request.getServletPath()=="/login"){
System.out.println(request.getServletPath());
return true;
}else{
response.sendRedirect(request.getContextPath() +"/login");
return false;
}
}
}
|
Markdown
|
UTF-8
| 976 | 2.53125 | 3 |
[] |
no_license
|
# Dirt Bike Unchained Hack 10k free tokens cheats mod android unlimtied cash tips
Dirt Bike Unchained Hack 10k free tokens cheats mod android unlimtied cash tips - Lots of people knows that it is hard to achieve high level in Dirt Bike Unchained without free tokens and unlimite cash. Not everyone can afford to spend his own money and not everyone want to do it. We’ve gone in front of your expectations and we built Dirt Bike Unchained hack. Now you won’t feel bad because lack of money. Since now you will be able to generate unlimited Tokens to this wonderful game. Thanks to Dirt Bike Unchained mod all the frustration will disappear, and now you won’t have any limits to buy anything. Everything is on hand. Only thing you need to do is to sit, run Dirt Bike Unchained and then our Dirt Bike Unchained cheats. Then you choose quantities of Tokens and in just few minutes you will became rich player. Don’t wait!
here https://lahasoft.com/dirt-bike-unchained/
|
Python
|
UTF-8
| 322 | 2.875 | 3 |
[] |
no_license
|
class Control:
#takes charID from rules and sends to Location
def initializeCharacters(self,charID):
Control.l.addID(charID)
print("charid added to location")
#pass a reference to the Location class so that we can access it.
def __init__(self,L):
Control.l=L
|
Markdown
|
UTF-8
| 2,493 | 3.46875 | 3 |
[] |
no_license
|
# PHP 與 MySQL 的互動:刪除資料
### HULI 範例
```php=
<?php
//連結 local host
require_once('conn.php');
//預防空白輸入
if (empty($_GET['id'])) {
die('請輸入 id');
}
//request method
$id = $_GET['id'];
$sql = sprintf(
"delete from users where id = %d",
$id
);
echo $sql . '<br>';
$result = $conn->query($sql);
if (!$result) {
die($conn->error);
}
//回傳是否成功
if ($conn->affected_rows >= 1) {
echo '刪除成功';
} else {
echo '查無資料';
}
// header("Location: index.php");
?>
```
- 刪除做法與 insert 很像,主要變更部分是把 insert 改成 delete 語法,首先我們先把 data.php 新增一個刪除按鈕
```php
<?php
require_once('conn.php');
//拿資料
$result = $conn->query('SELECT * from users order by id DESC;');
//now() 也可用 * 取代,另外 order by id DESC (由大到小)、 ASC(由小到大)
//檢查資料有無錯誤
if (!$result) {
die($conn->error);
}
//拿出已取得的資料,藉由 fetch_assoc() 取得相對應得資料
while($row = $result->fetch_assoc()) {
echo 'id:' . $row['id'];
echo "<a href='delete.php?id=" . $row['id'] ."'>刪除</a>" . '<br>';
echo 'username:' . $row['username'] . '<br>';
}
?>
```
- 接著把 Php request 部分改成 delete method
```php=
<?php
require_once('conn.php');
//拿資料
if (empty($_GET['id'])) {
die('請輸入 id');
}
$id = $_GET['id'];
$sql = sprintf( //前面用 spintf() function
"DELETE FROM users WHERE id = %d",
$id //%d 是 place holder ,後面的變數會依序取代
);
echo $sql;
$result = $conn->query($sql);
print_r($result);
//檢查資料有無錯誤,有錯就終止城市
if (!$result) {
die($conn->error);
}
header("Location: data.php");
?>
<a href='data.php'>go back<a>
```
- 另外要注意的是假設我們 delete 一個不存在的 id ,還是會執行成功,對於資料庫來說刪除一個不存在的資料是合理的。
- 接著我們其實可以用判斷刪除之後影響幾列,來知道有沒有成功刪除存在的資料,用到的函數是 afffected_rows,會回傳影響幾列
```php=
echo $conn->affected_rows;
```

- 所以我們可以透過判斷 affected_row 的數量來判斷是否有刪除成功
```php=
if ($conn->affected_rows >0) {
echo '刪除成功';
} else {
echo '刪除失敗';
}
```

###### tags: `week9`
|
Go
|
UTF-8
| 1,170 | 3.859375 | 4 |
[] |
no_license
|
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
)
// ComputeFuelForMassRecursively return fuel needed to move a module based on its mass plus an accumulator
func ComputeFuelForMassRecursively(accumulator int, mass int) int {
res := mass/3 - 2
if res < 0 {
return accumulator
}
return ComputeFuelForMassRecursively(accumulator+res, res)
}
// ComputeFuelForMass return fuel needed to move a module based on its mass
func ComputeFuelForMass(mass int) int {
return ComputeFuelForMassRecursively(0, mass)
}
// ComputeFuelForAllModule return fuel needed to move all modules in file
// each module is described by its respective mass
func ComputeFuelForAllModule(file *os.File) (int, error) {
fuel := 0
scanner := bufio.NewScanner(file)
for scanner.Scan() {
mass, _ := strconv.Atoi(scanner.Text())
fuel = fuel + ComputeFuelForMass(mass)
}
return fuel, scanner.Err()
}
// ReadFile reads a file and prints all its value
func ReadFile() {
file, err := os.Open("./input/day1.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
fuel, err := ComputeFuelForAllModule(file)
if err != nil {
log.Fatal(err)
}
fmt.Println(fuel)
}
|
Java
|
UTF-8
| 160 | 1.914063 | 2 |
[] |
no_license
|
package theGardener.powers;
import theGardener.garden.structures.AbstractPlant;
public interface OnHarvestSubscriber {
void onHarvest(AbstractPlant p);
}
|
Python
|
UTF-8
| 16,437 | 2.609375 | 3 |
[] |
no_license
|
import board
import neopixel
import time
import datetime
import logging
from datetime import timezone
import numpy
import json
from skyfield.api import N, W, wgs84, load, utc
from skyfield.almanac import find_discrete, risings_and_settings
#initialize log
logging.basicConfig(filename='main.log', format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)
logging.logProcesses = 0
logging.logThreads = 0
def read_config():
with open('config.json') as json_file:
config_data = json.load(json_file)
return config_data
def planet_timestamp(name, action, ts, planets, city, eph, names):
print(name, action)
logging.info('%s %s' % (name, action))
# this function returns the next rise or set time from now
t0 = datetime.datetime.now(timezone.utc)
print('t0:', t0)
logging.info('t0: %s' % t0)
# make hours 24+1 because during spring, next sunset will be more than 24h later than current
t1 = t0 + datetime.timedelta(hours=28)
print('t1:', t1)
logging.info('t1: %s' % t1)
# t0 = t0.replace(tzinfo=utc)
t0 = ts.utc(t0)
# t1 = t1.replace(tzinfo=utc)
t1 = ts.utc(t1)
f = risings_and_settings(eph, planets[names.index(name)], city)
#This returns a function taking a Time argument returning True if the body’s altazimuth altitude angle plus radius_degrees is greater than horizon_degrees, else False
t, values = find_discrete(t0, t1, f)
#Find the times at which a discrete function of time changes value. in this case, find the set (0) and rise (1) times, t.
if action == 'rise':
#values array is 1 for the rise. we look up the index of the rise in the time array, t, to get the time of the rise event.
timestamp = t[numpy.where(values == 1)].utc_datetime()
print('timestamp:', timestamp)
logging.info('timestamp: %s' % timestamp)
else:
#values array is 0 for the set. we look up the index of the set in the time array, t, to get the time of the set event.
timestamp = t[numpy.where(values == 0)].utc_datetime()
print('timestamp:', timestamp)
logging.info('timestamp: %s' % timestamp)
timestamp = timestamp[0].timestamp()
return int(timestamp)
def make_planet_list(ts, planets, city, eph, names):
rise = [[0 for i in range(3)] for j in range(len(names))]
sett = [[0 for i in range(3)] for j in range(len(names))]
for i, name in enumerate(names):
# obtain the next rise time
rise[i][0] = planet_timestamp(name, 'rise', ts, planets, city, eph, names)
rise[i][1] = name
rise[i][2] = 'rise'
print('acquired:', rise[i][0], name, 'rise')
logging.info('acquired: %s, %s, rise' % (rise[i][0], name))
# obtain the next set time
sett[i][0] = planet_timestamp(name, 'sett', ts, planets, city, eph, names)
sett[i][1] = name
sett[i][2] = 'sett'
print('acquired:', sett[i][0], name, 'sett')
logging.info('acquired: %s, %s, sett' % (sett[i][0], name))
rise = [tuple(l) for l in rise]
sett = [tuple(l) for l in sett]
planet_list = rise + sett
return planet_list
def run_clock():
#initialize skyfield stuff
eph = load('de421.bsp')
sun = eph['sun']
moon = eph['moon']
mercury = eph['mercury']
venus = eph['venus']
earth = eph['earth']
mars = eph['mars']
jupiter = eph['JUPITER BARYCENTER']
saturn = eph['SATURN BARYCENTER']
uranus = eph['URANUS BARYCENTER']
neptune = eph['NEPTUNE BARYCENTER']
planets = [sun,
moon,
mercury,
venus,
mars,
jupiter,
saturn,
uranus,
neptune]
ts = load.timescale()
# define variables
# lat = 38.9072
# lon = 77.0369
config_data = read_config()
#define city just by lat/lon for almanac lookup
city = wgs84.latlon(float(config_data['lat']), float(config_data['lon']))
names = ['sun', 'moon', 'mercury', 'venus', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune']
#initialize neopixel
pixel_pin = board.D18
n = 81
ORDER = neopixel.RGBW
pixels = neopixel.NeoPixel(pixel_pin, n, brightness=1, pixel_order=ORDER)
# LED list for each light
LED = [(0, 0, 0, 25),
(0, 0, 0, 25),
(0, 0, 0, 25),
(0, 0, 0, 25),
(0, 0, 0, 25),
(0, 0, 0, 25),
(0, 0, 0, 25),
(0, 0, 0, 25),
(0, 0, 0, 25)]
now = int(time.time()) # return time since the Epoch
print('current unix timestamp:', now)
logging.info('current unix timestamp: %s' % now)
now_local = time.localtime(now)
now_local_str = " ".join(map(str, now_local))
print('local time string:', now_local_str)
logging.info('local time string: %s' % now_local_str)
planet_list = make_planet_list(ts, planets, city, eph, names)
for i in range(len(names)):
#clear LEDs at boot
pixels[i * 9] = (0, 0, 0, 0)
pixels[i * 9 + 1] = (0, 0, 0, 0)
pixels[i * 9 + 2] = (0, 0, 0, 0)
pixels[i * 9 + 3] = (0, 0, 0, 0)
pixels[i * 9 + 4] = (0, 0, 0, 0)
pixels[i * 9 + 5] = (0, 0, 0, 0)
pixels[i * 9 + 6] = (0, 0, 0, 0)
pixels[i * 9 + 7] = (0, 0, 0, 0)
pixels[i * 9 + 8] = (0, 0, 0, 0)
pixels.show()
time.sleep(0.5)
#turn on LEDs for planets already above horizon
if planet_list[i][0] > planet_list[i + 9][0]: # if rise time is later than set time, it's above the horizon
print('above horizon:', planet_list[i][1])
dur_rem = planet_list[i + 9][0] - now #find time remaining until set
dur = (24 * 3600) - (planet_list[i][0] - planet_list[i + 9][0]) #find approximate total time above horizon
dur_int = int(dur / (2 * (n / len(names)) - 1)) #find duration of a single timestemp interval
int_rem = int(dur_rem / dur_int) # number of intervals remaining is the duration remaining divided by duration interval
if int_rem > 17:
int_rem = 17
dur_int_rem = dur % dur_int #remainder of time in final interval
print('duration remaining:', dur_rem)
print('intervals remaining:', int_rem)
timestamp, planetname, action = planet_list[i + 9]
#if the planet is setting:
if int_rem < (n / len(names)) and not int_rem == 0:
# 1. find a_set timestamps
for j in range(int_rem - 1):
above_set_timestamp = int(timestamp - ((dur_int * (j + 1)) + dur_int_rem))
above_set_tuple = (above_set_timestamp, planetname, 'a_set')
planet_list.append(above_set_tuple)
# 2. light up last int_rem LEDs for setting
if i % 2 == 1:
for j in range(int_rem):
pixels[i * 9 + 9 - (j + 1)] = LED[j]
pixels.show()
elif i % 2 == 0:
for j in range(int_rem):
pixels[i * 9 + j] = LED[j]
pixels.show()
elif int_rem == 0: #if the planet is about to set, light up last LED only
if i % 2 == 1:
pixels[i * 9 + 9 - 1] = LED[0]
pixels.show()
elif i % 2 == 0:
pixels[i * 9] = LED[0]
pixels.show()
# if the planet is rising:
else:
#1. find a_rise timestamps
for j in range(int_rem - int(n / len(names))):
above_rise_timestamp = int(timestamp - (int((n / len(names)) - 1) * dur_int + dur_int * (j + 1) + dur_int_rem))
above_rise_tuple = (above_rise_timestamp, planetname, 'a_rise')
planet_list.append(above_rise_tuple)
#2. find a_set timestamps
for j in range(int(n / len(names) - 1)):
above_set_timestamp = int(timestamp - (dur_int * (j + 1) + dur_int_rem))
above_set_tuple = (above_set_timestamp, planetname, 'a_set')
planet_list.append(above_set_tuple)
#3. light up LEDs
for j in range(2 * int(n / len(names)) - int_rem):
if i % 2 == 1:
pixels[i * 9 + j] = LED[j]
pixels.show()
elif i % 2 == 0:
pixels[i * 9 + 9 - (j + 1)] = LED[j]
pixels.show()
list.sort(planet_list) #sort list of rise and set chronologically
print('planet list:')
print(planet_list)
logging.info('planet_list: %s' % planet_list)
while True:
timestamp, planetname, action = planet_list.pop(0)
timestamp_local = time.localtime(timestamp)
timestamp_local_str = " ".join(map(str, timestamp_local))
print('next up:',
'planet:', planetname,
'action:', action,
'unix timestamp:', timestamp,
'local event time:', timestamp_local_str)
logging.info('next up: planet: %s, action: %s, unix timestamp: %s, local event time: %s' % (planetname, action, timestamp,timestamp_local_str))
planet_num = names.index(planetname)
#sleep until the action
delay = timestamp - now
print('delay is:', delay)
logging.info('delay is: %s' % delay)
if delay > 0:
# sleep until timestamp
time.sleep(delay)
if action == 'rise':
print('action is:', action)
logging.info('action is: %s' % action)
#part 1: create list of above horizon intervals to adjust LEDs
dur = [item for item in planet_list if planetname in item][0][0] - timestamp
#find duration above horizon in seconds by looking up the timstamp of that planet's set time in planet_list (the rise time has been popped out)
dur_int = int(dur / (2 * (n / len(names)) - 1)) #find duration of a single timestemp interval
#dur_rem = dur % dur_int #find duration leftover (might not need this)
print('total time above horizon:', dur)
logging.info('total time above horizon: %s' % dur)
#add action timestamps for above_rise and above_set intervals between rise and set
for j in range(int((n / len(names)) - 1)):
above_rise_timestamp = int((timestamp + dur_int * (j + 1)))
above_rise_tuple = (above_rise_timestamp, planetname, 'a_rise')
planet_list.append(above_rise_tuple)
for j in range(int((n / len(names)) - 1)):
above_set_timestamp = int((timestamp + int((n / len(names)) - 1) * dur_int + dur_int * (j + 1)))
above_set_tuple = (above_set_timestamp, planetname, 'a_set')
planet_list.append(above_set_tuple)
#turn on first LED at rise action timestamp
if planet_num % 2 == 1:
pixels[planet_num * 9] = LED[0]
pixels.show()
if planet_num % 2 == 0:
pixels[planet_num * 9 + 9 - 1] = LED[0]
pixels.show()
print(planetname, 'rise')
logging.info('%s, rise' % planetname)
elif action == "a_rise":
print('action is:', action)
logging.info('action is: %s' % action)
#count remaining instances of a_rise
count = 0
for i in range(len(planet_list)):
if planet_list[i][1] == planetname and planet_list[i][2] == action:
count += 1
LED_count = int(n / len(names)) - count
print('count is:', count)
logging.info('count is: %s' % count)
for i in range(LED_count):
if planet_num % 2 == 1:
pixels[planet_num * 9 + i] = LED[i]
pixels.show()
elif planet_num % 2 == 0:
pixels[planet_num * 9 + 9 - (i + 1)] = LED[i]
pixels.show()
elif action == "a_set":
print('action is:', action)
logging.info('action is: %s' % action)
count = 0
for i in range(len(planet_list)):
if planet_list[i][1] == planetname and planet_list[i][2] == action:
count += 1
LED_count = count + 1
print('count is:', count)
logging.info('count is: %s' % count)
pixels[planet_num * 9] = (0, 0, 0, 0)
pixels[planet_num * 9 + 1] = (0, 0, 0, 0)
pixels[planet_num * 9 + 2] = (0, 0, 0, 0)
pixels[planet_num * 9 + 3] = (0, 0, 0, 0)
pixels[planet_num * 9 + 4] = (0, 0, 0, 0)
pixels[planet_num * 9 + 5] = (0, 0, 0, 0)
pixels[planet_num * 9 + 6] = (0, 0, 0, 0)
pixels[planet_num * 9 + 7] = (0, 0, 0, 0)
pixels[planet_num * 9 + 8] = (0, 0, 0, 0)
for i in range(LED_count):
if planet_num % 2 == 1:
pixels[planet_num * 9 + 9 - (i + 1)] = LED[i]
pixels.show()
if planet_num % 2 == 0:
pixels[planet_num * 9 + i] = LED[i]
pixels.show()
elif action == "sett":
print('action is:', action)
logging.info('action is: %s' % action)
pixels[planet_num * 9] = (0, 0, 0, 0)
pixels[planet_num * 9 + 1] = (0, 0, 0, 0)
pixels[planet_num * 9 + 2] = (0, 0, 0, 0)
pixels[planet_num * 9 + 3] = (0, 0, 0, 0)
pixels[planet_num * 9 + 4] = (0, 0, 0, 0)
pixels[planet_num * 9 + 5] = (0, 0, 0, 0)
pixels[planet_num * 9 + 6] = (0, 0, 0, 0)
pixels[planet_num * 9 + 7] = (0, 0, 0, 0)
pixels[planet_num * 9 + 8] = (0, 0, 0, 0)
pixels.show()
time.sleep(5)
if [item for item in planet_list if item[1] == planetname and item[2] == 'rise']:
#get next set timestamp only and add to list if there's already a 'rise' timestamp
next_set_timestamp = planet_timestamp(planetname, 'sett', ts, planets, city, eph, names)
next_set_tuple = (next_set_timestamp, planetname, 'sett')
planet_list.append(next_set_tuple)
print('rise found in planet_list')
print('next set:', next_set_timestamp)
logging.info('rise found in planet_list')
logging.info('next set: %s' % next_set_timestamp)
else:
print('no rise found in planet_list')
logging.info('no rise found in planet_list')
#get next rise timestamp and add to tuple if there isn't a rise
next_rise_timestamp = planet_timestamp(planetname, 'rise', ts, planets, city, eph, names)
next_rise_tuple = (next_rise_timestamp, planetname, 'rise')
planet_list.append(next_rise_tuple)
print('next rise:', next_rise_timestamp)
logging.info('next rise: %s' % next_rise_timestamp)
#get next set timestamp and add to list
next_set_timestamp = planet_timestamp(planetname, 'sett', ts, planets, city, eph, names)
next_set_tuple = (next_set_timestamp, planetname, 'sett')
planet_list.append(next_set_tuple)
print('next set:', next_set_timestamp)
logging.info('next set: %s' % next_set_timestamp)
now = int(time.time()) # return time since the Epoch (embedded)
print('current unix timestamp:', now)
logging.info('current unix timestamp: %s' % now)
now_local = time.localtime(now)
now_local_str = " ".join(map(str, now_local))
print('current local time:', now_local_str)
logging.info('current local time: %s' % now_local_str)
list.sort(planet_list)
print('planet list:')
print(planet_list)
logging.info('planet list: %s' % planet_list)
if __name__ == "__main__":
try:
run_clock()
except Exception as e:
logging.exception(e)
raise
|
Shell
|
UTF-8
| 1,351 | 3.59375 | 4 |
[] |
no_license
|
#!/bin/bash
#Script to execute the commands!
DATE=$(date '+%m-%d-%Y');
filename="${DATE}.txt"
num=0
while [ -f $filename ]; do
num=$(( $num + 1 ))
filename="${DATE}--${num}.txt"
done
touch $filename
dt=$(date '+%m/%d/%Y %H:%M:%S');
echo -e Hi there,"\n" >> $filename
echo -e At $dt, the following commands were executed and their outputs were collected >> $filename
echo -e "\n " >> $filename
sudo kill -3 2242
echo -e "Execute sudo netstat -tulpna" >> $filename
sudo netstat -tulpna >> $filename
echo -e "\n \n" >> $filename
echo -e "Execute sudo ss -ap" >> $filename
sudo ss -ap >> $filename
echo -e "\n \n" >> $filename
echo -e "Execute sudo ss -s" >> $filename
sudo ss -s >> $filename
echo -e "\n \n" >> $filename
echo -e "Execute sudo vmstat 3 3" >> $filename
sudo vmstat 3 3 >> $filename
echo -e "\n \n" >> $filename
echo -e "Execute sudo ps -auxf | sort -nr -k 4 | head -10" >> $filename
sudo ps -auxf | sort -nr -k 4 | head -10 >> $filename
echo -e "\n \n" >> $filename
echo -e "Execute sudo ps -auxf | sort -nr -k 3 | head -10" >> $filename
sudo ps -auxf | sort -nr -k 3 | head -10 >> $filename
echo -e "\n \n" >> $filename
echo -e Execute sudo lsof -i -U >> $filename
sudo lsof -i -U >> $filename
echo -e "\n \n" >> $filename
echo -e "Execute sudo lsof -a -p 2242" >> $filename
sudo lsof -a -p 2242 >> $filename
|
Python
|
UTF-8
| 7,305 | 3.390625 | 3 |
[
"MIT"
] |
permissive
|
import pytest
def test_dice_roll():
"""Test that the output of a dice roll is a list"""
from main import roll_dice
assert type(roll_dice()) == list
def test_many_dice():
"""Test that when 3 dice are rolled, three numbers come out"""
from main import roll_dice
assert len(roll_dice(num_die=3)) == 3
def test_dice_range():
"""Test that when multiple dice are rolled and a range is given,
the total of the dice rolls is less than or equal to
that limit multipled"""
from main import roll_dice
assert sum(roll_dice(20, 4)) <= 80
def char_setup():
from main import Character
bob = Character()
bob.char_name = "Bob"
bob.money = {
"GP": 100, "SP": 100, "EP": 100, "CP": 100, "PP": 100
}
return bob
STATS_TABLE = [
"strength", "dexterity", "charisma", "constitution",
"intelligence", "wisdom"
]
STATS_MODIFIER_TABLE = [
(1, -5), (2, -4), (3, -4), (4, -3), (5, -3), (6, -2), (7, -2),
(8, -1), (9, -1), (10, 0), (11, 0), (12, 1), (13, 1), (14, 2), (15, 2),
(16, 3), (17, 3), (18, 4), (19, 4), (20, 5), (21, 5), (22, 6), (23, 6),
(24, 7), (25, 7), (26, 8), (27, 8), (28, 9), (29, 9), (30, 10)
]
STATS_CHANGE_TABLE = [
("strength", 1), ("strength", 5),
("strength", -3)
]
MONEY_TYPES = [
"GP", "CP", "EP", "SP", "PP"
]
ADD_MONEY_TABLE = [
("GP", 5), ("GP", 1)
]
SPEND_MONEY_TABLE = [
("GP", 10, {"GP": 90, "SP": 100, "EP": 100, "CP": 100, "PP": 100}),
("SP", 10, {"GP": 100, "SP": 90, "EP": 100, "CP": 100, "PP": 100}),
("EP", 10, {"GP": 100, "SP": 100, "EP": 90, "CP": 100, "PP": 100}),
("CP", 10, {"GP": 100, "SP": 100, "EP": 100, "CP": 90, "PP": 100}),
("PP", 10, {"GP": 100, "SP": 100, "EP": 100, "CP": 100, "PP": 90}),
]
EXCHANGE_RATES = {
"PP": {"GP": 10, "SP": 100, "EP": 20, "CP": 1000, "PP": 1},
"GP": {"GP": 1, "SP": 10, "EP": 2, "CP": 100, "PP": 0.1},
"EP": {"GP": 0.5, "SP": 5, "EP": 1, "CP": 50, "PP": 0.5},
"SP": {"GP": 0.1, "SP": 1, "EP": 0.2, "CP": 10, "PP": 0.01},
"CP": {"GP": 0.01, "SP": 0.1, "EP": 0.02, "CP": 1, "PP": 0.001},
}
EXCHANGE_TABLE = [
("GP", 1, "SP"), ("CP", 100, "GP"), ("SP", 50, "EP"),
("PP", 1, "CP"), ("EP", 20, "PP")
]
EXPERIENCE_TABLE = [
(0, 1), (5, 1), (299, 1), (300, 2), (899, 2), (900, 3), (901, 3),
(2700, 4), (6500, 5), (14000, 6), (23000, 7), (34000, 8),
(48000, 9), (64000, 10), (85000, 11), (100000, 12), (120000, 13),
(140000, 14), (165000, 15), (195000, 16), (225000, 17), (265000, 18),
(305000, 19), (355000, 20), (355001, 20)
]
PROFICIENCY_TABLE = [
(0, 2), (5, 2), (299, 2), (300, 4), (899, 4), (900, 6), (901, 6),
(2700, 8), (6500, 11), (14000, 14), (23000, 17), (34000, 20),
(48000, 24), (64000, 28), (85000, 32), (100000, 36), (120000, 41),
(140000, 46), (165000, 51), (195000, 56), (225000, 62), (265000, 68),
(305000, 74), (355000, 80), (355001, 80)
]
@pytest.mark.parametrize("stat", STATS_TABLE)
def test_char_has_stats(stat):
bob = char_setup()
assert hasattr(bob, stat)
@pytest.mark.parametrize("num, mod", STATS_MODIFIER_TABLE)
def test_char_test_modifier(num, mod):
bob = char_setup()
bob.strength = num
assert bob.get_ability_modifier("strength") == mod
@pytest.mark.parametrize("stat, points", STATS_CHANGE_TABLE)
def test_change_stat(stat, points):
bob = char_setup()
bob.strength = 10
old = bob.strength
bob.change_stat(stat, points)
assert bob.strength == old + points
def test_cant_change_stat():
bob = char_setup()
bob.strength = 10
old = bob.strength
assert bob.change_stat(
"strength", -20) == "You can't decrease strength below 0\n(10 - 20 = -10)."
def test_has_money():
bob = char_setup()
assert type(bob.money) == dict
@pytest.mark.parametrize("money_type", MONEY_TYPES)
def test_has_money_types(money_type):
bob = char_setup()
assert money_type in bob.money.keys()
def test_show_money():
bob = char_setup()
print(bob.show_money())
assert type(bob.show_money()) == str
@pytest.mark.parametrize("money_type, amt", ADD_MONEY_TABLE)
def test_add_money(money_type, amt):
bob = char_setup()
old_amt = bob.money[money_type]
bob.add_money(money_type, amt)
assert bob.money[money_type] == old_amt + amt
@pytest.mark.parametrize("money_type, amt, money_dict", SPEND_MONEY_TABLE)
def test_spend_money(money_type, amt, money_dict):
bob = char_setup()
bob.spend_money(money_type, amt)
assert bob.money == money_dict
def test_cant_spend_money():
bob = char_setup()
assert bob.spend_money(
"GP", 200) == "You don't have enough money for this."
def test_not_enough_to_make_change():
bob = char_setup()
assert bob.exchange_money(
"GP", 200, "SP") == "You don't have enough GP for this exchange."
def test_cant_change_lt_1():
bob = char_setup()
assert bob.exchange_money(
"GP", 1, "PP") == "You don't have enough GP for this exchange."
@pytest.mark.parametrize("cash_out, amt, cash_in", EXCHANGE_TABLE)
def test_exchange_money(cash_out, amt, cash_in):
from copy import copy
bob = char_setup()
old = copy(bob.money)
bob.exchange_money(cash_out, amt, cash_in)
assert bob.money[cash_out] == old[cash_out] - amt
assert bob.money[cash_in] == old[cash_in] + \
EXCHANGE_RATES[cash_out][cash_in] * amt
def test_exchange_fractional():
from copy import copy
bob = char_setup()
old = copy(bob.money)
bob.exchange_money("GP", 22, "PP")
assert bob.money["GP"] == old["GP"] - 20
assert bob.money["PP"] == old["PP"] + 2
def test_add_experience():
bob = char_setup()
bob.gain_experience(100)
assert bob.experience == 100
@pytest.mark.parametrize("xp, level", EXPERIENCE_TABLE)
def test_levelups(xp, level):
bob = char_setup()
bob.gain_experience(xp)
assert bob.level == level
@pytest.mark.parametrize("xp, proficiency", PROFICIENCY_TABLE)
def test_proficiency_with_experience(xp, proficiency):
bob = char_setup()
bob.gain_experience(xp)
assert bob.proficiency == proficiency
@pytest.mark.parametrize("this_stat", STATS_TABLE)
def test_roll_random_stats(this_stat):
bob = char_setup()
assert getattr(bob, this_stat) > 0 and getattr(bob, this_stat) < 20
def test_display_health():
bob = char_setup()
assert bob.current_hp == bob.max_hp‰
out = bob.show_health()
assert "Current HP: {}/{}".format(bob.current_hp, bob.max_hp) in out
def test_take_damage():
bob = char_setup()
bob.take_damage(1)
assert bob.current_hp == bob.max_hp - 1
def test_take_critical_damage():
bob = char_setup()
bob.take_damage(10)
assert bob.current_hp == 0
def test_heal_damage():
bob = char_setup()
bob.current_hp = bob.max_hp = 6
bob.take_damage(3)
bob.heal_damage(2)
assert bob.current_hp == bob.max_hp - 1
def test_heal_more_than_max():
bob = char_setup()
bob.heal_damage(20)
assert bob.current_hp == bob.max_hp
def test_carry_capacity():
bob = char_setup()
assert bob.carry_capacity == bob.strength * 15
def test_carry_capacity_changes_on_strength_change():
"""TODO: write a test where the strength changes and on that change
the carry capacity changes."""
assert False
|
C#
|
UTF-8
| 19,599 | 2.953125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using ARMSim.Preferences;
using ARMSim.Simulator;
namespace ARMSim.GUI.Views
{
/// <summary>
/// This class manages the WatchView for the simulator user interface.
/// It manages a list of watch items that the user creates. Each watch item
/// is updated with its current value after the simulator stops executing instructions(updateView).
/// </summary>
public partial class WatchView : UserControl, IView, IViewXMLSettings
{
private List<WatchEntry> _loadedEntries;
private GraphicElements _graphicElements;
private Color _highlightColor;
/// <summary>
/// This enum defines the types of watch items that be loaded into the listview.
/// </summary>
public enum WatchType
{
Byte,
HalfWord,
Word,
Character,
String
}
/// <summary>
/// This class defines one entry in the watchview listview
/// The Value property is where the entry will evaluate itself
/// to the type requested and return a string representation of the value.
/// </summary>
private class WatchEntry
{
//private uint _address = 0;
//access to the items fields
public uint Address { get; set; }
private readonly string _label;
private readonly WatchView.WatchType _wt;
private readonly bool _signed;
private readonly bool _displayHex;
private ApplicationJimulator _JM;
/// <summary>
/// WatchEntry ctor
/// </summary>
/// <param name="label">the label name to be displayed</param>
/// <param name="wt">the type of watch item</param>
/// <param name="signed">true to display as a signed number</param>
/// <param name="displayHex">true to display in hexadecimal</param>
/// <param name="JM">a reference to the simulator</param>
public WatchEntry(string label, WatchView.WatchType wt, bool signed, bool displayHex, ApplicationJimulator JM)
{
_label = label;
_wt = wt;
_signed = signed;
_displayHex = displayHex;
_JM = JM;
}//WatchEntry ctor
public string Label { get { return _label; } }
public WatchView.WatchType WatchType { get { return _wt; } }
public bool Signed { get { return _signed; } }
public bool DisplayHex { get { return _displayHex; } }
/// <summary>
/// Property to evaluate itself and return a string representation.
/// </summary>
public override string ToString()
{
//evaluate based on its type
switch (_wt)
{
//item is a byte
case WatchView.WatchType.Byte:
{
//get byte from memory
uint data = _JM.GetMemoryNoSideEffect(this.Address, ARMPluginInterfaces.MemorySize.Byte);
//and convert to signed/unsigned, then to string
if (_signed)
return ((sbyte)data).ToString();
else
return _displayHex ? "0x" + ((byte)data).ToString("x2") : ((byte)data).ToString();
}
//item is a halfword(2 bytes)
case WatchView.WatchType.HalfWord:
{
uint data = _JM.GetMemoryNoSideEffect(this.Address, ARMPluginInterfaces.MemorySize.HalfWord);
//and convert to signed/unsigned, then to string
if (_signed)
return ((short)data).ToString();
else
return _displayHex ? "0x" + ((ushort)data).ToString("x4") : ((ushort)data).ToString();
}
//item is a word(4 bytes)
case WatchView.WatchType.Word:
{
uint data = _JM.GetMemoryNoSideEffect(this.Address, ARMPluginInterfaces.MemorySize.Word);
//and convert to signed/unsigned, then to string
if (_signed)
return ((int)data).ToString();
else
return _displayHex ? "0x" + data.ToString("x8") : data.ToString();
}
//item is a character
case WatchView.WatchType.Character:
{
uint data = _JM.GetMemoryNoSideEffect(this.Address, ARMPluginInterfaces.MemorySize.Byte);
//if the character is normal ascii, return it, otherwise indicate a dot(.)
char cdata = '.';
if (data >= 32 && data <= 127)
{
cdata = (char)data;
}
return "'" + cdata + "'";
}
//item is a string
case WatchView.WatchType.String:
{
//load string for simulator memory, no side effects
string str = Utils.loadStringFromMemory(_JM.GetMemoryNoSideEffect, this.Address, 64);
return "\"" + str + "\"";
}
default: return "";
}//switch
}//ToString
}//class WatchEntry
//public event ARMSimWindowManager.OnRecalLayout OnRecalLayout;
private ApplicationJimulator _JM;
private CodeLabelsDelegate _codeLabelsHandler;
private ResolveSymbolDelegate _resolveSymbolHandler;
/// <summary>
/// WatchView ctor.
/// </summary>
/// <param name="jm">A reference to the simulator</param>
/// <param name="codeLabelsHandler">a delegate to resolve codelabels to address</param>
/// <param name="resolveSymbolHandler">a delegate to resolve symbols to address</param>
public WatchView(ApplicationJimulator jm, CodeLabelsDelegate codeLabelsHandler, ResolveSymbolDelegate resolveSymbolHandler)
{
_JM = jm;
_codeLabelsHandler = codeLabelsHandler;
_resolveSymbolHandler = resolveSymbolHandler;
//create the watchentry list
_loadedEntries = new List<WatchEntry>();
this.Text = WatchView.ViewName;
InitializeComponent();
//setup the views graphic elements
_graphicElements = new GraphicElements(this);
//set view to default settings
this.defaultSettings();
}
/// <summary>
/// The font to use for the text in the watchentry list box
/// </summary>
public Font CurrentFont
{
get { return listView1.Font; }
set { listView1.Font = value; }
}
/// <summary>
/// The font color to use for the text in the watchentry list box
/// </summary>
public Color CurrentTextColour
{
get { return listView1.ForeColor; }
set { listView1.ForeColor = value; }
}
/// <summary>
/// The highlight color to use for the text in the watchentry list box
/// </summary>
public Color CurrentHighlightColour
{
get { return this._highlightColor; }
set { this._highlightColor = value; }
}
/// <summary>
/// The background color to use for the text in the watchentry list box
/// </summary>
public Color CurrentBackgroundColour
{
get { return listView1.BackColor; }
set { listView1.BackColor = value; }
}
/// <summary>
/// Return a reference to the watchview control
/// </summary>
public Control ViewControl { get { return this; } }
/// <summary>
/// This is called when the view is reset. This can happen when the user restarts a program
/// or the program is loaded for the first time.
/// Check if the entries to load array is > 0, if so, then this array was
/// loaded from the xml document.
/// Simply create the watch entries in the listview from this array. If the symbol
/// cannot be resolved, then it may be for another program, so ignore it.
/// </summary>
public void resetView()
{
if (_loadedEntries.Count > 0)
{
listView1.Items.Clear();
foreach (WatchEntry we in _loadedEntries)
{
uint address = 0;
if (_resolveSymbolHandler(we.Label, ref address))
{
we.Address = address;
ListViewItem lvi = new ListViewItem(new string[2] { we.Label, we.ToString() });
lvi.Tag = we;
listView1.Items.Add(lvi);
}
}
_loadedEntries.Clear();
return;
}
//else if the entries to load is zero, then this is possibly a new program loaded.
//we must scan the listview and make sure the watch items are still valid. If not, remove
//it, otherwise recompute the labels address. (It may have changed)
foreach (ListViewItem lvi in listView1.Items)
{
uint address = 0;
if (_resolveSymbolHandler((lvi.Tag as WatchEntry).Label, ref address))
{
(lvi.Tag as WatchEntry).Address = address;
}
else
{
listView1.Items.Remove(lvi);
}
}//foreach
}//resetView
/// <summary>
/// This is called when the view needs to be updated. When the simulator hits a breakpoint or
/// the program terminates are examples.
/// Evaluate all the watch entries and update their values in the listview.
/// </summary>
public void updateView()
{
if (_JM == null || !_JM.ValidLoadedProgram) return;
foreach (ListViewItem lvi in listView1.Items)
{
WatchEntry we = (lvi.Tag as WatchEntry);
lvi.SubItems[1].Text = we.ToString();
}
}//updateView
/// <summary>
/// Returns the string name of this view.
/// </summary>
public static string ViewName { get { return "WatchView"; } }
/// <summary>
/// Returns the index of the watch entry currently selected in the listview.
/// Returns -1 if none selected
/// </summary>
public int SelectedWatchItem
{
get
{
ListView.SelectedIndexCollection indexes = this.listView1.SelectedIndices;
return (indexes.Count == 1) ? indexes[0] : -1;
}
}//SelectedWatchItem
/// <summary>
/// Removes any watch entries that are selected
/// </summary>
public void DeleteCurrentWatchItem()
{
int selectedWatchItem = this.SelectedWatchItem;
if (selectedWatchItem >= 0)
{
this.listView1.Items.RemoveAt(selectedWatchItem);
}
}//DeleteCurrentWatchItem
/// <summary>
/// Removes all watch entries from the listview
/// </summary>
public void ClearAllWatchItems()
{
_loadedEntries.Clear();
this.listView1.Items.Clear();
}//ClearAllWatchItems
public void stepStart() { }
public void stepEnd() { }
/// <summary>
/// Adds a watch item to the listview. Displays a dialog allowing the user to
/// specify the watchentry to create.
/// </summary>
public void AddWatchItem()
{
//create an instance of the add watch dialog
AddWatch aw = new AddWatch();
//set the code label resolver delegate
aw.CodeLabels = _codeLabelsHandler();
//show the dialog. If OK was pressed, then add watch entry
if (aw.ShowDialog(this) == DialogResult.OK)
{
string lab = aw.Label;
if (!string.IsNullOrEmpty(lab))
{
//resolve the label name to an address in memory. If we cannot resolve it, just exit
uint address = 0;
if (_resolveSymbolHandler(lab, ref address))
{
//create a new watch entry and set the resolved address
WatchEntry we = new WatchEntry(lab, aw.WatchType, aw.Signed, aw.DisplayHex, _JM);
we.Address = address;
//add watch entry to listview
ListViewItem lvi = new ListViewItem(new string[2] { we.Label, we.ToString() });
lvi.Tag = we;
listView1.Items.Add(lvi);
}
}
}
}//AddWatchItem
/// <summary>
/// Setup view settings to default values
/// </summary>
public void defaultSettings()
{
_highlightColor = Color.LightBlue;
}//defaultSettings
/// <summary>
/// Given a screen coordinate, determine the watch entry at that point.
/// </summary>
/// <param name="pt"></param>
/// <returns></returns>
private ListViewItem ItemFromPoint(Point pt)
{
return (listView1.HitTest(listView1.PointToClient(pt))).Item;
}//ItemFromPoint
/// <summary>
/// Add a watchItem. Invoked from the view context menu.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItem_AddWatchItem(object sender, System.EventArgs e)
{
this.AddWatchItem();
}
/// <summary>
/// Remove a watchItem. Invoked from the view context menu.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void menuItem_RemoveItem(object sender, System.EventArgs e)
{
DeleteCurrentWatchItem();
}
/// <summary>
/// Called when a context menu is being created for the listview.
/// Add some entries to manipulate the listview.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
//get the menu and clear it out
ContextMenuStrip cms = (ContextMenuStrip)sender;
cms.Items.Clear();
//add the 2 items for adding and removing items
ToolStripMenuItem addItem = new ToolStripMenuItem("&Add Watch", null, this.menuItem_AddWatchItem);
ToolStripMenuItem removeItem = new ToolStripMenuItem("&Remove Watch", null, this.menuItem_RemoveItem);
//assume both are not valid for now
addItem.Enabled = false;
removeItem.Enabled = false;
//the simulator engine must be valid
if (_JM.ValidLoadedProgram)
{
//so adding is valid now
addItem.Enabled = true;
//cjeck if the mouse was over a watchentry. If so, enable the remove command.
if (ItemFromPoint(Control.MousePosition) != null)
{
removeItem.Enabled = true;
}
}
//add to menu
cms.Items.Add(addItem);
cms.Items.Add(removeItem);
//popup context menu
_graphicElements.Popup(cms, true);
}//contextMenuStrip1_Opening
/// <summary>
/// Called when a keypress is detected in the listview.
/// Check if it is the delete key and remove the current watch entry if it is.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete || e.KeyCode == Keys.Back)
DeleteCurrentWatchItem();
}
/// <summary>
/// Called when the view is loading. Load any settings saved in the xml document.
/// </summary>
/// <param name="xmlIn"></param>
public void LoadFromXML(XmlReader xmlIn)
{
try
{
xmlIn.MoveToContent();
_graphicElements.loadFromXML(xmlIn);
xmlIn.Read();
do
{
if (xmlIn.NodeType == XmlNodeType.EndElement) break;
if (xmlIn.NodeType == XmlNodeType.Element && xmlIn.Name == "WatchItem")
{
string label = xmlIn.GetAttribute("Label");
WatchType wt = (WatchType)Enum.Parse(typeof(WatchType), xmlIn.GetAttribute("WatchType"), true);
bool signed = bool.Parse(xmlIn.GetAttribute("Signed"));
bool displayHex = bool.Parse(xmlIn.GetAttribute("DisplayHex"));
_loadedEntries.Add(new WatchEntry(label, wt, signed, displayHex, _JM));
}
xmlIn.Skip();
} while (!xmlIn.EOF);
}
catch (Exception ex)
{
ARMPluginInterfaces.Utils.OutputDebugString(ex.Message);
this.defaultSettings();
}
}//LoadFromXML
/// <summary>
/// Called when the application is shutting down. Save all the view settings
/// to the xml document.
/// </summary>
/// <param name="xmlOut"></param>
public void saveState(XmlWriter xmlOut)
{
xmlOut.WriteStartElement(WatchView.ViewName);
//_graphicElements.savetoXML(xmlOut);
foreach (ListViewItem lvi in listView1.Items)
{
WatchEntry we = (lvi.Tag as WatchEntry);
xmlOut.WriteStartElement("WatchItem");
xmlOut.WriteAttributeString("Label", we.Label);
xmlOut.WriteAttributeString("WatchType", Enum.GetName(typeof(WatchType), we.WatchType));
xmlOut.WriteAttributeString("Signed", we.Signed.ToString());
xmlOut.WriteAttributeString("DisplayHex", we.DisplayHex.ToString());
xmlOut.WriteEndElement();
}//foreach
_graphicElements.SaveToXML(xmlOut);
xmlOut.WriteEndElement();
}
public void TerminateInput() { }
}//class WatchView
}
|
Java
|
UTF-8
| 3,212 | 2.234375 | 2 |
[] |
no_license
|
package com.example.george.ommfcm;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import com.google.android.gms.plus.People;
import java.util.ArrayList;
import java.util.List;
/**
* Created by George on 10/17/15.
*/
public class AdaptadorEstado extends ArrayAdapter<Estado> {
Context context;
int resource, textViewResourceId;
List<Estado> listaEstados, listaTemporal, listaSugerencias;
public AdaptadorEstado(Context context, int resource, int textViewResourceId, List<Estado> listaEstados){
super(context, resource,textViewResourceId, listaEstados);
this.context = context;
this.resource = resource;
this.textViewResourceId = textViewResourceId;
this.listaEstados = listaEstados;
listaTemporal = new ArrayList<Estado>(listaEstados);
listaSugerencias = new ArrayList<Estado>();
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.fila_resultado_estado, parent, false);
}
Estado estado = listaEstados.get(position);
if(estado != null){
TextView nombre = (TextView) view.findViewById(R.id.nombre_estado);
if(nombre != null){
nombre.setText(estado.getNombre());
}
}
return view;
}
@Override
public Filter getFilter(){
return filtroNombres;
}
Filter filtroNombres = new Filter() {
@Override
public CharSequence convertResultToString(Object resultValue) {
String str = ((Estado) resultValue).getNombre();
return str;
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
listaSugerencias.clear();
for (Estado estado : listaTemporal) {
if (estado.getNombre().toLowerCase().contains(constraint.toString().toLowerCase())) {
listaSugerencias.add(estado);
}
}
FilterResults resultados_filtro = new FilterResults();
resultados_filtro.values = listaSugerencias;
resultados_filtro.count = listaSugerencias.size();
return resultados_filtro;
} else {
return new FilterResults();
}
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
List<Estado> filterList = (ArrayList<Estado>) results.values;
if (results != null && results.count > 0) {
clear();
for (Estado estado : filterList) {
add(estado);
notifyDataSetChanged();
}
}
}
};
}
|
PHP
|
UTF-8
| 3,507 | 2.78125 | 3 |
[] |
no_license
|
<?php
class excelWorkbook {
private $Worksheets ;
private $Styles ;
function __construct() {
$this->Worksheets = array() ;
$this->Styles = array() ;
}
function __destruct() {
}
function __set($property, $value) {
$this->$property = $value;
}
function __get($property) {
if (isset($this->$property)) {
return $this->$property;
}
}
public function addWorksheet($ws) {
$this->Worksheets[] = $ws ;
}
public function getXml() {
$count = 0 ;
$s = "" ;
$s .= $this->createWorkbook() ;
$s .= $this->createStyle() ;
foreach ($this->Worksheets as $ws) {
if ($ws->SheetName == "") {
$ws->SheetName = 'Sheet' . $count;
$count++;
}
$s .= $ws->getXml() ;
}
$s .= $this->closeWorkbook() ;
return $s ;
}
public function downloadFile($filename) {
$xml = $this->getXml() ;
header("Cache-Control: public, must-revalidate");
header("Pragma: no-cache");
header("Content-Length: " . strlen($xml) );
header("Content-Type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
echo $xml;
}
private function createWorkbook() {
$s = "" ;
$s .= '<?xml version="1.0"?>' . "\n" ;
$s .= '<?mso-application progid="Excel.Sheet"?>' . "\n";
$s .= '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" ' . "\n";
$s .= ' xmlns:o="urn:schemas-microsoft-com:office:office" ' . "\n";
$s .= ' xmlns:x="urn:schemas-microsoft-com:office:excel" ' . "\n";
$s .= ' xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" ' . "\n";
$s .= ' xmlns:html="http://www.w3.org/TR/REC-html40">' . "\n" ; //to allow html tag in xml
$s .= ' <DocumentProperties>' . "\n";
$s .= ' <o:Author></o:Author>' . "\n";
$s .= ' </DocumentProperties>' . "\n";
$s .= ' <x:ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">' . "\n";
//sb.Append(" <x:WindowHeight>9120</x:WindowHeight>" + Environment.NewLine);
//sb.Append(" <x:WindowWidth>10005</x:WindowWidth>" + Environment.NewLine);
//sb.Append(" <x:WindowTopX>120</x:WindowTopX>" + Environment.NewLine);
//sb.Append(" <x:WindowTopY>135</x:WindowTopY>" + Environment.NewLine);
//sb.Append(" <x:ActiveSheet>0</x:ActiveSheet>") ; //first visible sheet when workbook opened.
//sb.Append(" <x:SelectedSheets>1</x:SelectedSheets>"); //how many sheet can be selected at one time.
$s .= ' <x:ProtectStructure>False</x:ProtectStructure>' . "\n";
$s .= ' <x:ProtectWindows>False</x:ProtectWindows>' . "\n";
$s .= ' </x:ExcelWorkbook>' . "\n";
return $s ;
}
private function closeWorkbook() {
return '</Workbook>';
}
private function CreateStyle() {
$s = "" ;
$spc = " ";
$s .= $spc . '<Styles>' . "\n";
$s .= excelStyle::getDefaultStyle($spc . " ");
//if (!is_null($this->Styles) && count($this->Styles) > 0) {
//foreach ($this->Styles as $style) {
//$s .= excelStyle::getStyleXml($style,$spc . " ");
//}
//}
$s .= $spc . '</Styles>' . "\n";
return $s ;
}
}
?>
|
Ruby
|
UTF-8
| 155 | 3.109375 | 3 |
[] |
no_license
|
class Note
def create
print "Enter your tag:"
tag = gets.chomp()
print "Enter your note:"
note = gets.chomp()
[tag,note]
end
end
|
Java
|
UTF-8
| 2,816 | 3.15625 | 3 |
[] |
no_license
|
package br.com.exer2;
import java.util.Scanner;
/**
* Created by BRUNO on 06/09/2017.
*/
public class Comida {
private double tottal;
public static enum Bebidas {
PEPSI("Pepsi", 4.0), SUCO("suco", 3.0), AGUA("agua", 3.5);
private String nome;
private double preco;
public double getPreco() {
return preco;
}
public String getNome() {
return nome;
}
Bebidas(String nome, double preco) {
this.preco = preco;
this.nome = nome;
}
}
public static enum Comidas {
SANDUICHE("Sanduiche", 4.0), HOTDOG("HotDog", 3.0), XBURGER("X-Burger", 3.5);
private double preco;
private String nome;
public double getPreco() {
return preco;
}
public String getNome() {
return nome;
}
Comidas(String nome, double preco) {
this.preco = preco;
this.nome = nome;
}
}
public static void menu() {
System.out.println("\tBebidas ");
System.out.println("1. " + Bebidas.PEPSI.getNome() + " R$ " + Bebidas.PEPSI.getPreco());
System.out.println("2. " + Bebidas.SUCO.getNome() + " R$ " + Bebidas.SUCO.getPreco());
System.out.println("3. " + Bebidas.AGUA.getNome() + " R$ " + Bebidas.AGUA.getPreco());
System.out.println("\tComidas ");
System.out.println("4. " + Comidas.SANDUICHE.getNome() + " R$ " + Comidas.SANDUICHE.getPreco());
System.out.println("5. " + Comidas.HOTDOG.getNome() + " R$ " + Comidas.HOTDOG.getPreco());
System.out.println("6. " + Comidas.XBURGER.getNome() + " R$ " + Comidas.XBURGER.getPreco());
System.out.println("0. Sair ");
System.out.println("Escolha sua opção: ");
}
public static double preco(int opcao) {
switch (opcao) {
case 1:
return Bebidas.PEPSI.getPreco();
case 2:
return Bebidas.SUCO.getPreco();
case 3:
return Bebidas.AGUA.getPreco();
case 4:
return Comidas.SANDUICHE.getPreco();
case 5:
return Comidas.HOTDOG.getPreco();
case 6:
return Comidas.XBURGER.getPreco();
default:
return 0.0;
}
}
public static void main(String[] args) {
double tottal = 0.0;
int opcao = 0;
Scanner entrada = new Scanner(System.in);
do {
menu();
opcao = entrada.nextInt();
tottal += preco(opcao);
System.out.println("Opçao escolhida: " + opcao);
System.out.println("Valor a pagar: " + tottal + "\n");
} while (opcao != 0);
}
}
|
Java
|
UTF-8
| 1,839 | 2.203125 | 2 |
[] |
no_license
|
/**
*
*/
package com.lti.action.mutualfund;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.lti.action.Action;
import com.lti.system.ContextHolder;
import com.opensymphony.xwork2.ActionSupport;
import com.lti.service.SecurityManager;
import com.lti.service.bo.Security;
import com.lti.type.TimeUnit;
import com.lti.util.LTIDate;
/**
* @author Administrator
*
*/
public class SetDefaultDateAction extends ActionSupport implements Action {
private static final long serialVersionUID = 1L;
private String symbol;
private String resultString;
private Integer interval;
public String execute(){
SecurityManager securityManager=(SecurityManager)ContextHolder.getInstance().getApplicationContext().getBean("securityManager");
Security se = securityManager.get(symbol);
Date eDate = se.getEndDate();
Date sDate = LTIDate.getLastYear(eDate);
Date earliestDate = se.getStartDate();
resultString="";
if(earliestDate==null)
return Action.ERROR;
earliestDate = LTIDate.getNewNYSETradingDay(earliestDate,interval+2);
if(sDate.before(earliestDate))
sDate = earliestDate;
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String startDate = sdf.format(sDate);
String endDate = sdf.format(eDate);
resultString=startDate +"#" + endDate;
return Action.SUCCESS;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public String getResultString() {
return resultString;
}
public void setResultString(String resultString) {
this.resultString = resultString;
}
public Integer getInterval() {
return interval;
}
public void setInterval(Integer interval) {
this.interval = interval;
}
}
|
C
|
UTF-8
| 2,740 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
/**
* registry.c
*
* Simple program for exploring the wayland registry.
* I have not been able to find documentation on what interfaces will
* consistently be in the registry, and if they have consistent names (ids).
*
* Copyright 2019 by Joshua Gutow
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stddef.h>
#include <stdio.h>
#include <wayland-client-core.h>
#include <wayland-client-protocol.h>
static void registry_handle_global(void *data, struct wl_registry *registry,
uint32_t name, const char *interface,
uint32_t version)
{
if(data != NULL)
puts("DATA IS NOT NULL");
printf("interface: %s\nname: %d\nversion: %d\n\n",
interface, name, version);
}
static void registry_handle_global_remove(void *data,
struct wl_registry *registry,
uint32_t name)
{
if(data != NULL)
puts("DATA IS NOT NULL");
printf("%d has been removed\n", name);
}
/**
* Wrapper around registry add and remove function pointers.
*/
static const struct wl_registry_listener registry_listener = {
.global = ®istry_handle_global,
.global_remove = ®istry_handle_global_remove,
};
int main()
{
// Grab the default display
struct wl_display *display = wl_display_connect(NULL);
// Get the global registry for that display
struct wl_registry *registry = wl_display_get_registry(display);
// Add our listeners
wl_registry_add_listener(registry, ®istry_listener, NULL);
// Starts processing incoming events on the listeners
wl_display_dispatch(display);
// Disconnect and clean up
wl_display_disconnect(display);
return 0;
}
|
Python
|
UTF-8
| 934 | 2.6875 | 3 |
[] |
no_license
|
from flask import request
from flask_api import FlaskAPI, status, exceptions
import json
from modules import MicroController as mc
app = FlaskAPI(__name__)
@app.route("/state", methods=['GET'])
def get():
"""
GET : returns the item state with 2** status code
4**, 5** accordingly if MicroController is not avaliable
"""
return json.dumps(mc.getState())
@app.route("/update/<int:state>/", methods=['POST'])
def post(state):
"""
POST : tells the client what to do ie. close/open the blind
returns status codes 2**, 4**, 5** accordingly
"""
if(mc.updateState(state)):
return '200: The request has succeeded.', status.HTTP_200_OK
return '500: The server encountered an unexpected condition which prevented it from fulfilling the request.', status.HTTP_500_INTERNAL_SERVER_ERROR
if __name__ == "__main__":
app.run(host='192.168.1.119', port=1234, debug=True)
|
Markdown
|
UTF-8
| 1,617 | 3.65625 | 4 |
[] |
no_license
|
**Iteratiu**
* Tenemos un bucle dentro de un bucle, el primero mira si el numero es mayor que 9, el segundo suma todos los digitos
```
while aux:
sumatori += aux % 10
aux //= 10
```
* El Coste de este bucle interno es, en resumen, el numero de digitos de aux ( Mas constantes)
* Como podemos asumir el coste de este bucle casi como una constante en si mismo, lo interesante viene en el bucle externo:
```
while num > 9:
aux = num
sumatori = 0
Coste Bucle Interno
num = sumatori
```
* Como Tenemos solo asignaciones, podemos obviarlas por ahora, por lo que nos quedaria:
```
Coste (while num > 9:)
Coste Bucle Interno
```
* Dependemos entonces, del numero de cifras, y su valor, el mejor caso Posible se ve entonces muy rapido:
$ \theta $ = 1 * Coste Bucle Interno
* En el peor caso posible, es para n con varios digitos y todos ellos 9's
n= 9999999.....
99-18-9
999-27-9
9999-36-9
999999999-81-9
9999999999-90-9
(log_Base10(N) + 2 ) * Coste Bucle Interno
Complejidad = log_base10(n)
**Recursivo**
```
def suma_recursiva(value):
"""Suma recursiva de digits """
aux = int(value)
if aux <= 9:
return aux
ultimo_digito = aux % 10
resto = aux // 10
return ultimo_digito + suma_recursiva(resto)
def decrypt_recursive(value):
"""Decrypt recursio """
aux = suma_recursiva(value)
if aux <= 9:
return aux
return decrypt_recursive(aux)
```
Mejor Caso - Coste C' (constante, entrando en el if)
Peor Caso - Igual que en recursivo??? Varios 99999..
log Base10(N)?
|
TypeScript
|
UTF-8
| 9,920 | 2.765625 | 3 |
[] |
no_license
|
/**
*
* Elijah Cobb
* elijah@elijahcobb.com
* https://elijahcobb.com
*
*
* Copyright 2019 Elijah Cobb
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
import { ECTReport } from "./ECTReport";
import { ECTItem } from "./ECTItem";
import { ECTOutput } from "./ECTOutput";
import { ECTInput } from "./ECTInput";
import { ECErrorStack, ECErrorOriginType, ECErrorType } from "@elijahjcobb/error";
import ECConsole from "@elijahjcobb/console";
/**
* A class to validate an object with a structure.
*/
export class ECTValidator {
private readonly types: ECTInput;
/**
* Create a new ECTValidator instance.
* @param {ECTInput} types The structure that is accepted.
*/
public constructor(types: ECTInput) {
this.types = types;
}
/**
* Inspect the object provided against the structure of the validator.
* @param {object} object The object to be inspected.
* @return {ECTOutput} An ECTOutput.
*/
public inspect(object: object): ECTOutput {
let typesKeys: string[] = Object.keys(this.types);
let res: ECTOutput = {};
for (let i: number = 0; i < typesKeys.length; i ++) {
let key: string = typesKeys[i];
let expectedValueType: ECTItem = this.types[key];
let actualValue: any = object[key];
let actualValueType: string = typeof actualValue;
let isOptional: boolean = expectedValueType.optional;
if (actualValueType === "object" && Array.isArray(actualValue)) actualValueType = "array";
if (actualValueType === "array" && actualValue === undefined) actualValueType = "undefined";
if (actualValueType === "object" && actualValue === undefined) actualValueType = "undefined";
if (isOptional && (actualValue === undefined || actualValue === null)) continue;
if (expectedValueType.type === "any" && actualValue !== undefined && actualValue !== null) continue;
if (actualValueType === "array") {
if (expectedValueType.type === "object") {
res[key] = {
expected: expectedValueType.type,
data: "{}",
index: 0,
actual: "object",
passed: false
};
continue;
}
let array: any[] = actualValue as any[];
let allowedTypes: string[] = expectedValueType.subtypes as string[];
for (let j: number = 0; j < array.length; j++) {
let item: any = array[j];
let itemType: string = typeof item;
if (allowedTypes.indexOf(itemType) === -1 && allowedTypes.indexOf("any") === -1) {
res[key] = {
expected: expectedValueType.type + "<" + (expectedValueType.subtypes as string[]).join(" | ") + ">",
data: item,
index: j,
actual: actualValueType + "<" + itemType + ">",
passed: false
};
break;
} else {
res[key] = {
expected: expectedValueType.type + "<" + (expectedValueType.subtypes as string[]).join(" | ") + ">",
data: itemType,
actual: actualValueType + "<" + itemType + ">",
passed: true
};
}
}
}
else if (actualValueType === "object") {
if (expectedValueType.type === "array") {
res[key] = {
expected: expectedValueType.type,
data: "[]",
index: 0,
actual: "array",
passed: false
};
continue;
}
let subRes: ECTOutput = {};
let passCount: number = 0;
let expectedSubValues: ECTInput = (expectedValueType.subtypes as ECTInput);
let expectedSubValueKeys: string[] = Object.keys(expectedSubValues);
if (expectedSubValueKeys[0] === "*") {
let expectedSubValue: ECTItem = expectedSubValues["*"];
let realSubValueKeys: string[] = Object.keys(actualValue);
for (let k: number = 0; k < realSubValueKeys.length; k++) {
let realSubValueKey: string = realSubValueKeys[k];
let realSubValue: any = actualValue[realSubValueKey];
let realSubValueType: string = typeof realSubValue;
if (realSubValueType !== expectedSubValue.type) {
subRes[realSubValueKey] = {
expected: expectedSubValue.type,
data: realSubValue,
actual: realSubValueType,
passed: false
};
break;
}
}
} else {
for (let j: number = 0; j < expectedSubValueKeys.length; j++) {
let expectedSubValueKey: string = expectedSubValueKeys[j];
let expectedSubValue: ECTItem = expectedSubValues[expectedSubValueKey];
let realSubValue: any = actualValue[expectedSubValueKey];
let realSubValueType: string = typeof realSubValue;
if (expectedSubValue.optional && (realSubValue === undefined || realSubValue === null)) continue;
let expectedSubValueType: string = expectedSubValue.type;
let passed: boolean = expectedSubValueType === realSubValueType && realSubValue !== null && realSubValue !== undefined;
subRes[expectedSubValueKey] = {
expected: expectedSubValueType,
data: realSubValue,
actual: realSubValueType,
passed
};
if (passed) passCount ++;
}
}
res[key] = {
passed: passCount >= expectedSubValueKeys.length,
children: subRes
};
// for (let j: number = 0; j < objectKeys.length; j++) {
//
// let subKey: string = objectKeys[j];
// let subValue: any = actualValue[subKey];
// let subValueType: string = typeof subValue;
// let expectedSubValue: ECTItem = (expectedValueType.subtypes as ECTInput)[subKey];
// if (!expectedSubValue) expectedSubValue = (expectedValueType.subtypes as ECTInput)["*"];
// if (expectedSubValue.optional && (subValue === undefined || subValue === null)) continue;
// let expectedSubValueType: string = expectedSubValue.type;
// if (expectedSubValueType === "*" && subValue !== undefined && subValue !== null) continue;
//
//
// let passed: boolean = expectedSubValueType === subValueType && subValue !== null && subValue !== undefined;
//
// subRes[subKey] = {
// expected: expectedSubValueType,
// data: subValue,
// actual: subValueType,
// passed
// };
//
// if (passed) passCount ++;
//
// }
//
// res[key] = {
// passed: passCount >= objectKeys.length,
// children: subRes
// };
} else {
res[key] = {
expected: expectedValueType.type,
data: actualValue,
actual: actualValueType,
passed: expectedValueType.type === actualValueType && actualValue !== null && actualValue !== undefined
};
}
}
return res;
}
/**
* Get only the properties that failed inspection.
* @param {object} object The object to inspect.
* @return {ECTOutput} An ECTOutput.
*/
public getFailures(object: object): ECTOutput {
let allData: object = this.inspect(object);
let allDataKeys: string[] = Object.keys(allData);
let failures: ECTOutput = {};
for (let i: number = 0; i < allDataKeys.length; i++) {
let key: string = allDataKeys[i];
let value: ECTReport = allData[key];
if (value["passed"] === false) failures[key] = value;
}
return failures;
}
/**
* Check if a object fails inspection.
* @param {object} object An object to inspect.
* @return {boolean} Whether it fails.
*/
public doesFail(object: object): boolean {
return Object.keys(this.getFailures(object)).length > 0;
}
/**
* Pretty print the inspection of an object using @elijahjcobb/console package.
* @param {object} object The object to print the inspection of.
*/
public print(object: object): void {
ECConsole(this.inspect(object));
}
/**
* Verify the object and throw an ECErrorStack instance if it is incorrect.
* @param {object} object An object to inspect.
*/
public verify(object: object): void {
let fails: ECTOutput = this.getFailures(object);
let errorMessage: string[] = [];
let failingKeys: string[] = Object.keys(fails);
failingKeys.forEach((key: string) => {
let failingValue: ECTReport | {
passed: boolean;
children: ECTOutput;
} = fails[key];
if (failingValue["children"]) {
let value: {
passed: boolean;
children: ECTOutput;
} = failingValue as {
passed: boolean;
children: ECTOutput;
};
let childrenKeys: string[] = Object.keys(value.children);
childrenKeys.forEach((childKey: string) => {
let childValue: ECTReport = value.children[childKey] as ECTReport;
if (!childValue.passed) errorMessage.push(`Value '${childValue.data}' for key '${childKey}' in object '${key}' is incorrect type (expected: '${childValue.expected}' actual: '${childValue.actual}').`);
});
} else {
let value: ECTReport = failingValue as ECTReport;
errorMessage.push(`Value '${value.data}' for key '${key}' is incorrect type (expected: '${value.expected}' actual: '${value.actual}').`);
}
});
if (errorMessage.length > 0) throw ECErrorStack.newWithMessageAndType(ECErrorOriginType.FrontEnd, ECErrorType.ParameterIncorrectFormat, new Error(errorMessage.join(" ")));
}
}
|
Ruby
|
UTF-8
| 559 | 2.625 | 3 |
[] |
no_license
|
# frozen_string_literal: true
require 'httparty'
module Formulary
# This class reads QHP data from a list of urls and loads it into a repository
class QHPImporter
attr_reader :urls, :repo
def initialize(urls, repo)
@urls = urls
@repo = repo
end
def import
urls.each do |url|
qhp_raw_data = HTTParty.get(url, verify: false) # FIXME
qhp_json.concat(JSON.parse(qhp_raw_data, symbolize_names: true))
end
repo.import(qhp_json)
end
def qhp_json
@qhp_json ||= []
end
end
end
|
C#
|
UTF-8
| 1,059 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
public class ViewExistingStudentsScenario
{
public ViewExistingStudentsScenario()
{
_fixture = new DatabaseFixture();
_controller = new StudentController(new StudentRepository(_fixture.Context));
}
public void GivenExistingStudents()
{
var expectedStudents = new List<Student>
{
new Student("Joe", "Bloggs"),
new Student("Jane", "Smith")
};
_existingStudents = _fixture.SeedContext.Save(expectedStudents);
}
public void WhenUserViewsStudents()
{
_actionResult = _controller.Index();
}
public void ThenUserShouldSeeStudentsOrderedByName()
{
List<StudentViewModel> viewModel;
_actionResult.ShouldRenderDefaultView()
.WithModel<List<StudentViewModel>>(vm => viewModel = vm);
viewModel.Select(s => s.Name).ShouldBe(
_existingStudents.OrderBy(s => s.FullName).Select(s => s.FullName))
}
[Test]
public void ExecuteScenario()
{
this.Bddfy();
}
private List<Student> _existingStudents;
private ActionResult _actionResult;
private DatabaseFixture _fixture;
}
|
Java
|
UTF-8
| 4,724 | 1.976563 | 2 |
[] |
no_license
|
package allinter.lowvision;
import allinter.BrowserTab;
import allinter.LowVisionOptions;
import org.eclipse.actf.model.ui.ImagePositionInfo;
import org.eclipse.actf.model.ui.editor.browser.ICurrentStyles;
import org.eclipse.actf.visualization.engines.lowvision.LowVisionException;
import org.eclipse.actf.visualization.engines.lowvision.LowVisionType;
import org.eclipse.actf.visualization.engines.lowvision.PageEvaluation;
import org.eclipse.actf.visualization.engines.lowvision.image.IPageImage;
import org.eclipse.actf.visualization.engines.lowvision.image.ImageException;
import org.eclipse.actf.visualization.eval.problem.IProblemItem;
import org.eclipse.actf.visualization.lowvision.util.LowVisionUtil;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.eclipse.actf.visualization.engines.lowvision.image.PageImageFactory.createSimulationPageImage;
public class Checker {
private final BrowserTab browser;
private final String address;
private final LowVisionType lowVisionType;
private IPageImage[] framePageImage;
private ImagePositionInfo[][] imageInfoInHtmlArray;
private ArrayList<Map<String, ICurrentStyles>> styleInfoArray;
private List<IProblemItem> lowvisionProblemList;
public Checker(final BrowserTab browser, final String address, final LowVisionType lowVisionType) {
this.browser = browser;
this.address = address;
this.framePageImage = new IPageImage[1];
this.imageInfoInHtmlArray = new ImagePositionInfo[1][];
this.styleInfoArray = new ArrayList<>(1);
this.styleInfoArray.add(Collections.emptyMap());
this.lowVisionType = lowVisionType;
}
public static Checker validate(final BrowserTab browser, final String url, final LowVisionOptions lowVisionOptions) throws LowVisionException, IOException {
if (! lowVisionOptions.isLowvision()) {
return null;
}
allinter.lowvision.Checker checker = new allinter.lowvision.Checker(browser, url, createLowVisionType(lowVisionOptions));
checker.run();
return checker;
}
private static LowVisionType createLowVisionType(final LowVisionOptions lowVisionOptions) throws LowVisionException {
LowVisionType lowVisionType = new LowVisionType();
if (lowVisionOptions.isLowvisionEyesight()) {
lowVisionType.setEyesight(lowVisionOptions.isLowvisionEyesight());
lowVisionType.setEyesightDegree(lowVisionOptions.getLowvisionEyesightDegree());
}
if (lowVisionOptions.isLowvisionCVD()) {
lowVisionType.setCVD(lowVisionOptions.isLowvisionCVD());
lowVisionType.setCVDType(lowVisionOptions.getLowvisionCVDType());
}
if (lowVisionOptions.isLowvisionColorFilter()) {
lowVisionType.setColorFilter(lowVisionOptions.isLowvisionColorFilter());
lowVisionType.setColorFilterDegree(lowVisionOptions.getLowvisionColorFilterDegree());
}
return lowVisionType;
}
public List<IProblemItem> getProblemList() {
return this.lowvisionProblemList;
}
public BufferedImage getSourceImage() {
return framePageImage[0].getBufferedImage();
}
public BufferedImage getLowvisionImage() throws ImageException {
IPageImage resultImage = createSimulationPageImage(framePageImage[0], this.lowVisionType);
return resultImage.getBufferedImage();
}
public void run() throws IOException {
final byte[] screenshot = browser.takeScreenshot();
final int frameId = 0;
final int lastFrame = 0;
framePageImage[frameId] = PageImageFactory.loadFromPng(screenshot);
imageInfoInHtmlArray[frameId] = browser.getAllImagePosition();
styleInfoArray.set(frameId, browser.getStyleInfo().getCurrentStyles());
if (lastFrame > 1) { // TODO frameURL.length?
imageInfoInHtmlArray[frameId] = LowVisionUtil
.trimInfoImageInHtml(imageInfoInHtmlArray[frameId],
framePageImage[frameId].getHeight());
styleInfoArray.set(frameId, LowVisionUtil
.trimStyleInfoArray(styleInfoArray.get(frameId),
framePageImage[frameId].getHeight()));
}
PageEvaluation targetPage = new PageEvaluation(framePageImage[frameId]);
targetPage.setInteriorImagePosition(imageInfoInHtmlArray[frameId]);
targetPage.setCurrentStyles(styleInfoArray.get(frameId));
lowvisionProblemList = targetPage.check(lowVisionType, address, frameId);
}
}
|
Markdown
|
UTF-8
| 795 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
# Project-1

## Description
this is a node based project to generate reademe
## Table of Contents
* [Installation](#Installation)
* [Usage](#Usage)
* [License](#License)
* [Contributing](#Contributing)
* [Tests](#Tests)
* [Questions](#Questions)
## Installation
there are 4 steps involved
## Usage
there are the following instrcutions
## License
This application is covered under [ISC](
https://opensource.org/licenses/ISC
) license.
## Contributing
this is how others can contribute
## Tests
ther are no tests
## Questions
If need more information, please checkout my [github account](https://github.com/harry-100). You can also reach me via [email](mailto:harry@gmail.com?subject=Project-1).
|
Java
|
UTF-8
| 4,768 | 2.5 | 2 |
[] |
no_license
|
package com.im.websocket;
import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import com.google.gson.Gson;
import com.im.db.DBUtils;
import com.im.domain.BaseBean;
@ServerEndpoint(value = "/websocketdoc")
public class WebSocket_Doc {
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
DBUtils a = new DBUtils();
BaseBean data = new BaseBean(); // 基类对象,回传给客户端的json对象
Gson gson = new Gson();
String json = null;
String docId;
/**
* 连接建立成功调用的方法
*
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
* @throws Exception
*/
@OnOpen
public void onOpen(Session session) throws Exception {
this.session = session;
docId = session.getQueryString();
if (!WebSocketMapUtil_Doc.webSocketMap.containsKey(docId)) {
WebSocketMapUtil_Doc.webSocketMap.put(docId, this);
sendMessage("上线成功!");
System.out.println("docwebsocket.join.id:"+docId);
}
}
/**
* 连接关闭调用的方法
*
* @throws Exception
*/
@OnClose
public void onClose() throws Exception {
// 当医生关闭连接后,将其从map去除
WebSocketMapUtil_Doc.webSocketMap.remove(docId);
System.out.println("docwebsocket.leave.id:" + docId);
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
* @throws IOException
*/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
System.out.println("docwebsocket.message.content:"+message);
if(message.equals("heartBeat")){//如果客户端发送的心跳检测包,则给予回复
sendMessage("heartBeat");
}else {
WebSocket_Doc sockettest = ((WebSocket_Doc) WebSocketMapUtil_Doc.get(docId));
if (sockettest != null) {
MyWebSocket my = new MyWebSocket();
// 当医生发送next准备接诊学生时
if (message.equals("next")) {
synchronized (WebSocket_Doc.class) {
String next = null;
//首先给队首的学生发送接诊消息
next = WebSocketMapUtil.queue.poll();
if (next != null) {//如果队首有学生挂号
// sendMessageToUser(session.getQueryString(), next+"向您发送了接诊邀请!");
sendMessage(next + "向您发送了接诊邀请!");
// 准备连接数据库将医生的名字传给看病的学生
a.openConnect();
String[] docData = a.getDocNameAndPicture(docId);// docData的零位置为名字,1位置为图片地址
a.closeConnect();
my.sendMessageToUser(next, "到你啦!医生id为" + docId + "医生姓名为" + docData[0] + "医生头像为" + docData[1]);
my.sendMessageToUser(next, "等待医生接受邀请,请等待!");
//给队首的学生发送完消息之后,将学生对象从map中移除
WebSocketMapUtil.webSocketMap.remove(next);
} else {
// sendMessageToUser(session.getQueryString(), "当前没有人在挂号,请稍等!");
sendMessage("当前没有人在挂号,请稍等!");
System.out.println("没有人挂号");
}
}
}
}
}
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
System.out.println("docwebsocket.error.id:" + docId);
// sendMessageToUser(session.getQueryString(), "Doc: "+error.getMessage());
try {
sendMessage("Doc: " + error.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 发送消息方法。
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
data.setCode(0);
data.setMsg(message);
json = gson.toJson(data);
this.session.getBasicRemote().sendText(json);
}
// /**
// * 群发消息方法。
// *
// * @param message
// * @throws IOException
// */
// public static void sendMessageAll(String message) throws IOException {
// for (WebSocket_Doc sockettest : WebSocketMapUtil_Doc.getValues()) {
// sockettest.sendMessage(message);
// }
// }
public static int getCount() {
return WebSocketMapUtil_Doc.getValues().size();
}
public String getSessionId() {
return session.getQueryString();
}
}
|
Java
|
UTF-8
| 7,722 | 2.140625 | 2 |
[] |
no_license
|
package org.port.trade.activity;
/**
* Created by 超悟空 on 2015/3/3.
*/
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import org.mobile.model.fragment.BaseIncludeWebFragment;
import org.mobile.model.operate.DataGetHandle;
import org.port.trade.R;
import org.port.trade.fragment.function.FunctionErrorSearchFragment;
import org.port.trade.util.MemoryConfig;
import org.port.trade.util.StaticValue;
/**
* 功能三级内容界面
*
* @author 超悟空
* @version 1.0 2015/3/3
* @since 1.0
*/
public class FunctionContentActivity extends ActionBarActivity {
/**
* 日志前缀
*/
private static final String LOG_TAG = "FunctionContentActivity.";
/**
* 标题栏的标题文本
*/
private TextView toolbarTitleTextView = null;
/**
* 用于显示查询结果内容的包含WebView的片段
*/
private BaseIncludeWebFragment contentFragment = null;
/**
* 保存功能查询布局片段的数据提供接口对象,用于提取查询网址
*/
private DataGetHandle<String> functionSearchFragment = null;
/**
* 是否第一次加载本页面,默认为true
*/
private boolean isFirstOpen = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_function_content);
// 初始化布局
initView();
// 将首次加载标记置为true
isFirstOpen = true;
}
@Override
protected void onStart() {
super.onStart();
// 判断是否为第一次加载完毕
if (isFirstOpen) {
// 默认执行一次查询
searchButtonClick();
}
// 标记设为非第一次加载
isFirstOpen = false;
}
/**
* 初始化布局
*/
private void initView() {
// 初始化标题栏
initToolbar();
// 初始化功能查询片段
initFunctionFragment();
// 初始化内容展示片段
initFunctionContentFragment();
}
/**
* 初始化内容展示片段
*/
private void initFunctionContentFragment() {
// 获取内容片段
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.activity_function_content_webView_fragment);
// 转换为包含WebView的片段
if (fragment instanceof BaseIncludeWebFragment) {
contentFragment = (BaseIncludeWebFragment) fragment;
}
}
/**
* 初始化标题栏
*/
private void initToolbar() {
// 得到Toolbar标题栏
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// 得到标题文本控件
toolbarTitleTextView = (TextView) findViewById(R.id.toolbar_title);
// 关联ActionBar
setSupportActionBar(toolbar);
// 取消原actionBar标题
getSupportActionBar().setDisplayShowTitleEnabled(false);
// 显示后退
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//toolbar.setNavigationIcon(R.drawable.back_icon);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 导航回父activity
goBackParentActivity();
// 与返回键相同
//onBackPressed();
}
});
}
/**
* 导航回父activity
*/
private void goBackParentActivity() {
Intent upIntent = NavUtils.getParentActivityIntent(this);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities();
} else {
upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(this, upIntent);
}
}
/**
* 初始化功能查询片段
*/
private void initFunctionFragment() {
// 获取意图
Intent intent = getIntent();
// 提取数据
// 提取当前功能标题,并设为标题栏标题
setTitle(intent.getCharSequenceExtra(StaticValue.FUNCTION_ITEM_TITLE));
// 片段管理器
FragmentManager fragmentManager = getSupportFragmentManager();
// 提取功能的查询片段
Fragment functionFragment = MemoryConfig.getConfig().getFunctionSearchFragment();
// 替换默认片段为当前功能
if (functionFragment != null) {
// 功能布局存在
Log.i(LOG_TAG + "initFunctionFragment", "function fragment is " + functionFragment.toString());
fragmentManager.beginTransaction().replace(R.id.activity_function_content_search_frameLayout, functionFragment).commit();
// 尝试转换为数据提供接口
if (functionFragment instanceof DataGetHandle) {
// 转为String泛型的数据提供接口
//noinspection unchecked
functionSearchFragment = (DataGetHandle<String>) functionFragment;
}
} else {
// 功能布局不存在,加载一个错误提示
Fragment errorFragment = new FunctionErrorSearchFragment();
Log.d(LOG_TAG + "initFunctionFragment", "function not exist, load " + errorFragment.toString());
fragmentManager.beginTransaction().replace(R.id.activity_function_content_search_frameLayout, errorFragment).commit();
}
}
@Override
public void onBackPressed() {
// 如果网页可以后退则优先执行网页后退
if (contentFragment == null || !contentFragment.onGoBack()) {
super.onBackPressed();
}
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
// 设置标题
toolbarTitleTextView.setText(title);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_function_search, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.menu_search:
// 查询按钮
Log.i(LOG_TAG + "onOptionsItemSelected", "click menu_search");
searchButtonClick();
break;
default:
super.onOptionsItemSelected(item);
}
return true;
}
/**
* 点击查询按钮,执行查询网页加载
*/
private void searchButtonClick() {
if (functionSearchFragment != null) {
// 获取地址
String url = functionSearchFragment.getData();
if (url != null) {
Log.i(LOG_TAG + "menu_search", "url is -->" + url);
// 让WebView片段加载此url
if (contentFragment != null) {
contentFragment.reloadUrl(url);
}
} else {
Log.d(LOG_TAG + "menu_search", "url is null");
}
} else {
Log.d(LOG_TAG + "menu_search", "functionSearchFragment is null");
}
}
}
|
Python
|
UTF-8
| 2,797 | 2.734375 | 3 |
[] |
no_license
|
#!/usr/bin/python
import time
import os
from sys import argv
import sendmail
import re
import xml.etree.ElementTree as ET
import logging
class LogEventMonitorError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class ConfigError(LogEventMonitorError): pass
class XmlError(LogEventMonitorError): pass
class LEMRuntimeError(LogEventMonitorError): pass
class LogEventMonitor(object):
def __init__(self, filename):
self.logger = logging.getLogger("log_event_monitor.LogEventMonitor")
self.logger.debug("creating instance of LogEventMonitor")
self.mail_handler = None
self.pattern = r""
self.log_file = ""
self.timeout = 1
self.get_config(filename)
def get_config(self, filename):
try:
tree = ET.parse(filename)
except IOError as e:
raise ConfigError("File handling error: %s" % e)
except ET.ParseError as e:
raise XmlError("Error in xml syntax: %s" % e)
root = tree.getroot()
pattern = root.find('pattern')
if pattern is not None:
self.pattern = re.compile(pattern.text)
else:
raise ConfigError("Pattern is not found in the %s" % filename)
timeout = root.find('timeout')
if timeout is not None:
self.timeout = int(timeout.text)
log_file = root.find('logfile')
if log_file is not None:
self.log_file = log_file.text
else:
raise ConfigError("Log file is no spicified in %s" % filename)
mailconfig = root.find('mailconfig')
if mailconfig is not None:
mailconfig_str = ET.tostring(mailconfig)
self.mail_handler = sendmail.SendMail(mailconfig_str)
else:
raise ConfigError("Mailconfig is not found in %s" % filename)
def run(self):
buffer = ""
timer = 0
try:
self.logger.debug("opening file %s" % self.log_file)
with open(self.log_file) as fh:
fh.seek(0, os.SEEK_END)
while(1):
line = fh.readline()
if self.pattern.search(line):
buffer += line
if timer == 0:
timer = time.time()
if timer and ( time.time() - timer > self.timeout ):
self.mail_handler.sendmail_conf(buffer)
timer = 0
buffer = ""
time.sleep(0.001)
except IOError as e:
raise LEMRuntimeError("Can't handle log file %s" % e)
|
C++
|
UTF-8
| 1,424 | 2.859375 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
class graph{
int v;
// list<int> *adj;
unordered_multimap <int,int> adj;
public:
graph(int v){
this->v=v;
}
void addEdge(int u,int v){
adj.emplace(v,u);
adj.emplace(u,v);
}
void bfs(int s){
vector<bool> visited(v,false);
vector<int> distance(v,0);
deque<int> q;
visited[s]=true;
q.push_back(s);
while(!q.empty()){
int f = q.front();
q.pop_front();
pair<unordered_multimap<int,int>::iterator ,unordered_multimap<int,int>::iterator > r=adj.equal_range(f);
for(auto i=r.first;i!=r.second;i++){
if(!visited[*i]){
visited[i]=true;
q.push_back(i);
distance[i]=distance[f]+6;
}
}
}
for(int i=0;i<v;i++){
if(i == s)
continue;
if(distance[i]==0)
cout<<"-1 ";
else
cout<<distance[i]<<" ";
}
cout<<endl;
}
};
int main() {
int query,v,e,s;
cin>>query;
while(query--){
cin>>v>>e;
graph g(v);
for(int i=0;i<e;i++){
int a,b;
cin>>a>>b;
g.addEdge(a-1,b-1);
}
cin>>s;
g.bfs(s-1);
}
return 0;
}
|
Python
|
UTF-8
| 124 | 3.4375 | 3 |
[] |
no_license
|
### programa responsavel por printar 5 vezes "Hello World" na forma de String
for i in range(5):
print ("Hello World")
|
PHP
|
UTF-8
| 1,439 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* User: cfn <cfn@leapy.cn>
* Datetime: 2021/8/20 9:33
* Copyright: php
*/
namespace unionpay\Kernel\Traits;
use Exception;
use Symfony\Component\HttpFoundation\Response;
/**
* Class PaymentNotifyHandle
*
* @package unionpay\Kernel\Traits
*/
trait PaymentNotifyHandle
{
/**
* @var string
*/
protected static $SUCCESS = 'success';
/**
* @var string
*/
protected $data = [];
/**
* 是否验签
* @var bool
*/
public $isCheck = true;
/**
* @author cfn <cfn@leapy.cn>
* @date 2021/8/20 9:34
*/
protected function toResponse()
{
return new Response(self::$SUCCESS);
}
/**
* @return array|string
* @throws Exception
* @author cfn <cfn@leapy.cn>
* @date 2021/8/20 9:37
*/
protected function getData()
{
if (!empty($this->data)) return $this->data;
try {
$param_str = strval($this->app['request']->getContent());
parse_str($param_str,$data);
}catch (Exception $e)
{
throw new Exception('Invalid request.', 400);
}
if (!is_array($data) || empty($data)) {
throw new Exception('Invalid request.', 400);
}
if ($this->isCheck)
if (!$this->app->signature->validate($data))
throw new Exception('Invalid signature.', 400);
return $this->data = $data;
}
}
|
Python
|
UTF-8
| 491 | 4.0625 | 4 |
[] |
no_license
|
# Coursera Python Training 2
# Lucas Silva
# Week 1 - Exercício 2 - Soma de Matrizes
def soma_matrizes(m1,m2):
if len(m1)==len(m2) and len(m1[0])==len(m2[0]):
m3=[]
for i in range(0,len(m1)):
linha=[]
for j in range(0,len(m1[0])):
linha.append(m1[i][j] + m2[i][j])
m3.append(linha)
return m3
else:
return False
m1 = [[1, 2, 3], [4, 5, 6]]
m2 = [[2, 3, 4], [5, 6, 7]]
print(soma_matrizes(m1, m2))
|
JavaScript
|
UTF-8
| 5,040 | 2.515625 | 3 |
[] |
no_license
|
/// <reference types="cypress" />
context('Happy Path', () => {
// Select the 1st case
it('should select the case', () => {
cy.visit('https://learning.elucidat.com/course/5c9126fd760e5-60ba4c3fe8135')
cy.get('h1.projectTitle').should('contain','FINDING THE TRUTH');
cy.get('.add_option_button a.button').click()
cy.get('#pa_5c9126fe3f4fb_p179d7b273e1-link--imgCard-1').click()
cy.get('#pa_5c9126fe434ba_p1557cb3bfec-video').should('have.class','video e-has-video e-video-completed')
});
// Click on Judge button and check if two vote options are visible
it('judge the case', () => {
cy.get('#pa_5c9126fe434ba_p15564daa856-button__text').should('contain', 'JUDGE THIS').click()
cy.get('form[id="pa_5c9126fe47260_p15515116385-form--scq"]').invoke('text').then(form =>{
expect(form).contains('Guilty' && 'Not guilty')
})
});
// Click guilty and click vote, check if 1st radio button is checked and second remain unchecked, then check if text You think Kevin is guilty appears.
it('guilty or not guilty', () => {
cy.get('form[id="pa_5c9126fe47260_p15515116385-form--scq"]').find('[type="radio"]').then(radioButtons => {
cy.wrap(radioButtons).first().check({force:true})
.should('be.checked')
cy.wrap(radioButtons).eq(1).should('not.be.checked')
})
cy.get('#pa_5c9126fe47260_p15515116385-button__text').click()
cy.get('#pa_5c9126fe47260_p1554e607e46-modal__text__wrapper').should('contain', 'You think Kevin is guilty.')
cy.get('#pa_5c9126fe47260_p15583b88249-button__text').should('contain', 'CONTINUE')
});
//Click continue, then confirm there are 6 explore evidence buttons
it('guilty approval', () => {
cy.get('#pa_5c9126fe47260_p15583b88249-button__text').click()
cy.get('#pa_5c9126fe4b742_p1554fa6d6c6-explorer__inner').find('i[class="ti ti-magnify"]').then(explorer =>{
const evidenceAmount = explorer.length
expect(evidenceAmount).to.equal(6)
})
});
// CLick on the top explore button, then confirm that pop up window with the "FOOTPRINTS" text appears
it('check the evidence', () => {
cy.get('#pa_5c9126fe4b742_p1554fa6d6c6-explorer__inner').find('i[class="ti ti-magnify"]').eq(1).click()
cy.get('h2#pa_5c9126fe4b742_p1554fa6d7d7-modalTitle-2').should('contain','FOOTPRINTS')
cy.get('#pa_5c9126fe4b742_p15583bfb7a0-button__text-2').should('contain', 'CLOSE')
});
// Click on the Close button
it('close the evidence', () => {
cy.get('#pa_5c9126fe4b742_p15583bfb7a0-button__text-2').click()
});
// Click on the Continue button, confirm the text "There seems to be quite of evidence suggesting that Kevin is guilty" exists
it('continue', () => {
cy.get('#pa_5c9126fe4b742_p15550a254a1-button__text').click()
cy.get('#pa_5c9126fe4f952_p15507291710-textWrapper').should('contain', 'There seems to be quite a bit of evidence suggesting that Kevin is guilty.')
});
// Click on the Continue button, you should see the page with 4 radio buttons
it('You decide', () => {
cy.get('#pa_5c9126fe4f952_p15578944323-button__text').click()
cy.get('#pa_5c9126fe5331b_p155cc4e94a5-answerGrid__inner').find('[class="card imageCard answer e-card--medium e-image_type--landscape"]').then(evidenceRadio => {
const evidenceButton = evidenceRadio.length
expect(evidenceButton).to.equal(4)
})
});
//Click on the last radio button, confirm that area around selected radio button is framed
it('radio buttons', () => {
cy.get('#pa_5c9126fe5331b_p155cc4e94a5-answerGrid__inner').find('[class="card imageCard answer e-card--medium e-image_type--landscape"]').eq(3).then(radioSelected => {
cy.wrap(radioSelected).click()
cy.wrap(radioSelected).should('have.class', 'card imageCard answer e-card--medium e-image_type--landscape selected')
})
});
//Click on the Vote button, window with text "Our experts disagrees" should be visible
it('fingerprint evidence vote', () => {
cy.get('#pa_5c9126fe5331b_p155cc4e94a5-button__text').click()
cy.get('#pa_5c9126fe5331b_p155cc4e96fb-modalTitle').should('contain', 'Our expert disagrees')
});
// CLick on the Continue button, text "THE DNA' should be vidible in the header"
it('fingerprint continue', () => {
cy.get('#pa_5c9126fe5331b_p155cc4e970b-button__text').click()
cy.get('#pr_5c9126fd760e5_p155729036fa-page__title').should('contain','THE DNA')
});
// Click on the First Flip card, confirm that text contains "You can't argue with DNA evidence"
it('the DNA evidence note', () => {
cy.get('#pa_5c9126fe57197_p15578a164ba-button__text-front').click()
cy.get('#pa_5c9126fe57197_p15578a165c1-text').should('contain', 'You can’t argue with DNA evidence.')
});
})
|
Python
|
UTF-8
| 635 | 3.40625 | 3 |
[] |
no_license
|
from sys import argv
script , filename = argv
print "WE are going to erase %r" % filename
print "if you dont want that hit CTRL-C (^C)"
print "If you do want that hit Return "
raw_input("?")
print "opening file ..."
target = open(filename,'w')
print "Turnicating the file day Goodbye ! "
target.truncate()
print " Now i am going to ask you for 3 lines "
line1 = raw_input("line1:")
line2 = raw_input("line2:")
line3 = raw_input("line3:")
print "I am going to write the to the file "
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
print " and we close it here "
target.close()
|
C++
|
UTF-8
| 1,680 | 2.953125 | 3 |
[] |
no_license
|
#include "Stats.h"
#include <string>
#include <fstream>
#include <windows.h>
#include <vector>
#include <iostream>
Stats::Stats()
{
GetUserName(profile, &profile_len);
profile_name = profile;
}
void Stats::stat()
{
std::ofstream cf;
cf.open("C\:\\Users\\" + profile_name + "\\Desktop\\CharacterFile.txt", std::ios::app);
std::ifstream st("statTypes.txt");
const int NUMTHREADS = 6;
if (cf.is_open())
{
if (st.is_open())
{
std::string saying[NUMTHREADS];
for (int i = 0; i < NUMTHREADS; i++)
{
std::getline(st, saying[i]);
int randNum = rand();
int trueNum = (randNum % 13) + 6; // Random number between 6-18.
cf << saying[i] + " " + std::to_string(trueNum) + "\n";
}
cf.close();
st.close();
}
else
{
std::cout << "File ST could not be open.\n";
}
}
else
{
std::cout << "File CF could not be open.\n";
}
}
void Stats::randStat()
{
std::ofstream rcf;
rcf.open("C\:\\Users\\" + profile_name + "\\Desktop\\RandomCharacterFile.txt", std::ios::app);
std::ifstream st("statTypes.txt");
const int NUMTHREADS = 6;
if (rcf.is_open())
{
if (st.is_open())
{
std::string saying[NUMTHREADS];
for (int i = 0; i < NUMTHREADS; i++)
{
std::getline(st, saying[i]);
int randNum = rand();
int trueNum = (randNum % 13) + 6; // Random number between 6-18.
rcf << saying[i] + " " + std::to_string(trueNum) + "\n";
}
rcf.close();
st.close();
}
else
{
std::cout << "File ST could not be open.\n";
}
}
else
{
std::cout << "File RCF could not be open.\n";
}
}
Stats::~Stats()
{
}
|
Markdown
|
UTF-8
| 456 | 2.90625 | 3 |
[] |
no_license
|
### 声明空间
两种声明空间: 类型声明空间和变量声明空间
##### 类型声明空间
包含用来当做类型注解的内容
出现错误提示: cannot find name 'Bar' 的原因是名称 Bar 并未定义在变量声明空间。
##### 变量声明空间
#### 基本注解
```ts
const num: number = 123;
function identity(num:number):number {
return num;
}
const identify = (num:number):number=>{
return num;
}
```
|
Java
|
UTF-8
| 5,749 | 2.265625 | 2 |
[] |
no_license
|
package com.example.vanosidor.moxygithubrepositories.ui.mvp.presenter;
import android.util.Log;
import com.arellomobile.mvp.InjectViewState;
import com.example.vanosidor.moxygithubrepositories.ui.GithubApp;
import com.example.vanosidor.moxygithubrepositories.ui.database.RepositoriesDao;
import com.example.vanosidor.moxygithubrepositories.ui.database.UserDao;
import com.example.vanosidor.moxygithubrepositories.ui.mvp.data.NetworkDataSource;
import com.example.vanosidor.moxygithubrepositories.ui.mvp.data.RepositoryDataSource;
import com.example.vanosidor.moxygithubrepositories.ui.mvp.data.TestDataSource;
import com.example.vanosidor.moxygithubrepositories.ui.mvp.model.Repository;
import com.example.vanosidor.moxygithubrepositories.ui.mvp.view.RepositoriesView;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
/**
* Created by Ivan on 06.11.2017.
*/
@InjectViewState
public class RepositoriesPresenter extends BasePresenter<RepositoriesView> {
private static final int PAGE_SIZE = 50;
private static final String TAG = RepositoriesPresenter.class.getSimpleName();
public enum State {FIRSTLOADING,REFRESH,LOADMORE}
private int mCurrentPageCount;
private boolean mIsLoading;
@Inject
UserDao userDao;
@Inject
RepositoriesDao reposDao;
public RepositoriesPresenter() {
GithubApp.getAppComponent().inject(this);
}
@Override
protected void onFirstViewAttach() {
super.onFirstViewAttach();
Log.d(TAG, "onFirstViewAttach");
loadRepositories(State.FIRSTLOADING);
}
public void loadRepositories(State state){
loadData(state,1);
}
public void loadMoreRepositories(int repositoriesCount){
//loadingStart(State.LOADMORE);
if(mCurrentPageCount >= PAGE_SIZE){
int page = repositoriesCount / PAGE_SIZE + 1;
Log.d(TAG, "loadMoreRepositories.Page number = " + page);
loadData(State.LOADMORE,page);
}
}
private void loadData(State state, int page) {
//https://api.github.com/users/JakeWharton/repos?page=2&&per_page=50
String userName = "vanosidor";
//change real data to test data from local json
RepositoryDataSource dataSource = new TestDataSource();
//RepositoryDataSource dataSource = new NetworkDataSource();
//Load from network
if (mIsLoading) {
return;
}
loadingStart(state);
Observable<List<Repository>> repositoriesObservable = dataSource.getRepositories(userName,page,PAGE_SIZE)
.map(repositories -> {
Log.d(TAG, "before save repos in db.Count = "+repositories.size());
if (state==State.FIRSTLOADING || state == State.REFRESH ){
reposDao.clearAllRepositories();
}
saveReposInDB(repositories);
Log.d(TAG, "after save repos in db.Count = "+repositories.size());
return repositories;
});
Disposable disposable = repositoriesObservable
.subscribeOn(Schedulers.io())
//.doOnSubscribe(this::showLoadingView)
.delay(500, TimeUnit.MILLISECONDS) //imitation of slow download
.onErrorResumeNext(loadFromDb)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(repositories -> {
//repositories=new ArrayList<>(); //test no repositories
loadingFinish(state);
//loadingError(new Throwable("test error!")); //for test error comment next string
loadingSuccess(repositories,state);
},
throwable -> {
loadingFinish(state);
loadingError(throwable);
});
unsubscribeOnDestroy(disposable);
}
private void saveReposInDB(List<Repository> repositories) {
reposDao.insert(repositories);
}
private final Function<Throwable, Observable<List<Repository>>> loadFromDb = throwable -> Observable.just(reposDao.getRepositories());
private void loadingStart(State state) {
switch (state){
case FIRSTLOADING: getViewState().showLoadingProgressBar();break;
case REFRESH:getViewState().showRefreshView();break;
case LOADMORE:getViewState().showLoadMoreProgress();break;
}
}
private void loadingFinish(State state) {
mIsLoading = false;
switch (state){
case FIRSTLOADING: getViewState().hideLoadingProgressBar();break;
case REFRESH:getViewState().hideRefreshView();break;
case LOADMORE:getViewState().hideLoadMoreProgress();break;
}
}
private void loadingError(Throwable throwable) {
getViewState().showError(throwable);
}
private void loadingSuccess(List<Repository> repositories,State state) {
Log.d(TAG, "loadingSuccess: loaded "+repositories.size()+" items");
mCurrentPageCount = repositories.size();
if(state!= State.LOADMORE){
if(repositories.size()==0) getViewState().showEmptyData();
else getViewState().showData(repositories);
}
else {
getViewState().showMoreData(repositories);
}
}
}
|
Python
|
UTF-8
| 1,258 | 3.609375 | 4 |
[] |
no_license
|
from collections import namedtuple
# 1. списки смежности
graph = []
graph.append([1, 2])
graph.append([0, 2, 3])
graph.append([0, 1])
graph.append([1])
print(graph)
print(*graph, sep='\n')
# как проверить что из вершины 1 мы попадем в вершину 3?
# - перебрать весь список
print('*' * 50)
# 2. ориентированный граф
graph_2 = {
0: {1, 2},
1: {0, 2, 3},
2: {0, 1},
3: {1}
}
print(graph_2)
# как проверить что из вершины 1 мы попадем в вершину 3?
if 3 in graph_2[1]:
print(True)
# 3. взвешенный граф
print('*' * 50)
Vertex = namedtuple('Vertex', ['vertex', 'edge'])
graph_3 = []
graph_3.append([Vertex(1, 2), Vertex(2, 3)])
graph_3.append([Vertex(0, 2), Vertex(2, 2), Vertex(3, 1)])
graph_3.append([Vertex(0, 3), Vertex(1, 2)])
graph_3.append([Vertex(1, 1)])
print(*graph_3, sep='\n')
# как проверить что из вершины 1 мы попадем в вершину 3?
for v in graph_3[1]:
if v.vertex ==3:
print(True)
class Graph:
def __init__(self, vertex, edge,spam):
self.vertex = vertex
self.edge = edge
self.spam = spam
|
TypeScript
|
UTF-8
| 2,787 | 2.609375 | 3 |
[] |
no_license
|
module com {
export module google {
export module analytics {
export module campaign {
export class CampaignTracker extends egret.HashObject {
public content:string;
public id:string;
public clickId:string;
public name:string;
public term:string;
public medium:string;
public source:string;
public constructor(param1:string = "",param2:string = "",param3:string = "",param4:string = "",param5:string = "",param6:string = "",param7:string = "")
{
super();
super();
this.id = param1;
this.source = param2;
this.clickId = param3;
this.name = param4;
this.medium = param5;
this.term = param6;
this.content = param7;
}
public toTrackerString():string
{
var _loc1_:Array<any> = <any>null;
_loc1_ = [];
this._addIfNotEmpty(_loc1_,"utmcsr=",this.source);
this._addIfNotEmpty(_loc1_,"utmccn=",this.name);
this._addIfNotEmpty(_loc1_,"utmcmd=",this.medium);
this._addIfNotEmpty(_loc1_,"utmctr=",this.term);
this._addIfNotEmpty(_loc1_,"utmcct=",this.content);
this._addIfNotEmpty(_loc1_,"utmcid=",this.id);
this._addIfNotEmpty(_loc1_,"utmgclid=",this.clickId);
return _loc1_.join(com.google.analytics.campaign.CampaignManager.trackingDelimiter);
}
public isValid():boolean
{
if(this.id != "" || this.source != "" || this.clickId != "")
{
return true;
}
return false;
}
private _addIfNotEmpty(param1:Array<any>,param2:string,param3:string)
{
if(param3 != "")
{
param3 = param3.split("+").join("%20");
param3 = param3.split(" ").join("%20");
param1.push(param2 + param3);
}
}
public fromTrackerString(param1:string)
{
var _loc2_:string = <any>null;
var _loc3_:com.google.analytics.utils.Variables = <any>null;
_loc2_ = param1.split(com.google.analytics.campaign.CampaignManager.trackingDelimiter).join("&");
_loc3_ = new com.google.analytics.utils.Variables(_loc2_);
if(_loc3_.hasOwnProperty("utmcid"))
{
this.id = _loc3_["utmcid"];
}
if(_loc3_.hasOwnProperty("utmcsr"))
{
this.source = _loc3_["utmcsr"];
}
if(_loc3_.hasOwnProperty("utmccn"))
{
this.name = _loc3_["utmccn"];
}
if(_loc3_.hasOwnProperty("utmcmd"))
{
this.medium = _loc3_["utmcmd"];
}
if(_loc3_.hasOwnProperty("utmctr"))
{
this.term = _loc3_["utmctr"];
}
if(_loc3_.hasOwnProperty("utmcct"))
{
this.content = _loc3_["utmcct"];
}
if(_loc3_.hasOwnProperty("utmgclid"))
{
this.clickId = _loc3_["utmgclid"];
}
}
}
}
}
}
}
|
Python
|
UTF-8
| 3,399 | 3.53125 | 4 |
[] |
no_license
|
import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
import calendar
# https://github.com/QCaudron/pydata_pandas -- based from
# Temporary fix to print() not showing newline at the end
nl = "\n"
coffeeData = pd.read_csv("data/coffees.csv")
# ===== Showing Data =====
# Print first 5 rows(data entries). .head([amount]) / .tail([amount])
print(coffeeData.head(), nl)
# NaN - Not a Number
# Shows second entry of data. .iloc[x]
print("Entry 1:\n", coffeeData.loc[1], nl)
# Shows different data info ex. freq, count, top, etc
print("line 22:\n", coffeeData.describe(), nl)
# Shows all data entries where the coffees column is null (NaN, etc)
print("All NaN entries:\n", coffeeData[coffeeData.coffees.isnull()], nl)
# Shows data types
print("Data types:\n", coffeeData.dtypes, nl)
# Prints first timestamp object and shows what object type it is
print("timestamp[0]:\n", coffeeData.timestamp[0])
print("timestamp[0] type:\n", type(coffeeData.timestamp[0]), nl)
# ===== Setup =====
print("coffees column to numeric\nBefore:\n", coffeeData.head())
print(coffeeData.dtypes, nl)
# Sets coffees data to numeric and set anything else to NaN
coffeeData.coffees = pd.to_numeric(coffeeData.coffees, errors="coerce")
print("After:\n", coffeeData.head())
print(coffeeData.dtypes)
print("coffees[0] type:\n", type(coffeeData.coffees[0]), nl)
# Drops NaN entries inplace, instead of making a copy. This will also drop the index corresponding to the dropped NaN
coffeeData.dropna(inplace=True)
print("Drop NaN:\n", coffeeData.head(), nl)
# Converts to int64 instead of float64. put after .to_numeric and .dropna() to not encounter type conflict
coffeeData.coffees = coffeeData.coffees.astype(int)
coffeeData.timestamp = pd.to_datetime(coffeeData.timestamp)
print("timestamp column to datetime:\n", coffeeData.dtypes, nl)
print(coffeeData.describe(include="all"), nl)
# Only data that is before specified data. pandas automatically converts string to datetime for boolean expression
coffeeData = coffeeData[coffeeData.timestamp < "2013-03-01"]
print("data entries before 2013-03-01\n", coffeeData.tail(), nl)
# Shows # of occurrences in contributor
print("Contributor count:\n", coffeeData.contributor.value_counts())
# Adds weekday column to data frame using datetime.weekday_name
coffeeData = coffeeData.assign(weekday=coffeeData.timestamp.dt.weekday_name)
print("Added weekday to data frame:\n", coffeeData.head(), nl)
# Groups data by weekday then sorts by weekday name. How many entries on given day
cData_weekdayGrouped = coffeeData.groupby('weekday').count()
cData_weekdayGrouped = cData_weekdayGrouped.loc[list(calendar.day_name)]
print("Grouped by weekday:\n", cData_weekdayGrouped.head())
# ===== Plotting =====
plt.rcParams['axes.grid'] = True # Enables grid for all
# This will plot x: index and y: coffees. not exactly what we want
#coffeeData.coffees.plot()
# Show both plots in one window
fig1, axes = plt.subplots(nrows=1, ncols=2, figsize=(13, 5), num="Coffee Data")
coffeeData.plot(x='timestamp', y='coffees', style='.-', title="Time x Coffees", ax=axes[0], grid=True)
coffeeData.contributor.value_counts().plot(kind='bar', title="Contributor x Times", ax=axes[1])
# New window. on newer Macs it'll open a new tab
fig2 = plt.figure()
# Bar graph of how many days by weekday
cData_weekdayGrouped.coffees.plot(kind='bar')
plt.show()
|
Python
|
UTF-8
| 2,094 | 3.578125 | 4 |
[] |
no_license
|
# encoding=utf-8
# -,- 回头理解清楚一下
class Solution(object):
def recur_search(self, left, right, nums, target):
if left == right:
if nums[left] == target:
return left
else:
return -1
mid = (left + right) / 2
if nums[mid] == target:
return mid
if nums[mid] == nums[left]:
tmp = mid
while nums[tmp] == nums[left] and tmp > left:
tmp = tmp -1
if tmp == left:
return self.recur_search(mid+1,right,nums,target)
else: mid = tmp
if nums[mid] == target:
return mid
if nums[mid] < nums[left]:
if target >= nums[left] or target < nums[mid]:
return self.recur_search(left, mid - 1, nums, target)
else:
return self.bin_search(mid + 1, right, nums, target)
if target >= nums[left] and target < nums[mid]:
return self.bin_search(left, mid - 1, nums, target)
else:
return self.recur_search(mid + 1, right, nums, target)
def bin_search(self, left, right, nums, target):
if target < nums[left] or target > nums[right]:
return -1
if left == right:
if nums[left] == target:
return left
else:
return False
mid = (left + right) / 2
if nums[mid] == target:
return mid
if nums[mid] > target:
return self.bin_search(left, mid - 1, nums, target)
else:
return self.bin_search(mid + 1, right, nums, target)
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return False
x = self.recur_search(0, len(nums) - 1, nums, target)
if x >= 0:
print x
return True
else: return False
if __name__ == '__main__':
so = Solution()
a = [1,3,1]
tar = 2
print so.search(a,tar)
|
Java
|
UTF-8
| 5,279 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
public class LagObserver {
private static int groupsize = 3; // 1 ... 24
private static int managerLagLevel = 1;
public static int groupsize() {
return groupsize;
}
public static int getManagerLagLevel() {
return managerLagLevel;
}
public static int managerRotationSize() { // 7, 14, 21, 28
return MANAGER_ROTATION_SIZE * managerLagLevel;
}
public static int managerExecuteRotation(int manager, int index) {
return (MANAGER_ROTATION_SIZE * index + manager) % managerRotationSize();
}
// public static void main(String[] ar) {
//
// for (int frame = 0; frame < 32; frame++) {
// boolean e0 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER0, 0), testRotationSize());
// boolean e0_2 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER0, 1), testRotationSize());
// boolean e1 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER1, 0), testRotationSize());
// boolean e1_2 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER1, 1), testRotationSize());
// boolean e2 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER2, 0), testRotationSize());
// boolean e2_2 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER2, 1), testRotationSize());
// boolean e3 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER3, 0), testRotationSize());
// boolean e3_2 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER3, 1), testRotationSize());
// boolean e4 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER4, 0), testRotationSize());
// boolean e4_2 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER4, 1), testRotationSize());
// boolean e5 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER5, 0), testRotationSize());
// boolean e5_2 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER5, 1), testRotationSize());
// boolean e6 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER6, 0), testRotationSize());
// boolean e6_2 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER6, 1), testRotationSize());
// boolean e7 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER7, 0), testRotationSize());
// boolean e7_2 = testRotation(frame, testManagerExecuteRotation(LagObserver.MANAGER7, 1), testRotationSize());
// System.out.println(e0 + ", " + e1 + ", " + e2 + ", " + e3 + ", " + e4 + ", " + e5 + ", " + e6 + ", " + e7);
// System.out.println(e0_2 + ", " + e1_2 + ", " + e2_2 + ", " + e3_2 + ", " + e4_2 + ", " + e5_2 + ", " + e6_2 + ", " + e7_2);
// System.out.println();
// }
// }
//
//
// private static int testManagerExecuteRotation(int manager, int index) {
// return (MANAGER_ROTATION_SIZE * index + manager) % testRotationSize();
// }
//
// private static boolean testRotation(int frame, int group, int rotationSize) {
// return (frame % rotationSize) == group;
//// return true;
// }
//
// private static int testRotationSize() {
// return 16;
// }
private static final int MANAGER_ROTATION_SIZE = 9;
public static final int MANAGER0 = 0; //info
public static final int MANAGER1 = 1; //strategy
public static final int MANAGER2 = 2; //mapgrid
public static final int MANAGER3 = 3; //build provider
public static final int MANAGER4 = 4; //build
public static final int MANAGER5 = 5; //construction
public static final int MANAGER6 = 6; //worker
public static final int MANAGER7 = 7; //combat
public static final int MANAGER8 = 8; //attack decision
private static final boolean ADJUST_ON = true;
public static final long MILLISEC_MAX_COAST = 30;
// private static final long MILLISEC_MIN_COAST = 30;
private static int groupMaxSize = 48; // max : 2초 딜레이
private static int groupMinSize = 3;
private static final int OBSERVER_CAPACITY = 15 * 24; // 15초간 delay가 없어서 groupsize를 낮춘다.
private static long[] observedTime = new long[OBSERVER_CAPACITY];
private static final String LAG_RELIEVE_ADJUSTMENT = "Lag Relieve Adjustment: LELEL - %d ... (%s)";
private long startTime;
public LagObserver() {
}
public void start() {
this.startTime = System.currentTimeMillis();
}
public void observe() {
observedTime[MyBotModule.Broodwar.getFrameCount() % OBSERVER_CAPACITY] = System.currentTimeMillis() - this.startTime;
this.startTime = System.currentTimeMillis();
this.adjustment();
}
public void adjustment() {
if (ADJUST_ON) {
long cost = observedTime[MyBotModule.Broodwar.getFrameCount() % OBSERVER_CAPACITY];
if (cost > MILLISEC_MAX_COAST) {
if (groupsize < groupMaxSize) {
groupsize++;
}
} else {
if (groupsize > groupMinSize) {
boolean exceedTimeExist = false;
for (long t : observedTime) {
if (t >= MILLISEC_MAX_COAST) {
exceedTimeExist = true;
break;
}
}
if (!exceedTimeExist) {
groupsize--;
}
}
}
managerLagLevel = groupsize / MANAGER_ROTATION_SIZE + 1; // manager size = 9
if (MyBotModule.Broodwar.self().supplyUsed() > 300) {
groupMinSize = MANAGER_ROTATION_SIZE;
if (groupsize < groupMinSize) {
groupsize = MANAGER_ROTATION_SIZE;
}
}
}
}
}
|
Shell
|
UTF-8
| 8,666 | 2.609375 | 3 |
[] |
no_license
|
# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc.
# Initialization code that may require console input (password prompts, [y/n]
# confirmations, etc.) must go above this block; everything else may go below.
if [[ -s "${ZDOTDIR:-$HOME}/.zprezto/init.zsh" ]]; then
source "${ZDOTDIR:-$HOME}/.zprezto/init.zsh"
fi
# If you come from bash you might have to change your $PATH.
export PATH=$HOME/bin:/usr/local/bin:
export PATH="/usr/local/bin:$PATH"
export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/latest/bin
export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH=$PATH:$HOME/.rvm/bin
export PATH=$PATH:/usr/local/go/bin
export PATH=/Users/`whoami`/Library/Python/3.7/bin/:$PATH
export PATH=$PATH:$HOME/go/bin
export NODE_ENV='dev'
export EDITOR=vim
export VISUAL=$EDITOR
export DOTNET_DIR=/usr/local/share/dotnet
export PATH=$DOTNET_DIR:$PATH
export PATH=~/homebrew/bin:$PATH
export PATH="$HOME/.cargo/bin:$PATH"
export JAVA_HOME="/Users/tyler.simpson/Library/Java/JavaVirtualMachines/liberica-11.0.16.1"
export GIT_USERNAME=digilob
export GIT_ACCESS_TOKEN=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
export GIT_NPM_TOKEN=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
# change the size of history
export HISTSIZE=2000
export HISTFILE="$HOME/.history"
export SAVEHIST=$HISTSIZE
ZSH_THEME="powerlevel10k/powerlevel10k"
setopt hist_ignore_all_dups
setopt hist_ignore_space
#################################################
### Aliases
#################################################
#################
#Work/Play Time
#################
#alias air='~/.air'
#alias vim="nvim"
alias cat="bat"
alias less="batpipe"
alias watch="batwatch"
alias diff="batdiff"
alias ls="exa"
alias lg="lazygit"
alias ld="lazydocker"
alias sub="open -a 'Sublime Text'"
alias vis="open -a 'Visual Studio Code'"
alias cdw="cd /Users/tyler.simpson/projects/digicert"
alias cdp="cd /Users/tyler.simpson/projects"
alias co="git checkout"
alias cls="clear"
alias cl="colorls -al"
alias lc="lolcat"
alias his="history"
alias who="whoami"
alias gst="git status"
alias cra="create-react-app"
alias chnpm="sudo chown -R $(whoami):staff"
alias dc="docker-compose"
alias dp="docker ps"
alias dk="docker kill $(docker ps -aq)"
alias dcup="docker-compose up"
alias dcdn="docker-compose down"
alias klf="kubectl logs -f"
alias kgp="kubectl get pods"
alias kpf="kubectl port-forward"
alias kdp="kubectl delete pods"
alias ll="ls -al"
alias chrome='open -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args -remote-debugging-port=9222'
alias binfix='/usr/bin/find ~/bin -type f | xargs chmod +x'
alias GOFLAGS="-mod=mod"
alias python=python3
#alias tmux='tmux -vv -f /dev/null new'
#################
#pbcopy replacement
#################
#alias pbcopy='xsel --clipboard --input'
#alias pbcopy='xsel --clipboard --input'
#alias pbcopy="clip.exe"
#alias pbpaste="powershell.exe -command 'Get-Clipboard' | head -n -1"
#################
#Docker Time
#################
alias dm=docker-machine
alias dmnfs=". ~/.docker_env && docker-machine-nfs default --mount-opts='noacl,async,nolock,vers=3,udp,noatime,actimeo=1'"
alias dmcfg="docker-machine env default > ~/.docker_env && source ~/.docker_env && dmnfs"
alias dmclean="dmclean1 && dmclean2 && dmclean3"
alias dmstart="dm start && dmcfg && devupdate && appupdate && dmclean"
alias policyupdate="adgpupdate"
alias fuck='eval $(thefuck $(fc -ln -1 | tail -n 1)); fc -R'
# Docker JJ
alias dkpsa='docker ps -a' # List all containers (default lists just running)
alias dkcls='docker container ls' # List containers
alias dkcps='docker-compose ps' # List docker-compose containers
alias dkils='docker image ls' # List images
alias dkvls='docker volume ls' # List volumes
alias dkmls='docker-machine ls' # List docker-machines
alias dkstoprm='docker stop $(docker ps -a -q) && docker rm $(docker ps -a -q)'
# Clean up exited containers (docker < 1.13)
alias dkrmC='docker rm $(docker ps -qaf status=exited)'
# Clean up dangling images (docker < 1.13)
alias dkrmI='docker rmi $(docker images -qf dangling=true)'
# Pull all tagged images
alias dkplI='docker images --format "{{ .Repository }}" | grep -v "^<none>$" | xargs -L1 docker pull'
# Clean up dangling volumes (docker < 1.13)
alias dkrmV='docker volume rm $(docker volume ls -qf dangling=true)'
# kills all running docker containers, and does a minimal clean
alias docker-stupid='docker-compose down ; docker stop $(docker ps -aq) ; docker rm $(docker ps -qa) ; docker network rm $(docker network ls | grep "bridge" | awk "/ / { print $1 }")'
# kills all running docker containers, and does a larger clean
alias dmclean='docker-compose down ; docker stop $(docker ps -aq) ; docker rm $(docker ps -qa) ; docker network rm $(docker network ls | grep "bridge" | awk "/ / { print $1 }") ; docker rmi $(docker images --filter "dangling=true" -q --no-trunc)'
# kills all running docker containers, and purges everything docker has done
alias dmpurge='docker-compose down ; docker stop $(docker ps -aq) ; docker rm $(docker ps -qa) ; docker network rm $(docker network ls | grep "bridge" | awk "/ / { print $1 }") ; docker volume ls | grep -v DRIVER | while read driver name ; do docker volume rm $name ; done ; docker image ls -a | grep -v "REPOSITORY" | while read repo tag image etc ; do docker rmi $image --force ; done'
startover() {
echo 'Killing everything'
docker stop $(docker ps -a -q)
docker rm -f $(docker ps -a -q)
docker rmi -f $(docker images -q)
echo 'Everything killed, my lord'
}
# k8s
#alias kap='kubectl delete all --all --all-namespaces' # kill all pods
alias wgp='watch kubectl get pods' # watcher for pods
alias kctx=kubectx
alias kns=kubens
# getting kubectx && kubens going
if [ $(command -v kubectx) ] && ! [ $(command -v kctx) ]; then
CMD="$(which kubectx)"
ln -s $CMD /usr/local/bin/kctx || alias kctx=$CMD
fi
if [ $(command -v kubens) ] && ! [ $(command -v kns) ]; then
CMD="$(which kubens)"
ln -s $CMD /usr/local/bin/kns || alias kns=$CMD
fi
#https://github.com/jeffkaufman/icdiff
alias diff="icdiff"
alias gd="git icdiff"
# https://github.com/sharkdp/bat
batdiff() {
git diff --name-only --relative --diff-filter=d | xargs bat --diff
}
#fzf
if type rg &> /dev/null; then
export FZF_DEFAULT_COMMAND='rg --files'
export FZF_DEFAULT_OPTS='-m --height 50% --border'
fi
#fd() {
#local dir
#dir=$(find ${1:-.} -path '*/\.*' -prune \
#-o -type d -print 2> /dev/null | fzf +m) &&
#cd "$dir"
#}
## type "fo" to open a file in its default application by hiting ctrl + o when
## the file is selected
#fo() {
#x=$(preview)
#folder_path=$(echo $x | cut -d '.' -f 1,1 | rev | cut -d "/" -f2- | rev);
#cd $folder_path
#nvim $(echo $x | rev | cut -d '/' -f 1,1 | rev)
#}
#
export NVM_DIR="$HOME/.nvm"
[ -s "/Users/tyler.simpson/homebrew/opt/nvm/nvm.sh" ] && \. "/Users/tyler.simpson/homebrew/opt/nvm/nvm.sh" # This loads nvm
[ -s "/Users/tyler.simpson/homebrew/opt/nvm/etc/bash_completion.d/nvm" ] && \. "/Users/tyler.simpson/homebrew/opt/nvm/etc/bash_completion.d/nvm" # This loads nvm bash_completion
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
ZSH_DISABLE_COMPFIX='true'
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
alias ls='ls -G'
#################################################
### Colorize Man pages
#################################################
#export MANPAGER="sh -c 'col -bx | bat -l man -p'"
#man 2 select
#export MANROFFOPT='-c'
#export LESS_TERMCAP_mb=$(tput bold; tput setaf 2)
#export LESS_TERMCAP_md=$(tput bold; tput setaf 6)
#export LESS_TERMCAP_me=$(tput sgr0)
#export LESS_TERMCAP_so=$(tput bold; tput setaf 3; tput setab 4)
#export LESS_TERMCAP_se=$(tput rmso; tput sgr0)
#export LESS_TERMCAP_us=$(tput smul; tput bold; tput setaf 7)
#export LESS_TERMCAP_ue=$(tput rmul; tput sgr0)
#export LESS_TERMCAP_mr=$(tput rev)
#export LESS_TERMCAP_mh=$(tput dim)
# The following lines were added by compinstall
zstyle ':completion:*' completer _expand _complete _ignored _correct _approximate
zstyle ':completion:*' max-errors 3 not-numeric
zstyle :compinstall filename '/Users/tsimpson/.zshrc'
neofetch
# To customize prompt, run `p10k configure` or edit ~/.p10k.zsh.
[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh
export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"
source ~/powerlevel10k/powerlevel10k.zsh-theme
export WASMTIME_HOME="$HOME/.wasmtime"
export PATH="$WASMTIME_HOME/bin:$PATH"
export PATH="/Users/tyler.simpson/homebrew/opt/openjdk/bin:$PATH"
export CPPFLAGS="-I/Users/tyler.simpson/homebrew/opt/openjdk/include"
|
JavaScript
|
UTF-8
| 414 | 3.15625 | 3 |
[] |
no_license
|
class Tanker {
constructor(x, y, width, height) {
var options = {
isStatic: true
}
this.body = Bodies.rectangle(x, y, width, height, options);
this.width = width;
this.height = height;
this.x= x;
this.y= y;
};
display(){
var pos =this.body.position;
fill(225)
rect(this.body.position.x,this.body.position.y, this.width, this.height);
}
}
|
PHP
|
UTF-8
| 18,171 | 2.609375 | 3 |
[] |
no_license
|
<?php
class SQLiquid {
protected $_init_done;
protected $_null_result;
protected $_where;
protected $_or_where;
protected $_join;
protected $_groupby;
protected $_order;
protected $_debug;
protected $_pretend;
protected $_cols;
protected $_fields;
protected $_table;
public $_db;
/**
* Can instantiate with a pkey, or an array (or object) of values to be loaded
*/
public function __construct($load_id=false,$fields='')
{
$this->_init();
if ($load_id)
{
if (is_numeric($load_id))
{
$this->loadById($load_id,$fields);
}
else
{
$this->loadValset($load_id);
}
}
}
protected function _init()
{
static $schema;
$CI = get_instance();
$this->_db = $CI->db;
$this->_null_result = false;
$this->_table = strtolower(substr(get_class($this),0,-6));
$table = $this->_table;
if (!isset($schema[$table]))
{
$cache_key = "Schema: $table";
//if (!$schema[$table] = MCache::get($cache_key))
{
$q = $CI->db->query("DESCRIBE $table");
$cols = $q->result();
//var_dump($cols);
foreach ($cols as $r)
{
if ($r->Null == 'YES')
{
$r->Type .= ' NULL';
}
$this->_cols[$r->Field] = $r->Type;
}
// Get subclass defined cols (override table desc)
$cols = get_object_vars($this);
foreach ($cols as $col_name=>$col_val)
{
if (substr($col_name,0,1) != '_')
{
$this->_cols[$col_name] = $col_val;
}
}
$this->_loadAttribs();
$schema[$table] = $this->_cols;
//MCache::put($cache_key,$schema[$table]);
}
}
$this->_cols = $schema[$table];
foreach ($this->_cols as $k=>$v)
{
$this->$k = null;
}
$this->_init_done = true;
}
public function getCols()
{
return $this->_cols;
}
/**
* This prevents trying to set fields which dont exist
*/
public function __set($key,$val)
{
//if ($this->_init_done && !isset($this->$key))
if ($this->_init_done && !isset($this->$key) && substr($key,0,1) != '_')
{
echo "Field '$key' does not exist <br/>\n";
return;
}
$this->$key = $val;
}
public function __toString()
{
if ($this->_null_result)
{
return '0';
}
else
{
return '1';
}
}
public function __call($field, $arguments)
{
if (!empty($field) && isset($this->_cols[$field]))
{
$attr = $this->_cols[$field];
//var_dump($this->_cols);
return new DataProp($this->_table,$field,$this->$field,$attr);
}
else
{
echo "$field not found in model";
return new StdClass;
}
}
/**
* Loads values to instance from DB
*
* @param integer $load_id
* @param string $fields
* @return bool
*/
public function loadById($load_id='',$fields='')
{
if ($load_id)
{
$pkey = $this->_get_pkey();
$this->$pkey = $load_id;
}
$arr = $this->get($fields,1);
if (is_array($arr) && isset($arr[0]))
{
foreach ($arr[0] as $key=>$val)
{
$this->$key = $val;
}
return true;
}
else
{
$this->_null_result = true;
return false;
}
}
/**
* Loads values into instance
*
* @param array $arr OR stdClass
*/
public function loadValset($arr)
{
if (is_array($arr))
{
foreach ($this->_cols as $key=>$val)
{
if (isset($arr[$key]) && $arr[$key] !== null)
{
$this->$key = $arr[$key];
}
}
}
elseif ($arr instanceof stdClass)
{
foreach ($this->_cols as $key=>$val)
{
if (isset($arr->$key) && $arr->$key !== null)
{
$this->$key = $arr->$key;
}
}
}
}
/**
* Loads values from DataProp rendered Post
* Example: users__fname
*
* TODO change naming format to "data[cms_sites][all_reviews]"
*
* @param array $arr
*/
public function loadPost($arr)
{
$table_key = $this->_table.'__';
foreach ($this->_cols as $key=>$val)
{
$arr_key = $table_key.$key;
if (isset($arr[$arr_key]) && $arr[$arr_key] !== null)
{
$this->$key = $arr[$arr_key];
}
}
}
/**
* Selects from DB, returns array
*
* @param string $fields
* @param integer $limit
* @param integer $offset
* @param bool $count_only
* @return array
*/
public function get($fields='', $limit=false, $offset=false, $count_only=false)
{
$table = $this->_table;
$join = '';
$where = '';
$or_where = '';
$order = '';
foreach ($this->_cols as $key=>$val)
{
// automatically add a filter for values we already have
if ($this->$key !== null)
{
if (!isset($auto_where))
{
$auto_where = array();
}
$auto_where[] = "(`$table`.$key = '".addslashes($this->$key)."')";
}
}
if (empty($fields))
{
$fields = "`$table`.*";
}
if (isset($this->_fields))
{
$fields .= ', '.substr($this->_fields,0,-2);
}
if (is_array($this->_join))
{
$join = implode(' ',$this->_join);
$add_ins[] = $join;
}
if (isset($auto_where) && is_array($auto_where))
{
$where = 'WHERE '.implode(' AND ',$auto_where);
}
if (is_array($this->_where))
{
if (empty($where))
{
$where = 'WHERE '.implode(' AND ',$this->_where);
}
else
{
$where .= ' AND '.implode(' AND ',$this->_where);
}
}
$add_ins[] = $where;
if (is_array($this->_or_where))
{
if (empty($where))
{
$or_where = 'WHERE '.implode(' OR ',$this->_or_where);
}
else
{
$where .= ' AND '.implode(' AND ',$this->_or_where);
}
$add_ins[] = $or_where;
}
if (is_array($this->_groupby))
{
$groupby = 'GROUP BY '.implode(' ',$this->_groupby);
$add_ins[] = $groupby;
}
if (is_array($this->_order))
{
$order = 'ORDER BY '.implode(', ',$this->_order);
$add_ins[] = $order;
}
if ($limit > 0)
{
$add_ins[] = "LIMIT $limit";
}
if ($offset > 0)
{
$add_ins[] = "OFFSET $offset";
}
if (is_array($add_ins))
{
$add_ins = ' '.implode(' ',$add_ins);
}
if ($count_only)
{
$sql = "SELECT COUNT(*) AS count FROM `{$table}`{$add_ins}";
}
else
{
$sql = "SELECT {$fields} FROM `{$table}`{$add_ins}";
}
if ($this->_debug)
{
echo "Ran SQL: \"$sql\"\n";
}
$q = $this->_db->query($sql);
if ($count_only)
{
$q = $q->result();
return $q[0]->count;
}
else
{
return $q->result();
}
}
/**
* Returns one row
*/
public function getOne($fields='')
{
$res = $this->get($fields, 1);
if (isset($res[0]))
{
return $res[0];
}
return false;
}
/**
* Returns one column from one row
*/
function getVal($fields='')
{
$res = $this->getOne($fields);
if (is_object($res))
{
$field = array_keys(get_object_vars($res));
if (is_array($field))
{
$field = $field[0];
return $res->$field;
}
}
}
/**
* Returns an array like $[field1] = field2;
*/
function getList($fields='', $limit=false, $offset=false)
{
$res = $this->get($fields, $limit, $offset);
if (is_array($res) && isset($res[0]) && is_object($res[0]))
{
$fields_list = explode(',',$fields);
if (count($fields_list) != 2)
{
$fields_list = array_keys(get_object_vars($res[0]));
}
$key = trim($fields_list[0]);
$val = trim($fields_list[1]);
foreach ($res as $r)
{
$ret[$r->$key] = $r->$val;
}
return $ret;
}
return false;
}
/**
* Returns an array like $[field1] = row;
*/
public function getIndexed($fields='', $limit=false, $offset=false)
{
$res = $this->get($fields, $limit, $offset);
if ($res[0] && is_object($res[0]))
{
$key = array_keys(get_object_vars($res[0]));
$key = $key[0];
foreach ($res as $r)
{
$ret[$r->$key] = $r;
}
return $ret;
}
return false;
}
/**
* Adds a join to the get() query
*
* Each field can have an alias
* Example: username as created_by
*
* @param string $table name of foreign table to join with
* @param string $join_key name of local field which holds primary key of foreign table
* @param string $fields one or more fields to select from the foreign table delimited by commas
* @param string $pkey primary key of foreign table
* @param string $jointype
*/
public function join($table, $join_key, $fields='', $jointype='LEFT')
{
static $join_id = 0;
$join_id++;
$join_key = explode('=',$join_key);
if (!isset($join_key[1]))
{
$join_key[1] = $join_key[0];
}
$join_src = '';
if (isset($this->_cols[$join_key[0]]))
{
$join_src = "`$this->_table`.";
}
@list($table, $t_alias) = explode(' ',$table);
if (!$t_alias)
{
$t_alias = 'join'.$join_id;
}
if ($fields)
{
$fields = explode(',',$fields);
foreach ($fields as $field)
{
$field = trim($field);
$this->_fields .= "`$t_alias`.{$field}, ";
}
}
$this->_join[] = "$jointype JOIN `$table` AS $t_alias ON {$join_src}{$join_key[0]} = `$t_alias`.{$join_key[1]}";
}
public function delete()
{
$table = $this->_table;
foreach ($this->_cols as $key=>$val)
{
if ($this->$key !== null)
{
$where[] = "`$table`.$key = '".addslashes($this->$key)."'";
}
}
// CANT DELETE WITHOUT _SOME_ CONDITION
if (is_array($where))
{
$where = implode(' AND ',$where);
$sql = "DELETE FROM `{$table}` WHERE $where";
if ($this->_pretend)
{
echo "Pretend Ran SQL: \"$sql\"\n";
}
else
{
if ($this->_debug)
{
echo "Ran SQL: \"$sql\"\n";
}
$this->_db->query($sql);
}
return true;
}
return false;
}
/**
* Determines Add or Update operation
*
* @return bool
*/
public function save()
{
$pkey = $this->_get_pkey();
if (empty($this->$pkey))
{
return $this->add();
}
return $this->update();
}
/**
* Insert a record
*
* @return bool
*/
public function add()
{
if (!$this->validate())
{
return $this->_error;
}
$pkey = $this->_get_pkey();
$values = '';
$fields = '';
foreach ($this->_cols as $key=>$val)
{
if ($key == $pkey) continue;
if ($this->$key !== null)
{
$fields .= "`$key`, ";
if (is_object($this->$key) && $this->$key instanceof SqlFunc)
{
$values .= $this->$key.', ';
}
else
{
$values .= "'".addslashes($this->$key)."', ";
}
}
}
$fields = substr($fields,0,-2);
$values = substr($values,0,-2);
$sql = "INSERT INTO `$this->_table` ($fields) VALUES ($values)";
if ($this->_debug)
{
echo "Ran SQL: \"$sql\"\n";
}
$this->_db->query($sql);
$this->$pkey = $this->_db->insert_id();
return true;
}
/**
* Update a record
*
* @return bool
*/
public function update($fields='')
{
if (!$this->validate())
{
//throw new Exception('not validate');
return $this->_error;
}
$pkey = $this->_get_pkey();
if (empty($this->$pkey))
{
return;
}
// optionally specify fields to update
if ($fields)
{
$tmp = explode(',',$fields);
$fields = array();
foreach ($tmp as $v)
{
$fields[$v] = '';
}
}
else
{
$fields = $this->_cols;
}
$values = '';
foreach ($fields as $key=>$val)
{
$val = $this->$key;
if ($val !== null && $key != $pkey)
{
$attribs = $this->_cols[$key];
if (strstr($key,'roll'))
{
if ($val === '' && $attribs['type'] == 'int' && $attribs['null'])
{
$val = new SqlFunc('NULL');
}
}
if (is_object($val) && $val instanceof SqlFunc)
{
$values .= "`$key`={$val}, ";
}
else
{
$values .= "`$key`='".addslashes($val)."', ";
}
}
}
$values = substr($values,0,-2);
if (!empty($values))
{
$sql = "UPDATE `$this->_table` SET $values WHERE `$pkey` = '{$this->$pkey}'";
if ($this->_debug)
{
echo "Ran SQL: \"$sql\"\n";
}
$this->_db->query($sql);
return true;
}
return false;
}
/**
* Adds a SQL conditional
*
* Example:
* id = 1
*
* @param string $sql
*/
public function where($sql)
{
if (!isset($this->_where))
{
$this->_where = array();
}
$this->_where[] = "($sql)";
}
public function orWhere($sql)
{
if (!isset($this->_or_where))
{
$this->_or_where = array();
}
$this->_or_where[] = "($sql)";
}
/**
* Adds an SQL ORDER BY
*
* @param string $field name of field with optional desc\asc seperated by one space
*/
public function order($field)
{
$this->_order[] = "`$field`";
}
/**
* Adds an SQL GROUP BY
*
* @param string $sql
*/
public function group($sql)
{
if (!isset($this->_groupby))
{
$this->_groupby = array();
}
$this->_groupby[] = "($sql)";
}
public function validate()
{
$valid = true;
foreach ($this->_cols as $key=>$attrib)
{
//var_dump($this->$key);
//var_dump($attrib);exit;
$val = (string) $this->$key;
if ($val === '')
{
if (isset($attrib['required']))
{
$valid = false;
$this->addError($key,'Cannot be empty');
}
else
{
//var_dump($key.' not req');
continue;
}
}
$type = '';
if (isset($attrib['type']))
{
$type = $attrib['type'];
switch ($type)
{
case 'int':
if (!is_numeric($val))
{
$valid = false;
$this->addError($key,'Must be numeric');
}
break;
case 'ip':
// TODO
//$valid = false;
//$this->addError($key,"Invalid $type");
break;
case 'email':
// TODO
//$valid = false;
//$this->addError($key,"Invalid $type");
break;
}
}
if (isset($attrib['maxlength']))
{
if ($type == 'str' && strlen($val) > $attrib['maxlength'])
{
$valid = false;
$this->addError($key,"Exceeds maxlength {$attrib['maxlength']}");
}
}
if (isset($attrib['match']))
{
if (!preg_match($attrib['match'],$val))
{
$valid = false;
$this->addError($key,"Does not match {$attrib['match']}");
}
}
}
if ($this->_debug)
{
if (isset($this->_error) && !empty($this->_error))
{
var_dump($this->_error);
}
}
return $valid;
}
public function required($field)
{
$this->addValidation($field,'required');
}
public function addValidation($field,$val)
{
if (isset($this->_cols[$field]))
{
if (is_array($this->_cols[$field]))
{
if (is_array($val))
{
$key = array_keys($val);
$this->_cols[$field][$key[0]] = $val[$key[0]];
}
else
{
$this->_cols[$field][$val] = true;
}
}
}
}
protected function _parseColAttribs($val)
{
preg_match("`([\w]+)(\(.+\))?`i",$val,$m);
$attrib = array();
if (strstr($val,'NULL'))
{
$attrib['null'] = true;
}
switch ($m[1])
{
case 'pkey':
$attrib['type'] = 'pkey';
$attrib['maxlength'] = substr($m[2],1,-1);
break;
case 'decimal':
$attrib['type'] = 'int';
break;
case 'int':
$attrib['type'] = 'int';
$attrib['maxlength'] = substr($m[2],1,-1);
break;
case 'varchar':
$attrib['maxlength'] = substr($m[2],1,-1);
$attrib['type'] = 'str';
break;
case 'text':
case 'longtext':
$attrib['type'] = 'str';
$attrib['type_ext'] = 'textarea';
break;
case 'enum':
$attrib['type'] = 'enum';
$attrib['vals'] = explode(',',substr(str_replace("'",'',$m[2]),1,-1));
break;
}
return $attrib;
}
/**
* This is done so that _cols will continue to hold field attribs
* while the public facing properties are null
*
*/
protected function _loadAttribs()
{
$i=0;
foreach ($this->_cols as $key=>$val)
{
if (is_string($val))
{
if ($i == 0)
{
$this->_cols[$key] = $this->_parseColAttribs('pkey(11)');
}
else
{
$this->_cols[$key] = $this->_parseColAttribs($val);
}
}
$i++;
}
}
public function _get_pkey()
{
if (!isset($this->_pkey))
{
$pkey = array_keys($this->_cols);
$this->_pkey = $pkey[0];
}
return $this->_pkey;
}
protected function addError($field, $message)
{
$this->_error[$field][] = $message;
}
public function getError($field='')
{
if ($field)
{
return $this->_error[$field];
}
else
{
return $this->_error;
}
}
public function debug($bool=1)
{
$this->_debug = $bool;
}
public function pretend($bool=1)
{
$this->_pretend = $bool;
}
}
class SqlFunc
{
function __construct($val)
{
$this->val = $val;
}
function __toString()
{
return (string) $this->val;
}
}
class DataProp
{
public $table;
public $field;
public $field_val;
public $attr;
function __construct($table,$field,$field_val,$attr)
{
$this->table = $table;
$this->field = $field;
$this->field_val = $field_val;
$this->attr = $attr;
}
function __toString()
{
//return $this->field_val;
return $this->render();
}
public function render($type_override='',$style='')
{
$html = '';
$table = $this->table;
$field = $this->field;
if ($type_override)
{
$type = $type_override;
}
else
{
$type = $this->attr['type'];
if ($this->attr['type_ext'])
{
$type = $this->attr['type_ext'];
}
}
//var_dump($field,$attr);
if (!empty($style))
{
$style = "style=\"$style\" ";
}
$size = '';
switch ($type)
{
case 'pkey':
$html = Html::input($table.'__'.$field,$this->field_val,'hidden');
break;
case 'textarea':
if ($this->attr['maxlength'])
{
$size = 'maxlength="'.$this->attr['maxlength'].'" ';
}
$html = '<textarea class="mdata" cols="70" rows="6" id="'.$table.'__'.$field.'" name="'.$table.'__'.$field.'" '.$size.$style.'>'.$this->field_val.'</textarea>';
break;
case 'enum':
$html = Html::select($table.'__'.$field,$this->attr['vals'],$this->field_val);
break;
default:
if ($this->attr['maxlength'])
{
if ($this->attr['maxlength'] > 80)
{
$size = 'size="80" ';
}
else
{
$size = 'size="'.$this->attr['maxlength'].'" ';
}
}
$html = '<input class="mdata" id="'.$table.'__'.$field.'" name="'.$table.'__'.$field.'" '.$size.$style.'value="'.$this->field_val.'" />';
}
return $html;
}
}
|
Python
|
UTF-8
| 551 | 3.375 | 3 |
[] |
no_license
|
from bs4 import BeautifulSoup
import requests
def scrapeSite(url,out):
r = requests.get(url)
txt = r.text
htmlCode = BeautifulSoup(txt,'html.parser')
if htmlCode.h1:
ans = htmlCode.find_all('h1')
for i in ans:
out.write(str(i.string) + "\n")
if htmlCode.p:
ans = htmlCode.find_all('p')
for i in ans:
out.write(str(i.string) + "\n")
try:
url = input("Enter a url:")
out = open("out6.txt","w")
scrapeSite(url,out)
out.close()
except IOError as e:
print(e)
|
Java
|
WINDOWS-1250
| 6,611 | 2.96875 | 3 |
[] |
no_license
|
package us.lsi.graphs.search;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.jgrapht.Graph;
import org.jgrapht.GraphPath;
import org.jgrapht.Graphs;
import org.jgrapht.graph.GraphWalk;
import us.lsi.common.Preconditions;
import us.lsi.common.TriFunction;
import us.lsi.flujossecuenciales.Iterators;
import us.lsi.graphs.virtual.ActionSimpleEdge;
import us.lsi.graphs.virtual.EGraph;
/**
* @author migueltoro
*
* @param <V> El tipo de los vértices
* @param <E> El tipo de las aristas
*
* Distintos tipos de búsquedas sobre grafos
*
*/
public interface GSearch<V,E> extends Iterator<V>, Iterable<V> {
/**
* @param <V> El tipo de los vértices
* @param <E> El tipo de las aristas
* @param graph Un grafo
* @param initialVertex El vértice inicial
* @param nextEdge
* @return Un algoritmo de búsqueda voraz siguiendo las aristas del grafo
*/
public static <V, E> GreedySearchOnGraph<V, E> greedy(
Graph<V, E> graph,
V initialVertex, Comparator<E> nextEdge) {
return new GreedySearchOnGraph<V, E>(graph, initialVertex, nextEdge);
}
/**
* @param <V> El tipo de los vértices
* @param <E> El tipo de las aristas
* @param initialVertex El vértice inicial
* @param nextAction La acción a tomar desde el vértice actual
* @param nextVertex El vértice obtenido siguiendo un acción
* @param nextEdge La arista siguiendo una acción de un vértice al siguiente
* @return Un algoritmo voraz
*/
public static <V, E extends ActionSimpleEdge<V, A>, A> GreedySearch<V, E, A> greedy(
V initialVertex,
Function<V, A> nextAction,
BiFunction<V, A, V> nextVertex,
TriFunction<V, V, A, E> nextEdge) {
return new GreedySearch<V, E, A>(initialVertex, nextAction, nextVertex, nextEdge);
}
/**
* @param <V> El tipo de los vértices
* @param <E> El tipo de las aristas
* @param g Un grafo
* @param startVertex El vrtice inicial
* @return Una algoritmo de búsqueda en profundidad
*/
public static <V, E> DephtSearch<V, E> depth(Graph<V, E> g, V startVertex) {
return new DephtSearch<V, E>(g, startVertex);
}
/**
* @param <V> El tipo de los vértices
* @param <E> El tipo de las aristas
* @param g Un grafo
* @param startVertex El vrtice inicial
* @return Una algoritmo de búsqueda en anchura
*/
public static <V, E> BreadthSearch<V, E> breadth(Graph<V, E> g, V startVertex) {
return new BreadthSearch<V, E>(g, startVertex);
}
/**
* @param <V> El tipo de los vértices
* @param <E> El tipo de las aristas
* @param graph Un grafo
* @param initial El vértice inicial
* @return Una algoritmo de búsqueda de Dijsktra
*/
public static <V, E> AStarSearch<V, E> dijsktra(
EGraph<V, E> graph, V initial) {
return new AStarSearch<V, E>(graph, initial, null, (v1,v2)->0.);
}
/**
* @param <V> El tipo de los vértices
* @param <E> El tipo de las aristas
* @param graph Un grafo
* @param initial El vértice inicial
* @param end El vértice final
* @param heuristic La heurística
* @return Una algoritmo de búsqueda de AStar
*/
public static <V, E> AStarSearch<V, E> aStar(
EGraph<V, E> graph, V initial, V end,
BiFunction<V, V, Double> heuristic) {
return new AStarSearch<V, E>(graph, initial, end, heuristic);
}
E getEdgeToOrigin(V v);
boolean isSeenVertex(V v);
Graph<V, E> getGraph();
Iterator<V> iterator();
V initialVertex();
/**
* @param v Un vértice
* @return El vértice siguiente el camino hacia el origen
*/
default V getParent(V v) {
return Graphs.getOppositeVertex(this.getGraph(), this.getEdgeToOrigin(v), v);
}
/**
* @return Un flujo con los vértices del grafo recorridos según la búsqueda seguida
*/
default public Stream<V> stream(){
return Iterators.asStream(this.iterator());
}
/**
* @param p Un predicado
* @return Encuentra el priemr vértice que cumple el predicado según la búsqueda seguida
*/
default public V find(Predicate<V> p) {
if(p.test(initialVertex())) return initialVertex();
Optional<V> r = this.stream().filter(p).findFirst();
Preconditions.checkArgument(r.isPresent(), "No se ha encontrado un vrtice que cumpla el predicado");
return r.get();
}
/**
* @param v Un vértice
* @return Encuentra el priemr vértice que que es igual a v según la búsqueda seguida
*/
default public V find(V v) {
return find(x->x.equals(v));
}
/**
* @param v Un vértice
* @return Encuentra el peso del camino hasta el primer vértice que es igual a v según la búsqueda seguida
*/
default public Double findWeight(V v) {
if(v.equals(initialVertex())) return 0.;
V vf = find(v);
return this.pathFromOrigin(vf).getWeight();
}
/**
* @pre El vértice v tiene que haber sido visitado
* @param v Un vértice
* @return El camino hacia el origen
*/
default public GraphPath<V,E> pathToOrigin(V v){
if(v.equals(initialVertex())) return new GraphWalk<V,E>(this.getGraph(),List.of(initialVertex()),0.);
Preconditions.checkArgument(this.getEdgeToOrigin(v)!=null,String.format("El vrtice %s no ha sido visitado",v));
E edge = this.getEdgeToOrigin(v);
List<V> path = new ArrayList<>();
path.add(v);
Double w = 0.;
while(edge!=null) {
w = w+this.getGraph().getEdgeWeight(edge);
v = this.getParent(v);
path.add(v);
edge = this.getEdgeToOrigin(v);
}
return new GraphWalk<V,E>(this.getGraph(),path,w);
}
/**
* @pre El vértice v tiene que haber sido visitado
* @param v Un vértice
* @return El camino hacia el origen
*/
default public GraphPath<V,E> pathFromOrigin(V v){
if(v.equals(initialVertex())) return new GraphWalk<V,E>(this.getGraph(),List.of(initialVertex()),0.);
GraphPath<V,E> gp = pathToOrigin(v);
List<V> vertices = gp.getVertexList();
Collections.reverse(vertices);
return new GraphWalk<V,E>(this.getGraph(),vertices,gp.getWeight());
}
}
|
Java
|
UTF-8
| 3,700 | 2.21875 | 2 |
[] |
no_license
|
package vn.wae.spring.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.URL;
@Entity
@Table(name = "team")
public class Teammate implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6561751438228980238L;
@Id
@Column(name = "`id`")
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
@Column(name = "`name`")
@NotBlank(message = "Name is not blank")
String name;
@Column(name = "`avatar`")
@NotBlank(message = "Avatar is not blank")
@URL(message = "URL format fail")
String avatar;
@Column(name = "`title`")
@NotBlank(message = "Title is not blank")
String title;
@Column(name = "`short_desc`")
String shortDesc;
@Column(name = "`facebook`")
@URL(message = "URL format fail")
String facebook;
@Column(name = "`twitter`")
String twitter;
@Column(name = "`linkedin`")
@URL(message = "URL format fail")
String linkedIn;
@Column(name = "`google_plus`")
String googlePlus;
@Column(name = "`status`", columnDefinition = "TINYINT(1)")
boolean status;
public Teammate() {
}
public Teammate(int id, String name, String avatar, String title, String shortDesc, String facebook, String twitter,
String linkedIn, String googlePlus, boolean status) {
this.id = id;
this.name = name;
this.avatar = avatar;
this.title = title;
this.shortDesc = shortDesc;
this.facebook = facebook;
this.twitter = twitter;
this.linkedIn = linkedIn;
this.googlePlus = googlePlus;
this.status = status;
}
public Teammate(String name, String avatar, String title, String shortDesc, String facebook, String twitter,
String linkedIn, String googlePlus, boolean status) {
this.name = name;
this.avatar = avatar;
this.title = title;
this.shortDesc = shortDesc;
this.facebook = facebook;
this.twitter = twitter;
this.linkedIn = linkedIn;
this.googlePlus = googlePlus;
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getShortDesc() {
return shortDesc;
}
public void setShortDesc(String shortDesc) {
this.shortDesc = shortDesc;
}
public String getFacebook() {
return facebook;
}
public void setFacebook(String facebook) {
this.facebook = facebook;
}
public String getTwitter() {
return twitter;
}
public void setTwitter(String twitter) {
this.twitter = twitter;
}
public String getLinkedIn() {
return linkedIn;
}
public void setLinkedIn(String linkedIn) {
this.linkedIn = linkedIn;
}
public String getGooglePlus() {
return googlePlus;
}
public void setGooglePlus(String googlePlus) {
this.googlePlus = googlePlus;
}
public boolean getStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
@Override
public String toString() {
return "Teammate [id=" + id + ", name=" + name + ", avatar=" + avatar + ", title=" + title + ", shortDesc="
+ shortDesc + ", facebook=" + facebook + ", twitter=" + twitter + ", linkedIn=" + linkedIn
+ ", googlePlus=" + googlePlus + ", status=" + status + "]";
}
}
|
JavaScript
|
UTF-8
| 925 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
import * as React from 'react';
import Action from '../actions/TodoAction';
import Store from '../stores/TodoStore';
class ListItem extends React.Component {
constructor(props){
super(props);
this.onClickHandler = this.onClickHandler.bind(this);
this.action = new Action();
}
onClickHandler(e){
e.preventDefault();
this.action.changeState(this.props.todo);
}
render(){
let { todo } = this.props;
function isDone(){
if(todo.isDone){
return ' is-done';
}
return '';
}
return (
<li className="list-item{isDone()}">
<div>{todo.title}</div>
<input type="checkbox" checked={todo.isDone} onClick={this.onClickHandler} />
</li>
);
}
}
ListItem.propTypes = {
todo: React.PropTypes.object
};
export default ListItem;
|
C++
|
UTF-8
| 603 | 2.984375 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
int trapRainWater(const vector<int>&v)
{
int size=v.size();
vector<int>lMax(size),rMax(size);
lMax[0]=v[0];
for(int i=1;i<size;i++)
{
lMax[i]=max(lMax[i-1],v[i]);
}
rMax[size-1]=v[size-1];
for(int j=size-2;j>=0;j--)
{
rMax[j]=max(rMax[j+1],v[j]);
}
int count=0;
for(int i=0;i<size;i++)
{
count+=(min(lMax[i],rMax[i])-v[i]);
}
return count;
}
int main()
{
vector<int>vec={3, 0, 2, 0, 4};
int trap=trapRainWater(vec);
cout<<"Total Trapped:"<<trap;
return 0;
}
|
JavaScript
|
UTF-8
| 2,695 | 3.171875 | 3 |
[] |
no_license
|
var Hamming = function(n){//2 to the n bits of parity
var blockSize = 1<<n;
var blockDataSize = blockSize - n - 1;
this.encode = function(bits){
var blocks = [];
var idx = 0;//index of the bit
while(idx < bits.length){
var block = [0];
blocks.push(block);
var cnt = 0;
for(var k = 0; k < n; k++){
block[1<<k] = 0;//initializing
}
for(var i = 0; i < n; i++){
var thisval = 1<<i;
var nextval = 1<<(i+1);
for(var j = thisval+1; j < nextval; j++){
block[j] = bits[idx] || 0;
idx++;
//nowincrementing the parity bits
for(var k = 0; k < n; k++){
//xor equal
block[1<<k] ^= ((j>>k)&1)&(block[j] || 0);
}
}
}
//block filled
}
return blocks;
};
this.decode = function(blocks){
var data = [];
for(var ii = 0; ii < blocks.length; ii++){
var block = blocks[ii];
var parities = [];
for(var i = 0; i < n; i++){
var thisval = 1<<i;
var nextval = 1<<(i+1);
for(var j = thisval+1; j < nextval; j++){
//now incrementing the parity bits
for(var k = 0; k < n; k++){
block[1<<k] ^= ((j>>k)&1)&(block[j] || 0);
//this should be 0 by the end
}
}
}
//tally of parity is the wrong address
var address = 0;
for(var k = 0; k < n; k++){
address += block[1<<k]<<k;
}
block[address] = [(block[address]^1)];//flip it and mark it
}
for(var i = 0; i < n; i++){
var thisval = 1<<i;
var nextval = 1<<(i+1);
for(var j = thisval+1; j < nextval; j++){
data.push(block[j]);
}
}
return data;
};
};
var hamming = new Hamming(4);
var data0 = [0,1,1,0,1,0,1,0,0,1,1];
console.log("original data: "+JSON.stringify(data0));
console.log("encoding");
var coded = hamming.encode(data0);
var erridx = 5;
coded[0][erridx] ^= 1;
console.log("introducing error at block 0 bit "+erridx);
//introducing error
console.log("blocks: "+JSON.stringify(coded));
var data1 = hamming.decode(coded);
console.log("corrected result: "+JSON.stringify(data1));
console.log("corrected bit has been marked by []");
|
Java
|
UTF-8
| 28,664 | 1.9375 | 2 |
[] |
no_license
|
package com.ratio.deviceService.data;
import android.content.Context;
import android.util.Log;
import com.ratio.deviceService.accessory.AccessoryConfig;
import com.ratio.deviceService.communication.provider.SleepDetailDB;
import com.ratio.deviceService.communication.provider.SleepDetailTB;
import com.ratio.deviceService.datamanager.AccessoryValues;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* Created by Mesogene on 2015/5/24.
*/
public class AccessoryDataParseUtil extends LocalDecode {
private static int todaySleep;
private int index = 0;
SleepDetailDB mSleepDetailDB = null;
long sleepEndtime = 0L;
long startSleep = 0L;
public AccessoryDataParseUtil(Context paramContext) {
super(paramContext);
}
private HashMap<String, AccessoryValues> _analysis(ArrayList<ArrayList<Integer>> paramArrayList) {
HashMap localHashMap = new HashMap();
this.mSleepDetailDB.open();
this.mSleepDetailDB.beginTransaction();
int i = -1;
this.sleepEndtime = 0L;
this.startSleep = 0L;
String str1 = "";
Iterator localIterator1 = paramArrayList.iterator();
ArrayList localArrayList;
while (true) {
if (!localIterator1.hasNext()) {
calcSleepInTransacntion(localHashMap);
long l9 = calStartTime(this.sleepEndtime);
insetDB(l9, -1);
long l10 = l9 + 200000L;
insetDB(l10, -1);
long l11 = l10 + 200000L;
insetDB(l11, -1);
this.sleepEndtime = (l11 + 200000L);
getSleepTotalIntrans(AccessoryConfig.userID, this.startSleep, this.sleepEndtime, localHashMap);
calTotalSleep(localHashMap);
Log.d(this.TAG, "parse over");
this.mSleepDetailDB.setTransactionSuccessful();
this.mSleepDetailDB.endTransaction();
this.mSleepDetailDB.close();
return localHashMap;
}
localArrayList = (ArrayList) localIterator1.next();
if (localArrayList.size() == 6) {
int j = 0;
int k = 0;
Iterator localIterator2 = localArrayList.iterator();
label212:
if (!localIterator2.hasNext()) {
i = 0;
if (j != 6)
if (k == 6)
i = 3;
break;
}
switch (i) {
default:
break;
case 0:
i = 1;
int m = ((Integer) localIterator2.next()).intValue();
if (m == 254) {
j++;
if (!localIterator2.hasNext()) {
i = 0;
if (j != 6)
if (k == 6)
i = 3;
break;
}
}
if (m != 253)
if (!localIterator2.hasNext()) {
i = 0;
if (j != 6)
if (k == 6)
i = 3;
break;
}
k++;
if (!localIterator2.hasNext()) {
i = 0;
if (j != 6)
if (k == 6)
i = 3;
break;
}
if (k == 6)
i = 3;
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
this.curTime = getTime(localArrayList);
if (!isInvalidTime(this.curTime)) {
str1 = getDateString(this.curTime);
AccessoryValues localAccessoryValues14 = null;
if (!localHashMap.containsKey(str1)) {
AccessoryValues localAccessoryValues13 = new AccessoryValues();
localAccessoryValues14 = localAccessoryValues13;
localHashMap.put(str1, localAccessoryValues14);
localAccessoryValues14.time = str1;
}
while (true) {
if (localAccessoryValues14.start_sport_time != 0L) {
AccessoryValues localAccessoryValues15 = localAccessoryValues14;
}
localAccessoryValues14.start_sport_time = this.curTime;
i = 2;
localAccessoryValues14 = (AccessoryValues) localHashMap.get(str1);
break;
}
AccessoryValues localAccessoryValues15 = localAccessoryValues14;
if (localAccessoryValues14.start_sport_time < this.curTime) ;
for (long l8 = localAccessoryValues14.start_sport_time; ; l8 = this.curTime) {
localAccessoryValues15.start_sport_time = l8;
break;
}
}
i = -1;
int[] arrayOfInt2 = getSportData(localArrayList);
filterSportResult(arrayOfInt2);
this.curTime = (600000L + this.curTime);
AccessoryValues localAccessoryValues8 = null;
if (!localHashMap.containsKey(str1)) {
AccessoryValues localAccessoryValues7 = new AccessoryValues();
localAccessoryValues8 = localAccessoryValues7;
localAccessoryValues8.time = str1;
localHashMap.put(str1, localAccessoryValues8);
}
while (true) {
if (arrayOfInt2[0] != 0) {
AccessoryValues localAccessoryValues12 = localAccessoryValues8;
localAccessoryValues12.sport_duration = (10 + localAccessoryValues12.sport_duration);
}
AccessoryValues localAccessoryValues9 = localAccessoryValues8;
localAccessoryValues9.steps += arrayOfInt2[0];
AccessoryValues localAccessoryValues10 = localAccessoryValues8;
localAccessoryValues10.calories += arrayOfInt2[1];
AccessoryValues localAccessoryValues11 = localAccessoryValues8;
localAccessoryValues11.distances += arrayOfInt2[2];
localAccessoryValues8 = (AccessoryValues) localHashMap.get(str1);
break;
}
i = 4;
this.curTime = getTime(localArrayList);
if (!isInvalidTime(this.curTime)) {
str1 = getDateString(this.curTime);
AccessoryValues localAccessoryValues5 = null;
long l3;
long l4;
long l5 = 0;
long l6 = 0;
String str3 = null;
if (!localHashMap.containsKey(str1)) {
AccessoryValues localAccessoryValues4 = new AccessoryValues();
localAccessoryValues5 = localAccessoryValues4;
localHashMap.put(str1, localAccessoryValues5);
localAccessoryValues5.time = str1;
if (this.startSleep == 0L)
this.startSleep = calStartTime(this.curTime);
if (this.sleepEndtime <= this.curTime)
l3 = this.curTime;
l3 = this.sleepEndtime;
this.sleepEndtime = l3;
this.sleepEndtime = calcuEndtime(this.sleepEndtime);
i = 5;
AccessoryValues localAccessoryValues6 = localAccessoryValues5;
if (localAccessoryValues5.tmpEndSleep <= this.curTime)
l4 = this.curTime;
l4 = localAccessoryValues5.tmpEndSleep;
localAccessoryValues6.tmpEndSleep = l4;
l5 = calcuEndtime(this.curTime);
l6 = calStartTime(localAccessoryValues5.tmpEndSleep);
localAccessoryValues5.tmpEndSleep = this.curTime;
str3 = "";
}
while (true) {
if (l6 < l5) {
localAccessoryValues5 = (AccessoryValues) localHashMap.get(str1);
l3 = this.curTime;
l4 = this.curTime;
break;
}
long l7 = l5;
try {
Long localLong2 = Long.valueOf(l7);
int i1 = -1;
if (localAccessoryValues5.sleepdetail.containsKey(localLong2))
i1 = ((Integer) localAccessoryValues5.sleepdetail.remove(localLong2)).intValue();
StringBuilder localStringBuilder2 = new StringBuilder(String.valueOf(str3));
str3 = "reduce " + localLong2 + " result:" + i1 + "\r\n";
l5 = 200000L + l5;
Long localLong3 = Long.valueOf(l5);
if (localAccessoryValues5.sleepdetail.containsKey(localLong3))
i1 = ((Integer) localAccessoryValues5.sleepdetail.remove(localLong3)).intValue();
l5 = 200000L + l5;
StringBuilder localStringBuilder3 = new StringBuilder(String.valueOf(str3));
str3 = "reduce " + localLong3 + " result:" + i1 + "\r\n";
Long localLong4 = Long.valueOf(l5);
if (localAccessoryValues5.sleepdetail.containsKey(localLong4))
i1 = ((Integer) localAccessoryValues5.sleepdetail.remove(localLong4)).intValue();
l5 = 200000L + l5;
StringBuilder localStringBuilder4 = new StringBuilder(String.valueOf(str3));
str3 = "reduce " + localLong4 + " result:" + i1 + "\r\n";
SleepDataUtil.saveInfo2File(str3);
} catch (Exception localException) {
localException.printStackTrace();
}
}
}
i = -1;
}
}
str1 = getDateString(this.curTime);
AccessoryValues localAccessoryValues2;
int[] arrayOfInt1 = new int[0];
String str2 = null;
long l1 = 0;
int n = 0;
if (!localHashMap.containsKey(str1)) {
AccessoryValues localAccessoryValues1 = new AccessoryValues();
localAccessoryValues2 = localAccessoryValues1;
localHashMap.put(str1, localAccessoryValues2);
localAccessoryValues2.time = str1;
arrayOfInt1 = getSportData(localArrayList);
str2 = "";
l1 = calStartTime(this.curTime);
n = 0;
if (n < arrayOfInt1.length) {
Long localLong1 = Long.valueOf(l1 + 1000 * (200 * n));
}
SleepDataUtil.saveInfo2File(str2);
AccessoryValues localAccessoryValues3 = localAccessoryValues2;
localAccessoryValues3.tmpEndSleep = (600000L + localAccessoryValues3.tmpEndSleep);
this.curTime = (600000L + this.curTime);
if (this.sleepEndtime <= this.curTime) ;
}
for (long l2 = this.sleepEndtime; ; l2 = this.curTime) {
this.sleepEndtime = l2;
this.sleepEndtime = calcuEndtime(this.sleepEndtime);
localAccessoryValues2 = (AccessoryValues) localHashMap.get(str1);
Long localLong1 = Long.valueOf(l1 + 1000 * (200 * n));
Integer localInteger1 = Integer.valueOf(0);
if (localAccessoryValues2.sleepdetail.containsKey(localLong1))
localInteger1 = (Integer) localAccessoryValues2.sleepdetail.get(localLong1);
StringBuilder localStringBuilder1 = new StringBuilder(String.valueOf(str2));
str2 = " add time " + localLong1;
Integer localInteger2 = Integer.valueOf(localInteger1.intValue() + arrayOfInt1[n]);
localAccessoryValues2.sleepdetail.put(localLong1, localInteger2);
n++;
if (n < arrayOfInt1.length) {
localLong1 = Long.valueOf(l1 + 1000 * (200 * n));
}
break;
}
return localHashMap;
}
private long calStartTime(long paramLong) {
return paramLong / 600000L * 600000L;
}
private void calTotalSleep(HashMap<String, AccessoryValues> paramHashMap) {
Object localObject1 = null;
long l = 0;
if ((paramHashMap != null) && (paramHashMap.size() > 0)) {
localObject1 = getDateString(System.currentTimeMillis());
if (paramHashMap.containsKey(localObject1)) {
l = ((AccessoryValues) paramHashMap.get(localObject1)).sleep_startTime;
localObject1 = paramHashMap.keySet().iterator();
}
}
while (true) {
if (!((Iterator) localObject1).hasNext())
return;
Object localObject2 = ((AccessoryValues) paramHashMap.get((String) ((Iterator) localObject1).next())).sleepdetail;
if ((localObject2 != null) && (((HashMap) localObject2).size() > 0)) {
localObject2 = ((HashMap) localObject2).keySet().iterator();
while (((Iterator) localObject2).hasNext())
if (((Long) ((Iterator) localObject2).next()).longValue() >= l)
todaySleep += 200;
}
}
}
private void calcSleepInTransacntion(HashMap<String, AccessoryValues> paramHashMap) {
if ((paramHashMap == null) || (paramHashMap.size() == 0))
return;
long l1 = calcuEndtime(System.currentTimeMillis());
Iterator localIterator1 = paramHashMap.keySet().iterator();
todaySleep = 0;
while (true) {
if (!localIterator1.hasNext())
return;
AccessoryValues localAccessoryValues = (AccessoryValues) paramHashMap.get((String) localIterator1.next());
localAccessoryValues.sleep_endTime = 0L;
localAccessoryValues.sleep_startTime = 0L;
long l2 = calcuEndtime(localAccessoryValues.start_sport_time);
insetDB(l2, -1);
l2 += 200000L;
insetDB(l2, -1);
l2 += 200000L;
insetDB(l2, -1);
Iterator localIterator2 = localAccessoryValues.sleepdetail.keySet().iterator();
while (localIterator2.hasNext()) {
Long localLong = (Long) localIterator2.next();
if (localLong.longValue() < l1) {
int i = ((Integer) localAccessoryValues.sleepdetail.get(localLong)).intValue();
insetDB(localLong.longValue(), i);
}
}
}
}
private long calcuEndtime(long paramLong) {
int j = 600000;
int i = j;
if (paramLong % j == 0L)
i = 0;
return paramLong / 600000L * 600000L + i;
}
public static long[] getCurrentData(HashMap<String, AccessoryValues> paramHashMap) {
if ((paramHashMap != null) && (paramHashMap.size() > 0)) {
long[] arrayOfLong = new long[17];
int i = 0;
Object localObject = null;
if (i >= arrayOfLong.length) {
localObject = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
if (paramHashMap.containsKey(localObject)) {
localObject = (AccessoryValues) paramHashMap.get(localObject);
arrayOfLong[0] = ((AccessoryValues) localObject).start_sport_time;
arrayOfLong[1] = ((AccessoryValues) localObject).sport_duration;
arrayOfLong[2] = ((AccessoryValues) localObject).steps;
arrayOfLong[3] = ((AccessoryValues) localObject).calories;
arrayOfLong[4] = ((AccessoryValues) localObject).distances;
arrayOfLong[10] = ((AccessoryValues) localObject).deepSleep;
arrayOfLong[11] = ((AccessoryValues) localObject).light_sleep;
arrayOfLong[12] = ((AccessoryValues) localObject).wake_time;
arrayOfLong[13] = todaySleep / 60;
arrayOfLong[14] = ((AccessoryValues) localObject).sleep_startTime;
arrayOfLong[15] = ((AccessoryValues) localObject).sleep_endTime;
}
localObject = paramHashMap.keySet().iterator();
}
AccessoryValues localAccessoryValues;
while (true) {
if (!((Iterator) localObject).hasNext()) {
todaySleep = 0;
arrayOfLong[i] = 0L;
i += 1;
return arrayOfLong;
}
localAccessoryValues = (AccessoryValues) paramHashMap.get(((Iterator) localObject).next());
if (arrayOfLong[5] != 0L)
if (arrayOfLong[5] < localAccessoryValues.start_sport_time) break;
arrayOfLong[5] = localAccessoryValues.start_sport_time;
arrayOfLong[6] += localAccessoryValues.sport_duration;
arrayOfLong[7] += localAccessoryValues.steps;
arrayOfLong[8] += localAccessoryValues.calories;
arrayOfLong[9] += localAccessoryValues.distances;
arrayOfLong[16] += localAccessoryValues.sleepmins;
}
if (arrayOfLong[5] < localAccessoryValues.start_sport_time) ;
for (long l = arrayOfLong[5]; ; l = localAccessoryValues.start_sport_time) {
arrayOfLong[5] = l;
break;
}
}
return null;
}
private String getDateString(long paramLong) {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date(paramLong));
}
public HashMap<String, AccessoryValues> analysisDatas(ArrayList<ArrayList<Integer>> paramArrayList) {
Object localObject1;
if ((paramArrayList == null) || (paramArrayList.size() < 1)) {
return null;
}
String str = "";
ArrayList localArrayList1 = new ArrayList();
ArrayList localArrayList2 = new ArrayList();
Object localObject2 = localArrayList2;
int i = 0;
Iterator localIterator1 = paramArrayList.iterator();
while (true) {
if (!localIterator1.hasNext()) {
SleepDataUtil.saveInfo2File(str);
localObject1 = _analysis(localArrayList1);
break;
}
Iterator localIterator2 = ((ArrayList) localIterator1.next()).iterator();
while (localIterator2.hasNext()) {
Integer localInteger = (Integer) localIterator2.next();
((ArrayList) localObject2).add(localInteger);
StringBuilder localStringBuilder1 = new StringBuilder(String.valueOf(str));
str = localInteger + " ";
i++;
if (i == 6) {
StringBuilder localStringBuilder2 = new StringBuilder(String.valueOf(str));
str = "\r\n";
i = 0;
localArrayList1.add(localObject2);
ArrayList localArrayList3 = new ArrayList();
localObject2 = localArrayList3;
}
}
}
return (HashMap<String, AccessoryValues>) localObject2;
}
public void getSleepTotalIntrans(String paramString, long paramLong1, long paramLong2, HashMap<String, AccessoryValues> paramHashMap) {
List localList = this.mSleepDetailDB.get(paramString, paramLong1, paramLong2);
ArrayList localArrayList = null;
Object localObject1 = null;
int j = 0;
int k = 0;
if ((localList != null) && (localList.size() > 0)) {
int i = localList.size();
localArrayList = new ArrayList();
AccessoryValues localAccessoryValues1 = new AccessoryValues();
localObject1 = localAccessoryValues1;
((AccessoryValues) localObject1).sleep_startTime = paramLong1;
((AccessoryValues) localObject1).sleep_endTime = paramLong2;
j = 0;
if (j >= i) {
if (localArrayList.size() == 0)
localArrayList.add(localObject1);
StringBuilder localStringBuilder2 = new StringBuilder(" find start begin from:");
String str2 = paramLong1 + " end:" + paramLong2;
Log.d(this.TAG, str2);
k = 0;
if (k < localArrayList.size()) {
AccessoryValues localAccessoryValues3 = (AccessoryValues) localArrayList.get(k);
}
if (localArrayList.size() == 0)
Log.e(this.TAG, "not find start or end");
}
}
while (true) {
assert localList != null;
SleepDetailTB localSleepDetailTB = (SleepDetailTB) localList.get(j);
if ((((AccessoryValues) localObject1).sleep_startTime == 0L) && (localSleepDetailTB.time != 0L)) {
Object localObject4 = localObject1;
Object localObject5 = localObject1;
long l3 = localSleepDetailTB.time;
((AccessoryValues) localObject5).sleep_endTime = l3;
((AccessoryValues) localObject4).sleep_startTime = l3;
}
do {
j++;
if (localSleepDetailTB.type != -1) {
Object localObject3 = localObject1;
if (((AccessoryValues) localObject1).sleep_endTime < localSleepDetailTB.time) ;
for (long l2 = localSleepDetailTB.time; ; l2 = ((AccessoryValues) localObject1).sleep_endTime) {
((AccessoryValues) localObject3).sleep_endTime = l2;
break;
}
}
}
while (localSleepDetailTB.type != -1);
Object localObject2 = localObject1;
if (((AccessoryValues) localObject1).sleep_endTime < localSleepDetailTB.time) ;
for (long l1 = localSleepDetailTB.time; ; l1 = ((AccessoryValues) localObject1).sleep_endTime) {
((AccessoryValues) localObject2).sleep_endTime = l1;
if (0L == ((AccessoryValues) localObject1).sleep_startTime)
break;
localArrayList.add(localObject1);
AccessoryValues localAccessoryValues2 = new AccessoryValues();
localObject1 = localAccessoryValues2;
break;
}
assert localArrayList != null;
AccessoryValues localAccessoryValues3 = (AccessoryValues) localArrayList.get(k);
String str3 = getDateString(localAccessoryValues3.sleep_endTime);
AccessoryValues localAccessoryValues5 = null;
long l5;
AccessoryValues localAccessoryValues6 = null;
if (!paramHashMap.containsKey(str3)) {
AccessoryValues localAccessoryValues4 = new AccessoryValues();
localAccessoryValues5 = localAccessoryValues4;
paramHashMap.put(str3, localAccessoryValues5);
localAccessoryValues5.time = str3;
if (localAccessoryValues5.sleep_startTime == 0L)
for (long l4 = localAccessoryValues5.sleep_endTime; ; l4 = localAccessoryValues3.sleep_endTime) {
localAccessoryValues6.sleep_endTime = l4;
k++;
localAccessoryValues5 = (AccessoryValues) paramHashMap.get(str3);
l5 = localAccessoryValues5.sleep_startTime;
localAccessoryValues5.sleep_startTime = localAccessoryValues3.sleep_startTime;
break;
}
AccessoryValues localAccessoryValues7 = localAccessoryValues5;
if (localAccessoryValues3.sleep_startTime >= localAccessoryValues5.sleep_startTime)
for (long l4 = localAccessoryValues5.sleep_endTime; ; l4 = localAccessoryValues3.sleep_endTime) {
localAccessoryValues6.sleep_endTime = l4;
k++;
localAccessoryValues5 = (AccessoryValues) paramHashMap.get(str3);
l5 = localAccessoryValues5.sleep_startTime;
localAccessoryValues5.sleep_startTime = localAccessoryValues3.sleep_startTime;
break;
}
l5 = localAccessoryValues3.sleep_startTime;
localAccessoryValues7.sleep_startTime = l5;
localAccessoryValues6 = localAccessoryValues5;
if (localAccessoryValues5.sleep_endTime <= localAccessoryValues3.sleep_endTime)
for (long l4 = localAccessoryValues5.sleep_endTime; ; l4 = localAccessoryValues3.sleep_endTime) {
localAccessoryValues6.sleep_endTime = l4;
k++;
localAccessoryValues5 = (AccessoryValues) paramHashMap.get(str3);
l5 = localAccessoryValues5.sleep_startTime;
localAccessoryValues5.sleep_startTime = localAccessoryValues3.sleep_startTime;
break;
}
return;
}
for (long l4 = localAccessoryValues5.sleep_endTime; ; l4 = localAccessoryValues3.sleep_endTime) {
localAccessoryValues6.sleep_endTime = l4;
k++;
localAccessoryValues5 = (AccessoryValues) paramHashMap.get(str3);
l5 = localAccessoryValues5.sleep_startTime;
localAccessoryValues5.sleep_startTime = localAccessoryValues3.sleep_startTime;
break;
}
String str1 = this.TAG;
StringBuilder localStringBuilder1 = new StringBuilder("not find detail between ");
Log.e(str1, paramLong1 + " end " + paramLong2);
}
}
public SleepDetailTB insetDB(long paramLong, int paramInt) {
SleepDetailTB localSleepDetailTB = this.mSleepDetailDB.get(AccessoryConfig.userID, paramLong);
if (localSleepDetailTB == null) {
localSleepDetailTB = new SleepDetailTB();
localSleepDetailTB.time = paramLong;
localSleepDetailTB.userid = AccessoryConfig.userID;
localSleepDetailTB.sleepvalue = paramInt;
localSleepDetailTB.type = getSleepLevelByTime(localSleepDetailTB.sleepvalue);
this.mSleepDetailDB.insert(localSleepDetailTB);
return localSleepDetailTB;
}
localSleepDetailTB.time = paramLong;
localSleepDetailTB.userid = AccessoryConfig.userID;
if (paramInt != -1)
if (localSleepDetailTB.sleepvalue > paramInt)
paramInt = localSleepDetailTB.sleepvalue;
for (localSleepDetailTB.sleepvalue = paramInt; ; localSleepDetailTB.sleepvalue = -1) {
localSleepDetailTB.type = getSleepLevelByTime(localSleepDetailTB.sleepvalue);
this.mSleepDetailDB.update(localSleepDetailTB);
break;
}
return localSleepDetailTB;
}
}
|
JavaScript
|
UTF-8
| 590 | 4.03125 | 4 |
[
"MIT"
] |
permissive
|
/* How to generate a Factorial number
*/
//Create a big-integer class
var bigInt = require("big-integer");
//This function returns the factorialization of nonnegative integer, and
//makes use of the big-integer datatype.
//@param index the integer to be factorialized
function factorial(index) {
if(index < 1 || isNaN(index)) {
return "Improper input to function factorial. Please input a positive integer.";
}
var fact = bigInt(index);
if(index > 1) {
return fact.multiply(factorial(index - 1)).toString();
} else {
return fact.toString();
}
}
console.log(factorial(45));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.