language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 2,289
| 2.546875
| 3
|
[] |
no_license
|
package game.worldsrv.support;
import game.worldsrv.support.Utils;
import java.util.Properties;
import core.support.SysException;
/**
* 系统参数 本类都是简单的参数配置,如果需要判断系统环境, 比如是手游还是页游,则使用C.java判断
*/
public class C {
// 配置文件名称
private static final String CONFIG_NAME = "config.properties";
public static final String GAME_DATAEYE_APPID;// 数据分析appid
public static final String GAME_DATAEYE_LOGDIR;// 数据分析日志目录
public static final String GAME_I18N_KEY; // 游戏语言
public static final int GAME_PLATFORM_ID; // 运营平台ID[1,91]:不可设置为0,1到91为可设置范围
public static final int GAME_SERVER_ID; // 游戏区服ID[0,9999]:0为测试服,1到9999为正式服
public static final boolean DEBUG_ENABLE; // 是否启动调试,开启则不处理心跳检测
static {
Properties prop = Utils.readProperties(CONFIG_NAME);
if (prop.containsKey("game.dataeye.appid")) {
GAME_DATAEYE_APPID = prop.getProperty("game.dataeye.appid");
} else {// 默认为空,无需接入数据分析SDK
GAME_DATAEYE_APPID = "";
}
if (prop.containsKey("game.dataeye.logdir")) {
GAME_DATAEYE_LOGDIR = prop.getProperty("game.dataeye.logdir");
} else {// 默认为空
GAME_DATAEYE_LOGDIR = "";
}
GAME_I18N_KEY = prop.getProperty("game.i18n.key");
// 运营平台ID[1,91]:不可设置为0,1到91为可设置范围
if (prop.containsKey("game.platform.id")) {
GAME_PLATFORM_ID = Integer.valueOf(prop.getProperty("game.platform.id"));
} else {
GAME_PLATFORM_ID = -1;
}
if (GAME_PLATFORM_ID < 1 || GAME_PLATFORM_ID > 91) {
throw new SysException("==={}配置错误,请检查:运营平台ID={}", CONFIG_NAME, GAME_PLATFORM_ID);
}
// 游戏区服ID[0,9999]:0为测试服,1到9999为正式服
if (prop.containsKey("game.server.id")) {
GAME_SERVER_ID = Integer.valueOf(prop.getProperty("game.server.id"));
} else {
GAME_SERVER_ID = -1;
}
if (GAME_SERVER_ID < 0 || GAME_SERVER_ID > 9999) {
throw new SysException("==={}配置错误,请检查:游戏区服ID={}", CONFIG_NAME, GAME_SERVER_ID);
}
DEBUG_ENABLE = Utils.booleanValue(prop.getProperty("debug.enable"));
}
}
|
Python
|
UTF-8
| 1,805
| 2.671875
| 3
|
[] |
no_license
|
#!/usr/bin/python3
from locators.locators import Locators
class HomePage:
def __init__(self, driver):
self.driver = driver
# ----------------------------------- Elements -----------------------------------
self.user_icon_link_xpath = Locators.user_icon_link_xpath
self.my_profile_link_xpath = Locators.my_profile_link_xpath
self.sign_out_link_xpath = Locators.sign_out_link_xpath
self.home_icon_xpath = Locators.home_icon_xpath
self.new_talent_btn_xpath = Locators.new_talent_btn_xpath
self.talent_1_edit_icon_xpath = Locators.talent_1_edit_icon_xpath
# ----------------------------------- Methods -----------------------------------
def click_home_icon(self):
ele = self.driver.find_element_by_xpath(self.home_icon_xpath)
self.driver.execute_script("arguments[0].click();", ele)
def click_new_talent_button(self):
self.driver.find_element_by_xpath(self.new_talent_btn_xpath).click()
def click_user_icon(self):
ele = self.driver.find_element_by_xpath(self.user_icon_link_xpath)
self.driver.execute_script("arguments[0].click();", ele)
def click_my_profile_link(self):
self.driver.find_element_by_xpath(self.my_profile_link_xpath).click()
def click_sign_out(self):
self.driver.find_element_by_xpath(self.sign_out_link_xpath).click()
def sign_out(self):
ele = self.driver.find_element_by_xpath(self.user_icon_link_xpath)
self.driver.execute_script("arguments[0].click();", ele)
self.driver.find_element_by_xpath(self.sign_out_link_xpath).click()
def click_talent_01_edit_icon(self):
self.driver.find_element_by_xpath(self.talent_1_edit_icon_xpath).click()
|
C
|
UTF-8
| 3,347
| 3.78125
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define tamanho_vetor 1000
#define range 10000
void insereOrdenado(int vetor[], int valor, int posicao){
int aux = 0, i = 0;
//Insere o primeiro elemento no vetor
if(posicao == 0){
vetor[posicao] = valor;
}else{
//verifica a posição onde o valor vai ser inserido no vetor
while( ( i < posicao) && (vetor[i] < valor)){
aux = i;
i++;
}
//Insere quando o valor é menor que a primeira posição
if( aux == 0){
for(int j = posicao; j > i; j--){
vetor[j] = vetor[j - 1];
}
vetor[i] = valor;
//Insere no vetor quanto está na última posição
}else if(i == posicao){
vetor[i] = valor;
//Insere no vetor quando está no meio
}else{
for(int j = posicao; j > i; j--){
vetor[j] = vetor[j - 1];
}
vetor[i] = valor;
}
}
}
int verificaIguais(int vetor[], int valor, int posicao){
for(int i = 0; i < posicao; i++){
if(vetor[i] == valor){
//Retorna 0 - Quando os valores se repetem
return 0;
}
}
//Retorna 1 - Quando os valores não se repetem
return 1;
}
void aleatoriosDistintos(int vetor[]){
int valor;
//Semente aleatória criada;
srand(time(NULL));
//Preenchendo o vetor
for(int i = 0; i < tamanho_vetor; i++){
valor = rand() % range;
//Verificando se o valor atual é igual a algum valor do vetor
while( verificaIguais(vetor, valor, i) != 1 ){
valor = rand() % range;
}
//Insere ordenadamente os valores no vetor
insereOrdenado(vetor, valor, i);
}
}
int buscaBinaria(int vetor[], int esq, int dir, int valor, int comparacoes){
int i;
if(dir >= esq){
i = (esq + dir) / 2;
comparacoes++;
printf("\n Comparacao: %d", comparacoes);
if(vetor[i] == valor){
return i;
}
if(vetor[i] > valor){
return buscaBinaria(vetor, esq, i - 1, valor, comparacoes);
}else{
return buscaBinaria(vetor, i + 1, dir, valor, comparacoes);
}
}
return -1;
}
int main(){
int vetor[tamanho_vetor], valor, esq = 0, dir = tamanho_vetor, comparacoes = 0, resultado;
aleatoriosDistintos(vetor);
//Mostrando as 1000 posições do vetor
printf("******************************* VETOR *******************************\n");
for(int i = 0; i < tamanho_vetor; i++){
printf(" %d ", vetor[i]);
}
printf("\n\n");
printf("\n Entre com o valor para busca: ");
scanf("%d", &valor);
resultado = buscaBinaria(vetor, esq, dir, valor, comparacoes);
printf("\n Posicao encontrada foi: %d\n\n", resultado);
/*
printf("\n Posicao encontrada foi: %d\n\n", buscaBinaria(vetor, esq, dir, 45, comparacoes));
printf("\n Posicao encontrada foi: %d\n\n", buscaBinaria(vetor, esq, dir, 550, comparacoes));
printf("\n Posicao encontrada foi: %d\n\n", buscaBinaria(vetor, esq, dir, 1056, comparacoes));
printf("\n Posicao encontrada foi: %d\n\n", buscaBinaria(vetor, esq, dir, 7859, comparacoes));
*/
return 0;
}
|
Java
|
UTF-8
| 2,920
| 2.78125
| 3
|
[] |
no_license
|
package com.techelevator.operations;
public class Space {
private String spaceName;
private int spaceId;
private boolean isAccessible;
private String openDate;
private String closeDate;
private double dailyRate;
private int maxOccupancy;
private int menuID;
public String getSpaceName() {
return spaceName;
}
public void setSpaceName(String spaceName) {
this.spaceName = spaceName;
}
public int getSpaceId() {
return spaceId;
}
public void setSpaceId(int spaceId) {
this.spaceId = spaceId;
}
public boolean isAccessible() {
return isAccessible;
}
public void setAccessible(boolean isAccessible) {
this.isAccessible = isAccessible;
}
public String getOpenDate() {
return openDate;
}
public void setOpenDate(String openDate) {
this.openDate = openDate;
}
public String getCloseDate() {
return closeDate;
}
public void setCloseDate(String closeDate) {
this.closeDate = closeDate;
}
public double getDailyRate() {
return dailyRate;
}
public void setDailyRate(double dailyRate) {
this.dailyRate = dailyRate;
}
public int getMaxOccupancy() {
return maxOccupancy;
}
public void setMaxOccupancy(int maxOccupancy) {
this.maxOccupancy = maxOccupancy;
}
public int getMenuID() {
return menuID;
}
public void setMenuID(int menuID) {
this.menuID = menuID;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((closeDate == null) ? 0 : closeDate.hashCode());
long temp;
temp = Double.doubleToLongBits(dailyRate);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + (isAccessible ? 1231 : 1237);
result = prime * result + maxOccupancy;
result = prime * result + menuID;
result = prime * result + ((openDate == null) ? 0 : openDate.hashCode());
result = prime * result + spaceId;
result = prime * result + ((spaceName == null) ? 0 : spaceName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Space other = (Space) obj;
if (closeDate == null) {
if (other.closeDate != null)
return false;
} else if (!closeDate.equals(other.closeDate))
return false;
if (Double.doubleToLongBits(dailyRate) != Double.doubleToLongBits(other.dailyRate))
return false;
if (isAccessible != other.isAccessible)
return false;
if (maxOccupancy != other.maxOccupancy)
return false;
if (menuID != other.menuID)
return false;
if (openDate == null) {
if (other.openDate != null)
return false;
} else if (!openDate.equals(other.openDate))
return false;
if (spaceId != other.spaceId)
return false;
if (spaceName == null) {
if (other.spaceName != null)
return false;
} else if (!spaceName.equals(other.spaceName))
return false;
return true;
}
}
|
Markdown
|
UTF-8
| 1,278
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
## 功能
确认弹窗
## API
#### 属性
属性 | 说明 | 类型 | 默认值
---|---|---|---
content | 文本内容 | `string` | `确认?`
msg | 文本内容 | `string` | `确认?`
title | 弹窗标题 | `string` | `提示`
showIcon | 是否显示Icon | `boolean` | `false`
iconClass | icon的class | `string` | `icon-question`
cancelText | 取消按钮文字,如果是空串就不渲染取消按钮| `string` | `取消`
okText | 确定按钮的文字 | `string` | `确认`
footerHide| 是否隐藏footer| `Boolean`| `false`
renderContent| 自定义渲染内容| `function`| -
showIcon | 是否显示提示icon | `boolean` | `false`
status | icon的状态'success', 'error', 'question', 'info', '' | `string` | `''`
iconClass | 自定义icon的样式class,此时不要传status属性,否则优先使用status的样式 | `string` | -
okCallback | 点击确定时的回调,如果返回Promise则会等待这个Promise结束,如果promise状态变为resolve则关闭弹窗,否则不关闭弹窗;如果返回的不是promise则判断返回值是否为真,是则关闭弹窗,否则不关闭弹窗 | `function` | -
#### 基础用法
```js
Confirm.popup({ msg: '确认删除吗?' }).then(() => console.log('ok')).catch(() => console.log('cancel'));
```
|
Java
|
UTF-8
| 634
| 1.546875
| 2
|
[] |
no_license
|
package cn.com.jiahang.core.manager.system.service.impl;
import cn.com.jiahang.core.manager.system.entity.SysFillRule;
import cn.com.jiahang.core.manager.system.mapper.SysFillRuleMapper;
import cn.com.jiahang.core.manager.system.service.ISysFillRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* @Description: 填值规则
* @Author: jeecg-boot
* @Date: 2019-11-07
* @Version: V1.0
*/
@Service("sysFillRuleServiceImpl")
public class SysFillRuleServiceImpl extends ServiceImpl<SysFillRuleMapper, SysFillRule> implements ISysFillRuleService {
}
|
JavaScript
|
UTF-8
| 410
| 2.53125
| 3
|
[] |
no_license
|
class SlingShot{
constructor(bodyA,bodyB){
var options = {
bodyA: bodyA,
bodyB: bodyB,
stiffness: 0.02,
length: 40
}
this.sling= Constraint.create(options)
World.add(world,this.sling)
}
display(){
strokeWeight(4)
//line(x1,y1,x2,y2)
line(this.sling.bodyA.position.x,this.sling.bodyA.position.y,this.sling.bodyB.position.x,this.sling.bodyB.position.y)
}
}
|
C#
|
UTF-8
| 366
| 2.5625
| 3
|
[] |
no_license
|
using System;
using System.IO;
namespace Lemon2.Command.Commands {
public class PWD : CommandBase {
public PWD() : base("pwd", "prints working directory", "pwd") {}
public override void onCommand(string[] args) {
Console.WriteLine(Directory.GetCurrentDirectory());
}
}
}
|
JavaScript
|
UTF-8
| 1,956
| 3.234375
| 3
|
[] |
no_license
|
'use strict';
(function () {
window.library = {};
window.library.enableElement = function (element) {
element.removeAttribute('disabled');
};
window.library.disableElement = function (element) {
element.setAttribute('disabled', 'disabled');
};
window.library.selectElement = function (element) {
element.setAttribute('selected', 'selected');
};
window.library.disselectElement = function (element) {
element.removeAttribute('selected');
};
window.library.getRandomValue = function (minValue, maxValue) {
var randomValue = maxValue - (maxValue - 1 - minValue) * Math.random();
return Math.round(randomValue);
};
window.library.getRandomArrayElement = function (array) {
var maxValue = array.length - 1;
return array[window.library.getRandomValue(0, maxValue)];
};
window.library.shuffle = function (array) {
for (var i = array.length - 1; i > 0; --i) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[j];
array[j] = array[i];
array[i] = temp;
}
return array;
};
window.library.addListenerTo = function (cssSelector, eventName, eventListener) {
document.querySelector(cssSelector).addEventListener(eventName, eventListener);
};
window.library.removeListenerFrom = function (cssSelector, eventName, eventListener) {
document.querySelector(cssSelector).removeEventListener(eventName, eventListener);
};
window.library.addListenerToDocument = function (eventName, eventListener) {
document.addEventListener(eventName, eventListener);
};
window.library.removeListenerFromDocument = function (eventName, eventListener) {
document.removeEventListener(eventName, eventListener);
};
window.library.addClassToElement = function (element, className) {
element.classList.add(className);
};
window.library.removeClassFromElement = function (element, className) {
element.classList.remove(className);
};
})();
|
Python
|
UTF-8
| 641
| 2.734375
| 3
|
[] |
no_license
|
import sklearn
from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
# USES SKLEARN'S PIPELINE TO MAKE A CONTINOUS SET OF SUCCESSIVELY OCCURING FUNCTIONS, COUNTVECTORIZER() TO TOKENIZE AND BUILD A SET OF VOCABULARY,
#AND TFIDFTRANSFORMER TO CONVERT WORDS TO VECTORS
# USES SKLEARN'S MULTINOMIALNB (MULTINOMIAL NAIVE BAYES) ALGORITHM. MULTINOMIAL JUST MEANS MORE THAN 2 CLASS CLASSIFICATION USING NAIVE BAYES.
text_clf = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('clf', MultinomialNB())])
|
Java
|
UTF-8
| 518
| 1.914063
| 2
|
[] |
no_license
|
package de.xeqo.camcapdemo;
import android.hardware.usb.UsbDevice;
import android.view.View;
import android.view.View.OnClickListener;
final class k implements OnClickListener {
private /* synthetic */ RemoteCaptureActivity a;
k(RemoteCaptureActivity remoteCaptureActivity) {
this.a = remoteCaptureActivity;
}
public final void onClick(View view) {
this.a.c.clear();
for (UsbDevice a : this.a.e.getDeviceList().values()) {
this.a.f.connect(a);
}
}
}
|
PHP
|
UTF-8
| 580
| 3.140625
| 3
|
[] |
no_license
|
<?php
namespace App;
class Race
{
protected $distance;
protected $start;
protected $fleet;
public function distance()
{
return $this->distance;
}
public function setDistance($distance)
{
$this->distance = $distance;
}
public function start()
{
return $this->start;
}
public function setStart($start)
{
$this->start = $start;
}
public function fleet()
{
return $this->fleet;
}
public function setFleet($fleet)
{
$this->fleet = $fleet;
}
}
|
Java
|
UTF-8
| 3,130
| 3.375
| 3
|
[] |
no_license
|
package 大脑.测试;
import java.util.ArrayList;
import java.util.List;
public class 已处理 {
public List<Object> 获取句子对象集(String sentence){
List<String> subStrs= new ArrayList<String>();
for(int star=0;star<sentence.length();star++){
for(int end=star+1;end<=sentence.length();end++){
subStrs.add(sentence.substring(star, end));
}
}
List<Object> things= new ArrayList<Object>();
for(String str:subStrs){
// Object o = ds.find("_id",str);
//利用java-mongodb-driver 查询 "_id":str 这条记录的className属性值,然后根据这个值,实例化这个对象
// things.add(object);
}
return things;
}
public List<String> 获取句子方法(String sentence){
//这个sentence可能需要把在 “获取句子对象集” 方法中确定的对象 排除.
List<String> subStrs= new ArrayList<String>();
for(int star=0;star<sentence.length();star++){
for(int end=star+1;end<=sentence.length();end++){
subStrs.add(sentence.substring(star, end));
}
}
List<String> actions= new ArrayList<String>();
/**
* 两种思路:1.遍历每一个句子对象集中的对象,获取他们的所有方法,看是否有方法名与句子中排除对象名之后剩下的字符串相同。若有,则调用.
* 2. 对剩余字符串进行完全遍历拆分,并对每一个拆分的子字符串对对象进行反射调用,若不报错,则调用.调用时传入参数。
* ps:在对排出了对象名和方法名之后的剩余字符串,进行有用信息提取,排除掉无用字符串. 其实无用字符串有用,可以根据这些字符串判断心情等. 设计脏话排除算法,无用信息排除算法.
* 重点:1. 遵循无用字符串最少原则
* 2.重写文件时,读取文件,在文件后面加上方法和属性即可.
*/
for(String str:subStrs){
//Object o = ds.find("_id",str);
//利用java-mongodb-driver 查询 "_id":str 这条记录的className属性值,然后根据这个值,实例化这个对象
//things.add(object);
}
return actions;
}
//添加到类集中的各类中
public void how (Object whose, Object what, String...newValue){
//这是每一个类中方法的模板:
//方法拥有者为 who,所以连起来就是: who 把 whose what 改为 newValue -by- how。 如果what 为空,则需要根据一个newValue去数据库中寻找对应类并实例化,从而获得what。例如:
//我把他打瞎了。可以根据 瞎这个属性,找到数据库中属于 眼睛 这个类,所以可以获得眼睛这个对象。
}
}
|
C#
|
UTF-8
| 2,467
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using Musoq.Schema.DataSources;
namespace Musoq.Schema.Time
{
public static class TimeHelper
{
public static readonly IDictionary<string, int> TimeNameToIndexMap;
public static readonly IDictionary<int, Func<DateTimeOffset, object>> TimeIndexToMethodAccessMap;
public static readonly ISchemaColumn[] TimeColumns;
static TimeHelper()
{
TimeNameToIndexMap = new Dictionary<string, int>
{
{"DateTime", 0},
{nameof(DateTimeOffset.Second), 1},
{nameof(DateTimeOffset.Minute), 2},
{nameof(DateTimeOffset.Hour), 3},
{nameof(DateTimeOffset.Day), 4},
{nameof(DateTimeOffset.Month), 5},
{nameof(DateTimeOffset.Year), 6},
{nameof(DateTimeOffset.DayOfWeek), 7},
{nameof(DateTimeOffset.DayOfYear), 8},
{nameof(DateTimeOffset.TimeOfDay), 9}
};
TimeIndexToMethodAccessMap = new Dictionary<int, Func<DateTimeOffset, object>>
{
{0, date => date},
{1, date => date.Second},
{2, date => date.Minute},
{3, date => date.Hour},
{4, date => date.Day},
{5, date => date.Month},
{6, date => date.Year},
{7, date => (int) date.DayOfWeek},
{8, date => date.DayOfYear},
{9, date => date.TimeOfDay}
};
TimeColumns = new ISchemaColumn[]
{
new SchemaColumn("DateTime", 0, typeof(DateTimeOffset)),
new SchemaColumn(nameof(DateTimeOffset.Second), 1, typeof(int)),
new SchemaColumn(nameof(DateTimeOffset.Minute), 2, typeof(int)),
new SchemaColumn(nameof(DateTimeOffset.Hour), 3, typeof(int)),
new SchemaColumn(nameof(DateTimeOffset.Day), 4, typeof(int)),
new SchemaColumn(nameof(DateTimeOffset.Month), 5, typeof(int)),
new SchemaColumn(nameof(DateTimeOffset.Year), 6, typeof(int)),
new SchemaColumn(nameof(DateTimeOffset.DayOfWeek), 7, typeof(int)),
new SchemaColumn(nameof(DateTimeOffset.DayOfYear), 8, typeof(int)),
new SchemaColumn(nameof(DateTimeOffset.TimeOfDay), 9, typeof(TimeSpan))
};
}
}
}
|
C++
|
UTF-8
| 670
| 3.1875
| 3
|
[] |
no_license
|
#ifndef EXE_22
#define EXE_22
#include <string>
class Person
{
friend std::istream& read(std::istream&, Person&);
friend std::ostream& print(std::ostream&, const Person&);
private:
std::string _name;
std::string _address;
public:
std::string getName() const { return name; }
std::string getAddr() const { return address; }
Person() = default;
Person(const std::string &name, const std::string &address) :
_name(name), _address(address) { }
Person(std::istream &is)
{
read(is, *this);
}
};
std::istream& read(std::istream&, Person&);
std::ostream& print(std::ostream&, const Person&);
#endif // EXE_22
|
Java
|
UTF-8
| 6,250
| 2.359375
| 2
|
[] |
no_license
|
package com.iva.model;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.apache.commons.lang3.StringUtils;
@Entity(name="ivvtasgu")
public class Ventas{
@Id
private Integer id;
/*REPLICO ELEMENTOS ORIGINALES DEL SISTEMA VIEJO, SIN CAMBIAR NOMBRES*/
private Integer feccom;//Representa nro de didas desde la fecha 1800-12-28 ( Clarion :| ) , convertido en date.
private String tipcom; // FC o Z
private String letra; // A, B
private Integer nroloc; //punto de venta
private Integer nrocom; //nro comprobante
private Integer codpcli;
private String razsoc;
private String domcom;
private String tipiva;
private String nrcuit;
private Integer codint;
private Float impgra;
private Float impgra1;
private Float impgra2;
private Float impexe;
private Float impper;
private Float impiv1;
private Float impiv2;
private Float impiv3;
private Float impiv4;
private Float impiv5;
private Float impiv6;
private Float impiin;
private Float imptot;
private String nrohas;
private Integer mesano; //Se usa para buscar, se llama mesano, pero la informacion esta guardada en la base como anomes :)
private Float impv3;
private Float impv4;
private Float impv5;
private Float impv6;
private Date fecha;
public Float getTotalImpGravados() {
return impgra + impgra1 + impgra2;
}
public Float getTotalImpIVA() {
return impiv1 + impiv2 + impiv3 + impiv4 + impiv5 + impiv6;
}
public String getComprobante() {
return tipcom + "." + letra + StringUtils.leftPad(nroloc.toString(), 4, "0") + " " + StringUtils.leftPad(nrocom.toString(), 8,"0");
}
public String getTipoComprador() {
if (this.tipiva.equals("1"))
return "99";
//CUIT
return "80";
}
public String getTipoComprobante() {
/*
Letra A = 001
Letra B:
Pto de venta :2 -> 006
Pto de venta :4 -> 082
* */
if (this.letra.toUpperCase().equals("A"))
return "001";
else {
if (this.nroloc == 2)
return "006";
else
return "082";
}
}
public String getFechaArchivo() {
return new SimpleDateFormat("yyyyMMdd"). format(this.fecha);
}
//--GETTERS Y SETTERS
public Integer getFeccom() {
return feccom;
}
public void setFeccom(Integer feccom) {
this.feccom = feccom;
}
public String getTipcom() {
return tipcom;
}
public void setTipcom(String tipcom) {
this.tipcom = tipcom;
}
public String getLetra() {
return letra;
}
public void setLetra(String letra) {
this.letra = letra;
}
public Integer getNroloc() {
return nroloc;
}
public void setNroloc(Integer nroloc) {
this.nroloc = nroloc;
}
public Integer getNrocom() {
return nrocom;
}
public void setNrocom(Integer nrocom) {
this.nrocom = nrocom;
}
public Integer getCodpcli() {
return codpcli;
}
public void setCodpcli(Integer codpcli) {
this.codpcli = codpcli;
}
public String getRazsoc() {
return razsoc;
}
public void setRazsoc(String razsoc) {
this.razsoc = razsoc;
}
public String getDomcom() {
return domcom;
}
public void setDomcom(String domcom) {
this.domcom = domcom;
}
public String getTipiva() {
return tipiva;
}
public void setTipiva(String tipiva) {
this.tipiva = tipiva;
}
public String getNrcuit() {
return nrcuit;
}
public void setNrcuit(String nrcuit) {
this.nrcuit = nrcuit;
}
public Integer getCodint() {
return codint;
}
public void setCodint(Integer codint) {
this.codint = codint;
}
public Float getImpgra() {
return impgra;
}
public void setImpgra(Float impgra) {
this.impgra = impgra;
}
public Float getImpgra1() {
return impgra1;
}
public void setImpgra1(Float impgra1) {
this.impgra1 = impgra1;
}
public Float getImpgra2() {
return impgra2;
}
public void setImpgra2(Float impgra2) {
this.impgra2 = impgra2;
}
public Float getImpexe() {
return impexe;
}
public void setImpexe(Float impexe) {
this.impexe = impexe;
}
public Float getImpper() {
return impper;
}
public void setImpper(Float impper) {
this.impper = impper;
}
public Float getImpiv1() {
return impiv1;
}
public void setImpiv1(Float impiv1) {
this.impiv1 = impiv1;
}
public Float getImpiv2() {
return impiv2;
}
public void setImpiv2(Float impiv2) {
this.impiv2 = impiv2;
}
public Float getImpiin() {
return impiin;
}
public void setImpiin(Float impiin) {
this.impiin = impiin;
}
public Float getImptot() {
return imptot;
}
public void setImptot(Float imptotal) {
this.imptot = imptotal;
}
public String getNrohas() {
return nrohas;
}
public void setNrohas(String nrohas) {
this.nrohas = nrohas;
}
public Integer getMesano() {
return mesano;
}
public void setMesano(Integer mesano) {
this.mesano = mesano;
}
public Float getImpv3() {
return impv3;
}
public void setImpv3(Float impv3) {
this.impv3 = impv3;
}
public Float getImpv4() {
return impv4;
}
public void setImpv4(Float impv4) {
this.impv4 = impv4;
}
public Float getImpv5() {
return impv5;
}
public void setImpv5(Float impv5) {
this.impv5 = impv5;
}
public Float getImpv6() {
return impv6;
}
public void setImpv6(Float impv6) {
this.impv6 = impv6;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Float getImpiv3() {
return impiv3;
}
public void setImpiv3(Float impiv3) {
this.impiv3 = impiv3;
}
public Float getImpiv4() {
return impiv4;
}
public void setImpiv4(Float impiv4) {
this.impiv4 = impiv4;
}
public Float getImpiv5() {
return impiv5;
}
public void setImpiv5(Float impiv5) {
this.impiv5 = impiv5;
}
public Float getImpiv6() {
return impiv6;
}
public void setImpiv6(Float impiv6) {
this.impiv6 = impiv6;
}
public String getAlicuotaIVA() {
if (this.impgra * 0.21 == this.impiv1 ) {
return "0005";
} else
return "0004";
}
// private Float floatToDosDecimales(Float number) {
// NumberFormat formatter = NumberFormat.getInstance(Locale.getDefault());
// formatter.setMaximumFractionDigits(2);
// formatter.setMinimumFractionDigits(2);
// return new Float(formatter.format(number));
// }
//
}
|
Python
|
UTF-8
| 1,435
| 2.546875
| 3
|
[] |
no_license
|
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import turtle
>>> wn = turtle.Screen()
>>> tutle.Turtle()
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
tutle.Turtle()
NameError: name 'tutle' is not defined
>>> t1 = turtle.Turtle()
>>> t1 = shape('turtle')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
t1 = shape('turtle')
NameError: name 'shape' is not defined
>>> t1.shaple("turlte")
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
t1.shaple("turlte")
AttributeError: 'Turtle' object has no attribute 'shaple'
>>> t1.shape("turtle")
>>> wn.addshape("C:\Users\maple\Desktop\학교관련\컴사문\computing\99")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>> wn.addshape(99)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
wn.addshape(99)
File "C:\Users\maple\AppData\Local\Programs\Python\Python36-32\lib\turtle.py", line 1132, in register_shape
if name.lower().endswith(".gif"):
AttributeError: 'int' object has no attribute 'lower'
>>> wn.addshape("C:\\Users\\maple\\Desktop\\학교관련\\gg.gif")
>>> t1.shape("C:\\Users\\maple\\Desktop\\학교관련\\gg.gif")
>>>
|
Markdown
|
UTF-8
| 4,682
| 3.09375
| 3
|
[
"MIT",
"CC-BY-4.0"
] |
permissive
|
---
title: Use the HoloLens clicker
description: This article outlines how to use the HoloLens clicker, including clicker pairing, charging, and recovery.
ms.assetid: 7d4a30fd-cf1d-4c9a-8eb1-1968ccecbe59
ms.date: 09/16/2019
manager: jarrettr
keywords: hololens
ms.prod: hololens
ms.sitesec: library
author: v-miegge
ms.author: v-miegge
ms.topic: article
ms.localizationpriority: high
appliesto:
- HoloLens (1st gen)
---
# Use the HoloLens (1st gen) clicker
The clicker was designed specifically for HoloLens (1st gen) and gives you another way to interact with holograms. It comes with HoloLens (1st gen), in a separate box.
Use it in place of hand gestures to select, scroll, move, and resize apps.
## Clicker hardware and pairing
The HoloLens (1st gen) clicker has a finger loop to make it easier to hold, and an indicator light.

### Clicker indicator lights
Here's what the lights on the clicker mean.
- **Blinking white**. The clicker is in pairing mode.
- **Fast-blinking white**. Pairing was successful.
- **Solid white**. The clicker is charging.
- **Blinking amber**. The battery is low.
- **Solid amber**. The clicker ran into an error and you'll need to restart it. While pressing the pairing button, click and hold for 15 seconds.
### Pair the clicker with your HoloLens (1st gen)
1. Use the bloom gesture to go to **Start**, then select **Settings** > **Devices** and verify that Bluetooth is on.
1. On the clicker, press and hold the pairing button until the status light blinks white.
1. On the pairing screen, select **Clicker** > **Pair**.
### Charge the clicker
When the clicker battery is low, the battery indicator will blink amber. Plug the Micro USB cable into a USB power supply to charge the device.
## Use the clicker with HoloLens (1st gen)
### Hold the clicker
To put on the clicker, slide the loop over your ring or middle finger so that the Micro USB port faces toward your wrist. Rest your thumb in the indentation.

### Clicker gestures
Clicker gestures are small wrist rotations, not the larger movements used for HoloLens hand gestures. And HoloLens recognizes your gestures and clicks even if the clicker is outside the [gesture frame](hololens1-basic-usage.md), so you can hold the clicker in the position that's most comfortable for you.
- **Select**. To select a hologram, button, or other element, gaze at it, then click.
- **Click and hold**. Click and hold your thumb down on the button to do some of the same things you would with tap and hold, such as move or resize a hologram.
- **Scroll**. On the app bar, select **Scroll Tool**. Click and hold, then rotate the clicker up, down, left, or right. To scroll faster, move your hand farther from the center of the scroll tool.
- **Zoom**. On the app bar, select **Zoom Tool**. Click and hold, then rotate the clicker up to zoom in, or down to zoom out.
> [!TIP]
> To zoom in or out when using Microsoft Edge, gaze at a page and double-click.
## Restart or recover the clicker
Here are some things to try if the HoloLens clicker is unresponsive or isn’t working well.
### Restart the clicker
Use the tip of a pen to press and hold the pairing button. At the same time, click and hold the clicker for 15 seconds. If the clicker was already paired with your HoloLens, it will stay paired after it restarts.
If the clicker won't turn on or restart, try charging it by using the HoloLens charger. If the battery is very low, it might take a few minutes for the white indicator light to turn on.
### Re-pair the clicker
Select **Settings** > **Devices** and select the clicker. Select **Remove**, wait a few seconds, then pair the clicker again.
### Recover the clicker
If restarting and re-pairing the clicker don’t fix the problem, the Windows Device Recovery Tool can help you recover it. The recovery process may take some time, and it will install the latest version of the clicker software. To use the tool, you’ll need a computer running Windows 10 or later that has at least 4 GB of free storage space.
To recover the clicker:
1. Download and install the [Windows Device Recovery Tool](https://dev.azure.com/ContentIdea/ContentIdea/_queries/query/8a004dbe-73f8-4a32-94bc-368fc2f2a895/) on your computer.
1. Connect the clicker to your computer by using the Micro USB cable that came with your HoloLens.
1. Run the Windows Device Recovery Tool and follow the instructions.
If the clicker isn’t automatically detected, select **My device was not detected** and follow the instructions to put your device into recovery mode.
|
Python
|
UTF-8
| 6,168
| 3.203125
| 3
|
[] |
no_license
|
#bfs求解算法
import numpy as np
import math
class node:
def __init__(self, x=0, y=0, t=0):
self.x = x
self.y = y
self.t = t # t表示走到这个格子用的步数
class father:
def __init__(self, x=0, y=0, cz=[]):
self.x = x # 当前格子的父节点坐标
self.y = y
self.cz = cz # 由什么操作到达的这个格子,D,R,L,U
def bfs(s_point,e_point,mmap,mode):
lj = []
for i in range(0, 46):
lj += [[]]
for j in range(0, 85):
lj[i] += [father()] # 第i个元素是空列表,添加完以后每个第i元素都有十个father类的对象
x1 = s_point[0]
y1 = s_point[1]
x2 = e_point[0]
y2 = e_point[1]
# vis = [[False]*10]*10
vis = []
for i in range(0, 46):
vis += [[]]
for j in range(0, 85): # 10这个数大了,只不过没关系,vis与mmap是分开的
vis[i] += [0] # 先初始化为全部没访问过
xx = [1,0,0,-1] # 右、下、左、上
yy = [0,1,-1,0]
q = []
s = node()
f = node()
n = 44
m = 80
s.x = x1
s.y = y1
s.t = 0 ##规定起点和终点的
f.x = x2 ##f是终点,s是起点
f.y = y2
q.append(s) # q这个空列表存储的是node类型的对象
lj[s.x][s.y].x = 1000
lj[s.x][s.y].y = 1000
lj[s.x][s.y].cz = 0
vis[x1][y1] = 0 # 起始点标为已经访问过
# print("vis={}".format(vis))
while q: # 只要q中有值,就继续循环
now = q[0]
q.pop(0) #删去最q列表开始的元素
for i in range(0, 4): # 为何是4,上下左右xx,yy
new = node()
new.x = now.x + xx[i]
if(new.x == -1):
continue
new.y = now.y + yy[i]
if (new.y == -1):
continue
new.t = now.t + 1
# print("i={} new.x={} new.y={} now.x={} now.y={}".format(i, new.x, new.y, now.x, now.y))
# print("new.x ={} new.y={} n={} m={} vis[new.x][new.y]={} mmap[new.x][new.y]={}".format(new.x, new.y, n, m, vis[new.x][new.y], mmap[new.x][new.y]))
if ((new.x < 0 or new.y < 0 or new.x >= n or new.y >= m or vis[new.x][new.y] != 0 or mmap[new.x][new.y]) == 1): # 下标越界或者访问过(vis)或者是障碍物
continue
q.append(new)# 新的点被加进q去
lj[new.x][new.y].x = now.x # 新点取代旧点成为new,此点是坐标不是+-1
lj[new.x][new.y].y = now.y
if i == 0:
lj[new.x][new.y].cz = 'D'
elif i == 1:
lj[new.x][new.y].cz = 'R'
elif i == 2:
lj[new.x][new.y].cz = 'L'
elif i == 3:
lj[new.x][new.y].cz = 'U'
vis[new.x][new.y] = new.t # 走过的路变为1
if(mode == 1):
if(mmap[new.x][new.y] == 0):
return new.t, lj,[new.x,new.y]
# print("value={} ({},{}) {}\n".format(mmap[new.x][new.y], new.x, new.y, lj[new.x][new.y].cz))
# print("=============================================================")
if(mode == 0):
if new.x == f.x and new.y == f.y:
return new.t,lj,[new.x,new.y] # 到达终点
if(mode == 2 ):
if(mmap[new.x][new.y] == 2):
return new.t, lj,[new.x,new.y]
return False
class map:
def __init__(self):
self.mmap = np.zeros([44, 80])
self.cost_map = np.zeros([44, 80])
self.RP=[0,0,0,0,0,0]
self.way_lj = [] # 路径记载
self.dir_lj = [] # 方向记载
self.lj = []
def reflashmap(self):
obst = np.zeros([44, 80])
obst[10:12, 0:10] = 1
obst[21:24, 15:23] = 1
obst[34:44, 15:17] = 1
obst[9:12, 35:46] = 1
obst[33:36, 35:46] = 1
obst[21:24, 57:66] = 1
obst[0:10, 63:66] = 1
obst[32:35, 70:80] = 1
obst[20:24, 38:42] = 1
if self.RP[0] == 1:
obst[15:20, 3:8] = 1
if self.RP[1] == 1:
obst[26:31, 17:22] = 1
if self.RP[2] == 1:
obst[38:43, 38:44] = 1
if self.RP[3] == 1:
obst[3:7, 38:44] = 1
if self.RP[4] == 1:
obst[15:20, 60:65] = 1
if self.RP[5] == 1:
obst[26:31, 74:79] = 1
self.mmap = obst
return
def dfs(self,x1,y1,x,y):
if x == x1 and y == y1:
return
else:
self.dfs(x1,y1,self.lj[x][y].x,self.lj[x][y].y)
# print(lj[x][y].cz)
self.way_lj.append((self.lj[x][y].x,self.lj[x][y].y))
self.dir_lj.append(self.lj[x][y].cz)
def planning(self,s_point,e_point):
if(s_point == e_point):
return s_point
self.way_lj = [] # 路径记载
self.dir_lj = [] # 方向记载
mypath = []
for i in range(0, 46):
self.lj += [[]]
for j in range(0, 85):
self.lj[i] += [father()] # 第i个元素是空列表,添加完以后每个第i元素都有十个father类的对象
ans,self.lj,point= bfs(s_point,e_point,self.mmap,0)
x1 = s_point[0]
y1 = s_point[1]
x2 = e_point[0]
y2 = e_point[1]
if ans == False:
print("error")
else:
#print("起点{},终点{},需要行走{}步".format((x1, y1), (x2, y2), ans))
self.dfs(x1=x1,y1=y1,x=x2,y=y2)
self.way_lj.append((x2, y2))
mypath.append(self.way_lj[0])
for i in range(ans):
if(ans<10):
mypath.append(self.way_lj[i])
if(10<ans<=40):
if ((i + 1) % 3 == 0):
mypath.append(self.way_lj[i])
if(ans > 40):
if((i+1)%5==0):
mypath.append(self.way_lj[i])
mypath.append(self.way_lj[ans])
#print("行走经过{}".format(way_lj))
#print("地图行走方式{}".format(dir_lj))
return mypath
|
Shell
|
UTF-8
| 833
| 3.96875
| 4
|
[] |
no_license
|
#!/usr/bin/env bash
set -Eeu
git fetch --all
git pull
# Generate and iterate over an array of submodule names.
submodule_list_string="$(git config --file .gitmodules --get-regexp path | awk '{ print $2 }')"
IFS=$'\n' read -d '' -ra submodule_list_array <<< "${submodule_list_string}" || true
root_folder="${PWD}"
for submodule_name in "${submodule_list_array[@]}"; do
cd "${submodule_name}"
echo ">>> ${submodule_name}"
submodule_declared_branch="$(cd .. && git config -f .gitmodules submodule.${submodule_name}.branch)"
submodule_actual_branch="$(git symbolic-ref --short HEAD)"
# Test for a branch name match.
if [ "${submodule_declared_branch}" != "${submodule_actual_branch}" ]; then
continue
fi
git stash || true
git pull
git stash pop || true
cd "${root_folder}"
done
|
Markdown
|
UTF-8
| 1,493
| 3.109375
| 3
|
[] |
no_license
|
# BIM-chain
## Blockchain & Tokens
TBD
- [ ] Property token
- [ ] Possession token
## Data layer exercises
The following is a short excercise on how to put data onto ipfs and retrieve it again.
The idea is to put the reference (ipfs hash) to this data somewhere onto the blockchain and given that reference, retrieve the data from anywhere.
Precondition (installation instructions for ubuntu):
* ipfs (data layer technology) installed & running. `sudo snap install ipfs && ipfs init && ipfs daemon`
* jq (data extraction tool for JSON) installed. `sudo apt install jq`
## prepare, publish data & save reference hash
> split 5 objects and save the first in data.json
1. `jq '.[0]' test/mocks/5objects.json > data.json`
> add the data to ipfs, which returns a hash to retrieve the data from the network later, (which we will save in a database/blockchain)
2. `ipfs add data.json`
> save the reference that was output (Qme... is the format of your ipfs hash)
3. `echo Qme5GawkhEceihJYYccGPvK5MzatwcAifa85qhNmMowcb2 > ref`
## prepare, publish data & save reference hash (alternative command)
> Alternatively you can do 1, 2 & 3 in 1 command like this:
1. `jq '.[0]' test/mocks/5objects.json | ipfs add - | awk '{ print $NF }' > ref`
## fetch data & extract a value
> get the data from data layer back, e.g. cpi property
1. ```ipfs cat `cat ref` | jq '.cpi'```
## download data from ipfs
```bash
ipfs deamon
ipfs cat Qme5GawkhEceihJYYccGPvK5MzatwcAifa85qhNmMowcb2 > data/block1.json
```
|
Python
|
UTF-8
| 1,402
| 3.515625
| 4
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
step05_ver1x_ver2.py
ver1.x -> ver2.x
''' step08_variable_feed_csv.py -> ver2.0
1. 즉시 실행
2. 세션 대신 함수
3. @tf.function 함수 장식
'''
"""
import tensorflow as tf
import pandas as pd # csv file read
from sklearn.model_selection import train_test_split # data split
path = "C:/ITWILL/6_Tensorflow/data"
iris = pd.read_csv(path + "/iris.csv")
iris.columns = iris.columns.str.replace(".", "_")
iris.info()
# 1단계. 공급 data 생성 : DataFrame
cols = list(iris.columns)
x_data = iris[cols[:4]]
y_data = iris[cols[-1]]
x_data.shape # (150, 4)
y_data.shape # (150,)
# 3단계. train / test split
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size = 0.3)
x_train.shape # (105, 4)
x_test.shape # (45, 4)
# 4단계. session object : data 공급 -> 변수
# 훈련용 data 공급
import numpy as np
X_val = tf.constant(np.array(x_data))
Y_val = tf.constant(np.array(y_data))
print(X_val.numpy())
print(Y_val.numpy())
# 평가용 data 공급
X_val2 = tf.constant(np.array(x_test))
Y_val2 = tf.constant(y_test)
print(X_val2.numpy())
print(Y_val2.numpy())
print(Y_val2.numpy().shape) # (45,)
print(type(Y_val2.numpy())) # <class 'numpy.ndarray'>
# numpy -> pandas 변경
X_df = pd.DataFrame(X_val2.numpy())
print(X_df.info())
print(X_df.mean(axis = 0))
Y_ser = pd.Series(Y_val2.numpy())
print(Y_ser.value_counts())
|
Shell
|
UTF-8
| 290
| 3.078125
| 3
|
[] |
no_license
|
#!/bin/bash
set -e
set -x
set -o pipefail
RPMROOT=${HOME}/rpmbuild
WEBROOT=/var/www/html/pub
# direcry check
[ -d ${WEBROOT} ] || sudo mkdir -p ${WEBROOT}
# RPM Package Copy
cd ${RPMROOT}/RPMS/
pwd
sudo rsync -avx . ${WEBROOT}/
# make yum repositry
cd ${WEBROOT}
pwd
sudo createrepo .
|
Java
|
UTF-8
| 1,741
| 2.8125
| 3
|
[] |
no_license
|
/**
* VM Args: -verbose:gc
*/
public class ByteCodeEngine {
public static void main(String[] args) {
/**
* [GC (System.gc()) 70745K->66272K(249344K), 0.0161803 secs]
[Full GC (System.gc()) 66272K->66186K(249344K), 0.0197580 secs]
* @param args
*/
// byte[] placeholder = new byte[64 * 1024 * 1024];
// System.gc();
/**
* 作用域限制在括号内,依然无法回收
* 原因:局部变量表中的Slot是否还存有关于placeholder数组对象的引用。
* 代码虽然离开了作用域,但是在此后无任何对局部变量表的读写操作。
* placeholder所占用的Slot还未被其他变量所复用,所以作为GC Roots的一部分的
* 局部变量表仍然保持着对它的关联
* [GC (System.gc()) 70745K->66320K(249344K), 0.0009649 secs]
[Full GC (System.gc()) 66320K->66186K(249344K), 0.0046755 secs]
*/
// {
// byte[] placeholder = new byte[64 * 1024 * 1024];
//
// //“奇技”能使垃圾收集起作用,不使用的对象应手动赋值null
// //但不推荐作为编码规则,应以恰当变量作用域来控制变量回收时间才是最优雅的解决办法
//// placeholder = null; //可能JIT编译会被优化消除掉
// }
// System.gc();
/**
* 此次内存被回收
* [GC (System.gc()) 70745K->66288K(249344K), 0.0009181 secs]
[Full GC (System.gc()) 66288K->650K(249344K), 0.0052574 secs]
*/
// {
// byte[] placeholder = new byte[64 * 1024 * 1024];
// }
// int a = 0;
// System.gc();
}
}
|
C++
|
UTF-8
| 3,492
| 3.734375
| 4
|
[] |
no_license
|
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
//class Vector;
class Matrix
{
protected:
int m_rows;
int m_cols;
double** m_matrix;
public:
//! wrap operator [i][j], it has the same speed as (,) or direct access !
// When you have a decent compiler and if you judiciously use inlining, the compiler should optimize away the TEMPORARY objects.
// In other words, the operator[]-approach above will hopefully not be slower than what it would have been if you had directly called Matrix::operator()( row, col) in the first place. Of course you could have made your life simpler and avoided most of the above work by directly calling Matrix::operator()( row, col) in the first place.
// So you might as well directly call Matrix::operator()( row, col) in the first place.
class Row
{
public:
Matrix & m_matrix;
int m_row;
Row(Matrix & matrix, int row): m_matrix(matrix), m_row(row){};
double& operator [] (int col) {return m_matrix(m_row,col);}
};
Row operator [](int row)
{
return Row(*this,row);
}
////! const version (TODO, not very clear for me ... )
class ConstRow
{
public:
Matrix const & m_matrix;
int m_row;
ConstRow(Matrix const & matrix, int row): m_matrix(matrix), m_row(row){};
double operator [] (int col) const {return m_matrix(m_row,col);}
};
ConstRow operator [](int row) const
{
return ConstRow(*this,row);
}
//! ---- ---- ---- ---- Matrix ---- ---- ---- ----
//! constructor
Matrix(int rows, int cols, double val = 0); // creat a matrix, each element is zeros
Matrix(double** matrix, int rows, int cols);
Matrix(int rows, int cols, std::string & matrix_type); // generate special type of matrix ...
Matrix(vector<double> & x, bool if_column_matrix);
//! copy constructor and assignment constructor (no pointer attribute, use the default copy/assignement constructor)
Matrix(const Matrix& m);
Matrix& operator = (const Matrix& m);
//! destructor
virtual ~Matrix();
//! get functions ...
int rows() const;
int cols() const;
double** get_matrix();
//! functionalilities
double& operator()(int i, int j);
double operator()(int i, int j) const;
Matrix operator+ (const Matrix& m) const;
Matrix operator- (const Matrix& m) const;
void operator+=(const Matrix& m);
void operator-=(const Matrix& m);
Matrix operator*(const Matrix& m) const;
//Vector operator*(Vector& m);
Matrix operator~() const; // transpose a matrix ...
//! operation with scalar ...
void operator+=( double val );
void operator-=( double val );
void operator*=( double val );
void operator/=( double val );
void set_element_to_value(double v);
//! ---- ---- ---- ---- Square Matrix ---- ---- ---- ----
bool if_square_matrix() const;
double determinant__(double ** m, int n) const;
double determinant() const;
Matrix inverse() const;
vector<double> eigenvalues() const;
//! ---- ---- ---- ---- Symetric Matrix ---- ---- ---- ----
bool if_symetric_matrix() const;
Matrix Cholesky(Matrix& m_op) const;
//! ---- ---- ---- ---- Vector ---- ---- ---- ----
bool if_row_vector() const;
bool if_col_vector() const;
double inner_product(const Matrix& v) const; // about two column vectors
//! print
void print(std::string matrix_name = "");
};
//! TODO:
// to give a structure of the Matrix --> square matrix --> symetric matrix
// ans symetric matrix can be saved using half memeory ...
|
Java
|
UTF-8
| 25,111
| 2
| 2
|
[] |
no_license
|
/*******************************************************************************
* Copyright (c) 2004, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.swt.tools.internal;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Iterator;
public class NativesGenerator extends JNIGenerator {
boolean enterExitMacro;
public NativesGenerator() {
enterExitMacro = true;
}
public void generateCopyright() {
generateMetaData("swt_copyright");
}
public void generateIncludes() {
String outputName = getOutputName();
outputln("#include \"swt.h\"");
output("#include \"");
output(outputName);
outputln("_structs.h\"");
output("#include \"");
output(outputName);
outputln("_stats.h\"");
outputln();
}
public void generate(JNIClass clazz, String methodName) {
JNIMethod[] methods = clazz.getDeclaredMethods();
int count = 0;
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().startsWith(methodName)) count++;
}
JNIMethod[] result = new JNIMethod[count];
count = 0;
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().startsWith(methodName)) result[count++] = methods[i];
}
generate(result);
}
public void generate(JNIClass clazz) {
JNIMethod[] methods = clazz.getDeclaredMethods();
int i = 0;
for (; i < methods.length; i++) {
JNIMethod method = methods[i];
if ((method.getModifiers() & Modifier.NATIVE) != 0) break;
}
if (i == methods.length) return;
sort(methods);
generateNativeMacro(clazz);
generateExcludes(methods);
generate(methods);
}
public void generate(JNIMethod[] methods) {
sort(methods);
for (int i = 0; i < methods.length; i++) {
JNIMethod method = methods[i];
if ((method.getModifiers() & Modifier.NATIVE) == 0) continue;
generate(method);
if (progress != null) progress.step();
}
}
public void generate(JNIMethod method) {
if (method.getFlag(FLAG_NO_GEN)) return;
JNIType returnType = method.getReturnType(), returnType64 = method.getReturnType64();
if (!(returnType.isType("void") || returnType.isPrimitive() || isSystemClass(returnType) || returnType.isType("java.lang.String"))) {
output("Warning: bad return type. :");
outputln(method.toString());
return;
}
JNIParameter[] params = method.getParameters();
String function = getFunctionName(method), function64 = getFunctionName(method, method.getParameterTypes64());
generateSourceStart(function, function64);
boolean sameFunction = function.equals(function64);
if (!sameFunction) {
output("#ifndef ");
output(JNI64);
outputln();
}
if (isCPP) {
output("extern \"C\" ");
generateFunctionPrototype(method, function, params, returnType, returnType64, true);
outputln(";");
}
generateFunctionPrototype(method, function, params, returnType, returnType64, !sameFunction);
if (!function.equals(function64)) {
outputln();
outputln("#else");
if (isCPP) {
output("extern \"C\" ");
generateFunctionPrototype(method, function64, params, returnType, returnType64, true);
outputln(";");
}
generateFunctionPrototype(method, function64, params, returnType, returnType64, !sameFunction);
outputln();
outputln("#endif");
}
generateFunctionBody(method, function, function64, params, returnType, returnType64);
generateSourceEnd(function);
outputln();
}
public void setEnterExitMacro(boolean enterExitMacro) {
this.enterExitMacro = enterExitMacro;
}
void generateExcludes(JNIMethod[] methods) {
HashSet excludes = new HashSet();
for (int i = 0; i < methods.length; i++) {
JNIMethod method = methods[i];
if ((method.getModifiers() & Modifier.NATIVE) == 0) continue;
String exclude = method.getExclude();
if (exclude.length() != 0) {
excludes.add(exclude);
}
}
for (Iterator iter = excludes.iterator(); iter.hasNext();) {
String exclude = (String)iter.next();
outputln(exclude);
for (int i = 0; i < methods.length; i++) {
JNIMethod method = methods[i];
if ((method.getModifiers() & Modifier.NATIVE) == 0) continue;
String methodExclude = method.getExclude();
if (exclude.equals(methodExclude)) {
output("#define NO_");
outputln(getFunctionName(method));
}
}
outputln("#endif");
outputln();
}
}
void generateNativeMacro(JNIClass clazz) {
output("#define ");
output(clazz.getSimpleName());
output("_NATIVE(func) Java_");
output(toC(clazz.getName()));
outputln("_##func");
outputln();
}
boolean generateGetParameter(JNIMethod method, JNIParameter param, boolean critical, int indent) {
JNIType paramType = param.getType(), paramType64 = param.getType64();
if (paramType.isPrimitive() || isSystemClass(paramType)) return false;
String iStr = String.valueOf(param.getParameter());
for (int j = 0; j < indent; j++) output("\t");
output("if (arg");
output(iStr);
output(") if ((lparg");
output(iStr);
output(" = ");
if (paramType.isArray()) {
JNIType componentType = paramType.getComponentType();
if (componentType.isPrimitive()) {
if (critical) {
if (isCPP) {
output("(");
output(componentType.getTypeSignature2(!paramType.equals(paramType64)));
output("*)");
output("env->GetPrimitiveArrayCritical(arg");
} else {
output("(*env)->GetPrimitiveArrayCritical(env, arg");
}
output(iStr);
output(", NULL)");
} else {
if (isCPP) {
output("env->Get");
} else {
output("(*env)->Get");
}
output(componentType.getTypeSignature1(!paramType.equals(paramType64)));
if (isCPP) {
output("ArrayElements(arg");
} else {
output("ArrayElements(env, arg");
}
output(iStr);
output(", NULL)");
}
} else {
throw new Error("not done");
}
} else if (paramType.isType("java.lang.String")) {
if (param.getFlag(FLAG_UNICODE)) {
if (isCPP) {
output("env->GetStringChars(arg");
} else {
output("(*env)->GetStringChars(env, arg");
}
output(iStr);
output(", NULL)");
} else {
if (isCPP) {
output("env->GetStringUTFChars(arg");
} else {
output("(*env)->GetStringUTFChars(env, arg");
}
output(iStr);
output(", NULL)");
}
} else {
if (param.getFlag(FLAG_NO_IN)) {
output("&_arg");
output(iStr);
} else {
output("get");
output(paramType.getSimpleName());
output("Fields(env, arg");
output(iStr);
output(", &_arg");
output(iStr);
output(")");
}
}
outputln(") == NULL) goto fail;");
return true;
}
void generateSetParameter(JNIParameter param, boolean critical) {
JNIType paramType = param.getType(), paramType64 = param.getType64();
if (paramType.isPrimitive() || isSystemClass(paramType)) return;
String iStr = String.valueOf(param.getParameter());
if (paramType.isArray()) {
output("\tif (arg");
output(iStr);
output(" && lparg");
output(iStr);
output(") ");
JNIType componentType = paramType.getComponentType();
if (componentType.isPrimitive()) {
if (critical) {
if (isCPP) {
output("env->ReleasePrimitiveArrayCritical(arg");
} else {
output("(*env)->ReleasePrimitiveArrayCritical(env, arg");
}
output(iStr);
} else {
if (isCPP) {
output("env->Release");
} else {
output("(*env)->Release");
}
output(componentType.getTypeSignature1(!paramType.equals(paramType64)));
if (isCPP) {
output("ArrayElements(arg");
} else {
output("ArrayElements(env, arg");
}
output(iStr);
}
output(", lparg");
output(iStr);
output(", ");
if (param.getFlag(FLAG_NO_OUT)) {
output("JNI_ABORT");
} else {
output("0");
}
output(");");
} else {
throw new Error("not done");
}
outputln();
} else if (paramType.isType("java.lang.String")) {
output("\tif (arg");
output(iStr);
output(" && lparg");
output(iStr);
output(") ");
if (param.getFlag(FLAG_UNICODE)) {
if (isCPP) {
output("env->ReleaseStringChars(arg");
} else {
output("(*env)->ReleaseStringChars(env, arg");
}
} else {
if (isCPP) {
output("env->ReleaseStringUTFChars(arg");
} else {
output("(*env)->ReleaseStringUTFChars(env, arg");
}
}
output(iStr);
output(", lparg");
output(iStr);
outputln(");");
} else {
if (!param.getFlag(FLAG_NO_OUT)) {
output("\tif (arg");
output(iStr);
output(" && lparg");
output(iStr);
output(") ");
output("set");
output(paramType.getSimpleName());
output("Fields(env, arg");
output(iStr);
output(", lparg");
output(iStr);
outputln(");");
}
}
}
void generateEnterExitMacro(JNIMethod method, String function, String function64, boolean enter) {
if (!enterExitMacro) return;
if (!function.equals(function64)) {
output("#ifndef ");
output(JNI64);
outputln();
}
output("\t");
output(method.getDeclaringClass().getSimpleName());
output("_NATIVE_");
output(enter ? "ENTER" : "EXIT");
output("(env, that, ");
output(function);
outputln("_FUNC);");
if (!function.equals(function64)) {
outputln("#else");
output("\t");
output(method.getDeclaringClass().getSimpleName());
output("_NATIVE_");
output(enter ? "ENTER" : "EXIT");
output("(env, that, ");
output(function64);
outputln("_FUNC);");
outputln("#endif");
}
}
boolean generateLocalVars(JNIMethod method, JNIParameter[] params, JNIType returnType, JNIType returnType64) {
boolean needsReturn = enterExitMacro;
for (int i = 0; i < params.length; i++) {
JNIParameter param = params[i];
JNIType paramType = param.getType(), paramType64 = param.getType64();
if (paramType.isPrimitive() || isSystemClass(paramType)) continue;
output("\t");
if (paramType.isArray()) {
JNIType componentType = paramType.getComponentType();
if (componentType.isPrimitive()) {
output(componentType.getTypeSignature2(!paramType.equals(paramType64)));
output(" *lparg" + i);
output("=NULL;");
} else {
throw new Error("not done");
}
} else if (paramType.isType("java.lang.String")) {
if (param.getFlag(FLAG_UNICODE)) {
output("const jchar *lparg" + i);
} else {
output("const char *lparg" + i);
}
output("= NULL;");
} else {
if (param.getTypeClass().getFlag(Flags.FLAG_STRUCT)) {
output("struct ");
}
output(paramType.getSimpleName());
output(" _arg" + i);
if (param.getFlag(FLAG_INIT)) output("={0}");
output(", *lparg" + i);
output("=NULL;");
}
outputln();
needsReturn = true;
}
if (needsReturn) {
if (!returnType.isType("void")) {
output("\t");
output(returnType.getTypeSignature2(!returnType.equals(returnType64)));
outputln(" rc = 0;");
}
}
return needsReturn;
}
boolean generateGetters(JNIMethod method, JNIParameter[] params) {
boolean genFailTag = false;
int criticalCount = 0;
for (int i = 0; i < params.length; i++) {
JNIParameter param = params[i];
if (!isCritical(param)) {
genFailTag |= generateGetParameter(method, param, false, 1);
} else {
criticalCount++;
}
}
if (criticalCount != 0) {
outputln("#ifdef JNI_VERSION_1_2");
outputln("\tif (IS_JNI_1_2) {");
for (int i = 0; i < params.length; i++) {
JNIParameter param = params[i];
if (isCritical(param)) {
genFailTag |= generateGetParameter(method, param, true, 2);
}
}
outputln("\t} else");
outputln("#endif");
outputln("\t{");
for (int i = 0; i < params.length; i++) {
JNIParameter param = params[i];
if (isCritical(param)) {
genFailTag |= generateGetParameter(method, param, false, 2);
}
}
outputln("\t}");
}
return genFailTag;
}
void generateSetters(JNIMethod method, JNIParameter[] params) {
int criticalCount = 0;
for (int i = params.length - 1; i >= 0; i--) {
JNIParameter param = params[i];
if (isCritical(param)) {
criticalCount++;
}
}
if (criticalCount != 0) {
outputln("#ifdef JNI_VERSION_1_2");
outputln("\tif (IS_JNI_1_2) {");
for (int i = params.length - 1; i >= 0; i--) {
JNIParameter param = params[i];
if (isCritical(param)) {
output("\t");
generateSetParameter(param, true);
}
}
outputln("\t} else");
outputln("#endif");
outputln("\t{");
for (int i = params.length - 1; i >= 0; i--) {
JNIParameter param = params[i];
if (isCritical(param)) {
output("\t");
generateSetParameter(param, false);
}
}
outputln("\t}");
}
for (int i = params.length - 1; i >= 0; i--) {
JNIParameter param = params[i];
if (!isCritical(param)) {
generateSetParameter(param, false);
}
}
}
void generateDynamicFunctionCall(JNIMethod method, JNIParameter[] params, JNIType returnType, JNIType returnType64, boolean needsReturn) {
outputln("/*");
generateFunctionCall(method, params, returnType, returnType64, needsReturn);
outputln("*/");
outputln("\t{");
String name = method.getName();
if (name.startsWith("_")) name = name.substring(1);
output("\t\tLOAD_FUNCTION(fp, ");
output(name);
outputln(")");
outputln("\t\tif (fp) {");
output("\t\t");
generateFunctionCallLeftSide(method, returnType, returnType64, needsReturn);
output("((");
output(returnType.getTypeSignature2(!returnType.equals(returnType64)));
output(" (CALLING_CONVENTION*)(");
for (int i = 0; i < params.length; i++) {
if (i != 0) output(", ");
JNIParameter param = params[i];
String cast = param.getCast();
if (cast.length() > 2) {
output(cast.substring(1, cast.length() - 1));
} else {
JNIType paramType = param.getType(), paramType64 = param.getType64();
output(paramType.getTypeSignature4(!paramType.equals(paramType64), param.getFlag(FLAG_STRUCT)));
}
}
output("))");
output("fp");
output(")");
generateFunctionCallRightSide(method, params, 0);
output(";");
outputln();
outputln("\t\t}");
outputln("\t}");
}
void generateFunctionCallLeftSide(JNIMethod method, JNIType returnType, JNIType returnType64, boolean needsReturn) {
output("\t");
if (!returnType.isType("void")) {
if (needsReturn) {
output("rc = ");
} else {
output("return ");
}
output("(");
output(returnType.getTypeSignature2(!returnType.equals(returnType64)));
output(")");
}
if (method.getFlag(FLAG_ADDRESS)) {
output("&");
}
if (method.getFlag(FLAG_JNI)) {
output(isCPP ? "env->" : "(*env)->");
}
}
void generateFunctionCallRightSide(JNIMethod method, JNIParameter[] params, int paramStart) {
if (!method.getFlag(FLAG_CONST)) {
output("(");
if (method.getFlag(FLAG_JNI)) {
if (!isCPP) output("env, ");
}
for (int i = paramStart; i < params.length; i++) {
JNIParameter param = params[i];
if (i != paramStart) output(", ");
if (param.getFlag(FLAG_STRUCT)) output("*");
output(param.getCast());
if (param.getFlag(FLAG_GCOBJECT)) output("TO_OBJECT(");
if (i == params.length - 1 && param.getFlag(FLAG_SENTINEL)) {
output("NULL");
} else {
JNIType paramType = param.getType();
if (!paramType.isPrimitive() && !isSystemClass(paramType)) output("lp");
output("arg" + i);
}
if (param.getFlag(FLAG_GCOBJECT)) output(")");
}
output(")");
}
}
void generateFunctionCall(JNIMethod method, JNIParameter[] params, JNIType returnType, JNIType returnType64, boolean needsReturn) {
String name = method.getName();
boolean objc_struct = false;
if (name.equals("objc_msgSend_stret")) {
objc_struct = true;
outputln("\tif (sizeof(_arg0) > STRUCT_SIZE_LIMIT) {");
output("\t");
}
String copy = (String)method.getParam("copy");
boolean makeCopy = copy.length() != 0 && isCPP && !returnType.isType("void");
if (makeCopy) {
output("\t");
output(copy);
output(" temp = ");
} else {
generateFunctionCallLeftSide(method, returnType, returnType64, needsReturn);
}
int paramStart = 0;
if (name.startsWith("_")) name = name.substring(1);
if (name.equalsIgnoreCase("call")) {
output("(");
String cast = params[0].getCast();
if (cast.length() != 0 && !cast.equals("()")) {
output(cast);
} else {
output("(");
output(returnType.getTypeSignature2(!returnType.equals(returnType64)));
output(" (*)())");
}
output("arg0)");
paramStart = 1;
} else if (name.startsWith("VtblCall") || name.startsWith("_VtblCall")) {
output("((");
output(returnType.getTypeSignature2(!returnType.equals(returnType64)));
output(" (STDMETHODCALLTYPE *)(");
for (int i = 1; i < params.length; i++) {
if (i != 1) output(", ");
JNIParameter param = params[i];
JNIType paramType = param.getType(), paramType64 = param.getType64();
output(paramType.getTypeSignature4(!paramType.equals(paramType64), false));
}
output("))(*(");
JNIType paramType = params[1].getType(), paramType64 = params[1].getType64();
output(paramType.getTypeSignature4(!paramType.equals(paramType64), false));
output(" **)arg1)[arg0])");
paramStart = 1;
} else if (method.getFlag(FLAG_CPP) || method.getFlag(FLAG_SETTER) || method.getFlag(FLAG_GETTER) || method.getFlag(FLAG_ADDER)) {
if (method.getFlag(FLAG_GCOBJECT)) {
output("TO_HANDLE(");
}
output("(");
JNIParameter param = params[0];
if (param.getFlag(FLAG_STRUCT)) output("*");
String cast = param.getCast();
if (cast.length() != 0 && !cast.equals("()")) {
output(cast);
}
if (param.getFlag(FLAG_GCOBJECT)) {
output("TO_OBJECT(");
}
output("arg0");
if (param.getFlag(FLAG_GCOBJECT)) {
output(")");
}
output(")->");
String accessor = method.getAccessor();
if (accessor.length() != 0) {
output(accessor);
} else {
int index = -1;
if ((index = name.indexOf('_')) != -1) {
output(name.substring(index + 1, name.length()));
} else {
output(name);
}
}
paramStart = 1;
} else if (method.getFlag(FLAG_GCNEW)) {
output("TO_HANDLE(gcnew ");
String accessor = method.getAccessor();
if (accessor.length() != 0) {
output(accessor);
} else {
int index = -1;
if ((index = name.indexOf('_')) != -1) {
output(name.substring(index + 1));
} else {
output(name);
}
}
} else if (method.getFlag(FLAG_NEW)) {
output("new ");
String accessor = method.getAccessor();
if (accessor.length() != 0) {
output(accessor);
} else {
int index = -1;
if ((index = name.indexOf('_')) != -1) {
output(name.substring(0, index));
} else {
output(name);
}
}
} else if (method.getFlag(FLAG_DELETE)) {
output("delete ");
JNIParameter param = params[0];
String cast = param.getCast();
if (cast.length() != 0 && !cast.equals("()")) {
output(cast);
} else {
output("(");
output(name.substring(0, name.indexOf("_")));
output(" *)");
}
outputln("arg0;");
return;
} else {
if (method.getFlag(FLAG_GCOBJECT)) {
output("TO_HANDLE(");
}
if (method.getFlag(Flags.FLAG_CAST)) {
output("((");
output(returnType.getTypeSignature2(!returnType.equals(returnType64)));
output(" (*)(");
for (int i = 0; i < params.length; i++) {
if (i != 0) output(", ");
JNIParameter param = params[i];
String cast = param.getCast();
if (cast != null && cast.length() != 0) {
if (cast.startsWith("(")) cast = cast.substring(1);
if (cast.endsWith(")")) cast = cast.substring(0, cast.length() - 1);
output(cast);
} else {
JNIType paramType = param.getType(), paramType64 = param.getType64();
if (!(paramType.isPrimitive() || paramType.isArray())) {
if (param.getTypeClass().getFlag(FLAG_STRUCT)) {
output("struct ");
}
}
output(paramType.getTypeSignature4(!paramType.equals(paramType64), param.getFlag(FLAG_STRUCT)));
}
}
output("))");
}
String accessor = method.getAccessor();
if (accessor.length() != 0) {
output(accessor);
} else {
output(name);
}
if (method.getFlag(Flags.FLAG_CAST)) {
output(")");
}
}
if ((method.getFlag(FLAG_SETTER) && params.length == 3) || (method.getFlag(FLAG_GETTER) && params.length == 2)) {
output("[arg1]");
paramStart++;
}
if (method.getFlag(FLAG_SETTER)) output(" = ");
if (method.getFlag(FLAG_ADDER)) output(" += ");
if (!method.getFlag(FLAG_GETTER)) {
generateFunctionCallRightSide(method, params, paramStart);
}
if (method.getFlag(FLAG_GCNEW) || method.getFlag(FLAG_GCOBJECT)) {
output(")");
}
output(";");
outputln();
if (makeCopy) {
outputln("\t{");
output("\t\t");
output(copy);
output("* copy = new ");
output(copy);
outputln("();");
outputln("\t\t*copy = temp;");
output("\t\trc = ");
output("(");
output(returnType.getTypeSignature2(!returnType.equals(returnType64)));
output(")");
outputln("copy;");
outputln("\t}");
}
if (objc_struct) {
outputln("\t} else {");
output("\t\t*lparg0 = (*(");
JNIType paramType = params[0].getType(), paramType64 = params[0].getType64();
output(paramType.getTypeSignature4(!paramType.equals(paramType64), true));
output(" (*)(");
for (int i = 1; i < params.length; i++) {
if (i != 1) output(", ");
JNIParameter param = params[i];
String cast = param.getCast();
if (cast != null && cast.length() != 0) {
if (cast.startsWith("(")) cast = cast.substring(1);
if (cast.endsWith(")")) cast = cast.substring(0, cast.length() - 1);
output(cast);
} else {
paramType = param.getType(); paramType64 = param.getType64();
output(paramType.getTypeSignature4(!paramType.equals(paramType64), param.getFlag(FLAG_STRUCT)));
}
}
output("))objc_msgSend)");
generateFunctionCallRightSide(method, params, 1);
outputln(";");
outputln("\t}");
}
}
void generateReturn(JNIMethod method, JNIType returnType, boolean needsReturn) {
if (needsReturn && !returnType.isType("void")) {
outputln("\treturn rc;");
}
}
void generateMemmove(JNIMethod method, String function, String function64, JNIParameter[] params) {
generateEnterExitMacro(method, function, function64, true);
output("\t");
boolean get = params[0].getType().isPrimitive();
String className = params[get ? 1 : 0].getType().getSimpleName();
output(get ? "if (arg1) get" : "if (arg0) set");
output(className);
output(get ? "Fields(env, arg1, (" : "Fields(env, arg0, (");
output(className);
output(get ? " *)arg0)" : " *)arg1)");
outputln(";");
generateEnterExitMacro(method, function, function64, false);
}
void generateFunctionBody(JNIMethod method, String function, String function64, JNIParameter[] params, JNIType returnType, JNIType returnType64) {
outputln("{");
/* Custom GTK memmoves. */
String name = method.getName();
if (name.startsWith("_")) name = name.substring(1);
boolean isMemove = (name.equals("memmove") || name.equals("MoveMemory")) && params.length == 2 && returnType.isType("void");
if (isMemove) {
generateMemmove(method, function, function64, params);
} else {
boolean needsReturn = generateLocalVars(method, params, returnType, returnType64);
generateEnterExitMacro(method, function, function64, true);
boolean genFailTag = generateGetters(method, params);
if (method.getFlag(FLAG_DYNAMIC)) {
generateDynamicFunctionCall(method, params, returnType, returnType64, needsReturn);
} else {
generateFunctionCall(method, params, returnType, returnType64, needsReturn);
}
if (genFailTag) outputln("fail:");
generateSetters(method, params);
generateEnterExitMacro(method, function, function64, false);
generateReturn(method, returnType, needsReturn);
}
outputln("}");
}
void generateFunctionPrototype(JNIMethod method, String function, JNIParameter[] params, JNIType returnType, JNIType returnType64, boolean singleLine) {
output("JNIEXPORT ");
output(returnType.getTypeSignature2(!returnType.equals(returnType64)));
output(" JNICALL ");
output(method.getDeclaringClass().getSimpleName());
output("_NATIVE(");
output(function);
if (singleLine) {
output(")");
output("(JNIEnv *env, ");
} else {
outputln(")");
output("\t(JNIEnv *env, ");
}
if ((method.getModifiers() & Modifier.STATIC) != 0) {
output("jclass");
} else {
output("jobject");
}
output(" that");
for (int i = 0; i < params.length; i++) {
output(", ");
JNIType paramType = params[i].getType(), paramType64 = params[i].getType64();
output(paramType.getTypeSignature2(!paramType.equals(paramType64)));
output(" arg" + i);
}
output(")");
if (!singleLine) outputln();
}
void generateSourceStart(String function, String function64) {
if (function.equals(function64)) {
output("#ifndef NO_");
outputln(function);
} else {
output("#if (!defined(NO_");
output(function);
output(") && !defined(");
output(JNI64);
output(")) || (!defined(NO_");
output(function64);
output(") && defined(");
output(JNI64);
outputln("))");
}
}
void generateSourceEnd(String function) {
outputln("#endif");
}
boolean isCritical(JNIParameter param) {
JNIType paramType = param.getType();
return paramType.isArray() && paramType.getComponentType().isPrimitive() && param.getFlag(FLAG_CRITICAL);
}
boolean isSystemClass(JNIType type) {
return type.isType("java.lang.Object") || type.isType("java.lang.Class") ;
}
}
|
Java
|
UTF-8
| 1,823
| 1.585938
| 2
|
[
"Apache-2.0"
] |
permissive
|
package kotlin.internal;
import java.lang.annotation.Annotation;
import java.lang.annotation.RetentionPolicy;
import kotlin.DeprecationLevel;
import kotlin.Metadata;
import kotlin.SinceKotlin;
import kotlin.annotation.AnnotationRetention;
@java.lang.annotation.Retention(RetentionPolicy.SOURCE)
@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.CONSTRUCTOR})
@Metadata(bv={1, 0, 2}, d1={"\000$\n\002\030\002\n\002\020\033\n\000\n\002\020\016\n\002\b\002\n\002\030\002\n\000\n\002\030\002\n\000\n\002\020\b\n\000\b\002\030\0002\0020\001B0\022\006\020\002\032\0020\003\022\b\b\002\020\004\032\0020\003\022\b\b\002\020\005\032\0020\006\022\b\b\002\020\007\032\0020\b\022\b\b\002\020\t\032\0020\nR\t\020\t\032\0020\n¢\006\000R\t\020\005\032\0020\006¢\006\000R\t\020\004\032\0020\003¢\006\000R\t\020\002\032\0020\003¢\006\000R\t\020\007\032\0020\b¢\006\000¨\006\013"}, d2={"Lkotlin/internal/RequireKotlin;", "", "version", "", "message", "level", "Lkotlin/DeprecationLevel;", "versionKind", "Lkotlin/internal/RequireKotlinVersionKind;", "errorCode", "", "kotlin-stdlib"}, k=1, mv={1, 1, 9})
@kotlin.annotation.Retention(AnnotationRetention.SOURCE)
@kotlin.annotation.Target(allowedTargets={kotlin.annotation.AnnotationTarget.CLASS, kotlin.annotation.AnnotationTarget.FUNCTION, kotlin.annotation.AnnotationTarget.PROPERTY, kotlin.annotation.AnnotationTarget.CONSTRUCTOR, kotlin.annotation.AnnotationTarget.TYPEALIAS})
@SinceKotlin(version="1.2")
public @interface RequireKotlin
{
int errorCode() default -1;
DeprecationLevel level() default DeprecationLevel.ERROR;
String message() default "";
String version();
RequireKotlinVersionKind versionKind() default RequireKotlinVersionKind.LANGUAGE_VERSION;
}
|
Python
|
UTF-8
| 957
| 4.40625
| 4
|
[] |
no_license
|
from time import sleep
num1 = int(input('Primeiro valor: '))
num2 = int(input('Segundo valor: '))
opção = 0
while opção != 5:
print('''[1] somar
[2] multiplicar
[3] maior
[4] novos numeros
[5] sair do programa
''')
opcão = int(input('>>>>> Qual é a sua opção? '))
if opção == 1:
soma = num1 + num2
print(f'A Soma entre {num1} + {num2} é {soma}')
elif opção == 2:
produto = num1 * num2
print(f'O resultado de {num1} x {num2} é {produto}')
elif opção == 3:
if num1 > num2:
maior = num1
else:
maior = num2
print(f'Entre {num1} e {num2} o maior valor é {maior}')
elif opção == 4:
print('Informe os numeros novamente: ')
num1 = int(input('Primeiro valor: '))
num2 = int(input('Segundo valor: '))
elif opçã == 5:
print('Finalizando...')
else:
print('Opção invalida. Tente novamente')
print('=-=' * 10)
sleep(2)
print('Fim do programa! Volte sempre!')
|
C++
|
UTF-8
| 1,404
| 2.90625
| 3
|
[] |
no_license
|
//
// Created by anouk on 15-03-20.
//
using namespace std;
#include "../includes/crispr.h"
#include <algorithm>
Crispr::Crispr(std::string name_id, int dr_length, std::vector<int> dr_positions) {
id = name_id;
detected = 0;
partially_detected = 0;
length = dr_length;
positions = dr_positions;
}
void Crispr::check_candidate(int reps, int cand_length, int start, int end) {
//Discard candidate if its DR length is a different length and if it is out of range of the crispr
if (end <= positions.back()) {
int delta = length - cand_length;
//If the first and last candidate DR positions are in the array of occurences, the DR repetitions are counted as detected
for (int i = 0; i <= delta; i++) {
if (std::find(positions.begin(), positions.end(), start - i) != positions.end() &&
std::find(positions.begin(), positions.end(), end - i) != positions.end()) {
if (length == cand_length and i == 0) {
detected += reps;
} else {
partially_detected += reps;
}
break;
}
}
}
}
double Crispr::percentage_detected() {
return 100 * (double) detected / positions.size();
}
int Crispr::get_detected() {
return detected;
}
int Crispr::get_partially_detected() {
return partially_detected;
}
|
Python
|
UTF-8
| 4,548
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
# -*- coding:utf-8 -*-
"""
aiohttp client接口封装
Author: HuangTao
Date: 2018/05/03
"""
import aiohttp
from urllib.parse import urlparse
from quant.utils import logger
from quant.config import config
class AsyncHttpRequests(object):
""" HTTP异步请求封装
"""
_SESSIONS = {} # 每个域名保持一个公用的session连接(每个session持有自己的连接池),这样可以节省资源、加快请求速度
@classmethod
async def fetch(cls, method, url, params=None, body=None, data=None, headers=None, timeout=30, **kwargs):
""" 发起HTTP请求
@param method 请求方法 GET/POST/PUT/DELETE
@param url 请求的url
@param params 请求的uri参数
@param body 请求的body参数
@param data json格式的数据
@param headers 请求的headers
@param timeout 超时时间(秒)
@return (code, success, error) 如果成功,error为None,失败success为None,error为失败信息
"""
session = cls._get_session(url)
if not kwargs.get("proxy"):
kwargs["proxy"] = config.proxy # HTTP代理配置
try:
if method == "GET":
response = await session.get(url, params=params, headers=headers, timeout=timeout, **kwargs)
elif method == "POST":
response = await session.post(url, params=params, data=body, json=data, headers=headers,
timeout=timeout, **kwargs)
elif method == "PUT":
response = await session.put(url, params=params, data=body, json=data, headers=headers,
timeout=timeout, **kwargs)
elif method == "DELETE":
response = await session.delete(url, params=params, data=body, json=data, headers=headers,
timeout=timeout, **kwargs)
else:
error = "http method error!"
return None, None, error
except Exception as e:
logger.error("method:", method, "url:", url, "params:", params, "body:", body, "data:", data, "Error:", e,
caller=cls)
return None, None, e
code = response.status
if code not in (200, 201, 202, 203, 204, 205, 206):
text = await response.text()
logger.error("method:", method, "url:", url, "params:", params, "body:", body, "headers:", headers,
"code:", code, "result:", text, caller=cls)
return code, None, text
try:
result = await response.json()
except:
logger.warn("response data is not json format!", "method:", method, "url:", url, "params:", params,
caller=cls)
result = await response.text()
logger.debug("method:", method, "url:", url, "params:", params, "body:", body, "data:", data,
"code:", code, "result:", result, caller=cls)
return code, result, None
@classmethod
async def get(cls, url, params=None, body=None, data=None, headers=None, timeout=30, **kwargs):
""" HTTP GET 请求
"""
result = await cls.fetch("GET", url, params, body, data, headers, timeout, **kwargs)
return result
@classmethod
async def post(cls, url, params=None, body=None, data=None, headers=None, timeout=30, **kwargs):
""" HTTP POST 请求
"""
result = await cls.fetch("POST", url, params, body, data, headers, timeout, **kwargs)
return result
@classmethod
async def delete(cls, url, params=None, body=None, data=None, headers=None, timeout=30, **kwargs):
""" HTTP DELETE 请求
"""
result = await cls.fetch("DELETE", url, params, body, data, headers, timeout, **kwargs)
return result
@classmethod
async def put(cls, url, params=None, body=None, data=None, headers=None, timeout=30, **kwargs):
""" HTTP PUT 请求
"""
result = await cls.fetch("PUT", url, params, body, data, headers, timeout, **kwargs)
return result
@classmethod
def _get_session(cls, url):
""" 获取url对应的session连接
"""
parsed_url = urlparse(url)
key = parsed_url.netloc or parsed_url.hostname
if key not in cls._SESSIONS:
session = aiohttp.ClientSession()
cls._SESSIONS[key] = session
return cls._SESSIONS[key]
|
Java
|
UTF-8
| 1,660
| 3.234375
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java8;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
*
* @author sandeep.kumar
*/
public class MapSortEx {
public static void main(String...args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("A", 10);
map.put("C", 8);
map.put("B", 7);
map.put("X", 9);
map.put("V", 6);
map.put("S", 4);
map.put("T", 3);
map.put("L", 1);
map.put("M", 5);
map.put("F", 2);
map.put("G", 11);
Map<String, Integer> sortedMap = map.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
System.out.println(sortedMap);
sortedMap = map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
System.out.println(sortedMap);
LinkedHashMap<String, Integer> sortedMap1 = new LinkedHashMap<String, Integer>();
map.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue().reversed()).forEachOrdered(x -> sortedMap1.put(x.getKey(), x.getValue()));
System.out.println(sortedMap1);
}
}
|
Go
|
UTF-8
| 1,834
| 2.765625
| 3
|
[] |
no_license
|
package cssectl
import (
"encoding/json"
"net/http"
"time"
"github.com/gorilla/mux"
applogger "github.com/junkd0g/covid/lib/applogger"
csse "github.com/junkd0g/covid/lib/csse"
merror "github.com/junkd0g/neji"
)
/*
Get request to /api/csse/{country}
{
"country": "US",
"data": [
{
"county": "<nil>",
"province": "Diamond Princess",
"cases": 49,
"deaths": 0,
"recovered": 0
},
{
"county": "<nil>",
"province": "Grand Princess",
"cases": 103,
"deaths": 3,
"recovered": 0
}
]
}
*/
func Handle(w http.ResponseWriter, r *http.Request) {
start := time.Now()
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
jsonBody, status := perform(vars["country"])
w.WriteHeader(status)
w.Write(jsonBody)
elapsed := time.Since(start).Seconds()
applogger.LogHTTP("INFO", "cssectl", "Handle",
"Endpoint /api/world called with response JSON body "+string(jsonBody), status, elapsed)
}
//Perform used in the /api/csse/{country} endpoint's handle to return
// @return array of bytes of the json object
// @return int http code status
func perform(country string) ([]byte, int) {
csseData, err := csse.GetCSSECountryData(country)
if err != nil {
applogger.Log("ERROR", "cssectl", "perform", err.Error())
statsErrJSONBody, _ := merror.SimpeErrorResponseWithStatus(500, err)
return statsErrJSONBody, 500
}
jsonBody, jsonBodyErr := json.Marshal(csseData)
if jsonBodyErr != nil {
applogger.Log("ERROR", "cssectl", "perform", jsonBodyErr.Error())
errorJSONBody, _ := merror.SimpeErrorResponseWithStatus(500, jsonBodyErr)
return errorJSONBody, 500
}
return jsonBody, 200
}
|
Python
|
UTF-8
| 4,586
| 3.453125
| 3
|
[] |
no_license
|
'''
Scores are maintained in SCurrent and generated in SNext.
SCurrent is a dictionary where:
the key is the digit we are currently in
the value is another dictionary of all possible scores with their respective probabilities
Todo:
10 digit formatting
Test!!
'''
import math
class Phonepad:
def __init__(self):
self.setupNext();
self.setupS();
def createNext(self, modulo):
self.SNext = {}
# currentScores is a dictionary of all possible scores:
for currentDigit, currentScores in self.SCurrent.iteritems():
# nextDList is a list of next digit with the probability:
nextDList = self.nextD[currentDigit]
# Go through all scores:
for currentScore, currentProb in currentScores.iteritems():
# nextDP = (nextDigit, probability)
for nextDP in nextDList:
if nextDP[0] not in self.SNext:
self.SNext[nextDP[0]] = {}
nextScores = self.SNext[nextDP[0]]
nextScore = (currentScore + nextDP[0])
if modulo != None:
nextScore = nextScore % modulo
nextProb = currentProb * nextDP[1]
if nextScore in nextScores:
nextScores[nextScore] = nextScores[nextScore] + nextProb
else:
nextScores[nextScore] = nextProb
self.SCurrent = self.SNext
def prettyPrint(self):
for digit, scores in self.SCurrent.iteritems():
print "digit = {} possible values of S {}".format(digit, len(scores))
for score, prob in scores.iteritems():
print "score = {} probability = {}".format(score, prob)
#
# E(X) = sum x*p(x)
# V(X) = sum x^2*p(x) - (E(X))^2
def printExpectedVariance(self):
e = 0.0
exsquared = 0.0
v = 0.0
for digit, scores in self.SCurrent.iteritems():
for score, prob in scores.iteritems():
e += score * prob
exsquared += score * score * prob;
v = math.sqrt( exsquared - (e*e) )
print "Expected Value = {} Variance = {}".format(e, v)
def printConditionalProb(self, which, given, debug):
# which is the numerator
# given is the denominator:
l_scores = []
numer = 0.0
denom = 0.0
for digit, scores in self.SCurrent.iteritems():
for score, prob in scores.iteritems():
if debug:
l_scores.append(score)
if score % given == 0:
denom += prob
if score % which == 0:
numer += prob
whichProb = numer / denom
if debug:
print l_scores
print "Probability S is divisible by {} given S is divisible by {} is {}".format(which, given, whichProb)
def setupNext(self):
tempNextD = {
0: (4,6),
1: (6,8),
2: (7,9),
3: (4,8),
4: (0,3,9),
5: (),
6: (0,1,7),
7: (2,6),
8: (1,3),
9: (2,4)
};
self.nextD = dict()
for d, nextD in tempNextD.iteritems():
l = len(nextD)
tempV = list()
for i in nextD:
tempV.append( (i, 1.0/l) )
self.nextD[d] = tempV
## print self.nextD
def setupS(self):
self.SCurrent = { 0 : {0:1} }
self.SNext = {}
def main():
pad = Phonepad()
print "10 iterations; modulo 10"
for i in range(0,10):
##print "Iteration = {}".format(i+1)
pad.createNext(10)
# pad.prettyPrint()
pad.printExpectedVariance()
pad = Phonepad()
print "1024 iterations; modulo 1024"
for i in range(0,1024):
##print "Iteration = {}".format(i+1)
pad.createNext(1024)
# pad.prettyPrint()
pad.printExpectedVariance()
pad = Phonepad()
print "10 iterations; no modulo"
for i in range(0,10):
##print "Iteration = {}".format(i+1)
pad.createNext(None)
# pad.prettyPrint()
pad.printConditionalProb(5, 7, False)
pad = Phonepad()
print "1024 iterations; no modulo"
for i in range(0,1024):
##print "Iteration = {}".format(i+1)
pad.createNext(None)
# pad.prettyPrint()
pad.printConditionalProb(23, 29, False)
if __name__ == "__main__":
main();
|
Go
|
UTF-8
| 1,624
| 3.015625
| 3
|
[] |
no_license
|
package fileManager
import (
"io"
"net/http"
"os"
"github.com/gin-gonic/gin"
)
func UploadFileToPeer(c *gin.Context) {
file, err := c.FormFile("file")
// The file cannot be received.
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"message": "No file is received",
})
return
}
// src, err := file.Open()
// if err != nil {
// return err
// }
// defer src.Close()
// Create files folder
if _, err := os.Stat("files"); os.IsNotExist(err) {
os.Mkdir("files", os.ModeDir)
}
// // Destination
// dst, err := os.Create("files/" + file.Filename)
// if err != nil {
// return err
// }
// defer dst.Close()
// // Copy
// if _, err = io.Copy(dst, src); err != nil {
// return err
// }
// The file is received, so let's save it
if err := c.SaveUploadedFile(file, "files/"+file.Filename); err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"message": "Unable to save the file",
})
return
}
// File saved successfully. Return proper result
c.JSON(http.StatusOK, gin.H{
"message": "Your file has been successfully uploaded.",
})
}
func DownloadFileFromPeer(c *gin.Context) {
name := c.Param("name")
file, err := os.Open("files/" + name)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"message": "File not found",
})
return
}
defer file.Close()
c.Writer.Header().Add("Content-type", "application/octet-stream")
_, err = io.Copy(c.Writer, file)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
"message": "File download fail.",
})
return
}
}
|
Java
|
UTF-8
| 230
| 2.5
| 2
|
[] |
no_license
|
public class ReverseString {
public static void main(String[] args) {
String s1="Reverse";
StringBuilder b=new StringBuilder();
b.append(s1);
b.reverse();
System.out.println(b);
}
}
|
JavaScript
|
UTF-8
| 1,613
| 3.953125
| 4
|
[] |
no_license
|
function solution(input){
// Split the data into [category, item] format
// Ex: ['fruit_bannana', 'vegetable_carrot'] => [['fruit', 'bannana'], ['vegetable', 'carrot]]
let groceryItems = input.split(',').map(item => item.split('_'));
// Store the items in an object by category.
let groceryStorage = {fruit: [], meat: [], other:[], vegetable:[]};
let resultString = '';
groceryItems.forEach(groceryItem =>{
// if there is a cateogory other than fruit, vegetable, or meat, it is of category other
let category = ['fruit', 'vegetable', 'meat'].includes(groceryItem[0]) ? groceryItem[0] : 'other';
let item = groceryItem[1];
// Adding the item to the correct category
/*
category = 'fruit'
item = 'bannana';
groceryStorage[category].push(item) => {fruit: [bannana]}
----------------------------
category = 'vegetable'
item = 'carrot';
groceryStorage[category].push(item) => {vegetable: [carrot]}
*/
groceryStorage[category].push(item);
})
// groceryStorage should now have an array of items for each category
// So I am going to loop throught each category in the groceryStorage
// Each category holds an array, so I am going to sort the items and then join into a string
// I am then going to add a newline character after every string except for the vegetable category
for(let prop in groceryStorage){
resultString += prop + ':' + groceryStorage[prop].sort().join(',') + (prop !== 'vegetable' ? '\n': '');
}
return resultString;
}
|
PHP
|
UTF-8
| 1,047
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Apie\ApieBundle\Wrappers;
use Apie\CmsLayoutGraphite\GraphiteDesignSystemLayout;
use Apie\HtmlBuilders\Assets\AssetManager;
use Apie\HtmlBuilders\Interfaces\ComponentInterface;
use Apie\HtmlBuilders\Interfaces\ComponentRendererInterface;
final class CmsRendererFactory
{
private function __construct()
{
}
public static function createRenderer(?AssetManager $assetManager): ComponentRendererInterface
{
if (class_exists(GraphiteDesignSystemLayout::class)) {
return GraphiteDesignSystemLayout::createRenderer($assetManager);
}
$contents = file_get_contents(__DIR__ . '/../../resources/html/install-instructions-cms-renderer.html');
return new class($contents) implements ComponentRendererInterface {
public function __construct(private string $contents)
{
}
public function render(ComponentInterface $componentInterface): string
{
return $this->contents;
}
};
}
}
|
Shell
|
UTF-8
| 189
| 3.0625
| 3
|
[] |
no_license
|
#!/bin/bash
x=name
y=DOB
echo -n "What is your $x?
"
read $x
echo "What is your $y?"
read $y
m=( date +%Y )
let a=m-y
let r=50-a
let z=m+r
echo "$name will be of 50 years by $z"
|
Markdown
|
UTF-8
| 715
| 3.1875
| 3
|
[] |
no_license
|
在某些情况下,为了提高效率和操作方便,需要允许一个函数或类访问另一个类的私有成员,这需要通过友元实现。
友元可以实现数据共享,但在一定程度上破坏了类的封装性,除非在提高效率上有很大帮助,一般不提倡使用友元,友元较多地用在运算符重载中。为了更好地使用友元,需要在共享和封装之间找到一个结合点。
## 友元函数
友元函数是在类外定义的一个函数,它不是本类的成员函数,而是一个普通的函数或其他类的成员函数。
## 友元类
除了可以声明函数为类的友元函数外,还可以将一个类声明为另一个类的友元类。
|
JavaScript
|
UTF-8
| 2,791
| 2.953125
| 3
|
[] |
no_license
|
'use strict';
const express = require('express');
const { Pool } = require('pg');
const axios = require('axios');
const PORT = 8080;
const HOST = '0.0.0.0';
const sqlMaxSleep = parseFloat(process.env.SQL_SLEEP_MAX) || 0.0; // seconds
const loopCount = parseInt(process.env.LOOP_COUNT) || 0;
const poolSize = parseInt(process.env.POOL_SIZE) || 1;
const targetUrl = process.env.TARGET_URL.replace(/\/$/, '');
function randomString(len) {
return Math.random().toString(36).substring(len);
}
function randomInt(max) {
return Math.floor(Math.random() * max) + 1;
}
function createUser() {
var friend = {
name: randomString(10),
surname: randomString(3),
street: randomString(15),
school: randomString(9),
bank: randomString(4),
a: randomInt(100),
b: Math.random(),
c: randomInt(1090),
friend: null,
};
return {
name: randomString(10),
surname: randomString(3),
street: randomString(15),
school: randomString(9),
bank: randomString(4),
a: randomInt(100),
b: Math.random(),
c: randomInt(1090),
friend: friend,
};
}
function randSleep() {
return Math.random() * sqlMaxSleep;
}
// App
const app = express();
// DB
const pool = new Pool({
user: 'postgres',
host: '127.0.0.1',
database: 'postgres',
password: 'root',
port: 5432,
max: poolSize, // number of connections
});
// Routes
app.get('/', (req, res) => {
res.write("<html>It's me, Express App.<br/>");
res.write("Use routes:<br/><a href='./json'>json</a><br/>");
res.write("<a href='./db'>db</a></html>");
res.end();
});
app.get('/json', (req, res) => {
var user = createUser();
res.json(user);
});
app.get('/http', (req, res) => {
axios.get(`${targetUrl}/${randSleep()}`)
.then(result => res.json(result.data))
.catch(err => res.status(500).json(err));
});
app.get('/db', (req, res) => {
// Make a DB call
var qry = "";
if (sqlMaxSleep == 0) {
qry = "SELECT count(*) FROM pg_catalog.pg_user"
} else {
qry = `SELECT pg_sleep(${randSleep()})`;
}
pool.query(qry, (err, result) => {
if (err) {
console.warn(err);
res.status(500).json(err);
}
// Create some CPU and RAM load
var users = [];
for (var i = 0; i < loopCount; i++) {
users[i] = createUser();
}
var resultData = {
"db-query": qry,
"data": users,
"result": result,
};
res.json(resultData);
});
});
app.listen(PORT, HOST);
console.log(`Using SQL_SLEEP_MAX = ${sqlMaxSleep} seconds; LOOP_COUNT = ${loopCount}`);
console.log(`Running on http://${HOST}:${PORT}`);
|
Java
|
UTF-8
| 28,117
| 1.539063
| 2
|
[] |
no_license
|
/**
* This file was converted to Java from the original LLVM source file. The original
* source file follows the LLVM Release License, outlined below.
*
* ==============================================================================
* LLVM Release License
* ==============================================================================
* University of Illinois/NCSA
* Open Source License
*
* Copyright (c) 2003-2017 University of Illinois at Urbana-Champaign.
* All rights reserved.
*
* Developed by:
*
* LLVM Team
*
* University of Illinois at Urbana-Champaign
*
* http://llvm.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal with
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above copyright notice
* this list of conditions and the following disclaimers in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the names of the LLVM Team, University of Illinois at
* Urbana-Champaign, nor the names of its contributors may be used to
* endorse or promote products derived from this Software without specific
* prior written permission.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
* SOFTWARE.
*
* ==============================================================================
* Copyrights and Licenses for Third Party Software Distributed with LLVM:
* ==============================================================================
* The LLVM software contains code written by third parties. Such software will
* have its own individual LICENSE.TXT file in the directory in which it appears.
* This file will describe the copyrights, license, and restrictions which apply
* to that code.
*
* The disclaimer of warranty in the University of Illinois Open Source License
* applies to all code in the LLVM Distribution, and nothing in any of the
* other licenses gives permission to use the names of the LLVM Team or the
* University of Illinois to endorse or promote products derived from this
* Software.
*
* The following pieces of software have additional or alternate copyrights,
* licenses, and/or restrictions:
*
* Program Directory
* ------- ---------
* Autoconf llvm/autoconf
* llvm/projects/ModuleMaker/autoconf
* Google Test llvm/utils/unittest/googletest
* OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex}
* pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT}
* ARM contributions llvm/lib/Target/ARM/LICENSE.TXT
* md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h
*/
package org.llvm.mc;
import org.clank.support.*;
import org.clank.support.aliases.*;
import static org.llvm.mc.MCContextGlobals.$new_uint_MCContext_uint;
/// \brief Binary assembler expressions.
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 383,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 410,
FQN="llvm::MCBinaryExpr", NM="_ZN4llvm12MCBinaryExprE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExprE")
//</editor-fold>
public class MCBinaryExpr extends /*public*/ MCExpr {
/*public:*/
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::Opcode">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 385,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 412,
FQN="llvm::MCBinaryExpr::Opcode", NM="_ZN4llvm12MCBinaryExpr6OpcodeE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr6OpcodeE")
//</editor-fold>
public enum Opcode implements Native.NativeUIntEnum {
Add(0), ///< Addition.
And(Add.getValue() + 1), ///< Bitwise and.
Div(And.getValue() + 1), ///< Signed division.
EQ(Div.getValue() + 1), ///< Equality comparison.
GT(EQ.getValue() + 1), ///< Signed greater than comparison (result is either 0 or some
///< target-specific non-zero value)
GTE(GT.getValue() + 1), ///< Signed greater than or equal comparison (result is either 0 or
///< some target-specific non-zero value).
LAnd(GTE.getValue() + 1), ///< Logical and.
LOr(LAnd.getValue() + 1), ///< Logical or.
LT(LOr.getValue() + 1), ///< Signed less than comparison (result is either 0 or
///< some target-specific non-zero value).
LTE(LT.getValue() + 1), ///< Signed less than or equal comparison (result is either 0 or
///< some target-specific non-zero value).
Mod(LTE.getValue() + 1), ///< Signed remainder.
Mul(Mod.getValue() + 1), ///< Multiplication.
NE(Mul.getValue() + 1), ///< Inequality comparison.
Or(NE.getValue() + 1), ///< Bitwise or.
Shl(Or.getValue() + 1), ///< Shift left.
AShr(Shl.getValue() + 1), ///< Arithmetic shift right.
LShr(AShr.getValue() + 1), ///< Logical shift right.
Sub(LShr.getValue() + 1), ///< Subtraction.
Xor(Sub.getValue() + 1); ///< Bitwise exclusive or.
//<editor-fold defaultstate="collapsed" desc="hidden">
public static Opcode valueOf(int val) {
Opcode out = (val < 0) ? Values._VALUES[-val] : Values.VALUES[val];
assert out != null : "no value for " + val;
assert out.value == val : "asked [" + val + "] got " + out + ":" + out.value + "]";
return out;
}
private static final class Values {
private static final Opcode[] VALUES;
private static final Opcode[] _VALUES; // [0] not used
static {
int max = 0;
int min = 0;
for (Opcode kind : Opcode.values()) {
if (kind.value > max) { max = kind.value; }
if (kind.value < min) { min = kind.value; }
}
_VALUES = new Opcode[min < 0 ? (1-min) : 0];
VALUES = new Opcode[max >= 0 ? (1+max) : 0];
for (Opcode kind : Opcode.values()) {
if (kind.value < 0) {
if (_VALUES[-kind.value] == null) {
_VALUES[-kind.value] = kind;
} else {
assert true: "Must not replace " + _VALUES[-kind.value] + " by " + kind + ". Switch to int-based enum or filter valid.";
}
} else {
if (VALUES[kind.value] == null) {
VALUES[kind.value] = kind;
} else {
assert true: "Must not replace " + VALUES[kind.value] + " by " + kind + ". Switch to int-based enum or filter valid.";
}
}
}
}
}
private final /*uint*/int value;
private Opcode(int val) { this.value = (/*uint*/int)val;}
@Override public final /*uint*/int getValue() { return value;}
//</editor-fold>
};
/*private:*/
private Opcode Op;
private /*const*/ MCExpr /*P*/ LHS;
private /*const*/ MCExpr /*P*/ RHS;
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::MCBinaryExpr">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 415,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 442,
FQN="llvm::MCBinaryExpr::MCBinaryExpr", NM="_ZN4llvm12MCBinaryExprC1ENS0_6OpcodeEPKNS_6MCExprES4_",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExprC1ENS0_6OpcodeEPKNS_6MCExprES4_")
//</editor-fold>
private MCBinaryExpr(Opcode Op, /*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS) {
// : MCExpr(MCExpr::Binary), Op(Op), LHS(LHS), RHS(RHS)
//START JInit
super(MCExpr.ExprKind.Binary);
this.Op = Op;
this.LHS = LHS;
this.RHS = RHS;
//END JInit
}
/*public:*/
/// \name Construction
/// @{
/* *** */
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::create">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp", line = 141,
old_source = "${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp", old_line = 140,
FQN="llvm::MCBinaryExpr::create", NM="_ZN4llvm12MCBinaryExpr6createENS0_6OpcodeEPKNS_6MCExprES4_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr6createENS0_6OpcodeEPKNS_6MCExprES4_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ create(Opcode Opc, /*const*/ MCExpr /*P*/ LHS,
/*const*/ MCExpr /*P*/ RHS, final MCContext /*&*/ Ctx) {
return /*NEW_EXPR [operator new] NM=_ZnwjRN4llvm9MCContextEj*/
/*new (Ctx)*/ $new_uint_MCContext_uint(Ctx, (type$ptr<?> New$Mem)->{
return new MCBinaryExpr(Opc, LHS, RHS);
});
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createAdd">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 424,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 451,
FQN="llvm::MCBinaryExpr::createAdd", NM="_ZN4llvm12MCBinaryExpr9createAddEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr9createAddEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createAdd(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.Add, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createAnd">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 428,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 455,
FQN="llvm::MCBinaryExpr::createAnd", NM="_ZN4llvm12MCBinaryExpr9createAndEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr9createAndEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createAnd(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.And, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createDiv">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 432,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 459,
FQN="llvm::MCBinaryExpr::createDiv", NM="_ZN4llvm12MCBinaryExpr9createDivEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr9createDivEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createDiv(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.Div, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createEQ">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 436,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 463,
FQN="llvm::MCBinaryExpr::createEQ", NM="_ZN4llvm12MCBinaryExpr8createEQEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr8createEQEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createEQ(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.EQ, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createGT">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 440,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 467,
FQN="llvm::MCBinaryExpr::createGT", NM="_ZN4llvm12MCBinaryExpr8createGTEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr8createGTEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createGT(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.GT, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createGTE">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 444,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 471,
FQN="llvm::MCBinaryExpr::createGTE", NM="_ZN4llvm12MCBinaryExpr9createGTEEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr9createGTEEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createGTE(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.GTE, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createLAnd">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 448,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 475,
FQN="llvm::MCBinaryExpr::createLAnd", NM="_ZN4llvm12MCBinaryExpr10createLAndEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr10createLAndEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createLAnd(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.LAnd, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createLOr">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 452,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 479,
FQN="llvm::MCBinaryExpr::createLOr", NM="_ZN4llvm12MCBinaryExpr9createLOrEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr9createLOrEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createLOr(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.LOr, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createLT">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 456,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 483,
FQN="llvm::MCBinaryExpr::createLT", NM="_ZN4llvm12MCBinaryExpr8createLTEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr8createLTEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createLT(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.LT, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createLTE">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 460,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 487,
FQN="llvm::MCBinaryExpr::createLTE", NM="_ZN4llvm12MCBinaryExpr9createLTEEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr9createLTEEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createLTE(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.LTE, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createMod">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 464,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 491,
FQN="llvm::MCBinaryExpr::createMod", NM="_ZN4llvm12MCBinaryExpr9createModEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr9createModEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createMod(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.Mod, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createMul">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 468,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 495,
FQN="llvm::MCBinaryExpr::createMul", NM="_ZN4llvm12MCBinaryExpr9createMulEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr9createMulEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createMul(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.Mul, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createNE">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 472,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 499,
FQN="llvm::MCBinaryExpr::createNE", NM="_ZN4llvm12MCBinaryExpr8createNEEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr8createNEEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createNE(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.NE, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createOr">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 476,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 503,
FQN="llvm::MCBinaryExpr::createOr", NM="_ZN4llvm12MCBinaryExpr8createOrEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr8createOrEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createOr(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.Or, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createShl">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 480,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 507,
FQN="llvm::MCBinaryExpr::createShl", NM="_ZN4llvm12MCBinaryExpr9createShlEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr9createShlEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createShl(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.Shl, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createAShr">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 484,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 511,
FQN="llvm::MCBinaryExpr::createAShr", NM="_ZN4llvm12MCBinaryExpr10createAShrEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr10createAShrEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createAShr(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.AShr, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createLShr">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 488,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 515,
FQN="llvm::MCBinaryExpr::createLShr", NM="_ZN4llvm12MCBinaryExpr10createLShrEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr10createLShrEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createLShr(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.LShr, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createSub">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 492,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 519,
FQN="llvm::MCBinaryExpr::createSub", NM="_ZN4llvm12MCBinaryExpr9createSubEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr9createSubEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createSub(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.Sub, LHS, RHS, Ctx);
}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::createXor">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 496,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 523,
FQN="llvm::MCBinaryExpr::createXor", NM="_ZN4llvm12MCBinaryExpr9createXorEPKNS_6MCExprES3_RNS_9MCContextE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr9createXorEPKNS_6MCExprES3_RNS_9MCContextE")
//</editor-fold>
public static /*const*/ MCBinaryExpr /*P*/ createXor(/*const*/ MCExpr /*P*/ LHS, /*const*/ MCExpr /*P*/ RHS,
final MCContext /*&*/ Ctx) {
return MCBinaryExpr.create(Opcode.Xor, LHS, RHS, Ctx);
}
/// @}
/// \name Accessors
/// @{
/// \brief Get the kind of this binary expression.
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::getOpcode">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 506,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 533,
FQN="llvm::MCBinaryExpr::getOpcode", NM="_ZNK4llvm12MCBinaryExpr9getOpcodeEv",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZNK4llvm12MCBinaryExpr9getOpcodeEv")
//</editor-fold>
public Opcode getOpcode() /*const*/ {
return Op;
}
/// \brief Get the left-hand side expression of the binary operator.
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::getLHS">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 509,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 536,
FQN="llvm::MCBinaryExpr::getLHS", NM="_ZNK4llvm12MCBinaryExpr6getLHSEv",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZNK4llvm12MCBinaryExpr6getLHSEv")
//</editor-fold>
public /*const*/ MCExpr /*P*/ getLHS() /*const*/ {
return LHS;
}
/// \brief Get the right-hand side expression of the binary operator.
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::getRHS">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 512,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 539,
FQN="llvm::MCBinaryExpr::getRHS", NM="_ZNK4llvm12MCBinaryExpr6getRHSEv",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZNK4llvm12MCBinaryExpr6getRHSEv")
//</editor-fold>
public /*const*/ MCExpr /*P*/ getRHS() /*const*/ {
return RHS;
}
/// @}
//<editor-fold defaultstate="collapsed" desc="llvm::MCBinaryExpr::classof">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", line = 516,
old_source = "${LLVM_SRC}/llvm/include/llvm/MC/MCExpr.h", old_line = 543,
FQN="llvm::MCBinaryExpr::classof", NM="_ZN4llvm12MCBinaryExpr7classofEPKNS_6MCExprE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.adtsupport/llvmToClangType ${LLVM_SRC}/llvm/lib/MC/MCExpr.cpp -nm=_ZN4llvm12MCBinaryExpr7classofEPKNS_6MCExprE")
//</editor-fold>
public static boolean classof(/*const*/ MCExpr /*P*/ E) {
return E.getKind() == MCExpr.ExprKind.Binary;
}
@Override public String toString() {
return "" + "Op=" + Op // NOI18N
+ ", LHS=" + "[MCExpr]" // NOI18N
+ ", RHS=" + "[MCExpr]" // NOI18N
+ super.toString(); // NOI18N
}
}
|
C#
|
UTF-8
| 1,808
| 2.796875
| 3
|
[] |
no_license
|
using Async_MVVM.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WpfAutoCompleteControls.Editors;
namespace Async_MVVM
{
internal sealed class SuggestionProvider : ISuggestionProvider
{
public readonly List<CountryListData> countriesList = new List<CountryListData>();
private readonly TimeSpan Delay = TimeSpan.FromSeconds(0);
public SuggestionProvider()
{
DataFetch();
}
public async void DataFetch()
{
try
{
RootObject covidData = await CovidData.GetCovidData();
covidData.Countries.ForEach(country => countriesList.Add(new CountryListData(country.Country)));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
public IEnumerable GetSuggestions(string filter)
{
Thread.Sleep(Delay);
if (string.IsNullOrWhiteSpace(filter))
{
return countriesList;
}
filter = filter.Trim();
return countriesList.Where(x => x.Name.StartsWith(filter, StringComparison.OrdinalIgnoreCase));
/*.Where(x => x.Name.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0);*/
}
IEnumerable ISuggestionProvider.GetSuggestions(string filter)
{
IEnumerable suggestions = GetSuggestions(filter);
return suggestions;
}
}
public class CountryListData
{
public string Name { get; set; }
public CountryListData(string country)
{
this.Name = country;
}
}
}
|
Python
|
UTF-8
| 716
| 2.671875
| 3
|
[] |
no_license
|
#/usr/bin/env python
def bipartilte_matching():
res = 0
import numpy as np
N = int(input())
red = sorted([tuple(map(int, input().split())) for _ in range(N)], reverse=True)
blue = sorted([tuple(map(int, input().split())) for _ in range(N)], reverse=True)
ref = np.zeros((N, N))
for r in range(N):
for b in range(N):
if red[r][0] < blue[b][0] and red[r][1] < blue[b][1]:
ref[r, b] = 1
unsearched_red = list(range(N))
unsearched_blue = list(range(N))
cnt = 0
for b in range(N):
for r in range(N):
if ref[r, b] and (r in unsearched_red) and (b in unsearched_blue):
cnt += 1
unsearched_red.remove(r)
unsearched_blue.remove(b)
print(cnt)
|
Java
|
UTF-8
| 2,190
| 2.5
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import View.viewIntroVsExtro;
import View.viewSensingVsIntution;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
/**
*
* @author Irawansyah
*/
public class controllerSensingVsIntuition extends MouseAdapter implements ActionListener {
private viewSensingVsIntution view;
String Array[] = new String[4];
public controllerSensingVsIntuition(String [] array){
// String b = a;
this.Array[0]=array[0];
view = new viewSensingVsIntution();
view.addActionListener(this);
view.setVisible(true);
}
public controllerSensingVsIntuition() {
view = new viewSensingVsIntution();
view.addActionListener(this);
view.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if(source.equals(view.getBtn3bar())){
view.dispose();
new controllerMenuUser();
} else if(source.equals(view.getBtnLogout())){
view.dispose();
new controllerLogin();
// }else if (source.equals(view.getBack1())){
// view.dispose();
// new controllerIntroVsExtro();
} else if(source.equals(view.getNext())){
Array[1] = view.getIntution();
if (view.getIntution().equals("null")){
}else{
view.dispose();
System.out.println(this.Array[1]);
new controllerThinkingVsFeeling(Array);
}
// if (source.equals(view.getIntution())){
// Array[1].equals(view.getIntution());
// }
// System.out.println(Array[1]);
// view.dispose();
// new controllerThinkingVsFeeling(Array);
// }else if(source.equals(view.getIntution())){
// view.dispose();
// new controllerThinkingVsFeeling();
}
}
}
|
Rust
|
UTF-8
| 774
| 2.765625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
use proc_macro2::TokenStream;
use quote::quote;
pub enum Operand {
Borrowed(TokenStream),
Owned(TokenStream),
}
pub use self::Operand::*;
impl Operand {
pub fn tokens(&self) -> &TokenStream {
match self {
Borrowed(n) | Owned(n) => n,
}
}
pub fn ref_tokens(&self) -> TokenStream {
match self {
Borrowed(n) => n.clone(),
Owned(n) => quote!(&#n),
}
}
pub fn ref_mut_tokens(&self) -> TokenStream {
match self {
Borrowed(n) => n.clone(),
Owned(n) => quote!(&mut #n),
}
}
pub fn owned_tokens(&self) -> TokenStream {
match self {
Borrowed(n) => quote!(*#n),
Owned(n) => n.clone(),
}
}
}
|
JavaScript
|
UTF-8
| 622
| 2.9375
| 3
|
[] |
no_license
|
'use strict';
angular.module('CSApp')
.filter('timeReadable', function() {
return function(input) {
var h = parseInt(input/100);
var m = input%100;
if (h < 10) {
h = '0' + h;
}
if (m < 10) {
m = '0' + m;
}
return h + ':' + m;
};
});
angular.module('CSApp')
.filter('decade', function() {
return function (input) {
return input + "'s";
};
});
angular.module('CSApp')
.filter('sex', function() {
return function (input) {
if (input === 'm') { return 'Male'; }
if (input === 'f') { return 'Female'; }
};
});
|
Rust
|
UTF-8
| 2,734
| 2.953125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/
/
!
Helper
module
to
compute
a
CRC32
checksum
use
std
:
:
io
;
use
std
:
:
io
:
:
prelude
:
:
*
;
use
crc32fast
:
:
Hasher
;
/
/
/
Reader
that
validates
the
CRC32
when
it
reaches
the
EOF
.
pub
struct
Crc32Reader
<
R
>
{
inner
:
R
hasher
:
Hasher
check
:
u32
/
/
/
Signals
if
inner
stores
aes
encrypted
data
.
/
/
/
AE
-
2
encrypted
data
doesn
'
t
use
crc
and
sets
the
value
to
0
.
ae2_encrypted
:
bool
}
impl
<
R
>
Crc32Reader
<
R
>
{
/
/
/
Get
a
new
Crc32Reader
which
checks
the
inner
reader
against
checksum
.
/
/
/
The
check
is
disabled
if
ae2_encrypted
=
=
true
.
pub
(
crate
)
fn
new
(
inner
:
R
checksum
:
u32
ae2_encrypted
:
bool
)
-
>
Crc32Reader
<
R
>
{
Crc32Reader
{
inner
hasher
:
Hasher
:
:
new
(
)
check
:
checksum
ae2_encrypted
}
}
fn
check_matches
(
&
self
)
-
>
bool
{
self
.
check
=
=
self
.
hasher
.
clone
(
)
.
finalize
(
)
}
pub
fn
into_inner
(
self
)
-
>
R
{
self
.
inner
}
}
impl
<
R
:
Read
>
Read
for
Crc32Reader
<
R
>
{
fn
read
(
&
mut
self
buf
:
&
mut
[
u8
]
)
-
>
io
:
:
Result
<
usize
>
{
let
invalid_check
=
!
buf
.
is_empty
(
)
&
&
!
self
.
check_matches
(
)
&
&
!
self
.
ae2_encrypted
;
let
count
=
match
self
.
inner
.
read
(
buf
)
{
Ok
(
0
)
if
invalid_check
=
>
{
return
Err
(
io
:
:
Error
:
:
new
(
io
:
:
ErrorKind
:
:
Other
"
Invalid
checksum
"
)
)
}
Ok
(
n
)
=
>
n
Err
(
e
)
=
>
return
Err
(
e
)
}
;
self
.
hasher
.
update
(
&
buf
[
0
.
.
count
]
)
;
Ok
(
count
)
}
}
#
[
cfg
(
test
)
]
mod
test
{
use
super
:
:
*
;
use
std
:
:
io
:
:
Read
;
#
[
test
]
fn
test_empty_reader
(
)
{
let
data
:
&
[
u8
]
=
b
"
"
;
let
mut
buf
=
[
0
;
1
]
;
let
mut
reader
=
Crc32Reader
:
:
new
(
data
0
false
)
;
assert_eq
!
(
reader
.
read
(
&
mut
buf
)
.
unwrap
(
)
0
)
;
let
mut
reader
=
Crc32Reader
:
:
new
(
data
1
false
)
;
assert
!
(
reader
.
read
(
&
mut
buf
)
.
unwrap_err
(
)
.
to_string
(
)
.
contains
(
"
Invalid
checksum
"
)
)
;
}
#
[
test
]
fn
test_byte_by_byte
(
)
{
let
data
:
&
[
u8
]
=
b
"
1234
"
;
let
mut
buf
=
[
0
;
1
]
;
let
mut
reader
=
Crc32Reader
:
:
new
(
data
0x9be3e0a3
false
)
;
assert_eq
!
(
reader
.
read
(
&
mut
buf
)
.
unwrap
(
)
1
)
;
assert_eq
!
(
reader
.
read
(
&
mut
buf
)
.
unwrap
(
)
1
)
;
assert_eq
!
(
reader
.
read
(
&
mut
buf
)
.
unwrap
(
)
1
)
;
assert_eq
!
(
reader
.
read
(
&
mut
buf
)
.
unwrap
(
)
1
)
;
assert_eq
!
(
reader
.
read
(
&
mut
buf
)
.
unwrap
(
)
0
)
;
/
/
Can
keep
reading
0
bytes
after
the
end
assert_eq
!
(
reader
.
read
(
&
mut
buf
)
.
unwrap
(
)
0
)
;
}
#
[
test
]
fn
test_zero_read
(
)
{
let
data
:
&
[
u8
]
=
b
"
1234
"
;
let
mut
buf
=
[
0
;
5
]
;
let
mut
reader
=
Crc32Reader
:
:
new
(
data
0x9be3e0a3
false
)
;
assert_eq
!
(
reader
.
read
(
&
mut
buf
[
.
.
0
]
)
.
unwrap
(
)
0
)
;
assert_eq
!
(
reader
.
read
(
&
mut
buf
)
.
unwrap
(
)
4
)
;
}
}
|
PHP
|
UTF-8
| 8,005
| 2.515625
| 3
|
[] |
no_license
|
<?php
require_once __DIR__ . '/../static.php';
/**
* May already be defined in TYPO3
*/
if (!function_exists('debug')) {
/**
* @param mixed,...$a
*/
function debug(...$a)
{
$params = func_num_args() == 1 ? $a : func_get_args();
if (class_exists(Debug::class)) {
$debug = Debug::getInstance();
$debug->debug($params);
} elseif (DEVELOPMENT) {
ob_start();
var_dump($params);
$dump = ob_get_clean();
$dump = str_replace("=>\n", ' =>', $dump);
if (!function_exists('xdebug_break')) {
$dump = htmlspecialchars($dump);
}
echo '<pre>' . $dump . '</pre>';
debug_pre_print_backtrace();
}
}
}
if (!function_exists('debugList')) {
function debugList(array $a, $name = null)
{
$debug = Debug::getInstance();
$debug->name = $name;
foreach ($a as &$b) {
$b = $b . '';
}
debug($a);
}
function debugTable(array $a)
{
debug(new slTable($a));
}
function ddie()
{
debug(func_get_args());
die(__FUNCTION__ . '#' . __LINE__);
}
}
if (!function_exists('d')) {
function d($a)
{
$params = func_num_args() == 1 ? $a : func_get_args();
if (DEVELOPMENT) {
ob_start();
var_dump($params);
$dump = ob_get_clean();
$dump = str_replace("=>\n", ' =>', $dump);
if (!function_exists('xdebug_break')) {
$dump = htmlspecialchars($dump);
}
echo '<pre>' . $dump . '</pre>';
}
}
/**
* @param ...$a
*/
function nodebug(...$a)
{
}
function getDebug(...$a)
{
$params = func_get_args();
$debug = Debug::getInstance();
$dh = new DebugHTML($debug);
$content = $dh->printStyles();
if (ifsetor($params[1]) === DebugHTML::LEVELS) {
$levels = ifsetor($params[2]);
$params[1] = $levels;
}
$content .= call_user_func_array([$dh, 'view_array'], $params);
return $content;
}
/**
* @param ..$a
* @noinspection ForgottenDebugOutputInspection
*/
function pre_print_r(...$a)
{
if (PHP_SAPI !== 'cli') {
echo '<pre class="pre_print_r" style="white-space: pre-wrap;">';
print_r(func_num_args() === 1 ? $a : func_get_args());
echo '</pre>';
} else {
print_r(func_num_args() === 1 ? $a : func_get_args());
echo PHP_EOL;
}
}
function get_print_r(...$a)
{
return '<pre class="pre_print_r" style="white-space: pre-wrap;">' .
print_r($a, true) .
'</pre>';
}
/** @noinspection ForgottenDebugOutputInspection */
function pre_var_dump(...$a)
{
echo '<pre class="pre_var_dump" style="white-space: pre-wrap; font-size: 8pt;">';
var_dump(func_num_args() === 1 ? $a : func_get_args());
echo '</pre>';
}
function debug_once(...$a)
{
static $used = null;
if (is_null($used)) {
$used = [];
}
$trace = debug_backtrace();
array_shift($trace); // debug_once itself
$first = array_shift($trace);
$key = $first['file'] . '.' . $first['line'];
if (!ifsetor($used[$key])) {
$v = func_get_args();
//$v[] = $key;
call_user_func_array('debug', $v);
$used[$key] = true;
}
}
function debug_size(...$a)
{
if (is_object($a)) {
$vals = get_object_vars($a);
$keys = array_keys($vals);
} else {
$vals = $a;
$keys = array_keys($a);
}
$assoc = [];
foreach ($keys as $key) {
$sxe = $vals[$key];
if ($sxe instanceof SimpleXMLElement) {
$sxe = $sxe->asXML();
}
//$len = strlen(serialize($vals[$key]));
$len = strlen(json_encode($sxe));
//$len = gettype($vals[$key]) . ' '.get_class($vals[$key]);
$assoc[$key] = $len;
}
debug($assoc);
}
function debug_get_backtrace()
{
ob_start();
if (phpversion() >= '5.3.6') {
debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
} else {
debug_print_backtrace();
}
$content = ob_get_clean();
$content = str_replace(dirname(getcwd()), '', $content);
$content = str_replace('C:\\Users\\' . getenv('USERNAME') . '\\AppData\\Roaming\\Composer\\vendor\\phpunit\\phpunit\\src\\', '', $content);
return $content;
}
function debug_pre_print_backtrace()
{
if (DEVELOPMENT) {
require_once __DIR__ . '/../HTTP/Request.php';
if (!Request::isCLI()) {
print '<pre style="
white-space: pre-wrap;
background: #eeeeee;
border-radius: 5px;
padding: 0.5em;
">';
}
echo debug_get_backtrace();
if (!Request::isCLI()) {
print '</pre>';
}
}
}
/**
* http://php.net/manual/en/function.error-reporting.php#65884
* @param int $value
* @return string
*/
function error2string($value)
{
$level_names = [
E_ERROR => 'E_ERROR',
E_WARNING => 'E_WARNING',
E_PARSE => 'E_PARSE',
E_NOTICE => 'E_NOTICE',
E_CORE_ERROR => 'E_CORE_ERROR',
E_CORE_WARNING => 'E_CORE_WARNING',
E_COMPILE_ERROR => 'E_COMPILE_ERROR',
E_COMPILE_WARNING => 'E_COMPILE_WARNING',
E_USER_ERROR => 'E_USER_ERROR',
E_USER_WARNING => 'E_USER_WARNING',
E_USER_NOTICE => 'E_USER_NOTICE'];
if (defined('E_STRICT')) {
$level_names[E_STRICT] = 'E_STRICT';
}
$levels = [];
if (($value & E_ALL) == E_ALL) {
$levels[] = 'E_ALL';
$value &= ~E_ALL;
}
foreach ($level_names as $level => $name) {
if (($value & $level) == $level) {
$levels[] = $name;
}
}
return implode(' | ', $levels);
}
/**
* similar to gettype() but return more information depending on data type in HTML
* @param mixed $something
* @param bool $withHash
* @param null $isCLI
* @return HTMLTag
*/
function typ($something, $withHash = true, $isCLI = null)
{
if ($isCLI === null) {
$isCLI = Request::isCLI();
}
$type = gettype($something);
if ($type === 'object') {
if ($withHash) {
$hash = md5(spl_object_hash($something));
$hash = substr($hash, 0, 6);
require_once __DIR__ . '/../HTTP/Request.php';
if (!Request::isCLI()) {
require_once __DIR__ . '/../Value/Color.php';
$color = new Color('#' . $hash);
$complement = $color->getComplement();
if (!$isCLI) {
$hash = new HTMLTag('span', [
'class' => 'tag',
'style' => 'background: ' . $color . '; color: ' . $complement,
], $hash);
}
}
$typeName = get_class($something) . '#' . $hash;
} else {
$typeName = get_class($something);
}
} else {
$typeName = $type;
}
$bulma = [
'string' => 'is-primary',
'NULL' => 'is-danger',
'object' => 'is-warning',
'array' => 'is-link',
'boolean' => 'is-info',
'integer' => 'is-success',
'resource' => '',
];
$class = ifsetor($bulma[$type]) . ' tag';
if ($type === 'string') {
$typeName .= '[' . strlen($something) . ']';
}
if ($type === 'array') {
$typeName .= '[' . sizeof($something) . ']';
}
if (!Request::isCLI()) {
return new HTMLTag('span', ['class' => $class], $typeName, true);
}
return $typeName;
}
/**
* @param array|mixed $something
* @return array|htmlString
*/
function gettypes($something)
{
if (is_array($something)) {
$types = [];
foreach ($something as $key => $element) {
$types[$key] = strip_tags(typ($element));
}
return $types;
} else {
return typ($something);
}
//return json_encode($types, JSON_PRETTY_PRINT);
}
}
function invariant($value, $message = null)
{
if (!$value) {
throw new Exception($message ?: 'Invariant failure in ' . Debug::getCaller());
}
}
function llog(...$vars)
{
$caller = Debug::getCaller();
$jsonOptions = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
if (defined('JSON_UNESCAPED_LINE_TERMINATORS')) {
$jsonOptions |= JSON_UNESCAPED_LINE_TERMINATORS;
}
$vars = array_map(static function ($el) {
if (is_object($el) && !($el instanceof stdClass)) {
return trim(strip_tags(typ($el)));
}
return $el;
}, $vars);
if (count($vars) === 1) {
$output = json_encode([
'type' => gettype(first($vars)),
'value' => first($vars)
], $jsonOptions);
} else {
$output = json_encode($vars, $jsonOptions);
}
if (strlen($output) > 80) {
$output = json_encode(count($vars) === 1
? [
'type' => gettype(first($vars)),
'value' => first($vars)
] : $vars, $jsonOptions | JSON_PRETTY_PRINT);
}
error_log($caller . ' ' . $output);
}
|
Python
|
UTF-8
| 3,048
| 2.8125
| 3
|
[] |
no_license
|
from flask import Flask, render_template, redirect, request, session, flash
from vocabchallenge import app, database, mp
import random
@app.route('/game/<lang>', methods=('post', 'get'))
def game(lang):
#if the player is currently in a game
if session.pop('ingame',False):
#word and definition retrieved from database
if 'wordnum' in session:
#user has submitted feedback
if 'wordguess' in request.form:
try:
wordguess = int(request.form['wordguess']) - 1
except ValueError:
wordguess = -1
#user has guessed the word correctly
if wordguess == session.pop('wordnum'):
flash('Correct!')
session['ingame'] = True
session['score'] += 1
return redirect('/game/'+lang)
#user has incorrectly guessed the word
else:
session['lives'] -= 1
#tell the user if they are entering the wrong input
if 0<=wordguess<=3:
flash('Incorrect, the correct answer was: '+session['word'])
else:
flash('Please only enter numbers between 1-4')
#player has no guesses remaining
if session['lives'] < 1:
return redirect('/game_ended')
session['ingame'] = True
return redirect('/game/'+lang)
#user has not yet submitted feedback
else:
session['ingame'] = True
return render_template('game.html', words=session['words'], definition=session['definition'], lang=lang, lives=session['lives'], score=session['score'])
#word and definition not yet retrieved from database
else:
session['ingame'] = True
session['word'], session['definition'] = database.get_entry(lang)
session['words'] = database.get_padding_words(lang, session['word'] ,3)
session['wordnum'] = int(round(random.uniform(0,3)))
session['words'].insert(session['wordnum'] ,session['word'])
return render_template('game.html', words=session['words'], definition=session['definition'], lang=lang, lives=session['lives'], score=session['score'])
#if the player is not yet in a game initialize variables for a new game
else:
#note that this value is set to true before the user is redirected to /game. This is so that the game is ended if the user quits the game (consider implementing this in a better way)
session['ingame'] = True
session['language'] = lang
session['score'] = 0
session['lives'] = 3
#so each new quiz starts with a new word
session.pop('word', None)
session.pop('wordnum', None)
mp.track(session['username'],'new game: '+lang)
return redirect('/game/'+lang)
|
C++
|
UTF-8
| 6,964
| 3.03125
| 3
|
[] |
no_license
|
#include "Mesh.h"
using namespace DirectX;
/// <summary>
/// Constructor for a procedurally generated mesh.
/// </summary>
/// <param name="vertices">array of indexed vertices</param>
/// <param name="numVertices">number of vertices</param>
/// <param name="indices">array of indices</param>
/// <param name="numIndices">number of indices</param>
/// <param name="device">the device to create the buffers on</param>
Mesh::Mesh(const Vertex* vertices,
int numVertices,
int* indices,
int numIndices,
ID3D11Device* device)
{
//create vertex buffer
D3D11_BUFFER_DESC vbd;
vbd.Usage = D3D11_USAGE_IMMUTABLE;
vbd.ByteWidth = sizeof(Vertex) * numVertices;
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.CPUAccessFlags = 0;
vbd.MiscFlags = 0;
vbd.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA vertexData;
vertexData.pSysMem = vertices;
HR(device->CreateBuffer(&vbd, &vertexData, &vertexBuffer));
// create index buffer
D3D11_BUFFER_DESC ibd;
ibd.Usage = D3D11_USAGE_IMMUTABLE;
ibd.ByteWidth = sizeof(int) * numIndices;
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
ibd.MiscFlags = 0;
ibd.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA indexData;
indexData.pSysMem = indices;
HR(device->CreateBuffer(&ibd, &indexData, &indexBuffer));
// we'll need this to draw the mesh
indexCount = numIndices;
}
/// <summary>
/// Constructor for building a mesh from an OBJ format file.
/// </summary>
/// <param name="filename">name of obj file</param>
/// <param name="device">the device to create the buffers on</param>
Mesh::Mesh(char* filename, ID3D11Device* device)
{
// File input object
std::ifstream obj(filename); // <-- Replace filename with your parameter
// Check for successful open
if (!obj.is_open())
return;
// Variables used while reading the file
std::vector<XMFLOAT3> positions; // Positions from the file
std::vector<XMFLOAT3> normals; // Normals from the file
std::vector<XMFLOAT2> uvs; // UVs from the file
std::vector<Vertex> verts; // Verts we're assembling
std::vector<UINT> indices; // Indices of these verts
unsigned int triangleCounter = 0; // Count of triangles/indices
char chars[100]; // String for line reading
// Still good?
while (obj.good())
{
// Get the line (100 characters should be more than enough)
obj.getline(chars, 100);
// Check the type of line
if (chars[0] == 'v' && chars[1] == 'n')
{
// Read the 3 numbers directly into an XMFLOAT3
XMFLOAT3 norm;
sscanf_s(
chars,
"vn %f %f %f",
&norm.x, &norm.y, &norm.z);
// Add to the list of normals
normals.push_back(norm);
}
else if (chars[0] == 'v' && chars[1] == 't')
{
// Read the 2 numbers directly into an XMFLOAT2
XMFLOAT2 uv;
sscanf_s(
chars,
"vt %f %f",
&uv.x, &uv.y);
// Add to the list of uv's
uvs.push_back(uv);
}
else if (chars[0] == 'v')
{
// Read the 3 numbers directly into an XMFLOAT3
XMFLOAT3 pos;
sscanf_s(
chars,
"v %f %f %f",
&pos.x, &pos.y, &pos.z);
// Add to the positions
positions.push_back(pos);
}
else if (chars[0] == 'f')
{
// Read the 9 face indices into an array
unsigned int i[9];
sscanf_s(
chars,
"f %d/%d/%d %d/%d/%d %d/%d/%d",
&i[0], &i[1], &i[2],
&i[3], &i[4], &i[5],
&i[6], &i[7], &i[8]);
// - Create the verts by looking up
// corresponding data from vectors
// - OBJ File indices are 1-based, so
// they need to be adusted
Vertex v1;
v1.Position = positions[i[0] - 1];
v1.Uv = uvs[i[1] - 1];
v1.Normal = normals[i[2] - 1];
Vertex v2;
v2.Position = positions[i[3] - 1];
v2.Uv = uvs[i[4] - 1];
v2.Normal = normals[i[5] - 1];
Vertex v3;
v3.Position = positions[i[6] - 1];
v3.Uv = uvs[i[7] - 1];
v3.Normal = normals[i[8] - 1];
// Add the verts to the vector
verts.push_back(v1);
verts.push_back(v2);
verts.push_back(v3);
// Add three more indices
indices.push_back(triangleCounter++);
indices.push_back(triangleCounter++);
indices.push_back(triangleCounter++);
}
}
// Close
obj.close();
// - At this point, "verts" is a vector of Vertex structs, and can be used
// directly to create a vertex buffer: &verts[0] is the first vert
// - The vector "indices" is similar. It's a vector of unsigned ints and
// can be used directly for the index buffer: &indices[0] is the first int
// - "triangleCounter" is BOTH the number of vertices and the number of indices
//create vertex buffer
D3D11_BUFFER_DESC vbd;
vbd.Usage = D3D11_USAGE_IMMUTABLE;
vbd.ByteWidth = sizeof(Vertex) * triangleCounter;
vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbd.CPUAccessFlags = 0;
vbd.MiscFlags = 0;
vbd.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA vertexData;
vertexData.pSysMem = &verts[0];
HR(device->CreateBuffer(&vbd, &vertexData, &vertexBuffer));
// create index buffer
D3D11_BUFFER_DESC ibd;
ibd.Usage = D3D11_USAGE_IMMUTABLE;
ibd.ByteWidth = sizeof(int) * triangleCounter;
ibd.BindFlags = D3D11_BIND_INDEX_BUFFER;
ibd.CPUAccessFlags = 0;
ibd.MiscFlags = 0;
ibd.StructureByteStride = 0;
D3D11_SUBRESOURCE_DATA indexData;
indexData.pSysMem = &indices[0]; // <--- why doesn't vector::data work here?
HR(device->CreateBuffer(&ibd, &indexData, &indexBuffer));
// we'll need this to draw the mesh
indexCount = triangleCounter;
}
/// <summary>
/// Gets the pointer to the ID3D11Buffer storing the indexed vertices for this mesh.
/// </summary>
/// <returns>pointer to the vertex buffer</returns>
ID3D11Buffer* Mesh::GetVertexBuffer() { return vertexBuffer; }
/// <summary>
/// Gets the pointer to the ID3D11Buffer storing the indices for this mesh.
/// </summary>
/// <returns>pointer to the index buffer</returns>
ID3D11Buffer* Mesh::GetIndexBuffer() { return indexBuffer; }
/// <summary>
/// Gets the number of indices in the index buffer.
/// </summary>
/// <returns>number of vertices in the index buffer</returns>
int Mesh::GetIndexCount() { return indexCount; }
// draw the mesh to the screen
// allows for reusability of the basic steps required to draw the mesh,
// and cleans up the main draw method so it's a bit clearer
/// <summary>
/// Draws the mesh.
/// </summary>
/// <param name="context">the context to use for drawing the mesh</param>
void Mesh::Draw(ID3D11DeviceContext* context)
{
// set the buffers to be used
UINT stride = sizeof(Vertex);
UINT offset = 0;
context->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset);
context->IASetIndexBuffer(indexBuffer, DXGI_FORMAT_R32_UINT, 0);
//do the actual draw operation
context->DrawIndexed(indexCount, 0, 0);
}
/// <summary>
/// Destructor. Releases the vertex and index buffers on the graphics card.
/// </summary>
Mesh::~Mesh()
{
//release the buffers (this should be the only reference to them (we hope))
vertexBuffer->Release();
indexBuffer->Release();
}
|
C
|
UTF-8
| 227
| 3.875
| 4
|
[] |
no_license
|
/* 1> Accept a char input from the user and display it on the console */
#include <stdio.h>
void main()
{
char c;
printf("Enter a char: \n");
scanf("%c", &c);
printf("The character you entered is: %c\n", c);
}
|
C++
|
UTF-8
| 678
| 2.8125
| 3
|
[] |
no_license
|
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
int main(){
string a,b,c;
cin>>a>>b;
int lena=a.length(),lenb=b.length();
for(int i=0;i<=lena/2-1;i++){
swap(a[i],a[lena-1-i]);
}
for(int i=0;i<=lenb/2-1;i++){
swap(b[i],b[lenb-1-i]);
}
if(lena<lenb){
a.append(lenb-lena,'0');
}
else{
b.append(lena-lenb,'0');
}
int temp=0;
char str[13]={'0','1','2','3','4','5','6','7','8','9','J','Q','K'};
for(int i=0;i<a.length();i++){
if(i%2==0){
c+=str[(a[i]-'0'+b[i]-'0')%13];
}else{
temp=b[i]-a[i];
if(temp<0)temp+=10;
c+=str[temp];
}
}
for(int i=c.length()-1;i>=0;i--){
cout<<c[i];
}
return 0;
}
|
C++
|
UTF-8
| 4,572
| 2.90625
| 3
|
[] |
no_license
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "header-file.h"
#include <windows.h>
#include <conio.h>
NUMEROS n;
void introducao()
{
printf("Ol\240, Seja muito bem vindo!\nEsse \202 o Lord of Mathematics 6\n");
printf("\n(Qualquer duvida digite: ?)\n");
}
void primeiroValor()
{
printf("\n-----------------------------------");
printf("\n\nDigite o primeiro valor: ");
scanf("%f",& n.num1);
}
void operacao()
{
int flag = 0;
printf("\nDigite a opera\207\706o: ");
while(flag == 0)
{
scanf("%c",& n.letra);
switch (n.letra)
{
case '+':
funcAdicao();
flag = 1;
break;
case '-':
funcSubtracao();
flag = 1;
break;
case '*':
funcMultiplicacao();
flag = 1;
break;
case '/':
funcDivisao();
flag = 1;
break;
case '%':
funcDivisao();
flag = 1;
break;
case 's':
seno();
break;
case 'S':
seno();
break;
case 'c':
cosseno();
break;
case 'C':
cosseno();
break;
case 't':
tangente();
break;
case 'T':
tangente();
break;
case 'l':
loga();
break;
case 'L':
loga();
break;
case 'r':
raiz();
break;
case 'R':
raiz();
break;
case 'p':
poten();
break;
case 'P':
poten();
break;
case 'z':
limpaTela();
break;
case 'Z':
limpaTela();
break;
case 'x':
sobreNos();
break;
case 'X':
sobreNos();
break;
case '?':
duvida();
break;
default:
flag = 0;
break;
}
}
}
void sobreNos()
{
system("cls");
printf("Nossa empresa tem como principal principio o desenvolvimento de aplica\207\744es simples, \240geis\ne seguras para a ajudar voc\210 usu\240rio! O Lord of Mathematics 6 \202 o m\240ximo da tecnologia,\nutilizando os m\202todos mais modernos e poderosos para deixar essa vers\706o extremamente intuitiva\ne moderna.");
printf("\n\nFeito por: Astronaut.lab\nProjeto liderado por: Everton Dias\nFeito em: novembro / 2018\n");
primeiroValor();
operacao();
}
void limpaTela()
{
system("cls");
introducao();
primeiroValor();
operacao();
}
void duvida()
{
printf("\nA nossa calculadora \202 muito simples de ser usada!\nBasta digitar o numero e a opera\207\706o:\n\n");
printf(" Adi\207\706o: + Multiplica\207\706o: * \n");
printf(" Subtra\207\706o: - Divis\706o: / \n");
printf(" Seno: S Cosseno: C \n");
printf(" Tangente: T Logaritmo: L \n");
printf(" Raiz Quadrada: R Potencia\207\706o: P \n");
printf(" Limpar a tela: Z Sobre n\242s: X\n");
primeiroValor();
operacao();
}
void seno()
{
float seno = sin(n.num1);
printf("\nValor de seno de %.2f = %f \n", n.num1, seno);
primeiroValor();
operacao();
}
void cosseno()
{
float cosseno = cos(n.num1);
printf("\nValor de cosseno de %.2f = %f \n", n.num1, cosseno);
primeiroValor();
operacao();
}
void tangente()
{
float tangente = tan(n.num1);
printf("\nValor de tangente de %.2f = %f \n", n.num1, tangente);
primeiroValor();
operacao();
}
void loga()
{
float logaritmo = log(n.num1);
printf("\nValor do logaritmo natural de %.2f = %f \n", n.num1, logaritmo);
primeiroValor();
operacao();
}
void raiz()
{
float raiz = sqrt(n.num1);
printf("\nValor da raiz quadrada de %.2f = %f \n", n.num1, raiz);
primeiroValor();
operacao();
}
void poten()
{
printf("\nDigite o valor que deseja elevar %.0f: ", n.num1);
scanf("%f",& n.num2);
n.resul = pow(n.num1, n.num2);
printf("\nValor de %.2f elevado a %.2f = %f \n", n.num1, n.num2,n.resul);
primeiroValor();
operacao();
}
void funcResul()
{
printf("\n\nA conta feita foi essa:");
printf("\n\n %.0f\n%c %.0f\n---------\n %.0f", n.num1, n.letra, n.num2, n.resul);
printf("\n\nResultado: %f\n", n.resul);
}
void segundoValor()
{
printf("\n%.3f %c ", n.num1, n.letra);
scanf("%f",& n.num2);
}
void funcAdicao()
{
segundoValor();
n.resul = n.num1 + n.num2;
funcResul();
primeiroValor();
operacao();
}
void funcSubtracao()
{
segundoValor();
n.resul = n.num1 - n.num2;
funcResul();
primeiroValor();
operacao();
}
void funcMultiplicacao()
{
segundoValor();
n.resul = n.num1 * n.num2;
funcResul();
primeiroValor();
operacao();
}
void funcDivisao()
{
segundoValor();
n.resul = n.num1 / n.num2;
printf("\n\n%.2f |_%.2f\n %.2f", n.num1, n.num2, n.resul);
printf("\n\nResultado: %f\n", n.resul);
primeiroValor();
operacao();
}
void padrao()
{
system("mode con:cols=95 lines=30");
system("color 1F");
}
int main()
{
padrao();
introducao();
primeiroValor();
operacao();
}
|
C++
|
UTF-8
| 765
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
#pragma once
#include <archive.h>
#include <archive_entry.h>
#include "arcpp/entry.hpp"
namespace arcpp {
/**
* @brief To iterate over all entries in the archive.
*
*/
class iterator {
public:
iterator(::archive* ar);
/**
* @brief Check if the iterator still has files to read.
*
* @return true If there are no more files left in the archive
*/
bool done() const;
/**
* @brief Get the entry at the current iterator point
*
* @return entry
*/
entry get() const;
/**
* @brief Move the iterator pointer to the next entry.
*
* @return iterator& *this
*/
iterator& next();
/**
* @brief Move the iterator to the first entry.
*
*/
void reset();
private:
::archive* m_ar;
archive_entry* m_entry;
bool m_ok;
};
}
|
Java
|
UTF-8
| 1,650
| 1.789063
| 2
|
[] |
no_license
|
package project.FleaMarket.P002.D006.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import project.FleaMarket.P002.D006.dao.F_P002_D006DAO;
import project.FleaMarket.P002.D006.vo.F_P002_D006VO;
@Service("F_P002_D006Service")
@Transactional(propagation = Propagation.REQUIRED)
public class F_P002_D006ServiceImpl implements F_P002_D006Service {
@Autowired
private F_P002_D006DAO d006DAO;
@Override
public List<F_P002_D006VO> searchList(Map<String, Object> searchMap) throws DataAccessException {
List<F_P002_D006VO> list = d006DAO.searchList(searchMap);
return list;
}
@Override
public List<F_P002_D006VO> searchMod(Map<String, Object> searchMap) throws DataAccessException {
List<F_P002_D006VO> list = d006DAO.searchMod(searchMap);
return list;
}
@Override
public List<F_P002_D006VO> searchAdd() throws DataAccessException {
// TODO Auto-generated method stub
return null;
}
@Override
public void updateMember(Map<String, Object> datahMap) throws Exception {
d006DAO.updateMember(datahMap);
}
@Override
public void insertMember(Map<String, Object> datahMap) throws Exception {
d006DAO.insertMember(datahMap);
}
@Override
public void deleteMember(Map<String, Object> datahMap) throws Exception {
d006DAO.deleteMember(datahMap);
}
}
|
Python
|
UTF-8
| 350
| 3.078125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
# x= float(8)
# y = 8.4
# name = 'cınar'
# isonline = True
# print(type(x))
# print(type(y))
# print(type(name))
# print(type(isonline))
pi=3.14
r =float(input('dairenin yarıcapını giriniz:'))
dairenin_cevresi = 2*pi*r
dairenin_alani = pi*r*r
print('dairenin_cevresi:', dairenin_cevresi)
print('dairenin alanı: ', dairenin_alani )
|
PHP
|
UTF-8
| 2,080
| 2.96875
| 3
|
[] |
no_license
|
<?php
namespace WordPressDotOrg\FiveForTheFuture\PledgeForm;
use WordPressDotOrg\FiveForTheFuture;
use WordPressDotOrg\FiveForTheFuture\Company;
use WordPressDotOrg\FiveForTheFuture\CompanyMeta;
use WP_Error;
defined( 'WPINC' ) || die();
function render_shortcode( $attributes, $content ) {
$action = filter_input( INPUT_POST, 'action' );
$messages = [];
$complete = false;
$html = '';
if ( 'Submit' === $action ) {
$processed = process_form( $_POST );
if ( is_wp_error( $processed ) ) {
$messages = array_merge( $messages, $processed->get_error_messages() );
} elseif ( 'success' === $processed ) {
$complete = true;
}
}
if ( $complete ) {
$html = wpautop( __( 'Thank you for your submission.', 'wporg' ) );
} else {
ob_start();
require FiveForTheFuture\PATH . 'views/pledge-form.php';
$html = ob_get_clean();
}
return $html;
}
add_shortcode( 'five_for_the_future_pledge_form', __NAMESPACE__ . '\render_shortcode' );
/**
*
*
* @param array $form_values
*
* @return string|WP_Error String "success" if the form processed correctly. Otherwise WP_Error.
*/
function process_form( array $form_values ) {
$required_fields = CompanyMeta\has_required_company_meta( $form_values );
if ( is_wp_error( $required_fields ) ) {
return $required_fields;
}
$name = sanitize_meta(
CompanyMeta\META_PREFIX . 'company-name',
$form_values['company-name'],
'post',
Company\CPT_SLUG
);
$created = create_new_company( $name );
if ( is_wp_error( $created ) ) {
return $created;
}
CompanyMeta\save_company_meta( $created, $form_values );
// save teams contirbuted to as terms
return 'success';
}
/**
*
*
* @param string $name The name of the company to use as the post title.
*
* @return int|WP_Error Post ID on success. Otherwise WP_Error.
*/
function create_new_company( $name ) {
$args = [
'post_type' => Company\CPT_SLUG,
'post_title' => $name,
'post_status' => 'pending',
'post_author' => get_current_user_id(), // TODO is this how we want to do this?
];
return wp_insert_post( $args, true );
}
|
Java
|
UTF-8
| 5,775
| 1.757813
| 2
|
[] |
no_license
|
package com.yondervision.yfmap.result.hulunbuir;
/**
*
*/
public class HulunbuirAppApi0100801Result {
/** 个人姓名*/
private String accname = "";
/** 出生日期 */
private String birthday = "";
/** 证件号码*/
private String certinum = "";
/** 证件类型*/
private String certitype = "";
/** 学历 */
private String eduexp = "";
/** 家庭住址 */
private String famaddr = "";
/** 家庭月收入 */
private String fammonthinc = "";
/** 手机 */
private String handset = "";
/** 职务 */
private String headship = "";
/** 个人账户状态 */
private String indiaccstate = "";
/** 个人账户类型 */
private String indiacctype = "";
/** 婚姻状况 */
private String marstatus = "";
/** 短信签约标志 */
private String msgflag = "";
/** 职业 */
private String occupation = "";
/** 开户日期 */
private String opnaccdate = "";
/** 电话 */
private String phone = "";
/** 通用客户号 */
private String pubcustid = "";
/** 性别 */
private String sex = "";
/** 职称 */
private String techpost = "";
/** 单位名称 */
private String unitaccname = "";
/** 单位账号 */
private String unitaccnum = "";
/** 单位账号 */
private String attworkdate = "";
/**
* 交易代码
*/
private String transCode="";
/**
* 返回日期
*/
private String sendDate="";
/**
* 返回时间
*/
private String sendTime="";
/**
* 发送方流水号
*/
private String sendSeqno="";
/**
* 安全标识
*/
private String key="";
/**
* 中心流水号
*/
private String centerSeqno="";
/**
* 响应码
*/
private String recode="";
/**
* 响应信息
*/
private String msg="";
public String getTransCode() {
return transCode;
}
public void setTransCode(String transCode) {
this.transCode = transCode;
}
public String getSendDate() {
return sendDate;
}
public void setSendDate(String sendDate) {
this.sendDate = sendDate;
}
public String getSendTime() {
return sendTime;
}
public void setSendTime(String sendTime) {
this.sendTime = sendTime;
}
public String getSendSeqno() {
return sendSeqno;
}
public void setSendSeqno(String sendSeqno) {
this.sendSeqno = sendSeqno;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getCenterSeqno() {
return centerSeqno;
}
public void setCenterSeqno(String centerSeqno) {
this.centerSeqno = centerSeqno;
}
public String getRecode() {
return recode;
}
public void setRecode(String recode) {
this.recode = recode;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getAccname() {
return accname;
}
public void setAccname(String accname) {
this.accname = accname;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getCertinum() {
return certinum;
}
public void setCertinum(String certinum) {
this.certinum = certinum;
}
public String getCertitype() {
return certitype;
}
public void setCertitype(String certitype) {
this.certitype = certitype;
}
public String getEduexp() {
return eduexp;
}
public void setEduexp(String eduexp) {
this.eduexp = eduexp;
}
public String getFamaddr() {
return famaddr;
}
public void setFamaddr(String famaddr) {
this.famaddr = famaddr;
}
public String getFammonthinc() {
return fammonthinc;
}
public void setFammonthinc(String fammonthinc) {
this.fammonthinc = fammonthinc;
}
public String getHandset() {
return handset;
}
public void setHandset(String handset) {
this.handset = handset;
}
public String getHeadship() {
return headship;
}
public void setHeadship(String headship) {
this.headship = headship;
}
public String getIndiaccstate() {
return indiaccstate;
}
public void setIndiaccstate(String indiaccstate) {
this.indiaccstate = indiaccstate;
}
public String getIndiacctype() {
return indiacctype;
}
public void setIndiacctype(String indiacctype) {
this.indiacctype = indiacctype;
}
public String getMarstatus() {
return marstatus;
}
public void setMarstatus(String marstatus) {
this.marstatus = marstatus;
}
public String getMsgflag() {
return msgflag;
}
public void setMsgflag(String msgflag) {
this.msgflag = msgflag;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getOpnaccdate() {
return opnaccdate;
}
public void setOpnaccdate(String opnaccdate) {
this.opnaccdate = opnaccdate;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPubcustid() {
return pubcustid;
}
public void setPubcustid(String pubcustid) {
this.pubcustid = pubcustid;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getTechpost() {
return techpost;
}
public void setTechpost(String techpost) {
this.techpost = techpost;
}
public String getUnitaccname() {
return unitaccname;
}
public void setUnitaccname(String unitaccname) {
this.unitaccname = unitaccname;
}
public String getUnitaccnum() {
return unitaccnum;
}
public void setUnitaccnum(String unitaccnum) {
this.unitaccnum = unitaccnum;
}
public String getAttworkdate() {
return attworkdate;
}
public void setAttworkdate(String attworkdate) {
this.attworkdate = attworkdate;
}
}
|
Markdown
|
UTF-8
| 5,280
| 2.765625
| 3
|
[
"MIT",
"CC-BY-4.0"
] |
permissive
|
---
title: Frequently asked questions about Azure Cosmos DB point-in-time restore feature.
description: This article lists frequently asked questions about the Azure Cosmos DB point-in-time restore feature that is achieved by using the continuous backup mode.
author: kanshiG
ms.service: cosmos-db
ms.topic: conceptual
ms.date: 02/01/2021
ms.author: govindk
ms.reviewer: sngun
---
# Frequently asked questions on the Azure Cosmos DB point-in-time restore feature (Preview)
[!INCLUDE[appliesto-sql-mongodb-api](includes/appliesto-sql-mongodb-api.md)]
> [!IMPORTANT]
> The point-in-time restore feature(continuous backup mode) for Azure Cosmos DB is currently in public preview.
> This preview version is provided without a service level agreement, and it's not recommended for production workloads. Certain features might not be supported or might have constrained capabilities.
> For more information, see [Supplemental Terms of Use for Microsoft Azure Previews](https://azure.microsoft.com/support/legal/preview-supplemental-terms/).
This article lists frequently asked questions about the Azure Cosmos DB point-in-time restore functionality(Preview) that is achieved by using the continuous backup mode.
## How much time does it takes to restore?
The restore duration dependents on the size of your data.
### Can I submit the restore time in local time?
The restore may not happen depending on whether the key resources like databases or containers existed at that time. You can verify by entering the time and looking at the selected database or container for a given time. If you see no resources exist to restore, then the restore process doesn't work.
### How can I track if an account is being restored?
After you submit the restore command, and wait on the same page, after the operation is complete, the status bar shows successfully restored account message. You can also search for the restored account and [track the status of account being restored](continuous-backup-restore-portal.md#track-restore-status). While restore is in progress, the status of the account will be *Creating*, after the restore operation completes, the account status will change to *Online*.
Similarly for PowerShell and CLI, you can track the progress of restore operation by executing `az cosmosdb show` command as follows:
```azurecli-interactive
az cosmosdb show --name "accountName" --resource-group "resourceGroup"
```
The provisioningState shows *Succeeded* when the account is online.
```json
{
"virtualNetworkRules": [],
"writeLocations" : [
{
"documentEndpoint": "https://<accountname>.documents.azure.com:443/",
"failoverpriority": 0,
"id": "accountName" ,
"isZoneRedundant" : false,
"locationName": "West US 2",
"provisioningState": "Succeeded"
}
]
}
```
### How can I find out whether an account was restored from another account?
Run the `az cosmosdb show` command, in the output, you can see that the value of `createMode` property. If the value is set to **Restore**. it indicates that the account was restored from another account. The `restoreParameters` property has further details such as `restoreSource`, which has the source account ID. The last GUID in the `restoreSource` parameter is the instanceId of the source account.
For example, in the following output, the source account's instance ID is *7b4bb-f6a0-430e-ade1-638d781830cc*
```json
"restoreParameters": {
"databasesToRestore" : [],
"restoreMode": "PointInTime",
"restoreSource": "/subscriptions/2a5b-f6a0-430e-ade1-638d781830dd/providers/Microsoft.DocumentDB/locations/westus/restorableDatabaseAccounts/7b4bb-f6a0-430e-ade1-638d781830cc",
"restoreTimestampInUtc": "2020-06-11T22:05:09Z"
}
```
### What happens when I restore a shared throughput database or a container within a shared throughput database?
The entire shared throughput database is restored. You cannot choose a subset of containers in a shared throughput database for restore.
### What is the use of InstanceID in the account definition?
At any given point in time, Azure Cosmos DB account's `accountName` property is globally unique while it is alive. However, after the account is deleted, it is possible to create another account with the same name and hence the "accountName" is no longer enough to identify an instance of an account.
ID or the `instanceId` is a property of an instance of an account and it is used to disambiguate across multiple accounts (live and deleted) if they have same name for restore. You can get the instance ID by running the `Get-AzCosmosDBRestorableDatabaseAccount` or `az cosmosdb restorable-database-account` commands. The name attribute value denotes the "InstanceID".
## Next steps
* What is [continuous backup](continuous-backup-restore-introduction.md) mode?
* Configure and manage continuous backup using [Azure portal](continuous-backup-restore-portal.md), [PowerShell](continuous-backup-restore-powershell.md), [CLI](continuous-backup-restore-command-line.md), or [Azure Resource Manager](continuous-backup-restore-template.md).
* [Manage permissions](continuous-backup-restore-permissions.md) required to restore data with continuous backup mode.
* [Resource model of continuous backup mode](continuous-backup-restore-resource-model.md)
|
C++
|
SHIFT_JIS
| 964
| 3.0625
| 3
|
[] |
no_license
|
/**
* @file can_begin_method.hpp
* @brief w肵^std::beginł邩ǂ肷郁^
* @author ΎR I
* @date 2018/12/13
*/
#ifndef SAKI_TYPE_TRAITS_BEGIN_METHOD_HPP
#define SAKI_TYPE_TRAITS_BEGIN_METHOD_HPP
#include <type_traits>
#include <utility>
#include <iterator>
#include <saki/macro/namespace_macro.hpp>
SAKI_NAMESPACE_BEGIN
/**
* @brief beginł邩ǂ肷\
*/
template <typename T>
struct can_begin
{
private:
template <typename U>
static constexpr std::true_type begin_check(decltype(std::begin(std::declval<U>())) *u);
template <typename U>
static constexpr std::false_type begin_check(...);
public:
static constexpr auto value = decltype(begin_check<T>(nullptr))::value;
};
/**
* @brief can_beginȒPɌĂяoϐ
*/
template <typename T>
inline constexpr auto can_begin_v = saki::can_begin<T>::value;
SAKI_NAMESPACE_END
#endif //SAKI_TYPE_TRAITS_CAN_BEGIN_METHOD_HPP
|
Java
|
UTF-8
| 1,070
| 3.671875
| 4
|
[] |
no_license
|
package com.satya.list;
/**
* Created by Satya on 10/31/18.
*/
public class LinkedList {
private Node head;
public static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
public void printList() {
Node temp = head;
while(temp != null) {
System.out.print(temp.data+" ");
temp=temp.next;
}
}
public void deleteKey(int key) {
Node temp = head;
while(temp.next != null) {
if(temp.next.data == key) {
temp.next=temp.next.next;
}
else{
temp=temp.next;
}
}
}
public static void main(String args[]){
LinkedList list=new LinkedList();
list.head=new Node(7);
Node second=new Node(2);
Node third=new Node(5);
Node temp= list.head;
while (temp != null){
temp.next=second;
temp=temp.next;
}
list.printList();
}
}
|
Shell
|
UTF-8
| 417
| 3.390625
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env sh
echo "TRAVIS_OS_NAME=$TRAVIS_OS_NAME"
if [ "$TRAVIS_OS_NAME" = "osx" ];
then
# Parse 'Mono JIT compiler version 5.0.1.1' to '5.0.1'
monoVer=$(mono --version | head -n 1 | cut -d' ' -f 5 | cut -d'.' -f 1-3)
prefix="/Library/Frameworks/Mono.framework/Versions/$monoVer";
else
prefix="/usr";
fi
echo "./autogen.sh --prefix=$prefix"
./autogen.sh --prefix=$prefix
|
Java
|
UTF-8
| 9,392
| 2.3125
| 2
|
[] |
no_license
|
package com.aromasoft;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.opengl.GLSurfaceView.Renderer;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.os.Build;
import android.util.Log;
import android.view.View;
import com.aromasoft.util.Image;
import java.util.ArrayList;
import java.util.HashMap;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
@TargetApi(Build.VERSION_CODES.CUPCAKE)
public class CubeRenderer implements Renderer
{
private final View mView;
private ArrayList<Cube> cubes;
private int [] mTextureID = null;
private HashMap<Integer, Float> positionMap;
private int mCubeCount;
public float mX;
public float DISTANCE = 2.0f;
public float CRITERIA = 2.0f;
public int ROTATE_ANGLE = 30;
public float RIGHT_MAX_ROTATE_ANGLE = -60f;
public float LEFT_MAX_ROTATE_ANGLE = 60f;
public float MOVE_EXACTLY_VALUE = 5f;
public float MOVE_MORE_EXACTLY_VALUE = 1f;
public float MAX_REM_VALUE = 195f;
public float MIN_REM_VALUE = 4.5f;
public final int COMPENSATION_VALUE = 100;
public float SCALE = 0.7f;
public float SCALE_COMPENSATION_VALUE = CRITERIA * SCALE * 100;
public boolean mIsMoving = false;
public int selectedPosition;
private Context mContext;
public CubeRenderer(CubeSurfaceView view, Context context, int cubeCount)
{
mContext = context;
mView = view;
mX = 0;
mCubeCount = cubeCount;
mTextureID = new int[mCubeCount];
cubes = new ArrayList<Cube>();
for (int i = 0; i < mCubeCount; i++)
{
cubes.add(new Cube());
}
if (positionMap == null)
{
positionMap = new HashMap<Integer, Float>();
}
positionMap.clear();
}
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
gl.glGenTextures(mCubeCount, mTextureID, 0);
for( int i = 0; i < mCubeCount ; i++ )
{
Bitmap bitmap = Image.loadImageByMp3(mContext, mView, i);
if (bitmap != null)
{
loadTexture(gl, bitmap, i);
}
}
gl.glEnable(GL10.GL_TEXTURE_2D);
// 물체를 부드럽게 처리해준다.
// 둘중 하나의 인자를 가진다. GL_FLAT or GL_SMOOTH
gl.glShadeModel(GL10.GL_SMOOTH);
// 화면을 설정된 값으로 지운다.(또는 채워서 칠한다.)
// red, green, blue, alpha 이며 0.0f~ 1.0f 로 어두운값에서 밝은 값으로 정의된다.
gl.glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
// 깊이 버퍼를 설정한다. 물체가 여러개 있을때 앞에 있는지 뒤에 있는지를 구분하여 표현되어 진다.
gl.glClearDepthf(1.0f);
// 깊이 테스팅을 활성화 해 줍니다.
gl.glEnable( GL10.GL_DEPTH_TEST );
// 깊이 버퍼 종류가 해야할 것을 설정한다.
gl.glDepthFunc( GL10.GL_LEQUAL );
// 가장 빠른 화면을 그리도록 요청한다.
gl.glHint( GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST );
}
public void onSurfaceChanged(GL10 gl, int width, int height)
{
if (height == 0)
{
height = 1;
}
// 그려질 화면을 전체 화면으로 설정한다.
gl.glViewport(0, 0, width, height);
// Projection View Matrix 에 영향을 미칠 값이 있다고 알린다.
// Projection View Perspective View 에 영향을 미치는 Matrix 이다.
gl.glMatrixMode(GL10.GL_PROJECTION);
// Matrix 를 초기화한다. ( Matrix 를 초기상태인 단위 행렬로 만든다. )
gl.glLoadIdentity();
// 관측 윈도우의 각도와 표현할 near & far 의 깊이를 설정한다.
GLU.gluPerspective(gl, 45.0f, (float) width / height, 1.0f, 100.0f);
// Model View Matrix 에 영향을 미칠 값이 있다고 알린다.
// Model View Matrix 를 물체의 정보가 저장되는 곳이다.
// 물체의 정보라 하면 3차원적 위치, 3차원 크기, 3차원적 회전각을 의미하며,
// 이모든것은 4x4 행렬로 표현된다.
gl.glMatrixMode(GL10.GL_MODELVIEW);
// Model View Matrix 를 초기화한다.
gl.glLoadIdentity();
}
public void onDrawFrame(GL10 gl)
{
int center = getCenterPosition();
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
if (!mIsMoving)
{
if (isNeedAutoLock())
{
moveToExactlyItemPosition();
}
else
{
Intent intent = new Intent(CubeActivity.EXACTLYPOSITION);
intent.putExtra("position", selectedPosition);
mContext.sendBroadcast(intent);
}
}
for (int i = 0; i < mCubeCount; i++)
{
gl.glLoadIdentity();
float distance = 0;
distance = ((i + 1) - center) * DISTANCE;
gl.glTranslatef(mX + distance, 0, -5.5f);
positionMap.put(i, mX + distance);
if (positionMap.get(i) == 0)
{
selectedPosition = i;
}
float angle = -(positionMap.get(i) * ROTATE_ANGLE);
if (angle < RIGHT_MAX_ROTATE_ANGLE)
{
angle = RIGHT_MAX_ROTATE_ANGLE;
}
else if (angle > LEFT_MAX_ROTATE_ANGLE)
{
angle = LEFT_MAX_ROTATE_ANGLE;
}
gl.glRotatef(angle, 0, 1f, 0);
float scale = CRITERIA * COMPENSATION_VALUE - (Math.abs(positionMap.get(i)) * COMPENSATION_VALUE);
if (scale > 0)
{
if (scale < SCALE_COMPENSATION_VALUE)
{
gl.glScalef(1, 1, 1);
}
else
{
gl.glScalef(scale / SCALE_COMPENSATION_VALUE, scale / SCALE_COMPENSATION_VALUE, 1);
}
}
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID[i]);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
cubes.get(i).draw(gl);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
}
private void loadTexture(GL10 gl, Bitmap bitmap, int index)
{
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID[index]);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
}
public int getCenterPosition()
{
int centerPosition = 0;
if (mCubeCount % 2 == 0)
centerPosition = mCubeCount / 2;
else
centerPosition = mCubeCount / 2 + 1;
return centerPosition;
}
public boolean isOdds()
{
if (mCubeCount % 2 == 0)
return false;
return true;
}
public void setPosition(float x)
{
mX = Math.round(mX * COMPENSATION_VALUE) + x;
mX = mX / COMPENSATION_VALUE;
Log.i(">>>>","mX = " + mX);
}
public boolean isNeedAutoLock()
{
float absMx = Math.abs(mX);
if (((absMx * COMPENSATION_VALUE) % (CRITERIA * COMPENSATION_VALUE)) == 0)
{
return false;
}
return true;
}
private void moveToExactlyItemPosition()
{
float absMx = Math.abs(mX);
if (CubeSurfaceView.getCubeSurfaceView().DIRECTION == 0)
{
if (((absMx * COMPENSATION_VALUE) % (CRITERIA * COMPENSATION_VALUE)) > MAX_REM_VALUE
|| ((absMx * COMPENSATION_VALUE) % (CRITERIA * COMPENSATION_VALUE)) < MIN_REM_VALUE)
{
mX = Math.round(mX * COMPENSATION_VALUE) + MOVE_MORE_EXACTLY_VALUE;
mX = mX / COMPENSATION_VALUE;
}
else
{
mX = Math.round(mX * COMPENSATION_VALUE) + MOVE_EXACTLY_VALUE;
mX = mX / COMPENSATION_VALUE;
}
}
else if (CubeSurfaceView.getCubeSurfaceView().DIRECTION == 1)
{
if (((absMx * COMPENSATION_VALUE) % (CRITERIA * COMPENSATION_VALUE)) > MAX_REM_VALUE
|| ((absMx * COMPENSATION_VALUE) % (CRITERIA * COMPENSATION_VALUE)) < MIN_REM_VALUE)
{
mX = Math.round(mX * COMPENSATION_VALUE) - MOVE_MORE_EXACTLY_VALUE;
mX = mX / COMPENSATION_VALUE;
}
else
{
mX = Math.round(mX * COMPENSATION_VALUE) - MOVE_EXACTLY_VALUE;
mX = mX / COMPENSATION_VALUE;
}
}
CubeSurfaceView.getCubeSurfaceView().requestRenderer();
}
}
|
PHP
|
UTF-8
| 526
| 2.625
| 3
|
[] |
no_license
|
<?php
class TestMigration extends Migration {
public $tables = array("users", "photos");
public function up() {
$table = $this->create_table('users');
$table->string('name');
$table->integer('my_int');
$table->timestamps();
$table->go();
$table2 = $this->create_table('photos');
$table2->belongs_to('user');
$table2->string('title');
$table2->go();
}
public function down() {
foreach($this->tables as $t) {
$this->drop_table($t);
}
}
}
?>
|
Markdown
|
UTF-8
| 1,394
| 3.71875
| 4
|
[] |
no_license
|
# HTML Slots
[HTML Slot Specification](https://html.spec.whatwg.org/multipage/scripting.html#the-slot-element)
[Slot MDN Page](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot)
A `<slot>` is a named element that can be used as a placeholder for other content to be "slotted" in later.
A slot will display any nested nodes from the slot's declaration, unless there is named content to fill the slot, in which the slot's content will be replaced with the specified content.
The `<slot>` element has a single attribute, `name`, that is used to provide the name of the slot.
``` html
<slot name="my-slot">Default content</slot>
```
Slots can then be referenced by their name using a `slot` attribute on the content to be inserted into the `<slot>` location.
``` html
<template id="example-content">
<style>
code {
color: #CCCCCC;
}
</style>
<code><pre><slot name="example">Default</slot></pre></code>
</template>
```
``` JavaScript
class ExampleContentElement extends HTMLElement {
constructor() {
super();
const template = document.querySelector('#example-content').content;
this.attachShadow({mode: 'open'}).appendChild(template.cloneNode(true));
}
}
customElements.define('example-content', ExampleContentElement);
```
``` html
<example-content>
<span slot="example">console.log('Hello, World');</span>
</example-content>
```
|
JavaScript
|
UTF-8
| 473
| 2.828125
| 3
|
[] |
no_license
|
class VillageState {
constructor(place, parcels) {
this.place = place;
this.parcels = parcels;
}
move(destination) {
if (!roadGraph[this.place].includes(destination)) {
return this;
} else {
let parcels = this.parcels.map(p => {
if (p.place != this.place) return p;
return {place: destination, address: p.address};
}).filter(p => p.place != p.address);
return new VillageState(destination, parcels);
}
}
}
|
Markdown
|
UTF-8
| 2,700
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
---
layout: post
category: tech
tagline: ""
tags : [git, devops]
comments: true
---
{% include JB/setup %}
``参考,部分转载:https://yorkyu.cn/how-to-use-rebase-to-gracefully-fallback-code-08cdafe3d403.html``
# 基本操作概念
1. Git Revert
使用命令 ``git revert commit_id`` 能产生一个 与 ``commit_id`` 完全相反的提交,即在 log 中会看到一条新的提交 ``new_commit_id``, revert 提交就是删除 ``commit_id`` 的提交。
2. Git Reset
``reset`` 也能使代码回到某次提交,但跟 revert 不同的是, reset 是将提交的 ``HEAD`` 指针指到某次提交,之后的提交记录会消失,就像从没有过这么一次提交
3. Get Rebase
``rebase`` 是“变基”的意思,这里的“基”,指[多次] commit 形成的 git workflow,使用 rebase,我们可以改变这些历史提交,修改 commit 信息,将多个 commit 进行组合。
# Rebase+Revert回退
1. 切出一个新分支 ``feature1``
首先,切出一个新分支 ``feature1``,使用 git log 查询一下``要回退到的`` commit 版本 ``commit_n``。
2. ``feature1`` 分支执行命令 git rebase -i commit_n
3. ``feature1`` 合并 commit2 ~ commit4 到最旧的 commit1 上
在合并 commit 时,我们可以选择 pick(p) 最旧的 commit1,然后在后续的 commit_xxx 前添加 squash(s) 命令,将这些 commits 都合并到最旧的 commit1 上。
```
pick 6fa5869 commit1
squash 0b84ee7 commit2
squash 986c6c8 commit3
squash 91a0dcc commit4
```
4. ``feature1`` 合并提交记录
```
# 执行rebase 生成的新记录
commit 5
# 回退代码的版本号
commit_n
```
5. `` feature1`` 合并 ``master`` 到 ``feature1``
由于 ``feature1`` 分支落后与 ``master`` 分支,因此需要执行 ``git merge master`` 将``master`` 分支向 ``feature1`` 分支合并。
合并后 git 会发现 ``commit1`` 到 ``commit4`` 提交的内容和 ``feature1`` 分支上 ``commit5`` 的修改内容是完全相同的,会自动进行合并,内容不变,但多了一个 commit5。
```
# feature1 分支
commit 5
commit 4
commit 3
commit 2
commit 1
# 回退代码的版本号
commit_n
```
6. ``feature1`` 分支执行 revert 反提交
在 ``feature1`` 分支上对 ``commit5`` 进行一次 ``revert`` 反提交,就实现了把 ``commit1`` 到 ``commit4`` 的提交全部回退。即撤回步骤5中的合并。
```
git revert commit_5
# 执行rebase 生成的新记录
commit 5
# 回退代码的版本号
commit_n
```
7. ``master`` 分支执行合并``feature1``到``master``
``master`` 代码回退,但保留了``commit_n, 1,2,3,4,5``所有记录
```
# 切回到 master
$ git checkout master
# 合并 feature1
$ git merge feature1
```
|
Python
|
UTF-8
| 14,242
| 3.359375
| 3
|
[] |
no_license
|
'''
Python dash file:
Visualizes the dashboard for the predction model and
the optimization model
'''
# package imports
import pandas as pd
import dash
import dash_table
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
from virginia_prediction_model import predict
from virginia_optimization_model import optimize
import plotly.express as px
# css stylesheet
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
# python dash app
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# radio buttons for state prediction vs county prediction
state_vs_county = {
'state level': [],
'county level': []
}
# sorted list of county names
my_counties = pd.read_csv('locality_populations.csv',names=['locality','population'])
my_counties = my_counties.sort_values(by=['locality'])
# prediction model input variables
location = 'Virginia'
scenario = 1
days = 30
custom_params = {
'theta': 0.00683125,
'sigma': 0.072947592,
'kappa': 0.003590055,
'V1': 0.00364
}
# optimizatioin model input variables
stockpile = 0
# html layout code
app.layout = html.Div([
# dashboard tabs
dcc.Tabs([
# Introduction tab
dcc.Tab(label='Welcome Page',children=[
html.Div(children=[
html.H1(
children= 'The Virginia COVID-19 Vaccine Dashboard',
style={
'textAlign': 'center',
'text-decoration': 'underline'
}
),
dcc.Markdown('''
## Introduction
Welcome to the Virginia COVID-19 Vaccine dashboard!
The purpose of this dashboard is to use vaccine administration
data in tandem with the well-understood COVID-19 cases data to
see how the virus is affecting
the state of Virginia now and in the future. This dashboard
features a suite of functionalities that enables the user to
simulate custom COVID-19 progression scenarios and easily derive
insights from the results. The two models we introduce here is
the **prediction model** and the **optimization model**.
## Prediction Model
Given some initial parameters, the prediction model forecasts
the potiential spread of COVID-19 in Virginia over a specified
number of days. To use the prediction model, click the
"Prediction Model" tab. Let's go over what each of the
prediction model inputs mean, and how to interpret the output.
1. **Region**:
The prediction model can run a simulation at the state level
or at the individual county level. In the first block of the
prediction model page, the user can select the **state level**
radio button if they want their results to be for the entire
state of Virginia, or they can select the **county level**
button if they want to see results for a specific county.
If the user selects the **county level** button,
they can pick their county of interest from the
**select county** dropdown menu.
2. **Scenarios**:
Due to factors like virus variants, vaccine hesitancy, and
vaccine distribution, there is a degree of uncertainty in
how COVID-19 can progress. Our predition model takes this
uncertainty by enabling the user to simulate different
scenarios in our **Scenarios** section. When the scenarios
dropdown menu is clicked, the user sees 4 options for
scenarios. The **real scenario** option represents the expected
progress of COVID-19, barring any unexpected events. The
**bad scenario** option represents a "worst-case scenario"
so to speak. In the bad scenario, the virus is more
transmisible, vaccine administration counts is diminished,
and vaccine hesitancy is high, resulting in more reinfections.
On the flip size, the **good scenario** option represents
a best-case scenario, where vaccine hesitancy is low and the
virus is less transmisible.
The scenarios section also has a **custom scenarios** option,
where the user can input specific prediction model scenario
parameters. If enabled, the user can input custom infection
rates, recovery rates, deaths rates, and vaccine rates into
the prediction model.
3. **Period**:
In the **Period** block, the user select how far into the
future the prediction model runs.
4. **Output**:
When the user is satified with their inputs, they can
click the **Predict** button to execute the prediction model.
The output itself is a normalized time series of different
variables of interest, like the number of people infected and
the number of people vaccinated.
## Optimization Model
Given a number of vaccines, the optimization model
methodologically allocates vaccines to the counties that
need it most. The output to the optimization model is a table
that tells how many vaccines a county receives, and the
prioritization level of the county.
'''),
],style={'background-color': '#e6f2ff'})],
),
# prediction model tab
dcc.Tab(label='Prediction Model', children=[
html.Div(children=[
# html heading (makes the thin grey line)
html.Hr(),
# state prediction vs county prediction radio button html
html.Label('1. Region'),
dcc.RadioItems(
id='state-v-county-radio',
options=[{'label': k, 'value': k} for k in \
state_vs_county.keys()],
value='state level'
),
# county drop-down box
html.Label('select county'),
dcc.Dropdown(
id='county-dropdown-prediction',
options=[{'label': k, 'value':k} for k in my_counties['locality']],
),
html.Hr(),
# scenario type drop-down box
html.Label("2. Scenarios"),
dcc.Dropdown(
id='scenario-dropdown',
options=[
{'label': 'real scenario', 'value': 'average'},
{'label': 'bad scenario', 'value': 'bad'},
{'label': 'good scenario', 'value': 'good'},
{'label': 'custom scenario', 'value': 'custom'}
],
value='average',
clearable=False
),
# custom scenario parameters text boxes
html.Label('Custom infection rate',id="custom-infection-label"),
dcc.Input(
id='infection-rate',
placeholder='infection rate (decimal)',
type='text',
disabled=True,
debounce = True
),
html.Label('Custom recovery rate',id="custom-recovery-label"),
dcc.Input(
id='recovery-rate',
placeholder='recovery rate (decimal)',
type='text',
disabled=True,
debounce = True
),
html.Label('Custom death rate',id="custom-death-label"),
dcc.Input(
id='death-rate',
placeholder='death rate (decimal)',
type='text',
disabled=True,
debounce=True
),
html.Label('Custom vaccine rate',id="custom-vaccine-label"),
dcc.Input(
id='vaccine-rate',
placeholder='vaccine rate (decimal)',
type='text',
disabled=True,
debounce=True
),
html.Hr(),
# slider for days to prediction
html.Label("Period"),
dcc.Slider(
id='prediction-days',
min=30,
max=360,
step=None,
marks={
30: '30 days',
60: '60 days',
90: '90 days',
120: '120 days',
150: '150 days',
180: '180 days',
210: '210 days',
240: '240 days',
270: '270 days',
300: '300 days',
330: '330 days',
360: '360 days'
},
value=30
),
html.Hr(),
# prediction button
html.Label('Execute prediction'),
html.Button('predict',id='predict-button'),
# prediction model output
html.Div(id='prediction-loading'),
dcc.Loading(
id="p-loading",
type="dot",
children=dcc.Graph(id='prediction-output')
)
])]),
# optimization model tab
dcc.Tab(label='Optimization Model', children=[
html.Hr(),
# stockpile input
html.Label('Vaccine Allocation'),
dcc.Input(
id='vaccine-stockpile',
type='number',
placeholder='integer',
),
# optimization button
html.Label('Execute optimization'),
html.Button('optimize',id='optimize-button'),
# optimizaton model output
dcc.Loading(
id="optimization-loading",
type="cube",
children=html.Div(id="optimization-output")
),
]),
])
])
# functions for interacting with user input
# --------------------------------------------
# disable county drop-down when state level is selected
@app.callback(
Output('county-dropdown-prediction','disabled'),
Input('state-v-county-radio','value'),prevent_initial_call=True)
def set_stateOrCounty_status(val):
if val == 'state level':
global location
location = 'Virginia'
return True
else:
return False
# updates pred model location parameter
@app.callback(
Output('county-dropdown-prediction','value'),
Input('county-dropdown-prediction','value'),prevent_initial_call=True
)
def update_location(val):
global location
location = val
return val
# disables custom scenario text-boxes when custom is not selected
@app.callback(
Output('infection-rate','disabled'),
Output('recovery-rate','disabled'),
Output('death-rate','disabled'),
Output('vaccine-rate','disabled'),
Input('scenario-dropdown','value'),prevent_initial_call=True
)
def set_scenario_custom_status(val):
if val == 'custom':
return [False,False,False,False]
else:
return [True,True,True,True]
# updates scenario input parameter
@app.callback(
Output('scenario-dropdown','value'),
Input('scenario-dropdown','value'),prevent_initial_call=True
)
def update_scen(val):
global scenario
if val == 'average':
scenario = 1
elif val == 'bad':
scenario = 0
elif val == 'good':
scenario = 2
elif val =='custom':
scenario = custom_params
return val
# next few functions updates custom parameter values (backend stuff)
@app.callback(
Output('infection-rate','value'),
Input('infection-rate', 'value'),prevent_initial_call=True
)
def update_infection(val):
global custom_params
global scenario
custom_params['theta'] = float(val)
scenario = custom_params
return val
@app.callback(
Output('recovery-rate','value'),
Input('recovery-rate','value'),prevent_initial_call=True
)
def update_recovery(val):
global custom_params
global scenario
custom_params['sigma'] = float(val)
scenario = custom_params
return val
@app.callback(
Output('death-rate','value'),
Input('death-rate','value'),prevent_initial_call=True
)
def update_death(val):
global custom_params
global scenario
custom_params['kappa'] = float(val)
scenario = custom_params
return val
@app.callback(
Output('vaccine-rate','value'),
Input('vaccine-rate','value'),prevent_initial_call=True
)
def update_vaccine(val):
global custom_params
global scenario
custom_params['V1'] = float(val)
scenario = custom_params
return val
@app.callback(
Output('prediction-days','value'),
Input('prediction-days','value'),prevent_initial_call=True
)
# updates days input parameter
def update_days(val):
global days
days = val
return val
@app.callback(
Output('prediction-output', 'figure'),
Input('predict-button','n_clicks')
)
# when prediction button is clicked, run prediction model
def execute_predict(btn):
changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
if 'predict-button' in changed_id:
pred = predict(location,scenario,days) # prediction model
fig = px.line(pred, x = "time", y = pred.columns[0:5])
fig.update_layout(title='Covid-19 Prediction Model',
xaxis_title='days',
yaxis_title='Number of people normalized',
transition_duration=500)
return fig
else:
return {}
@app.callback(
Output('vaccine-stockpile','value'),
Input('vaccine-stockpile','value'),prevent_initial_call=True
)
# updates stockpile input parameter
def update_stockpile(val):
global stockpile
stockpile = val
return val
@app.callback(
Output("optimization-output", "children"),
Input("optimize-button", "n_clicks")
)
# when optimization button is clicked, run optimiztion model
def execute_optimize(btn):
changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
if 'optimize-button' in changed_id:
opt = optimize(stockpile)
return dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in opt.columns],
data=opt.to_dict('records'),
)
if __name__ == '__main__':
app.run_server(debug=True)
|
C#
|
UTF-8
| 370
| 2.640625
| 3
|
[] |
no_license
|
using System;
using System.Linq;
using System.Windows.Media;
namespace SharpestBeak.UI
{
internal static class LocalHelper
{
#region Public Methods
public static Color WithAlpha(this Color color, byte alpha)
{
return Color.FromArgb(alpha, color.R, color.G, color.B);
}
#endregion
}
}
|
Swift
|
UTF-8
| 2,353
| 2.6875
| 3
|
[] |
no_license
|
//
// IssueDetailHeaderView.swift
// IssueTracker
//
// Created by sihyung you on 2020/11/04.
// Copyright © 2020 IssueTracker-15. All rights reserved.
//
import UIKit
enum IssueBadgeColor: String {
case open = "OpenIssueBackgroundColor"
case closed = "ClosedIssueBackgroundColor"
}
class IssueDetailHeaderView: UICollectionReusableView {
@IBOutlet weak var profilePicture: UIImageView!
@IBOutlet weak var issueAuthor: UILabel!
@IBOutlet weak var issueTitle: UILabel!
@IBOutlet weak var issueNumber: UILabel!
@IBOutlet weak var issueBadge: UIButton!
func configure(with headerViewModel: IssueDetailHeaderViewModel) {
self.issueAuthor.text = headerViewModel.author.userName
self.issueTitle.text = headerViewModel.title
self.issueNumber.text = "#" + String(headerViewModel.id)
configureIssueBadge(isOpened: headerViewModel.isOpened)
headerViewModel.needImage { [weak self] (data) in
self?.setProfileImage(data: data)
}
}
private func configureIssueBadge(isOpened: Bool) {
var badgeColor: UIColor
var badgeText: String
badgeColor = isOpened ? UIColor(named: IssueBadgeColor.open.rawValue) ?? UIColor.green : UIColor(named: IssueBadgeColor.closed.rawValue) ?? UIColor.red
badgeText = isOpened ? "Open" : "Closed"
issueBadge.convertToIssueBadge(text: badgeText, backgroundColor: badgeColor)
issueBadge.contentEdgeInsets = UIEdgeInsets(top: 3, left: 10, bottom: 3, right: 10)
}
private func setProfileImage(data: Data?) {
guard let data = data,
let image = UIImage(data: data)
else { return }
profilePicture.image = image
}
override func layoutSubviews() {
super.layoutSubviews()
profilePicture.setRound(ratio: 1)
}
}
extension IssueDetailHeaderView: UICollectionViewHeaderRegisterable {
static var headerIdentifier: String {
return "IssueDetailHeaderView"
}
static var headerNib: UINib {
return UINib(nibName: "IssueDetailHeaderView", bundle: .main)
}
}
extension UIButton {
func convertToIssueBadge(text: String, backgroundColor: UIColor) {
self.backgroundColor = backgroundColor
self.setTitle(text, for: .normal)
}
}
|
JavaScript
|
UTF-8
| 828
| 3.265625
| 3
|
[] |
no_license
|
var fortunes = [
"Have a nice day",
"You look really good today",
"It's your birthday!",
"Never play leapfrog with a unicorn"
];
var net = require('net');
var server = net.createServer(function(connection){
connection.write("Enter the number of fortunes you want: ");
connection.on('data', function(data){
var num_fortunes = parseInt(data, 10);
if(isNaN(num_fortunes)) {
connection.write("That's not a number, silly.");
connection.end();
} else if(num_fortunes > 4) {
connection.write("You're too greedy. Ask for fewer fortunes next time.");
connection.end();
} else {
for(var i = 0; i < num_fortunes; i += 1) {
connection.write(fortunes[i] + "\n");
}
connection.end();
}
connection.on('error', function(){});
});
});
server.listen(1234);
|
C++
|
UTF-8
| 2,405
| 2.859375
| 3
|
[
"Apache-2.0"
] |
permissive
|
#ifndef __TYPE_CHECK_H__
#define __TYPE_CHECK_H__
#include <stdexcept>
#include <string>
#include <cstdint>
// Set of macros to assist with performing the type checks such the arguments
// required to generate the exception message are not evaluated unless the
// condition is met
#define TYPE_CHECK_ARRAY(condition, datatype_name, expected, received) \
if (condition) throw kx::arrowkdb::TypeCheckArray(datatype_name, expected, received);
#define TYPE_CHECK_ITEM(condition, datatype_name, expected, received) \
if (condition) throw kx::arrowkdb::TypeCheckItem(datatype_name, expected, received);
#define TYPE_CHECK_UNSUPPORTED(datatype_name) \
throw kx::arrowkdb::TypeCheckUnsupported(datatype_name);
#define TYPE_CHECK_LENGTH(condition, datatype_name, expected, received) \
if (condition) throw kx::arrowkdb::TypeCheckLength(datatype_name, expected, received);
namespace kx {
namespace arrowkdb {
// Hierachy of TypeCheck exceptions with each derived type being using for a
// specific check when converting from a kdb object to an arow arrow.
class TypeCheck : public std::invalid_argument
{
public:
TypeCheck(std::string message) : std::invalid_argument(message.c_str()) {};
};
class TypeCheckArray : public TypeCheck
{
public:
TypeCheckArray(const std::string& datatype_name, int expected, int received) :
TypeCheck("Invalid array, datatype: '" + datatype_name + "', expected: " + std::to_string(expected) + ", received: " + std::to_string(received))
{};
};
class TypeCheckItem : public TypeCheck
{
public:
TypeCheckItem(const std::string& datatype_name, int expected, int received) :
TypeCheck("Invalid item, datatype: '" + datatype_name + "', expected: " + std::to_string(expected) + ", received: " + std::to_string(received))
{};
};
class TypeCheckUnsupported : public TypeCheck
{
public:
TypeCheckUnsupported(const std::string& datatype_name) :
TypeCheck("Unsupported datatype: '" + datatype_name + "'")
{};
};
class TypeCheckLength : public TypeCheck
{
public:
TypeCheckLength(const std::string& datatype_name, int64_t expected, int64_t received) :
TypeCheck("Invalid length, datatype: '" + datatype_name + "', expected: " + std::to_string(expected) + ", received: " + std::to_string(received))
{};
};
} // namespace arrowkdb
} // namespace kx
#endif // __TYPE_CHECK_H__
|
C#
|
UTF-8
| 2,394
| 2.546875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
namespace Common
{
public class Unit
{
public enum HostilityEnum : sbyte
{
/// <summary>
/// Unspecified Hostility status
/// </summary>
UNSPECIFIED = -1,
/// <summary>
/// Unknown Hostility status
/// </summary>
UNKNOWN = 0,
/// <summary>
/// Friendly status
/// </summary>
FRIEND,
/// <summary>
/// Neutral status
/// </summary>
NEUTRAL,
/// <summary>
/// Hostile status
/// </summary>
HOSTILE
}
public ulong Id { get; set; }
[StringValidator(MaxLength = 21)]
public string Designation { get; set; }
public Telemetry Telemetry { get; set; }
[StringValidator(MaxLength = 20)]
public string StaffComment { get; set; }
[StringValidator(MaxLength = 20)]
public string AdditionalInfo { get; set; }
public HostilityEnum Hostility { get; set; }
[IntegerValidator(MinValue = 0, MaxValue = 100)]
public byte StatusAmmo { get; set; }
[IntegerValidator(MinValue = 0, MaxValue = 100)]
public byte StatusPersonel { get; set; }
[IntegerValidator(MinValue = 0, MaxValue = 100)]
public byte StatusWeapons { get; set; }
[IntegerValidator(MinValue = 0, MaxValue = 100)]
public byte StatusPOL { get; set; }
[StringValidator(MaxLength = 20)]
public string EquipmentType { get; set; }
public Unit()
{
Designation = "";
Telemetry = new Telemetry();
StaffComment = "";
AdditionalInfo = "";
Hostility = HostilityEnum.UNKNOWN;
StatusAmmo = 0;
StatusPersonel = 0;
StatusWeapons = 0;
StatusPOL = 0;
EquipmentType = "";
}
public IList<HostilityEnum> HostilityEnumTypes {
get {
return Enum.GetValues(typeof(HostilityEnum)).Cast<HostilityEnum>().ToList<HostilityEnum>();
}
}
public HostilityEnum HostilityEnumValue {
get;
set;
}
}
}
|
JavaScript
|
UTF-8
| 624
| 2.59375
| 3
|
[] |
no_license
|
export const state = () => ({
_snackbar: false,
_text: `Hello, I'm a snackbar`,
});
export const mutations = {
CHANGE_SNACBAR(state, bool) {
state._snackbar = bool;
},
CHANGE_TEXT(state, text) {
state._text = text;
},
};
export const actions = {
openSnacbar({ commit, dispatch }, { time, text }) {
commit('CHANGE_TEXT', text);
commit('CHANGE_SNACBAR', true);
setTimeout(() => {
dispatch('closeSnacbar');
}, time);
},
closeSnacbar({ commit }) {
commit('CHANGE_SNACBAR', false);
},
};
export const getters = {
snackbar: (s) => s._snackbar,
text: (s) => s._text,
};
|
Python
|
UTF-8
| 6,930
| 4.1875
| 4
|
[] |
no_license
|
'''
Write a program to evaluate poker hands and determine the winner
Read about poker hands here.
https://en.wikipedia.org/wiki/List_of_poker_hands
'''
def is_four_of_a_kind(hand):
'''
This code is to check if the given hand is
four of a kind or not.
Converted the hand into a list of indexes and calculated
the difference between the consicutive numbers.
If the difference is equal to four then we can say that it is
'''
# stng_values = "--23456789TJQKA"
# hand_values = []
# for i in hand:
# hand_values.append(stng_values.index(i[0]))
# hand_values.sort() #For the sorting the indexes in hand.
# #print(hand_values)
# count_diff = 1
# for i in range(len(hand_values) - 1):
# if hand_values[i] - hand_values[i+1] == 0:
# count_diff += 1
# if count_diff == 4:
# return True
hand_values = [f for f, s in hand]
values = set(hand_values)
four_of_a_kind = [f for f in values if hand_values.count(f) == 4]
#print(four_of_a_kind)
return len(four_of_a_kind) == 1
def is_full_house(hand):
'''
The hand is said to be inn full house if the three cards
are either 3 or 6.
'''
#stng_values = "--23456789TJQKA"
hand_values = []
for i in hand:
hand_values.append(i[0])
hand_values.sort()
#print(hand_values)
count = 1
for i in hand_values:
if i in (3, 6):
count += 1
return count == 3
def is_straight(hand):
'''
How do we find out if the given hand is a straight?
The hand has a list of cards represented as strings.
There are multiple ways of checking if the hand is a straight.
Do we need both the characters in the string? No.
The first character is good enough to determine a straight
Think of an algorithm: given the card face value how to check if it a straight
Write the code for it and return True if it is a straight else return False
'''
stng_values = "--23456789TJQKA"
hand_values = []
for i in hand:
hand_values.append(stng_values.index(i[0]))
hand_values.sort()
#print(hand_values)
for i in range(len(hand_values) - 1):
if hand_values[i] - hand_values[i+1] != -1:
return False
return True
def is_flush(hand):
'''
How do we find out if the given hand is a flush?
The hand has a list of cards represented as strings.
Do we need both the characters in the string? No.
The second character is good enough to determine a flush
Think of an algorithm: given the card suite how to check if it is a flush
Write the code for it and return True if it is a flush else return False
'''
values_set = set({})
for i in hand:
values_set.add(i[1])
#print(values_set)
return len(values_set) == 1
def is_three_pair(hand):
'''
This code is to check if the given hand is
four of a kind or not.
Converted the hand into a list of indexes and calculated
the difference between the consicutive numbers.
If the difference is equal to three then we can say that it is
'''
# stng_values = "--23456789TJQKA"
# hand_values = []
# for i in hand:
# hand_values.append(stng_values.index(i[0]))
# hand_values.sort() #For the sorting the indexes in hand.
# #print(hand_values)
# count_diff = 1
# #print(hand_values)
# for i in range(len(hand_values) - 1):
# if hand_values[i] - hand_values[i+1] == 0:
# count_diff += 1
# if count_diff == 3:
# return True
hand_values = [f for f, s in hand]
values = set(hand_values)
three_pairs = [f for f in values if hand_values.count(f) == 3]
#print(three_pairs)
return len(three_pairs) == 1
def is_two_pair(hand):
''' Sees if the hand is a two pair or not '''
hand_values = [f for f, s in hand]
values = set(hand_values)
twopairs = [f for f in values if hand_values.count(f) == 2]
#print(twopairs)
return len(twopairs) == 2
def is_one_pair(hand):
'''
This code is to check if the given hand is
one pair or not.'''
hand_values = [f for f, s in hand]
values = set(hand_values)
one_pair = [f for f in values if hand_values.count(f) == 1]
#print(one_pair)
return len(one_pair) == 1
def is_high_card(hand):
''' Function to return high card '''
stng_values = "--23456789TJQKA"
hand_values = []
for i in hand:
hand_values.append(stng_values.index(i[0]))
# hand_values = [f for f, s in hand]
# values = set(hand_values)
#print(values)
max_value = max(hand_values)
list_1.append(max_value)
#return max(max(list_1),hand)
def hand_rank(hand):
'''
You will code this function. The goal of the function is to
return a value that max can use to identify the best hand.
As this function is complex we will progressively develop it.
The first version should identify if the given hand is a straight
or a flush or a straight flush.
'''
hand_rank_value = 0
if is_straight(hand) and is_flush(hand):
hand_rank_value = 9
elif is_four_of_a_kind(hand):
hand_rank_value = 8
elif is_full_house(hand):
hand_rank_value = 7
elif is_flush(hand):
hand_rank_value = 6
elif is_straight(hand):
hand_rank_value = 5
elif is_three_pair(hand):
hand_rank_value = 4
elif is_two_pair(hand):
hand_rank_value = 3
elif is_one_pair(hand):
hand_rank_value = 2
elif is_high_card(hand):
hand_rank_value = 1
else:
hand_rank_value = 0
return hand_rank_value
def poker(hands):
'''
This function is completed for you. Read it to learn the code.
Input: List of 2 or more poker hands
Each poker hand is represented as a list
Print the hands to see the hand representation
Output: Return the winning poker hand
'''
# the line below may be new to you
# max function is provided by python library
# learn how it works, in particular the key argument, from the link
# https://www.programiz.com/python-programming/methods/built-in/max
# hand_rank is a function passed to max
# hand_rank takes a hand and returns its rank
# max uses the rank returned by hand_rank and returns the best hand
return max(hands, key=hand_rank)
if __name__ == "__main__":
# read the number of test cases
COUNT = int(input())
# iterate through the test cases to set up hands list
list_1 = []
HANDS = []
for x in range(COUNT):
line = input()
ha = line.split(" ")
HANDS.append(ha)
# test the poker function to see how it works
print(' '.join(poker(HANDS)))
#print(HANDS)
#print(is_flush(HANDS))
|
PHP
|
UTF-8
| 1,753
| 3.046875
| 3
|
[] |
no_license
|
<?php
namespace GatewayWorker\Lib;
/**
* Event objects are passed as parameters to event listeners when an event occurs.
*
* @see EventDispatcher
* @author 不再迟疑
*/
class Event {
private static $sEventPool = array ();
/**
*
* @var EventDispatcher $_target
*/
public $target;
/**
*
* @var EventDispatcher $_currentTarget
*/
public $currentTarget;
/**
*
* @var string $_type
*/
public $type;
/**
*
* @var boolean $_stopsImmediatePropagation
*/
public $stopsImmediatePropagation;
public $data;
/**
* Creates an event object that can be passed to listeners.
*/
public function __construct($type, $data = null) {
$this->type = $type;
$this->data = $data;
}
/**
* Prevents any other listeners from receiving the event.
*/
public function stopImmediatePropagation() {
$this->stopsImmediatePropagation = true;
}
// event pooling
/**
*
* @param string $type
* @param unknown $data
*/
public static function fromPool($type, $data = null) {
if (count ( Event::$sEventPool ))
return array_pop ( Event::$sEventPool )->reset ( $type, $data );
else
return new Event ( $type, $data );
}
/**
*
* @param Event $event
*/
public static function toPool($event) {
$event->data = $event->target = $event->currentTarget = null;
array_push ( Event::$sEventPool, $event );
}
/**
*
* @param string $type
* @param * $data
*/
public function reset($type, $data = null) {
$this->type = $type;
$this->data = $data;
$this->target = $this->currentTarget = null;
$this->stopsImmediatePropagation = false;
return $this;
}
}
|
C++
|
UTF-8
| 8,971
| 3.296875
| 3
|
[] |
no_license
|
//****************************************************************************************************
//
// File: StudentList.cpp
//
// Student: Michael Remphry
//
// Assignment: Program #9
//
// Course Name: Data Structures II
//
// Course Number: COSC 3100 - 10
//
// Due: April 23, 2019
//
// This is a program to create a list of students using a linked list
//
// Other files required:
// 1. Student.h
// 2. BST.h
// 3. Node.h
//
//****************************************************************************************************
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
#include "Student.h"
#include "BST.h"
//****************************************************************************************************
void process(BST<Student> &);
char getChoice();
void buildList(BST<Student> &);
void displayStudents(Student);
void printStudents(BST<Student> &);
void listInformation(BST<Student> &);
void addStudent(BST<Student> &);
void searchStudent(BST<Student> &);
void updateStudent(BST<Student> &);
void deleteStudent(BST<Student> &);
//****************************************************************************************************
int main()
{
BST<Student> studentList;
buildList(studentList);
process(studentList);
return 0;
}
//****************************************************************************************************
void process(BST<Student> & studentList)
{
char choice;
do
{
choice = getChoice();
switch(choice)
{
case 'A': addStudent(studentList);
break;
case 'S': updateStudent(studentList);
break;
case 'U': updateStudent(studentList);
break;
case 'D': deleteStudent(studentList);
break;
case 'P': printStudents(studentList);
break;
case 'L': listInformation(studentList);
break;
case 'Q': break;
}
}
while (choice != 'Q');
}
//****************************************************************************************************
char getChoice()
{
char choice;
bool valid;
cout << "======== MENU ========\n"
<< " A: Add a Student\n"
<< " S: Search a Student\n"
<< " U: Update a Student\n"
<< " D: Delete a Student\n"
<< " P: Display all Students\n"
<< " L: List Information\n"
<< " Q: Quit\n\n"
<< " Enter your choice: ";
do
{
cin >> choice;
choice = toupper(choice);
cout << endl;
switch (choice)
{
case 'A':
case 'S':
case 'U':
case 'D':
case 'P':
case 'L':
case 'Q': valid = true;
break;
default: valid = false;
cout << "\aInvalid choice\n" << "Please try again: ";
break;
}
}
while (!valid);
return choice;
}
//****************************************************************************************************
void buildList(BST<Student> & studentList)
{
Student student;
ifstream studentData;
studentData.open("studentFile.txt");
while (studentData >> student.id)
{
studentData.ignore();
studentData.getline(student.name, 50);
studentData.getline(student.citystate, 50);
studentData >> (student.phone);
studentData >> (student.gender);
studentData >> (student.year);
studentData >> (student.credits);
studentData >> (student.gpa);
studentData >> (student.major);
studentList.insert(student);
}
studentData.close();
}
//****************************************************************************************************
void displayStudent(Student student)
{
cout << student;
}
//****************************************************************************************************
void printStudents(BST<Student> & studentList)
{
cout << "==============================================================================" << endl;
cout << "ID" << setw(5) << "Name" << setw(10) << "Major" << setw(5) << "GPA" << setw(5)
<< "Credits" << endl;
studentList.inOrderTraversal(displayStudent);
cout << endl;
}
//****************************************************************************************************
void listInformation(BST<Student> & studentList)
{
int count = studentList.getCount();
int height = studentList.getHt();
cout << "Information about the student tree: " << endl;
cout << "Students in the list: " << count << endl;
cout << "Height of the list: " << height << endl;
if (!studentList.isEmpty())
{
cout << "This list is not empty" << endl;
}
else
{
cout << "This list is empty" << endl;
}
if(!studentList.isFull())
{
cout << "This list is not full" << endl;
}
else
{
cout << "This list is full" << endl;
}
cout << endl;
}
//****************************************************************************************************
void addStudent(BST<Student> & studentList)
{
Student student;
cout << "What is the new student's ID?: ";
cin >> student.id;
cout << "What is the student's name: ";
cin.ignore();
cin.getline(student.name, 50);
cout << "What is the student's citystate: ";
cin.getline(student.citystate, 50);
cout << "What is the student's phone: (Format: 1234567890)";
cin >> student.phone;
cout << "What is the student's gender: (enter 'M' or 'F')" << endl;
cin >> student.gender;
cout << "What year is the student: ";
cin >> student.year;
cout << "How many credits does the student have: ";
cin >> student.credits;
cout << "What is the student's GPA: ";
cin >> student.gpa;
cout << "What is the students major: (Enter abbriviated major)" << endl;
cin >> student.major;
studentList.insert(student);
}
//****************************************************************************************************
void searchStudent(BST<Student> & studentList)
{
Student student;
int id;
cout << "Which student would you like to find? : ";
cin >> id;
student.id = id;
if(!studentList.retrieve(student))
{
cout << "Could not find that student\n" << endl;
}
else
{
cout << "Here is that student: " << endl;
cout << student << endl;
}
}
//****************************************************************************************************
void updateStudent(BST<Student> & studentList)
{
Student student;
cout << "Which student would you like to update? : ";
cin >> student.id;
if(!studentList.update(student))
{
cout << "Could not find that student" << endl;
}
else
{
cout << "What is the new student's ID?: ";
cin >> student.id;
cout << "What is the student's name: ";
cin.ignore();
cin.getline(student.name, 50);
cout << "What is the student's citystate: ";
cin.getline(student.citystate, 50);
cout << "What is the student's phone: (Format: 1234567890)";
cin >> student.phone;
cout << "What is the student's gender: (enter 'M' or 'F')" << endl;
cin >> student.gender;
cout << "What year is the student: ";
cin >> student.year;
cout << "How many credits does the student have: ";
cin >> student.credits;
cout << "What is the student's GPA: ";
cin >> student.gpa;
cout << "What is the students major: (Enter abbriviated major)" << endl;
cin >> student.major;
}
cout << "\nHere is the updated student: " << endl;
cout << student << endl;
}
//****************************************************************************************************
void deleteStudent(BST<Student> & studentList)
{
Student student;
int id;
cout << "Which student would you like to delete? : ";
cin >> id;
student.id = id;
if(!studentList.remove(student))
{
cout << "Could not remove that student\n" << endl;
}
else
{
cout << "Here is the removed student:\n" << endl;
cout << student << endl;
}
}
//****************************************************************************************************
|
Java
|
UTF-8
| 838
| 2.28125
| 2
|
[] |
no_license
|
package com.integration.structure.facade.client;
import com.integration.structure.facade.AbstractEncryptFacade;
import com.integration.structure.facade.impl.EncryptFacade;
import com.integration.structure.facade.impl.NewEncryptFacade;
/**
* Created by ZhangGang on 2019/6/4.
*/
public class Client {
public static void main(String args[]) {
AbstractEncryptFacade ef = new EncryptFacade();
AbstractEncryptFacade newef = new NewEncryptFacade();
String fileNameSrc = "D:\\signalway\\TestEntity\\src.txt";
String fileNameDes = "D:\\signalway\\TestEntity\\des.txt";
String newfileNameDes = "D:\\signalway\\TestEntity\\newdes.txt";
ef.FileEncrypt(fileNameSrc, fileNameDes);
newef.FileEncrypt(fileNameSrc, newfileNameDes);
System.out.println("执行完毕!");
}
}
|
Python
|
UTF-8
| 5,350
| 3.125
| 3
|
[] |
no_license
|
import tkinter as tk
import steamapi
class Application(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.create_widgets(master)
def create_widgets(self, master):
tk.Label(master, text=" ").grid(row=0, column=0)
tk.Label(master, text="Steam API Key:").grid(row=2, column=0)
self.api_key = tk.Entry(master, borderwidth=1)
self.api_key.grid(row=2, column=1)
tk.Label(master, text=" ").grid(row=3, column=0)
tk.Label(master, text="Add SteamIds to compare\n(Seperate with commas):").grid(row=4, column=0, ipady=30)
steamids_scrollbar = tk.Scrollbar(master)
self.steamids_input = tk.Text(master, height=5, width=30, borderwidth=2, relief="solid")
steamids_scrollbar.config(command=self.steamids_input.yview)
self.steamids_input.config(yscrollcommand=steamids_scrollbar.set, height=3)
self.steamids_input.insert(tk.END, "Add friends here.")
self.steamids_input.grid(row=4, column=1)
steamids_scrollbar.grid(row=4, column=2)
tk.Label(master, text=" ").grid(row=5, column=0)
submit = tk.Button(master)
submit["text"] = "Show Common Games"
submit["command"] = self.submit
submit.grid(row=6, column=1)
reset = tk.Button(master)
reset["text"] = "Reset Data"
reset["command"] = self.reset
reset.grid(row=6, column=0)
def submit(self):
api_key = self.api_key.get()
steamids = self.get_steamids(self.steamids_input.get("1.0", tk.END))
if not self.is_valid_api_key(api_key):
print("Invalid API key!")
print(api_key)
self.reset()
return
if len(steamids) < 2:
print("Invalid friends array! At least two valid SteamIds needed.")
print(steamids)
self.reset()
return
for steamid in steamids:
if not self.is_valid_steamid(steamid):
print("SteamID " + steamid + " is not a 17 digits number!")
self.reset()
return
print("Entered SteamIds:")
print(steamids)
new_root = tk.Tk()
new_root.geometry("360x560")
Result(new_root, api_key, steamids)
def reset(self):
self.api_key.delete(0, tk.END)
self.steamids_input.delete(0.0, tk.END) # Yes, this actually can't be an int. I have no idea why.
def get_steamids(self, steamids_str):
steamids_str = "".join(steamids_str.split())
return steamids_str.split(',')
def is_valid_steamid(self, steamid):
return len(steamid) == 17 and steamid.isdigit()
def is_valid_api_key(self, api_key):
return len(api_key) == 32
class Result(tk.Frame):
def __init__(self, master, api_key, steamids):
super().__init__(master)
self.master = master
self.connect_to_steam(api_key, steamids)
self.get_common_games()
self.display_results()
def connect_to_steam(self, api_key, steamids):
self.connection = steamapi.core.APIConnection(api_key=api_key, validate_key=True)
self.users = [steamapi.user.SteamUser(id) for id in steamids]
def get_common_games(self):
all_games = []
all_gameids = []
all_users_gameids = []
print("\n\n*STEAM USERS*")
for user in self.users:
user_game_ids = []
for game in user.games:
appid = game.appid
if appid not in all_gameids:
all_games.append(game)
all_gameids.append(appid)
user_game_ids.append(game.appid)
all_users_gameids.append(user_game_ids)
print(user.name + ", level " + str(user.level) + ", owns " + str(len(user_game_ids)) + " games")
common_gameids = all_users_gameids[0]
for i in range(1, len(all_users_gameids)):
common_gameids = self.intersection(common_gameids, all_users_gameids[i])
common_games = [self.get_game_from_list(all_games, steamid) for steamid in common_gameids]
common_games = list(filter(None, common_games))
self.common_game_names = [game.name for game in common_games]
self.common_game_names.sort()
print("\n\n*COMMON GAMES*")
for game_name in self.common_game_names:
print(game_name)
def display_results(self):
game_names_str = "\n".join(self.common_game_names)
game_names_scrollbar = tk.Scrollbar(self.master)
game_names_display = tk.Text(self.master, height=33, width=40, borderwidth=2, relief="solid")
game_names_scrollbar.config(command=game_names_display.yview)
game_names_display.config(yscrollcommand=game_names_scrollbar.set, height=33, width=40)
game_names_display.insert(tk.END, game_names_str)
game_names_display.grid(row=0, column=0)
game_names_scrollbar.grid(row=0, column=1)
def intersection(self, list_a, list_b):
return list(set(list_a) & set(list_b))
def get_game_from_list(self, games, appid):
for game in games:
if appid == game.appid:
return game
return None
root = tk.Tk()
root.geometry("420x270")
app = Application(master=root)
app.mainloop()
|
Java
|
UTF-8
| 331
| 1.78125
| 2
|
[] |
no_license
|
package zdanie3;
public class OpisZadania {
/*
Stworz dwie grupy zadan:
Producent: ktorego zadaniem bedzie np: co sekunde sprawdzanie np monitorowania ofert pracy na portalu np:
justJoin.It albo dowolnym innnym,
Consumer: bedzie pobieral oferty (nazwa, stanowisko, stawka, podstawowe wymagania)
z producenta.
*/
}
|
PHP
|
UTF-8
| 1,930
| 2.59375
| 3
|
[] |
no_license
|
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Đổi Mật Khẩu</title>
</head>
<form method="post">
<table align="center">
<tr>
<td>HỆ THỐNG ATM</td>
</tr>
<tr>
<td>Mật Khẩu Cũ</td>
<td><input type="password" name="txtOldPasswd"></td>
</tr>
<tr>
<td>Mật Khẩu Mới</td>
<td><input type="password" name="txtNewPasswd"></td>
</tr>
<tr>
<td>Nhập Lại Mật Khẩu</td>
<td><input type="password" name="txtPasswd"></td>
</tr>
<tr>
<td><input type="submit" name="OK" value="Xác Nhận"></td>
<td><input type="button" name="Return" value="Quay Lại" onClick="location='menu.php'"></td>
</tr>
</table>
</form>
<?php include 'connect.php';?>
<?php
$username = $_SESSION['txtTK'];
$sql="select * from login where UserName = '$username'";
$exeSql=mysqli_query($con, $sql);
while ($num =mysqli_fetch_array($exeSql)) {
?>
<?php
if(isset($_POST['OK']))
{
$mkcu = $_POST['txtOldPasswd'];
$mkmoi = $_POST['txtNewPasswd'];
$nlmk = $_POST['txtPasswd'];
if($num['PassWord'] != $mkcu)
{
echo "<script>alert('Sai mật khẩu.Update thật bại')</script>";
}else{
if($mkmoi != $nlmk){
echo "<script> alert('password và nhập lại mật khẩu phải trùng nhau')</script>";
die();
}else{
$sqlupdate = "UPDATE login SET PassWord = '$mkmoi' WHERE UserName = '$username'";
$ex = mysqli_query($con,$sqlupdate);
if($ex){
echo "<script> alert('Update thanh cong')</script>";
}
}
}}
?>
<?php } ?>
<body>
</body>
</html>
|
C++
|
UTF-8
| 1,176
| 3.25
| 3
|
[] |
no_license
|
//
// Created by nathan on 2021-01-23.
//
#include "io.h"
int8_t * readRawData(string fileName, char delimiter, int * sizeRet)
{
int size = 0;
ifstream infile;
infile.open (fileName);
if (infile.is_open())
{
string datum;
while (getline(infile, datum, delimiter))
size++;
int8_t * rawData = new int8_t[size];
infile.clear();
infile.seekg(0, ios::beg);
int i = 0;
while (getline(infile, datum, delimiter)) {
rawData[i] = stoi(datum, nullptr, 10);
i++;
}
*sizeRet = size;
infile.close();
return rawData;
}
cout << "Error opening file";
*sizeRet = -1;
return NULL;
}
bool writeData(string filename, char delimiter, int size, int8_t * data) {
ofstream ofile;
ofile.open (filename);
if (ofile.is_open()) {
for(int i = 0; i < size; i++) {
ofile << static_cast<int>(data[i]);
if(i != size - 1) ofile << delimiter;
}
ofile.close();
return true;
}
else {
cout << "file cannot be opened for writing\n";
return false;
}
}
|
Shell
|
UTF-8
| 746
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
#!/bin/bash
package_name="glew"
package_version="2.1.0"
package_description="Adds GLEW -- The OpenGL Extension Wrangler Library -- 2.1.0 to your environment."
set -o errexit \
-o nounset \
-o pipefail
source includes/source_includes.sh
module purge
module load gcc-libs
module load compilers/gnu
module load cmake
make_build_env ""
cd "$build_dir"
curl -sLO https://downloads.sourceforge.net/project/glew/glew/2.1.0/glew-2.1.0.tgz
manifest \
sha256:04de91e7e6763039bc11940095cd9c7f880baba82196a7765f727ac05a993c95 glew-2.1.0.tgz
tar -xf glew-2.1.0.tgz
cd glew-2.1.0
cd build
cmake \
-D CMAKE_INSTALL_PREFIX="$install_prefix" \
./cmake
make all
make install
make_module_v2
chmod a+rX "$module_dir"
post_build_report
|
Swift
|
UTF-8
| 921
| 3
| 3
|
[] |
no_license
|
//
// Data+Codable.swift
// ContactList
//
// Created by abuzeid on 01.10.20.
// Copyright © 2020 abuzeid. All rights reserved.
//
import Foundation
public extension Data {
func parse<T: Decodable>() -> T? {
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(DateFormatter.defaultJsonFormatter)
return try decoder.decode(T.self, from: self)
} catch let error {
print(error)
}
return nil
}
}
extension DateFormatter {
static var defaultJsonFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}
}
extension Date {
func getFormattedDate(format: String) -> String {
let dateformat = DateFormatter()
dateformat.dateFormat = format
return dateformat.string(from: self)
}
}
|
Java
|
UTF-8
| 1,455
| 2.0625
| 2
|
[] |
no_license
|
package tpm.qlts.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tpm.qlts.entitys.NhanVienRefThietBi;
import tpm.qlts.entitys.NhanVienRefThietBiPK;
import tpm.qlts.repositorys.NhanVienRefThietBiRepository;
@Service("NhanVienRefThietBiService")
public class NhanVienRefThietBiService {
@Autowired
private NhanVienRefThietBiRepository nhanVienRefThietBiRepository;
public void deleteById(NhanVienRefThietBiPK id)
{
nhanVienRefThietBiRepository.deleteById(id);
}
public NhanVienRefThietBi update(NhanVienRefThietBi nhanVienRefThietBi) {
return nhanVienRefThietBiRepository.save(nhanVienRefThietBi);
}
public List<NhanVienRefThietBi> updateAll(List<NhanVienRefThietBi> nhanVienRefThietBis) {
return (List<NhanVienRefThietBi>) nhanVienRefThietBiRepository.saveAll(nhanVienRefThietBis);
}
public Optional<NhanVienRefThietBi> findById(NhanVienRefThietBiPK id)
{
return nhanVienRefThietBiRepository.findById(id);
}
public List<NhanVienRefThietBi> findAll()
{
return (List<NhanVienRefThietBi>) nhanVienRefThietBiRepository.findAll();
}
public NhanVienRefThietBi getAllMathietbi(long id){
return nhanVienRefThietBiRepository.getAllMathietbi(id);
}
public List<NhanVienRefThietBi> getAllNVTBByIdPhongBan(String id){
return nhanVienRefThietBiRepository.getAllNVTBByIdPhongBan(id);
}
}
|
C#
|
UTF-8
| 1,016
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BandTracker.Models;
namespace BandTracker.Models.Tests
{
[TestClass]
public class BandTests : IDisposable
{
public BandTests()
{
DBConfiguration.ConnectionString = "server=localhost;user id=root;password=root;port=8889;database=band_tracker_test;";
}
public void Dispose()
{
Venue.ClearAll();
Band.ClearAll();
}
[TestMethod]
public void Save_SavesToDatabase_BandList()
{
// Arrange
Band testBand = new Band("Blink-182", "punkrock");
// Act
testBand.Save();
List<Band> result = Band.GetAll();
List<Band> testList = new List<Band>{testBand};
// Assert
CollectionAssert.AreEqual(testList, result);
}
[TestMethod]
public void GetAll_BEmptyAtFirst_0()
{
int result = Band.GetAll().Count;
Assert.AreEqual(0, result);
}
}
}
|
PHP
|
UTF-8
| 1,430
| 2.59375
| 3
|
[] |
no_license
|
<?php
namespace App\Controller;
use App\Entity\Album;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/albums", methods={"GET"})
*/
class AlbumController extends AbstractController
{
/**
* @Route("/{token}")
*/
public function getAlbum(Album $album): JsonResponse
{
$return = $this->albumToArray($album);
return $this->json($return);
}
private function albumToArray($album): array
{
$artist = $album->getArtist();
$return = [
'token' => $album->getToken(),
'title' => $album->getTitle(),
'description' => $album->getDescription(),
'cover' => $album->getCover(),
'artist' => [
'token' => $artist->getToken(),
'name' => $artist->getName(),
],
'songs' => [],
];
foreach ($album->getSongs() as $song) {
$minutes = floor($song->getSeconds() / 60);
$seconds = $song->getSeconds() % 60;
$return['songs'][] = [
'title' => $song->getTitle(),
'length' => sprintf('%d:%02d', $minutes, $seconds),
];
}
return $return;
}
}
|
Java
|
UTF-8
| 674
| 1.921875
| 2
|
[] |
no_license
|
package net.canang.populi.core.model;
import com.vividsolutions.jts.geom.Polygon;
/**
* @author rafizan.baharum
* @since 6/29/13
*/
public interface District {
Long getId();
void setId(Long id);
/**
* @return
*/
String getCode();
void setCode(String code);
/**
* @return
*/
String getDescription();
void setDescription(String description);
/**
* @return
*/
Polygon getBound();
void setBound(Polygon bound);
/**
* @return
*/
State getState();
void setState(State state);
// transient
Integer getHeadCount();
void setHeadCount(Integer headCount);
}
|
Java
|
UTF-8
| 4,193
| 2.65625
| 3
|
[] |
no_license
|
package com.hussein.java_project.models;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name="cards")
public class Card {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty(message="First Name is required!")
private String firstName;
@NotEmpty(message="Last Name is required!")
private String lastName;
@NotNull
private Long cardNumber;
@NotEmpty(message="Expiration date is required!")
private String expirationDate;
@NotNull
private Integer cvvNumber;
@NotEmpty(message="Address is required!")
private String streetAddress;
@NotEmpty(message="City is required!")
private String cityName;
@NotEmpty(message="State is required!")
private String stateName;
@NotNull
private Integer zipcode;
// One to One
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="cardUser_id")
private User cardUser;
// Date Created
@Column(updatable=false)
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date createdAt;
private Date updatedAt;
@PrePersist
protected void onCreate(){
this.createdAt = new Date();
}
@PreUpdate
protected void onUpdate(){
this.updatedAt = new Date();
}
// Constructers
public Card() {
}
public Card(String firstName, String lastName, Long cardNumber, String expirationDate, Integer cvvNumber, String streetAddress, String cityName, String stateName, Integer zipcode) {
this.firstName = firstName;
this.lastName = lastName;
this.cardNumber = cardNumber;
this.cityName = cityName;
this.stateName = stateName;
this.streetAddress = streetAddress;
this.expirationDate = expirationDate;
this.cvvNumber = cvvNumber;
this.zipcode = zipcode;
}
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getCardNumber() {
return cardNumber;
}
public void setCardNumber(Long cardNumber) {
this.cardNumber = cardNumber;
}
public String getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(String expirationDate) {
this.expirationDate = expirationDate;
}
public Integer getCvvNumber() {
return cvvNumber;
}
public void setCvvNumber(Integer cvvNumber) {
this.cvvNumber = cvvNumber;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public Integer getZipcode() {
return zipcode;
}
public void setZipcode(Integer zipcode) {
this.zipcode = zipcode;
}
public User getCardUser() {
return cardUser;
}
public void setCardUser(User cardUser) {
this.cardUser = cardUser;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
|
Java
|
UTF-8
| 304
| 2.65625
| 3
|
[] |
no_license
|
package com.valerie.retactor;
/**
* Created by valerie on 15/7/28
*/
public class Cal2 extends Cal {
/** Pull Members Down*/
public int add(int a,int b){
return super.add(a, b);
}
/** Pull Members Up*/
public int sub(int a,int b){
return super.sub(a, b);
}
}
|
Java
|
UTF-8
| 1,222
| 2.53125
| 3
|
[] |
no_license
|
package com.example.firstactivity;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CounterActivity extends AppCompatActivity implements View.OnClickListener {
Button i,d,r;
TextView count;
int c=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter);
i=findViewById(R.id.inc);
d=findViewById(R.id.dec);
r=findViewById(R.id.reset);
count=findViewById(R.id.count);
i.setOnClickListener(this);
d.setOnClickListener(this);
r.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.inc:
c++;
count.setText("COUNT : "+c);
break;
case R.id.dec:
c--;
count.setText("COUNT : "+c);
break;
case R.id.reset:
c=0;
count.setText("COUNT : "+c);
break;
}
}
}
|
Java
|
UTF-8
| 18,817
| 2.015625
| 2
|
[] |
no_license
|
package th.go.motorcycles.web.enjoy.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.simple.JSONObject;
import th.go.motorcycles.app.enjoy.bean.BrandBean;
import th.go.motorcycles.app.enjoy.bean.MotorDetailBean;
import th.go.motorcycles.app.enjoy.bean.UserDetailsBean;
import th.go.motorcycles.app.enjoy.dao.MotorDetailDao;
import th.go.motorcycles.app.enjoy.exception.EnjoyException;
import th.go.motorcycles.app.enjoy.form.MotorDetailForm;
import th.go.motorcycles.app.enjoy.main.Constants;
import th.go.motorcycles.app.enjoy.utils.EnjoyUtils;
import th.go.motorcycles.web.enjoy.common.EnjoyStandardSvc;
import th.go.motorcycles.web.enjoy.logger.LogWrapper;
import th.go.motorcycles.web.enjoy.utils.MotorUtil;
public class MotorDetailServlet<E> extends EnjoyStandardSvc {
static final long serialVersionUID = 1L;
private static final LogWrapper logger = LogWrapper.getLogger(MotorDetailServlet.class);
private static final String FORM_NAME = "motorDetailForm";
private MotorUtil motorUtil = null;
private MotorDetailForm form = null;
private HttpServletRequest request = null;
private HttpServletResponse response = null;
private HttpSession session = null;
private UserDetailsBean userBean = null;
private MotorDetailDao dao = null;
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws Exception {
// TODO Auto-generated method stub
doProcess(request, response);
}
private void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("[MotorDetailServlet][execute][Begin]");
String pageAction = null;
try{
pageAction = MotorUtil.nullToStr(request.getParameter("pageAction"));
System.out.println("pageAction : " + pageAction);
this.motorUtil = new MotorUtil(request, response);
this.request = request;
this.response = response;
this.session = request.getSession(false);
this.userBean = (UserDetailsBean)session.getAttribute("userBean");
this.form = (MotorDetailForm)session.getAttribute(FORM_NAME);
this.dao = new MotorDetailDao();
if( pageAction.equals("")){
System.out.println("[MotorDetailServlet][onLoad][Begin]");
request.setAttribute("target", Constants.PAGE_URL +"/MotorDetailScn.jsp");
}else if(pageAction.equals("new")){
this.form = new MotorDetailForm();
request.setAttribute("target", Constants.PAGE_URL +"/MotorDetailScn.jsp");
}else if(pageAction.equals("searchData")){
this.onSearch();
}else if(pageAction.equals("getBrandName")){
this.getBrandName();
}else if(pageAction.equals("getModel")){
this.getModel();
}else if(pageAction.equals("getCompany")){
this.getCompany();
}else if(pageAction.equals("delRecord")){
this.delRecord();
}else if(pageAction.equals("saveUpdData")){
this.saveUpdData();
}
session.setAttribute(FORM_NAME, this.form);
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("[MotorDetailServlet][execute][End]");
}
}
private void onSearch() throws Exception{
System.out.println("[MotorDetailServlet][onSearch][Begin]");
List<MotorDetailBean> listMotorDetail = null;
MotorDetailBean bean = null;
MotorDetailBean beanResult = null;
String brandSearch = null;
String companySearch = null;
String brandCode = null;
String companyId = null;
boolean dataRet = false;
try{
bean = new MotorDetailBean();
brandSearch = this.request.getParameter("brandSearch");
companySearch = this.request.getParameter("companySearch");
bean.setBrandSearch(brandSearch);
bean.setCompanySearch(companySearch);
listMotorDetail = (List <MotorDetailBean>) this.dao.findModelDetail(bean,this.form);
if(listMotorDetail.size()>0){
this.form.setListMotorDetail(listMotorDetail);
brandCode = listMotorDetail.get(0).getBrandCode();
companyId = listMotorDetail.get(0).getCompanyId();
beanResult = new MotorDetailBean();
beanResult.setBrandSearch(brandSearch);
beanResult.setCompanySearch(companySearch);
beanResult.setBrandCode(brandCode);
beanResult.setCompanyId(companyId);
this.form.setMotorDetailBean(beanResult);
dataRet = true;
}
if(dataRet==true){
this.motorUtil.writeMSG("OK:"+brandSearch+":"+companySearch);
}else{
this.motorUtil.writeMSG("No record!!");
}
}catch(Exception e){
e.printStackTrace();
throw new Exception(e.getMessage());
}finally{
listMotorDetail = null;
bean = null;
brandSearch = null;
companySearch = null;
dataRet = false;
System.out.println("[MotorDetailServlet][onSearch][End]");
}
}
private void getBrandName(){
System.out.println("[MotorDetailServlet][getBrandName][Begin]");
String brandName = null;
List<String> list = new ArrayList<String>();
String[] strArray = null;
MotorDetailBean motorDetailBean = null;
try{
brandName = EnjoyUtils.nullToStr(this.request.getParameter("brandName"));
motorDetailBean = this.form.getMotorDetailBean();
logger.info("[lp_getBrandName] brandName :: " + brandName);
motorDetailBean.setBrandName(brandName);
list = this.dao.brandNameList(brandName);
strArray = new String[list.size()];
strArray = list.toArray(strArray);
this.motorUtil.writeJsonMSG((String[]) strArray);
}catch(Exception e){
e.printStackTrace();
logger.info("[lp_getBrandName] " + e.getMessage());
}finally{
logger.info("[lp_getBrandName][End]");
}
System.out.println("[MotorDetailServlet][getBrandName][End]");
}
private void getModel(){
logger.info("[MotorDetailServlet][getModel][Begin]");
String brandName = null;
String model = null;
List<String> list = new ArrayList<String>();
String[] strArray = null;
MotorDetailBean motorDetailBean = null;
try{
brandName = EnjoyUtils.nullToStr(this.request.getParameter("brandName"));
model = EnjoyUtils.nullToStr(this.request.getParameter("model"));
motorDetailBean = this.form.getMotorDetailBean();
logger.info("[getModel] brandName :: " + brandName);
logger.info("[getModel] model :: " + model);
motorDetailBean.setBrandName(brandName);
motorDetailBean.setModel(model);
list = this.dao.modelList(brandName, model);
strArray = new String[list.size()];
strArray = list.toArray(strArray);
this.motorUtil.writeJsonMSG((String[]) strArray);
}catch(Exception e){
e.printStackTrace();
logger.info("[getModel] " + e.getMessage());
}finally{
logger.info("[MotorDetailServlet][getModel][End]");
}
}
private void getCompany(){
System.out.println("[MotorDetailServlet][getCompany][Begin]");
String branchName = null;
List<String> list = new ArrayList<String>();
String[] strArray = null;
MotorDetailBean motorDetailBean = null;
try{
branchName = EnjoyUtils.nullToStr(this.request.getParameter("branchName"));
motorDetailBean = this.form.getMotorDetailBean();
logger.info("[getCompany] branchName :: " + branchName);
motorDetailBean.setBranchName(branchName);
list = this.dao.branchNameList(branchName);
strArray = new String[list.size()];
strArray = list.toArray(strArray);
this.motorUtil.writeJsonMSG((String[]) strArray);
}catch(Exception e){
e.printStackTrace();
logger.info("[getCompany] " + e.getMessage());
}finally{
logger.info("[getCompany][End]");
}
System.out.println("[MotorDetailServlet][getCompany][End]");
}
private void saveUpdData() throws Exception{
System.out.println("[MotorDetailServlet][saveUpdRecord][Begin]");
String motorCode = null;
String brandCode = null;
String brandName = null;
String model = null;
String chassis = null;
String engineNo = null;
String size = null;
String companyId = null;
String branchName = null;
String[] getMotorCode = null;
String[] getBrandCode = null;
String[] getBrandName = null;
String[] getModel = null;
String[] getChassis = null;
String[] getEngineNo = null;
String[] getSize = null;
String[] getCompanyId = null;
String[] getBranchName = null;
String[] getMotorStatus = null;
MotorDetailBean bean = null;
BrandBean brandBean = null;
MotorDetailBean companyBean = null;
boolean insertRet = true;
boolean updateRet = true;
JSONObject obj = new JSONObject();
try{
getMotorCode = this.request.getParameterValues("hidMotorcyclesCode");
getBrandCode = this.request.getParameterValues("hidBrandCode");
getBrandName = this.request.getParameterValues("brandName");
getModel = this.request.getParameterValues("model");
getChassis = this.request.getParameterValues("chassis");
getEngineNo = this.request.getParameterValues("engineNo");
getSize = this.request.getParameterValues("size");
getCompanyId = this.request.getParameterValues("hidCompanyId");
getBranchName = this.request.getParameterValues("branchName");
getMotorStatus = this.request.getParameterValues("hidMotorStartus");
System.out.println("[MotorDetailServlet][MoterCode . length : ]" + getMotorCode.length);
for(int i=0; i < getMotorCode.length; i++){
System.out.println( " MotorDetailServlet == > " + getMotorCode[i] );
motorCode = EnjoyUtils.nullToStr(getMotorCode[i]);
brandCode = EnjoyUtils.nullToStr(getBrandCode[i]);
brandName = EnjoyUtils.nullToStr(getBrandName[i]);
model = EnjoyUtils.nullToStrUpperCase(getModel[i]);
chassis = EnjoyUtils.nullToStrUpperCase(getChassis[i]);
engineNo = EnjoyUtils.nullToStrUpperCase(getEngineNo[i]);
size = EnjoyUtils.nullToStr(getSize[i]);
companyId = EnjoyUtils.nullToStr(getCompanyId[i]);
branchName = EnjoyUtils.nullToStr(getBranchName[i]);
bean = new MotorDetailBean();
bean.setMotorcyclesCode(motorCode);
bean.setBrandCode(brandCode);
bean.setBrandName(brandName.toUpperCase());
bean.setModel(model);
bean.setChassis(chassis);
bean.setEngineNo(engineNo);
bean.setSize(EnjoyUtils.replaceComma(size));
bean.setCompanyId(companyId);
bean.setBranchName(branchName.toUpperCase());
logger.info("[lp_save] brandName :: " + brandName);
logger.info("[lp_save] branchName :: " + branchName);
brandBean = this.dao.validateBrandName(brandName);
companyBean = this.dao.validateBranchName(branchName);
logger.info("[lp_save] brandBean.getErrMsg() :: " + brandBean.getErrMsg());
logger.info("[lp_save] companyBean.getErrMsg() :: " + companyBean.getErrMsg());
if(brandBean.getErrMsg().equals("")&& companyBean.getErrMsg().equals("")){
logger.info("[lp_save] BrandCode :: " + brandBean.getBrandCode());
logger.info("[lp_save] CompanyId :: " + companyBean.getCompanyId());
if(getMotorStatus[i].equals("U")){//update
System.out.println( " MotorDetailServlet update : " + bean.toString() );
updateRet = false;
bean.setBrandCode(brandBean.getBrandCode());
bean.setCompanyId(companyBean.getCompanyId());
System.out.println(" bean to update : "+bean.toString());
updateRet = this.dao.updateMotorcycles(bean);
if(updateRet == true ){
System.out.println(" update MotorDetailBean : SUCCESS");
}
}else if(getMotorStatus[i].equals("N") ){//Add new
insertRet = false;
System.out.println( " MotorDetailServlet insert : " + bean.toString() );
bean.setBrandCode(brandBean.getBrandCode());
bean.setCompanyId(companyBean.getCompanyId());
System.out.println(" bean to insert : "+bean.toString());
insertRet = this.dao.insertMotorcycles(bean,this.form);
if(insertRet == true ){
System.out.println(" Insert MotorDetailBean : SUCCESS");
}
}
}else{
if (( ! brandBean.getErrMsg().equals("")) && ( ! companyBean.getErrMsg().equals(""))) {
throw new EnjoyException(brandBean.getErrMsg()+" หรือ "+companyBean.getErrMsg());
} else if ( ! brandBean.getErrMsg().equals("")) {
throw new EnjoyException(brandBean.getErrMsg());
} else if ( ! companyBean.getErrMsg().equals("")) {
throw new EnjoyException(companyBean.getErrMsg());
}
}
}
logger.info("[lp_save] insertRet :: " + insertRet);
logger.info("[lp_save] updateRet :: " + updateRet);
if(insertRet==true && updateRet==true){
obj.put("status", "SUCCESS");
}else{
bean.setErrMsg("เกิดข้อผิดพลาดในการบันทึกข้อมูล");
throw new EnjoyException(bean.getErrMsg());
}
}catch(EnjoyException e){
obj.put("status", "ERROR");
obj.put("errMsg", e.getMessage());
e.printStackTrace();
}catch(Exception e){
obj.put("status", "ERROR");
obj.put("errMsg", "เกิดข้อผิดพลาดในการบันทึกข้อมูล");
e.printStackTrace();
}finally{
this.motorUtil.writeMSG(obj.toString());
motorCode = null;
brandCode = null;
brandName = null;
model = null;
chassis = null;
engineNo = null;
size = null;
companyId = null;
branchName = null;
getMotorCode = null;
getBrandCode = null;
getBrandName = null;
getModel = null;
getChassis = null;
getEngineNo = null;
getSize = null;
getCompanyId = null;
getBranchName = null;
getMotorStatus = null;
bean = null;
brandBean = null;
companyBean = null;
updateRet = false;
insertRet = false;
System.out.println("[MotorDetailServlet][saveUpdRecord][End]");
}
}
private void delRecord() throws Exception{
System.out.println("[MotorDetailServlet][delRecord][Begin]");
MotorDetailBean bean = null;
String motorCode = null;
boolean dataRet = false;
String brandSearch = null;
String companySearch = null;
try{
bean = new MotorDetailBean();
motorCode = EnjoyUtils.nullToStr(this.request.getParameter("motorCode"));
brandSearch = EnjoyUtils.nullToStr(this.request.getParameter("brandSearch"));
companySearch = EnjoyUtils.nullToStr(this.request.getParameter("companySearch"));
bean.setMotorcyclesCode(motorCode);
bean.setBranchName(brandSearch);
bean.setCompanyName(companySearch);
if(bean.getMotorcyclesCode()!="" || bean.getMotorcyclesCode()!=null){
dataRet = this.dao.deleteMotorcycles(bean);
}
if(dataRet==true){
this.motorUtil.writeMSG("OK");
this.onSearchAfterDelete(bean);
}else{
this.motorUtil.writeMSG("MotorDetailServlet Delete failed !!");
}
}catch(Exception e){
e.printStackTrace();
throw new Exception(e.getMessage());
}finally{
bean = null;
motorCode = null;
dataRet = false;
System.out.println("[MotorDetailServlet][delRecord][End]");
}
}
private void onSearchAfterDelete(MotorDetailBean bean) throws Exception{
System.out.println("[MotorDetailServlet][onSearchAfterDelete][Begin]");
List<MotorDetailBean> listMotorDetail = null;
MotorDetailBean beanResult = null;
String brandCode = null;
String companyId = null;
boolean dataRet = false;
String brandSearch = null;
String companySearch = null;
MotorDetailBean motorDetailBean = null;
try{
motorDetailBean = new MotorDetailBean();
brandSearch = EnjoyUtils.nullToStr(this.request.getParameter("brandSearch"));
companySearch = EnjoyUtils.nullToStr(this.request.getParameter("companySearch"));
motorDetailBean.setBrandSearch(brandSearch);
motorDetailBean.setCompanySearch(companySearch);
System.out.println("onSearchAfterDelete motorDetailBean getBrandSearch :"+motorDetailBean.getBranchName());
System.out.println("onSearchAfterDelete motorDetailBean getCompanySearch :"+motorDetailBean.getCompanySearch());
listMotorDetail = (List <MotorDetailBean>) this.dao.findModelDetail(motorDetailBean,this.form);
if(listMotorDetail.size()>0){
this.form.setListMotorDetail(listMotorDetail);
brandCode = listMotorDetail.get(0).getBrandCode();
companyId = listMotorDetail.get(0).getCompanyId();
beanResult = new MotorDetailBean();
beanResult.setBrandSearch(bean.getBranchName());
beanResult.setCompanySearch(bean.getCompanyName());
beanResult.setBrandCode(brandCode);
beanResult.setCompanyId(companyId);
this.form.setMotorDetailBean(beanResult);
dataRet = true;
}
if(dataRet==true){
this.motorUtil.writeMSG("OK:"+bean.getBranchName()+":"+bean.getCompanyName());
}else{
this.motorUtil.writeMSG("No record!!");
}
}catch(Exception e){
e.printStackTrace();
throw new Exception(e.getMessage());
}finally{
listMotorDetail = null;
bean = null;
dataRet = false;
System.out.println("[MotorDetailServlet][onSearchAfterDelete][End]");
}
}
}
|
Go
|
UTF-8
| 373
| 2.671875
| 3
|
[] |
no_license
|
/*
* for index, card := range cards {
* index: index of this element in the array
* card : current item iterating over
* range *** : take the slice and loop over it
*}
*/
package main
func main() {
cards := newDeck()
cards.shuffle()
//cards.saveToFile("myCards")
//hand, remainingCards := deal(cards, 5)
//card1 := newDeckFromFile("myCards")
cards.print()
}
|
C++
|
UTF-8
| 634
| 3.125
| 3
|
[] |
no_license
|
#include "ExceptionLine.h"
ExceptionLine::ExceptionLine (const int &num,const string &error, const string& correction)
{
this->num = num;
this->error = error;
this->correction=correction;
}
string ExceptionLine::what ()
{
return "Ошибка: " + error;
}
int ExceptionLine::code ()
{
return num;
}
string ExceptionLine::fix ()
{
return correction;
}
bool ExceptionLine::CheckLine ( const string data )
{
if (data.empty())
throw ExceptionLine (1, "пустая строка.", "При вводе используйте любые символы.");
return true;
}
|
Java
|
UTF-8
| 6,560
| 3.140625
| 3
|
[] |
no_license
|
package eight_puzzle;
import java.util.ArrayList;
import java.util.List;
import edu.princeton.cs.algs4.StdRandom;
public class Board {
private int[][] blocks;
private int hamming;
private int manhattan;
private final int n;
private int blankPosition;
public Board(int[][] blocksParam) {
this.n = blocksParam.length;
int zeroPos = -1;
this.blocks = new int[n][n];
for (int i = 0; i < blocksParam.length; i++) {
for (int j = 0; j < blocksParam.length; j++) {
this.blocks[i][j] = blocksParam[i][j];
if (this.blocks[i][j] == 0) {
zeroPos = i * n + j;
}
}
}
blankPosition = zeroPos;
hamming = 0;
manhattan = 0;
for (int i = 0; i < this.blocks.length; i++) {
for (int j = 0; j < this.blocks.length; j++) {
hamming += calculateHamming(i, j);
manhattan += calculateManhattan(i, j);
}
}
}
private int calculateHamming(int i, int j) {
if (this.blocks[i][j] != 0 && this.blocks[i][j] != ((i * n) + j + 1)) {
return 1;
}
return 0;
}
private int calculateManhattan(int i, int j) {
if (this.blocks[i][j] != 0) {
int linha = (int) Math.ceil((double) this.blocks[i][j] / n);
int coluna = (this.blocks[i][j] % n == 0 ? n
: (this.blocks[i][j] % n));
return Math.abs(linha - i - 1) + Math.abs(coluna - j - 1);
}
return 0;
}
public int dimension() {
return n;
}
public int hamming() {
return hamming;
}
public int manhattan() {
return manhattan;
}
public boolean isGoal() {
return hamming() == 0;
}
private Board twinRandom() {
Board blocksTwin = new Board(blocks);
boolean found = false;
while (!found) {
int i1 = StdRandom.uniform(n);
int j1 = StdRandom.uniform(n);
int i2 = StdRandom.uniform(n);
int j2 = StdRandom.uniform(n);
if ((i1 != i2 || j1 != j2) && blocksTwin.blocks[i1][j1] != 0
&& blocksTwin.blocks[i2][j2] != 0) {
blocksTwin.exchange(i1, j1, i2, j2);
found = true;
}
}
return blocksTwin;
}
public Board twin() {
int position1 = 0;
int position2 = 0;
for (int i1 = 0; i1 < blocks.length; i1++) {
for (int j1 = 0; j1 < blocks.length; j1++) {
for (int i2 = 0; i2 < blocks.length; i2++) {
for (int j2 = 0; j2 < blocks.length; j2++) {
if ((i1 != i2 || j1 != j2) && blocks[i1][j1] != 0
&& blocks[i2][j2] != 0) {
position1 = i1 * n + j1;
position2 = i2 * n + j2;
if ((position1 < position2 && blocks[i1][j1] > blocks[i2][j2])
|| (position1 > position2 && blocks[i1][j1] < blocks[i2][j2])) {
Board blocksTwin = new Board(blocks);
blocksTwin.exchange(i1, j1, i2, j2);
return blocksTwin;
}
}
}
}
}
}
return twinRandom();
}
private void exchange(int i1, int j1, int i2, int j2) {
this.hamming -= (calculateHamming(i1, j1) + calculateHamming(i2, j2));
this.manhattan -= (calculateManhattan(i1, j1) + calculateManhattan(i2,
j2));
int aux = this.blocks[i1][j1];
this.blocks[i1][j1] = this.blocks[i2][j2];
this.blocks[i2][j2] = aux;
if (this.blocks[i1][j1] == 0) {
blankPosition = i1 * n + j1;
} else if (this.blocks[i2][j2] == 0) {
blankPosition = i2 * n + j2;
}
this.hamming += (calculateHamming(i1, j1) + calculateHamming(i2, j2));
this.manhattan += (calculateManhattan(i1, j1) + calculateManhattan(i2,
j2));
}
public boolean equals(Object y) {
if (y == null) {
return false;
}
if (y.getClass() != this.getClass()) {
return false;
}
Board other = (Board) y;
if (n != other.blocks.length) {
return false;
}
for (int i = 0; i < blocks.length; i++) {
if (n != other.blocks[i].length) {
return false;
}
for (int j = 0; j < blocks.length; j++) {
if (blocks[i][j] != other.blocks[i][j]) {
return false;
}
}
}
return true;
}
public Iterable<Board> neighbors() {
int i = (int) Math.floor((double) blankPosition / n);
int j = (blankPosition % n);
List<Board> neighbors = new ArrayList<Board>();
if (i > 0) {
Board newboard = new Board(blocks);
newboard.exchange(i, j, i - 1, j);
neighbors.add(newboard);
}
if (i < n - 1) {
Board newboard = new Board(blocks);
newboard.exchange(i, j, i + 1, j);
neighbors.add(newboard);
}
if (j > 0) {
Board newboard = new Board(blocks);
newboard.exchange(i, j, i, j - 1);
neighbors.add(newboard);
}
if (j < n - 1) {
Board newboard = new Board(blocks);
newboard.exchange(i, j, i, j + 1);
neighbors.add(newboard);
}
return neighbors;
}
public String toString() {
StringBuilder result = new StringBuilder(n + "");
for (int i = 0; i < blocks.length; i++) {
result.append("\n");
for (int j = 0; j < blocks.length; j++) {
result.append(" " + (this.blocks[i][j]));
}
}
return result.toString();
}
public static void main(String[] args) {
int[][] b = { { 8, 1, 3 }, { 4, 2, 0 }, { 7, 6, 5 } };
// int[][] b = {{1, 2, 0}, {4, 5, 6}, {7, 8, 3}};
// System.out.println((new Board(b)).manhattan());
// System.out.println((new Board(b)).hamming());
for (Board board : (new Board(b)).neighbors()) {
System.out.println(board);
}
}
}
|
Go
|
UTF-8
| 1,895
| 3
| 3
|
[] |
no_license
|
package main
import (
"encoding/json"
"fmt"
"time"
"github.com/nautilus/events"
"github.com/AlecAivazis/maestro/common"
)
// MaestroLogging is the service responsible for collecting and aggregating logs.
type MaestroLogging struct {
events.EventBroker
}
var logCache = make(map[string][]common.LogEntry)
func (s *MaestroLogging) HandleAction(a *events.Action) {
// what we do with the action depends on the type
switch a.Type {
// if we are logging something new
case common.ActionLogAction:
// a log payload to write to
payload := common.LogPayload{}
// try to parse the payload into the struct we know it to follow
err := json.Unmarshal([]byte(a.Payload), &payload)
// if something went wrong
if err != nil {
fmt.Println(err.Error())
return
}
// the log entry for the input
entry := common.LogEntry{
Body: payload.Payload,
DateCreated: time.Now().Format("Mon Jan _2 15:04:05 2006"),
}
// look for logs with the current label
val, ok := logCache[payload.Label]
// if there is an entry in the cache
if ok {
// add the payload to the cache
logCache[payload.Label] = append(val, entry)
} else {
// otherwise there is no log with that label so save one
logCache[payload.Label] = []common.LogEntry{entry}
}
// if we need to retrieve logs for a particular project
case common.ActionRetrieveLogs:
// the request for logs
req := common.RetrieveLogPayload{}
// try to unmarhsal the event payload into the structure we want
err := json.Unmarshal([]byte(a.Payload), &req)
if err != nil {
fmt.Println(err.Error())
return
}
// marshal the appropriate log entries
str, err := json.Marshal(logCache[req.Label])
if err != nil {
fmt.Println(err.Error())
return
}
// send the logs to the requester
events.Reply(s, a, &events.Action{
Type: "Hello",
Payload: string(str),
})
}
}
|
Java
|
UTF-8
| 1,188
| 2.09375
| 2
|
[] |
no_license
|
package com.example.dm2.ejercicios17;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void navegacion(View v) {
if (v.getId() == R.id.buttonActividad01){
Intent intent = new Intent(MainActivity.this, Actividad1.class);
startActivity(intent);
}
if (v.getId() == R.id.buttonActividad02){
Intent intent = new Intent(MainActivity.this, Actividad2.class);
startActivity(intent);
}
if (v.getId() == R.id.buttonActividad03){
Intent intent = new Intent(MainActivity.this, Actividad3.class);
startActivity(intent);
}
if (v.getId() == R.id.buttonActividad04){
Intent intent = new Intent(MainActivity.this, Actividad4.class);
startActivity(intent);
}
}
public void salir(View v){
finish();
}
}
|
C#
|
UTF-8
| 4,307
| 2.5625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using ToDo.WebApp.Models;
//using todoModels = ToDo.WebApp.Models;
using ToDo.WebApp.Models.Enums;
//using System.Threading.Tasks;
namespace ToDo.WebApp.Controllers
{
public class TasksController : Controller
{
private static IList<Task> _tasks;
static TasksController()
{
InitializeTasks();
}
private static void InitializeTasks()
{
_tasks = new List<Task>
{
new Task
{
Description = "Task 1 description",
Priority = Priority.Important,
Status = Status.ToDo,
Title = "Task 1 title",
Type = TaskType.Work,
SubTasks = new List<SubTask>
{
new SubTask
{
Description = "SubTask 1, Task 1 description",
Status = Status.ToDo,
Title = "SubTask 1, Task 1 title"
},
new SubTask
{
Description = "SubTask 2, Task 1 description",
Status = Status.Done,
Title = "SubTask 2, Task 1 title"
},
new SubTask
{
Description = "SubTask 3, Task 1 description",
Status = Status.InProgress,
Title = "SubTask 3, Task 1 title"
}
}
},
new Task
{
Description = "Task 2 description",
Priority = Priority.Medium,
Status = Status.InProgress,
Title = "Task 2 title",
Type = TaskType.Hobby,
SubTasks = new List<SubTask>
{
new SubTask
{
Description = "SubTask 1, Task 2 description",
Status = Status.InProgress,
Title = "SubTask 1, Task 2 title"
}
}
},
new Task
{
Description = "Task 3 description",
Priority = Priority.NotImportant,
Status = Status.Done,
Title = "Task 3 title",
Type = TaskType.Personal,
SubTasks = new List<SubTask>
{
new SubTask
{
Description = "SubTask 1, Task 3 description",
Status = Status.Done,
Title = "SubTask 1, Task 3 title"
},
new SubTask
{
Description = "SubTask 2, Task 3 description",
Status = Status.Done,
Title = "SubTask 2, Task 3 title"
}
}
},
};
foreach (var task in _tasks)
{
foreach (var subTask in task.SubTasks)
{
subTask.ParentTask = task;
}
}
}
public IActionResult Index(Status status = Status.ToDo)
{
var todoTasks = _tasks.Where(t => t.Status == status);
var statuses = Enum.GetNames(typeof(Status));
ViewBag.SelectedStatus = status;
return View(todoTasks);
}
[HttpGet]
public IActionResult AddTask()
{
return View();
}
[HttpPost]
public IActionResult AddTask(Task task)
{
if (ModelState.IsValid)
{
_tasks.Add(task);
return RedirectToAction("ToDo");
}
return View();
}
}
}
|
PHP
|
UTF-8
| 666
| 2.765625
| 3
|
[] |
no_license
|
<?php
header("Access-Control-Allow-Origin:*");
header("Content-Type: text/plain");
$myServer = "62.149.153.28";
$myUser = "MSSql187380";
$myPass = "u4uc43436l";
$myDB = "MSSql187380";
$serverName = $myServer; //serverName\instanceName
// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>$myDB, "UID"=>$myUser, "PWD"=>$myPass);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established";
}else{
echo "Connection could not be established";
die( print_r( sqlsrv_errors(), true));
}
?>
|
Markdown
|
UTF-8
| 455
| 2.578125
| 3
|
[] |
no_license
|
# Welcome to my portfolio!
You get to see all the guts behind my website.
## Summary
This website took about 2 years to make. I struggled with
learning React almost entirely on my own. Through my internship
and various projects for my classes at Georgia Tech,
I'm proud to present the culmination of my learnings
as a full-stack webapp developer.
## Stack
- Django back-end
- React front-end
- Hosted on AWS Lightsail
- DNS Hosted with AWS Route 53
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.