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 |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 690 | 3.9375 | 4 | [] | no_license | # Stage 1. Matrix multiplication.
class Matrix:
def __init__(self, row, col):
self.row = int(row)
self.col = int(col)
self.matrix = []
def get_matrix(self):
i = 1
while i <= self.row:
matr = list(map(int, input().split()))
self.matrix.append(matr)
i += 1
row1, col1 = input().split()
matrix_1 = Matrix(row1, col1)
matrix_1.get_matrix()
constant = int(input())
matrix_res = []
for h in range(int(row1)):
matrix_res.append([0] * int(col1))
for a in range(int(row1)):
for b in range(int(col1)):
matrix_res[a][b] = matrix_1.matrix[a][b] * constant
for _ in matrix_res:
print(*_)
|
Java | UTF-8 | 663 | 1.828125 | 2 | [] | no_license | package com.dianping.lion.dao;
import java.util.List;
import com.dianping.lion.entity.Service;
public interface ServiceDao {
public int updateService(Service service);
public int deleteService(Service service);
public int deleteServiceById(int id);
public Object createService(Service service);
public List<Service> getServiceList(int projectId, int envId);
public Service getServiceById(int id);
public Service getServiceByEnvNameGroup(int envId, String name, String group);
public List<Service> getServiceListByEnvName(int envId, String name);
public Integer getProjectId(String name);
}
|
Java | UTF-8 | 3,381 | 2.53125 | 3 | [] | no_license | package me.safrain.validator;
import me.safrain.validator.expression.Expression;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Iterator;
public class Violation {
public enum Type {
EXCEPTION, SEGMENT_REJECTED, INVALID
}
private Method method;
private Expression expression;
private Throwable throwable;
private String message;
private Object object;
private Object[] args;
private Type type;
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Violation(String message) {
this.message = message;
}
public Violation(Method method, Expression expression) {
this.method = method;
this.expression = expression;
}
public Violation(Method method, Expression expression, Object object) {
this.method = method;
this.expression = expression;
this.object = object;
}
public Violation(Method method, Expression expression, Object object, Throwable throwable) {
this.method = method;
this.expression = expression;
this.object = object;
this.throwable = throwable;
}
public Violation(Method method, Expression expression, Throwable throwable) {
this.method = method;
this.expression = expression;
this.throwable = throwable;
}
public Violation(Throwable throwable) {
this.throwable = throwable;
}
public Violation() {
}
public String getCommand() {
return method.getDeclaringClass().getName() + "." + method.getName();
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append("Violation [");
for (Iterator<String> iterator = Arrays.asList(
method != null ? "command=" + getCommand() : null,
expression != null ? "expression=" + expression.getExpression() : null,
message != null ? "message=" + message : null,
args != null ? "args=" + Arrays.toString(args) : null,
type != null ? "type=" + type.name() : null
).iterator(); iterator.hasNext(); ) {
String string = iterator.next();
if (string == null) continue;
s.append(string);
if (iterator.hasNext()) s.append(", ");
}
s.append("]");
return s.toString();
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public Expression getExpression() {
return expression;
}
public void setExpression(Expression expression) {
this.expression = expression;
}
public Throwable getThrowable() {
return throwable;
}
public void setThrowable(Throwable throwable) {
this.throwable = throwable;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public Object[] getArgs() {
return args;
}
public void setArgs(Object[] args) {
this.args = args;
}
}
|
Markdown | UTF-8 | 9,594 | 2.546875 | 3 | [] | no_license | ## 环境介绍:
本示例使用 `Vagrant` 工具模拟 Linux 环境
* 操作系统: CentOS/7
* 内存: 4G
* IP: 192.168.33.10/24
* Docker: docker-17.12.1
* Docker-compose:1.21.2
* Jenkins: 2.107.3
* Gitlab: gitlab-ce:10.7.3-ce.0
## Jenkins 安装
[详见 Jenkins 安装](install-jenkins.md)
## Gitlab 安装
Gitlab 默认启动在 80 端口,输入 IP:80 端口访问 Gitlab 服务,首次访问 Gitlab 将需要重置管理员密码。

### Gitlab 用户登录/注册
Gitlab 管理员密码重置后,将进入登录注册页面;
Gitlab 默认管理账号(root);

> 注: 建议为个人及 CI 创建独立账号,并赋予相关权限;
> 本示例中我们创建 gitadmin 账号用于 CI 及管理操作;
以管理员账号登录 gitlab,点击 Admin Area -> Overview -> User 为我刚创建的账号(gitadmin)添加到管理组;

### Gitlab 创建私有项目组及私有项目,将我们 gradle 项目推送到 gitlab 私有仓库
图略
将准备好的 Gradle 项目推送到 Gitlab 私有仓库
```
git remote add gitlab http://192.168.33.10/recruiting-system/2018-04-02-01-27-37-1522632457.git
git push gitlab master
```
> 注:由于我们虚拟机的 SSH 服务已绑定到 22 号端口,所以我们在启动 gitlab 的时候,把 git:// 协议绑定的端口设置到了 2222,所以在本地克隆、提交代码时将会稍有麻烦,因此在此建议使用 http 端口克隆提交项目;
## 新建 Pipeline
### Pipeline 创建
进入 Jenkins 首页,选择 New Item -> Pipeline,输入 Pipeline 名称:

### 配置从 GIT 仓库读取 Pipeline 配置

点击确定,即可完成 Pileline 的配置。
> 注:在项目的根目录下提交我们自己写的 Jenkinsfile 用来描述 pipeline 的定义,在此,我们使用项目根目录下的 Jenkinsfile-1 的示例;
> 注: Jenkinsfile-1 示例脚本是使用 `./gradlew` 命令自动下载 `gradle` 程序进行构建,因为默认 Jenkins 的镜像并不包含 gradle 的构建环境,因此一般有两种方式来解决:
> 1、基于 Jenkins Master 镜像添加 gradle 的运行环境;
> 2、基于 Jenkins + Slave 的结构,部署 Slave 节点添加 gradle 构建环境;
> 我们在后面再继续介绍.
### 为 Jenkins 生成 Gitlab 部署 Key(Deploy Key)
我们为 Jenkins 克隆 Gitlab 仓库使用 SSH 私钥的方式
```
# 使用 ssh-keygen 生成部署 Key
$ ssh-keygen -t rsa -f /tmp/jenkins
# 命令执行成功后,将在 /tmp 目录下生成 jenkins 公钥及私钥
$ ll /tmp/jenkins*
-rw-------. 1 root root 1675 May 23 10:12 /tmp/jenkins
-rw-r--r--. 1 root root 408 May 23 10:12 /tmp/jenkins.pub
```
### 为 Jenkins 添加部署 Key(Add Credentials)
private key 是使用刚刚生成的私钥(jenkins)

### 为 Gitlab 添加部署 Key
部署 Key 使用刚刚生成的公钥(jenkins.pub)
点击项目设置 Settings -> Repository -> Deploy Keys
Create a new deploy key for private project

### BUILD NOW
点击 `Build Now` 即可立即开始构建项目(手动构建的方式);

如上图,为 Jenkins 构建成功的视图。左下角显示了 Jenkins 构建历史,右上角为保存的 Artifact,右下角显示了 Stage View 的视图;
## Gitlab WebHook 配置
gitlab Webhook 主要为了解决,当 push 源代码到 gitlab 仓库,gitlab 自动触发 jenkins pipeline 做持续构建的过程;
### Jenkins 安装 gitlab 插件
Jenkins 为了与 Gitlab 集成,需要借助 Gitlab 的插件才能完成;
Manager Jenkins -> Manager Plugins -> Avaiable
勾选 Gitlab 插件,安装并重启 Jenkins。

### 为 Jenkins 创建 API 访问 Token
使用刚刚创建的 gitadmin 账号登录 gitlab,进入个人设置页面(Settings -> Access Token):

点击 `Create personal access token` 成功后,即可生成个人访问 Token:

### 为 Jenkins 配置 gitlab connections
Manage Jenkins -> Configure System -> Gitlab
输入 gitlab 的名称及 gitlab 的访问地址

Jenkins 配置 Gitlab API token(Add Credentials)

测试成功后,点击保存。
### Jenkins Pipeline 配置 `secret token`
回到刚刚创建的 Jenkins Pipeline 配置界面,生成 `secret token`

### gitlab 配置 Webhook 地址
拷贝 `secret token` 配置 Gitlab Web-Hooks
项目 Settings -> Integrations -> Add Web Hooks
输入 GitLab webhook URL、Secret Token,取消 `Enable SSL verification`,点击添加 Webhook。

> 注:关闭 SSL 验证,我们再此并没有使用 SSL 服务;
Gitlab Webhook 配置成功后,点击测试推送 `push event` 事件,即可自动触发 Jenkins Pipelien 做自动构建;
默认发送测试 push 请求将返回 500 错误,这是因为 gitlab 的安全设置默认不允许访问本地的 webhooks;
登录 gitlab 管理员账号,Admin Area -> Settings -> Outbound Requests
勾选 'Allow requests to the local network from hooks and services.' 即可解决;

再次测试,即可正常触发 Jenkins Pipeline 构建。
## Pipeline 定义构建 Docker Image,推送到 Docker Hub 官方仓库
在此,我们以 Docker Hub 官方仓库为例,演示如何构建 docker image,将镜像推送到 Docker Hub 官方仓库;
### Docker Hub 账号申请
Docker Hub 官方仓库地址,输入如下地址,创建 Docker Hub 账号。
https://hub.docker.com/
### 为 Docker Hub 创建 credentials
此处创建的 credentials 为 Jenkins 构建用来登录/访问 Docker Hub 的凭证(即刚刚在 Docker Hub 上创建的账号);
Jenkins 首页 -> Credentials -> System -> Global credentials -> Add Credentials

注: credentials id 为方便 Jenkinsfile 中引用 credentials 使用;
### Jenkinsfile
Jenkinsfile-2 示例:
```
#! groovy
node {
stage('checkout') {
checkout scm
}
stage('build') {
sh './gradlew clean build'
step([$class: 'ArtifactArchiver', artifacts: '**/build/libs/*.jar', fingerprint: true])
}
stage('test') {
sh './gradlew test'
step([$class: 'JUnitResultArchiver', testResults: '**/build/test-results/test/TEST-*.xml'])
}
stage('package') {
docker.withRegistry('https://index.docker.io/v1/', 'dockerhub') {
def customImage = docker.build("cnhttpd/2018-04-02-01-27-37-1522632457:${env.BUILD_ID}")
/* Push the container to the custom Registry */
customImage.push()
}
}
}
```
* 我们定义第三个 stage `package`
* docker.withRegistry 第一个参数为定义 Docker 仓库,我们使用 Docker Hub 官方仓库,第二个参数为 credentials Id
* docker.build 为镜像构建,包含镜像的名称及TAG,格式如下:
```
# Docker Hub 上私有镜像格式为(在此省略官方仓库地址):
username/imagename:tag
# 私有仓库镜像格式(私有仓库镜像 username 可以省略,registry 为私有仓库地址,默认端口号 5000):
registry:5000/username/imagename:tag
```
* TAG 标识,我们使用环境变量(${env.BUILD_ID}),BUILD_ID 即为构建 ID。注:这个值要持续的变化,我们一般使用 BUILD_ID 作为版本号;
* customImage.push() 即为推送镜像到 Docker Hub 官方仓库;
### 构建成功
如果 Pipeline 执行成功,我们就可以在 Docker Hub 访问到我们刚刚构建成功的镜像,并且通过 docker pull 拉取镜像;
我们可以点击 Build History, 查看构建历史(控制台输出、修改记录、git commit等);

如上图,右侧截图显示了保存的 Artifact、测试报告、stage view 等;
至此,我们简易版的持续集成的工作就基本结束.
### 小提示
你可能会有疑惑,该如何写 Jenkinsfile,只要了解了 pipeline、node、stage 等基本概念后,借助 Jenkins 脚手架可以帮助我们生成 pipeline step。
Jenkins Pipeline 配置界面 -> Pipeline Syntax

当然要想实现更复杂的 Pipeline,还是要借助 `groovy` 的语法。
## 参考文档:
* https://hub.docker.com/r/jenkins/jenkins/
* https://github.com/jenkinsci/docker/blob/master/README.md
* https://jenkins.io/doc/book/pipeline/docker/
* https://jenkins.io/doc/book/using/using-credentials/
* https://getintodevops.com/blog/building-your-first-docker-image-with-jenkins-2-guide-for-developers
* https://github.com/jenkinsci/gitlab-plugin/issues/375
* https://www.swtestacademy.com/jenkins-gitlab-integration/ |
Java | UTF-8 | 6,389 | 1.679688 | 2 | [
"MIT"
] | permissive | package qunar.tc.qconfig.server.config.longpolling.impl;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import qunar.tc.qconfig.client.Configuration;
import qunar.tc.qconfig.client.MapConfig;
import qunar.tc.qconfig.client.Numbers;
import qunar.tc.qconfig.common.util.Constants;
import qunar.tc.qconfig.server.config.check.CheckResult;
import qunar.tc.qconfig.server.config.check.CheckService;
import qunar.tc.qconfig.server.config.check.CheckUtil;
import qunar.tc.qconfig.server.config.longpolling.Listener;
import qunar.tc.qconfig.server.config.longpolling.LongPollingProcessService;
import qunar.tc.qconfig.server.config.longpolling.LongPollingStore;
import qunar.tc.qconfig.server.config.qfile.QFile;
import qunar.tc.qconfig.server.config.qfile.QFileFactory;
import qunar.tc.qconfig.server.config.qfile.impl.InheritQFileV2;
import qunar.tc.qconfig.server.domain.CheckRequest;
import qunar.tc.qconfig.server.feature.OnlineClientListService;
import qunar.tc.qconfig.server.support.context.ClientInfoService;
import qunar.tc.qconfig.server.web.servlet.AbstractCheckConfigServlet;
import qunar.tc.qconfig.servercommon.bean.ClientData;
import qunar.tc.qconfig.servercommon.bean.ConfigMeta;
import qunar.tc.qconfig.servercommon.bean.IpAndPort;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.AsyncContext;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author zhenyu.nie created on 2017 2017/3/28 15:26
*/
@Service
public class LongPollingProcessServiceImpl implements LongPollingProcessService {
private static final Logger logger = LoggerFactory.getLogger(LongPollingProcessServiceImpl.class);
@Resource(name = "v2Factory")
private QFileFactory qFileFactory;
@Resource
private ClientInfoService clientInfoService;
@Resource
private CheckService checkService;
@Resource
private LongPollingStore longPollingStore;
@Resource
private OnlineClientListService onlineClientListService;
private static final long DEFAULT_TIMEOUT = 60 * 1000L;
private volatile long timeout = DEFAULT_TIMEOUT;
@PostConstruct
public void init() {
MapConfig config = MapConfig.get("config.properties");
config.asMap();
config.addListener(new Configuration.ConfigListener<Map<String, String>>() {
@Override
public void onLoad(Map<String, String> conf) {
String newTimeout = conf.get("longPolling.server.timeout");
if (!Strings.isNullOrEmpty(newTimeout)) {
timeout = Numbers.toLong(newTimeout, DEFAULT_TIMEOUT);
}
}
});
}
@Override
public void process(AsyncContext context, List<CheckRequest> requests) {
IpAndPort address = new IpAndPort(clientInfoService.getIp(), clientInfoService.getPort());
AsyncContextHolder contextHolder = new AsyncContextHolder(context, address);
context.setTimeout(timeout);
context.addListener(new TimeoutServletListener(contextHolder));
processCheckRequests(requests, clientInfoService.getIp(), contextHolder);
}
@Override
public Set<String> getListeningClients(ConfigMeta meta) {
return onlineClientListService.getListeningClients(meta);
}
@Override
public Set<ClientData> getListeningClientsData(ConfigMeta meta) {
return onlineClientListService.getListeningClientsData(meta);
}
private void processCheckRequests(List<CheckRequest> requests, String ip, AsyncContextHolder contextHolder) {
CheckResult result = checkService.check(requests, ip, qFileFactory);
logger.info("profile:{}, result change list {} for check request {}", clientInfoService.getProfile(), result.getChanges(), requests);
if (!result.getChanges().isEmpty()) {
returnChanges(AbstractCheckConfigServlet.formatOutput(CheckUtil.processStringCase(result.getChanges())), contextHolder, Constants.UPDATE);
return;
}
addListener(result.getRequestsNoChange(), contextHolder);
registerOnlineClients(result, contextHolder);
}
private void addListener(Map<CheckRequest, QFile> requests, AsyncContextHolder contextHolder) {
for (Map.Entry<CheckRequest, QFile> noChangeEntry : requests.entrySet()) {
CheckRequest request = noChangeEntry.getKey();
QFile qFile = noChangeEntry.getValue();
if (!contextHolder.isComplete()) {
Listener listener = qFile.createListener(request, contextHolder);
longPollingStore.addListener(listener);
}
}
}
private void registerOnlineClients(CheckResult result, AsyncContextHolder contextHolder) {
Map<CheckRequest, QFile> noChanges = Maps.newHashMapWithExpectedSize(
result.getRequestsNoChange().size() + result.getRequestsLockByFixVersion().size());
noChanges.putAll(result.getRequestsNoChange());
noChanges.putAll(result.getRequestsLockByFixVersion());
for (Map.Entry<CheckRequest, QFile> noChangeEntry : noChanges.entrySet()) {
CheckRequest request = noChangeEntry.getKey();
QFile qFile = noChangeEntry.getValue();
if (!contextHolder.isComplete()) {
long version = request.getVersion();
ConfigMeta meta = qFile.getRealMeta();
String ip = contextHolder.getIp();
if (qFile instanceof InheritQFileV2) {
InheritQFileV2 inheritQFile = (InheritQFileV2) qFile;
Optional<Long> optional = inheritQFile.getCacheConfigInfoService().getVersion(inheritQFile.getRealMeta());
version = optional.isPresent() ? optional.get() : version;
onlineClientListService.register(inheritQFile.getRealMeta(), ip, version);
} else {
onlineClientListService.register(meta, ip, version);
}
}
}
}
private void returnChanges(String change, AsyncContextHolder contextHolder, String type) {
contextHolder.completeRequest(new ChangeReturnAction(change, type));
}
}
|
Markdown | UTF-8 | 790 | 2.75 | 3 | [] | no_license | ---
title: Ideas and questions to be explored
author: franc
date: 2014-10-22
template: project.jade
---
*"I talk about the gods, I am an atheist. But I am an artist too, and therefore a liar. Distrust everything I say. I am telling the truth. The only truth I can understand or express is, logically defined, a lie. Psychologically defined, a symbol. Aestheticaly defined, a metaphor."*
--Ursula K Le Guin, *The left hand of darkness*
### Binary card calculator
Conceived as a supporting tool for a workshop on binary card built by Toru Urakawa, the binary card calculator is used to translate from binary numbers, represented by up or down black and white cards, to decimal numbers, which are presented as big bubbly numbers.

### Twitter bots |
Java | UTF-8 | 3,507 | 2.03125 | 2 | [] | no_license | package com.cms.controller;
import com.cms.base.annotation.SystemLog;
import com.cms.base.controller.BaseCrudController;
import com.cms.base.query.PageQuery;
import com.cms.entity.CourseInfo;
import com.cms.entity.Score;
import com.cms.entity.Student;
import com.cms.entity.User;
import com.cms.service.*;
import com.cms.util.Result;
import com.cms.vo.ScoreVO;
import com.cms.vo.StudentVO;
import com.github.pagehelper.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* Created by hs on 2019.5.18.
*/
@Controller
@RequestMapping("/score")
public class ScoreController extends BaseCrudController<Score>{
@Autowired
private ScoreService scoreService;
@Autowired
private CourseService courseService;
@Autowired
private CourseInfoService courseinfoService;
@Autowired
private UserService userService;
@GetMapping
@RequiresPermissions("score:view")
public String rolePage(Model model) {
model.addAttribute("scoreList", scoreService.queryAll());
model.addAttribute("courseList",courseinfoService.queryAll());
model.addAttribute("userList",userService.queryList(new User().setRoleIds("4")));
return "system/score";
}
@ResponseBody
@GetMapping("/list")
@RequiresPermissions("score:view")
@Override
public Result<List<ScoreVO>> queryList(Score score, PageQuery pageQuery) {
String username = (String) SecurityUtils.getSubject().getPrincipal();
User user = userService.queryOne(new User().setUsername(username));
if(Integer.valueOf(user.getRoleIds()) == 4){
score.setStu_id(user.getId());
}
Page<Score> page = (Page<Score>) scoreService.queryList(score, pageQuery);
List<ScoreVO> scoreVOS = new ArrayList<>();
page.forEach(s -> {
ScoreVO scoreVO = new ScoreVO(s);
scoreVO.setStuname(userService.queryById(s.getStu_id()).getUsername());
scoreVO.setCoursename(courseinfoService.queryById(s.getCourse_id()).getName());
scoreVOS.add(scoreVO);
});
return Result.success(scoreVOS).addExtra("total", page.getTotal());
}
@ResponseBody
@RequiresPermissions("score:create")
@SystemLog("成绩管理创建")
@PostMapping("/create")
@Override
public Result create(@Validated Score score) {
scoreService.create(score);
return Result.success();
}
@ResponseBody
@RequiresPermissions("score:update")
@SystemLog("成绩管理更新角色")
@PostMapping("/update")
@Override
public Result update(@Validated Score score) {
scoreService.updateNotNull(score);
return Result.success();
}
@ResponseBody
@RequiresPermissions("student:delete")
@SystemLog("成绩管理删除角色")
@PostMapping("/delete-batch")
@Override
public Result deleteBatchByIds(@NotNull @RequestParam("id") Object[] ids) {
super.deleteBatchByIds(ids);
return Result.success();
}
}
|
PHP | UTF-8 | 301 | 2.796875 | 3 | [] | no_license | <?php
session_start();
if(isset($_SESSION['visited'])){
echo "Welcome again! This is the ".$_SESSION['visited']." time you're coming!";
$_SESSION['visited'] += 1;
}else{
echo "Welcome!";
$_SESSION['visited'] =0;
$_SESSION['visited'] += 1;
}
?>
|
PHP | UTF-8 | 412 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace DiDom\Tests;
use DiDom\Document;
class DocumentFragmentTest extends TestCase
{
public function testAppendXml()
{
$document = new Document();
$documentFragment = $document->createDocumentFragment();
$documentFragment->appendXml('<foo>bar</foo>');
$this->assertEquals('<foo>bar</foo>', $documentFragment->innerXml());
}
}
|
PHP | UTF-8 | 1,938 | 2.875 | 3 | [] | no_license | <?php
/**
* File for class AmazonS3StructAmazonCustomerByEmail
* @package AmazonS3
* @subpackage Structs
* @date 2013-09-04
* @author Mikaël DELSOL <contact@wsdltophp.com>
*/
/**
* This class stands for AmazonS3StructAmazonCustomerByEmail originally named AmazonCustomerByEmail
* Meta informations extracted from the WSDL
* - from schema : {@link http://doc.s3.amazonaws.com/2006-03-01/AmazonS3.xsd}
* @package AmazonS3
* @subpackage Structs
* @date 2013-09-04
* @author Mikaël DELSOL <contact@wsdltophp.com>
*/
class AmazonS3StructAmazonCustomerByEmail extends AmazonS3StructUser
{
/**
* The EmailAddress
* @var string
*/
public $EmailAddress;
/**
* Constructor method for AmazonCustomerByEmail
* @see parent::__construct()
* @param string $_emailAddress
* @return AmazonS3StructAmazonCustomerByEmail
*/
public function __construct($_emailAddress = NULL)
{
AmazonS3WsdlClass::__construct(array('EmailAddress'=>$_emailAddress));
}
/**
* Get EmailAddress value
* @return string|null
*/
public function getEmailAddress()
{
return $this->EmailAddress;
}
/**
* Set EmailAddress value
* @param string $_emailAddress the EmailAddress
* @return string
*/
public function setEmailAddress($_emailAddress)
{
return ($this->EmailAddress = $_emailAddress);
}
/**
* Method called when an object has been exported with var_export() functions
* It allows to return an object instantiated with the values
* @see AmazonS3WsdlClass::__set_state()
* @uses AmazonS3WsdlClass::__set_state()
* @param array $_array the exported values
* @return AmazonS3StructAmazonCustomerByEmail
*/
public static function __set_state(array $_array,$_className = __CLASS__)
{
return parent::__set_state($_array,$_className);
}
/**
* Method returning the class name
* @return string __CLASS__
*/
public function __toString()
{
return __CLASS__;
}
}
?> |
Python | UTF-8 | 3,223 | 3.171875 | 3 | [
"MIT"
] | permissive | from tictactoe import TicTacToe, GameState, Cell_coord
from strategy import Strategy
from typing import Optional, Tuple
import strategies as st
def input_q(msg: str) -> str:
resp = input(msg)
if resp.upper() in ["Q", "QUIT"]:
raise SystemExit
else:
return resp
def create_board() -> TicTacToe:
while True:
print('')
d = input_q("Number of dimensions: ")
n = input_q("Size of board: ")
mt = input_q("Number of moves per turn: ")
m = input_q("Misere (win if opponent gets n in a row): ")
try:
return TicTacToe(int(d), int(n), int(mt), m[0].upper() in ['Y', 'T'])
except MemoryError:
print("The board is too big to fit into available memory")
except Exception as e:
print("Could not create board. Please provide valid parameters")
print(f'{e}')
def choose_names(ttt: TicTacToe) -> None:
while True:
print('')
p1_name = input_q("Name of player 1: ")
p2_name = input_q("Name of player 2: ")
try:
ttt.names = p1_name, p2_name
return
except Exception as e:
print(f'{e}')
def choose_strategy(ttt: TicTacToe, p: int) -> Strategy:
idx_cls = {}
msg = f'Choose strategy for {str(ttt.names[p])}:\n'
idx = 0
for i, (k, v) in enumerate(st.strategies_cls.items(), 1):
try:
if v.validate(ttt.d, ttt.n, ttt.moves_per_turn, True):
idx += 1
msg = msg + ' ' + str(idx) + '. ' + k + '\n'
idx_cls[str(idx)] = v
except:
pass
msg = msg + 'Selection: '
while True:
print('')
s = input_q(msg)
try:
return idx_cls[s](ttt)
except Exception as e:
print(f'Invalid selection: {e}')
def restart(ttt: TicTacToe, s: Tuple[Strategy, Strategy]) -> None:
s[0].reset()
s[1].reset()
ttt.reset()
ttt.display()
while ttt.state == GameState.IN_PROGRESS:
print(f'\nActive player: {ttt.names[ttt.active_player]}')
s[ttt.active_player].move()
ttt.display()
# game has finished without user restart or new game
print(ttt.state_str())
play_again(ttt, s)
def new_game():
ttt = create_board()
choose_names(ttt)
s = choose_strategy(ttt, 0), choose_strategy(ttt, 1)
restart(ttt, s)
def play_again(ttt: TicTacToe, s: Tuple[Strategy, Strategy]) -> None:
while True:
print('')
resp = input_q("Replay(r), swap(s), new game(n) or quit(q): ")
try:
if resp.upper() in ['REPLAY', 'R']:
restart(ttt, s)
return
if resp.upper() in ['SWAP', 'S']:
ttt.names = ttt.names[1], ttt.names[0]
s = s[1], s[0]
restart(ttt, s)
return
elif resp.upper() in ['NEWGAME', 'N']:
new_game()
return
except Exception as e:
print(f'{e}')
if __name__ == "__main__":
# Display welcome message and instructions
msg = "Welcome to HyperOXO."
print(msg)
new_game()
|
JavaScript | UTF-8 | 1,679 | 3.21875 | 3 | [] | no_license | class Cell {
constructor(x, y) {
this.live = false;
this.nextGeneration = false;
this.adjacent = 0;
this.x = x;
this.y = y;
}
setLive() {
this.live = true;
}
setDead() {
this.live = false;
}
findNeighbors(board) {
if(this.live === true){
this.adjacent = -1
}else{
this.adjacent = 0
}
for (let ly = this.y - 1; ly < this.y + 2; ly++) {
if (ly >= 0 && ly < board.length) {
for (let lx = this.x - 1; lx < this.x + 2; lx++) {
if(lx>=0 && lx < board[ly].length){
if(board[ly][lx].live === true && [lx, ly] !== [this.x, this.y]){
this.adjacent += 1
}
}
}
}
}
if(this.adjacent === 3 ){
this.nextGeneration = true
}
if(this.live === true && this.adjacent===2){
this.nextGeneration = true
}
if(this.adjacent <= 1 ){
this.nextGeneration = false
}
if(this.adjacent > 3 ){
this.nextGeneration = false
}
}
updateGeneration(){
this.live = this.nextGeneration
}
renderCell(board, gridSize) {
if (this.live === false) {
board.strokeStyle = "blue";
board.beginPath();
board.arc(
this.x * gridSize + gridSize / 2,
this.y * gridSize + gridSize / 2,
2,
0,
2 * Math.PI
);
board.stroke();
} else {
board.strokeStyle = "red";
board.beginPath();
board.arc(
this.x * gridSize + gridSize / 2,
this.y * gridSize + gridSize / 2,
16,
0,
2 * Math.PI
);
board.stroke();
}
}
}
export default Cell;
|
Python | UTF-8 | 3,924 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env python
# Silly Twitter API scraper thingy. Feed it a twitter api page on
# standard input
#
# ideal output follows. Currently 'response' is not generated,
# 'requires_auth' is a boolean (since most pages just say 'true' and
# 'false', and methods will only ever be a list of the first method
# found.
#
# methods = [
# {'name':'statuses/user_timeline',
# 'methods':['GET'],
# 'limit':1,
# 'requires_auth':'user_based',
# 'response':{
# 'object':'status',
# 'cardinality':'n'},
# 'parameters':[
# {
# 'name':'id',
# 'required':False},
# {
# 'name':'user_id',
# 'required':False,
# 'type':'int'},
# {
# 'name':'count',
# 'required':False,
# 'type':'int',
# 'min':1,
# 'max':200},
# {
# 'name':'page',
# 'required':False,
# 'type':'int',
# 'min':1} ]
# }
# ]
import BeautifulSoup
import sys
import re
import json
import urllib2
from pprint import pprint
import re
def find_name():
baseurl = 'http://apiwiki.twitter.com/'
url_banner = soup.find(name='b', text=lambda t: 'URL' in t)
url = url_banner.findNext(text=lambda t: 'http' in t)
r = re.compile(r'(http://.*twitter.com/)(.*)(.format|)')
m = r.match(url)
return m.group(1), m.group(2)
def find_methods():
def is_http_method(t):
for method in ['GET', 'POST', 'PUT', 'DELETE']:
if method in t:
return True
http_banner = soup.find(name='b', text=lambda t: 'HTTP Method' in t)
return http_banner.findNext(text=is_http_method)
def find_limit():
number = [None]
def has_num_token(t):
matchobj = re.search(r'(\d)', t)
if matchobj:
number[0] = matchobj.group(1)
return matchobj
limit_heading = soup.find(name='b', text=lambda t: 'API rate limited' in t)
if limit_heading:
limit_heading.findNext(text=has_num_token)
return number[0]
def find_auth():
def banner_predicate(t):
return 'Requires Authentication' in t
requires_auth = [None]
def requires_auth_predicate(t):
matchobj = re.search(r'(true|false)', t)
if matchobj:
requires_auth[0] = matchobj.group(1)
return matchobj
requiresauth = soup.find(name='b', text=banner_predicate)
# has side effect mutating requires_auth
requiresauth.findNext(text=requires_auth_predicate)
return requires_auth[0]
def find_parameters():
def banner_predicate(t):
return 'Parameters' in t
parameters_banner = soup.find(text=banner_predicate)
for inner in parameters_banner.findNext('ul').contents:
if isinstance(inner, BeautifulSoup.Tag):
text_nodes = inner(text=True)
name = text_nodes[0]
tlob = ' '.join(str(x) for x in text_nodes[1:])
if name:
if 'Optional' in tlob:
yield {'name': name,
'required': 'false'}
elif 'Required' in tlob:
yield {'name': name,
'required': 'true'}
all = []
for s in sys.argv[1:]:
soup = BeautifulSoup.BeautifulSoup(urllib2.urlopen(s))
print >>sys.stderr, s
try:
baseurl, name = find_name()
all.append({'name': name,
'baseurl': baseurl,
'methods': [find_methods()],
'limit': find_limit(),
'requires_auth': find_auth(),
'parameters':list(find_parameters())})
except Exception, e:
print e
pprint(all)
|
Markdown | UTF-8 | 3,565 | 2.875 | 3 | [
"MIT"
] | permissive |
# 组件配置
## 组件配置
表单组件、行组件都是通过`render-custom-component`进行动态生成的。
每个字段的配置中有几处地方可以配置component:
1. column.form.component = 表单组件配置
2. column.component = 表格行展示组件配置
3. column.search.component = 查询表单组件配置
4. column.view.component = 查看表单组件配置
使用相关组件前,需要通过`Vue.use` 或 `Vue.component`引入组件
## 组件配置项
[d2-crud-x中的组件配置](../d2-crud-x/component.md)
```js
component:{ //添加和修改时form表单的组件
name: 'dict-select', //表单组件名称,支持任何v-model组件
props: { //表单组件的参数,具体参数请查看对应的组件文档
separator:",",//dict-select的组件参数,[不同组件参数不同]
elProps:{ //dict-select内部封装了el-select
filterable: true, //可过滤选择项
multiple: true, //支持多选
clearable: true, //可清除
}
},
placeholder:'',
disabled: false, //是否在表单中禁用组件
// disabled(context){return false}//还可以配置为方法
readonly: false, //表单组件是否是只读
// readonly(context){return false} //还可以配置为方法
show: true, //是否显示该字段,
// show(context){return false} //还可以配置为方法
on:{ //除input change事件外,更多组件事件监听
select(event){console.log(event)} //监听表单组件的select事件
},
slots:{ //scoped插槽jsx
default:(h,scope)=>{ //默认的scoped插槽
return (<div>{scope.data}</div>)
}
},
children:[ //子元素jsx
(h)=>{return (<div slot="prefix">非scoped插槽</div>)}
],
span: 12, //该字段占据多宽,24为占满一行
// 组件的其他html属性,会直接传递给组件
style:{width:'100px'},
class:{'d2-mr-5':true}
}
```
## 我想要配置组件的某个功能该如何查找文档
下面以`日期选择器禁用今天之前的日期`这个需求为例
### 1. 查看type对应使用的什么组件
日期选择器我们配置的 `type=date`
所以先去[字段类型列表](./types.html),查找`type=date`里面用的是什么组件
在[日期时间选择](./types.html#日期时间选择)这一条中我们找到了`type=date`的配置
```js
date: {
form: { component: { name: 'el-date-picker' } },
component: { name: 'date-format', props: { format: 'YYYY-MM-DD' } }
}
```
从这里知道`type=date`使用的`el-date-picker`组件
### 2.查找该组件的文档,确定参数
在[日期时间选择](./types.html#日期时间选择) 拉到下方
可以看到相关组件的文档链接(如果没有文档链接,请告诉我,我会尽快加上的)

点击[el-date-picker](https://element.eleme.cn/#/zh-CN/component/date-picker)
跳转到elementUI的文档页面,找到禁用日期相关参数


### 3.给component添加参数
```js
export const crudOptions = (vm) => {
return {
columns: [
{
title: '日期',
key: 'date',
type:'date',
form:{
component:{
props:{
pickerOptions:{
disabledDate: time => {
return time.getTime() < Date.now()
}
}
}
}
}
}
]
}
}
```
|
PHP | UTF-8 | 6,483 | 2.515625 | 3 | [] | no_license | <?php
//Reanudamos la sesión y controlamos que todo este bien
session_start();
if(!isset($_SESSION['usuario']) and $_SESSION['estado'] != 'Autorizado'){
echo 'Mal inicio de sesión;';
header('Location: ../index.php');
}else{
$usernick = $_SESSION['usuario'];
$userpass = $_SESSION['password'];
require ('/var/www/ConsumsPSPV/config/sesiones.php');
}
require ('../config/core.php');
require ('../config/database.php');
require ('../config/globals.php');
require ('../Classes/electricitat.php');
require ('../Classes/aigua.php');
require ('../Classes/oxigenAmpolla.php');
require ('../Classes/oxigenTank.php');
require ('../Classes/gasnatural.php');
//Procedemos con la inserción de los nuevos datos
require '/var/www/ConsumsPSPV/vendor/autoload.php';
use League\Csv\Reader;
$tipo = $_REQUEST["tipo"];
$target_name = basename($_FILES["fileToUpload"]["name"]);
$target_dir = "/var/www/ConsumsPSPV/CSV/newData/";
$uploadOk = 0;
//Eliminamos ficheros antiguos
$cmd = "rm -f ".$target_dir."*.csv";
try{
shell_exec($cmd);
}catch (Exception $e){
$msg = "[ERR] Fallo al borramos ficheros antiguos: ".$e->getMessage();
errorLog($msg);
die($msg);
}
// Iniciamos creación fichero
$target_file = $target_dir . $target_name;
$target_format = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Comprobamos si el fichero existe ya, ese quiere decir que algo ha ido mal.
// El fichero no debe existir puesto que es nuevo y al final de las operaciones borramos dicho fichero
// de esta carpeta.
if(file_exists($target_file)){
$msg = "[ERR] El fichero con los nuevos datos de '.$tipo.' ya existe."."\n";
errorLog($msg);
$uploadOk = 1;
}
// Comprobamos tamaño del fichero, si es más grande de 5 MB rechazamos.
if ($_FILES["fileToUpload"]["size"] > 500000){
$msg = "[ERR] El fichero es demasiado grande";
echo '<p id="Error">'.$msg.'</p>'."\n";
$uploadOk = 1;
errorLog($msg);
}
// Comprobamos formato, si no es CSV rechazamos;
if ($target_format != "csv"){
$msg = "[ERR] El fichero no tiene el formato apropiado";
echo '<p id="Error">'.$msg.'</p>'."\n";
$uploadOk = 1;
errorLog($msg);
}
// Comprobamos que el nombre del fichero y el consumo coinciden.
$arrayTipo = array();
$arrayNombres = array();
$arrayNombres = [ "file_consumoxiflow_ampolla.csv",
"file_consumoxiflow_tank.csv",
"file_consumsaigua.csv",
"file_consumselectricitat.csv",
"file_consumsgasnatural.csv"];
$arrayTipo = ["Oxigen Ampolla","Oxigen","Aigua","Electricitat","Gas Natural"];
// Comprobamos que el fichero corresponda al Consumo en el que queremos insertar los Datos
$isCorrectFile = comprobateFile($tipo,$target_name);
if ($isCorrectFile == 0){
$msg = '[ERR] El fichero no coincide con el consumo seleccionado. Detenemos Ejecucción'."\n";
errorLog($msg);
die($msg);
}
if ($_FILES["file"]["error"] > 0) {
echo "[ERR]: ". $_FILES["file"]["error"] . "<br />";
$uploadOk = 1;
}
// Procedemos a la subida del fichero
if ($uploadOk == 1) {
echo '<p id="Eroor">Ups alguna cosa no h\'acabat d\'anar bé. Poseu-vos en contacte amb l\'administrador de l\' aplicació.</p>'."\n";
echo '<p id="Error">info@romsolutions.es</p>'."\n";
die();
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo '<p id="OK">El fitxer ha sigut puxat amb éxit '. basename( $_FILES["fileToUpload"]["name"]).'</p>'."\n";
} else {
echo '<p id="Error">Problemas de conexió, torni-ho a intentar el fitxer no ha acabar de puxar correctament.!!</p>'."\n";
}
}
$database = new Database();
$db = $database->getConnection();
if($tipo == "Electricitat"){
$electricitat = new Electricitat($db);
$electricitat->comprobateLengthData($target_file);
$electricitat->createBackupTable();
$electricitat->truncateTable();
$csv = Reader::createFromPath($target_file);
//Objeto Reader, le quitamos la cabecera que no se ha de insertar
$csv->setHeaderOffset(0);
$electricitat->insertData($csv);
}elseif ($tipo == "Aigua"){
$aigua = new Aigua($db);
$aigua->comprobateLengthData($target_file);
$aigua->createBackupTable();
$aigua->truncateTable();
$csv = Reader::createFromPath($target_file);
//Objeto Reader, le quitamos la cabecera que no se ha de insertar
$csv->setHeaderOffset(0);
$aigua->insertData();
}elseif ($tipo == "Gas Natural"){
$gasnatural = new GasNatural($db);
$gasnatural->comprobateLengthData($target_file);
$gasnatural->createBackupTable();
$gasnatural->truncateTable();
$csv = Reader::createFromPath($target_file);
//Objeto Reader, le quitamos la cabecera que no se ha de insertar
$csv->setHeaderOffset(0);
$gasnatural->insertData($csv);
}elseif ($tipo == "Oxigen"){
$oxigenTank = new OxigenTank($db);
$oxigenTank->comprobateLengthData($target_file);
$oxigenTank->createBackupTable();
$oxigenTank->truncateTable();
$csv = Reader::createFromPath($target_file);
//Objeto Reader, le quitamos la cabecera que no se ha de insertar
$csv->setHeaderOffset(0);
$oxigenTank->insertData($csv);
}elseif ($tipo == "Oxigen Ampolles"){
$oxigenAmpolla = new OxigenAmpolles($db);
$oxigenAmpolla->comprobateLengthData($target_file);
$oxigenAmpolla->createBackupTable();
$oxigenAmpolla->truncateTable();
$csv = Reader::createFromPath($target_file);
//Objeto Reader, le quitamos la cabecera que no se ha de insertar
$csv->setHeaderOffset(0);
$oxigenAmpolla->insertData($csv);
}
?>
|
C# | UTF-8 | 1,007 | 2.671875 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Event/FeastEvent")]
public class FeastEvent : Event
{
private int amtConsumed;
public override void Execute(int index)
{
GameController gc = GameController.Instance;
switch (index)
{
case 0:
amtConsumed = gc.Roster.Count * gc.FoodPerPerson;
gc.ChangeFood(-amtConsumed);
gc.TeamMorale = Mathf.Min(Constants.MAX_VALUE, gc.TeamMorale + 10);
break;
case 1:
gc.TeamMorale = Mathf.Max(0, gc.TeamMorale - 5);
break;
}
}
public override string GetConsequencesText(int choice)
{
switch (choice)
{
case 0:
return "The villagers feast! Yay!\nFood: -" + amtConsumed + "\nMorale: +10";
case 1:
return "The villagers become angry, but ultimately trust in your leadership.\nFood: -0\nMorale: -5";
}
return "";
}
}
|
Python | UTF-8 | 454 | 3.390625 | 3 | [] | no_license | # Day 2 - 2015
def transform_data(data):
return [[y for y in x.strip().split('x')] for x in data.strip().split()]
with open('day2.txt') as f:
data = transform_data(f.read())
total_paper = 0
for present in data:
l = int(present[0])
w = int(present[1])
h = int(present[2])
lw = (l*w)
wh = (w*h)
lh = (l*h)
extra = min(x for x in [lw, wh, lh])
total_paper += (2*lw) + (2*wh) + (2*lh) + extra
print(total_paper)
|
SQL | UTF-8 | 7,044 | 4.5625 | 5 | [] | no_license | /* 1. SQL 문은 다른 프로그래밍 언어와 마찬가지로 산술 연산자를 사용할 수 있다.
* 2. 산술연산자 종류)
* + 덧셈, - 뺄셈, * 곱셈, / 나눗셈
*
*/
--emp01 테이블 생성
create table emp01(
empno int primary key -- 사원번호, int는 정수숫자 타입
,ename varchar(50) -- 사원명
,sal int -- 월급
,comm int -- 보너스
);
insert into emp01 values(101,'홍길동',250,25);
insert into emp01 values(102,'이순신',200,28);
insert into emp01 (empno,ename,sal)values(103,'강감찬',200);
--사원번호를 기준으로 내림차순 정렬
select * from emp01 order by empno desc;
--연봉계산
select ename, sal,sal*12 from emp01;
--출력결과 컬럼명에 별칭을 주고자 하는 경우는 as 문을 사용
select ename,sal,sal*12 as 연봉 from emp01;
select ename,sal as "월급", sal*12 as "연봉" from emp01;
select * from emp01 order by empno desc;
/* null특징)
* 1. null도 자료의 일종이며 정해지지 않는 값이란 의미이다.
* 미확정, 알 수 없는 값을 의미한다.
* 2. 어떤 값인지 알 수 없지만 값은 존재한다.
*/
--강감찬 사원의 보너스는 null 이기 때문에 sal*12 + conmm = null 이 된다.
--이 문제를 해결하기 위해서 오라클에서는 Null 을 0또는 다른 값으로 변환 하기 위한 함수 nvl 함수를 제공한다.
select ename , sal, sal*12+comm from emp01;
select ename, sal, sal*12+comm,nvl(comm.0),sal*12+nvl(comm,0) from empa01
--nvl(comm,e) 함수는 보너스에서 NULL을 0으로 변경
----------------------------------------------------------------------------
/*distinct 키워드 특징)
* 동일한 레코드 값이 중복되어 있으면 한번만 출력되게 한다.
*/
create table test01(
no number(38)
,name varchar2(28)
);
insert into test01 values(10,'홍길동');
insert into test01 values(10,'세종대왕님');
insert into test01 values(10,'신사임당님');
select no, name from test01;
select distinct no, name from test01;
/* 오라클 비교연산자 종류)
* == (같다) >(~보다 크다), <(~보다작다), >=(~보다 크거나 같다), <=(~보다 작거나 같다),
* <>, != ,^= (같지 않다)
*/
select ename, sal from emp01;
select ename, sal from emp01 where sal <> 200;
--월급이 200이 아닌 사원명과, 급여가 검색된다.
select * from test01;
--쿼리문은 대소문자를 구분하지 않지만 컬럼 레코드값 영문자는 대소문자를 구분한다.
insert into test01 values (20, 'FORD');
select no, name from test01 where name = 'ford';
select no, name from test01 where name = 'FORD';
/* 오라클 논리 연산자 종류)
* and : 두가지 조건 모두 만족해야 레코드가 검색
* or : 두가지 조건 중 한개라도 만족하면 검색
* not : 조건에 만족하지 못하는 것만 검색
*/
select * from TEST01 where no=10 and name='홍길동';
select * from TEST01 where no=10 and name='FORD';
SELECT * FROM TEST01 WHERE NOT NO=10;
select * from emp01;
--between 200 and 250
-- : 급여가 200이상 ~ 250이하 레코드만 검색한다.
--sal >=200 and sal <=250
select ename,sal from emp01 where sal between 200 and 250;
/* 컬럼명 in(A,B,C) 연산자 특징)
* 컬럼 레코드가 A,B,C 중 어느 하나만 만족하더라도 검색 가능
*/
--급여가 100,200,300 인 or 아닌 자료 검색
select ename, sal from emp01 where sal in(100,200,300);
select ename, sal from emp01 where sal not in(100,200,300);
--% 는 하나 이상의 임의의 모르는 문자와 매핑 대응.
select name from test01 where name like 'F%';
select * from emp01;
select empno, ename from emp01 where ename like '%길%';
--like 는 검색 연산자, _는 임의의 모르는 한문자와 매핑대응,
select ename from emp01 where ename like '_길동';
--이름중에 길이 포함안된 이름을 검색
select ename from emp01 where ename not like '%길%';
--보너스 중에서 null 인 경우만 검색
select * from emp01 where comm is null;
--보너스가 null이 아닌 경우만 검색
select * from emp01 where comm is not null;
--order by 는 정렬문이다. asc는 오름차순 정렬 asc 문은 생략 가능하다.
select sal from emp01 order by sal asc;
--desc : 내림차순 -> 생략 불가능, asc: 오름차순 -> 생략가능
select sal from emp01 order by sal desc;
--dual 테이블은 오라클 연산 결과값, 함수값, 시쿤스 값 등 출력용도로 활용됨.
select 100*120 from dual;
/* 듀얼 테이블의 컬럼 하나를 cmd에서 확인해본다. */
--desc dual;
/* 오라클 숫자함수)
* ABS(절대값), FLOOR(소수점 아래를 버림)
*/
select -10, abs(-10) from dual;
select 34.5678, FLOOR(34.5678) from dual;
--round(34.5678,2) 함수는 주어진 2의 뜻은 소수점 셋째자리에서 반올림하여 소수점 이하 2째자리까지 표시
select 34.5678, round(34.5678,2) from dual;
--mod 함수는 나머지를 구함
select mod(26,5) from dual;
--upper()함수는 영문대문자로 변경
select upper('seoul') from dual;
--lower()함수는 영문 소문자로 변경
select lower('BUSAN') from dual;
--initcao() 함수는 단어별 첫글자만 영문 대문자로 하고 나머지는 영문 소문자로 한다.
select initcap('welcome to oracle') from dual;
--length() 함수는 길이를 구함
select length('oracle') from dual;
--4번째 문자부터 세문자까지만 추출
select substr('oracle',4,3) from dual;
--a문자 위치번호 반환
select instr('oracle','a') from dual;
select LTRIM(' Oracle') from dual; --Ltrim()함수는 왼쪽공백을 제거
select rtrim(' oracle ') from dual; --rtrim()함수는 오른쪽공백을 제거
select trim(' oracle ') from dual; -- trim()함수는 양쪽공백을 제거
select sysdate from dual;--sysdate는 오라클 날짜함수
/* to_char() : 날짜형 또는 숫자형을 문자형으로 변환하는 함수이다.
* to_date() : 문자형을 날짜형으로 변환
* to_number() : 문자형을 숫자형으로 변환
*/
--emp01테이블 삭제
drop table emp01;
--decode 함수 실습
create table emp01(
deptno number(10) --부서번호
,ename varchar(30) -- 사원명
)
insert into emp01 values(10,'MILLER');
insert into emp01 values(20,'smith');
insert into emp01 values(20,'jones');
insert into emp01 values(30,'allen');
select* from emp01;
select ename, deptno, decode(deptno,10, 'ACCOUNTING',
20, 'RESEARCH',
30, 'SALES')
AS DNAME
FROM EMP01;
--case 함수
select ename, deptno,
case when deptno = 10 then'ACCOUNTING'
when deptno = 20 then 'RESEARCH'
when deptno = 30 then 'SALES'
END as DNAME
from EMP01;
|
Java | UTF-8 | 2,860 | 1.960938 | 2 | [] | no_license | package controlador.competencia;
import java.util.List;
import modelo.DatoBasico;
import modelo.Liga;
import modelo.PersonalForaneo;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.databind.AnnotateDataBinder;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Messagebox;
import servicio.implementacion.ServicioPersonalForaneo;
public class CntrlFrmCatalogoUmpire extends GenericForwardComposer {
AnnotateDataBinder binder;
Component catalogo;
ServicioPersonalForaneo servicioPersonalForaneo;
PersonalForaneo umpire;
DatoBasico datoBasico;
// Objeto Lista de lisgas que se mostraran en el catalogo...
List<PersonalForaneo> umpires;
Listbox lsbxUmpire;
// public AnnotateDataBinder getBinder() {
// return binder;
// }
//
// public void setBinder(AnnotateDataBinder binder) {
// this.binder = binder;
// }
//
// public Component getCatalogo() {
// return catalogo;
// }
//
// public void setCatalogo(Component catalogo) {
// this.catalogo = catalogo;
// }
public List<PersonalForaneo> getUmpires() {
return umpires;
}
public void setUmpires(List<PersonalForaneo> umpires) {
this.umpires = umpires;
}
public Listbox getLsbxUmpire() {
return lsbxUmpire;
}
public void setLsbxUmpire(Listbox lsbxUmpire) {
this.lsbxUmpire = lsbxUmpire;
}
public PersonalForaneo getUmpire() {
return umpire;
}
public void setUmpire(PersonalForaneo umpire) {
this.umpire = umpire;
}
public ServicioPersonalForaneo getServicioPersonalForaneo() {
return servicioPersonalForaneo;
}
public void setServicioPersonalForaneo(
ServicioPersonalForaneo servicioPersonalForaneo) {
this.servicioPersonalForaneo = servicioPersonalForaneo;
}
public DatoBasico getDatoBasico() {
return datoBasico;
}
public void setDatoBasico(DatoBasico datoBasico) {
this.datoBasico = datoBasico;
}
public void doAfterCompose(Component c) throws Exception {
super.doAfterCompose(c);
c.setVariable("cntrl", this, true);
catalogo = c;
umpires = servicioPersonalForaneo.listarUmpires();
}
public void onClick$btnAceptar() throws InterruptedException {
if (lsbxUmpire.getSelectedIndex() != -1) {
PersonalForaneo u = umpires.get(lsbxUmpire.getSelectedIndex());
Component formulario = (Component) catalogo.getVariable(
"formulario", false);
formulario.setVariable("umpire", u, false);
Events.sendEvent(new Event("onCatalogoCerrado", formulario));
catalogo.detach();
} else {
Messagebox.show("Seleccione un Umpire", "Mensaje", Messagebox.YES,
Messagebox.INFORMATION);
}
}
public void onClick$btnSalir() {
catalogo.detach();
}
}
|
Markdown | UTF-8 | 3,286 | 3.390625 | 3 | [] | no_license | ---
layout: post
title: "HTML/CSS Course: Session 5"
authors: ["Kat Li Yang"]
date: 2017-10-04 17:10:00 +0800
categories: HTML/CSS courses
---
From this session onwards, we will be starting to put what we have done in the past weeks online. We will be working with the popular platform Github with Github Pages. Github Pages enables Github users to host static sites on their servers.
First and foremost, we need to set up a Github account. For those who have yet to create a Github account, please follow this link and sign up for an account: [https://github.com/](https://github.com/)
Once you have signed up for an account, please download and install Github Desktop from here: [https://desktop.github.com/](https://desktop.github.com/)
While it is possible to use Git without a Graphical User Interface, it is much easier for new users to work with the GUI first. If you are interested in learning more about Git and the Git workflow, please feel free to read up from the git manual here: [https://git-scm.com/docs/gittutorial](https://git-scm.com/docs/gittutorial)
Once you have signed up for a Github account and installed Github Desktop, we will now create out first repository. A repository is like a folder where we store our code. After logging in to Github, click on the '+' sign on the top right. as shown.

You should see the page below:

For the name of the repository, please use [username].github.io. Only when your repository is named as such can it be set up as a Github Pages repository.
Once you have successfully set up your repository, here's what you should see:

Click on "Set up in Desktop" and allow Github Desktop to open.
Github Desktop should now prompt you about the location to set up the local repository. Choose a convenient location, such as your Desktop for now. What Github Desktop will do now is to clone the repository from the remote server onto your Desktop. You can make changes in the local folder. Let's try adding a simple page.
Move the simple page into the local repository.

Now, go into Github Desktop and you should see that there are some new changes made to your local repository.

In summary, add a description for your new commit. You may also add some message that would describe what you have changed. For instance, "Add page index.html" for the description summary.

Click on "Commit to master". Then, click on "Publish" in the top right corner. Now, the changes you have made to your local repository will be sync-ed with the remote repository on Github's servers.

Go to settings on Github.

Select "master branch" under "Github Pages".

Congratulations! Your site is now accessible.
For now, work on the site on your local repository, and sync it to Github when you want to see it online.
|
Python | UTF-8 | 6,980 | 2.53125 | 3 | [] | no_license | #!/usr/bin/env python
### Module imports ###
import sys
import math
import re
import numpy as np
from sklearn import linear_model, svm
from sklearn import preprocessing
from doc_utils import DocUtils, Query, CorpusInfo, ExtraFeaturesInfo
from pa3_utils import Pa3Utils
corpus = CorpusInfo()
corpus.load_doc_freqs()
extraFeaturesInfo = ExtraFeaturesInfo()
###############################
##### Point-wise approach #####
###############################
def pointwise_train_features(train_data_file, train_rel_file, extraFeaturesInfo=None):
X,y = DocUtils.extractXy_pointWise(train_data_file, train_rel_file, corpus, extraFeaturesInfo)
return (X, y)
def pointwise_test_features(test_data_file, extraFeaturesInfo=None):
X,queries,index_map = DocUtils.extractX_pointWise(test_data_file, corpus, extraFeaturesInfo)
return (X, queries, index_map)
def pointwise_learning(X, y):
model = linear_model.LinearRegression()
model.fit(X,y)
weights = model.coef_/np.linalg.norm(model.coef_)
print >> sys.stderr, "Weights:", weights
return model
def pointwise_learning_extra(X, y,alpha=1):
model = linear_model.Lasso(alpha)
model.fit(X,y)
weights = model.coef_/np.linalg.norm(model.coef_)
print >> sys.stderr, "Weights:", weights
return model
def pointwise_testing(X, model):
y = model.predict(X)
return y
##############################
##### Pair-wise approach #####
##############################
def pairwise_train_features(train_data_file, train_rel_file, extraFeaturesInfo=None):
X,y = DocUtils.extractXy_pairWise(train_data_file, train_rel_file, corpus, extraFeaturesInfo)
return (X, y)
def pairwise_test_features(test_data_file, extraFeaturesInfo=None):
X,queries,index_map = DocUtils.extractX_pairWise(test_data_file, corpus, extraFeaturesInfo)
return (X, queries, index_map)
def pairwise_learning(X, y):
model = svm.SVC(kernel='linear', C=1.0)
model.fit(X,y)
weights = model.coef_/np.linalg.norm(model.coef_)
print >> sys.stderr, "Weights:", weights
return model
def pairwise_testing(X, model):
weights = model.coef_/np.linalg.norm(model.coef_)
weights = preprocessing.scale(weights.T)
y = np.dot(X,weights).T
return y[0]
####################
##### Training #####
####################
def train(train_data_file, train_rel_file, task):
sys.stderr.write('\n## Training with feature_file = %s, rel_file = %s ... \n' % (train_data_file, train_rel_file))
if task == 1:
# Step (1): construct your feature and label arrays here
(X, y) = pointwise_train_features(train_data_file, train_rel_file)
# Step (2): implement your learning algorithm here
model = pointwise_learning(X, y)
elif task == 2:
# Step (1): construct your feature and label arrays here
(X, y) = pairwise_train_features(train_data_file, train_rel_file)
# Step (2): implement your learning algorithm here
model = pairwise_learning(X, y)
elif task == 3:
# Add more features
print >> sys.stderr, "Task 3\n"
## Step (1): construct your feature and label arrays here
#extraFeaturesInfo.load("pa3_bm25f_scores.txt", "pa3_window_sizes.txt")
#(X, y) = pointwise_train_features(train_data_file, train_rel_file, extraFeaturesInfo)
#
## Step (2): implement your learning algorithm here
#model = pointwise_learning(X, y)
# Step (1): construct your feature and label arrays here
extraFeaturesInfo.load("pa3_bm25f_scores.txt", "pa3_window_sizes.txt")
(X, y) = pairwise_train_features(train_data_file, train_rel_file, extraFeaturesInfo)
# Step (2): implement your learning algorithm here
model = pairwise_learning(X, y)
elif task == 4:
# Extra credit
print >> sys.stderr, "Extra Credit\n"
# Step (1): construct your feature and label arrays here
(X, y) = pointwise_train_features(train_data_file, train_rel_file)
# Step (2): implement your learning algorithm here
model = pointwise_learning_extra(X, y)
else:
X = [[0, 0], [1, 1], [2, 2]]
y = [0, 1, 2]
model = linear_model.LinearRegression()
model.fit(X, y)
return model
###################
##### Testing #####
###################
def test(test_data_file, model, task):
sys.stderr.write('\n## Testing with feature_file = %s ... \n' % (test_data_file))
if task == 1:
# Step (1): construct your test feature arrays here
(X, queries, index_map) = pointwise_test_features(test_data_file)
# Step (2): implement your prediction code here
y = pointwise_testing(X, model)
elif task == 2:
# Step (1): construct your test feature arrays here
(X, queries, index_map) = pairwise_test_features(test_data_file)
# Step (2): implement your prediction code here
y = pairwise_testing(X, model)
elif task == 3:
# Add more features
print >> sys.stderr, "Task 3\n"
# Generating BM25F and WindowSizes for test_data_file
bm25f_scores_output_file = "bm25f_scores.txt"
Pa3Utils.generateBM25FScoreFile(test_data_file, bm25f_scores_output_file, corpus)
window_sizes_output_file = "window_sizes.txt"
Pa3Utils.generateWindowSizesFile(test_data_file, window_sizes_output_file, corpus)
extraFeaturesInfo.load(bm25f_scores_output_file, window_sizes_output_file)
# Step (1): construct your test feature arrays here
#(X, queries, index_map) = pointwise_test_features(test_data_file, extraFeaturesInfo)
# Step (2): implement your prediction code here
#y = pointwise_testing(X, model)
# Step (1): construct your test feature arrays here
(X, queries, index_map) = pairwise_test_features(test_data_file, extraFeaturesInfo)
# Step (2): implement your prediction code here
y = pairwise_testing(X, model)
elif task == 4:
# Extra credit
print >> sys.stderr, "Extra credit\n"
# Step (1): construct your test feature arrays here
(X, queries, index_map) = pointwise_test_features(test_data_file)
# Step (2): implement your prediction code here
y = pointwise_testing(X, model)
else:
queries = ['query1', 'query2']
index_map = {'query1' : {'url1':0}, 'query2': {'url2':1}}
X = [[0.5, 0.5], [1.5, 1.5]]
y = model.predict(X)
# Step (3): output your ranking result to stdout in the format that will be scored by the ndcg.py code
rankedQueries = DocUtils.getRankedQueries(queries,index_map,y)
DocUtils.printRankedResults(rankedQueries,"ranked.txt")
if __name__ == '__main__':
sys.stderr.write('# Input arguments: %s\n' % str(sys.argv))
if len(sys.argv) != 5:
print >> sys.stderr, "Usage:", sys.argv[0], "train_data_file train_rel_file test_data_file task"
sys.exit(1)
train_data_file = sys.argv[1]
train_rel_file = sys.argv[2]
test_data_file = sys.argv[3]
task = int(sys.argv[4])
print >> sys.stderr, "### Running task", task, "..."
model = train(train_data_file, train_rel_file, task)
test(test_data_file, model, task)
|
Java | UTF-8 | 4,738 | 2.453125 | 2 | [] | no_license | package com.codeoftheweb.salvo.controller;
import com.codeoftheweb.salvo.dto.*;
import com.codeoftheweb.salvo.model.*;
import com.codeoftheweb.salvo.repository.*;
import com.codeoftheweb.salvo.repository.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api")
public class AppController {
@Autowired
private GameRepository gameRepository;
@Autowired
private PlayerRepository playerRepository;
@Autowired
private ShipRepository shipRepository;
@Autowired
private GamePlayerRepository gamePlayerRepository;
@Autowired
private ScoreRepository scoreRepository;
@RequestMapping("/players") //
public List<Object> getPlayers() {
PlayerDTO playerDTO = new PlayerDTO();
return playerRepository.findAll().stream().map(player -> playerDTO.makePlayerDto(player)).collect(Collectors.toList());
}
@RequestMapping(path = "/game_view/{gamePlayerId}", method = RequestMethod.GET) // Returns ony one map per player
public ResponseEntity<Map<String, Object>> getGameView(@PathVariable long gamePlayerId, Authentication authentication) {
GamePlayerDTO gamePlayerDTO = new GamePlayerDTO();
Player player = playerRepository.findByEmail(authentication.getName());
Player gpPlayer = gamePlayerRepository.findById(gamePlayerId).get().getPlayer();
if (Util.isGuest(authentication)) { // Check if guest
return new ResponseEntity<>(Util.makeMap("error", "Not Logged in"), HttpStatus.UNAUTHORIZED);
}
if (player.getId() == gpPlayer.getId()) { // Check if logged in player is that gamePlayer's player
GamePlayer gamePlayer = gamePlayerRepository.findById(gamePlayerId).orElse(null);
if(Util.gameState(gamePlayer).equals("TIE")) {
if (gamePlayer.getGame().getScores().size() < 2) {
Set<Score> scores = new HashSet<Score>();
Score score1 = new Score();
score1.setPlayer(gamePlayer.getPlayer());
score1.setGame(gamePlayer.getGame());
score1.setFinishDate(ZonedDateTime.now());
score1.setScore(0.5D);
scoreRepository.save(score1);
Score score2 = new Score();
score2.setPlayer(Util.getOpponent(gamePlayer).getPlayer());
score2.setGame(gamePlayer.getGame());
score2.setFinishDate(ZonedDateTime.now());
score2.setScore(0.5D);
scoreRepository.save(score2);
scores.add(score1);
scores.add(score2);
gamePlayer.getGame().setScores(scores); // Save scores to that game
}
}else if(Util.gameState(gamePlayer).equals("WON")) {
if (gamePlayer.getGame().getScores().size() < 2) {
Set<Score> scores = new HashSet<Score>();
Score score1 = new Score();
score1.setPlayer(gamePlayer.getPlayer());
score1.setGame(gamePlayer.getGame());
score1.setFinishDate(ZonedDateTime.now());
score1.setScore(1.0D);
scoreRepository.save(score1);
Score score2 = new Score();
score2.setPlayer(Util.getOpponent(gamePlayer).getPlayer());
score2.setGame(gamePlayer.getGame());
score2.setFinishDate(ZonedDateTime.now());
score2.setScore(0.0D);
scoreRepository.save(score2);
scores.add(score1);
scores.add(score2);
Util.getOpponent(gamePlayer).getGame().setScores(scores); // Save scores to that game
}
}
return new ResponseEntity<>(gamePlayerDTO.makeGameView(gamePlayerRepository.findById(gamePlayerId).orElse(null)), HttpStatus.ACCEPTED);
}else{
return new ResponseEntity<>(Util.makeMap("error", "Not the Logged in player"), HttpStatus.UNAUTHORIZED);
}
}
@RequestMapping("/leaderBoard") //
public List<Object> getScores() {
PlayerDTO playerDTO = new PlayerDTO();
return playerRepository.findAll().stream().map(player -> playerDTO.makeScoreDto(player)).collect(Collectors.toList());
}
}
|
PHP | UTF-8 | 2,290 | 2.703125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php declare(strict_types=1);
namespace Tests\Stefna\Mailchimp\Mocks;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class Client extends \Stefna\Mailchimp\Client
{
public function response(ResponseInterface $response)
{
$this->saveResponse($response);
return parent::response($response);
}
public function noOutputResponse(ResponseInterface $response): bool
{
$this->saveResponse($response);
return parent::noOutputResponse($response);
}
protected function sendRequest(RequestInterface $request): ResponseInterface
{
if ($response = $this->mockResponse($request)) {
return $response;
}
return parent::sendRequest($request);
}
protected function getResponseDir(): string
{
return __DIR__ . '/responses/';
}
protected function mockResponse(RequestInterface $request)
{
$file = $this->getResponseFilename($request);
if (!is_file($file)) {
return false;
}
if ($this->logger) {
$this->logger->debug("Reading response from $file");
}
return include $file;
}
protected function getResponseFilename(RequestInterface $request): string
{
$method = strtolower($request->getMethod());
$url = (string)$request->getUri();
$q = parse_url($url, PHP_URL_QUERY);
$queryParams = '';
if ($q) {
$queryParams = "?$q";
$url = substr($url, 0, -1 * strlen($queryParams));
}
$key = str_replace($this->apiEndpoint, '', $url);
$key = trim($key, '/');
return $this->getResponseDir() . $key . '/' . $method . $queryParams . '.php';
}
private function saveResponse(ResponseInterface $response): void
{
if ($this->lastRequest) {
$file = $this->getResponseFilename($this->lastRequest);
if (!is_file($file)) {
$this->writeResponse($file, $response);
}
}
}
private function writeResponse($file, ResponseInterface $response): void
{
$body = $response->getBody();
$body->rewind();
$content = preg_replace("@'@", "\\'", $body->getContents());
$data = "<?php\n\nreturn new \\GuzzleHttp\\Psr7\\Response(\n\t200,\n\t['IsMock' => true],\n\t'$content'\n);\n";
$dir = dirname($file);
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
file_put_contents($file, $data);
if ($this->logger) {
$this->logger->debug("Writing response to $file");
}
$body->rewind();
}
}
|
JavaScript | UTF-8 | 1,022 | 2.53125 | 3 | [] | no_license | import _ from 'lodash';
function sanitize(data, keys) {
return keys.reduce((result, key) => {
const val = _.get(result, key);
if (!val || _.isArray(val) || _.isObject(val)) {
return result;
} else {
return _.set(_.cloneDeep(result), key, '[SANITIZED]');
}
}, data);
}
test('API call', async () => {
// arrange
const username = 'ferrytalecreative';
try {
// act
const response = await realFetch(
// use real fetch, not mocked
`https://www.instagram.com/${username}/?__a=1`
);
// assert (test response)
expect(response).not.toBeNull();
expect(response).toMatchSnapshot();
let json = await response.json();
expect(json).not.toBeNull();
// sanitize the results
json = sanitize(json, [
'graphql.user.biography',
'graphql.user.external_url_linkshimmed',
'graphql.user.edge_owner_to_timeline_media.page_info.end_cursor',
]);
expect(json).toMatchSnapshot();
} catch (e) {
expect(e).toBeNull();
}
});
|
Python | UTF-8 | 4,491 | 2.640625 | 3 | [] | no_license | from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.db.models import ObjectDoesNotExist
from json import dumps
from hrs.models import Dept, Emp, BlogsPost
import time
def index(request):
ctx = {
'greeting': '你好,世界!'
}
return render(request, 'index.html', context=ctx)
def del_dept(request, no='0'):
try:
Dept.objects.get(pk=no).delete()
ctx = {'code': 200}
except (ObjectDoesNotExist, ValueError):
ctx = {'code': 404}
return HttpResponse(
dumps(ctx), content_type='application/json; charset=utf-8')
# 重定向 - 给浏览器一个URL, 让浏览器重新请求指定的页面
# return redirect(reverse('depts'))
# return depts(request)
def emps(request, no='0'):
# no = request.GET['no']
# dept = Dept.objects.get(no=no)
# ForeignKey(Dept, on_delete=models.PROTECT, related_name='emps')
# dept.emps.all()
# emps_list = dept.emp_set.all()
# all() / filter() ==> QuerySet
# QuerySet使用了惰性查询 - 如果不是非得取到数据那么不会发出SQL语句
# 这样做是为了节省服务器内存的开销 - 延迟加载 - 节省空间势必浪费时间
emps_list = list(Emp.objects.filter(dept__no=no).select_related('dept'))
ctx = {'emp_list': emps_list, 'dept_name': emps_list[0].dept.name} \
if len(emps_list) > 0 else {}
return render(request, 'emp.html', context=ctx)
def depts(request):
ctx = {'dept_list': Dept.objects.all()}
return render(request, 'dept.html', context=ctx)
# Create your views here.
def blog_index(request):
blog_list = BlogsPost.objects.all() # 获取所有数据
return render(request,'blogs.html', {'blog_list':blog_list}) # 返回blogs.html
# http://127.0.0.1:8000/helloLC/
def helloLC(request):
dateTimeNow=time.time();
print(dateTimeNow)
print((time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
dateTimeType=(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
dateTimeFormat=str((time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())));
print(type(dateTimeType)) #打印数据类型 <class 'str'>
print(type(dateTimeFormat))
# isinstance()
a = '字符串'
print(isinstance(a, str)) # 判断变量a 是否是字符串类型 True
print(isinstance(a, int)) # 判断变量a 是否是整形 False
ctx = {
'greeting': '你好,世界!',
'dateTimeNow':dateTimeNow,
'dateTimeFormat':dateTimeType
}
return render(request,'helloLC.html', context=ctx)
# 跳转到a+b页面html
def to_add_a_plus_b(request):
return render(request, 'a_plus_b.html')
# a+b 表单操作
def add_a_plus_b(request):
a = request.GET['a']
b = request.GET['b']
try:
if is_number(a) == True and is_number(b) == True:
print(type(a))
print(type(eval(a)))
print(type(a) == int)
print(type(eval(a)) == int)
if(type(eval(a)) == int):
a = int(a)
print('1-int-'+str(a))
else:
a = float(a)
print('2-float-' + str(a))
if (type(eval(b)) == int):
b = int(b)
print('3-int-' +str(b))
else:
b = float(b)
print('4-float-' + str(b))
return HttpResponse(str(a + b))
else:
return HttpResponse(str('a和b都请输入数字,小数和整数均可!'))
except ValueError and NameError:
print("Oops! That was no valid number. Try again ")
# 是否为数字的方法
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
# form post提交-action="/hrs/toAddFormPage/"
# 引入我们创建的表单类
from .formsPost import AddForm
def toAddFormPage(request):
if request.method == 'POST': # 当提交表单时
form = AddForm(request.POST) # form 包含提交的数据
if form.is_valid(): # 如果提交的数据合法
a = form.cleaned_data['a']
b = form.cleaned_data['b']
return HttpResponse(str(int(a) + int(b)))
else: # 当正常访问时
form = AddForm()
return render(request, 'a_plus_b_post.html', {'form': form})
|
Swift | UTF-8 | 1,511 | 2.59375 | 3 | [] | no_license | //
// IndicatorView.swift
// Vipassana
//
// Created by Dasha Chastokolenko on 5/16/19.
// Copyright © 2019 Dasha Chastokolenko. All rights reserved.
//
import UIKit
import Lottie
class InStatIndicatorView: UIView {
let animationView = AnimationView(name: "InStatIndicator")
override func awakeFromNib() {
super.awakeFromNib()
setupIndicator()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupIndicator()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setupIndicator() {
//animationView.loopMode = true
animationView.translatesAutoresizingMaskIntoConstraints = false
addSubview(animationView)
animationView.widthAnchor.constraint(equalToConstant: 30).isActive = true
animationView.heightAnchor.constraint(equalToConstant: 18).isActive = true
animationView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
animationView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
backgroundColor = UIColor(white: 1, alpha: 0.4)
}
}
extension InStatIndicatorView {
func startAnimation() {
DispatchQueue.main.async {
self.animationView.play()
self.isHidden = false
}
}
func stopAnimation() {
DispatchQueue.main.async {
self.isHidden = true
self.animationView.stop()
}
}
}
|
JavaScript | UTF-8 | 225 | 3.40625 | 3 | [
"MIT"
] | permissive | 'use strict';
function factorsOf(n) {
const factors = [];
for (let i = 1; i <= n; i++) { // change on this line
if (n / i === Math.floor(n / i)) {
factors.push(i);
}
} return factors;
} |
JavaScript | UTF-8 | 2,028 | 2.65625 | 3 | [] | no_license | $( function() {
$( "#slider-range1" ).slider({
range: true,
min: 0,
max: 6,
values: [ 3, 6 ],
slide: function( event, ui ) {
$( "#floor" ).val( ui.values[ 0 ] );
$( "#floor1" ).val( ui.values[ 1 ] );
}
});
$( "#floor" ).val( $( "#slider-range1" ).slider( "values", 0 ) );
$( "#floor1" ).val( $( "#slider-range1" ).slider( "values", 1 ) );
} );
$('.filter__btn-reset').click(function() {
$( "#slider-range1" ).slider({
values: [ 3, 6 ],
slide: function( event, ui ) {
$( "#floor" ).val( ui.values[ 0 ] );
$( "#floor1" ).val( ui.values[ 1 ] );
}
});
});
$( function() {
$( "#slider-range2" ).slider({
range: true,
min: 1891450,
max: 4531340,
values: [ 1891450, 4531340 ],
slide: function( event, ui ) {
$( "#price" ).val( ui.values[ 0 ] );
$( "#price1" ).val( ui.values[ 1 ] );
}
});
$( "#price" ).val( $( "#slider-range2" ).slider( "values", 0 ) );
$( "#price1" ).val( $( "#slider-range2" ).slider( "values", 1 ) );
} );
$('.filter__btn-reset').click(function() {
$( "#slider-range2" ).slider({
values: [ 1891450, 4531340 ],
slide: function( event, ui ) {
$( "#price" ).val( ui.values[ 0 ] );
$( "#price1" ).val( ui.values[ 1 ] );
}
});
});
$( function() {
$( "#slider-range3" ).slider({
range: true,
min: 0,
max: 78.4,
values: [ 25, 78.4 ],
slide: function( event, ui ) {
$( "#scq" ).val( ui.values[ 0 ] );
$( "#scq1" ).val( ui.values[ 1 ] );
}
});
$( "#scq" ).val( $( "#slider-range3" ).slider( "values", 0 ) );
$( "#scq1" ).val( $( "#slider-range3" ).slider( "values", 1 ) );
} );
$('.filter__btn-reset').click(function() {
$( "#slider-range3" ).slider({
values: [ 25, 78.4 ],
slide: function( event, ui ) {
$( "#scq" ).val( ui.values[ 0 ] );
$( "#scq1" ).val( ui.values[ 1 ] );
}
});
});
|
Java | UTF-8 | 818 | 2 | 2 | [] | no_license | package week1.dianshangjinjie.bw.com.demo4.api;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Query;
import week1.dianshangjinjie.bw.com.demo4.bean.CarBean;
import week1.dianshangjinjie.bw.com.demo4.bean.Product;
import week1.dianshangjinjie.bw.com.demo4.bean.ShopBean;
public interface ApiService {
@GET("small/order/verify/v1/findShoppingCart")
Observable<CarBean> getCar(@Header("userId") int uid, @Header("sessionId") String sid);
@GET("small/commodity/v1/findCategory")
Observable<ShopBean> getClz(@Header("userId") int uid, @Header("sessionId") String sid);
@GET("small/commodity/v1/findCommodityByCategory")
Observable<Product> getPro(@Query("categoryId")String cid,@Query("page") int page,@Query("count") int count);
}
|
Java | UTF-8 | 20,319 | 1.710938 | 2 | [
"Apache-2.0"
] | permissive | package com.rowland.onboarderwithstepperindicator.view;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.UiThread;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import com.rowland.onboarderwithstepperindicator.R;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("unused")
public class StepperIndicator extends View implements ViewPager.OnPageChangeListener {
private static final int DEFAULT_ANIMATION_DURATION = 250;
private static final float EXPAND_MARK = 1.3f;
private Paint circlePaint;
private Paint linePaint;
private Paint lineDonePaint;
private Paint lineDoneAnimatedPaint;
private Paint indicatorPaint;
private List<Path> linePathList = new ArrayList<>();
private float animProgress;
private float animIndicatorRadius;
private float animCheckRadius;
private float lineLength;
private float checkRadius;
// Modifiable at runtime using setters
private int mLineDoneColor;
private float mCircleStrokeWidth;
private int mCircleColor;
private int mIndicatorColor;
private int mLineColor;
private float mLineStrokeWidth;
private float mCircleRadius;
private float mIndicatorRadius;
private float mLineMargin;
private int mAnimationDuration;
private int stepCount;
private int currentStep;
private float[] indicators;
private ViewPager pager;
private Bitmap doneIcon;
private AnimatorSet animatorSet;
private ObjectAnimator lineAnimator, indicatorAnimator, checkAnimator;
private int previousStep;
public StepperIndicator(Context context) {
this(context, null);
}
public StepperIndicator(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public StepperIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public StepperIndicator(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr);
}
private static PathEffect createPathEffect(float pathLength, float phase, float offset) {
return new DashPathEffect(new float[]{pathLength, pathLength},
Math.max(phase * pathLength, offset));
}
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
final Resources resources = getResources();
// Default value
int defaultCircleColor = ContextCompat.getColor(context, R.color.stpi_default_circle_color);
float defaultCircleRadius = resources.getDimension(R.dimen.stpi_default_circle_radius);
float defaultCircleStrokeWidth = resources.getDimension(R.dimen.stpi_default_circle_stroke_width);
int defaultIndicatorColor = ContextCompat.getColor(context, R.color.stpi_default_indicator_color);
float defaultIndicatorRadius = resources.getDimension(R.dimen.stpi_default_indicator_radius);
float defaultLineStrokeWidth = resources.getDimension(R.dimen.stpi_default_line_stroke_width);
float defaultLineMargin = resources.getDimension(R.dimen.stpi_default_line_margin);
int defaultLineColor = ContextCompat.getColor(context, R.color.stpi_default_line_color);
int defaultLineDoneColor = ContextCompat.getColor(context, R.color.stpi_default_line_done_color);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StepperIndicator, defStyleAttr, 0);
circlePaint = new Paint();
mCircleStrokeWidth = a.getDimension(R.styleable.StepperIndicator_stpi_circleStrokeWidth, defaultCircleStrokeWidth);
circlePaint.setStrokeWidth(mCircleStrokeWidth);
circlePaint.setStyle(Paint.Style.STROKE);
mCircleColor = a.getColor(R.styleable.StepperIndicator_stpi_circleColor, defaultCircleColor);
circlePaint.setColor(mCircleColor);
circlePaint.setAntiAlias(true);
indicatorPaint = new Paint(circlePaint);
indicatorPaint.setStyle(Paint.Style.FILL);
mIndicatorColor = a.getColor(R.styleable.StepperIndicator_stpi_indicatorColor, defaultIndicatorColor);
indicatorPaint.setColor(mIndicatorColor);
indicatorPaint.setAntiAlias(true);
linePaint = new Paint();
mLineStrokeWidth = a.getDimension(R.styleable.StepperIndicator_stpi_lineStrokeWidth, defaultLineStrokeWidth);
linePaint.setStrokeWidth(mLineStrokeWidth);
linePaint.setStrokeCap(Paint.Cap.ROUND);
linePaint.setStyle(Paint.Style.STROKE);
mLineColor = a.getColor(R.styleable.StepperIndicator_stpi_lineColor, defaultLineColor);
linePaint.setColor(mLineColor);
linePaint.setAntiAlias(true);
lineDonePaint = new Paint(linePaint);
mLineDoneColor = a.getColor(R.styleable.StepperIndicator_stpi_lineDoneColor, defaultLineDoneColor);
lineDonePaint.setColor(mLineDoneColor);
lineDoneAnimatedPaint = new Paint(lineDonePaint);
mCircleRadius = a.getDimension(R.styleable.StepperIndicator_stpi_circleRadius, defaultCircleRadius);
checkRadius = mCircleRadius + circlePaint.getStrokeWidth() / 2f;
mIndicatorRadius = a.getDimension(R.styleable.StepperIndicator_stpi_indicatorRadius, defaultIndicatorRadius);
animIndicatorRadius = mIndicatorRadius;
animCheckRadius = checkRadius;
mLineMargin = a.getDimension(R.styleable.StepperIndicator_stpi_lineMargin, defaultLineMargin);
setStepCount(a.getInteger(R.styleable.StepperIndicator_stpi_stepCount, 2));
;
mAnimationDuration = a.getInteger(R.styleable.StepperIndicator_stpi_animDuration, DEFAULT_ANIMATION_DURATION);
a.recycle();
doneIcon = BitmapFactory.decodeResource(resources, R.drawable.ic_done_white_18dp);
if (isInEditMode())
currentStep = Math.max((int) Math.ceil(stepCount / 2f), 1);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
compute();
}
private void compute() {
indicators = new float[stepCount];
linePathList.clear();
float startX = mCircleRadius * EXPAND_MARK + circlePaint.getStrokeWidth() / 2f;
// Compute position of indicators and line length
float divider = (getMeasuredWidth() - startX * 2f) / (stepCount - 1);
lineLength = divider - (mCircleRadius * 2f + circlePaint.getStrokeWidth()) - (mLineMargin * 2);
// Compute position of circles and lines once
for (int i = 0; i < indicators.length; i++)
indicators[i] = startX + divider * i;
for (int i = 0; i < indicators.length - 1; i++) {
float position = ((indicators[i] + indicators[i + 1]) / 2) - lineLength / 2;
final Path linePath = new Path();
linePath.moveTo(position, getMeasuredHeight() / 2);
linePath.lineTo(position + lineLength, getMeasuredHeight() / 2);
linePathList.add(linePath);
}
}
@SuppressWarnings("ConstantConditions")
@Override
protected void onDraw(Canvas canvas) {
float centerY = getMeasuredHeight() / 2f;
// Currently Drawing animation from step n-1 to n, or back from n+1 to n
boolean inAnimation = false;
boolean inLineAnimation = false;
boolean inIndicatorAnimation = false;
boolean inCheckAnimation = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
inAnimation = animatorSet != null && animatorSet.isRunning();
inLineAnimation = lineAnimator != null && lineAnimator.isRunning();
inIndicatorAnimation = indicatorAnimator != null && indicatorAnimator.isRunning();
inCheckAnimation = checkAnimator != null && checkAnimator.isRunning();
}
boolean drawToNext = previousStep == currentStep - 1;
boolean drawFromNext = previousStep == currentStep + 1;
for (int i = 0; i < indicators.length; i++) {
final float indicator = indicators[i];
boolean drawCheck = i < currentStep || (drawFromNext && i == currentStep);
// Draw back circle
canvas.drawCircle(indicator, centerY, mCircleRadius, circlePaint);
// If current step, or coming back from next step and still animating
if ((i == currentStep && !drawFromNext) || (i == previousStep && drawFromNext && inAnimation)) {
// Draw animated indicator
canvas.drawCircle(indicator, centerY, animIndicatorRadius, indicatorPaint);
}
// Draw check mark
if (drawCheck) {
float radius = checkRadius;
if ((i == previousStep && drawToNext)
|| (i == currentStep && drawFromNext))
radius = animCheckRadius;
canvas.drawCircle(indicator, centerY, radius, indicatorPaint);
if (!isInEditMode()) {
if ((i != previousStep && i != currentStep) || (!inCheckAnimation && !(i == currentStep && !inAnimation)))
canvas.drawBitmap(doneIcon, indicator - (doneIcon.getWidth() / 2), centerY - (doneIcon.getHeight() / 2), null);
}
}
// Draw lines
if (i < linePathList.size()) {
if (i >= currentStep) {
canvas.drawPath(linePathList.get(i), linePaint);
if (i == currentStep && drawFromNext && (inLineAnimation || inIndicatorAnimation)) // Coming back from n+1
canvas.drawPath(linePathList.get(i), lineDoneAnimatedPaint);
} else {
if (i == currentStep - 1 && drawToNext && inLineAnimation) {
// Going to n+1
canvas.drawPath(linePathList.get(i), linePaint);
canvas.drawPath(linePathList.get(i), lineDoneAnimatedPaint);
} else
canvas.drawPath(linePathList.get(i), lineDonePaint);
}
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredHeight = (int) Math.ceil((mCircleRadius * EXPAND_MARK * 2) + circlePaint.getStrokeWidth());
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width = widthMode == MeasureSpec.EXACTLY ? widthSize : getSuggestedMinimumWidth();
int height = heightMode == MeasureSpec.EXACTLY ? heightSize : desiredHeight;
setMeasuredDimension(width, height);
}
public int getStepCount() {
return stepCount;
}
public void setStepCount(int stepCount) {
if (stepCount < 2)
throw new IllegalArgumentException("stepCount must be >= 2");
this.stepCount = stepCount;
currentStep = 0;
compute();
invalidate();
}
public int getCurrentStep() {
return currentStep;
}
/**
* Sets the current step
*
* @param currentStep a value between 0 (inclusive) and stepCount (inclusive)
*/
@UiThread
public void setCurrentStep(int currentStep) {
if (currentStep < 0 || currentStep > stepCount)
throw new IllegalArgumentException("Invalid step value " + currentStep);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (animatorSet != null)
animatorSet.cancel();
animatorSet = null;
lineAnimator = null;
indicatorAnimator = null;
if (currentStep == this.currentStep + 1) {
previousStep = this.currentStep;
animatorSet = new AnimatorSet();
// First, draw line to new
lineAnimator = ObjectAnimator.ofFloat(StepperIndicator.this, "animProgress", 1.0f, 0.0f);
// Same time, pop check mark
checkAnimator = ObjectAnimator
.ofFloat(StepperIndicator.this, "animCheckRadius", mIndicatorRadius, checkRadius * EXPAND_MARK, checkRadius);
// Finally, pop current step indicator
animIndicatorRadius = 0;
indicatorAnimator = ObjectAnimator
.ofFloat(StepperIndicator.this, "animIndicatorRadius", 0f, mIndicatorRadius * 1.4f, mIndicatorRadius);
animatorSet.play(lineAnimator).with(checkAnimator).before(indicatorAnimator);
} else if (currentStep == this.currentStep - 1) {
previousStep = this.currentStep;
animatorSet = new AnimatorSet();
// First, pop out current step indicator
indicatorAnimator = ObjectAnimator.ofFloat(StepperIndicator.this, "animIndicatorRadius", mIndicatorRadius, 0f);
// Then delete line
animProgress = 1.0f;
lineDoneAnimatedPaint.setPathEffect(null);
lineAnimator = ObjectAnimator.ofFloat(StepperIndicator.this, "animProgress", 0.0f, 1.0f);
// Finally, pop out check mark to display step indicator
animCheckRadius = checkRadius;
checkAnimator = ObjectAnimator.ofFloat(StepperIndicator.this, "animCheckRadius", checkRadius, mIndicatorRadius);
animatorSet.playSequentially(indicatorAnimator, lineAnimator, checkAnimator);
}
if (animatorSet != null) {
lineAnimator.setDuration(Math.min(500, mAnimationDuration));
lineAnimator.setInterpolator(new DecelerateInterpolator());
indicatorAnimator.setDuration(lineAnimator.getDuration() / 2);
checkAnimator.setDuration(lineAnimator.getDuration() / 2);
animatorSet.start();
}
}
this.currentStep = currentStep;
invalidate();
}
/**
* DO NOT CALL, used by animation to draw line
*/
public void setAnimProgress(float animProgress) {
this.animProgress = animProgress;
lineDoneAnimatedPaint.setPathEffect(createPathEffect(lineLength, animProgress, 0.0f));
invalidate();
}
public void setAnimIndicatorRadius(float animIndicatorRadius) {
this.animIndicatorRadius = animIndicatorRadius;
invalidate();
}
public void setAnimCheckRadius(float animCheckRadius) {
this.animCheckRadius = animCheckRadius;
invalidate();
}
public void setViewPager(ViewPager pager) {
if (pager.getAdapter() == null)
throw new IllegalStateException("ViewPager does not have adapter instance.");
setViewPager(pager, pager.getAdapter().getCount());
}
/**
* Sets the pager associated with this indicator
*
* @param pager viewpager to attach
* @param keepLastPage true if should not create an indicator for the last page, to use it as the final page
*/
public void setViewPager(ViewPager pager, boolean keepLastPage) {
if (pager.getAdapter() == null)
throw new IllegalStateException("ViewPager does not have adapter instance.");
setViewPager(pager, pager.getAdapter().getCount() - (keepLastPage ? 1 : 0));
}
/**
* Sets the pager associated with this indicator
*
* @param pager viewpager to attach
* @param stepCount the real page count to display (use this if you are using looped viewpager to indicate the real number of pages)
*/
public void setViewPager(ViewPager pager, int stepCount) {
if (this.pager == pager)
return;
if (this.pager != null)
pager.removeOnPageChangeListener(this);
if (pager.getAdapter() == null)
throw new IllegalStateException("ViewPager does not have adapter instance.");
this.pager = pager;
this.stepCount = stepCount;
currentStep = 0;
pager.addOnPageChangeListener(this);
invalidate();
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
setCurrentStep(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
currentStep = savedState.currentStep;
requestLayout();
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState savedState = new SavedState(superState);
savedState.currentStep = currentStep;
return savedState;
}
static class SavedState extends BaseSavedState {
@SuppressWarnings("UnusedDeclaration")
public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
private int currentStep;
public SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
currentStep = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(currentStep);
}
}
public void setLineColor(int lineColor) {
this.mLineColor = lineColor;
linePaint.setColor(mLineColor);
update();
}
public void setIndicatorColor(int indicatorColor) {
this.mIndicatorColor = indicatorColor;
indicatorPaint.setColor(mIndicatorColor);
update();
}
public void setCircleColor(int circleColor) {
this.mCircleColor = circleColor;
circlePaint.setColor(mCircleColor);
update();
}
public void setLineDoneColor(int lineDoneColor) {
this.mLineDoneColor = lineDoneColor;
lineDonePaint.setColor(mLineDoneColor);
lineDoneAnimatedPaint = new Paint(lineDonePaint);
update();
}
public void setCircleStrokeWidth(float circleStrokeWidth) {
this.mCircleStrokeWidth = circleStrokeWidth;
update();
}
public void setLineStrokeWidth(float lineStrokeWidth) {
this.mLineStrokeWidth = lineStrokeWidth;
update();
}
public void setCircleRadius(float circleRadius) {
this.mCircleRadius = circleRadius;
update();
}
public void setIndicatorRadius(float indicatorRadius) {
this.mIndicatorRadius = indicatorRadius;
update();
}
public void setLineMargin(float lineMargin) {
this.mLineMargin = lineMargin;
update();
}
public void setAnimationDuration(int animationDuration) {
this.mAnimationDuration = animationDuration;
update();
}
private void update() {
invalidate();
// requestLayout();
}
}
|
Java | UTF-8 | 1,630 | 2.28125 | 2 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"GPL-2.0-only",
"xpp",
"CC-BY-3.0",
"EPL-1.0",
"Classpath-exception-2.0",
"CPL-1.0",
"CDDL-1.0",
"MIT",
"LGPL-2.1-only",
"MPL-2.0",
"MPL-1.1",
"LicenseRef-scancode-unknown-license-reference",
... | permissive | /**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.portal.portlet.marketplace;
import java.util.ArrayList;
import java.util.List;
public class ScreenShot{
private String url;
private List<String> captions;
public ScreenShot(String url){
this.setUrl(url);
this.setCaptions(new ArrayList<String>());
}
public ScreenShot(String url, List<String> captions){
this.setUrl(url);
this.setCaptions(captions);
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
/**
* @author vertein
* @return the captions for a screen shot. Will not return null, might return empty list.
*/
public List<String> getCaptions() {
if(captions==null){
this.captions = new ArrayList<String>();
}
return captions;
}
private void setCaptions(List<String> captions) {
this.captions = captions;
}
}
|
Java | UTF-8 | 2,188 | 3.59375 | 4 | [] | no_license | package com.ray.leetcode.resolved;
import com.ray.util.Out;
/**
* Verify Preorder Serialization of a Binary Tree
* -----------------------------------------------------------------------------
* One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #.
* _9_
* / \
* 3 2
* / \ / \
* 4 1 # 6
* / \ / \ / \
* # # # # # #
* For example, the above binary tree can be serialized to the string 9,3,4,#,#,1,#,#,2,#,6,#,#, where # represents a null node.
* Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.
* Each comma separated value in the string must be either an integer or a character '#' representing null pointer.
* You may assume that the input format is always valid, for example it could never contain two consecutive commas such as 1,,3.
*
* Example:
* Example 1
* Input: 9,3,4,#,#,1,#,#,2,#,6,#,#
* Output: true
* Example 2
* Input: 1,#
* Output: false
* Example 3
* Input: 9,#,#,1
* Output: false
*
* Level : Medium
*
* @author ray
* @link https://leetcode-cn.com/problems/verify-preorder-serialization-of-a-binary-tree/
* @since 2020-03-14 13:44:42
*/
public class L0331_Verify_Preorder_Serialization_of_a_Binary_Tree {
static class Solution {
public boolean isValidSerialization(String preorder) {
int slot = 1;
for (int i = 0; i < preorder.length(); i ++) {
if (preorder.charAt(i) == '#') {
slot --;
} else if (preorder.charAt(i) != ',') {
slot ++;
while (i < preorder.length() - 1 && preorder.charAt(i + 1) != ',') i ++;
}
if (slot < 0 || slot == 0 && i < preorder.length()-1) return false;
}
return slot == 0;
}
}
public static void main(String[] args) {
Out.p(new Solution());
}
}
|
C++ | UTF-8 | 534 | 2.53125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Actor.h"
namespace bulletNS{
const float SCALE_X = .7;
const float SCALE_Y = .2;
const float SCALE_Z = .4;
const float LINESPAN = 1;
const float DAMAGE = 1;//Hits for 25 points of damage
};
class Bullet : public virtual Actor
{
private:
float lifeTime;
public:
void create(Vector3 pos){Actor::create(pos);lifeTime = 0;}
void init(NuclearLiberation* game,Geometry *b, float r){Actor::init(game,b,r); setScale(Vector3(bulletNS::SCALE_X,bulletNS::SCALE_Y,bulletNS::SCALE_Z));}
void update(float dt);
}; |
JavaScript | UTF-8 | 945 | 3.46875 | 3 | [
"MIT"
] | permissive | function unset() {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir (http://brett-zamir.me)
// * example 1: var arr = ['a', 'b', 'c'];
// * example 1: unset('arr[1]');
// * returns 1: undefined
// Must pass in a STRING to indicate the variable, not the variable itself (whether or not that evaluates to a string)
// Works only on globals
var i = 0, arg = '', win = '', winRef = /^(?:this)?window[.[]/, arr = [], accessor = '', bracket = /\[['"]?(\d+)['"]?\]$/;
for (i = 0; i < arguments.length; i++) {
arg = arguments[i];
winRef.lastIndex = 0, bracket.lastIndex = 0;
win = winRef.test(arg) ? '' : 'this.window.';
if (bracket.test(arg)) {
accessor = arg.match(bracket)[1];
arr = eval(win + arg.replace(bracket, ''));
arr.splice(accessor, 1); // We remove from the array entirely, rather than leaving a gap
}
else {
eval('delete ' + win + arg);
}
}
}
|
JavaScript | UTF-8 | 952 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | import Flickity from 'flickity';
const homeCarousel = document.querySelector('.home-intro');
const homeSlideCount = homeCarousel.childElementCount;
const prevButton = document.querySelector('.flickity-button.previous');
const nextButton = document.querySelector('.flickity-button.next');
const flkty = new Flickity(homeCarousel, {
cellAlign: 'left',
pageDots: false,
autoPlay: 6000,
wrapAround: homeSlideCount > 2 ? true : false,
contain: homeSlideCount < 3 ? true : false,
prevNextButtons: false
});
prevButton.onclick = (e) => {
flkty.previous();
}
nextButton.onclick = (e) => {
flkty.next();
}
// if wrap isn't enabled and at end, add class to button
if (homeSlideCount == 2) {
flkty.on('select', function(index) {
if (index == (homeSlideCount - 1)) {
nextButton.disabled = true;
prevButton.disabled = false;
} else {
prevButton.disabled = true;
nextButton.disabled = false;
}
});
}
|
C | UTF-8 | 2,221 | 3.03125 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* validation.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: elchrist <elchrist@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/12 18:02:40 by elchrist #+# #+# */
/* Updated: 2019/02/12 19:18:18 by elchrist ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
int check_size(char **tetr)
{
int x;
int y;
int size;
y = 0;
size = 0;
while (y < 4)
{
x = 0;
while (x < 5)
{
if (tetr[y][x] == '#')
size++;
x++;
}
y++;
}
return (size);
}
int check_link(char **tetr, int x, int y)
{
int link;
link = 0;
while (y < 4)
{
x = 0;
while (x < 5)
{
if (tetr[y][x] == '#')
{
if ((x < 4) && (tetr[y][x + 1] == '#'))
link++;
if ((x > 0) && (tetr[y][x - 1] == '#'))
link++;
if ((y < 3) && (tetr[y + 1][x] == '#'))
link++;
if ((y > 0) && (tetr[y - 1][x] == '#'))
link++;
}
x++;
}
y++;
}
return (link);
}
int check_points(char **tetr)
{
int x;
int y;
int points;
y = 0;
points = 0;
while (y < 4)
{
x = 0;
while (x < 5)
{
if (tetr[y][x] == '#' || tetr[y][x] == '.')
points++;
x++;
}
y++;
}
return (points);
}
int check_newline(char **tetr)
{
int x;
int y;
int newline;
y = 0;
while (tetr[y])
{
x = 0;
newline = 0;
while (x < 5)
{
if (tetr[y][x] == '\n')
newline++;
x++;
}
if (newline > 1)
return (1);
y++;
}
return (0);
}
void valid_check(char **tetr)
{
if ((check_points(tetr) != 16) || (check_size(tetr) != 4)
|| ((check_link(tetr, 0, 0) != 6) && (check_link(tetr, 0, 0) != 8))
|| (check_newline(tetr) == 1))
it_is_error();
}
|
Java | UTF-8 | 457 | 1.515625 | 2 | [] | no_license | package com.nooblog;
import com.nooblog.mail.EmailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.mail.javamail.JavaMailSender;
@SpringBootApplication
public class ServerMain {
public static void main(String[] args) {
SpringApplication.run(ServerMain.class, args);
}
}
|
Python | UTF-8 | 453 | 3 | 3 | [] | no_license | from dictionary import *
def decompose(turn):
frags = turn.split(" ")
# FIND THE KEYWORD
key = []
for w in frags:
if(w in keywords):
key.append(w)
# CREATE PATTERN OUT OF FRAGMENTS
pattern = []
segment = ""
for token in frags:
if(token in key):
if(len(segment) > 0):
pattern.append(segment)
pattern.append(token)
segment = ""
else:
segment += token
segment += " "
pattern.append(segment)
return pattern, key
|
TypeScript | UTF-8 | 3,669 | 2.671875 | 3 | [
"MIT"
] | permissive | import * as ts from 'typescript';
import { getNodeTags } from '../src';
describe('[code-analyzer] › utils › check node tags', () => {
test('normal node should return no node tags', () => {
const code = 'const VARIABLE = "test";';
const sourceFile = ts.createSourceFile('', code, ts.ScriptTarget.Latest, true);
const tags = getNodeTags(sourceFile.statements[0]);
expect(tags).toBeInstanceOf(Array);
expect(tags).toHaveLength(0);
});
test('exported node should contain exported', () => {
const code = 'export const VARIABLE = "test";';
const sourceFile = ts.createSourceFile('', code, ts.ScriptTarget.Latest, true);
const tags = getNodeTags(sourceFile.statements[0]);
expect(tags).toBeInstanceOf(Array);
expect(tags).toHaveLength(1);
expect(tags).toContain('exported');
});
test('jsdoc with design unrelated', () => {
const code = `
/** @design-unrelated */
const VARIABLE = "test";`;
const sourceFile = ts.createSourceFile('', code, ts.ScriptTarget.Latest, true);
const tags = getNodeTags(sourceFile.statements[0]);
expect(tags).toBeInstanceOf(Array);
expect(tags).toHaveLength(1);
expect(tags).toContain('unrelated');
});
test('jsdoc with design unrelated and internal', () => {
const code = `
/** @internal */
/** @design-unrelated */
export const VARIABLE = "test";`;
const sourceFile = ts.createSourceFile('', code, ts.ScriptTarget.Latest, true);
const tags = getNodeTags(sourceFile.statements[0]);
expect(tags).toBeInstanceOf(Array);
expect(tags).toHaveLength(3);
expect(tags).toContain('internal');
expect(tags).toContain('unrelated');
expect(tags).toContain('exported');
});
test('jsdoc with underscore variable', () => {
const code = 'const _underscored = "test";';
const sourceFile = ts.createSourceFile('', code, ts.ScriptTarget.Latest, true);
const tags = getNodeTags(sourceFile.statements[0]);
expect(tags).toBeInstanceOf(Array);
expect(tags).toHaveLength(1);
expect(tags).toContain('hasUnderscore');
});
test('private property in class', () => {
const code = `
export class Test {
private propertyItem: string = 'test';
}
`;
const sourceFile = ts.createSourceFile('', code, ts.ScriptTarget.Latest, true);
const tags = getNodeTags((sourceFile.statements[0] as ts.ClassDeclaration).members[0]);
expect(tags).toBeInstanceOf(Array);
expect(tags).toHaveLength(1);
expect(tags).toContain('private');
});
test('private property with jsdoc design unrelated in class', () => {
const code = `
export class Test {
/** @design-unrelated */
private propertyItem: string = 'test';
}
`;
const sourceFile = ts.createSourceFile('', code, ts.ScriptTarget.Latest, true);
const tags = getNodeTags((sourceFile.statements[0] as ts.ClassDeclaration).members[0]);
expect(tags).toBeInstanceOf(Array);
expect(tags).toHaveLength(2);
expect(tags).toContain('private');
expect(tags).toContain('unrelated');
});
test('component that does not need combinations', () => {
const code = `
/**
* some comment for the component
* @see linktoanything
* @no-design-combinations
* @example
*/
@Component({
moduleId: module.id,
selector: 'dt-icon',
})
export class DtIcon {
/** @design-unrelated */
private propertyItem: string = 'test';
}
`;
const sourceFile = ts.createSourceFile('', code, ts.ScriptTarget.Latest, true);
const tags = getNodeTags((sourceFile.statements[0]));
expect(tags).toBeInstanceOf(Array);
expect(tags).toHaveLength(2);
expect(tags).toContain('exported');
expect(tags).toContain('noCombinations');
});
});
|
Java | UTF-8 | 1,213 | 2.171875 | 2 | [] | no_license | package e.kiosque.appca.ModelData.PosteDetenteGaz;
import com.mapbox.geojson.Geometry;
import com.mapbox.geojson.Point;
public class PosteDetenteGaz {
private String nom;
private String commune;
private int insee;
private int idKey;
private Point geometry;
public PosteDetenteGaz(String nom, String commune, int insee, int idKey, Point geometry) {
this.nom = nom;
this.commune = commune;
this.insee = insee;
this.idKey = idKey;
this.geometry = geometry;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getCommune() {
return commune;
}
public void setCommune(String commune) {
this.commune = commune;
}
public int getInsee() {
return insee;
}
public void setInsee(int insee) {
this.insee = insee;
}
public int getIdKey() {
return idKey;
}
public void setIdKey(int idKey) {
this.idKey = idKey;
}
public Point getGeometry() {
return geometry;
}
public void setGeometry(Point geometry) {
this.geometry = geometry;
}
}
|
C# | UTF-8 | 810 | 2.6875 | 3 | [] | no_license | namespace AutoProcessor
{
public class BranchingProcess : Process
{
private Process _flagProcess;
private Process _ifFinished;
private Process _ifNotFinished;
public BranchingProcess(Process flagProcess, Process ifFinished, Process ifNotFinished)
{
_flagProcess = flagProcess;
_ifFinished = ifFinished;
_ifNotFinished = ifNotFinished;
ProcessStatus = Status.NotStarted;
}
public override void Start()
{
ProcessStatus = Status.Launched;
if (_flagProcess.ProcessStatus == Status.Finished)
NextProcess = _ifFinished;
else
NextProcess = _ifNotFinished;
ProcessStatus = Status.Finished;
}
}
}
|
Java | UTF-8 | 1,165 | 2.3125 | 2 | [] | no_license | package fr.tse.applicationDistrib.controller;
import java.util.List;
import org.json.JSONException;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import fr.tse.applicationDistrib.dto.EmployeeDTO;
import fr.tse.applicationDistrib.entity.Employee;
import fr.tse.applicationDistrib.repository.EmployeeRepository;
@RestController
public class SalaryRestController {
@Autowired
EmployeeRepository repo;
@RequestMapping(path = "/salaries-json",method = RequestMethod.POST)
public List<EmployeeDTO> consumeJson() throws JSONException {
ModelMapper modelMapper = new ModelMapper();
List<Employee> employee = repo.findAllByOrderBySalaryAsc();
// Define the target type
java.lang.reflect.Type targetListType = new TypeToken<List<EmployeeDTO>>() {}.getType();
List<EmployeeDTO> employeeDTO = modelMapper.map(employee, targetListType);
return employeeDTO;
}
}
|
C++ | UTF-8 | 565 | 3.28125 | 3 | [] | no_license | #include<stack>
using namespace std;
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* kthSmallestNode(BinaryTreeNode* root, int k) {
if (root == nullptr || k < 0) {
return nullptr;
}
stack<BinaryTreeNode*> stack;
BinaryTreeNode* pNode = root;
if (pNode || !stack.empty()) {
if (pNode) {
stack.push(pNode);
pNode = pNode->m_pLeft;
}
else {
pNode = stack.top();
stack.pop();
k--;
if (k == 0) {
return pNode;
}
pNode = pNode->m_pRight;
}
}
return 0;
} |
Markdown | UTF-8 | 2,544 | 2.9375 | 3 | [
"BSD-3-Clause"
] | permissive | ---
title: "Ответ на \"C#: фильтрация ip-адресов\""
se.owner.user_id: 240512
se.owner.display_name: "MSDN.WhiteKnight"
se.owner.link: "https://ru.stackoverflow.com/users/240512/msdn-whiteknight"
se.answer_id: 830696
se.question_id: 830562
se.post_type: answer
se.is_accepted: True
---
<p>Добавьте ссылку на System.Management и используйте WMI-запрос к классу <em>Win32_NetworkAdapter</em>, у реальных интерфейсов должно быть <em>PhysicalAdapter=true</em>. Для получения Guid интерфейса можно использовать <code>NetworkInterface.GetAllNetworkInterfaces()</code>. Как-то так:</p>
<pre><code>using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Management;
...
//Определяет, является ли адаптер физическим
public static bool IsAdapterPhysical(string guid)
{
ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mbs = new ManagementObjectSearcher(
"SELECT PhysicalAdapter FROM Win32_NetworkAdapter WHERE GUID = '" + guid + "'"
);
bool res = false;
using (mbs)
{
mbsList = mbs.Get();
foreach (ManagementObject mo in mbsList)
{
foreach (var p in mo.Properties)
{
if (p.Value != null)
{
res = (bool)p.Value;
break;
}
else res = false;
}
}
return res;
}
}
//Получает все локальные IP-адреса
public static List<IPAddress> GetIpAddresses()
{
List<IPAddress> res = new List<IPAddress>(10);
var ifs = NetworkInterface.GetAllNetworkInterfaces();
foreach (var interf in ifs)
{
var ipprop=interf.GetIPProperties();
if (ipprop == null) continue;
var unicast = ipprop.UnicastAddresses;
if (unicast == null) continue;
if (IsAdapterPhysical(interf.Id.ToString()))
{
//находим первый Unicast-адрес
foreach (var addr in unicast)
{
if (addr.Address.AddressFamily != AddressFamily.InterNetwork) continue;
res.Add(addr.Address);
break;
}
}
}
return res;
}
</code></pre>
|
PHP | UTF-8 | 120 | 2.96875 | 3 | [] | no_license | <?php #p55
$hantei1 = ("99" == 99);
$hantei2 = ("99" != 99);
var_dump($hantei1);
var_dump($hantei2);
?> |
JavaScript | UTF-8 | 1,811 | 3.234375 | 3 | [
"MIT"
] | permissive | /*
This module has core functions for SLIP protocol:
https://tools.ietf.org/html/rfc1055
Author: Dmitry Myadzelets
Assumptions:
1. The beginning and the end of the data are unknown.Both encode and decode
functions operate on chunks of data. The upper level should add END
character at the end (and the beginning) of the data.
2. Two bytes escape sequences are always in the same chunk during decoding.
Encode and decode functions do not modify data. For such the `slice` and `add`
functions should be provided.
*/
const END = 192
const ESC = 219
const ESC_END = 220
const ESC_ESC = 221
const buf = {
end: new Uint8Array([END]),
esc: new Uint8Array([ESC]),
escend: new Uint8Array([ESC, ESC_END]),
escesc: new Uint8Array([ESC, ESC_ESC])
}
function encode (chunk, slice, add) {
let start, end
for (start = 0, end = 0; end < chunk.length; end += 1) {
switch (chunk[end]) {
case ESC:
(end > start) && slice(chunk, start, end)
add(buf.escesc)
start = end + 1
break
case END:
(end > start) && slice(chunk, start, end)
add(buf.escend)
start = end + 1
break
}
}
(end > start) && slice(chunk, start, end)
}
function decode (chunk, slice, add, eof) {
let start, end
let esc = false
for (start = 0, end = 0; end < chunk.length; end += 1) {
switch (chunk[end]) {
case ESC_END:
esc && (start = end + 1) && add(buf.end)
break
case ESC_ESC:
esc && (start = end + 1) && add(buf.esc)
break
case END:
(end > start) && slice(chunk, start, end)
start = end + 1
eof()
break
}
esc = chunk[end] === ESC
}
(end > start) && slice(chunk, start, end)
}
module.exports = { encode, decode }
module.exports.END = buf.end
|
C++ | UTF-8 | 177 | 2.625 | 3 | [] | no_license | #include <stdio.h>
main(){
int numero, sucessor;
printf("Digite um numero inteiro\n");
scanf("%d",&numero);
sucessor = numero+1;
printf("Sucessor =%d",sucessor);
}
|
TypeScript | UTF-8 | 2,006 | 3.109375 | 3 | [] | no_license | import * as Phaser from 'phaser'
type Config = {
scene: Phaser.Scene,
cols: number,
rows: number,
width: number,
height: number
}
class AlignGrid {
config: Config
scene: Phaser.Scene
cw: number
ch: number
numberSize: number = 24
colorHex: string = '#ff0000'
get color () {
return Phaser.Display.Color.HexStringToColor(this.colorHex)
}
constructor (config: Config) {
const { scene, cols, rows, width, height } = config
this.config = config
this.scene = scene
this.cw = width / cols
this.ch = height / rows
}
show () {
const { scene, config, cw, ch, color } = this
const graphics = scene.add.graphics()
const handleLineStyle = (isCenter) => {
const lineWidth = isCenter ? 6 : 2
graphics.lineStyle(lineWidth, this.color.color32, 0.3)
}
for (let x = 0; x < config.width; x += cw) {
handleLineStyle(x === config.width / 2)
graphics.moveTo(x, 0)
graphics.lineTo(x, config.height)
const index = x / cw
scene.add.text(x, 0, `${index}`, {
color: this.color.rgba,
fontSize: this.numberSize
})
}
for (let y = 0; y < config.height; y += ch) {
handleLineStyle(y === config.height / 2)
graphics.moveTo(0, y)
graphics.lineTo(config.width, y)
const index = y / ch
scene.add.text(0, y, `${index}`, {
color: this.color.rgba,
fontSize: this.numberSize
})
}
graphics.strokePath()
}
placeAt (xx: number, yy: number, obj: { x: number, y: number }) {
const x = xx * this.cw
const y = yy * this.ch
obj.x = x
obj.y = y
}
scaleToGameW (obj: { displayWidth: number, scaleX: number, scaleY: number }, per: number) {
obj.displayWidth = this.config.width * per
obj.scaleY = obj.scaleX
}
scaleToGridW (obj: { displayWidth: number, scaleX: number, scaleY: number }, length: number) {
obj.displayWidth = this.cw * length
obj.scaleY = obj.scaleX
}
}
export default AlignGrid
|
C | UTF-8 | 1,771 | 3.015625 | 3 | [
"BSD-2-Clause"
] | permissive | #include "THLogAdd.h"
#include <float.h>
#ifdef USE_DOUBLE
#define MINUS_LOG_THRESHOLD -39.14
#else
#define MINUS_LOG_THRESHOLD -18.42
#endif
const double THLog2Pi = 1.83787706640934548355;
const double THLogZero = -DBL_MAX;
const double THLogOne = 0;
double THLogAdd(double log_a, double log_b) {
double minusdif;
if (log_a < log_b) {
double tmp = log_a;
log_a = log_b;
log_b = tmp;
}
minusdif = log_b - log_a;
#ifdef DEBUG
if (isnan(minusdif))
THError("THLogAdd: minusdif (%f) log_b (%f) or log_a (%f) is nan", minusdif,
log_b, log_a);
#endif
if (minusdif < MINUS_LOG_THRESHOLD)
return log_a;
else
return log_a + log1p(exp(minusdif));
}
double THLogSub(double log_a, double log_b) {
double minusdif;
if (log_a < log_b)
THError("LogSub: log_a (%f) should be greater than log_b (%f)", log_a,
log_b);
minusdif = log_b - log_a;
#ifdef DEBUG
if (isnan(minusdif))
THError("LogSub: minusdif (%f) log_b (%f) or log_a (%f) is nan", minusdif,
log_b, log_a);
#endif
if (log_a == log_b)
return THLogZero;
else if (minusdif < MINUS_LOG_THRESHOLD)
return log_a;
else
return log_a + log1p(-exp(minusdif));
}
/* Credits to Leon Bottou */
double THExpMinusApprox(const double x) {
#define EXACT_EXPONENTIAL 0
#if EXACT_EXPONENTIAL
return exp(-x);
#else
/* fast approximation of exp(-x) for x positive */
#define A0 (1.0)
#define A1 (0.125)
#define A2 (0.0078125)
#define A3 (0.00032552083)
#define A4 (1.0172526e-5)
if (x < 13.0) {
/* assert(x>=0); */
double y;
y = A0 + x * (A1 + x * (A2 + x * (A3 + x * A4)));
y *= y;
y *= y;
y *= y;
y = 1 / y;
return y;
}
return 0;
#undef A0
#undef A1
#undef A2
#undef A3
#undef A4
#endif
}
|
Java | UTF-8 | 864 | 2.0625 | 2 | [] | no_license | package com.ruinscraft.buildcomputil;
import com.github.intellectualsites.plotsquared.commands.CommandDeclaration;
import com.github.intellectualsites.plotsquared.plot.commands.CommandCategory;
import com.github.intellectualsites.plotsquared.plot.commands.RequiredType;
import com.github.intellectualsites.plotsquared.plot.commands.SubCommand;
import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
@CommandDeclaration(
command = "trust",
category = CommandCategory.SETTINGS,
usage = "/plot trust",
permission = "plots.trust",
description = "Disabled.",
requiredType = RequiredType.NONE)
public class PlotTrust extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer sender, String[] args) {
sender.sendMessage("Command disabled");
return false;
}
}
|
TypeScript | UTF-8 | 4,553 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | import DragUtils from './DragUtils';
function makeItems(count = 5) {
const items = [];
for (let i = 0; i < count; i += 1) {
items.push(i);
}
return items;
}
describe('single item in single list', () => {
it('handles dragging item to the next index', () => {
const items = makeItems();
DragUtils.reorder(items, [[0, 0]], items, 2);
expect(items).toEqual([1, 0, 2, 3, 4]);
DragUtils.reorder(items, [[1, 1]], items, 3);
expect(items).toEqual([1, 2, 0, 3, 4]);
DragUtils.reorder(items, [[2, 2]], items, 4);
expect(items).toEqual([1, 2, 3, 0, 4]);
DragUtils.reorder(items, [[3, 3]], items, 5);
expect(items).toEqual([1, 2, 3, 4, 0]);
DragUtils.reorder(items, [[4, 4]], items, 3);
expect(items).toEqual([1, 2, 3, 0, 4]);
DragUtils.reorder(items, [[3, 3]], items, 2);
expect(items).toEqual([1, 2, 0, 3, 4]);
DragUtils.reorder(items, [[2, 2]], items, 1);
expect(items).toEqual([1, 0, 2, 3, 4]);
DragUtils.reorder(items, [[1, 1]], items, 0);
expect(items).toEqual([0, 1, 2, 3, 4]);
});
it('handles dragging top item to the end', () => {
const items = makeItems();
DragUtils.reorder(items, [[0, 0]], items, 5);
expect(items).toEqual([1, 2, 3, 4, 0]);
});
it('handles dragging bottom item to the top', () => {
const items = makeItems();
DragUtils.reorder(items, [[4, 4]], items, 0);
expect(items).toEqual([4, 0, 1, 2, 3]);
});
});
describe('multi drag in single list', () => {
it('handles dragging pair to the next index', () => {
const items = makeItems();
DragUtils.reorder(items, [[0, 1]], items, 3);
expect(items).toEqual([2, 0, 1, 3, 4]);
DragUtils.reorder(items, [[1, 2]], items, 4);
expect(items).toEqual([2, 3, 0, 1, 4]);
DragUtils.reorder(items, [[2, 3]], items, 5);
expect(items).toEqual([2, 3, 4, 0, 1]);
});
it('handles dragging non-contiguous ranges', () => {
const items = makeItems();
DragUtils.reorder(
items,
[
[0, 0],
[2, 2],
[4, 4],
],
items,
2
);
expect(items).toEqual([1, 0, 2, 4, 3]);
});
});
describe('remove items in list', () => {
it('handles removing the top item', () => {
const items = makeItems();
const removedItems = DragUtils.removeItems(items, [[0, 0]]);
expect(items).toEqual([1, 2, 3, 4]);
expect(removedItems).toEqual([0]);
});
it('handles removing the bottom item', () => {
const items = makeItems();
const removedItems = DragUtils.removeItems(items, [[4, 4]]);
expect(items).toEqual([0, 1, 2, 3]);
expect(removedItems).toEqual([4]);
});
it('handles removing non-contiguous ranges of items', () => {
const items = makeItems();
const removedItems = DragUtils.removeItems(items, [
[0, 0],
[2, 3],
]);
expect(items).toEqual([1, 4]);
expect(removedItems).toEqual([0, 2, 3]);
});
it('handles removing all items', () => {
const items = makeItems();
const removedItems = DragUtils.removeItems(items, [[0, 4]]);
expect(items).toEqual([]);
expect(removedItems).toEqual([0, 1, 2, 3, 4]);
});
});
describe('adjusting destination index', () => {
it('does not adjust when all ranges are below', () => {
expect(DragUtils.adjustDestinationIndex(0, [[1, 1]])).toBe(0);
expect(
DragUtils.adjustDestinationIndex(0, [
[1, 1],
[3, 3],
])
).toBe(0);
expect(DragUtils.adjustDestinationIndex(0, [[1, 5]])).toBe(0);
expect(DragUtils.adjustDestinationIndex(3, [[5, 5]])).toBe(3);
});
it('adjusts up for ranges selected above', () => {
expect(DragUtils.adjustDestinationIndex(4, [[0, 0]])).toBe(3);
expect(DragUtils.adjustDestinationIndex(4, [[3, 3]])).toBe(3);
expect(
DragUtils.adjustDestinationIndex(4, [
[0, 0],
[2, 2],
])
).toBe(2);
expect(DragUtils.adjustDestinationIndex(4, [[0, 3]])).toBe(0);
});
it('adjusts when ranges are above and below', () => {
expect(
DragUtils.adjustDestinationIndex(3, [
[0, 0],
[5, 5],
])
).toBe(2);
expect(
DragUtils.adjustDestinationIndex(5, [
[0, 3],
[15, 25],
])
).toBe(1);
});
it('adjusts when ranges contain the destination index', () => {
expect(DragUtils.adjustDestinationIndex(0, [[0, 0]])).toBe(0);
expect(DragUtils.adjustDestinationIndex(3, [[0, 5]])).toBe(0);
expect(
DragUtils.adjustDestinationIndex(5, [
[0, 0],
[4, 6],
])
).toBe(3);
});
});
|
SQL | UTF-8 | 2,780 | 2.90625 | 3 | [] | no_license | -- MariaDB dump 10.17 Distrib 10.4.6-MariaDB, for Win64 (AMD64)
--
-- Host: localhost Database: pendaftaran_5
-- ------------------------------------------------------
-- Server version 10.4.6-MariaDB
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `tabel_registrasi`
--
DROP TABLE IF EXISTS `tabel_registrasi`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tabel_registrasi` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`namalengkap` varchar(200) NOT NULL,
`namadepan` varchar(100) NOT NULL,
`namabelakang` varchar(100) NOT NULL,
`jeniskelamin` varchar(50) NOT NULL,
`username` varchar(100) NOT NULL,
`email` varchar(255) NOT NULL,
`kotaasal` varchar(100) NOT NULL,
`alamat` varchar(255) NOT NULL,
`tanggallahir` date NOT NULL,
`jenistempat` varchar(50) NOT NULL,
`jurusan` varchar(50) NOT NULL,
`angkatan` int(4) NOT NULL,
`waktu` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `tabel_registrasi`
--
LOCK TABLES `tabel_registrasi` WRITE;
/*!40000 ALTER TABLE `tabel_registrasi` DISABLE KEYS */;
INSERT INTO `tabel_registrasi` VALUES (1,'Aulia Rezky','aulia','rezky','perempuan','auliaa12','aulia12@yahoo.com','Surabaya','Griya Asri','2001-01-01','Rumah Orang Tua','Teknik Kimia',2017,'2020-04-11 20:59:24'),(2,'Maghfirah Nurpadila','Fira','Padila','perempuan','firapadila','firapadila@gmail.com','Lombok','Daya','2000-01-11','Rumah Orang Tua','Teknik Elektro',2019,'2020-04-11 21:13:27');
/*!40000 ALTER TABLE `tabel_registrasi` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2020-04-11 21:41:48
|
Java | UTF-8 | 2,157 | 2.25 | 2 | [] | no_license | package com.example.news.navigation;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import com.example.news.app.App;
import com.example.news.presentation.view.DetailActualActivity;
import com.example.news.presentation.view.DetailFavoriteActivity;
import com.example.news.presentation.view.FavoriteNewsActivity;
public class Router {
private Activity activity;
public Router(Activity activity) {
this.activity = activity;
}
public void openDetailActualScreen() {
Intent intent = new Intent(activity, DetailActualActivity.class);
activity.startActivity(intent);
}
public void openNewsInBrowser(String url) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
activity.startActivity(intent);
}
public void shareNews(String source, String title, String url) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plan");
intent.putExtra(Intent.EXTRA_SUBJECT, source);
String body = title + "\n" + url + "\n" + "Shared from the News App" + "\n";
intent.putExtra(Intent.EXTRA_TEXT, body);
activity.startActivity(Intent.createChooser(intent, "Share in: "));
}
public void openFavoriteScreen() {
Intent intent = new Intent(activity, FavoriteNewsActivity.class);
activity.startActivity(intent);
}
public void openDetailFavoriteScreen() {
Intent intent = new Intent(activity, DetailFavoriteActivity.class);
activity.startActivity(intent);
}
public void openSettingsApp() {
Uri packageUri = Uri.fromParts("package", App.getApp().getPackageName(),
null);
Intent applicationDetailsSettingsIntent = new Intent();
applicationDetailsSettingsIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
applicationDetailsSettingsIntent.setData(packageUri);
applicationDetailsSettingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(applicationDetailsSettingsIntent);
}
}
|
Shell | UTF-8 | 596 | 2.515625 | 3 | [] | no_license | ui_print " Patching existing audio_effects files..."
for FILE in ${CFGS}; do
sed -i 's/^effects {/effects {\n v4a_standard_fx {\n library v4a_fx\n uuid 41d3c987-e6cf-11e3-a88a-11aba5d5c51b\n }/g' $AMLPATH$FILE
sed -i 's/^libraries {/libraries {\n v4a_fx {\n path \/system\/lib\/soundfx\/libv4a_fx_ics.so\n }/g' $AMLPATH$FILE
sed -i 's/^libraries {/libraries {\n dap {\n path \/system\/lib\/soundfx\/libswdap-mod.so\n }/g' $AMLPATH$FILE
sed -i 's/^effects {/effects {\n dap {\n library dap\n uuid 9d4921da-8225-4f29-aefa-39537a041337\n }/g' $AMLPATH$FILE
done
|
C | UTF-8 | 1,696 | 2.65625 | 3 | [] | no_license | /*
* debug.c
*
* Created on: 28 nov. 2017
* Author: thomas
*/
#include "debug.h"
#include "stm32f4xx_hal.h"
void unsign_print(UART_HandleTypeDef *huart_ptr, uint8_t var){
char str[32];
sprintf(str, "%u\n\r", var);
HAL_UART_Transmit(huart_ptr, (uint8_t *) str,strlen(str), 10);
}
void signed_print(UART_HandleTypeDef *huart_ptr, int16_t var){
char str[32];
sprintf(str, "%d\n\r", var);
HAL_UART_Transmit(huart_ptr, (uint8_t *) str,strlen(str), 10);
}
void float_print(UART_HandleTypeDef *huart_ptr, float var){
char str[32];
sprintf(str, "value: %e\n\r", var);
HAL_UART_Transmit(huart_ptr, (uint8_t *) str,strlen(str), 10);
}
void char_Print(UART_HandleTypeDef *huart_ptr, char _out[]){
HAL_UART_Transmit(huart_ptr, (uint8_t *) _out, strlen(_out), 10);
}
void debugReceive(UART_HandleTypeDef *huart_ptr){
//HAL_UART_Receive(huart_ptr, (uint8_t *)test, 64, 1);
}
void led_write(uint8_t number, uint8_t enable){
switch(number){
case 1: HAL_GPIO_WritePin(GPIOD, LED1_Pin,enable); break;
case 2: HAL_GPIO_WritePin(GPIOD, LED2_Pin,enable); break;
case 3: HAL_GPIO_WritePin(GPIOD, LED3_Pin,enable); break;
case 4: HAL_GPIO_WritePin(GPIOD, LED4_Pin,enable); break;
case 5: HAL_GPIO_WritePin(GPIOD, LED5_Pin,enable); break;
case 6: HAL_GPIO_WritePin(GPIOD, LED6_Pin,enable); break;
}
}
void led_toggle(uint8_t number){
switch(number){
case 1: HAL_GPIO_TogglePin(GPIOD,LED1_Pin); break;
case 2: HAL_GPIO_TogglePin(GPIOD,LED2_Pin); break;
case 3: HAL_GPIO_TogglePin(GPIOD,LED3_Pin); break;
case 4: HAL_GPIO_TogglePin(GPIOD,LED4_Pin); break;
case 5: HAL_GPIO_TogglePin(GPIOD,LED5_Pin); break;
case 6: HAL_GPIO_TogglePin(GPIOD,LED6_Pin); break;
}
}
|
Shell | UTF-8 | 4,894 | 2.546875 | 3 | [] | no_license | #!/bin/sh
#
#PBS -N MPI-MZ_f77_641_128_MX
#PBS -l walltime=5:00:00
#PBS -l nodes=4:r641:ppn=32
#PBS -j oe
cd $HOME/ESC/TP1/NPB3.3-MZ-MPI
commands_output_dir=../scripts_ex2/Paralelo/commands_output
mkdir -p $commands_output_dir
module load gnu/openmpi_mx/1.8.4
module load gcc/5.3.0
set -x
export OMP_NUM_THREADS=2
cp config/makeo0.def config/make.def
make bt-mz CLASS=W NPROCS=64
make bt-mz CLASS=A NPROCS=64
make bt-mz CLASS=B NPROCS=64
make bt-mz CLASS=C NPROCS=64
echo 'O0'
echo '------------Class W------------'
for i in {1..10}
do
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.W.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_00_class_W $i bt-mz.W.64
done
echo '------------Class A------------'
for i in {1..10}
do
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.A.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_00_class_A $i bt-mz.A.64
done
echo '------------Class B------------'
for i in {1..10}
do
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.B.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_00_class_B $i bt-mz.B.64
done
echo '------------Class C------------'
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.C.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_00_class_C $i bt-mz.C.64
cp config/makeo1.def config/make.def
make bt-mz CLASS=W NPROCS=64
make bt-mz CLASS=A NPROCS=64
make bt-mz CLASS=B NPROCS=64
make bt-mz CLASS=C NPROCS=64
echo 'O1'
echo '------------Class W------------'
for i in {1..10}
do
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.W.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_01_class_W $i bt-mz.W.64
done
echo '------------Class A------------'
for i in {1..10}
do
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.A.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_01_class_A $i bt-mz.A.64
done
echo '------------Class B------------'
for i in {1..10}
do
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.B.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_01_class_B $i bt-mz.B.64
done
echo '------------Class C------------'
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.C.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_01_class_C $i bt-mz.C.64
cp config/makeo2.def config/make.def
make bt-mz CLASS=W NPROCS=64
make bt-mz CLASS=A NPROCS=64
make bt-mz CLASS=B NPROCS=64
make bt-mz CLASS=C NPROCS=64
echo 'O2'
echo '------------Class W------------'
for i in {1..10}
do
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.W.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_02_class_W $i bt-mz.W.64
done
echo '------------Class A------------'
for i in {1..10}
do
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.A.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_02_class_A $i bt-mz.A.64
done
echo '------------Class B------------'
for i in {1..10}
do
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.B.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_02_class_B $i bt-mz.B.64
done
echo '------------Class C------------'
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.C.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_02_class_C $i bt-mz.C.64
cp config/makeo3.def config/make.def
make bt-mz CLASS=W NPROCS=64
make bt-mz CLASS=A NPROCS=64
make bt-mz CLASS=B NPROCS=64
make bt-mz CLASS=C NPROCS=64
echo 'O3'
echo '------------Class W------------'
for i in {1..10}
do
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.W.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_03_class_W $i bt-mz.W.64
done
echo '------------Class A------------'
for i in {1..10}
do
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.A.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_03_class_A $i bt-mz.A.64
done
echo '------------Class B------------'
for i in {1..10}
do
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.B.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_03_class_B $i bt-mz.B.64
done
echo '------------Class C------------'
mpirun -np 64 --map-by ppr:1:core -mca btl self,sm,tcp bin/bt-mz.C.64 &
source ../scripts_ex2/Paralelo/commands.sh $commands_output_dir/run_f77_641_128_mx_03_class_C $i bt-mz.C.64
|
Java | UTF-8 | 4,708 | 2.28125 | 2 | [] | no_license | package com.sap.amd.authentication;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.Cookie;
import com.sap.amd.utils.types.TBrowser;
import com.sap.amd.utils.types.TCookie;
import com.sun.jna.platform.win32.Crypt32Util;
public class SAPCookie
{
private String name;
private byte[] value;
private String domain;
private String path;
public SAPCookie(String name, byte[] value, String domain, String path)
{
this.name = name;
this.value = value;
this.domain = domain;
this.path = path;
}
public String getName()
{
return name;
}
public String getValue()
{
return decrypt(value);
}
public String getDomain()
{
return domain;
}
public String getPath()
{
return path;
}
public Cookie toCookie()
{
Cookie cookie = new Cookie(name, decrypt(value), domain, path, new Date(0));
return cookie;
}
public static List<Cookie> toCookies(List<SAPCookie> sapCookies)
{
List<Cookie> cookies = new ArrayList<Cookie>();
for (SAPCookie sapCookie : sapCookies)
{
cookies.add(sapCookie.toCookie());
}
return cookies;
}
private String decrypt(byte[] encryptedValue)
{
byte[] chars = Crypt32Util.cryptUnprotectData(encryptedValue);
String decryptedValue = "";
for (byte b : chars)
{
decryptedValue += (char) b;
}
return decryptedValue;
}
public static List<SAPCookie> getCookies(ResultSet cookiesTable)
{
List<SAPCookie> cookies = new ArrayList<SAPCookie>();
try
{
while (cookiesTable.next())
{
String name = cookiesTable.getString("name");
byte[] encryptedValue = cookiesTable.getBytes("encrypted_value");
String domain = cookiesTable.getString("host_key");
String path = cookiesTable.getString("path");
cookies.add(new SAPCookie(name, encryptedValue, domain, path));
}
}
catch (SQLException e)
{
return null;
}
return cookies;
}
public static ResultSet getCookiesTable(TBrowser browser, String profile)
{
String cookiesPath = null;
if (browser == TBrowser.Chrome)
{
cookiesPath = "jdbc:sqlite:" + System.getProperty("user.home") + "\\AppData\\Local\\Google\\Chrome\\User Data\\" + profile + "\\Cookies";
}
else
{
cookiesPath = "jdbc:sqlite:" + System.getProperty("user.home") + "\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\" + profile + "\\cookies.sqlite";
}
try
{
Class.forName("org.sqlite.JDBC");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
return null;
}
ResultSet queryResult = null;
try
{
Connection jdbcConnection = DriverManager.getConnection(cookiesPath);
Statement sqlStatement = jdbcConnection.createStatement();
if (browser == TBrowser.Chrome)
queryResult = sqlStatement.executeQuery("select * from cookies where name = 'MYSAPSSO2' or name = 'sap-appcontext' or name = 'sap-usercontext' or name = 'SAP_SESSIONID_BCS_001';");
else
queryResult = sqlStatement.executeQuery("select * from moz_cookies where name = 'MYSAPSSO2' or name = 'sap-appcontext' or name = 'sap-usercontext' or name = 'SAP_SESSIONID_BCS_001';");
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
return queryResult;
}
public static ResultSet getCookiesTable(TBrowser browser, String profile, List<TCookie> requiredCookies)
{
String cookiesPath = null;
if (browser == TBrowser.Chrome)
{
cookiesPath = "jdbc:sqlite:C:\\Users\\i841748.GLOBAL\\AppData\\Local\\Google\\Chrome\\User Data\\" + profile + "\\Cookies";
}
else
{
cookiesPath = "C:\\Users\\i841748.GLOBAL\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\" + profile + "\\cookies.sqlite";
}
try
{
Class.forName("org.sqlite.JDBC");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
return null;
}
ResultSet queryResult = null;
try
{
Connection jdbcConnection = DriverManager.getConnection(cookiesPath);
Statement sqlStatement = jdbcConnection.createStatement();
String names = "";
for (int i = 0; i < requiredCookies.size(); i++)
{
if (i != requiredCookies.size() - 1)
names += "name like '%" + requiredCookies.get(i).name() + "%' or ";
else
names += "name like '%" + requiredCookies.get(i).name() + "%';";
}
if (browser == TBrowser.Chrome)
queryResult = sqlStatement.executeQuery("select * from cookies where " + names);
else
queryResult = sqlStatement.executeQuery("select * from moz_cookies where " + names);
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
return queryResult;
}
}
|
Python | UTF-8 | 735 | 3.3125 | 3 | [] | no_license | # from typing import Generator
# dict_couple={"bride":["marry","bella","linda"],"groom":["jack","robert","eric"]}
# def muruvvet(bride,groom):
# couple_list =[]
# for x in zip(bride,groom):
# couple_list.append(x)
# return couple_list
# print(muruvvet(** dict_couple))
# def muruvvet_2(bride,groom):
# generate=[(bride,groom) for x in zip(bride,groom)]
# return generate
# friends={"Ahmet":34,"Mehmet":25,"Cemal":12}
# def meaner(Ahmet,Mehmet,Cemal):
# ortalama=(Ahmet+Mehmet+Cemal)/3
# return ortalama
# print(meaner(**friends))
friends={"Ahmet":34,"Mehmet":25,"Cemal":12}
def meaner(Ahmet,Mehmet,Cemal):
ortalama=sum(Ahmet,Mehmet,Cemal)/3
return ortalama
print(meaner(**friends))
|
Python | UTF-8 | 1,995 | 4.125 | 4 | [] | no_license | """Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
Example 2:
Input: root = [0,null,1]
Output: [1,null,1]
Example 3:
Input: root = [1,0,2]
Output: [3,3,2]
Example 4:
Input: root = [3,2,4,1]
Output: [7,9,4,10]"""
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
# initialize variable with value to add- start at 0
to_add = [0]
# create helper method to recurse through tree
def helper(root, to_add):
# if there is no node, return
if not root:
return root
# call helper method on right node if there is one, with to add sum to keep track of greater value nodes
helper(root.right, to_add)
# add 'to_add' to the current node val
root.val += to_add[0]
# set variable to the new sum
to_add[0] = root.val
# call helper method on left node if there is one
helper(root.left, to_add)
# return value for new greater sum node
return root
# call helper method recursively starting at root
return helper(root, to_add)
"""Runtime: 28 ms, faster than 90.41% of Python3 online submissions for Binary Search Tree to Greater Sum Tree.
Memory Usage: 14.1 MB, less than 96.51% of Python3 online submissions for Binary Search Tree to Greater Sum Tree.""" |
Java | UTF-8 | 814 | 2.1875 | 2 | [] | no_license | package com.furniture.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.furniture.dao.UserDAOImpl;
import com.furniture.model.User;
@Service
@Transactional
public class UserService {
@Autowired(required=true)
UserDAOImpl userDAO;
public List<User> list()
{
return userDAO.list();
}
public void saveOrUpdate(User user){
userDAO.saveOrUpdate(user);
}
public User getByName(String name) {
return userDAO.getByName(name);
}
public User getById(Integer id){
return userDAO.getById(id);
}
public String user(String name)
{
return userDAO.getByName(name).getUsername();
}
}
|
Markdown | UTF-8 | 7,151 | 3.1875 | 3 | [] | no_license | **Hardik Galiawala
B00777450
CSCI 5708
January 25, 2018**
# First Application: SplenDO
**Link to application:** https://play.google.com/store/apps/details?id=com.splendapps.splendo
SplenDO app comes under the Productivity category. It helps the user to manage their time in an efficient manner. The main idea of this app is to create various tasks for a day along with the start time. These created tasks can be grouped under user-defined categories. The categories may include Shopping, Work, and Personal to name a few. The app will notify the user about the upcoming tasks in advance. The time of notification can be set by the user as per the need.
One of the most important reasons for choosing this app is its simplicity. This app has the perfect amount of functions which makes it neither too complex nor too simple to be an app. It also has a very user-friendly graphical interface. It is also customizable to a certain extent in terms of notifications and task groups. It also gives functionality to create a quick task which requires only the name of the task. This helps users to add any task on the fly taking less than 5 seconds. The user may later edit it as per his/her convenience and update the other fields like notification time, task category, and others. SplenDO also allows users to enter tasks in a “Batch Mode”. The main idea is to enter multiple tasks which are linked to and dependent on one another. This functionality helps a user to divide a complex task into smaller sub-steps, helping them finish the task. SplenDO also allows adding tasks via voice. It also has notifications in the form of a speech synthesizer (Text to Speech).
The strengths of the application include multiple ways of adding a task, customizable notifications, and simple user interface. The disadvantage of this app is that there is no way to sync your schedule with the calendar of your email, audio-visual advertisements (for free version) which cover the full screen. It is important to work on these dis-advantages to improve the app. The app can be made with an option to synchronize the calendar. The advertisements should only have an image instead of an audio-visual. It is also a good idea to provide an optional field of end time, which would give the user a heads up if he/she is taking more time for that particular task to complete.
## First Heuristic Evaluation: Error prevention
The app is designed in a perfect way to avoid the slips and mistakes committed by the user [1]. Just as an example, if a user gives notification date past current date then it shows it in the red color font. This reminds the user politely that it is already past. The labels before the text boxes are well explained. This gives the user a clear idea of what is expected in the text fields. Also, the new task creation tab has a text field which at the top which requests for the name of the task followed by its due date and then the time. This decreases any kind of mistakes which may lead to an error on the user part.
## Second Heuristic Evaluation: Consistency and standards
The design of the app is consistent. The color scheme of the app is constant in the shade of blue and white. This color scheme makes the app professional and standard. The functional flow of the app is well structured keeping in mind the user’s thought process. The font color, type, size and face used gives the app a rich and professional look. Also, same font type is used throughout the app with almost no variation in font size.
# Second Application: FitMenCook – Healthy Recipes
**Link to application:** https://play.google.com/store/apps/details?id=com.nibbleapps.fitmencook
The app FitMenCook – Healthy Recipes comes under the Food and Drink category. As the name suggests this app helps the user to maintain a healthy diet by guiding them starting from the ingredient shopping till the end dish is ready. It also helps to keep track of the calories intake per day. This app guides the user in the form of videos and text recipes on how to prepare a dish in the least amount of time with less expensive ingredients.
Cooking healthy food requires a lot of time. It also tastes bland. This is where FitMenCook – Healthy Recipes app comes in the picture. It helps the user to keep track of the ingredients that are needed to cook a dish. The app has a feature that allows the user to add the list of items in the “To shop” category which reminds the user to buy it from the store. The app also allows customizing the number of serves. It adjusts the ingredients automatically based on the number of serves. The quantity of ingredients is also customizable. The user may use grams or pounds depending on his/her preference. Every dish has a nutrition value which helps the user to keep track of the amount of the calories. It also allows the user to add these nutrition values to Google Fit. It has various recipes categorized under Vegan, Vegetarian, Breakfast, Budget, Snacks & Sweets and Post-workout to name a few. As these names are self-explanatory, we won’t discuss them in detail. The user can share his/her recipe via various apps (e.g., Whatsapp, Messenger, and others).
After analyzing the app, it can be observed that the app has some strengths and weaknesses. The strengths are the user-friendliness, quick response time, easy to start using it, instant access to the recipes needed, smart categorization of the recipes, internationalization (currently supports Spanish). It takes more than expected time to play any video. The full-screen option lags during video playback. The app can be improved by creating a user profile which may help a user track the history of the food he/she had since the start date of using the app. It is a good idea to provide a dashboard with different dimensions to compare against different types of metrics.
## First Heuristic Evaluation: Match between system and the real world
The app’s landing screen is very neat and designed to display recently viewed items followed by the categories of the dishes if the user is already connected the Google fit. This order makes perfect sense from the end user perspective. The Category of dishes has perfect names which are self-explanatory as they have a resemblance to the real-world terms. The search icon placed on top of the home screen makes it clear that one can search for the recipes. The symbols for Favorites, Settings, Recipes, Shopping List, and others are relevant to their names. They are simple to identify for the user.
## Second Heuristic Evaluation: Consistency and standard
The logo of the app is not consistent. The launching icon has a light orange colored background, while the landing page has a white background. This variation in the logo leads to an unprofessional design. Also, the red colored tabs do not mix with the logo. It needs to be improved. The advertisements are not consistent with shape and size throughout the app. The font type and size are consistent throughout the app. But, the text is bold at the top while it is not at the bottom of the same text.
# References:
[1] https://www.nngroup.com/articles/slips/
|
Java | UTF-8 | 653 | 2.25 | 2 | [] | no_license | package org.cakepowered.mod.event;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import org.cakepowered.api.entity.Entity;
import org.cakepowered.api.event.PlayerInteractEntityEvent;
import org.cakepowered.mod.util.ForgeInterface;
public class ApiPlayerClickEntityEvent extends ApiPlayerInteractEvent implements PlayerInteractEntityEvent {
public PlayerInteractEvent.EntityInteract event;
public ApiPlayerClickEntityEvent(PlayerInteractEvent.EntityInteract e) {
super(e);
event = e;
}
@Override
public Entity getTarget() {
return ForgeInterface.getEntity(event.getTarget());
}
}
|
Python | UTF-8 | 3,897 | 2.9375 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | """ Defines the LegendTool class.
"""
# Enthought library imports
from traits.api import Bool, Enum
from enable.tools.drag_tool import DragTool
class LegendTool(DragTool):
""" A tool for interacting with legends.
Attach this tool to a legend by setting the tool's **component**
to the legend.
"""
# The mouse button that initiates the drag.
drag_button = Enum("left", "right")
# Whether to change the legend's **align** property in accord with
# the quadrant into which it is dropped.
auto_align = Bool(True)
def is_draggable(self, x, y):
""" Returns whether the (x,y) position is in a region that is OK to
drag.
Overrides DragTool.
"""
if self.component:
legend = self.component
return (x >= legend.x and x <= legend.x2 and \
y >= legend.y and y <= legend.y2)
else:
return False
def drag_start(self, event):
""" Called when the drag operation starts.
Implements DragTool.
"""
if self.component:
self.original_padding = self.component.padding
event.window.set_mouse_owner(self, event.net_transform())
event.handled = True
return
def dragging(self, event):
""" This method is called for every mouse_move event that the tool
receives while the user is dragging the mouse.
Implements DragTool. Moves the legend by aligning it to a corner of its
overlay component.
"""
# To properly move a legend (which aligns itself to a corner of its overlay
# component), we need to modify the padding amounts as opposed to modifying
# the position directly.
if self.component:
legend = self.component
valign, halign = legend.align
left, right, top, bottom = self.original_padding
dy = int(event.y - self.mouse_down_position[1])
if valign == "u":
# we subtract dy because if the mouse moves downwards, dy is
# negative but the top padding has increased
legend.padding_top = top - dy
else:
legend.padding_bottom = bottom + dy
dx = int(event.x - self.mouse_down_position[0])
if halign == "r":
legend.padding_right = right - dx
else:
legend.padding_left = left + dx
event.handled = True
legend.request_redraw()
return
def drag_end(self, event):
""" Called when a mouse event causes the drag operation to end.
Implements DragTool.
"""
# Make sure we have both a legend and that the legend is overlaying
# a component
if self.auto_align and self.component and self.component.component:
# Determine which boundaries of the legend's overlaid component are
# closest to the center of the legend
legend = self.component
component = legend.component
left = int(legend.x - component.x)
right = int(component.x2 - legend.x2)
if left < right:
halign = "l"
legend.padding_left = left
else:
halign = "r"
legend.padding_right = right
bottom = int(legend.y - component.y)
top = int(component.y2 - legend.y2)
if bottom < top:
valign = "l"
legend.padding_bottom = bottom
else:
valign = "u"
legend.padding_top = top
legend.align = valign + halign
if event.window.mouse_owner == self:
event.window.set_mouse_owner(None)
event.handled = True
legend.request_redraw()
return
# EOF
|
Swift | UTF-8 | 2,583 | 2.640625 | 3 | [] | no_license | // CookbookCollectionsView.swift
// RecipeMatcher
// Created by Eric Widjaja on 8/22/20.
// Copyright © 2020 Eric W. All rights reserved.
import UIKit
import Kingfisher
class CookbookCollectionsView: UIView {
//MARK: - Objects
lazy var myCollectionsCV: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 410, height: 180)
layout.scrollDirection = .vertical
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = .black
cv.showsHorizontalScrollIndicator = false
return cv
}()
lazy var myCollectionLabel: UILabel = {
let label = UILabel()
label.text = "My Cookbook Collections"
label.font = .boldSystemFont(ofSize: 30)
label.textColor = .white
return label
}()
override init(frame: CGRect) {
super.init(frame: UIScreen.main.bounds)
setMyFavCollectionsConstraints()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setMyFavCollectionsConstraints()
}
//MARK: - FavCollectionsView Constraints
private func setMyFavCollectionsConstraints() {
self.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
myFavCollTitleLabelConstraints()
myCollectionsCVConstraints()
}
private func myFavCollTitleLabelConstraints() {
addSubview(myCollectionLabel)
myCollectionLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
myCollectionLabel.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 8),
myCollectionLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
myCollectionLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
myCollectionLabel.heightAnchor.constraint(equalToConstant: 36)])
}
private func myCollectionsCVConstraints() {
addSubview(myCollectionsCV)
myCollectionsCV.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
myCollectionsCV.topAnchor.constraint(equalTo: myCollectionLabel.bottomAnchor, constant: 8),
myCollectionsCV.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
myCollectionsCV.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor),
myCollectionsCV.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor)])
}
}
|
Markdown | UTF-8 | 7,386 | 3.671875 | 4 | [
"MIT"
] | permissive | # String
## Common used methods
- get substring with start index & end index: slice(startIndex, endIndex) => s[startIndex, endIndex)
- get substring with start index & length: substr(startIndex, length)
- a.localeCompare(b) 为按字母表升序
- charCodeAt(); String.fromCharCode();
## Common operations
### 判断是否是回文串
```js
function isPalindrome(word) {
let i = 0,
j = word.length - 1;
while (i < j) {
if (word[i++] !== word[j--]) return false;
}
return true;
}
```
### 翻转字符串
```js
function reverse(word) {
let res = "";
for (let i = word.length - 1; i >= 0; i--) res += word[i];
return res;
}
```
### 判断 t 是否是 s 的 subsequence
```js
function isSubsequence(s, t) {
let i = 0, j = 0;
while (i < s.length && j < t.length) {
if (s[i] === t[j]) j++;
i++;
}
return j === t.length;
}
```
### 求所有指定长度的子序列 (combination of length n)
```js
function allSubsequencesOfK(s, k) {
let res = [];
const dfs = (idx, curr) => {
if (curr.length === k) {
res.push(curr);
return;
}
if (idx >= s.length) return;
dfs(idx + 1, curr + s[idx]);
dfs(idx + 1, curr);
};
dfs(0, "");
return res;
}
```
## 正则
+ 表示 >= 1,* 表示 >= 0,? 表示 0 个或 1 个,[] 表示字符集,() 表示分组。
RegExp.prototype.exec() 返回参数:
- res[0] => 匹配到的字符串
- res[1...n] => 分组 1 - n
## Questions
### [Implement strStr()](https://leetcode.com/problems/implement-strstr/)
判断 t 是否是 s 的子串
```js
var strStr = function(s, t) {
for (let i = 0;; i++) {
for (let j = 0;; j++) {
if (j === t.length) return i;
if (i + j === s.length) return -1;
if (t[j] !== s[i+j]) break;
}
}
}
```
### [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/)
O(Max(M, N)) O(M+N)
```js
function compareVersion(a, b) {
let ca = a.split('.').map(Number), cb = b.split('.').map(Number);
let n = Math.max(ca.length, cb.length);
for (let i = 0; i < n; i++) {
let na = i < ca.length ? ca[i] : 0;
let nb = i < cb.length ? cb[i] : 0;
if (na > nb) return 1;
else if (na < nb) return -1;
}
return 0;
}
```
O(Max(M, N)) O(1)
```js
function compareVersion(a, b) {
let i = 0, j = 0, vi = 0, vj = 0;
while (i < a.length || j < b.length) {
let pair1 = getNextChunk(a, i);
let pair2 = getNextChunk(b, j);
vi = pair1[0], i = pair1[1];
vj = pair2[0], j = pair2[1];
if (vi > vj) return 1;
else if (vi < vj) return -1;
}
return 0;
}
function getNextChunk(s, currentPos) {
if (currentPos >= s.length) return [0, s.length];
let i = currentPos, count = 0;
while (i < s.length && s[i] !== '.') {
i++;
count++;
}
let sub = s.substr(currentPos, count);
return [Number(sub), i + 1];
}
```
### [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/)
a list of **unique** words
考验设计 & 分析不同情况的能力。
cases:
case 1: s1 = '', s2 is palindrome => s1 + s2 & s2 + s1
case 2: s1, s2 = reverse(s1) => s1 + s2 & s2 + s1
case 3: s1[0:cut] is palindrome, s2 = reverse(s1[cut+1:]) => s2 + s1
case 4: s1[cut+1:] is palindrome, s2 = reverse(s1[0:cut]) => s1 + s2
```js
var palindromePairs = function (words) {
let res = [];
if (words === null || words.length === 0) return res;
let map = new Map();
for (let i = 0; i < words.length; i++) {
map.set(words[i], i);
}
// case 1
if (map.has("")) {
let idx = map.get("");
for (let i = 0; i < words.length; i++) {
if (isPalindrome(words[i]) && i !== idx) {
res.push([idx, i]);
res.push([i, idx]);
}
}
}
// case 2
for (let i = 0; i < words.length; i++) {
let temp = reverse(words[i]);
if (map.has(temp) && map.get(temp) !== i) {
res.push([i, map.get(temp)]);
}
}
for (let i = 0; i < words.length; i++) {
let curr = words[i];
for (let cut = 1; cut < curr.length; cut++) {
let left = curr.slice(0, cut),
right = curr.slice(cut);
// case 3
if (isPalindrome(left)) {
let temp = reverse(right);
if (map.has(temp) && map.get(temp) !== i) {
res.push([map.get(temp), i]);
}
}
// case 4
if (isPalindrome(right)) {
let temp = reverse(left);
if (map.has(temp) && map.get(temp) !== i) {
res.push([i, map.get(temp)]);
}
}
}
}
return res;
};
```
### [Remove Comments](https://leetcode.com/problems/remove-comments/)
考验设计 & 分析不同情况的能力。
corner cases:
- `['aa//bb','cc'] => ['aa', 'cc']`
- `['aa/*bb*///cc'] => ['aa']`
- `['aa/*bb', 'cc*/dd'] => ['aadd']`
```js
var removeComments = function (source) {
let res = [],
inBlock = false,
newLine = "";
for (let line of source) {
for (let i = 0; i < line.length; i++) {
if (inBlock) {
if (line[i] == "*" && i + 1 < line.length && line[i + 1] == "/") {
inBlock = false;
i++;
}
} else {
if (line[i] == "/" && i + 1 < line.length && line[i + 1] == "/") {
break;
} else if (
line[i] == "/" &&
i + 1 < line.length &&
line[i + 1] == "*"
) {
inBlock = true;
i++;
} else {
newLine += line[i];
}
}
}
if (!inBlock && newLine.length > 0) {
res.push(newLine);
newLine = "";
}
}
return res;
};
```
### [Simplify Path](https://leetcode.com/problems/simplify-path/)
```js
var simplifyPath = function (path) {
let stack = [], paths = path.split('/').filter(p => p.length > 0);
for (let dic of paths) {
if (dic !== '.' && dic !== '..') stack.push(dic);
else if (dic === '..') stack.pop();
}
return '/' + stack.join('/');
};
```
### [Find Common Characters](https://leetcode.com/problems/find-common-characters/)
数字、英文字母间转换
'a' => 97; 'A' => 65;
两字母间不能直接做减法。
```js
var commonChars = function (A) {
let res = [],
map = Array(26).fill(10001);
for (let a of A) {
let curr = Array(26).fill(0);
for (let ch of a) curr[ch.charCodeAt() - 97]++;
for (let i = 0; i < 26; i++) map[i] = Math.min(map[i], curr[i]);
}
for (let i = 0; i < 26; i++) {
for (let j = 0; j < map[i]; j++) {
res.push(String.fromCharCode(i + 97));
}
}
return res;
};
```
### [Solve the Equation](https://leetcode.com/problems/solve-the-equation/)
表达式解析
[一个有用的正则:/(?=[+-])/](https://stackoverflow.com/questions/4416425/how-to-split-string-with-some-separator-but-without-removing-that-separator-in-j)
```js
var solveEquation = function (equation) {
let [left, right] = equation.split("=");
let [f1, i1] = evaluate(left),
[f2, i2] = evaluate(right);
f1 -= f2;
i1 = i2 - i1;
if (f1 === 0 && i1 === 0) return "Infinite solutions";
if (f1 === 0) return "No solution";
return "x=" + i1 / f1;
};
function evaluate(s) {
let tokens = s.split(/(?=[+-])/),
res = [0, 0];
for (let token of tokens) {
if (token === "+x" || token === "x") res[0]++;
else if (token === "-x") res[0]--;
else if (token.includes("x")) {
res[0] += parseInt(token.slice(0, token.indexOf("x")));
} else {
res[1] += parseInt(token);
}
}
return res;
}
```
|
C++ | UTF-8 | 1,100 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string,int>patientList;
std::string request;
std::cout << "Input your request, or 'exit' for exit" << std::endl;
std::getline(std::cin,request);
int k = 0;
while(request != "exit"){
if(request == "Next"){
if(patientList.size()>0) {
auto it = patientList.begin();
std::cout << it->first << std::endl;
if (it->second > 1) {
it->second--;
} else {
patientList.erase(it);
}
} else{
std::cout << "There is nobody!" << std::endl;
}
}else{
auto it = patientList.find(request);
if(it == patientList.end()) {
patientList.insert(std::make_pair(request, 1));
} else {
it -> second++;
}
}
std::cout << "Input your request, or 'exit' for exit" << std::endl;
std::getline(std::cin,request);
}
return 0;
}
|
Shell | UTF-8 | 1,548 | 3.5625 | 4 | [
"Apache-2.0"
] | permissive | #!/bin/bash
#usage: ./loadCsvToTable.sh csv db_addr username table_name db_type
postgres () {
CSV=$1
DB_ADDR=$2
USERNAME=$3
PWD=$4
TABLE_NAME=$5
echo $DB_ADDR $USERNAME $TABLE_NAME
#PGPASSWORD=postgres psql --user=${USERNAME} --dbname=$DB_ADDR -c "COPY "'"'$TABLE_NAME'"'" FROM '$CSV' DELIMITER '"'`'"' CSV;"
PGPASSWORD= psql --user=${USERNAME} --dbname=$DB_ADDR -c "COPY "'"'$TABLE_NAME'"'" FROM '$CSV' DELIMITER '"'`'"';"
}
db2 () {
CSV=$1
DB_ADDR=$2
USERNAME=$3
PWD=$4
TABLE_NAME=$5
echo $DB_ADDR $USERNAME $TABLE_NAME
db2 import from $CSV of del insert into '"'${TABLE_NAME}'"' ####### MODIFY
# db2 CONNECT RESET
}
if [ $# -eq 6 ]
then
CSV=$1
DB_ADDR=$2
TABLE_NAME=$3
USER=$4
PWD=$5
DB_TYPE=$6
if [ $DB_TYPE == postgres ]
then
postgres $CSV $DB_ADDR $USER $PWD $TABLE_NAME
else
if [ $DB_TYPE == db2 ]
then
db2 $CSV $DB_ADDR $USER $PWD $TABLE_NAME
else
if [ $DB_TYPE == mysql ]
then
echo 'SET foreign_key_checks = 0;' > sql.tmp
echo LOAD DATA INFILE "'"${CSV}"'" INTO TABLE $TABLE_NAME FIELDS TERMINATED BY "'"'`'"'" >> sql.tmp
cat sql.tmp
mysql $DB_ADDR --user=$USER --password=$PWD < sql.tmp
rm sql.tmp
else
echo "usage: ./loadCsvToTable.sh csv db_addr table_name username password db_type (db_type = postgres, mysql, db2)"
fi
fi
fi
else
echo "usage: ./loadCsvToTable.sh csv db_addr table_name username password db_type (db_type = postgres, mysql, db2)"
fi
|
Java | UTF-8 | 1,063 | 1.984375 | 2 | [] | no_license | package cn.sanleny.framework.auth.autoconfigure;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
import java.util.Collection;
/**
* 认证相关
* @Author: LG
* @Date: 2020-09-22
* @Version: 1.0
**/
@Data
@Configuration
@ConfigurationProperties("sanleny.auth")
public class AuthProperties {
/**
* 客户端ID
*/
private String clientId = "cloud";
/**
* 客户端密码
*/
private String clientSecret = "123456";
/**
* 授权类型: password、client_credentials
*/
private String grantType = "password";
/**
* 权限范围
*/
private Collection<String> scope = Arrays.asList("all", "select");
/**
* 签名key
*/
private String signingKey = "123";
/**
* token key 前缀
*/
private String tokenPrefix = "cloud:oauth:";
/**
* token 过期时间
*/
private int tokenValidityTime = 3000;
}
|
C | UTF-8 | 420 | 3.234375 | 3 | [] | no_license | #include "ft_printf.h"
static int ft_intlen(unsigned int n)
{
int ilen;
if (n == 0)
ilen = 1;
else
ilen = ft_strlen(ft_itoa_unsint(n));
return (ilen);
}
static void ft_process_nbr(unsigned int n)
{
if (n >= 10)
{
ft_process_nbr(n / 10);
ft_process_nbr(n % 10);
}
else
ft_putchar(48 + n);
}
int ft_putuint(unsigned int n)
{
int ret;
ret = ft_intlen(n);
ft_process_nbr(n);
return (ret);
}
|
Shell | UTF-8 | 6,560 | 3.796875 | 4 | [
"MIT"
] | permissive | #!/bin/bash
. "`dirname "$0"`/install-common.sh" || exit 1
PARENT_DIR="$(cd "$(dirname "$0")"; pwd -P)"
DEFAULT_REMOTE_SSH_PORT=22
DEFAULT_REMOTE_ADMIN=root
DEFAULT_REMOTE_USER=fwd
DEFAULT_SSH_KEY_NAME=fwd
DEFAULT_LOCAL_SSH_PORT=22
echo "Enter the URL or IP address of your remote server."
echo -n "> "
read REMOTE_SERVER
echo "Enter the SSH port of your remote server (or press ENTER to use \"$DEFAULT_REMOTE_SSH_PORT\")"
echo -n "($DEFAULT_REMOTE_SSH_PORT) > "
read REMOTE_SSH_PORT
test -z "$REMOTE_SSH_PORT" && REMOTE_SSH_PORT=$DEFAULT_REMOTE_SSH_PORT
echo "Enter the admin username on your remote server (or press ENTER to use \"$DEFAULT_REMOTE_ADMIN\")."
echo -n "($DEFAULT_REMOTE_ADMIN) > "
read REMOTE_ADMIN
test -z "$REMOTE_ADMIN" && REMOTE_ADMIN=$DEFAULT_REMOTE_ADMIN
echo "Enter the username of the account to be used for forwarding (or press ENTER to use \"$DEFAULT_REMOTE_USER\")"
echo -n "($DEFAULT_REMOTE_USER) > "
read REMOTE_USER
test -z "$REMOTE_USER" && REMOTE_USER=$DEFAULT_REMOTE_USER
echo "Enter the name of the SSH key to be used to connect to the server (or press ENTER to use \"$DEFAULT_SSH_KEY_NAME\")"
echo -n "($DEFAULT_SSH_KEY_NAME) > "
read SSH_KEY_NAME
test -z "$SSH_KEY_NAME" && SSH_KEY_NAME=$DEFAULT_SSH_KEY_NAME
echo "Enter the SSH port of your local machine to be forwarded (or press ENTER to use \"$DEFAULT_LOCAL_SSH_PORT\")"
echo -n "($DEFAULT_LOCAL_SSH_PORT) > "
read LOCAL_SSH_PORT
test -z "$LOCAL_SSH_PORT" && LOCAL_SSH_PORT=$DEFAULT_LOCAL_SSH_PORT
color yellow "Using $REMOTE_ADMIN@$REMOTE_SERVER (port $REMOTE_SSH_PORT) to add forwarding to this local user (port $LOCAL_SSH_PORT) through $REMOTE_USER@$REMOTE_SERVER with SSH key stored in $HOME/.ssh/$SSH_KEY_NAME and $HOME/.ssh/$SSH_KEY_NAME.pub"
yes_or_no "Continue with these options?"
if [[ "$answer" == "n" ]]; then
error "Cancelled!"
fi
REMOTE_SSH_COMMAND="ssh -p $REMOTE_SSH_PORT $REMOTE_USER@$REMOTE_SERVER"
REMOTE_SSH_COMMAND_ADMIN="ssh -p $REMOTE_SSH_PORT $REMOTE_ADMIN@$REMOTE_SERVER"
color green "Checking if forwarding user exists on remote server..."
if $REMOTE_SSH_COMMAND_ADMIN id -u $REMOTE_USER \> /dev/null; then
warning "User $REMOTE_USER@$REMOTE_SERVER already exists."
yes_or_no "Continue and use this user?"
if [[ "$answer" == "n" ]]; then
error "Cancelled!"
fi
else
color green "Creating forwarding user on remote server..."
$REMOTE_SSH_COMMAND_ADMIN sudo useradd --create-home $REMOTE_USER || error "Error creating user!"
fi
color green "Setting up .ssh directory..."
$REMOTE_SSH_COMMAND_ADMIN sudo -u $REMOTE_USER mkdir -p /home/$REMOTE_USER/.ssh || error "Error creating .ssh directory!"
$REMOTE_SSH_COMMAND_ADMIN sudo -u $REMOTE_USER touch /home/$REMOTE_USER/.ssh/authorized_keys || error "Error creating authorized_keys file!"
if [[ -f "$HOME/.ssh/$SSH_KEY_NAME" ]]; then
warning "SSH key $HOME/.ssh/$SSH_KEY_NAME already exists."
yes_or_no "Continue and use this key?"
if [[ "$answer" == "n" ]]; then
error "Cancelled!"
fi
else
color green "Generating SSH key..."
ssh-keygen -b 4096 -N "" -f "$HOME/.ssh/$SSH_KEY_NAME" || error "Error generating ssh key!"
fi
color green "Checking if the forwarding user already has the SSH key..."
if $REMOTE_SSH_COMMAND_ADMIN grep \"`cat "$HOME/.ssh/$SSH_KEY_NAME.pub"`\" "/home/$REMOTE_USER/.ssh/authorized_keys" \> /dev/null; then
color green "Key already uploaded."
else
color green "Uploading SSH key..."
cat "$HOME/.ssh/$SSH_KEY_NAME.pub" | $REMOTE_SSH_COMMAND_ADMIN sudo -u "$REMOTE_USER" "cat >> /home/$REMOTE_USER/.ssh/authorized_keys" || error "Error uploading ssh key!"
fi
color green "Enabling GatewayPorts in /etc/ssh/sshd_config..."
$REMOTE_SSH_COMMAND_ADMIN 'grep "^GatewayPorts yes$" /etc/ssh/sshd_config > /dev/null|| sed -i "s/^#GatewayPorts no$/GatewayPorts yes/g" /etc/ssh/sshd_config' || error "Error enabling GatewayPorts!"
#to disable: sed -i "s/^GatewayPorts yes$/#GatewayPorts no/g" /etc/ssh/sshd_config
color green "Checking if GatewayPorts is enabled..."
$REMOTE_SSH_COMMAND_ADMIN 'grep "^GatewayPorts yes$" /etc/ssh/sshd_config > /dev/null' || error "GatewayPorts could not be enabled!"
color green "Restarting SSH..."
$REMOTE_SSH_COMMAND_ADMIN sudo systemctl restart sshd || error "Error restarting SSH!"
color green "Allowing ports 28400 to 28500 (to be used for each client)..."
$REMOTE_SSH_COMMAND_ADMIN sudo ufw allow 28400:28500/tcp || error "Error allowing ports in the firewall!"
color green "Adding ssh key to keychain..."
ssh-add ~/.ssh/$SSH_KEY_NAME || eval `ssh-agent -s`
ssh-add ~/.ssh/$SSH_KEY_NAME
REMOTE_SSH_FWD_PORT=`$REMOTE_SSH_COMMAND cat /home/$REMOTE_USER/port || echo 28399`
REMOTE_SSH_FWD_PORT=$((REMOTE_SSH_FWD_PORT + 1))
if [[ "$REMOTE_SSH_FWD_PORT" -ge 28500 ]]; then
REMOTE_SSH_FWD_PORT=28400
fi
echo "$REMOTE_SSH_FWD_PORT" | $REMOTE_SSH_COMMAND "cat > port" || error "Error incrementing port number!"
mkdir -p "$PARENT_DIR/configs"
CONNECT_CONFIG="$PARENT_DIR/configs/$REMOTE_USER@$REMOTE_SERVER:$REMOTE_SSH_FWD_PORT"
echo "REMOTE_SERVER=$REMOTE_SERVER
REMOTE_SSH_PORT=$REMOTE_SSH_PORT
REMOTE_USER=$REMOTE_USER
SSH_KEY_NAME=$SSH_KEY_NAME
LOCAL_SSH_PORT=$LOCAL_SSH_PORT
REMOTE_SSH_FWD_PORT=$REMOTE_SSH_FWD_PORT" > $CONNECT_CONFIG
CONNECT_SCRIPT="$PARENT_DIR/remote-tunnel.sh $CONNECT_CONFIG"
color green "Adding connection script to local crontab..."
CRON_JOB="*/5 * * * * $CONNECT_SCRIPT"
cron_temp_file=$(mktemp)
crontab -l > "$cron_temp_file" || error "Error retrieving crontab!"
if grep -Fx "$CRON_JOB" "$cron_temp_file"; then
color green "Cron job already installed."
else
echo "$CRON_JOB" >> "$cron_temp_file" || error "Error adding job to crontab!"
crontab "$cron_temp_file" || error "Error installing crontab!"
fi
rm "$cron_temp_file"
color green "Running connection script now..."
$CONNECT_SCRIPT &> /dev/null &
color green "Done. SSH to this machine from anywhere with the command:
----------------------------------------------------------------
ssh -p $REMOTE_SSH_FWD_PORT `whoami`@$REMOTE_SERVER
----------------------------------------------------------------
or add these lines to your ~/.ssh/config on another computer:
----------------------------------------------------------------
Host `hostname`
HostName $REMOTE_SERVER
Port $REMOTE_SSH_FWD_PORT
User `whoami`
----------------------------------------------------------------
and then SSH to this machine with \"ssh `hostname`\"
:)"
#TODO maintain ssh_config_fwd on the server, copy it to local, import it from existing .ssh/ssh_config
#TODO enable SSH on the local machine
#TODO script to uninstall
|
Swift | UTF-8 | 1,224 | 3.15625 | 3 | [
"BSD-3-Clause"
] | permissive | public func hasEntry<K, V>(_ keyMatcher: Matcher<K>, _ valueMatcher: Matcher<V>) -> Matcher<Dictionary<K, V>> {
return Matcher("a dictionary containing [\(keyMatcher.description) -> \(valueMatcher.description)]") { (dictionary: Dictionary<K, V>) -> Bool in
for (key, value) in dictionary {
if keyMatcher.matches(key).boolValue && valueMatcher.matches(value).boolValue {
return true
}
}
return false
}
}
public func hasEntry<K, V: Equatable>(_ expectedKey: K, _ expectedValue: V) -> Matcher<Dictionary<K, V>> {
return hasEntry(equalToWithoutDescription(expectedKey), equalToWithoutDescription(expectedValue))
}
public func hasKey<K, V>(_ matcher: Matcher<K>) -> Matcher<Dictionary<K, V>> {
return hasEntry(matcher, anything())
}
public func hasKey<K, V>(_ expectedKey: K) -> Matcher<Dictionary<K, V>> {
return hasKey(equalToWithoutDescription(expectedKey))
}
public func hasValue<K, V>(_ matcher: Matcher<V>) -> Matcher<Dictionary<K, V>> {
return hasEntry(anything(), matcher)
}
public func hasValue<K, V: Equatable>(_ expectedValue: V) -> Matcher<Dictionary<K, V>> {
return hasValue(equalToWithoutDescription(expectedValue))
}
|
Python | UTF-8 | 1,743 | 3.390625 | 3 | [] | no_license | class Employee:
def __init__(self, employeeId, employeeName, department, salary, role):
self.employeeId = employeeId
self.employeeName = employeeName
self.department = department
self.salary = salary
self.role = role
def calculateIncentive(self, roleIncentivePercentage): # a dict is passed
for k, v in roleIncentivePercentage.items():
if k.lower() == self.role.lower():
incentive = self.salary * (v / 100)
return incentive
return None
def calculateEmployeeSalaryByRole(r, e_list, i_dict):
res_list = []
for p in e_list:
if r.lower() == p.role.lower():
increment = Employee.calculateIncentive(p, i_dict)
p.salary += increment
res_list.append(p)
if len(res_list) == 0:
return None
else:
return res_list
if __name__ == "__main__":
nor = int(input())
role_d = {}
for i in range(nor):
r_name = input()
r_inc = int(input())
role_d[r_name] = r_inc
noe = int(input())
em_list = []
for s in range(noe):
e_id = int(input())
e_name = input()
e_dep = input()
e_sal = int(input())
e_role = input()
e_obj = Employee(e_id, e_name, e_dep, e_sal, e_role)
em_list.append(e_obj)
target_role = input()
res1 = em_list[0].calculateIncentive(role_d)
if res1 is None:
print("Employee Not Found")
else:
print(res1)
res2 = calculateEmployeeSalaryByRole(target_role,em_list,role_d)
if res2 is None:
print("Employee Not Found")
else:
for x in res2:
print(f"{x.employeeId} {x.employeeName} {x.salary}")
|
PHP | UTF-8 | 5,322 | 3.171875 | 3 | [] | no_license | <?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of DateOfBirth
*
* @author Bri
*/
namespace App\Models\Fatcha\Helpers;
class DateUtility {
private $current_num_year;
private $current_num_month;
private $current_num_day;
private $current_num_month_days;
public $birth_num_year;
public $birth_num_month;
public $birth_num_day;
private $yy;
private $mm;
private $dd;
public $age;
const ISO8601 = 'Y-m-d\TH:i:sP';
public function __construc()
{
$this->current_num_year = date("Y");
$this->current_num_month = date("m");
$this->current_num_day = date("j");
$this->current_num_month_days = date("t");
}
private function birthday_before_today()
{
$this->yy = $this->current_num_year - $this->birth_num_year;
$this->mm = $this->current_num_month - $this->birth_num_month - 1;
$this->dd = $this->birth_num_month_days - $this->birth_num_day + $this->current_num_day;
if($this->dd > $this->current_num_month_days)
{
$this->mm += 1;
$this->dd -= $this->current_num_month_days;
}
}
private function birthday_on_today()
{
$this->yy = $this->current_num_year - $this->birth_num_year;
$this->mm = 0;
$this->dd = 0;
}
private function birthday_after_today()
{
$this->yy = $this->current_num_year - $this->birth_num_year - 1;
$this->mm = $this->birth_num_month + $this->current_num_month - 1;
$this->dd = $this->birth_num_month_days - $this->birth_num_day + $this->current_num_day;
if($this->dd > $this->current_num_month_days)
{
$this->mm += 1;
$this->dd -= $this->current_num_day;
}
}
public function calculate_age()
{
$this->birth_num_month_days = date( "t", mktime(0, 0, 0, $this->birth_num_month, $this->birth_num_day, $this->birth_num_year) );
if($this->current_num_month > $this->birth_num_month)
{
$this->birthday_before_today();
}
if($this->current_num_month < $this->birth_num_month)
{
$this->birthday_after_today();
}
if($this->current_num_month == $this->birth_num_month)
{
if($this->current_num_day == $this->birth_num_day)
{
$this->birthday_on_today();
}
if($this->current_num_day < $this->birth_num_day)
{
$this->birthday_after_today();
}
if($this->current_num_day > $this->birth_num_day)
{
$this->birthday_before_today();
}
}
$this->age = $this->yy . ' years, ' . $this->mm . ' months, ' . $this->dd . ' days';
}
public static function getAge($dateYMD){
$today=date("Y/m/d");
$diff = abs(strtotime($today) - strtotime($dateYMD));
return floor($diff/(60*60*24*365));
}
/*
* Get date from age
*/
public static function getDateFromAge($age){
$today=strtotime(date("Y-m-d"));
/*Must have $age + 1
* Because a person born at J-1year +1 day has the same year yet.
*/
$timeElapsed=($age+1)*(60*60*24*365);
$timeElapsed=$today- strtotime(date('Y-m-d', $timeElapsed));
return date('Y-m-d', $timeElapsed);
}
public static function getTimeElapsed($date_string,$type="all"){
$now=strtotime(date("Y-m-d H:i:s"));
$d2 = strtotime($date_string);
//echo ;
$return="";
//$nb_jours = $diff->H;
$seconds=$now-$d2;
if($type=="seconds"){
return $seconds;
}
$arrayReturn=array();
if($seconds<60){
//moins d'une minute
return $seconds." secondes";
}else if($seconds<3600){
$min=floor($seconds/60);
if($min>1){
return $min." minutes";
}else{
return $min." minute";
}
}else if($seconds<(3600*24)){
$hours=floor($seconds/3600);
if($hours>1){
$return.=" heures";
}else{
$return.=" heure";
}
return floor($seconds/3600).$return;
}else if($seconds>(3600*24)){
$day=floor(($seconds/3600)/24);
$hours=(floor($seconds/3600)%24);
$return= $day." jour(s) ";
if($hours>0){
$return.=$hours;
if($hours>1){
$return.=" heures";
}else{
$return.=" heure";
}
}
return $return;
}
return ;
}
public static function dateFromDBToFrontend($dateDBFormat , $dateFormat= 'd-m-Y'){
return date($dateFormat, strtotime($dateDBFormat));
}
public static function dateFromFrontendToDB($dateFrontFormat){
$date = str_replace('/', '-', $dateFrontFormat);
return date('Y-m-d', strtotime($date));
}
}
?> |
JavaScript | UTF-8 | 1,113 | 2.734375 | 3 | [] | no_license | const clipImage = (src, imgW, imgH, cb) => {
// ‘canvas’为前面创建的canvas标签的canvas-id属性值
let ctx = wx.createCanvasContext('canvas');
let canvasW = 640,
canvasH = imgH;
if (imgW / imgH > 5 / 4) {
canvasW = imgH * 5 / 4;
console.log("imgW / imgH > 5 / 4");
} else if (imgW / imgH < 5 / 4) {
canvasH = imgW * 4 / 5;
console.log("imgW / imgH < 5 / 4");
}else {
canvasW = imgW;
console.log("imgW / imgH = 5 / 4");
}
// 将图片绘制到画布
ctx.drawImage(src, (imgW - canvasW) / 2, 0, canvasW, canvasH, 0, 0, canvasW, canvasH)
// draw()必须要用到,并且需要在绘制成功后导出图片
ctx.draw(false, () => {
// setTimeout(() => {
// 导出图片
wx.canvasToTempFilePath({
width: canvasW,
height: canvasH,
destWidth: canvasW,
destHeight: canvasH,
canvasId: 'canvas',
fileType: 'jpg',
success: (res) => {
// res.tempFilePath为导出的图片路径
typeof cb == 'function' && cb(res.tempFilePath);
}
})
// }, 1);
})
}
module.exports = clipImage |
Shell | UTF-8 | 493 | 3.71875 | 4 | [
"MIT"
] | permissive | #!/bin/sh
# This script updates the file if the public IP address has changed
ipaddr=""
if [[ $(cat ~/current_public_ip.txt) = $(curl -4s http://www.icanhazip.com) ]]
then
logger -p local0.info "No change to public IP address"
else
ipaddr=$(curl -4s http://www.icanhazip.com)
echo "IP address has changed to $ipaddr" | mail -s "IP change" sendit2me@myemail.com
echo $ipaddr > ~/current_public_ip.txt
logger -p local0.notice "IP address has changed to $ipaddr"
fi
|
C# | UTF-8 | 800 | 2.828125 | 3 | [] | no_license | using System;
namespace Savchin.Data
{
/// <summary>
/// ParentObjectNotExistsException.
/// </summary>
///
[Serializable()]
public class ParentEntityNotExistsException : IntegrityException
{
private string name;
/// <summary>
/// Gets the name of the object.
/// </summary>
/// <value>The name of the object.</value>
public string Name
{
get { return name; }
}
/// <summary>
/// Initializes a new instance of the <see cref="T:ParentEntityNotExistsException"/> class.
/// </summary>
/// <param name="name">The name.</param>
public ParentEntityNotExistsException(string name): base("Parent Entity Not Exists: " + name)
{
this.name = name;
}
}
}
|
Ruby | UTF-8 | 636 | 3.421875 | 3 | [
"MIT"
] | permissive | # Pascal's Triangle Total Accepted: 50771 Total Submissions: 168463
#
# Given numRows, generate the first numRows of Pascal's triangle.
#
# For example, given numRows = 5,
# Return
#
# [
# [1],
# [1,1],
# [1,2,1],
# [1,3,3,1],
# [1,4,6,4,1]
# ]
#
# Wrote in browser directly
#
# 15 / 15 test cases passed.
# Status: Accepted
# Runtime: 76 ms
#
# Submitted: 0 minutes ago
#
def generate(num_rows)
1.upto(num_rows).inject([]) { |acc, x|
if acc.empty?
acc << [1]
else
acc << [1] + acc.last.each_cons(2).map { |a, b| a + b } + [1]
end
}
end
|
C++ | UTF-8 | 1,252 | 2.875 | 3 | [] | no_license | /*
Create Task pinned to specific core using xTaskCreatePinnedToCore
Main Loop - Core 1
Blink LED Task - Core 0
*/
#include <Arduino.h>
#define LED 15
void Task1( void * parameter )
{
for (;;) {
Serial.print("Task1 runs on Core: ");
Serial.println(xPortGetCoreID());
digitalWrite(LED, HIGH);
Serial.println("LED ON Task 1");
//delay(1000);
vTaskDelay(1000);
digitalWrite(LED, LOW);
//delay(1000);
vTaskDelay(1000);
Serial.println("LED OFF Task 1");
}
}
void setup() {
Serial.begin(115200);
pinMode(LED, OUTPUT);
//Create Blink Task pinned to core 0 - PRO_CPU
xTaskCreatePinnedToCore(
Task1, /* Task function. */
"BLINK", /* name of task. */
1000, /* Stack size of task */
NULL, /* parameter of the task */
1, /* priority of the task */
0, /* Task handle to keep track of created task */
0); /* Core */
}
void loop() {
Serial.print(" Main Loop runs on Core: ");
Serial.println(xPortGetCoreID());
delay(2000);
while(1){
delay(10);
}
}
|
Java | UTF-8 | 1,536 | 3.171875 | 3 | [] | no_license | package utils;
import models.Book;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class JsonParser {
public static List<Book> getJsonContent(String filePath) {
//JSON parser object to parse read file
JSONParser jsonParser = new JSONParser();
List<Book> books = new ArrayList<>();
try (FileReader reader = new FileReader("./books.json")) {
//Read JSON file
Object obj = jsonParser.parse(reader);
JSONArray bookList = (JSONArray) obj;
// System.out.println(bookList);
//Iterate over employee array
bookList.forEach(emp -> books.add(parseBookObject((JSONObject) emp)));
} catch (IOException |
ParseException e) {
e.printStackTrace();
}
return books;
}
private static Book parseBookObject(JSONObject book) {
//Get employee object within list
JSONObject employeeObject = (JSONObject) book.get("book");
//Get employee first name
String title = (String) employeeObject.get("title");
// System.out.println(firstName);
//Get employee last name
String author = (String) employeeObject.get("author");
// System.out.println(lastName);
return new Book(title, author);
}
}
|
C++ | UTF-8 | 1,365 | 3.5625 | 4 | [] | no_license | // Serial sketch, read from serial port and blink LED according to the number that is transmitted over serial
/*
* In python:
*
* import serial
*
* ser = serial.Serial('/dev/ttyUSB0', 9600)
*
* ser.write('3'.encode('utf-8'))
*
* You should get '3' blinks on the arduino. Does not sanitize input for 1-9 only, watch out!
*/
const int LEDpin = 13;
int newlong = 0;
int newlat = 0;
void setup() {
pinMode(LEDpin, OUTPUT);
digitalWrite(LEDpin, LOW);
Serial.begin(9600);
while (!Serial) {
;
}
for (int i = 1; i < 6; i++) { //blink 5 times for readiness.
delay(250);
digitalWrite(LEDpin, HIGH);
delay(250);
digitalWrite(LEDpin, LOW);
}
}
void loop() {
/*
if(Serial.available()){
blink(Serial.read() - '0'); //automagically converts the character '1'-'9' to decimal 1-9
}
delay(500);
}*/
while (Serial.available() > 0) {
string latlong = Serial.readString()
//look for the next valid interger in the incoming serial stream:
//Should be sent in the form "x,y"
//newlong = Serial.parseInt();
//newlat = Serial.parseInt();
blink(newlong);
delay(1000);
blink(newlat);
delay(1000);
}
}
void blink(int numberofTimes) {
for (int i = 0; i < numberofTimes; i++) {
digitalWrite(LEDpin, HIGH);
delay(500);
digitalWrite(LEDpin, LOW);
delay(500);
}
}
|
Python | UTF-8 | 970 | 2.78125 | 3 | [] | no_license | import pandas as pd
from datetime import datetime
import math as m
def basicCalc(timeValue):
return m.ceil((timeValue+1)/5)
def multiCalc(timeValue):
return timeValue*12
def settingTheTimeLabel(timeValue):
sTime = str(timeValue)
if(len(sTime) < 3 ):
return basicCalc(int(sTime))
elif(len(sTime) < 4):
f_digit = int(sTime[:1])
rest = int(sTime[1:])
return multiCalc(f_digit)+basicCalc(rest)
else:
f_digit = int(sTime[:2])
rest = int(sTime[2:])
return multiCalc(f_digit)+basicCalc(rest)
def createTimeIndex():
now = datetime.now().strftime("%H%M")
return settingTheTimeLabel(now)
def createTimeList():
timeIndex = createTimeIndex()
return [timeIndex for i in range(1, 5626)]
def createLocationList():
return [i for i in range(1, 5626)]
def createDataFrame():
return pd.DataFrame({ "time_index" : createTimeList(), "location_index" : createLocationList() }) |
C# | UTF-8 | 2,043 | 2.765625 | 3 | [] | no_license | using Microsoft.AspNetCore.Mvc;
using Sample7.Models;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Sample7.Api.Actions
{
public sealed class EmployeeCsvResult : FileResult
{
private readonly IEnumerable<IModel> _data;
public EmployeeCsvResult(IEnumerable<IModel> data, string fileDownloadName) : base("text/csv")
{
_data = data;
FileDownloadName = fileDownloadName;
}
public async override Task ExecuteResultAsync(ActionContext context)
{
var response = context.HttpContext.Response;
context.HttpContext.Response.Headers.Add("Content-Disposition", new[] { "attachment; filename=" + FileDownloadName });
using (var streamWriter = new StreamWriter(response.Body))
{
var properties = _data.First().GetType().GetProperties();
var header = "";
foreach (var pro in properties)
{
if (typeof(IEnumerable<IModel>).IsAssignableFrom(pro.PropertyType) || typeof(IModel).IsAssignableFrom(pro.PropertyType))
continue;
header += $"{pro.Name};";
}
await streamWriter.WriteLineAsync(header);
foreach (var p in _data)
{
var props = p.GetType().GetProperties();
var line = "";
foreach (var pro in props)
{
if (typeof(IEnumerable<IModel>).IsAssignableFrom(pro.PropertyType) || typeof(IModel).IsAssignableFrom(pro.PropertyType))
continue;
line += $"{pro.GetValue(p)};";
}
await streamWriter.WriteLineAsync(line);
//await streamWriter.FlushAsync();
}
await streamWriter.FlushAsync();
}
}
}
}
|
Shell | UTF-8 | 7,716 | 3.5625 | 4 | [] | no_license | #! /bin/bash
ND_HOME=/home/cavisson/netdiagnostics
Controller_name=work
F1(){
read -p "Enter TierName: " TierName
read -p "Enter ServerName: " ServerName
read -p "Enter InstanceName: " InstanceName
read -p "Enter NDC_IP: " NDC_IP
read -p "Enter NDC_Port: " NDC_PORT
echo -e "tier=$TierName\nserver=$ServerName\ninstance=$InstanceName\nndcHost=$NDC_IP\nndcPort=$NDC_PORT" > $ND_HOME/config/ndsettings_$ndlPort.conf
}
while true
do
echo "Press 1: To change Controller if Not Work."
echo "Press 2: To configure NDC site."
echo "Press 3: To configure Agent site."
echo -e "Press 4: Quit.\n"
read -p "Enter Your Choice: " usr
clear
if (( $usr==1 )); then
read $Controller_name
elif (( $usr==2 )); then
while true
do
echo "Press 1: To change Controller if Controller is Not Work."
echo "Press 2: To know current NDC Port."
echo "Press 3: To know NDC Pid."
echo "Press 4: Enter the available port which you want to use as NDC port."
echo "Press 5: To Start/Stop/ForceReload/Restart/Status NDC Service."
echo -e "Press 6: To Quit.\n"
read -p "Enter your choice: " usr2
if (( $usr2==1 ))
then read -p "Enter the name of Controller you want to use." Controller_name
elif (( $usr2==2 ))
then NDC_CUR=$(grep '^PORT' $NS_WDIR/ndc/conf/ndc.conf|egrep -o '[0-9]{1,5}')
echo "NDC_PORT=$NDC_CUR"
elif (( $usr2==3 )); then
if [[ $Controller_name = "work" ]]; then
/etc/init.d/ndc show | tail -1 | cut -d ' ' -f 2
else
/etc/init.d/ndc_$Controller_name show | tail -1 | cut -d ' ' -f 2
fi
elif (( $usr2==4 ))
then read NDC_PORT
NDC_CUR=$(grep '^PORT' $NS_WDIR/ndc/conf/ndc.conf|egrep -o '[0-9]{1,5}')
sed -i "s/${NDC_CUR}/${NDC_PORT}/" $NS_WDIR/ndc/conf/ndc.conf
elif (( $usr2==5 ))
then echo "Press 1: To check Status."
echo "Press 2: To show Pid."
echo "Press 3: To Start NDC"
echo "Press 4: To Stop NDC"
echo "Press 5: To ForceStop NDC"
echo "Press 6: To Restart NDC"
echo -e "Press 7: To Quit.\n"
read -p "Enter Your Choice: " usr6
if (( $usr6==1 )); then
if [[ $Controller_name = "work" ]]; then
/etc/init.d/ndc show
else
/etc/init.d/ndc_$Controller_name show
fi
elif (( $usr6==2 )); then
if [[ $Controller_name = "work" ]]; then
/etc/init.d/ndc start
else
/etc/init.d/ndc_$Controller_name start
fi
elif (( $usr6==3 )); then
if [[ $Controller_name = "work" ]]; then
/etc/init.d/ndc stop
else
/etc/init.d/ndc_$Controller_name stop
fi
elif (( $usr6==4 )); then
if [[ $Controller_name = "work" ]]; then
/etc/init.d/ndc forcestop
else
/etc/init.d/ndc_$Controller_name forcestop
fi
elif (( $usr6==5 )); then
if [[ $Controller_name = "work" ]]; then
/etc/init.d/ndc restart
else
/etc/init.d/ndc_$Controller_name restart
fi
elif (( $usr6==6 )); then
break
else
echo "You Entered a Wrong Choice."
break
fi
elif (( $usr2==6 )); then
break
else
echo "You Entered a Wrong Choice."
break
fi
done
elif (( $usr==3 ))
then echo "Press 1: To add BCI agent in Tomcat."
echo "Press 2: To Configure already deployed BCI agent in Tomcat."
echo "Press 3: To change Controller if not work."
echo "Press 4: To Start/Stop/Status Tomcat."
echo -e "Press 5: To Quit.\n"
read -p "Enter your choice: " usr3
if (( $usr3==1 ))
then echo "Press 1: To change ND HOME path. [default:/home/cavisson/netdiagnostics]"
echo "Press 2: To configure tomcat file"
echo "Press 3: To configure ndsettings file"
read -p "Press 4: To Quit: " usr4
if (( $usr4==1 )); then
read ND_HOME
elif (( $usr4==2 )); then
read -p "Enter ndlPort: " ndlPort
echo
echo export TOMCAT_OPTS="-Xmx500m -Xmx1500m -XX:PermSize=100m -XX:MaxPermSize=200m -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=60 -javaagent:$ND_HOME/lib/ndmain.jar=time,ndAgentJar=$ND_HOME/lib/ndagent-with-dep.jar,ndHome=$ND_HOME,ndlPort=$ndlPort" >> $NS_WDIR/sys/site.env
elif (( $usr4==3 )); then
F1
elif (( $usr4==4 )); then
break
else
echo "You Entered a Wrong Choice.\n"
break
fi
elif (( $usr3==2 )); then
echo "Press 1: To change ND HOME path. [default:/home/cavisson/netdiagnostics]."
echo "Press 2: To show current ndl port."
echo "Press 3: To make ndsetting file for current ndl port."
echo -e "Press 4: To Quit.\n"
read -p "Enter your choice: " usr5
echo
if (( $usr5==1 )); then
read ND_HOME
echo
elif (( $usr5==2 )); then
ndlPort=$(grep "^export TOMCAT_OPTS=" $NS_WDIR/sys/site.env | egrep -o 'ndlPort=[0-9]{1,5}'| egrep -o '[0-9]{1,5}')
echo -e "ndlPort=$ndlPort\n"
elif (( $usr5==3 )); then
F1
elif (( $usr5==4 )); then
break
else
echo -e "You Entered a Wrong Choice.\n"
break
fi
elif (( $usr3==3 )); then
read $Controller_name
echo
elif (( $usr3==4 )); then
echo "Press 1: To show Pid."
echo "Press 2: To start Tomcat Service."
echo "Press 3: To stop Tomcat Service."
echo "Press 4: To restart Tomcat Service."
echo "Press 5: To forceReload Tomcat Service."
echo -e "Press 6: To Quit\n"
read -p "Enter Your Choice: " usr7
echo
if (( $usr7==1 )); then
ps -ef | grep tomcat | grep $Controller_name |head -2 | cut -d ' ' -f 2
elif (( $usr7==2 )); then
if [[ $Controller_name = "work" ]]; then
/etc/init.d/tomcat start
echo
else
/etc/init.d/tomcat_$Controller_name start
echo
fi
elif (( $usr7==3 ))
then
if [[ $Controller_name = "work" ]]; then
/etc/init.d/tomcat stop
echo
else
/etc/init.d/tomcat_$Controller_name stop
echo
fi
elif (( $usr7==4 )); then
if [[ $Controller_name = "work" ]]; then
/etc/init.d/tomcat restart
echo
else
/etc/init.d/tomcat_$Controller_name restart
echo
fi
elif (( $usr7==5 )); then
if [[ $Controller_name = "work" ]]; then
/etc/init.d/tomcat force-reload
echo
else
/etc/init.d/tomcat_$Controller_name force-reload
echo
fi
elif (( $usr7==6 )); then
break
else
echo "You Entered a Wrong Choice."
break
fi
elif (( $usr3==5 )); then
break
else
echo -e "You Entered a Wrong Choice.\n"
break
fi
elif (( $usr==4 )); then
break
else
echo -e "You Entered a Wrong Choice.\n"
break
fi
done
|
Java | UTF-8 | 182 | 2.21875 | 2 | [] | no_license | public class New {
public static void main (String[] args){
int i = 500;
while (i < 785487643) {
System.out.println("Chizza");
}
}
}
|
C++ | UTF-8 | 5,443 | 2.515625 | 3 | [
"GPL-3.0-only"
] | permissive | #pragma once
#include "../../../../JString.hpp"
#include "./AtomicLong.def.hpp"
namespace java::util::concurrent::atomic
{
// Fields
// Constructors
inline AtomicLong::AtomicLong()
: java::lang::Number(
"java.util.concurrent.atomic.AtomicLong",
"()V"
) {}
inline AtomicLong::AtomicLong(jlong arg0)
: java::lang::Number(
"java.util.concurrent.atomic.AtomicLong",
"(J)V",
arg0
) {}
// Methods
inline jlong AtomicLong::accumulateAndGet(jlong arg0, JObject arg1) const
{
return callMethod<jlong>(
"accumulateAndGet",
"(JLjava/util/function/LongBinaryOperator;)J",
arg0,
arg1.object()
);
}
inline jlong AtomicLong::addAndGet(jlong arg0) const
{
return callMethod<jlong>(
"addAndGet",
"(J)J",
arg0
);
}
inline jlong AtomicLong::compareAndExchange(jlong arg0, jlong arg1) const
{
return callMethod<jlong>(
"compareAndExchange",
"(JJ)J",
arg0,
arg1
);
}
inline jlong AtomicLong::compareAndExchangeAcquire(jlong arg0, jlong arg1) const
{
return callMethod<jlong>(
"compareAndExchangeAcquire",
"(JJ)J",
arg0,
arg1
);
}
inline jlong AtomicLong::compareAndExchangeRelease(jlong arg0, jlong arg1) const
{
return callMethod<jlong>(
"compareAndExchangeRelease",
"(JJ)J",
arg0,
arg1
);
}
inline jboolean AtomicLong::compareAndSet(jlong arg0, jlong arg1) const
{
return callMethod<jboolean>(
"compareAndSet",
"(JJ)Z",
arg0,
arg1
);
}
inline jlong AtomicLong::decrementAndGet() const
{
return callMethod<jlong>(
"decrementAndGet",
"()J"
);
}
inline jdouble AtomicLong::doubleValue() const
{
return callMethod<jdouble>(
"doubleValue",
"()D"
);
}
inline jfloat AtomicLong::floatValue() const
{
return callMethod<jfloat>(
"floatValue",
"()F"
);
}
inline jlong AtomicLong::get() const
{
return callMethod<jlong>(
"get",
"()J"
);
}
inline jlong AtomicLong::getAcquire() const
{
return callMethod<jlong>(
"getAcquire",
"()J"
);
}
inline jlong AtomicLong::getAndAccumulate(jlong arg0, JObject arg1) const
{
return callMethod<jlong>(
"getAndAccumulate",
"(JLjava/util/function/LongBinaryOperator;)J",
arg0,
arg1.object()
);
}
inline jlong AtomicLong::getAndAdd(jlong arg0) const
{
return callMethod<jlong>(
"getAndAdd",
"(J)J",
arg0
);
}
inline jlong AtomicLong::getAndDecrement() const
{
return callMethod<jlong>(
"getAndDecrement",
"()J"
);
}
inline jlong AtomicLong::getAndIncrement() const
{
return callMethod<jlong>(
"getAndIncrement",
"()J"
);
}
inline jlong AtomicLong::getAndSet(jlong arg0) const
{
return callMethod<jlong>(
"getAndSet",
"(J)J",
arg0
);
}
inline jlong AtomicLong::getAndUpdate(JObject arg0) const
{
return callMethod<jlong>(
"getAndUpdate",
"(Ljava/util/function/LongUnaryOperator;)J",
arg0.object()
);
}
inline jlong AtomicLong::getOpaque() const
{
return callMethod<jlong>(
"getOpaque",
"()J"
);
}
inline jlong AtomicLong::getPlain() const
{
return callMethod<jlong>(
"getPlain",
"()J"
);
}
inline jlong AtomicLong::incrementAndGet() const
{
return callMethod<jlong>(
"incrementAndGet",
"()J"
);
}
inline jint AtomicLong::intValue() const
{
return callMethod<jint>(
"intValue",
"()I"
);
}
inline void AtomicLong::lazySet(jlong arg0) const
{
callMethod<void>(
"lazySet",
"(J)V",
arg0
);
}
inline jlong AtomicLong::longValue() const
{
return callMethod<jlong>(
"longValue",
"()J"
);
}
inline void AtomicLong::set(jlong arg0) const
{
callMethod<void>(
"set",
"(J)V",
arg0
);
}
inline void AtomicLong::setOpaque(jlong arg0) const
{
callMethod<void>(
"setOpaque",
"(J)V",
arg0
);
}
inline void AtomicLong::setPlain(jlong arg0) const
{
callMethod<void>(
"setPlain",
"(J)V",
arg0
);
}
inline void AtomicLong::setRelease(jlong arg0) const
{
callMethod<void>(
"setRelease",
"(J)V",
arg0
);
}
inline JString AtomicLong::toString() const
{
return callObjectMethod(
"toString",
"()Ljava/lang/String;"
);
}
inline jlong AtomicLong::updateAndGet(JObject arg0) const
{
return callMethod<jlong>(
"updateAndGet",
"(Ljava/util/function/LongUnaryOperator;)J",
arg0.object()
);
}
inline jboolean AtomicLong::weakCompareAndSet(jlong arg0, jlong arg1) const
{
return callMethod<jboolean>(
"weakCompareAndSet",
"(JJ)Z",
arg0,
arg1
);
}
inline jboolean AtomicLong::weakCompareAndSetAcquire(jlong arg0, jlong arg1) const
{
return callMethod<jboolean>(
"weakCompareAndSetAcquire",
"(JJ)Z",
arg0,
arg1
);
}
inline jboolean AtomicLong::weakCompareAndSetPlain(jlong arg0, jlong arg1) const
{
return callMethod<jboolean>(
"weakCompareAndSetPlain",
"(JJ)Z",
arg0,
arg1
);
}
inline jboolean AtomicLong::weakCompareAndSetRelease(jlong arg0, jlong arg1) const
{
return callMethod<jboolean>(
"weakCompareAndSetRelease",
"(JJ)Z",
arg0,
arg1
);
}
inline jboolean AtomicLong::weakCompareAndSetVolatile(jlong arg0, jlong arg1) const
{
return callMethod<jboolean>(
"weakCompareAndSetVolatile",
"(JJ)Z",
arg0,
arg1
);
}
} // namespace java::util::concurrent::atomic
// Base class headers
#include "../../../lang/Number.hpp"
#ifdef QT_ANDROID_API_AUTOUSE
using namespace java::util::concurrent::atomic;
#endif
|
Markdown | UTF-8 | 13,494 | 3.0625 | 3 | [] | no_license | #Workflows
Each aggregate root tyoe in the system has an associated workflow which manages its state and transitions. It is possible to fully customise the workflow configuration. We can configure the states to meet the requirements in these files:
* `config/Owner/workflows.xml`
* `config/Account/workflows.xml`
* `config/Topic/workflows.xml`
* `config/Comment/workflows.xml`
##The default workflow
The default state machine has three states: `edit`, `published` and `deleted`. It also has a special state named `edit_task` which is used by Honeybee to handle the proceeding of the workflow state back to the original state after an edit. The default workflow can be visualised as follows.

##Configuring workflow states
The workflows are expected to start at an *initial* state, be *promoted* and *demoted* between intermediary states, and *deleted* to a *final* irreversible state. Each state (except the final state) allows definition of named *events* which must specify a transition *target* state which optionally may have a *guard* definition which checks if the state transition is allowed. The entities in our demo need slightly different workflows from the default. We can easily modify the default configuration to suit our needs.
Honeybee specifically uses the `promote`, `demote` and `delete` event names in order to proceed or return from states. Other custom state event names would require explicit configuration for your application.
---
######Introducing Workflux
Workflow and state management is provided by the [Workflux][1] library. This tool allows sophisticated yet easy configuration of state machines, and offers variable and expression based state transitions. Workflux is also responsible for rendering the images on the page.
---
###Owner workflow configuration
The **Owner** has the most complicated workflow with four states, *unverified*, *verified*, *administrator*, and *deleted*. The configuraton has been modified from the default by renaming some states and introducing a new one. The state machine can be visualised as follows.

######config/Owner/workflows.xml
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<state_machines xmlns="urn:schemas-workflux:statemachine:0.5.0">
<state_machine name="hbdemo_commenting_owner_workflow_default">
<initial name="unverified" class="Workflux\State\VariableState">
<event name="edit">
<transition target="edit_task" />
</event>
<event name="promote">
<transition target="verified" />
</event>
<event name="delete">
<transition target="deleted" />
</event>
<option name="read_only_actions">
<option name="resource_history">
<option name="route">hbdemo.commenting.owner.resource.history</option>
</option>
<option name="view_resource">
<option name="route">hbdemo.commenting.owner.resource</option>
</option>
</option>
</initial>
<state name="verified" class="Workflux\State\VariableState">
<event name="edit">
<transition target="edit_task" />
</event>
<event name="demote">
<transition target="unverified" />
</event>
<event name="promote">
<transition target="administrator" />
</event>
<event name="delete">
<transition target="deleted" />
</event>
<option name="read_only_actions">
<option name="resource_history">
<option name="route">hbdemo.commenting.owner.resource.history</option>
</option>
<option name="view_resource">
<option name="route">hbdemo.commenting.owner.resource</option>
</option>
<option name="resource_hierarchy">
<option name="route">hbdemo.commenting.owner.hierarchy</option>
</option>
</option>
</state>
<state name="administrator" class="Workflux\State\VariableState">
<event name="edit">
<transition target="edit_task" />
</event>
<event name="demote">
<transition target="verified" />
</event>
<event name="delete">
<transition target="deleted" />
</event>
<option name="read_only_actions">
<option name="resource_history">
<option name="route">hbdemo.commenting.owner.resource.history</option>
</option>
<option name="view_resource">
<option name="route">hbdemo.commenting.owner.resource</option>
</option>
<option name="resource_hierarchy">
<option name="route">hbdemo.commenting.owner.hierarchy</option>
</option>
</option>
</state>
<state name="edit_task" class="Workflux\State\VariableState">
<transition target="verified">
<guard class="Workflux\Guard\VariableGuard">
<option name="expression">current_state == "verified"</option>
</guard>
</transition>
<transition target="unverified">
<guard class="Workflux\Guard\VariableGuard">
<option name="expression">current_state == "unverified"</option>
</guard>
</transition>
<transition target="administrator">
<guard class="Workflux\Guard\VariableGuard">
<option name="expression">current_state == "administrator"</option>
</guard>
</transition>
<option name="variables">
<option name="task_action">
<option name="module">HBDemo_Commenting</option>
<option name="action">Owner.Resource.Modify</option>
</option>
</option>
</state>
<final name="deleted" />
</state_machine>
</state_machines>
```
###Account workflow configuration
The **Account** workflow is simpler than the default since it only has two steady states, *active* and *deleted*.

######config/Account/workflows.xml
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<state_machines xmlns="urn:schemas-workflux:statemachine:0.5.0">
<state_machine name="hbdemo_commenting_account_workflow_default">
<initial name="active" class="Workflux\State\VariableState">
<event name="edit">
<transition target="edit_task" />
</event>
<event name="delete">
<transition target="deleted" />
</event>
<option name="read_only_actions">
<option name="resource_history">
<option name="route">hbdemo.commenting.account.resource.history</option>
</option>
<option name="view_resource">
<option name="route">hbdemo.commenting.account.resource</option>
</option>
</option>
</initial>
<state name="edit_task" class="Workflux\State\VariableState">
<transition target="active">
<guard class="Workflux\Guard\VariableGuard">
<option name="expression">current_state == "active"</option>
</guard>
</transition>
<option name="variables">
<option name="task_action">
<option name="module">HBDemo_Commenting</option>
<option name="action">Account.Resource.Modify</option>
</option>
</option>
</state>
<final name="deleted" />
</state_machine>
</state_machines>
```
###Topic workflow configuration
The **Topic** workflow is the same structure as the default except the state names have been renamed to *active*, *frozen* and *deleted* which are more meaningful for this subject.

######config/Topic/workflows.xml
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<state_machines xmlns="urn:schemas-workflux:statemachine:0.5.0">
<state_machine name="hbdemo_commenting_topic_workflow_default">
<initial name="active" class="Workflux\State\VariableState">
<event name="edit">
<transition target="edit_task" />
</event>
<event name="promote">
<transition target="frozen" />
</event>
<event name="delete">
<transition target="deleted" />
</event>
<option name="read_only_actions">
<option name="resource_history">
<option name="route">hbdemo.commenting.topic.resource.history</option>
</option>
<option name="view_resource">
<option name="route">hbdemo.commenting.topic.resource</option>
</option>
</option>
</initial>
<state name="frozen" class="Workflux\State\VariableState">
<event name="edit">
<transition target="edit_task" />
</event>
<event name="demote">
<transition target="active" />
</event>
<event name="delete">
<transition target="deleted" />
</event>
<option name="read_only_actions">
<option name="resource_history">
<option name="route">hbdemo.commenting.owner.resource.history</option>
</option>
<option name="view_resource">
<option name="route">hbdemo.commenting.owner.resource</option>
</option>
<option name="resource_hierarchy">
<option name="route">hbdemo.commenting.owner.hierarchy</option>
</option>
</option>
</state>
<state name="edit_task" class="Workflux\State\VariableState">
<transition target="active">
<guard class="Workflux\Guard\VariableGuard">
<option name="expression">current_state == "active"</option>
</guard>
</transition>
<transition target="frozen">
<guard class="Workflux\Guard\VariableGuard">
<option name="expression">current_state == "frozen"</option>
</guard>
</transition>
<option name="variables">
<option name="task_action">
<option name="module">HBDemo_Commenting</option>
<option name="action">Topic.Resource.Modify</option>
</option>
</option>
</state>
<final name="deleted" />
</state_machine>
</state_machines>
```
###Comment workflow configuration
The **Comment** workflow is also simplified to two states, *published* and *deleted*.

######config/Comment/workflows.xml
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<state_machines xmlns="urn:schemas-workflux:statemachine:0.5.0">
<state_machine name="hbdemo_commenting_comment_workflow_default">
<initial name="published" class="Workflux\State\VariableState">
<event name="edit">
<transition target="edit_task" />
</event>
<event name="delete">
<transition target="deleted" />
</event>
<option name="read_only_actions">
<option name="resource_history">
<option name="route">hbdemo.commenting.comment.resource.history</option>
</option>
<option name="view_resource">
<option name="route">hbdemo.commenting.comment.resource</option>
</option>
</option>
</initial>
<state name="edit_task" class="Workflux\State\VariableState">
<transition target="published">
<guard class="Workflux\Guard\VariableGuard">
<option name="expression">current_state == "published"</option>
</guard>
</transition>
<option name="variables">
<option name="task_action">
<option name="module">HBDemo_Commenting</option>
<option name="action">Comment.Resource.Modify</option>
</option>
</option>
</state>
<final name="deleted" />
</state_machine>
</state_machines>
```
[1]: https://github.com/shrink0r/workflux
|
C | UTF-8 | 2,373 | 3.765625 | 4 | [] | no_license | /*
** unique_ptr.c
**/
#include <iostream>
#include <vector>
#include <memory>
#include <cstdio>
#include <fstream>
#include <cassert>
#include <functional>
struct B
{
virtual void bar() { std::cout << "B::bar\n"; }
virtual ~B() = default;
};
struct D : B
{
D() { std::cout << "D::D\n"; }
~D() { std::cout << "D::~D\n"; }
void bar() override { std::cout << "D::bar\n"; }
};
// a function consuming a unique_ptr can take it by value or by rvalue reference
std::unique_ptr<D> pass_through(std::unique_ptr<D> p)
{
p->bar();
return p;
}
int main(int argc, char** argv)
{
std::cout << "unique ownership semantics demo\n";
{
auto p = std::make_unique<D>(); // p is a unique_ptr that owns a D
auto q = pass_through(std::move(p));
assert(!p); // now p owns nothing and holds a null pointer
q->bar(); // and q owns the D object
} // ~D called here
std::cout << "Runtime polymorphism demo\n";
{
std::unique_ptr<B> p = std::make_unique<D>(); // p is a unique_ptr that owns a D
// as a pointer to base
p->bar(); // virtual dispatch
std::vector<std::unique_ptr<B>> v; // unique_ptr can be stored in a container
v.push_back(std::make_unique<D>());
v.push_back(std::move(p));
v.emplace_back(new D);
for(auto& p: v) p->bar(); // virtual dispatch
} // ~D called 3 times
std::cout << "Custom deleter demo\n";
std::ofstream("demo.txt") << 'x'; // prepare the file to read
{
std::unique_ptr<std::FILE, decltype(&std::fclose)> fp(std::fopen("demo.txt", "r"),
&std::fclose);
if(fp) // fopen could have failed; in which case fp holds a null pointer
std::cout << (char)std::fgetc(fp.get()) << '\n';
} // fclose() called here, but only if FILE* is not a null pointer
// (that is, if fopen succeeded)
std::cout << "Custom lambda-expression deleter demo\n";
{
std::unique_ptr<D, std::function<void(D*)>> p(new D, [](D* ptr)
{
std::cout << "destroying from a custom deleter...\n";
delete ptr;
}); // p owns D
p->bar();
} // the lambda above is called and D is destroyed
std::cout << "Array form of unique_ptr demo\n";
{
std::unique_ptr<D[]> p{new D[3]};
} // calls ~D 3 times
}
|
C++ | UTF-8 | 1,357 | 2.734375 | 3 | [] | no_license | #ifndef _GPIOCTRL_H_
#define _GPIOCTRL_H_
#include <climits>
#include <thread>
#include "globals.h"
extern globalVars globals;
// Set maximum number of controls
const int MaxControls = 20;
enum pinType {
Rot1 = 0,
Rot2 = 1,
Push = 2,
Toggle = 3,
Led = 4
};
class gpioctrl
{
private:
std::thread *watcherThread = NULL;
public:
int controlCount = 0;
int gpio[MaxControls][5]; // One slot for each pinType
int rotateValue[MaxControls];
int pushValue[MaxControls];
int toggleValue[MaxControls];
int lastRotateValue[MaxControls];
int lastPushValue[MaxControls];
int lastRotateState[MaxControls];
int lastPushState[MaxControls];
bool clockwise[MaxControls];
public:
gpioctrl(bool initWiringPi);
~gpioctrl();
int getSetting(const char* control, const char* controlType, const char* attribute);
int addControl();
int addRotaryEncoder(const char* controlName);
int addButton(const char* controlName);
int addSwitch(const char* controlName);
int addLamp(const char* controlName);
int readRotation(int control);
int readPush(int control);
int readToggle(int control);
void writeLed(int control, bool on);
private:
void validateControl(const char* controlName, int control);
void initPin(int pin, bool isInput);
};
#endif // _GPIOCTRL_H_
|
Java | UTF-8 | 574 | 2.3125 | 2 | [] | no_license | package org.ajax4jsf.bean;
public class AjaxLogBean {
private boolean popup = false;
/**
* Gets value of popup field.
*
* @return value of popup field
*/
public boolean isPopup() {
return popup;
}
/**
* Set a new value for popup field.
*
* @param popup
* a new value for popup field
*/
public void setPopup(boolean popup) {
this.popup = popup;
}
public void initPopupMode() {
popup = true;
}
public void reset() {
popup = false;
}
}
|
C | UTF-8 | 1,102 | 3.1875 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int i,j,temp,n,b[10],totw=0,tott=0,wt[10],tat[10];
float avgwt, avgtat;
printf("FCFS scheduling\n");
printf("Enter the number of processes \n");
scanf("%d",&n);
printf("Enter the burst time of %d processes\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
for(i=0;i<n;i++)
{
if (i==0)
{
wt[0]=0;
tat[0]=b[0];
continue;
}
else
{
wt[i]=b[i-1]+wt[i-1];
tat[i]=wt[i]+b[i];
totw+=wt[i];
tott+=tat[i];
}
}
avgwt=(float)totw/n;
avgtat=(float)tott/n;
printf("In FCFS \naverage waiting time is %f \naverage turnaround time is %f\n",avgwt,avgtat);
printf("SJF scheduling\n");
totw=0;
tott=0;
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(b[j]>b[j+1])
{
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}
}
}
for(i=0;i<n;i++)
{
if (i==0)
{
wt[0]=0;
continue;
}
wt[i]=b[i-1]+wt[i-1];
tat[i]=wt[i]+b[i];
totw+=wt[i];
tott+=tat[i];
}
avgwt=(float)totw/n;
avgtat=(float)tott/n;
printf("In SJF \naverage waiting time is %f \naverage turnaround time is %f\n",avgwt,avgtat);
return 0;
}
|
Markdown | UTF-8 | 1,146 | 2.609375 | 3 | [] | no_license | ## 二级存储
这里我们配置NFS服务作为CloudStack中用到的二级存储, 并在其上引入系统虚拟机模板。
### NFS服务器
在Management节点上,默认的nfs-utils已经被安装,所以我们只需要按照以下步骤配置:
```
# vim /etc/exports
/home/exports *(rw,async,no_root_squash,no_subtree_check)
# mkdir -p /home/exports
# chmod 777 -R /home/exports/
# chkconfig nfs on
# chkconfig rpcbind on
# service nfs restart
# service rpcbind restart
# iptables -D INPUT -j REJECT --reject-with icmp-host-prohibited
# vim /etc/sysconfig/iptables
-D INPUT -j REJECT --reject-with icmp-host-prohibited
```
### 引入系统虚拟机模板
在Management机器上做如下操作:
```
# mount -t nfs 192.168.139.2:/home/exports/ /mnt
# /usr/share/cloudstack-common/scripts/storage/secondary/cloud-install-sys-tmplt \
-m /mnt/ -u http://192.168.0.79/systemvm64template-4.5-kvm.qcow2.bz2 -h kvm -F
```
安装完模板后我们可以到/home/exports目录下检查:
```
[root@csmgmt ~]# ls /home/exports/
template
[root@csmgmt ~]# du -hs /home/exports/template/
290M /home/exports/template/
```
|
Java | UTF-8 | 914 | 3.015625 | 3 | [] | no_license | package Day27_Wrappers.StaticPractice;
public class AmazonTest {
public static void main(String[] args) throws Exception {
AmozonUtils.navigate(Testdata.URL);
AmozonUtils.login(Testdata.username, Testdata.password);
AmozonUtils.search("Carpet");
String[] actualResult = {"carpet","rug","Turkish carpet","American carpet"}; // , "sofa"
for(String result: actualResult) {
if(result.contains("carpet") || result.contains("rug")) {
}else {
System.out.println("FAILED");
throw new Exception("FAILED. Expected: carpet, but Actual:"+ result);
}
}
double[] cartItemPrices = {30.99, 26.95, 39.99};
double actualTotalAmount = 97.93;
double expectedTotalAmount = Calculator.sum(cartItemPrices);
if(actualTotalAmount != expectedTotalAmount) {
System.out.println("Prices are not match:\nActual: "+ actualTotalAmount+"\nExpected: "+expectedTotalAmount);
}
}
}
|
Java | UTF-8 | 416 | 2.234375 | 2 | [] | no_license | package sample;
public enum Genres {
FPS("FPS"), ShootThemUp("Shoot 'em up"), Roguelike("Roguelike"), Roguelite("Roguelite"), RPG("RPG"), ActionRPG("ActionRPG"),
Platformer("Platformer"), Metroidvania("Metroidvania"), Simulator("Simulator"), Race("Race"), MMORPG("MMORPG"), RTS("RTS"), Strategy("Strategy"),
Puzzle("Puzzle");
String name;
Genres(String name){
this.name = name;
}
}
|
C++ | UTF-8 | 1,131 | 2.609375 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
char token[1024][512];
int tlen[1024];
int WIDTH, offset = 0, n = 0;
char buf[10<<20];
static int readtoken(char **ret) {
static const int N = 10<<20;
static char *end = buf, *token = NULL;
if(token == NULL) {
if((end = buf + fread(buf, 1, N, stdin)) == buf)
return EOF;
token = strtok(buf, " \n");
} else {
token = strtok(NULL, " \n");
}
*ret = token;
return 1;
}
void mflush() {
if (n == 0) return;
if (n == 1) {
printf("%s", token[0]);
for (int i = offset; i < WIDTH; i++)
putchar(' ');
} else {
int base = (WIDTH - offset) / (n-1), ss = (WIDTH - offset) % (n-1);
for (int i = 0; i < n; i++) {
printf("%s", token[i]);
if (i != n-1)
for (int j = 0; j < base; j++)
putchar(' ');
if (i < ss) putchar(' ');
}
}
puts("");
n = 0, offset = 0;
}
int main() {
char *s;
readtoken(&s);
sscanf(s, "%d", &WIDTH);
while (readtoken(&s) != EOF && s) {
int m = strlen(s);
if (offset + n + m > WIDTH)
mflush();
strcpy(token[n], s);
tlen[n] = m, offset += m;
n++;
}
mflush();
return 0;
}
|
Python | UTF-8 | 922 | 2.765625 | 3 | [] | no_license | def test(Tdentro,t):
Qsaida = (Tdentro-Tfora)/(espessura/(kar*Areainterna) + 1/(har*Areainterna))
Qentrada = o * emissividade * Areainterna * (Tpessoa**4-Tdentro**4)
dTdt = (Qentrada-Qsaida)/m0*cneve
print(Qsaida)
return dTdt
from math import pi
kar = 500
raio = 2
Areainterna = 4*pi*raio**2/2
espessura = 0.3
har = 10
Tfora = -45 + 273.15
o = 5.6703e-8
emissividade = 0.95
Tpessoa = 37 + 273.15
volume_ar = 4/3*pi*raio**3
densidade_ar = 1.2922
m0 = densidade_ar * volume_ar
cneve = 2090
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
Tdentro = [Tfora]
Tmax = 24
listaTempo = np.arange(0,Tmax,1)
solucao = odeint(test,Tdentro,listaTempo)
#TempC = [temp-273.15 for temp in solucao[:,0]]
#TempoH = [t/3600 for t in listaTempo]
plt.plot(listaTempo,solucao)
plt.xlabel('Tempo (s)')
plt.ylabel('Temperatura K')
plt.show() |
PHP | UTF-8 | 3,077 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
];
});
$factory->define(App\Goal::class, function (Faker\Generator $faker){
return [
'name' => $faker->sentence,
'inactive' => 0,
];
});
$factory->define(App\Assessor::class, function (Faker\Generator $faker){
return [
'username' => $faker->userName,
'name' => $faker->name,
];
});
$factory->define(App\Team::class, function (Faker\Generator $faker){
return [
'name' => $faker->sentence,
'mission' => $faker->sentence,
];
});
$factory->define(App\Assessment::class, function (Faker\Generator $faker){
return [
'assessor_id' => function () {
return factory('App\Assessor')->create()->id;
},
'period' => '2018',
'slo_id' => rand(1,200),
'goal_id' => rand(1,7),
'team_id' => rand(1,30),
'course' => $faker->word,
'method' => $faker->sentence,
'measure' => $faker->sentence,
];
});
$factory->define(App\Slo::class, function (Faker\Generator $faker){
return [
'name' => $faker->sentence,
'team_id' => rand(1,30),
'team_id' => function () {
return factory('App\Team')->create()->id;
},
'inactive' => 0,
];
});
$factory->define(App\Reassessment::class, function (Faker\Generator $faker){
return [
// 'assessor_id' => function () {
// return factory('App\Assessor')->create()->id;
// },
'assessor_id' => rand(1,200),
'slo_id' => rand(1,200),
'goal_id' => rand(1,7),
// return [
'team_id' => function () {
return factory('App\Team')->create()->id;
},
'course' => $faker->word,
'method' => $faker->sentence,
'measure' => $faker->sentence,
'floyd' => $faker->sentence,
'cartersville' => $faker->sentence,
'marietta' => $faker->sentence,
'paulding' => $faker->sentence,
'heritage' => $faker->sentence,
'douglasville' => $faker->sentence,
'elearning' => $faker->sentence,
'data_summary' => $faker->sentence,
'recommended_actions' => $faker->sentence,
'results' => rand(1,4),
'submit_date' => $faker->date('Y-m-d'),
'complete_date' => $faker->date('Y-m-d'),
];
});
|
Java | UTF-8 | 628 | 2.203125 | 2 | [
"Unlicense"
] | permissive | package cc.novoline.events;
import cc.novoline.events.EventManager;
import java.lang.reflect.Method;
final class EventManager$MethodData {
private final Object source;
private final Method target;
private final byte priority;
public EventManager$MethodData(Object var1, Method var2, byte var3) {
EventManager.b();
super();
this.source = var1;
this.target = var2;
this.priority = var3;
}
public Object getSource() {
return this.source;
}
public Method getTarget() {
return this.target;
}
public byte getPriority() {
return this.priority;
}
}
|
C# | UTF-8 | 1,102 | 3.09375 | 3 | [] | no_license | using System.IO;
namespace lib
{
public class StringWriterWithEvent : StringWriter
{
public event OnFlushed Flushed;
public delegate void OnFlushed();
public event OnWritten Written;
public delegate void OnWritten(string str);
public bool AutoFlush { get; set; }
public override void Flush()
{
base.Flush();
if (Flushed != null) Flushed();
}
public override void Write(bool value)
{
base.Write(value);
if (Written != null) Written(value.ToString());
if (AutoFlush) Flush();
}
public override void Write(char[] buffer)
{
base.Write(buffer);
if (Written != null) Written(new string(buffer));
if (AutoFlush) Flush();
}
public override void Write(char[] buffer, int index, int count)
{
base.Write(buffer, index, count);
if (Written != null) Written(new string(buffer, index, count));
if (AutoFlush) Flush();
}
}
}
|
Markdown | UTF-8 | 2,675 | 2.828125 | 3 | [] | no_license | #### 第四百零六章 愣严真传承 大法波罗尊
多耶波落嘎
愣严法身成就时候,炼成他时候,张口对虚空说,捏了一个法诀我知道这个意思
(愣严法身)召唤十方三世一切诸佛菩萨罗汉护
法眷属敕令
锅嘎
愣严金身成就时候也是张嘴说了这个,我也是记录自然知道他的意思,捏了一个诀
(愣严金身)命令一切众生
莫令
愣严法相成就时候也是如此,捏了一个诀,开口喝言,虚空沸腾振动……
(愣言法相)镇魔王
最后愣严法相开口,虚空沸腾振动,而成功修成,外面无数穿黄僧衣和尚泪流漫漫………
只是扣头不止………
多耶波落嘎,法身又捏诀说了一句,无数金刚护法出现,他将手一直,就是那害我的小人,那些金刚护法竖掌胸前一礼,杀去了………
愣严法身金身法相终于成就了………
记得多年前,我踏入修行,不太懂,就去如今药师佛身那个道场,有那经书,所谓结缘的
我就拿了那本愣严神咒
那个时候我每天上班,早上闹钟起来练功,后烧水洗漱而去上班,还记得衣服一身上下两天一换,同事都说我太爱干净
女同事特别喜欢我………额,…此处有些尴尬……
而那个时候,经常夏门有台风什么的,我就沐浴点燃香,那里捧着愣严神咒念,那摩萨多喃…………………………
一直念,多少遍,记不得,反正一遍过大概就是半小时吧……
后来我说,我不要台风过来,我要它消散,……
后来它就没有了,……………
很多次都是这样,我一直上班修行,后来我记得哪天我去火车站,那里下车一个灵体女仙,说契约到了,该去北方了,我们安排…………
后来认识了先妻,她过来夏门,后又回去了,是那夜,大雨倾盆磅礴,……
万灵流泪相送,有一部分随我去北方,我去寻先妻去了,要度他……
从此北方兴盛那2014年后(根据自己空间照片显示),后度成,被害妻儿车祸,我回来南方………
然也,本尊莫哭,本座当报仇,给你交待,……
因为我立过规矩,不管自己什么身道成就,必须彻查当年车祸我一家被害事情,……
法身飞天而去,金身法身亦是如此。
自己也是无奈,很多知道我有这个,后无比激动的,想抢夺的更不用说
佛祖解决了,那边传来讯息
让我快速修成,……………
我也是无奈不睡了,爬将起来双腿一盘完成任务也。
|
TypeScript | UTF-8 | 631 | 3.59375 | 4 | [
"MIT",
"CC0-1.0"
] | permissive | import createMathOperation from './.internal/createMathOperation';
/**
* @ignore
*/
const internalAdd = createMathOperation((augend: any, addend: any) => augend + addend, 0);
/**
* Adds two numbers.
*
* @since 5.3.0
* @category Math
* @param augend The first number in an addition.
* @param addend The second number in an addition.
* @returns Returns the total.
* @example
*
* ```js
* add(6, 4)
* // => 10
* add('6', '4')
* // => '64'
* ```
*
*/
export function add<T>(augend: T, addend: T): T;
export function add(augend: any, addend: any): any {
return internalAdd(augend, addend);
}
export default add;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.