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,051
| 2.53125
| 3
|
[] |
no_license
|
package com.atguigu.test;
import java.util.HashMap;
import java.util.List;
import javax.swing.plaf.synth.SynthSeparatorUI;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.atguigu.bean.Department;
import com.atguigu.bean.Emploer;
import com.atguigu.dao.DepartmentMapper;
import com.atguigu.dao.EmployeeMapper;
/**
* 测试dao层的工作
* @author 79056
*推荐Spring的项目就可以使用spring的单元测试,可以自动注入我们需要的组件
* 使用这个注解ContextConfiguration指定spring配置文件的位置
* ContextConfiguration有一个属性叫locations,是一个数组
* RunWith是junit的注解
* 运行单元测试的时候你可以用哪个单元测试来运行,我们用的是spring的单元测试模块,RunWith(value)的value值就是
* SpringJunit4ClassRunner.class
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class MapperTest {
@Autowired
DepartmentMapper departmentMapper;
@Autowired
EmployeeMapper employeeMapper;
@Test
public void testCrud(){
//1.创建SpringIOC容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从容器中获取mapper
DepartmentMapper bean = ioc.getBean(DepartmentMapper.class);
System.out.println(bean);
// departmentMapper.insertDepartment(new Department("计算机7"));
// System.out.println(departmentMapper.findDepart("计算机"));
List<Emploer> resultFind = employeeMapper.getEmployees();
System.out.println(resultFind);
System.out.println(departmentMapper.findDepart1("计算机"));
String a = departmentMapper.findDepart1("计算机").get("dname");
}
}
|
C#
|
UTF-8
| 2,200
| 2.609375
| 3
|
[] |
no_license
|
using System.Collections.Generic;
using System.Linq;
using MobiFinanceBank.DAL.Repositories.Interfaces;
using MobiFinanceBank.Model.Models;
using MobiFinanceBank.Vm;
using MobiFinanceBank.VmService.Interfaces;
using ClientType = MobiFinanceBank.Model.Enums.ClientType;
namespace MobiFinanceBank.VmService
{
/// <summary>
/// Client overview view model service
/// </summary>
/// <seealso cref="IClientOverviewVmService"/>
public class ClientOverviewVmService: IClientOverviewVmService
{
private readonly IClientRepository clientRepository;
/// <summary>
/// Initializes new instance of client overview view model service
/// </summary>
/// <param name="_clientRepository">Client repository</param>
public ClientOverviewVmService(IClientRepository _clientRepository)
{
this.clientRepository = _clientRepository;
}
/// <summary>
/// Gets filtered client overview data
/// </summary>
/// <param name="overviewFilter">Overview filter</param>
/// <returns>Collection of clients</returns>
public IEnumerable<Client> GetClientOverview(ClientOverviewFilter overviewFilter)
{
var clients = this.clientRepository.GetAsQueryable();
if (overviewFilter.ClientType == ClientType.Privatni)
{
if (!string.IsNullOrEmpty(overviewFilter.FirstName))
clients = clients.Where(client => client.FirstName.Contains(overviewFilter.FirstName));
if (!string.IsNullOrEmpty(overviewFilter.LastName))
clients = clients.Where(client => client.LastName.Contains(overviewFilter.LastName));
}
if (overviewFilter.ClientType == ClientType.Poslovni)
{
if (!string.IsNullOrEmpty(overviewFilter.Company))
clients = clients.Where(client => client.CompanyName.Contains(overviewFilter.Company));
}
var clientsFiltered = clients.Where(client => client.ClientType.Name == overviewFilter.ClientType.ToString()).ToList();
return clientsFiltered;
}
}
}
|
C#
|
UTF-8
| 800
| 2.515625
| 3
|
[] |
no_license
|
using CodeGenerator.Core.Templates.Commands.Parameters;
using System.Collections.Generic;
using System;
namespace CodeGenerator.Core.Templates.Parser
{
public class FallbackParser : CommandParserBase
{
public FallbackParser(IInternalParsable parsable)
: base(parsable)
{
}
public override bool CanParse(string line)
{
if (!string.IsNullOrEmpty(line))
{
return CanParseInternal(new string[]
{ line
});
}
return false;
}
public override List<CommandParameterBase> Parse(string line)
{
line = line.Trim();
return ParseInternal(new string[]
{ line
});
}
}
}
|
Java
|
UTF-8
| 662
| 2.328125
| 2
|
[] |
no_license
|
package tp2.factCt;
import jade.core.behaviours.Behaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
public class ReceiveBhv extends Behaviour {
private FactAgt parentAgt;
public ReceiveBhv(FactAgt parentAgt){
this.parentAgt = parentAgt;
}
//@Override
public void action() {
MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.REQUEST);
ACLMessage message = this.parentAgt.receive(mt);
if (message != null) {
this.parentAgt.addBehaviour(new FactBhv(this.parentAgt, message));
}
else {
block();
}
}
//@Override
public boolean done() {
return false;
}
}
|
C#
|
UTF-8
| 1,842
| 3.421875
| 3
|
[] |
no_license
|
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
namespace Leaf
{
public class GrayScaleImage
{
private List<List<byte>> _image;
private int _pixelHeight;
private int _pixelWidth;
public int PixelHeight => _pixelHeight;
public int PixelWidth => _pixelWidth;
public GrayScaleImage(int width, int height, Stream pixelStream)
{
Contract.Equals(width * height * 4, pixelStream.Length);
_image = new List<List<byte>>();
_pixelHeight = height;
_pixelWidth = width;
for (uint y = 0; y < height; y++)
{
var pixelLine = new List<byte>();
for (uint x = 0; x < width; x++)
{
var b = (byte)pixelStream.ReadByte();
var g = (byte)pixelStream.ReadByte();
var r = (byte)pixelStream.ReadByte();
var a = (byte)pixelStream.ReadByte();
pixelLine.Add((byte)((r + g + b)/3));
}
_image.Add(pixelLine);
}
}
public byte GetPixel(int x, int y)
{
return _image[y][x];
}
public void SetPixel(int x, int y, byte pixel)
{
_image[y][x] = pixel;
}
public void CopyToStream(Stream stream)
{
stream.Flush();
for (int y = 0; y < PixelHeight; y++)
{
for (int x = 0; x < PixelWidth; x++)
{
stream.WriteByte(_image[y][x]);
stream.WriteByte(_image[y][x]);
stream.WriteByte(_image[y][x]);
stream.WriteByte(255);
}
}
}
}
}
|
JavaScript
|
UTF-8
| 8,049
| 2.8125
| 3
|
[] |
no_license
|
var count = 0;
function searchMedicine() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById('searchMedicine');
filter = input.value.toUpperCase();
table = document.getElementById('myTable');
tr = table.getElementsByTagName('tr');
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName('td')[3];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = '';
} else {
tr[i].style.display = 'none';
}
}
}
}
// function myFunction(element) {
// var textField = document.createElement('textarea');
// textField.innerText = element;
// document.body.appendChild(textField);
// textField.select();
// document.execCommand("copy");
// textField.remove();
// alert("Copied Medicine Name: " + element);
// }
function addOtherFields(billIdx) {
var input,
filter,
table,
tr,
td,
i,
txtValue,
reqRow,
reqExpiry,
reqExpiry1,
reqMRP;
input = document.getElementById('medName' + billIdx);
filter = input.value.toUpperCase();
tableRef = document.getElementById('myTable');
tr = tableRef.getElementsByTagName('tr');
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName('td')[3];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
reqRow = tr[i];
reqMRP = reqRow.getElementsByTagName('td')[3].innerText.substring(1);
reqExpiry = reqRow.getElementsByTagName('td')[5].innerText;
reqExpiry1 =
reqExpiry.substring(6, 10) +
'-' +
reqExpiry.substring(0, 2) +
'-' +
reqExpiry.substring(3, 5);
document.getElementById('medMRP' + billIdx).value = reqMRP;
document.getElementById('medExpiry' + billIdx).value = reqExpiry1;
document.getElementById('medQuantity' + billIdx).value = 0;
} else {
}
}
}
}
function calcTotal(billIdx) {
var reqQuantity, reqMRP;
reqQuantity = document.getElementById('medQuantity' + billIdx).value;
reqMRP = document.getElementById('medMRP' + billIdx).value;
if (reqQuantity <= 0) {
document.getElementById('medQuantity' + billIdx).value = 0;
document.getElementById('medTotal' + billIdx).value = 0;
} else {
document.getElementById('medTotal' + billIdx).value = reqMRP * reqQuantity;
}
var curr = Number(document.getElementById('totalBillAmt').value);
curr = curr + Number(medCost);
document.getElementById('totalBillAmt').value = curr;
if (document.getElementById('discount') !== null) {
document.getElementById('discount').max = curr - 1;
}
}
function calcBill() {
document.getElementById('totalBillAmt').value = Number(0);
var billTable = document
.getElementById('billTable')
.getElementsByTagName('tbody')[0];
var numRow = billTable.getElementsByTagName('tr').length;
for (let index = 0; index < numRow; index++) {
const medCost = Number(document.getElementById('medTotal' + index).value);
// console.log(medCost);
if (!medCost) {
console.log('Not a number');
continue;
} else {
var curr = Number(document.getElementById('totalBillAmt').value);
curr = curr + Number(medCost);
document.getElementById('totalBillAmt').value = curr;
if (document.getElementById('discount') !== null) {
document.getElementById('discount').max = curr - 1;
}
}
}
}
function calcFinalBill() {
var actualTotal = document.getElementById('totalBillAmt').value;
var discount =
document.getElementById('discount') === null
? 0
: document.getElementById('discount').value;
// console.log(discount);
document.getElementById('finalTotalCost').value = actualTotal - discount;
var curr = Number(document.getElementById('totalBillAmt').value);
curr = curr + Number(medCost);
document.getElementById('totalBillAmt').value = curr;
if (document.getElementById('discount') !== null) {
document.getElementById('discount').max = curr - 1;
}
}
$('.sliding-link').click(function (e) {
e.preventDefault();
var aid = $(this).attr('href');
$('html,body').animate({ scrollTop: $(aid).offset().top }, 'slow');
});
function addMed(medIdStockId) {
// console.log(medIdStockId);
var medRow = document.getElementById(medIdStockId);
// console.log(medRow);
var medId = medRow.getElementsByTagName('td')[1].innerText;
var medStockId = medRow.getElementsByTagName('td')[2].innerText;
var medName = medRow.getElementsByTagName('td')[3].innerText;
var medMRP = medRow.getElementsByTagName('td')[4].innerText;
var medExpiry = medRow.getElementsByTagName('td')[6].innerText;
var medExpiry1 =
medExpiry.substring(6, 10) +
'-' +
medExpiry.substring(0, 2) +
'-' +
medExpiry.substring(3, 5);
var billTable = document
.getElementById('billTable')
.getElementsByTagName('tbody')[0];
var row = billTable.insertRow(count);
row.setAttribute('id', 'BillMed' + medId + 'Stock' + medIdStockId);
var cell1 = row.insertCell(0);
cell1.innerHTML =
"<btn class='btn btn-dark btn-sm' onclick='removeMed(" +
count +
");'><i class='fas fa-trash'></i></btn>";
var cell2 = row.insertCell(1);
cell2.innerHTML = 1 + Number(count);
var cell3 = row.insertCell(2);
cell3.innerHTML =
"<input id='medName" +
count +
"' name='medName" +
count +
"' readonly class='form-control-plaintext' type='text' oninput='addOtherFields('" +
count +
"');' value='" +
medName +
"'>";
var cell4 = row.insertCell(3);
cell4.innerHTML =
"<input id='medId" +
count +
"' name='medId" +
count +
"' readonly class='form-control-plaintext' type='number' value='" +
medId +
"'>";
var cell5 = row.insertCell(4);
cell5.innerHTML =
"<input id='medStockId" +
count +
"' name='medStockId" +
count +
"' readonly class='form-control-plaintext' type='number' value='" +
medStockId +
"'>";
var cell6 = row.insertCell(5);
cell6.innerHTML =
"<input id='medMRP" +
count +
"' name='medMRP" +
count +
"' class='form-control-plaintext' type='number' readonly step='0.1' value='" +
medMRP +
"'>";
var cell7 = row.insertCell(6);
cell7.innerHTML =
"<input id='medQuantity" +
count +
"' name='medQuantity" +
count +
"' type='number' class='form-control' min='1' oninput='calcTotal(" +
count +
");' required>";
var cell8 = row.insertCell(7);
cell8.innerHTML =
"<input id='medExpiry" +
count +
"' name='medExpiry" +
count +
"' type='date' class='form-control-plaintext' readonly value='" +
medExpiry1 +
"'>";
var cell9 = row.insertCell(8);
cell9.innerHTML =
"<input id='medTotal" +
count +
"' name='medTotal" +
count +
"' type='number' class='form-control-plaintext' readonly step='0.1'>";
++count;
}
function removeMed(rowNo) {
--count;
document
.getElementById('billTable')
.getElementsByTagName('tbody')[0]
.deleteRow(rowNo);
var table = document
.getElementById('billTable')
.getElementsByTagName('tbody')[0];
var tr = table.getElementsByTagName('tr');
for (var i = 0; i < tr.length; ++i) {
tr[i].cells[1].innerHTML = i + 1;
for (var j = 2; j < 9; ++j) {
var inputId = tr[i].cells[j].getElementsByTagName('input')[0].id;
tr[i].cells[j].getElementsByTagName('input')[0].id =
inputId.substring(0, inputId.length - 1) + i;
tr[i].cells[j].getElementsByTagName('input')[0].name =
inputId.substring(0, inputId.length - 1) + i;
}
tr[i].cells[2]
.getElementsByTagName('input')[0]
.setAttribute('oninput', 'addOtherFields(' + i + ')');
tr[i].cells[6]
.getElementsByTagName('input')[0]
.setAttribute('oninput', 'calcTotal(' + i + ')');
tr[i].cells[0]
.getElementsByTagName('btn')[0]
.setAttribute('onclick', 'removeMed(' + i + ')');
}
}
|
JavaScript
|
UTF-8
| 5,201
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
"use strict";
var AppView = (function(){
function create(){
var appView = {};
bind(appView);
appView.init();
return appView;
}
function bind(appView){
appView.installServiceWorker = installServiceWorker.bind(appView);
appView.serviceWorkerInstalled = serviceWorkerInstalled.bind(appView);
appView.serviceWorkerInstallFailed = serviceWorkerInstallFailed.bind(appView);
appView.cacheDom = cacheDom.bind(appView);
appView.setBndr = setBndr.bind(appView);
appView.init = init.bind(appView);
appView.save = save.bind(appView);
appView.load = load.bind(appView);
appView.crypt = crypt.bind(appView);
appView.changePassword = changePassword.bind(appView);
}
function installServiceWorker(){
if("serviceWorker" in navigator){
navigator.serviceWorker.register("service-worker.js", {scope: "./"})
.then(this.serviceWorkerInstalled)
.catch(this.serviceWorkerInstallFailed);
}
}
function serviceWorkerInstalled(registration){
console.log("App Service registration successful with scope:", registration.scope);
}
function serviceWorkerInstallFailed(error){
console.error("App Service failed to install", error);
}
function cacheDom(){
this.dom = {};
}
function setBndr(){
this.bndr = Bndr.create()
.setTemplate(document.body)
.setModel({
encryptMode : true,
modeText : "Encrypt",
status : "",
text : "",
filename : "",
resultText : "",
password : "",
passwordKey : "",
cryptoVisible : true
})
.bindClassReversed("#mode", "encryptMode", "on")
.bindClassReversed("#encrypted-input", "cryptoVisible", "hidden")
.bindAttributeExistenceReversed("#load", "filename", "disabled")
.bindAttributeExistenceReversed("#save", "filename", "disabled")
.bindElement("#encrypted-input", "resultText")
.bindElement("#status", "status")
.bindElement("#mode-label", "modeText")
.bindElementReverse("#password", "password")
.bindElementReverse("#filename", "filename")
.bindElementTwoWay("#input", "text")
.bindEvent("#save", "click", this.save)
.bindEvent("#load", "click", this.load)
.bindToggleEvent("#preview", "click", "cryptoVisible")
.bindToggleEvent("#mode", "click", "encryptMode")
.bindChange("text", this.crypt)
.bindChange("password", this.changePassword)
.bindChange("passwordKey", x => this.crypt(this.model.text))
.computeValue("encryptMode", x => x ? "Encrypt" : "Decrypt", "modeText")
.attach();
this.model = this.bndr.getBoundModel();
}
function save(){
if(!this.dropbox.isAuthorized()){
return this.dropbox.authorize();
}
this.dropbox.upload(this.model.resultText,{
path : `/${this.model.filename}`,
mode : "overwrite"
})
.then(x => this.model.status = "Saved!")
.then(Util.wait(5000))
.then(x => this.model.state = "")
.catch(x => this.model.status = `Error saving: ${x}`);
}
function load(){
if(!this.dropbox.isAuthorized()){
return this.dropbox.authorize();
}
this.dropbox.download(`/${this.model.filename}`)
.then(x => x.arrayBuffer())
.then(x => {
this.model.encryptMode = false;
this.model.text = Util.arrayBufferToString(new Uint8Array(x))
})
.catch(x => this.model.status = `Error loading: ${x}`);
}
function crypt(value){
this.model.status = "";
if(!this.model.passwordKey){
return;
}
if(this.model.encryptMode){
let valueBytes = Util.stringToArrayBuffer(value);
const vector = crypto.getRandomValues(new Uint8Array(16));
crypto.subtle.encrypt({ name : "AES-CBC", iv : vector }, this.model.passwordKey, valueBytes)
.then(x => {
this.model.resultText = Util.arrayBufferToString(Util.concatBuffers(vector, new Uint8Array(x)));
})
.catch(x => {
this.model.status = `Could not encrypt: ${x}`;
Util.wait(5000).then(y => this.model.status = "");
});
}else{
const buffer = Util.stringToArrayBuffer(value);
const vector = buffer.slice(0, 16);
const encryptedBytes = buffer.slice(16);
crypto.subtle.decrypt({ name : "AES-CBC", iv : vector }, this.model.passwordKey, encryptedBytes)
.then(x => this.model.resultText = Util.arrayBufferToString(new Uint8Array(x)))
.catch(x => {
this.model.status = `Could not decrypt: ${x}`;
Util.wait(5000).then(y => this.model.status = "");
});
}
}
function changePassword(password){
let passwordBytes = Util.stringToArrayBuffer(password);
crypto.subtle.digest({ name : "SHA-256" }, passwordBytes)
.then(x => crypto.subtle.importKey("raw", x, { name : "AES-CBC" }, false, ["encrypt", "decrypt"]))
.then(x => this.model.passwordKey = x);
}
function getQueryData(){
let searchParams = new URLSearchParams(window.location.search.substr(1));
}
function init(){
this.installServiceWorker();
this.dropbox = Dropbox.create({
appKey : "hxnx6192t96ejeg",
appName : "cryptoTool"
});
this.cacheDom();
this.setBndr();
}
return {
create : create
};
})();
|
Markdown
|
UTF-8
| 3,545
| 2.75
| 3
|
[] |
no_license
|
# 九月十三日相克宗至红龙乡

天路十八旁
今天的骑行路,从相克宗到红龙乡,我一直知道并担忧其难度的。
从3400上升到4200,然后基本保持在4100至4400之间的大起大伏。总行程八十公里的高海拨骑行。晚饭时,一个自驾从亚丁回来的住客还告诉我,剪子湾隧道全线无灯,这。。。
晚饭后,我还向老板打听搭车的价格。老板推荐我搭施工队的车上去。
不知道是高反还是犹豫不决,昨天一整晚都没有睡踏实,早上三四点钟,村里的狗开始疯狂地叫。
促使我决定还是出发的原因,是早上的阳光。看起来今天天气会不错,所以我决定挑战一下自我。

相克宗朝霞
从相克宗一出来就是天路十八弯。也许是前几天适应的不错,体能有所上升,在上午11点的时候,就已经,爬完了天路18弯。来到了剪子湾隧道口。

完全没有灯的隧道
整条隧道确实没有灯,一般来说,司机会特别注意这样的情况,所以应该是没有安全问题的。但是,带着微小的灯光,冲进一个完全黑暗的空间,还是让人有一种恐怖的感觉。

群山之上
除了隧道口之后,就是一片,高山草原的感觉。

有好吃的土豆和鸡蛋
熊宗卡旅游服务站有个非常好的大哥,在那售卖煮熟的土豆,鸡蛋,还有玉米,价格非常公道,一定要在这补充好食物,后面就没有这样的机会了。

高山草原和群山
按理说我应该通过了海拔,4400米左右的卡子拉山,但我居然没有看到垭口标志,就冲下山去了。
今天一天的骑行中,经历了暴晒,大雨,冰雹,然后又是暴晒。

远处下雨的云
我看到远处的云的时候,做了一个判断,认为雨不会下在我的路线上。所以当别人穿戴雨具的时候,我直接冲了下去。
我的判断是错的。暴雨和冰雹瞬间把我的裤子全部打湿了。但瞬间我又冲进了烈日之中,打湿的衣裤在十几分钟就全部晒干了。
今天还遭遇了狂风。特别是当我以三四十公里的速度往下冲的时候,那些风让我眼泪鼻涕乱流。
下午5点钟的时候,我还必须要爬最后一个四公里的坡。筋疲力尽的我,开始执行一公里休息一次的目标,一公里后改成了500米休息一次。如果坡再长一点,我估计200米就要休息一次。
总而言之,今天的骑行,遭遇到了高原骑行时所有的困难状况。

温暖的柴火炉
下午六点半下山以后,我尽快找了一家客栈住下,在温暖的柴火炉边半躺着,喝了几杯酥油菜,感觉生活生命又回来了。
明天的骑行很简单,大约半天可以到理塘,我需要在那休整。
|
C#
|
UTF-8
| 916
| 3.640625
| 4
|
[
"MIT"
] |
permissive
|
using System;
class Styrofoam
{
static void Main()
{
double budget = double.Parse(Console.ReadLine());
double houseArea = double.Parse(Console.ReadLine());
int windowsCount = int.Parse(Console.ReadLine());
double styrofoamPackArea = double.Parse(Console.ReadLine());
double styrofoamPackPrice = double.Parse(Console.ReadLine());
double coveringArea = (houseArea - windowsCount * 2.4) * 1.1;
double styrofoamPackNeeded = Math.Ceiling(coveringArea / styrofoamPackArea);
double budgetNeeded = styrofoamPackNeeded * styrofoamPackPrice;
if (budgetNeeded <= budget)
{
Console.WriteLine("Spent: {0:0.00}", budgetNeeded);
Console.WriteLine("Left: {0:0.00}", budget-budgetNeeded);
}
else
{
Console.WriteLine("Need more: {0:0.00}", budgetNeeded-budget);
}
}
}
|
Shell
|
UTF-8
| 287
| 2.6875
| 3
|
[] |
no_license
|
#!/bin/sh
# save as asmtomach.sh and run:
# chmod u+rwx asmtomach.sh
# then run:
# ./asmtomach.sh 'mov $1, %eax'
cd /var/tmp
echo $1 > asmtomach.s
gcc -m32 -c asmtomach.s
objdump -d asmtomach.o | grep '[0-9a-f][0-9a-f] ' | grep -v '00000000 <.text>' | cut -c 7-
cd - 2>&1 >/dev/null
|
SQL
|
UTF-8
| 256
| 3.25
| 3
|
[] |
no_license
|
-- Q) Listar los articulos que tengan un precio mayor a la mitad del precio
-- promedio de los articulos y un stock minimo mayor a 200 unidades. (6 filas)
SELECT *
FROM ARTICULOS
WHERE PTO_REPOSICION>200 AND PRECIO>(SELECT AVG(PRECIO)/2 FROM ARTICULOS)
|
Java
|
UTF-8
| 1,685
| 2.421875
| 2
|
[] |
no_license
|
package ejb;
import domain.Expediente;
import exceptions.ExpedienteNoEncontradoException;
import java.util.List;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
@Stateless
public class ModificarExpedienteEJB implements GestionExpediente {
private static final Logger LOG = Logger.getLogger(ModificarExpedienteEJB.class.getCanonicalName());
@PersistenceContext(name="Proyecto-SII")
private EntityManager em;
@Override
public void actualizarExpediente(Expediente expediente) throws ExpedienteNoEncontradoException {
//busca el expediente si no esta lanaza una exception y si esta se modifica con el .merge
Expediente p=em.find(Expediente.class, expediente.getNumExpediente());
if(p==null) throw new ExpedienteNoEncontradoException();
em.merge(expediente);
}
@Override
public Expediente findExpediente(int n) throws ExpedienteNoEncontradoException {
Expediente e = em.find(Expediente.class, n);
if(e == null) throw new ExpedienteNoEncontradoException();
return e;
}
@Override
public List<Expediente> getAllExpediente() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Expediente> cq = cb.createQuery(Expediente.class);
Root<Expediente> rootEntry = cq.from(Expediente.class);
CriteriaQuery<Expediente> all = cq.select(rootEntry);
TypedQuery<Expediente> allQuery = em.createQuery(all);
return allQuery.getResultList();
}
}
|
C#
|
UTF-8
| 4,501
| 2.734375
| 3
|
[
"MIT",
"ImageMagick",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace NMagickWand
{
public delegate IntPtr MagickQueryStringListDelegate(string pattern, out UIntPtr count);
public delegate IntPtr MagickWandQueryStringListDelegate(IntPtr wand, string pattern, out UIntPtr count);
public delegate IntPtr MagickWandDoubleListDelegate(IntPtr wand, out UIntPtr count);
public delegate IntPtr MagickWandPixelWandListDelegate(IntPtr wand, out UIntPtr count);
public static class MagickHelper
{
public static string GetMagickString(IntPtr ptr)
{
if(ptr == IntPtr.Zero)
{
return null;
}
var str = Marshal.PtrToStringAnsi(ptr);
MagickWandApi.MagickRelinquishMemory(ptr);
return str;
}
public static string GetMagickConstString(IntPtr ptr)
{
if(ptr == IntPtr.Zero)
{
return null;
}
return Marshal.PtrToStringAnsi(ptr);
}
public static string GetMagickConstString(IntPtr ptr, UIntPtr length)
{
if(ptr == IntPtr.Zero || length == UIntPtr.Zero)
{
return null;
}
return Marshal.PtrToStringAnsi(ptr, (int)length);
}
public static IReadOnlyList<string> GetMagickStringList(IntPtr arrayPtr, UIntPtr count)
{
var ptrs = GetMagickIntPtrArray(arrayPtr, count, true);
return ptrs.Select(x => GetMagickString(x)).ToList();
}
public static IReadOnlyList<double> GetMagickDoubleList(IntPtr arrayPtr, UIntPtr count)
{
var result = GetMagickDoubleArray(arrayPtr, count);
return new List<double>(result);
}
public static IReadOnlyList<PixelWand> GetMagickPixelWandList(IntPtr arrayPtr, UIntPtr count)
{
var result = GetMagickIntPtrArray(arrayPtr, count, false);
return result.Select(x => new PixelWand(x, false)).ToList();
}
public static double[] GetMagickDoubleArray(IntPtr arrayPtr, UIntPtr count)
{
if(arrayPtr == IntPtr.Zero || count == UIntPtr.Zero)
{
return new double[0];
}
double[] result = new double[(int)count];
Marshal.Copy(arrayPtr, result, 0, (int)count);
MagickWandApi.MagickRelinquishMemory(arrayPtr);
return result;
}
public static IntPtr[] GetMagickIntPtrArray(IntPtr arrayPtr, UIntPtr count, bool free)
{
if(arrayPtr == IntPtr.Zero || count == UIntPtr.Zero)
{
return new IntPtr[0];
}
IntPtr[] result = new IntPtr[(int)count];
Marshal.Copy(arrayPtr, result, 0, (int)count);
if(free)
{
MagickWandApi.MagickRelinquishMemory(arrayPtr);
}
return result;
}
public static IReadOnlyList<string> ExecuteMagickWandQueryStringList(IntPtr wand, string pattern, MagickWandQueryStringListDelegate del)
{
if(string.IsNullOrEmpty(pattern))
{
pattern = "*";
}
UIntPtr count;
var strPtr = del(wand, pattern, out count);
return MagickHelper.GetMagickStringList(strPtr, count);
}
public static IReadOnlyList<string> ExecuteMagickQueryStringList(string pattern, MagickQueryStringListDelegate del)
{
if(string.IsNullOrEmpty(pattern))
{
pattern = "*";
}
UIntPtr count;
var strPtr = del(pattern, out count);
return MagickHelper.GetMagickStringList(strPtr, count);
}
public static IReadOnlyList<double> ExecuteMagickWandDoubleList(IntPtr wand, MagickWandDoubleListDelegate del)
{
UIntPtr count;
var strPtr = del(wand, out count);
return MagickHelper.GetMagickDoubleList(strPtr, count);
}
public static IReadOnlyList<PixelWand> ExecuteMagickWandPixelWandList(IntPtr wand, MagickWandPixelWandListDelegate del)
{
UIntPtr count;
var pwPtr = del(wand, out count);
return MagickHelper.GetMagickPixelWandList(pwPtr, count);
}
}
}
|
Java
|
UTF-8
| 928
| 3.9375
| 4
|
[] |
no_license
|
import java.util.Scanner;
public class homework2{
public static void main(String[] args) {
Scanner rd = new Scanner(System.in);
//Definir variables
String palabra;
//Solicitar una String
System.out.print("Ingrese una palabra: ");
palabra = rd.next();// Definir la variables
int size = palabra.length();// Definir una variable que me indique la cantidad de caracteres.
for(int y = 0;y < size;y++){// Establecer una variable igual a 0, que sea menor que size y que aumente uno despues de cada ciclo.
char lector = palabra.charAt(y);//Definir una variable que indique que se empezara a leer el String desde y, osea desde 0.
System.out.println(palabra.charAt(y));//Imprimir el caracter en y.
if(y<=size){
continue;//Si despues de imprimir el lector esta ubicado antes del final o al final de la palabra, que repita el proceso hasta que imprima el ultimo caracter.
}
}
}
}
|
Java
|
UTF-8
| 2,035
| 1.96875
| 2
|
[] |
no_license
|
package com.cn.thinkx.merchant.domain;
import java.sql.Date;
public class CardBal {
private String selectDate;
private String insCode;
private String productCode;
private String outAmt;
private String cardBal;
private String createUser;
private String updateUser;
private Date createTime;
private Date updateTime;
private long cardNum;
private double cardSumBal;//会员卡余额
private int cardSumNum;//会员卡数量
public String getSelectDate() {
return selectDate;
}
public void setSelectDate(String selectDate) {
this.selectDate = selectDate;
}
public String getInsCode() {
return insCode;
}
public void setInsCode(String insCode) {
this.insCode = insCode;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getOutAmt() {
return outAmt;
}
public void setOutAmt(String outAmt) {
this.outAmt = outAmt;
}
public String getCardBal() {
return cardBal;
}
public void setCardBal(String cardBal) {
this.cardBal = cardBal;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public String getUpdateUser() {
return updateUser;
}
public void setUpdateUser(String updateUser) {
this.updateUser = updateUser;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public long getCardNum() {
return cardNum;
}
public void setCardNum(long cardNum) {
this.cardNum = cardNum;
}
public double getCardSumBal() {
return cardSumBal;
}
public void setCardSumBal(double cardSumBal) {
this.cardSumBal = cardSumBal;
}
public int getCardSumNum() {
return cardSumNum;
}
public void setCardSumNum(int cardSumNum) {
this.cardSumNum = cardSumNum;
}
}
|
Java
|
UTF-8
| 885
| 2.46875
| 2
|
[] |
no_license
|
package com.valencia.sopra.component;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* EJEMPLO DE UN PROCESO SPRING BATCH USANDO LAS ANOTACIONES
* ESPECIFICAS 'Scheduled' A NIVEL DE COMPONENTE Y 'EnableScheduling'
* A NIVEL DE LA CLASE CONFIGURACION DE SPRING, SI LAS QUITAMOS
* DESACTIVAMOS EL PROCESO BATCH, BASTA CON QUITAR EL 'EnableScheduling'
* DE LA CLASE DE CONFIGURACIÓN DE SPRING
*
* @author jlGoldaracena
*
*/
@Component("taskComponent")
public class TaskComponent {
private static final Log LOG = LogFactory.getLog(TaskComponent.class);
@Scheduled(fixedDelay=15000)
public void doTask() {
LOG.info("Fecha, Hora y Año actuales: " + new Date ());
}
}
|
JavaScript
|
UTF-8
| 4,996
| 2.96875
| 3
|
[] |
no_license
|
import React, { Component } from 'react';
import Form from '../components/Form';
export default class FormContainer extends Component {
constructor(props){
super(props);
this.state = {
firstName: '',
lastName: '',
email: '',
message: '',
invalidChars: false,
charLimit: 500,
count: 0
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
if (this.state.message.length === 0){
alert('Don\'t forget to type a message!');
if (this.state.message.length === 0){ document.querySelector('#Message').classList.add('Invalid-field');}
}
if (this.state.firstName.length === 0 || this.state.lastName.length === 0 || this.state.email.length === 0 || this.state.invalidChars){
alert('Please fill out all of the fields!');
if (this.state.firstName.length === 0){ document.querySelector('.First-name').classList.add('Invalid-field');}
if (this.state.lastName.length === 0){ document.querySelector('.Last-name').classList.add('Invalid-field');}
if (this.state.email.length === 0){ document.querySelector('.Email').classList.add('Invalid-field');}
}
if (document.querySelectorAll('.Invalid-field').length === 0 && this.state.message.length > 0) {
document.querySelector('.Form').classList.add('Contact-send-animation');
document.querySelector('.Checkmark-container').style.zIndex = 100;
document.querySelector('.Checkmark-message').textContent = 'Message sent.';
setTimeout(() =>{
document.querySelector('.Checkmark-message').classList.add('animation');
}, 300);
document.querySelector('.Checkmark').classList.add('animation');
document.querySelector('.Checkmark-circle').classList.add('animation');
document.querySelector('.Checkmark-check').classList.add('animation');
}
}
handleChange(e) {
const name = e.target.name;
const value = e.target.value;
const count = e.target.value.length;
this.setState({ [name]: value.slice(0, 128) }, this.validate(name, count, e));
if (name === 'message' ) this.setState({ count: count});
}
validate(name, count, e) {
const messageField = document.getElementById('Message');
const countText = document.getElementById('Count');
if (name !== 'message' && count === 0) {
document.querySelector(`input[name=${name}]`).classList.add('Invalid-field');
}
if (name !== 'message' && !this.state.invalidChars && count > 0) {
document.querySelector(`input[name=${name}]`).classList.remove('Invalid-field');
}
if (name === 'email') {
if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(e.target.value)){
document.querySelector(`input[name=${name}]`).classList.add('Invalid-field');
this.setState({ invalidChars: true});
} else {
document.querySelector(`input[name=${name}]`).classList.remove('Invalid-field');
this.setState({ invalidChars: false});
}
}
if (name === 'firstName' || name === 'lastName') {
if (/\W+|\d+|\_/gm.test(e.target.value)){
document.querySelector(`input[name=${name}]`).classList.add('Invalid-field');
this.setState({ invalidChars: true});
} else {
document.querySelector(`input[name=${name}]`).classList.remove('Invalid-field');
this.setState({ invalidChars: false});}
}
if (name === 'message') {
if (this.state.message.length < this.state.charLimit){
countText.style.color = 'black'
}
if (e.target.value.length >= this.state.charLimit){
messageField.value = messageField.value.slice(0, this.state.charLimit);
countText.style.color = 'red';
}
if (this.state.message.length > 0){
document.querySelector('#Message').classList.remove('Invalid-field');
}
if (e.target.value.length === 0){
document.querySelector('#Message').classList.add('Invalid-field');
}
}
}
render(){
return (
<Form
handleChange={this.handleChange}
handleSubmit={this.handleSubmit}
firstName={this.state.firstName}
lastName={this.state.lastName}
email={this.state.email}
message={this.state.message}
count={this.state.count}
charLimit={this.state.charLimit}
/>
)
}
};
|
Markdown
|
UTF-8
| 9,240
| 2.53125
| 3
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
# Installation instructions
<!-- toc -->
- [Installation instructions](#installation-instructions)
- [Basic requirements](#basic-requirements)
- [Installation steps:](#installation-steps)
- [Load required modules](#load-required-modules)
- [Archiving new emails via Postfix or the likes](#archiving-new-emails-via-postfix-or-the-likes)
- [Setting up OAuth](#setting-up-oauth)
- [Setting up Google OAuth](#setting-up-google-oauth)
- [Setting up GitHub OAuth](#setting-up-github-oauth)
- [Setting up web replies](#setting-up-web-replies)
- [Online Management Console](#online-management-console)
- [Hiding tracebacks from users](#hiding-tracebacks-from-users)
- [Archiving options](#archiving-options)
<!-- tocstop -->
## Basic requirements
- Linux or other UNIX-like operating system
- ElasticSearch 7.x or higher installed
- Python 3.7.3 or higher
- PipEnv program (typically `apt install pipenv` or `yum install pipenv` etc)
- A web server of your choice with proxy capabilities
Warning: the ElasticSearch client libraries from 7.14 have strict server version checking
and will not run with the wrong version.
You may need to update the requirements.txt files in tools/ and server/ accordingly.
## Installation steps:
- Clone the Foal git repository to your machine: `git clone https://github.com/apache/incubator-ponymail-foal.git foal`
- Install the Python requirements for the setup:
~~~shell script
cd foal/tools
pipenv install -r requirements.txt
~~~
- Install any desired optional dependencies, for example:
- html2text (GNU GPL 3) - convert HTML to plain text
- mailman (GPLv3+) - interface with Mailman lists
- zope (Zope Public Licence 2.1) - required for Mailman integration
- Run the setup process:
~~~shell script
pipenv run python3 setup.py
cd ..
~~~
- Import any mailboxes you need to, using `tools/import-mbox.py` OR migrate your old Pony Mail database
using the [Foal migrator](MIGRATING.md).
- Install the server requirements:
~~~shell script
cd server/
pipenv install -r requirements.txt
~~~
- start the server:
~~~shell script
pipenv run python3 main.py
~~~
- use a web server like httpd or nginx to serve UI and proxy to the API. A sample httpd configuration could be:
~~~apache
# Load required modules
LoadModule proxy_module ...
LoadModule proxy_http_module ...
...
<VirtualHost *:80>
ServerName ponymail.example.org
DocumentRoot /var/www/ponymail-foal/webui/
ProxyPass /api/ http://localhost:8080/api/
# PathInfo is needed for threads
AcceptPathInfo On
# Also needed for threads to be able to handle message-ids with embedded /:
AllowEncodedSlashes On # (or NoDecode)
</VirtualHost>
~~~
A sample nginx config could be:
~~~nginx
server {
root /var/www/ponymail-foal/webui/;
index index.html index.htm;
location /api/ {
proxy_pass http://127.0.0.1:8080/api/;
}
}
~~~
## Archiving new emails via Postfix or the likes
To set up archiving, the easiest path is to edit your `/etc/aliases` file on the machine
that receives email. If your receiving address for email is `inbox@yourmachine.tld`, your
alias entry should look like this:
~~~text
inbox: "| /path/to/foal/tools/archiver.py"
~~~
For privately archived emails, use the `--private` flag for your command:
~~~text
inbox: "| /path/to/foal/tools/archiver.py --private"
~~~
Once you have added the entry, be sure to run the `newaliases` command to update the compiled alias list.
`archiver.py` will automatically sort out which list the email is for, if there is a List-ID header.
You can override or manually set a list using the `--lid` flag:
~~~text
inbox-somealias: "| /path/to/foal/tools/archiver.py --lid somealias@mydomain.tld"
~~~
## Setting up OAuth
By default, OAuth is enabled for the following providers:
- Google
- GitHub
- Generic (like oauth.apache.org)
None of these are marked as _authoritative_ by default. Authoritative OAuth domains
allow users to compose emails via the UI and see private emails (unless you reshape the
AAA plugin). Non-authoritative domains only allows the user to log in, nothing more.
To set an OAuth provider as authoritative, you need to add or uncomment the
`authoritative_domains` section of the `oauth` configuration in `server/ponymail.yaml`:
~~~yaml
oauth:
authoritative_domains:
- googleapis.com
- myoauthprovider.tld
~~~
For administrative access to certain features, such as deleting/moving email via the UI,
you can set a list of people who, via an authoritative oauth provider, will have access to
this, as such:
~~~yaml
oauth:
authoritative_domains:
- googleapis.com
admins:
- humbedooh@gmail.com
- example@gmail.com
~~~
Currently, you will also need to enable or tweak your `webui/js/config.js` file to match your
choice of OAuth providers, though that is subject to change.
### Setting up Google OAuth
To begin using Google OAuth, you must procure an OAUth2 client id from the
[Gooogle Developers Console](https://console.developers.google.com/apis/credentials/oauthclient/).
Callback URL must be oauth.html in your webui installation.
Once you have a `Client ID`, you should set it in `server/ponymail.yaml` in the
`google_client_id` directive. You will also need to currently set it in `webui/js/config.js`.
After this is done, OAuth should work with Google, and you may enable authoritativeness by adding
`googleapis.com` to the `authoritative_domains` section in `server/ponymail.yaml`.
### Setting up GitHub OAuth
To begin using GitHub OAuth, create an OAuth app at the
[GitHub Developer Console](https://github.com/settings/developers).
Callback URL must be oauth.html in your webui installation.
Once you have created your OAuth app, copy the client ID and client secret to your
`server/ponymail.yaml` oauth section, as `github_client_id` and `github_client_secret`
respectively.
When you've done that, you must currently also edit `webui/js/config.js` and set the
`client_id` for GitHub to the correct value.
## Setting up web replies
It is possible to reply to emails on a list via the web interface, provided you have enabled
this feature. To do so, you must set a `mailhost` option as well as designate certain
domains and subdomains as allowed recipients of email. This is done in the `server/ponymail.yaml`
file, under ui:
~~~yaml
ui:
wordcloud: true
mailhost: smtp.mydomain.tld:25
sender_domains: mydomain.tld *.mydomain.tld
~~~
You may use wildcards in your domain names, as per standard GLOB/fnmatch rules,
separating each entry with a single space:
- to allow email for list@mydomain.tld, sender_domains must include `mydomain.tld`
- to allow email for list@sub.mydomain.tld, you should add `sub.mydomain.tld`
- to allow email for all lists at any subdomain under mydomain.tld, you should add `*.mydomain.tld`
Only users logged in via authoritative OAuth will be able to compose replies via the
web interface.
## Online Management Console
the `ui` paragraph of the server configuration allows for enabling an administrative interface
for editing or removing emails from the archives. To enable this, set `mgmtconsole` to `true`.
For GDPR compliance (deleting an email deletes from disk), set `allow_delete` to `true`.
If left out or set to false, deleted emails are merely hidden, and can be recovered at a later
stage by an administrator.
~~~yaml
ui:
mgmtconsole: true
allow_delete: true
~~~
The administrative interface can be accessed by clicking on the yellow cog in the context menu
of an email. Admins are defined in the [OAuth](#setting-up-oauth) configuration.
## Hiding tracebacks from users
By default, API errors will include a full traceback for debugging purposes. If you wish to
instead have this be printed to the system journal (`stderr`), you can set the `traceback`
option to `false` in `server/ponymail.yaml`. This will instead print an error ID to the user,
corresponding to a traceback in stderr.
If the error ID is, for instance, `a06f7d4b-3a82-4ecf`, you can find the corresponding traceback
by grepping your programs output. If you are running Foal as a systemd service, you could find
the traceback with: `journalctl --no-pager -u yourservicename | grep a06f7d4b-3a82-4ecf`
## Archiving options
To enable the storage in elasticsearch of extra properties related to
threading, the following configuation snippet can be used in the
`server/ponymail.yaml` file:
~~~yaml
archiver:
threadinfo: yes
threadparents: 10
threadtimeout: 5
~~~
The `threadparents` value limits the number of existing messages that
will be queried for thread information at archive time when a new
message is received. The `threadtimeout` value limits the duration of
each query to elasticsearch.
Enabling `threadinfo` means that `top`, `thread`, and `previous`
properties will be added to each stored message. The `top` property is
a boolean, indicating whether or not the message is the start of a new
thread. The `thread` property gives the generated Foal ID of the top
of the current thread; this will be the same as the ID of the current
message if `top` is true. The `previous` property gives the generated
Foal ID of either the most recent parent message if the message is not
the top of a thread, or the top of the most recent thread otherwise.
|
Shell
|
UTF-8
| 537
| 3.40625
| 3
|
[] |
no_license
|
#!/bin/bash
javac Syllables.java
OUTPUT="$(java Syllables < input.txt)"
LINESOUT="$(echo "${OUTPUT}" | nl)"
DIFF="$(diff <(echo "${LINESOUT}") <(nl output.txt) | grep ">")"
IFS=$'\n'; array=($DIFF);unset IFS;
for element in "${array[@]}"
do
LINE="$(echo "$element" | sed -e '$!d' | grep -o -E '[0-9]+' | head -1)"
NEWOUT="$(cat input.txt | nl | grep "\s${LINE}\s")"
echo "${NEWOUT}"
done
echo "${DIFF}" | nl | sed -e '$!d' | grep -o -E '[0-9]+' | head -1
# echo "${LINESOUT}"
# diff <(${LINESOUT}) <(nl output.txt)
|
JavaScript
|
UTF-8
| 3,662
| 3.125
| 3
|
[
"Unlicense"
] |
permissive
|
/*
* https://leetcode.com/contest/weekly-contest-185/
*
* Rank Name Score Finish Time Q1 (3) Q2 (4) Q3 (5) Q4 (6)
* 2666 / 14208 claytonjwong 12 1:23:20 0:10:28 *1 0:41:44 1:13:20 *1
*/
/*
* 1417. Reformat The String
*
* Q: https://leetcode.com/problems/reformat-the-string/
* A: https://leetcode.com/problems/reformat-the-string/discuss/586472/Javascript-and-C%2B%2B-solutions
*/
let reformat = s => {
let letters = s.split('').filter(c => c.charCodeAt(0) >= 97),
digits = s.split('').filter(c => c.charCodeAt(0) < 97);
if (Math.abs(letters.length - digits.length) > 1)
return '';
let N = letters.length + digits.length;
let ans = Array(N);
let turn = letters.length >= digits.length ? 0 : 1; // 0 == letters first 1 == digits first
for (let i = 0; i < N; ++i)
if (i % 2 == turn)
ans[i] = letters.shift();
else
ans[i] = digits.shift();
return ans.join('');
};
// console.log(reformat('1229857369'));
/*
* 1418. Display Table of Food Orders in a Restaurant
*
* Q: https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/
* A: https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/586639/Javascript-and-C%2B%2B-solutions
*/
let displayTable = orders => {
let T = {};
let items = new Set();
for (let [_, table, item] of orders) {
items.add(item);
if (!T[table])
T[table] = {};
if (!T[table][item])
T[table][item] = 0;
++T[table][item];
}
let tables = [...Object.entries(T)];
tables.sort((a, b) => Number(a[0]) - Number(b[0]));
items = [...items].sort();
let header = ['Table'].concat(items);
let ans = [header];
tables.forEach(table => {
let next = [table[0]];
items.forEach(item => next.push(table[1][item] ? table[1][item].toString() : '0'));
ans.push(next);
})
return ans;
};
// console.log(displayTable([["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]));
/*
* 1419. Minimum Number of Frogs Croaking
*
* Q: https://leetcode.com/problems/minimum-number-of-frogs-croaking/
* A: https://leetcode.com/problems/minimum-number-of-frogs-croaking/discuss/586488/Javascript-and-C%2B%2B-solutions
*/
// hardcoded count
let minNumberOfFrogs = (S, cnt = { c: 0, r: 0, o: 0, a: 0, k: 0 }, max = -Infinity) => {
let ok = () => cnt.c >= cnt.r && cnt.r >= cnt.o && cnt.o >= cnt.a && cnt.a >= cnt.k;
for (let c of S) {
++cnt[c];
if (!ok())
return -1;
if (c == 'k')
max = Math.max(max, 1 + Math.max(cnt.c - cnt.k, cnt.r - cnt.k, cnt.o - cnt.k, cnt.a - cnt.k));
}
return cnt.c == cnt.r && cnt.r == cnt.o && cnt.o == cnt.a && cnt.a == cnt.k ? max : -1;
};
// count array
let minNumberOfFrogs = (S, order = 'croak', cnt = Array(5).fill(0), max = 0) => {
let ok = () => cnt.every((_, i) => i == 0 || cnt[i - 1] >= cnt[i]);
for (let c of S) {
if (!ok())
return -1;
++cnt[order.indexOf(c)];
if (c == 'k')
for (let pre of 'croa'.split(''))
max = Math.max(max, 1 + cnt[order.indexOf(pre)] - cnt[order.indexOf(c)]);
}
return cnt.every((_, i) => i == 0 || cnt[i - 1] == cnt[i]) ? max : -1;
};
console.log(minNumberOfFrogs('croakcroak'))
console.log(minNumberOfFrogs('crcoakroak'))
console.log(minNumberOfFrogs('croakcrook'))
console.log(minNumberOfFrogs('croakcroa'))
|
Python
|
UTF-8
| 2,825
| 2.875
| 3
|
[] |
no_license
|
import re
import os
import sys
def replyToPost(subreddit, answerToPost, query):
if not os.path.isfile("posts_replied_to.txt"):
print("Nessun file posts_replied_to.txt, verrà creato al primo controllo!")
posts_replied_to = []
else:
with open("posts_replied_to.txt", "r") as f:
print("File posts_replied_to.txt trovato! Si utilizzerà quello per popolare i post già visitati.")
posts_replied_to = f.read()
posts_replied_to = posts_replied_to.split("\n")
posts_replied_to = list(filter(None, posts_replied_to))
print("Adesso controlliamo se qualcuno ha pubblicato qualche post che parla bene di Javascript...")
print("Subreddit : ", subreddit.title)
checked = 0
commented = 0
for submission in subreddit.hot(limit=25):
print("Titolo Post : ", submission.title)
print("Autore Post : ", submission.author)
print("Upvotes : ", submission.score)
print("Comments : ", submission.num_comments)
print("---------------------------------------")
if submission.id not in posts_replied_to:
if re.search(query, submission.title, re.IGNORECASE):
checked+=1
commented+=1
print("Questo post APPREZZA javascript!")
print("Dobbiamo fare qualcosa! ", submission.author, " deve essere una persona molto stupida!")
print("Fortuna che il nostro bot viene in aiuto!")
print("Rispondo al post con ID : ", submission.id, ", risposta del bot :", answerToPost)
print("...")
submission.reply(answerToPost)
print("...")
print("Risposta aggiunta!")
print("Aggiungo il post all'elenco dei post a cui il bot ha già risposto...")
posts_replied_to.append(submission.id)
with open("posts_replied_to.txt", "w") as f:
for post_id in posts_replied_to:
f.write(post_id + "\n")
print("Aggiunto id :", submission.id, "a posts_replied_to.txt")
print("___________________________________________")
else:
checked+=1
print("Il post non presenta apprezzamenti verso Javascript, bravo, ", submission.author, "!!")
print("___________________________________________")
else:
checked+=1
print("Il post è già stato commentato da dal bot! Salto...")
print("__________________________________________")
print("Finito!")
print("Post controllati : ", checked)
print("Post commentati :", commented)
input("Inserisci qualunque cosa per continuare...")
sys.exit(0)
|
Java
|
UTF-8
| 1,565
| 3.171875
| 3
|
[] |
no_license
|
package com.example.nurse;
import java.util.TreeMap;
import android.util.Log;
/*
* This class includes 3 vital signs:temperature(float),
* blood pressure(float), heart rate(float).
* These information is recorded in a map(Use recorded time as key).
* Every time someone tries to add new information, it is added into the map in VitalSign class.
*/
public class VitalSign {
TreeMap<String, Float> Temperature;
TreeMap<String, Float[]> BloodPressure;
TreeMap<String, Integer> HeartRate;
TreeMap<String, String> TextDescription;
public VitalSign(TreeMap<String, Float> temperature,
TreeMap<String, Float[]> bloodPressure,
TreeMap<String, Integer> heartRate,
TreeMap<String, String> textDescription) {
this.Temperature = temperature;
this.BloodPressure = bloodPressure;
this.HeartRate = heartRate;
this.TextDescription = textDescription;
}
// get patient's temperature.
public float getTemperature() {
return (Float) this.Temperature.lastEntry().getValue();
}
// get patient's systolic.
public float getSystolic() {
return (Float) this.BloodPressure.lastEntry().getValue()[0];
}
// get patient's diastolic.
public float getDiastolic() {
return (Float) this.BloodPressure.lastEntry().getValue()[1];
}
// get patient's heart rate.
public float getHeartRate() {
Log.d("das", this.HeartRate.lastEntry().getValue().toString());
return (Integer) this.HeartRate.lastEntry().getValue();
}
// get patient's description.
public String getTextDescription() {
return this.TextDescription.lastEntry().getValue();
}
}
|
Java
|
UTF-8
| 2,373
| 2.828125
| 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 BTVN_L1;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
/**
*
* @author hungh
*/
public class Client {
private static Socket s;
private static DataInputStream dis;
private static DataOutputStream dos;
public static void nhapHeSo() throws IOException {
Scanner sc = new Scanner(System.in);
double a, b, c, d;
int choice;
do{
System.out.println("1. Giai PTB3");
System.out.println("0. Thoat");
System.out.print("Nhap lua chon: ");
choice = sc.nextInt();
switch(choice){
case 1:
System.out.print("Nhap vao so a: ");
a = sc.nextDouble();
System.out.print("Nhap vao so b: ");
b = sc.nextDouble();
System.out.print("Nhap vao so c: ");
c = sc.nextDouble();
System.out.print("Nhap vao so d: ");
d = sc.nextDouble();
dos.writeInt(choice);
dos.writeDouble(a);
dos.writeDouble(b);
dos.writeDouble(c);
dos.writeDouble(d);
if(dis.readBoolean() == true){
System.out.println("Phuong trinh co nghiem la: " + dis.readDouble());
}else{
System.out.println("Phuong trinh co nghiem phuc: " + dis.readDouble() + "+" + "(" + dis.readDouble() + ")" + "*1");
}
break;
case 0:
dos.writeInt(choice);
break;
}
}while(choice != 0);
}
public static void main(String[] args) throws IOException {
s = new Socket("localhost",1234);
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
nhapHeSo();
}
}
|
C#
|
UTF-8
| 1,096
| 2.78125
| 3
|
[] |
no_license
|
using System.Collections.Generic;
namespace RQL.Net
{
public class RQLResponse
{
internal RQLResponse( RQLRequestBatch batch, string jsonResult, bool success )
{
Success = success;
Batch = batch;
JsonResponse = jsonResult;
if( success )
{
Results = Newtonsoft.Json.JsonConvert.DeserializeObject<IReadOnlyList<object[][]>>( jsonResult );
}
}
/// <summary>
/// Gets whether a result has been obtained or not
/// </summary>
public bool Success { get; }
/// <summary>
/// Gets the raw json Response
/// </summary>
public string JsonResponse { get; }
/// <summary>
/// Gets the original <see cref="RQLRequestBatch"/> request sent and build
/// </summary>
public RQLRequestBatch Batch { get; }
/// <summary>
/// Gets the result of the RQL requests, in the order of the batch.
/// </summary>
public IReadOnlyList<object[][]> Results { get; }
}
}
|
Markdown
|
UTF-8
| 5,814
| 2.953125
| 3
|
[] |
no_license
|
# Books
This is a demo project that uses the Google Books API with React and Redux.
#### Selected Enhancements
- Sort books by ascending, descending, recently added*. Linkable (i.e. copy/paste browser
url and same view displays).
- Switchable layouts (from grid view to list view). Linkable.
(**instead of recently added, publishedDate was used from the Google Books API*)
### Installation
- Download / Unzip the repo.
- ```yarn install```
### Run Local Dev
```yarn start```
### To Run Tests
```yarn run test```
### Test Coverage
```yarn test -- --coverage```
# Project Synopsis & Documentation
## BROILER PLATE
This project uses Create React App with some broiler plate that I’ve used with success on other projects before.
The broiler plate is primaryly in:
- `src/app.js`
- `src/index.js`
- `src/modules.js` (chunking modules is probably total overkill for this project, but this was in my prior broiler plate, so I just left it)
- `src/reducer.js`
- `src/common`
## APP STRUCTURE
The Architexture was guided by the principles of [Unix Philosophy](https://en.wikipedia.org/wiki/Unix_philosophy) and [Worse is Better](https://en.wikipedia.org/wiki/Worse_is_better)
### In Redux/React terms, this means:
- each module has one reducer
- each module has one container with connect()
- anything under the container is a “dumb” component
- modules are encapsulated (though some actions are inevitably public for cross component communication):
* *for example `BooksContainer` can call `FavoritesActions.Add()` on the `FavoritesModule`, however the `FavoritesModule` manages and updates it's own reducer*
- since the modules are self contained they all get chunked to their own files; this is a good pattern for very large products as you only send down the wire what is nessacary, also the relatively "loose coupling" of modules makes them easy to replace, modify or remove, much like a MicroServices Architexture.
## NAMING CONVENTION
Many projects name every file `reducer.js`, `container.js`, `index.js`, etc.
For dev friendliness I errored on the side of caution and chose a naming structure like `favoriteBooks/_favoriteBooksContainer.js`
* the underscore here denotes that the particular file is to do with redux state
Though the names end up much longer, this generally makes navigation of bigger projects easier when you are browsing a repo online, or if you use a menu prompt to open files in your editor.
## OTHER LIBRARIES
When you `yarn install` you may realize you have to download the entire Universe.
I relied heavily on other modules so that I could be productive and produce something that is hopefully bug free in a short amount of time.
- Semantic React UI (HTML/CSS)
- Axios for requests
- Redux Thunk for actions
- query-string, because I am making the whole app linkable/stateful through the URL Hash
## DATA
I decided to use the Google Books API for books data. This would have big implications everywhere, especially since I chose the “linkable URL” option for a feature.
Basically I came to think of Google Books API as my database; and so there is quite bit of work going on with requests, isLoading states and then sorting and displaying this data.
For example, to make every view linkable / reloadable, I had to do a request on every container mount.
A couple things to note:
- on keypress in the search bar I had to cancel prior requests, or else the UI updates would be very funky and without cancelation there would also be potential race conditions on every keypress/network event
- fav book ids get added into the hash, as well as the other feature information orderBy, view and searchTerm
- because of this, the books reducer initializes on “window.location.hash”
- I started out with an action to build the URL, but since this was so central to my app, I eventually moved it to `store.subscribe` in src/app, I felt this made more sense since every state change was effect the “window.location.hash” as de factor database.
## POST MORTEM
## Did it go smoothly?
At the beginning of the project I read the requirements a few times; then went for a walk and thought about what I would do. After the walk I made some rough notes about what I would build.
After that I built it in a very methodical manner.
I would have liked to try out Jest more in my testing, however I am not super familiar with this library, so ended up using Enzyme.
Overall I am pleased with how it turned out; I believe the code is clean, readable and well organized.
## Any surprises or lessons learned?
- [query-string](https://www.npmjs.com/package/query-string) is my new goto for working with URL's
- This is my first time time using [Semantic UI React](https://react.semantic-ui.com/introduction) but found it very easy to use, and I think it is also very "semantic" which makes the code more readable, I now much prefer it over React Bootstrap for prototyping and small projects
- I found The Google API dashboard confusing from a usability perspective. I am always surprised that a big company like this can get things like this wrong; however maybe it's just because they have so many products.
## Should we implement a production ready version of what you built, or would you do things differently next time?
I think the code is strong enough to be used in production, however I’d tweak a few things:
- I’d get a designer UI/UX pro to review it
- I’d make the loading of the views a little smoother
- I’d upgrade some of the modules in package.json
- I’m confident in my QA, but I’d get some other people to look at it
- The Google API has a daily limit of 1000 requests
- right now the CSS is loaded in the index file, for a production build with Webpack this would have to be added into the build script
|
C++
|
UTF-8
| 451
| 2.609375
| 3
|
[] |
no_license
|
#include<iostream>
#include"Matrix.h"
int main(int argc,char* argv[]){
/*int I=atoi(argv[1]),J=atoi(argv[2]);
Mat<Q> m(I,vector<Q>(J,0));
for(int i=0;i<I;i++){
for(int j=0;j<J;j++){
m[i][j]=Q(argv[i*J+j+3]);
}
}*/
int I,J;
cin>>I>>J;
Mat<Q> m(I,vector<Q>(J,0));
for(int i=0;i<I;i++){
for(int j=0;j<J;j++){
double x;
cin>>x;
m[i][j]=Q(x);
}
}
cout<<matrixRank(m)<<endl;
printMatrix(m);
}
|
C++
|
UTF-8
| 3,430
| 2.671875
| 3
|
[] |
no_license
|
#define OLC_PGE_APPLICATION
#include "olcPixelGameEngine.h"
// define map in 1d array
// load sprite and draw
// move with mouse
class BreakOut : public olc::PixelGameEngine
{
public:
BreakOut()
{
sAppName = "Pixel Experiments";
}
private:
float fBatPos = 20.0f;
float fBatWidth = 40.0f;
olc::vf2d vBall = { 200.0f, 200.0f };
olc::vf2d vBallVel = { 200.0f, -100.0f };
float fBatSpeed = 250.0f;
float fBallRadius = 5.0f;
olc::vi2d vBlockSize = { 16,16 };
std::unique_ptr<int[]> blocks;
std::unique_ptr<olc::Sprite> sprTile;
//test
olc::vd2d tilePosition = {5, 5};
public:
bool OnUserCreate() override
{
// 10x10 is our cutom map for putting obstacle and things as sprited (assmued square).
// so always take dimention of sprite as 10x10 dim or no. defined here.
blocks = std::make_unique<int[]>(10 * 10);
for (int y = 0; y < 10; y++)
{
for (int x = 0; x < 10; x++)
{
// when this virtual 2d we write in index
if (x == 0 || y == 0 || x == 9 || y == 9) // this will draw in whole line.
// we write in index single value
// i = x + width * y
blocks[y * 10 + x] = 10;
else
blocks[y * 10 + x] = 0;
if(x == 5 && y == 5){
blocks[y * 10 + x] = 1;
}
//if (x > 2 && x <= 20 && y > 3 && y <= 5)
//blocks[y * 24 + x] = 1;
//if (x > 2 && x <= 20 && y > 5 && y <= 7)
//blocks[y * 24 + x] = 2;
//if (x > 2 && x <= 20 && y > 7 && y <= 9)
//blocks[y * 24 + x] = 3;
// std::cout << blocks [y * 10 + x]; // debug
}
// std::cout << std::endl; //debug
}
// Load the sprite
sprTile = std::make_unique<olc::Sprite>("D:/ADesktop/vsCppWorkSpace/cpppge/pge_pixel_experiments/gfx/tut_tiles.png");
return true;
}
bool OnUserUpdate(float fElapsedTime) override
{
// Draw Screen
Clear(olc::DARK_BLUE);
SetPixelMode(olc::Pixel::MASK); // Dont draw pixels which have any transparency
for (int y = 0; y < 10; y++)
{
for (int x = 0; x <10; x++)
{
switch (blocks[y * 10 + x])
{
case 0: // Do nothing
break;
case 10: // Draw Boundary, second (0,0) is index of tile.png to get diff. color tile.
DrawPartialSprite(olc::vi2d(x, y) * vBlockSize, sprTile.get(), olc::vi2d(0, 0) * vBlockSize, vBlockSize);
break;
// case 1: // Draw Red Block
// DrawPartialSprite(olc::vi2d(x, y) * vBlockSize, sprTile.get(), olc::vi2d(1, 0) * vBlockSize, vBlockSize);
// break;
// case 2: // Draw Green Block
// DrawPartialSprite(olc::vi2d(x, y) * vBlockSize, sprTile.get(), olc::vi2d(2, 0) * vBlockSize, vBlockSize);
// break;
// case 3: // Draw Yellow Block
// DrawPartialSprite(olc::vi2d(x, y) * vBlockSize, sprTile.get(), olc::vi2d(3, 0) * vBlockSize, vBlockSize);
// break;
}
//std::cout << olc::vi2d(x, y) * vBlockSize;
}
//std::cout << std::endl;
}
if ( GetMouse(0).bHeld ){
tilePosition = {GetMouseX() / 16, GetMouseY() / 16};
// our greed is 160x160 and sprite are 16x16
// mouse will return actuali pixel so we need to devide by sprite dim 16x16
// to move with mouse
}
DrawPartialSprite(olc::vi2d(tilePosition) * vBlockSize, sprTile.get(), olc::vi2d(1, 0) * vBlockSize, vBlockSize);
SetPixelMode(olc::Pixel::NORMAL); // Draw all pixels
return true;
}
};
int main()
{
BreakOut demo;
//std::cout << system("dir") << std::endl;
if ( demo.Construct(160, 160, 4, 4) );
demo.Start();
return 0;
}
|
C
|
UTF-8
| 3,557
| 2.75
| 3
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
////////////////////////////////////////////////////////////////////////////////
// COPYRIGHT (c) 2016 Igal Maly. ALL RIGHTS RESERVED.
// Use of this source code is governed by a FreeBSD License that can be found
// in the LICENSE file.
//------------------------------------------------------------------------------
/// \file
/// \author imaly
///
/// \brief Regfile accessing/parsing
/// Registers are Engine's struct members, pointing to physical bus address
/// Register fields are register members represented as 2-dimensional arrays
/// as follows:
/// ==========================================================
/// || field[field bit width][field start bit number*] ||
/// ==========================================================
/// *counting from 1 - first bit (LSB) is '1' (and not '0')
///
////////////////////////////////////////////////////////////////////////////////
#ifndef REGFILE_ACCESS_H_
#define REGFILE_ACCESS_H_
#include "hwaccess.h"
/// HW engine register access (for reading and assignment)
/// \regPath represents a register following this project's regfile convention
/// \usage Read: a = REG(pHwRegFileEng->someRegister);
/// Write: REG(pHwRegFileEng->someRegister) = 5;
#define REG(regPath) HW_MEM(REG_ADDR(regPath))
/// HW engine field-in-a-register reading
/// 'Field' is a continous set of bits in a register with a specific function
/// \fieldPath represents a field member following this project's regfile convention
/// \usage a = REG_FIELD_GET(pHwRegFileEng->someRegister.someField);
#define REG_FIELD_GET(fieldPath) HW_FIELD_GET(REG_ADDR(fieldPath), FIELD_BIT_OFFSET(fieldPath), FIELD_BIT_SIZE(fieldPath))
/// HW engine field-in-a-register writing
/// 'Field' is a continous set of bits in a register with a specific function
/// \fieldPath represents a field member following this project's regfile convention
/// \usage REG_FIELD_WR(pHwRegFileEng->someRegister.someField, 5);
#define REG_FIELD_WR(fieldPath, val) HW_FIELD_WR(REG_ADDR(fieldPath), FIELD_BIT_OFFSET(fieldPath), FIELD_BIT_SIZE(fieldPath), val)
/// Alias for HW engine bit-field-in-a-register clearing
#define REG_BIT_CLR(fieldPath) REG_FIELD_WR(fieldPath, 0)
/// Alias for HW engine bit-field-in-a-register setting
#define REG_BIT_SET(fieldPath) REG_FIELD_WR(fieldPath, 1)
//------------------------------------------------------------
// For manipulating shadow registers (not on HW bus)
//------------------------------------------------------------
/// Same as REG(), but with no volatile casting
#define SHADOW(path) (*((MEM_ADDR_t*)(&(path))))
#define SHADOW_FIELD_GET(fieldPath) \
BITS_GET(SHADOW(fieldPath), FIELD_BIT_OFFSET(fieldPath), FIELD_BIT_SIZE(fieldPath))
#define SHADOW_FIELD_WR(fieldPath, val) \
BITS_WR(SHADOW(fieldPath), FIELD_BIT_OFFSET(fieldPath), FIELD_BIT_SIZE(fieldPath), val)
#define SHADOW_FIELD_WR_NO_CLR(fieldPath, val) \
BITS_WR_NO_CLR(SHADOW(fieldPath), FIELD_BIT_OFFSET(fieldPath), FIELD_BIT_SIZE(fieldPath), val)
#define SHADOW_BIT_CLR(fieldPath) BIT_CLR(SHADOW(fieldPath), FIELD_BIT_OFFSET(fieldPath))
#define SHADOW_BIT_SET(fieldPath) BIT_SET(SHADOW(fieldPath), FIELD_BIT_OFFSET(fieldPath))
//---- INTERNAL, USE MACROS ABOVE -----
#define FIELD_BIT_OFFSET(fieldPath) (sizeof((*fieldPath)[0]) - 1)
#define FIELD_BIT_SIZE(fieldPath) (sizeof(*fieldPath) / sizeof((*fieldPath)[0]))
#define REG_ADDR(path) ((MEM_ADDR_t)(&(path)))
#endif // Header-file guard
|
C++
|
UTF-8
| 4,314
| 2.75
| 3
|
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
#define ericxiao ios_base::sync_with_stdio(0);cin.tie(0);
using namespace std;
int B, N, d, x, M;
inline int Abs(int x){
return (x < 0) ? -x : x;
}
inline char readchar() {
static const size_t bufsize = 65536;
static char buf[bufsize];
static char *p = buf, *end = buf;
if (p == end) end = buf + fread_unlocked(buf, 1, bufsize, stdin), p = buf;
return *p++;
}
inline void const Read(int & p) {
p = 0;
int tmp = 0;
char c = readchar();
tmp = !(c^'-');
while (c < '0' || c > '9') {
c = readchar();
}
while (c >= '0' && c <= '9')
p = (p<<3)+(p<<1)+(c^48), c = readchar();
p = tmp?-p:p;
}
struct BIT{
vector<int> bit;
int N;
BIT(){}
BIT(int N): N(N){
bit.resize(N);
}
void add(int p, int x){
for(; p < N; p += p & -p) bit[p] += x;
}
int res(int p){
if(p <= 0) return 0;
if(p >= N) return res(N - 1);
int r = 0;
for(; p; p -= p & -p) r += bit[p];
return r;
}
int sum(int l, int r){ // [l, r]
return res(r) - res(l - 1);
}
};
struct BIT2D{
vector<BIT> bit;
int N;
BIT2D(){}
BIT2D(int N): N(N){
bit.resize(N);
for(BIT &b : bit) b = BIT(N);
}
void add(int x, int y, int v){
for(; x < N; x += x & -x) bit[x].add(y, v);
}
int res(int x, int y){
if(x <= 0) return 0;
if(x >= N) return res(N - 1, y);
int r = 0;
for(; x; x -= x & -x) r += bit[x].res(y);
return r;
}
int sum(int a, int b, int c, int d){ //[a, c] * [b, d]
return res(c, d) - res(c, b - 1) - res(a - 1, d) + res(a - 1, b - 1);
}
};
struct BIT3D{
vector<BIT2D> bit;
int N;
BIT3D(){}
BIT3D(int N): N(N){
bit.resize(N);
for(BIT2D &b : bit) b = BIT2D(N);
}
void add(int x, int y, int z, int v){
for(; x < N; x += x & -x) bit[x].add(y, z, v);
}
int res(int x, int y, int z){
if(x <= 0) return 0;
if(x >= N) return res(N - 1, y, z);
int r = 0;
for(; x; x -= x & -x) r += bit[x].res(y, z);
return r;
}
int sum(int a, int b, int c, int x, int y, int z){ //[a, x] * [b, y] * [c, z]
return res(x, y, z) - res(x, b - 1, z) - res(x, y, c - 1) - res(a - 1, y, z) + res(x, b - 1, c - 1) + res(a - 1, b - 1, z) + res(a - 1, y, c - 1) - res(a - 1, b - 1, c - 1);
}
};
struct PP{
int x, y;
PP(){}
PP(int a, int b): x(a), y(b){}
};
struct PS{
int x, y, z, w;
PS(){}
PS(int a, int b, int c, int d): x(a), y(b), z(c), w(d){}
};
void solve1(){
Read(N); Read(d); Read(M);
vector<int> cur, all;
cur.resize(N);
for(int i = 0; i < N; i++){
Read(cur[i]);
}
sort(cur.begin(), cur.end());
for(int x : cur) all.push_back(x);
int l = 0, r = 0;
long long int ans = 0;
for(int i = 0; i < N; i++){
while(r < N && Abs(all[r] - cur[i]) <= d) r++;
while(l < N && Abs(all[l] - cur[i]) > d) l++;
ans += (r - l - 1);
}
cout << ans / 2 << endl;
}
void solve2(){
Read(N); Read(d); Read(M);
BIT bit = BIT(2 * M + 5);
vector<PP> cur, all;
int x, y;
for(int i = 0; i < N; i++){
Read(x); Read(y);
cur.emplace_back(x + y, x - y);
}
sort(cur.begin(), cur.end(), [](PP &a, PP &b) {
return a.x < b.x;
});
for(auto p : cur) all.push_back(p);
int l = 0, r = 0;
long long int ans = 0;
for(int i = 0; i < N; i++){
while(r < N && Abs(all[r].x - cur[i].x) <= d){
bit.add(all[r++].y + M, 1);
}
while(l < N && Abs(all[l].x - cur[i].x) > d){
bit.add(all[l++].y + M, -1);
}
ans += bit.sum(cur[i].y + M - d, cur[i].y + M + d) - 1;
}
cout << ans / 2 << endl;
}
void solve3(){
Read(N); Read(d); Read(M);
BIT3D bit = BIT3D(4 * M + 5);
vector<PS> cur, all;
int x, y, z;
for(int i = 0; i < N; i++){
Read(x); Read(y); Read(z);
cur.emplace_back(x + y + z, x + y - z + 2 * M, x - y + z + 2 * M, x - y - z + 2 * M);
}
sort(cur.begin(), cur.end(), [](PS &a, PS &b) {
return a.x < b.x;
});
for(auto p : cur) all.push_back(p);
int l = 0, r = 0;
long long int ans = 0;
for(int i = 0; i < N; i++){
while(r < N && Abs(all[r].x - cur[i].x) <= d){
bit.add(all[r].y, all[r].z, all[r].w, 1);
r++;
}
while(l < N && Abs(all[l].x - cur[i].x) > d){
bit.add(all[l].y, all[l].z, all[l].w, -1);
l++;
}
ans += bit.sum(cur[i].y - d, cur[i].z - d, cur[i].w - d, cur[i].y + d, cur[i].z + d, cur[i].w + d) - 1;
}
cout << ans / 2 << endl;
}
int main(){
ericxiao;
Read(B);
if(B == 1){
solve1();
} else if(B == 2){
solve2();
} else {
solve3();
}
}
|
JavaScript
|
UTF-8
| 1,280
| 3.125
| 3
|
[] |
no_license
|
/*
* Title:
* Description:
* Author: Md Asif Joardar
* Date:
*
*/
// dependencies
const crypto = require('crypto');
const environments = require('./environments');
// module scaffolding
const utilities = {};
// parse json string to object
utilities.parseJSON = (jsonString) => {
let output;
try{
output = JSON.parse(jsonString);
}catch {
output = {};
}
return output;
};
// hash string
utilities.hash = (str) => {
if(typeof str === 'string' && str.length > 0 ){
const hash = crypto.createHmac('sha256', environments.secretKey)
.update(str)
.digest('hex');
return hash;
} else{
return false;
}
};
// create random string
utilities.createRandomString = (strLength) => {
let length = strLength;
length = typeof(strLength) === 'number' && strLength > 0 ? strLength : false;
if(length){
let possibleCharacters = 'abcdefghijklmnopqrstuvwxyz0123456789';
let output = '';
for(let i=1; i<=length; i++){
output += possibleCharacters.charAt(Math.floor(Math.random() * 35));
}
return output;
} else{
return false;
}
};
module.exports = utilities;
|
C++
|
UTF-8
| 18,726
| 2.578125
| 3
|
[] |
no_license
|
/* HOW THE LIGHT PATTERN WORKS:
> The prefix (half past, quarter to, etc) will be a separate color from the hours.
> Hours will be one of two solid colors, one for AM, one for PM
- Light blue for AM, Purple for PM?
> The prefix will fade from green -> red over the course of the 5 min interval
*/
/*
* Button 1: Big Word Mode (100ms); Secret Message Mode (5s)
*/
//------Define/Includes----------
#define DEBUG 1
//#define RESET_TIME 1 //Comment out to negate
#include <Adafruit_NeoPixel.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_GFX.h>
#include <RTClib.h>
#include <Wire.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define DATA_PIN 6
#define BUTTON 4 //The Mode Button
#define DST_BUTTON 5
#define WORD_MODE 0
#define BIG_DIGIT_MODE 1
#define BIRTHDAY_MODE 2
#define SECRET_WORD_MODE 3
#define NUM_BIRTHDAYS 1
//------Object Declarations-------
Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(11, 11, DATA_PIN, NEO_MATRIX_TOP + NEO_MATRIX_LEFT + NEO_MATRIX_ROWS + NEO_MATRIX_ZIGZAG, NEO_KHZ800 + NEO_GRB);
RTC_DS3231 rtc;
//------Global Variables----------
DateTime theTime;
// Find the date
uint16_t theYear;
uint8_t theMonth;
uint8_t theDay;
//Find the time
uint8_t theHour;
uint8_t theMinute;
uint8_t theSecond;
//Global var color
uint16_t color;
uint16_t AM_COLOR = matrix.Color(0, 255, 196);
uint16_t PM_COLOR = matrix.Color(239, 0, 255);
uint16_t BIG_DIGIT_COLOR = matrix.Color(0, 255, 0);
uint16_t BIG_DIGIT_OUTSIDE_COLOR = matrix.Color(0, 0, 0);
uint16_t CURSOR_COLOR = makeColor('R');
//For Debounce
unsigned long lastTimeChanged;
int previousState; //For the button debounce
int buttonState = HIGH;
int lastButtonState = LOW;
//For DST State
int lastDSTstate; //For the changing of the DST BUTTON
//For Blinking Cursor
unsigned long lastBlink = 0;
bool blinkState = 0;
//Various
bool firstSecretTime = 1; //For the Secret Message timer
double seed; //For the color fade
uint8_t prevSecond = 0; //Tracker for the color fade, to increment each second
bool isBirthday = 0; //Flash the happy birthday when in birthday mode (will be true for entirety of brithday)
uint8_t digitPrevSecond = 0; //For the flashing of the big digits
uint8_t BIRTH_MONTH[NUM_BIRTHDAYS] = {8};
uint8_t BIRTH_DAY[NUM_BIRTHDAYS] = {12};
int mode;
// ----Character Number Declarations ----
const bool CHAR_NUMS[10][5][5] {
{
{0, 1, 1, 1, 0}, // ZERO
{0, 1, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0}
},
{
{0, 1, 1, 0, 0}, // ONE
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 1, 1, 1, 0}
},
{
{0, 1, 1, 1, 0}, //TWO
{0, 0, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 1, 0, 0, 0},
{0, 1, 1, 1, 0}
},
{
{0, 1, 1, 1, 0}, //THREE
{0, 0, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 1, 0},
{0, 1, 1, 1, 0}
},
{
{0, 1, 0, 1, 0}, //FOUR
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 1, 0},
{0, 0, 0, 1, 0}
},
{
{0, 1, 1, 1, 0}, //FIVE
{0, 1, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 1, 0},
{0, 1, 1, 1, 0}
},
{
{0, 1, 1, 1, 0}, //SIX
{0, 1, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0}
},
{
{0, 1, 1, 1, 0}, //SEVEN
{0, 0, 0, 1, 0},
{0, 0, 0, 1, 0},
{0, 0, 0, 1, 0},
{0, 0, 0, 1, 0}
},
{
{0, 1, 1, 1, 0}, //EIGHT
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0}
},
{
{0, 1, 1, 1, 0}, //NINE
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 1, 0},
{0, 1, 1, 1, 0}
}
};
// ---- END Number Character declarations ----
void setup() {
#ifdef DEBUG
Serial.begin(9600);
#endif
matrix.begin(); //across, down
matrix.setTextWrap(true); //Used for big digit display mode
rtc.begin(); //start the time module
#ifdef RESET_TIME
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)) + TimeSpan(0, 0, 0, 6)); //Resets to time of compilation w/ 6s adjust for upload time
#endif
if (rtc.lostPower()) { //If RTC loses power, flash red lights 5 times, then adjust time
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)) + TimeSpan(0, 0, 0, 6)); //Potential problem bc 5 seconds after runtime?
for (int i = 0; i < 5; i++) {
matrix.fillScreen(matrix.Color(255, 0, 0));
delay(1000);
matrix.fillScreen(0);
delay(1000);
}
}
pinMode(BUTTON, INPUT_PULLUP);
previousState = digitalRead(BUTTON);
pinMode(DST_BUTTON, INPUT_PULLUP); // Ground DST Pushbutton, LOW means on
//lastDSTstate = digitalRead(DST_BUTTON);
if(digitalRead(DST_BUTTON) == HIGH)
mode = WORD_MODE;
}
void loop() {
matrix.clear();
updateTime(); //Update the time and timing container (hour, min, sec) every clock cycle
updateSeed();
readButtonPush(); //Read the Mode button push
checkDST();
// Serial.println();
// Serial.print("**********************");
// Serial.print(seed);
// Serial.print("***************");
// Serial.println();
switch (mode) {
case WORD_MODE: //Word mode
displayWords();
break;
case BIG_DIGIT_MODE:
displayBigDigits();
break;
case SECRET_WORD_MODE:
displaySecretWord();
break;
case BIRTHDAY_MODE:
displayBirthday();
break;
default:
matrix.fillScreen(matrix.Color(255, 0, 0)); //Fill screen with red for error
break;
}
//delay(1000);
matrix.show();
}
// ----- AUXILIARY FUNCTIONS FROM VOID LOOP() ----
void updateTime() {
theTime = rtc.now(); //Gather current time information
// Find the date
theYear = theTime.year();
theMonth = theTime.month();
theDay = theTime.day();
//Find the time
theHour = theTime.hour();
theMinute = theTime.minute();
theSecond = theTime.second();
#ifdef DEBUG
Serial.print(theHour);
Serial.print(':');
Serial.print(theMinute);
Serial.print(':');
Serial.print(theSecond);
Serial.println();
#endif
if (theHour == theMinute == theSecond == 0) { //Every new day check for a birthday
checkBirthday();
}
}
void readButtonPush() {
int reading = digitalRead(BUTTON);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) { //On any change of the switch
// reset the debouncing timer
lastTimeChanged = millis();
}
if ((millis() - lastTimeChanged) > 2000) {
if (reading == LOW) {
mode = SECRET_WORD_MODE;
firstSecretTime = 1;
#ifdef DEBUG
Serial.println();
Serial.print("------------MODE CHANGE, New Mode: ");
Serial.print(mode);
Serial.print("--------------");
Serial.println();
#endif
lastButtonState = HIGH;
return;
}
}
if ((millis() - lastTimeChanged) > 50) { //If the swtich was last changed 50 ms ago
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) {
// CHANGE MODE HERE
switch (mode) {
case WORD_MODE:
mode = BIG_DIGIT_MODE;
break;
case BIG_DIGIT_MODE:
case SECRET_WORD_MODE:
case BIRTHDAY_MODE:
mode = WORD_MODE;
break;
}
#ifdef DEBUG
Serial.println();
Serial.print("------------MODE CHANGE, New Mode: ");
Serial.print(mode);
Serial.print("--------------");
Serial.println();
#endif
lastButtonState = reading;
return;
}
Serial.println(50);
}
}
lastButtonState = reading;
}
void checkDST() {
int currentState = digitalRead(DST_BUTTON);
if (currentState != lastDSTstate) { //If the button has changed positions
if (currentState == LOW) { //If the button is PRESSED IN
DateTime hourAhead = (rtc.now() + TimeSpan(0, 1, 0, 0));
rtc.adjust(hourAhead);
}
if (currentState == HIGH) { //If the button is NOT PRESSED IN
DateTime hourBehind = (rtc.now() - TimeSpan(0, 1, 0, 0));
rtc.adjust(hourBehind);
}
lastDSTstate = currentState; //Update the last state of the button
}
}
void checkBirthday() { //Sets a boolean if there is a birthday occuring, then changes mode if birthday
for (int i = 0; i < NUM_BIRTHDAYS; i++) {
if (BIRTH_MONTH[i] == theMonth) {
if (BIRTH_DAY[i] == theDay) {
isBirthday = 1;
} else isBirthday = 0;
} else isBirthday = 0;
}
if (isBirthday) {
mode = BIRTHDAY_MODE;
}
}
// ----- STATE FUNCTIONS ---- The Display Modes
void displayWords() {
color = fadeGreenToRed(seed);
W_ITS();
//Break up time into 5 minute intervals
if (theMinute < 5) { //0-5 past hour - Its CURRENT HOUR oclock
lightHour(0);
color = fadeGreenToRed(seed); //For the OCLOCK
W_OCLOCK();
} else if (theMinute < 10) { //5-10 past hour - Its Five past CURRENT HOUR
W_FIVE();
W_PAST();
lightHour(0);
} else if (theMinute < 15) { //10-15 past hour - Its ten past CURRENT HOUR
W_TEN();
W_PAST();
lightHour(0);
} else if (theMinute < 20) { //15-20 - Its a quarter past CURRENT HOUR
W_A();
W_QUARTER();
W_PAST();
lightHour(0);
} else if (theMinute < 25) { //20-25 - Its twenty past CURRENT HOUR
W_TWENTY();
W_PAST();
lightHour(0);
} else if (theMinute < 30) { //25-30 - Its twenty five past CURRENT HOUR
W_TWENTY();
W_FIVE();
W_PAST();
lightHour(0);
} else if (theMinute < 35) { //30-35 - Its half way past CURRENT HOUR
W_HALF();
W_WAY();
W_PAST();
lightHour(0);
} else if (theMinute < 40) { //35-40 - Its twenty five til NEXT HOUR
W_TWENTY();
W_FIVE();
W_TIL();
lightHour(1);
} else if (theMinute < 45) { //40-45 - Its twenty til NEXT HOUR
W_TWENTY();
W_TIL();
lightHour(1);
} else if (theMinute < 50) { //45-50 - Its a quarter til NEXT HOUR
W_A();
W_QUARTER();
W_TIL();
lightHour(1);
} else if (theMinute < 55) { //50-55 - Its ten til NEXT HOUR
W_TEN();
W_TIL();
lightHour(1);
} else if (theMinute < 60) { //55-60 - Its five til NEXT HOUR
W_FIVE();
W_TIL();
lightHour(1);
}
}
void displayBigDigits() { //HAVE TO TEST WHETHER IT LOOKS NATURAL TO DO 4 DIGIT DISPLAY ON ARRAY
int localMode; //1 for numbers, 2 for happy birthday
if (isBirthday) { //If its a birthday, flash the happy birthday message every 5 seconds between
if (millis() - digitPrevSecond > 5000) {
localMode = 2; //Happy birthday
digitPrevSecond = millis();
} else localMode = 1; //Big Digits
} else localMode = 1; //Big Digits
switch (localMode) {
case 1: //Digits
parseTimeAndDisplayDigits();
blinkCursor();
break;
case 2: //Happy birthday
displayBirthday();
break;
}
}
void displaySecretWord() {
color = makeColor('R');
W_I();
W_LOVE();
W_YOU();
if (firstSecretTime) {
matrix.show();
delay(3000);
firstSecretTime = 0;
}
}
void displayBirthday() {
color = matrix.Color(255, 230, 0);
W_HAPPY();
W_BIRTHDAY();
}
// ----- Functions for COLOR --------
uint16_t makeColor(char letter) { //Sends red, green, or blue depending on given char input
if (letter == 'R') {
return matrix.Color(255, 0, 0);
}
if (letter == 'G') {
return matrix.Color(0, 255, 0);
}
if (letter == 'B') {
return matrix.Color(0, 0, 255);
}
return 0;
}
uint16_t fadeGreenToRed(double num) { //seed will be number from 0-299
double r;
double g;
int b = 0;
if (num < 150) { //Green is 255, red fades in from 0-255
g = 255;
r = num * 1.7; //Being that the increment is 5 minutes, and this is all 510 steps broken into 5*60 steps, changes once per second
}
if (num >= 150) { //Red is 255, green fades out from 255-0
r = 255;
g = (300 - num) * 1.7;
}
return matrix.Color((int) r, (int) g, b);
}
// ----- Other Auxiliary functions called elsewhere ----
// @PARAM int - set to 0 for current hour, set to 1 for next hour (30-60 min)
void lightHour (int hourFlag) { // Pushes out info for the hour, Called by displayWords()
if (theHour >= 12) color = PM_COLOR;
if (theHour < 12) color = AM_COLOR;
int lightHour = (theHour + hourFlag) % 12;
switch (lightHour) {
case 0: // THIS IS 12, handle special
//compare pre - mod value
if ((theHour + hourFlag) == 12) {
color = PM_COLOR;
N_NOON();
} else if (((theHour + hourFlag) == 24) || ((theHour + hourFlag) == 0)) {
color = AM_COLOR;
N_MIDNIGHT();
}
break;
case 1:
N_ONE();
break;
case 2:
N_TWO();
break;
case 3:
N_THREE();
break;
case 4:
N_FOUR();
break;
case 5:
N_FIVE();
break;
case 6:
N_SIX();
break;
case 7:
N_SEVEN();
break;
case 8:
N_EIGHT();
break;
case 9:
N_NINE();
break;
case 10:
N_TEN();
break;
case 11:
N_ELEVEN();
break;
default:
break;
}
}
//Misleading name, actually does not push info out to matrix
void light(uint8_t across, uint8_t down) { //Pushes out info to light a specific pixel- DOES NOT UPDATE SCREEN
matrix.drawPixel(across, down, color);
}
void off() { // Pushes info to clear screen
matrix.fillScreen(0);
}
void parseTimeAndDisplayDigits() { //Example input (15, 56), taken from global variables theHour, theMinute
int hourTen, hourOne, minuteTen, minuteOne;
hourTen = theHour / 10;
minuteTen = theMinute / 10;
hourOne = theHour % 10;
minuteOne = theMinute % 10;
lightTL(hourTen);
lightTR(hourOne);
lightBL(minuteTen);
lightBR(minuteOne);
}
void lightTL(int num) { // Accepts input 1-9 (actually should really only be a zero or one or two), displays number in the top left quadrant
int i, j;
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (CHAR_NUMS[num][i][j]) {
matrix.drawPixel(j, i, BIG_DIGIT_COLOR);
} else matrix.drawPixel(j, i, BIG_DIGIT_OUTSIDE_COLOR);
}
}
}
void lightTR(int num) { // Accepts input 1-9 displays number in the top right quadrant
int i, j;
int offsetHorizontal = 6;
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (CHAR_NUMS[num][i][j]) {
matrix.drawPixel(j + offsetHorizontal, i, BIG_DIGIT_COLOR);
} else matrix.drawPixel(j + offsetHorizontal, i, BIG_DIGIT_OUTSIDE_COLOR);
}
}
}
void lightBL(int num) { // Accepts input 1-9 displays number in the bottom left quadrant
int i, j;
int offsetVertical = 6;
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (CHAR_NUMS[num][i][j]) {
matrix.drawPixel(j, i + offsetVertical, BIG_DIGIT_COLOR);
} else matrix.drawPixel(j, i + offsetVertical, BIG_DIGIT_OUTSIDE_COLOR);
}
}
}
void lightBR(int num) { // Accepts input 1-9 displays number in the bottom right quadrant
int i, j;
int offsetVerticalAndHorizontal = 6;
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (CHAR_NUMS[num][i][j]) {
matrix.drawPixel(j + offsetVerticalAndHorizontal, i + offsetVerticalAndHorizontal, BIG_DIGIT_COLOR);
} else matrix.drawPixel(j + offsetVerticalAndHorizontal, i + offsetVerticalAndHorizontal, BIG_DIGIT_OUTSIDE_COLOR);
}
}
}
void blinkCursor() {
// if (hasSecondChanged()) {
// if (theSecond % 2 == 0) { //Every 2 distinct seconds, set the color to the cursor color
// color = CURSOR_COLOR;
// C_CURSOR();
// } else {
// //color = matrix.Color(0, 0, 0); //Every offset two seconds, set the color to OFF
// }
// }
if ((millis() - lastBlink) >= 1000) {
lastBlink = millis();
if (blinkState == 0) {
blinkState = 1;
} else blinkState = 0;
}
if (blinkState) {
color = CURSOR_COLOR;
} else color = matrix.Color(0, 0, 0);
C_CURSOR();
}
bool hasSecondChanged() {
if (theSecond != prevSecond) {
prevSecond = theSecond;
return 1;
} else return 0;
}
void updateSeed() {
if (hasSecondChanged()) {
if (theMinute % 5 == 0 && theSecond == 0) { //If we land on a fifth minute, reset the seed
seed = 0;
} else seed++; //else add one to the seed
}
}
// ----- WORD FUNCTIONS -- Pushes out info for the words/phrases ------
void W_ITS() { //Word_ITS
for (int i = 0; i <= 2; i++) {
light(i, 0);
}
}
void W_A() {
light(4, 0);
}
void W_HALF() {
for (int i = 6; i <= 9; i++) {
light(i, 0);
}
}
void W_TEN() {
for (int i = 1; i <= 3; i++) {
light(i, 1);
}
}
void W_QUARTER() {
for (int i = 4; i <= 10; i++) {
light(i, 1);
}
}
void W_TWENTY() {
for (int i = 0; i <= 5; i++) {
light(i, 2);
}
}
void W_FIVE() {
for (int i = 7; i <= 10; i++) {
light(i, 2);
}
}
void W_WAY() {
for (int i = 0; i <= 2; i++) {
light(i, 3);
}
}
void W_TIL() {
for (int i = 3; i <= 5; i++) {
light(i, 3);
}
}
void W_PAST() {
for (int i = 6; i <= 9; i++) {
light(i, 3);
}
}
void N_SEVEN() {
for (int i = 1; i <= 5; i++) {
light(i, 4);
}
}
void N_NOON() {
for (int i = 7; i <= 10; i++) {
light(i, 4);
}
}
void W_BIRTHDAY() {
for (int i = 1; i <= 5; i++) {
light(i, 5);
}
for (int j = 7; j <= 9; j++) {
light(j, 5);
}
}
void N_MIDNIGHT() {
for (int i = 0; i <= 7; i++) {
light(i, 6);
}
}
void N_TEN() {
for (int i = 8; i <= 10; i++) {
light(i, 6);
}
}
void N_FIVE() {
for (int i = 0; i <= 3; i++) {
light(i, 7);
}
}
void N_NINE() {
for (int i = 4; i <= 7; i++) {
light(i, 7);
}
}
void N_TWO() {
for (int i = 8; i <= 10; i++) {
light(i, 7);
}
}
void N_ELEVEN() {
for (int i = 0; i <= 5; i++) {
light(i, 8);
}
}
void N_EIGHT() {
for (int i = 6; i <= 10; i++) {
light(i, 8);
}
}
void N_ONE() {
for (int i = 0; i <= 2; i++) {
light(i, 9);
}
}
void N_SIX() {
for (int i = 3; i <= 5; i++) {
light(i, 9);
}
}
void N_THREE() {
for (int i = 6; i <= 10; i++) {
light(i, 9);
}
}
void N_FOUR() {
for (int i = 0; i <= 3; i++) {
light(i, 10);
}
}
void W_OCLOCK() {
for (int i = 5; i <= 10; i++) {
light(i, 10);
}
}
void W_HAPPY() {
for (int i = 0; i <= 4; i++) {
light(6, i);
}
}
void W_I() {
light(3, 0);
}
void W_LOVE() {
light(8, 0);
light(10, 0);
light(9, 2);
light(10, 2);
}
void W_YOU() {
light(0, 4);
light(0, 5);
light(4, 10);
}
void C_CURSOR() {
light(5, 4);
light(5, 5);
light(5, 6);
light(4, 5);
light(6, 5);
}
|
JavaScript
|
UTF-8
| 3,343
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
import Ajax from "./ajax.js";
let game;
let player;
const rock_button = document.getElementById("rock_button");
const paper_button = document.getElementById("paper_button");
const scissors_button = document.getElementById("scissors_button");
const lizard_button = document.getElementById("lizard_button");
const spock_button = document.getElementById("spock_button");
const history_list = document.getElementById("history_list");
rock_button.onclick = function () {
button_click("Rock");
};
paper_button.onclick = function () {
button_click("Paper");
};
scissors_button.onclick = function () {
button_click("Scissors");
};
lizard_button.onclick = function () {
button_click("Lizard");
};
spock_button.onclick = function () {
button_click("Spock");
};
const winner_text = [
"Game Draw",
"I Win",
"Opponent Wins"
];
const check_result = function () {
Ajax.query({
"type": "check_result",
"id": game.id
}).then(function (result_game) {
game = result_game;
if (game.closed) {
const li = document.createElement("li");
const final_plays = (
player === 1
? [game.player_1_play, game.player_2_play]
: [game.player_2_play, game.player_1_play]
);
let winner; // Here 1 is me, 2 is opponent.
if (game.winner === 0) {
winner = 0;
} else if (player === 1) {
winner = game.winner;
} else {
winner = 3 - game.winner; // 1 → 2, 2 → 1
}
li.textContent = (
`I played ${final_plays[0]}, ` +
`Opponent played ${final_plays[1]}: ` +
`${winner_text[winner]}`
);
history_list.append(li);
my_play_span.textContent = emoji[final_plays[0]];
their_play_span.textContent = emoji[final_plays[1]];
} else {
setTimeout(check_result, game.play_due - game.current_time);
}
});
};
const my_play_span = document.getElementById("my_play");
const their_play_span = document.getElementById("their_play");
const emoji = {
"Rock": "🪨",
"Paper": "🧻",
"Scissors": "✂️",
"Lizard": "🦖",
"Spock": "🖖",
"": "💁"
};
const button_click = function (my_play) {
my_play_span.textContent = emoji[my_play];
if (!game || game.closed) {
their_play_span.textContent = emoji[""];
Ajax.query({
"type": "ready_to_play"
}).then(function (response_game) {
game = response_game;
player = (
game.full
? 2
: 1
);
Ajax.query({
"type": "play_a_move",
"id": game.id,
"player": player,
"play": my_play
});
setTimeout(check_result, game.play_due - game.current_time);
});
} else {
Ajax.query({
"type": "play_a_move",
"id": game.id,
"player": player,
"play": my_play
});
}
};
// const ai_play = function () {
// const plays = ["Rock", "Paper", "Scissors"];
// return plays[Math.floor(Math.random() * plays.length)];
// };
|
Python
|
UTF-8
| 915
| 2.5625
| 3
|
[] |
no_license
|
#!/usr/bin/python
import os
import re
import subprocess
filename = "/var/log/zimbio/error.log"
stdin,stdout = os.popen2("tail -100 %s" % filename)
stdin.close()
lines = stdout.readlines()
stdout.close()
# Loop through the lines backwards until we find the "REQUEST STATS"
counter = len(lines) - 1
lns = []
while counter >= 0:
if re.search("DEBUG REQUEST STATS", lines[counter]):
lns.append(lines[counter])
counter = counter - 1
views = []
for line in lns:
comp = line.split(" ")
this_one = False
for x in comp:
if this_one:
views.append(x)
break
if x == "View":
this_one = True
for view in views:
command = "ack \"def %s\(\"" % view
#print command
#print view
res = subprocess.check_output(command, shell=True)
comp = res.split(":")
if comp:
print "%s : %s : line %s" % (view, comp[0], comp[1])
|
C#
|
UTF-8
| 640
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
using System;
using Windows.UI.Xaml.Data;
namespace Musicus
{
public class BoolOpacityConverter : IValueConverter
{
public bool IsReverse { get; set; }
public object Convert(object value, Type targetType, object parameter, string language)
{
var state = (bool)value;
if (state)
{
return IsReverse ? 1 : 0.3;
}
return IsReverse ? 0.3 : 1;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
|
PHP
|
UTF-8
| 4,791
| 2.640625
| 3
|
[] |
no_license
|
<?php
/**
* Elementor Counter Widget.
*
* Elementor widget that inserts an embbedable content into the page, from any given URL.
*
* @since 1.0.0
*/
class Alesha_Counter_Widget extends \Elementor\Widget_Base {
/**
* Get widget name.
*
* Retrieve Counter widget name.
*
* @since 1.0.0
* @access public
*
* @return string Widget name.
*/
public function get_name() {
return 'Alesha Counter';
}
/**
* Get widget title.
*
* Retrieve Counter widget title.
*
* @since 1.0.0
* @access public
*
* @return string Widget title.
*/
public function get_title() {
return __( 'Atl Counter', 'atl-extension' );
}
/**
* Get widget icon.
*
* Retrieve Counter widget icon.
*
* @since 1.0.0
* @access public
*
* @return string Widget icon.
*/
public function get_icon() {
return 'eicon-number-field';
}
/**
* Get widget categories.
*
* Retrieve the list of categories the Counter widget belongs to.
*
* @since 1.0.0
* @access public
*
* @return array Widget categories.
*/
public function get_categories() {
return [ 'atl-category' ];
}
/**
* Register Counter widget controls.
*
* Adds different input fields to allow the user to change and customize the widget settings.
*
* @since 1.0.0
* @access protected
*/
protected function _register_controls() {
$this->start_controls_section(
'content_section',
[
'label' => __( 'Content', 'atl-extension' ),
'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
]
);
$repeater = new \Elementor\Repeater();
$repeater->add_control(
'counter_list_number', [
'label' => __( 'Counter List Number', 'atl-extension' ),
'type' => \Elementor\Controls_Manager::NUMBER,
'default' => __( '1000' , 'atl-extension' ),
'label_block' => true,
]
);
$repeater->add_control(
'counter_list_title', [
'label' => __( 'Counter List Title', 'atl-extension' ),
'type' => \Elementor\Controls_Manager::TEXT,
'default' => __( 'Project Finished' , 'atl-extension' ),
'label_block' => true,
]
);
$this->add_control(
'counter_lists',
[
'label' => __( 'Counters Lists', 'atl-extension' ),
'type' => \Elementor\Controls_Manager::REPEATER,
'fields' => $repeater->get_controls(),
'title_field' => '{{{ counter_list_title }}}',
]
);
$this->end_controls_section();
// Title & Description Style Tab
$this->start_controls_section(
'title_style_section',
[
'label' => __( 'Title & Description', 'atl-extension' ),
'tab' => \Elementor\Controls_Manager::TAB_STYLE,
]
);
// Title Options
$this->add_control(
'title_heading',
[
'label' => __( 'Title', 'atl-extension' ),
'type' => \Elementor\Controls_Manager::HEADING,
'separator' => 'before'
]
);
// Title Color
$this->add_control(
'title_color',
[
'label' => __( 'Color', 'atl-extension' ),
'type' => \Elementor\Controls_Manager::COLOR,
'scheme' => [
'type' => \Elementor\Core\Schemes\Color::get_type(),
'value' => \Elementor\Core\Schemes\Color::COLOR_1,
],
'default' => '#fff',
'selectors' => [
'{{WRAPPER}} .counter' => 'color: {{VALUE}}',
],
]
);
// Title Typography
$this->add_group_control(
\Elementor\Group_Control_Typography::get_type(),
[
'name' => 'title_typography',
'label' => __( 'Typography', 'atl-extension' ),
'scheme' => \Elementor\Core\Schemes\Typography::TYPOGRAPHY_1,
'selector' => '{{WRAPPER}} .counter .counter__title',
]
);
}
/**
* Render Counter widget output on the frontend.
*
* Written in PHP and used to generate the final HTML.
*
* @since 1.0.0
* @access protected
*/
protected function render() {
$settings = $this->get_settings_for_display();
?>
<section id="counter" class="counter">
<div class="container">
<div class="row row-cols-2 row-cols-md-4 g-4">
<?php
if ( $settings['counter_lists'] ) {
foreach ( $settings['counter_lists'] as $item ) {
?>
<div class="col">
<div class="counter__count"><?php echo $item['counter_list_number']; ?></div>
<div class="counter__title"><?php echo $item['counter_list_title']; ?></div>
</div>
<?php
}
}
?>
</div>
</div>
</section>
<?php
}
}
|
Java
|
UTF-8
| 737
| 2.8125
| 3
|
[] |
no_license
|
package com.chengxuxiaoba.video.model;
import java.util.HashMap;
import java.util.Map;
public class KeyValuePair<K, V> {
private Map<K, V> mapContainer = new HashMap<K, V>();
public KeyValuePair(){}
public KeyValuePair(K key, V value)
{
mapContainer.put(key, value);
}
public void put(K key, V value) {
mapContainer = new HashMap<K, V>();
mapContainer.put(key, value);
}
public void clear()
{
mapContainer.remove(getKey());
}
public K getKey() {
for (K key : mapContainer.keySet()) {
return key;
}
return null;
}
public V getValue() {
K key = getKey();
return mapContainer.get(key);
}
}
|
Java
|
UTF-8
| 1,873
| 2.265625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.study.fuli.data;
import com.study.fuli.data.remote.ApiUrl;
import com.study.fuli.data.remote.Utils;
import com.study.fuli.event.EventButtGirlGot;
import org.greenrobot.eventbus.EventBus;
import java.io.IOException;
import java.util.ArrayList;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by hsy on 2016/2/22.
*/
public class DataManager {
private static DataManager sInstance;
private OkHttpClient mOkHttpClient = new OkHttpClient();
private DataManager() {
}
public static DataManager getInstance() {
if (sInstance == null) {
synchronized (DataManager.class) {
if (sInstance == null) {
sInstance = new DataManager();
}
}
}
return sInstance;
}
public void getButtGirls(int page) {
final Request request = new Request.Builder().url(ApiUrl.DouBanButtGirlUrl + page).build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// just post an empty result
ArrayList<EventButtGirlGot> result = new ArrayList<EventButtGirlGot>();
EventBus.getDefault().post(result);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseContent = response.body().string();
ArrayList<String> buttGirlsUrls = Utils.parseWebPageImageUrl(responseContent);
EventButtGirlGot eventButtGirlGot = new EventButtGirlGot();
eventButtGirlGot.mPayload = buttGirlsUrls;
EventBus.getDefault().post(eventButtGirlGot);
}
});
}
}
|
Java
|
UTF-8
| 3,986
| 1.890625
| 2
|
[] |
no_license
|
package khttp.responses;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Iterator;
import kotlin.Metadata;
import kotlin.Unit;
import kotlin.jvm.internal.markers.KMappedMarker;
import org.jetbrains.annotations.NotNull;
@Metadata(bv = {1, 0, 0}, d1 = {"\u0000!\n\u0000\n\u0002\u0010(\n\u0002\u0010\u0012\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0010\u000b\n\u0002\b\u0002*\u0001\u0000\b\n\u0018\u00002\b\u0012\u0004\u0012\u00020\u00020\u0001B\u0005¢\u0006\u0002\u0010\u0003J\t\u0010\b\u001a\u00020\tH\u0002J\t\u0010\n\u001a\u00020\u0002H\u0002R\u0011\u0010\u0004\u001a\u00020\u0005¢\u0006\b\n\u0000\u001a\u0004\b\u0006\u0010\u0007¨\u0006\u000b"}, d2 = {"khttp/responses/GenericResponse$contentIterator$1", "", "", "(Lkhttp/responses/GenericResponse;I)V", "stream", "Ljava/io/InputStream;", "getStream", "()Ljava/io/InputStream;", "hasNext", "", "next", "khttp"}, k = 1, mv = {1, 1, 1})
/* compiled from: GenericResponse.kt */
public final class GenericResponse$contentIterator$1 implements Iterator<byte[]>, KMappedMarker {
final /* synthetic */ int $chunkSize;
@NotNull
private final InputStream stream;
final /* synthetic */ GenericResponse this$0;
public void remove() {
throw new UnsupportedOperationException("Mutating immutable collection");
}
GenericResponse$contentIterator$1(GenericResponse genericResponse, int i) {
this.this$0 = genericResponse;
this.$chunkSize = i;
genericResponse = genericResponse;
this.stream = genericResponse.getRequest().getStream() != 0 ? genericResponse.getRaw() : (InputStream) new ByteArrayInputStream(genericResponse.getContent());
}
@NotNull
public final InputStream getStream() {
return this.stream;
}
@NotNull
public byte[] next() {
byte[] bArr = new byte[Math.min(this.$chunkSize, this.stream.available())];
this.stream.read(bArr);
Unit unit = Unit.INSTANCE;
return bArr;
}
public boolean hasNext() {
/* JADX: method processing error */
/*
Error: java.lang.NullPointerException
at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.searchTryCatchDominators(ProcessTryCatchRegions.java:75)
at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.process(ProcessTryCatchRegions.java:45)
at jadx.core.dex.visitors.regions.RegionMakerVisitor.postProcessRegions(RegionMakerVisitor.java:63)
at jadx.core.dex.visitors.regions.RegionMakerVisitor.visit(RegionMakerVisitor.java:58)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:31)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:17)
at jadx.core.ProcessClass.process(ProcessClass.java:34)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:282)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200)
at jadx.api.JadxDecompiler$$Lambda$8/1603198149.run(Unknown Source)
*/
/*
r3 = this;
r0 = 0;
r1 = r3.this$0; Catch:{ IOException -> 0x001a }
r1 = r1.getRaw(); Catch:{ IOException -> 0x001a }
r1 = r1.available(); Catch:{ IOException -> 0x001a }
if (r1 <= 0) goto L_0x000f; Catch:{ IOException -> 0x001a }
L_0x000d:
r1 = 1; Catch:{ IOException -> 0x001a }
goto L_0x0010; Catch:{ IOException -> 0x001a }
L_0x000f:
r1 = 0; Catch:{ IOException -> 0x001a }
L_0x0010:
if (r1 != 0) goto L_0x0017; Catch:{ IOException -> 0x001a }
L_0x0012:
r2 = r3.stream; Catch:{ IOException -> 0x001a }
r2.close(); Catch:{ IOException -> 0x001a }
L_0x0017:
r2 = kotlin.Unit.INSTANCE; Catch:{ IOException -> 0x001a }
r0 = r1;
L_0x001a:
return r0;
*/
throw new UnsupportedOperationException("Method not decompiled: khttp.responses.GenericResponse$contentIterator$1.hasNext():boolean");
}
}
|
Markdown
|
UTF-8
| 1,280
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
---
title: "Ricetta pane con uvetta, semplice"
date: 2021-05-22 07:30:00 +0200
author: Stefano Marzorati
layout: post
image: 'https://marzorati.co/img/ricette.png'
share-img: 'https://marzorati.co/img/ricette.png'
categories: [Ricette]
tags: [ricetta, pane, uvetta, lievito, acqua, sale, farina]
---
**Quantitativo per fare un filoncino da 900 grammi**
<p align="center">
<img src="https://marzorati.co/img/post/pane_uvetta_1a.jpg">
</p>
***Ingredienti:***
* 400 grammi di farina 0
* 240 grammi di acqua
* 2 grammi di lievito di birra disidratato
* 8 grammi di sale
* 250 grammi di uvetta
* 20 grammi di burro
<p align="center">
<img src="https://marzorati.co/img/post/pane_uvetta_2a.jpg">
</p>
***Procedimento:***
* Metti in ammollo 250 grammi di uvetta per 15/30 minuti.
* In una ciotola metti **240 grammi di acqua** e sciogli **2 grammi di lievito di birra** disidratato.
* **Aggiungere la farina** e comincia ad impastare.
* Dopo 5 minuti inserisci nell'impasto gli 8 grammi di sale, i 25 grammi di burro, e i 250 grammi di uvetta.
* Coprire la ciotola con della pellicola trasparente e **lasciare lievitare** (almeno 6 ore).
* Infornare a **180°/190°C per circa 40 minuti**.
* **Lascia raffreddare** il pane a temperatura ambiente prima di tagliarlo.
|
Python
|
UTF-8
| 1,781
| 2.609375
| 3
|
[] |
no_license
|
class ResultManager:
def __init__(self, gen, syn, exo, syn_merger, hit_merger, hit_analyzer):
self.results = {g.name: Result(g) for g in gen.intervals()}
# merge in the synteny data
for result in self.results.values():
syn_merger.merge(result=result, syn=syn)
# merge in the exonerate hit data
for hit in exo.generator():
try:
hit_merger.merge(result=self.results[hit.name], hit=hit, syn=syn)
except KeyError:
err('The gene {} in the hit file is missing from the gff file' % hit.name)
# hit_analyzer.filter(self.results)
def get(self, name):
return self.results[name]
def write(self):
for r in self.results.values():
s = str(r)
if s:
print(s)
class Result:
'''
Stores all results and handles record output
'''
def __init__(self, gene):
self.name = gene.name
self.gene = gene
# --- variables set by SynMerger ---
# -------------------------------------------
self.is_present = False
self.is_simple = False
self.lower = None # the block downstream of the last homologous block
self.upper = None # the block upstream of the last homologous block
# --- variables set by HitMerger ---
# -------------------------------------------
# declaration of an interval containing the flanks around the gene
# in the query
self.query_flanks = None
self.total_hits = 0
self.hits = []
def __str__(self):
# out = '\t'.join((self.gene.name, str(self.is_present), str(self.is_simple)))
out = '\n'.join([str(h) for h in self.hits])
return(out)
|
JavaScript
|
UTF-8
| 917
| 2.765625
| 3
|
[] |
no_license
|
(function(){
let ajaxHelper = new AjaxHelper();
var code = document.querySelector("#code");
var name = document.querySelector("#name");
var update = false;
let create = async () =>{
var data = {
name: name.value
};
if(!update){
data.code = code.value;
var response = await ajaxHelper.postMethod("careers", data);
}
else{
data.id = code.value;
var response = await ajaxHelper.putMethod("careers", data);
}
window.location.href = "careerAdmin.html";
}
document.querySelector("#create").addEventListener("click", create);
var carrer = sessionStorage.getItem("carrer-selected");
if(carrer){
update = true;
code.disabled = true;
carrer = JSON.parse(carrer);
code.value = carrer.id;
name.value = carrer.name;
}
})();
|
TypeScript
|
UTF-8
| 3,147
| 2.640625
| 3
|
[] |
no_license
|
import { Injectable } from '@angular/core';
@Injectable()
export class CheatCodesService {
// Variables
cheatCodes= [
["ArrowUp", "ArrowUp", "ArrowDown", "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowLeft", "ArrowRight", "b", "a"],
["[", "]", "ArrowDown", "l", "2", "ArrowUp", "l", "1", "o", "ArrowUp", "x", "ArrowLeft"],
["ArrowUp", "b", "Escape"]
];
currCode= JSON.parse(localStorage.getItem("currCode")) || [];
appendKeyToCode(args:Event) {
// Variables
let key= args["key"] || "";
let found= false;
this.currCode[this.currCode.length]= key;
for(let i= 0; i< this.cheatCodes.length; i++) {
// Variables
let temp= this.cheatCodes[i].slice(0);
temp.splice(this.currCode.length);
// Finds a match and they are both the same size
if(this.arrayEquals(temp, this.currCode)) {
//console.log(JSON.stringify(temp));
if(this.cheatCodes[i].length=== this.currCode.length) {
this.performAction(i);
}
else {
found= true;
}
}
}
if(!found) this.currCode= [];
localStorage.setItem("currCode", JSON.stringify(this.currCode));
//localStorage.setItem("cheatCodes", JSON.stringify(this.cheatCodes));
}
arrayEquals(temp, curr) {
for(var i= 0; i< temp.length; i++) {
if(temp[i]!== curr[i])
return false;
}
return true;
}
performAction(index:Number) {
switch(index) {
case 0: {
// Variables
let x= document.getElementsByTagName("*");
for(let i= 0; i< x.length; i++) {
x[i].remove();
}
let b= document.createElement("body");
let q= [];
for(let i= 0; i< 4; i++) {
q[i]= document.createElement("img");
q[i].src= "assets/punished_kojima.gif";
b.appendChild(q[i]);
}
document.appendChild(b);
}break;
case 1: {
// Variables
let temp= document.createElement("div");
let cvs= document.createElement("canvas");
let scripts= [
document.createElement("script"),
document.createElement("script"),
document.createElement("script")
];
temp.id= "gx";
cvs.id= "cvs";
scripts[0].src= "assets/csmuga/csmuga.js";
scripts[1].src= "assets/timer.min.js";
scripts[2].innerHTML= "setTimeout(function(){carshmup.runGame();}, 500);";
temp.appendChild(cvs);
temp.appendChild(scripts[0]);
temp.appendChild(scripts[1]);
temp.appendChild(scripts[2]);
document.body.appendChild(temp);
}break;
case 2: {
// Variables
let temp= document.createElement("div");
let cvs= document.createElement("canvas");
let scripts= [
document.createElement("script"),
document.createElement("script"),
document.createElement("script")
];
temp.id= "gx";
cvs.id= "cvs";
scripts[0].src= "assets/pkds/pkds.js";
scripts[1].src= "assets/timer.min.js";
scripts[2].innerHTML= "setTimeout(function(){pkds.run();}, 500);";
temp.appendChild(cvs);
temp.appendChild(scripts[0]);
temp.appendChild(scripts[1]);
temp.appendChild(scripts[2]);
document.body.appendChild(temp);
//localStorage.clear(); // TODO: Appropriate?
}break;
}
}
}
|
C++
|
UTF-8
| 1,782
| 3.640625
| 4
|
[] |
no_license
|
#include <iostream>
using namespace std ;
#include "FormeS.hpp"
//Implantation de la classe FormeS
//Constructeur
//qui prend en paramètrela taille
FormeS::FormeS(size_t taille)
:maxformes(taille), nbformes(0), formes(nullptr) //liste d'initialisation
{ formes = new Forme * [maxformes] ; } //On crée le tableau
//Destructeur
FormeS::~FormeS()
{ for(size_t i = 0 ; i < nbformes ; i++)
delete formes[i] ; //On vide le tableau
delete [] formes ; //On supprime le tableau
}
void FormeS::ajouter(Forme * forme)
{
if (nbformes+1 > maxformes)
throw std::runtime_error("Trop de formes") ; //Erreur: le tableau est plein
formes[nbformes++] = forme ; //le pointeur sur Forme passé en paramètre est ajouté dans le tableau
}
void FormeS::dessiner(EZWindow & win) const
{ for(size_t i = 0 ; i < nbformes ; ++i)
formes[i] -> dessiner(win) ; //On dessine dans la fenêtre les formes présentent dans le tableau
}
Forme * FormeS::isOver(uint x, uint y)
{
for(size_t i = 0 ; i < nbformes ; ++i)
if (formes[i] -> isOver(x, y))
return formes[i] ;
return nullptr ;
}
ostream & operator<<(ostream & os, FormeS formes)
{ os << formes ; return os ; }
void FormeS::charger(istream & is)
{
for(size_t i = 0 ; i<nbformes ; i++)
delete formes[i] ; //On vide le tableau
nbformes = 0 ; //On ré-initialise le nombre de forme
size_t num ;
is >> num ;
if (num <= maxformes)
for(size_t i = 0 ; i < num ; i++)
ajouter(formes[i]->Forme::charger(is)) ; //On ajoute les nouvelles formes dans le tableau
else
throw runtime_error("Trop de formes") ;
}
void FormeS::sauver(ostream & os)
{
os << nbformes << endl;
for(size_t i=0; i<nbformes; i++){
formes[i]->ecrire(os); //Ecrit dans le flux les formes présentent dans le tableau
os << endl;
}
}
|
PHP
|
UTF-8
| 3,998
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace OneSite\Notifier\Services;
use GuzzleHttp\Client;
use OneSite\Notifier\Contracts\NotificationInterface;
/**
* Class FirebaseService
* @package OneSite\Notifier\Services
*/
class FirebaseService implements NotificationInterface
{
/**
* @var Client
*/
private $client;
/**
* @var string
*/
private $fcmUrl = "https://fcm.googleapis.com/fcm";
/**
* @var string
*/
private $iidUrl = "https://iid.googleapis.com/iid";
/**
* @var null
*/
private $apiKey = null;
/**
* Firebase constructor.
*/
public function __construct()
{
$this->client = new Client();
$this->apiKey = config('notifier.fcm.api_key');
}
/**
* @return null
*/
public function getApiKey()
{
return $this->apiKey;
}
/**
* @param null $apiKey
*/
public function setApiKey($apiKey)
{
$this->apiKey = $apiKey;
}
/**
* @param $to
* @param $data
* @param array $options
* @return mixed|\Psr\Http\Message\ResponseInterface
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function send($to, $data, $options = [])
{
$body = [
'content-available' => true,
'priority' => 'HIGH'
];
if (!empty($options['is_ios'])) {
$body['notification'] = $data;
} else {
$body['notification'] = $data;
$body['data'] = $data;
}
if (is_array($to)) {
$body['registration_ids'] = $to;
} else {
$body['to'] = $to;
}
return $this->client->request('POST', $this->fcmUrl . "/send", [
'http_errors' => false,
'verify' => false,
'headers' => [
"Authorization" => "key=" . $this->getApiKey(),
"Content-Type" => "application/json"
],
'body' => json_encode($body)
]);
}
/**
* @param $topic
* @param array $devices
* @return \Psr\Http\Message\ResponseInterface
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function createTopic($topic, $devices = [])
{
return $this->client->request('POST', $this->iidUrl . "/v1:batchAdd", [
'http_errors' => false,
'verify' => false,
'headers' => [
"Authorization" => "key=" . $this->getApiKey(),
"Content-Type" => "application/json"
],
'body' => json_encode([
'to' => $topic,
'registration_tokens' => $devices
])
]);
}
/**
* @param $deviceId
* @return \Psr\Http\Message\ResponseInterface
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function getTopics($deviceId)
{
return $this->client->request('GET', $this->iidUrl . '/info/' . $deviceId, [
'http_errors' => false,
'verify' => false,
'headers' => [
"Authorization" => "key=" . $this->getApiKey(),
"Content-Type" => "application/json"
],
'query' => [
'details' => true
]
]);
}
/**
* @param $topic
* @param array $devices
* @return \Psr\Http\Message\ResponseInterface
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function removeTopic($topic, $devices = [])
{
return $this->client->request('POST', $this->iidUrl . "/v1:batchRemove", [
'http_errors' => false,
'verify' => false,
'headers' => [
"Authorization" => "key=" . $this->getApiKey(),
"Content-Type" => "application/json"
],
'body' => json_encode([
'to' => $topic,
'registration_tokens' => $devices
])
]);
}
}
|
Java
|
UTF-8
| 4,479
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package edu.stanford.nlp.sempre;
import java.util.*;
import fig.basic.*;
/**
* Similar to LexiconFn, but list all approximate matches from a FuzzyMatchable instance.
*
* @author ppasupat
*/
public class FuzzyMatchFn extends SemanticFn {
public static class Options {
@Option public int verbose = 0;
}
public static Options opts = new Options();
public enum FuzzyMatchFnMode { UNARY, BINARY, ENTITY,
ORDER_BEFORE, ORDER_AFTER, ORDER_NEXT, ORDER_PREV, ORDER_ADJACENT };
private FuzzyMatchFnMode mode;
// Generate all possible denotations regardless of the phrase
private boolean matchAny = false;
public void init(LispTree tree) {
super.init(tree);
for (int i = 1; i < tree.children.size(); i++) {
String value = tree.child(i).value;
if ("unary".equals(value)) this.mode = FuzzyMatchFnMode.UNARY;
else if ("binary".equals(value)) this.mode = FuzzyMatchFnMode.BINARY;
else if ("entity".equals(value)) this.mode = FuzzyMatchFnMode.ENTITY;
else if ("any".equals(value)) this.matchAny = true;
else if ("before".equals(value)) this.mode = FuzzyMatchFnMode.ORDER_BEFORE;
else if ("after".equals(value)) this.mode = FuzzyMatchFnMode.ORDER_AFTER;
else if ("next".equals(value)) this.mode = FuzzyMatchFnMode.ORDER_NEXT;
else if ("prev".equals(value)) this.mode = FuzzyMatchFnMode.ORDER_PREV;
else if ("adjacent".equals(value)) this.mode = FuzzyMatchFnMode.ORDER_ADJACENT;
else throw new RuntimeException("Invalid argument: " + value);
}
}
public FuzzyMatchFnMode getMode() { return mode; }
public boolean getMatchAny() { return matchAny; }
@Override
public DerivationStream call(Example ex, Callable c) {
return new LazyFuzzyMatchFnDerivs(ex, c, mode, matchAny);
}
// ============================================================
// Derivation Stream
// ============================================================
public static class LazyFuzzyMatchFnDerivs extends MultipleDerivationStream {
final Example ex;
final FuzzyMatchable matchable;
final Callable c;
final String query;
final List<String> sentence;
final FuzzyMatchFnMode mode;
final boolean matchAny;
int index = 0;
List<Formula> formulas;
public LazyFuzzyMatchFnDerivs(Example ex, Callable c, FuzzyMatchFnMode mode, boolean matchAny) {
this.ex = ex;
if (ex.context != null && ex.context.graph != null && ex.context.graph instanceof FuzzyMatchable)
this.matchable = (FuzzyMatchable) ex.context.graph;
else
this.matchable = null;
this.c = c;
this.query = (matchAny || c.getChildren().isEmpty()) ? null : c.childStringValue(0);
if (c.getRule().rhs.size() == 1 && Rule.phraseCat.equals(c.getRule().rhs.get(0))) {
sentence = ex.getTokens();
} else if (c.getRule().rhs.size() == 1 && Rule.lemmaPhraseCat.equals(c.getRule().rhs.get(0))) {
sentence = ex.getLemmaTokens();
} else {
sentence = null;
}
this.mode = mode;
this.matchAny = matchAny;
if (opts.verbose >= 2)
LogInfo.logs("FuzzyMatchFn[%s]%s.call: %s",
this.mode, (this.matchAny ? "[matchAny]" : ""), this.query);
}
@Override
public Derivation createDerivation() {
if (matchable == null) return null;
if (query == null && !matchAny) return null;
// Compute the formulas if not computed yet
if (formulas == null) {
if (matchAny)
formulas = new ArrayList<>(matchable.getAllFormulas(mode));
else if (sentence != null)
formulas = new ArrayList<>(matchable.getFuzzyMatchedFormulas(sentence, c.getStart(), c.getEnd(), mode));
else
formulas = new ArrayList<>(matchable.getFuzzyMatchedFormulas(query, mode));
}
// Use the next formula to create a derivation
if (index >= formulas.size()) return null;
Formula formula = formulas.get(index++);
SemType type = TypeInference.inferType(formula);
FeatureVector features = new FeatureVector();
if (FeatureExtractor.containsDomain("fuzzyMatch")) {
features.add("fuzzyMatch", "mode=" + mode);
if (matchAny)
features.add("fuzzyMatch", "mode=" + mode + "_any");
}
return new Derivation.Builder()
.withCallable(c)
.formula(formula)
.type(type)
.localFeatureVector(features)
.createDerivation();
}
}
}
|
JavaScript
|
UTF-8
| 1,668
| 2.5625
| 3
|
[] |
no_license
|
import React, { Component } from 'react';
import './App.css';
import AppNavbar from './AppNavbar';
import { Table } from 'reactstrap';
class Movies extends Component {
constructor(props){
super(props);
this.state = {
isLoading: true,
movies: [],
testmovie: []
};
}
async componentDidMount() {
const movieres = await fetch('http://www.omdbapi.com/?i=tt3896198&apikey=30042119');
const response = await fetch('/movies');
const moviebod = await movieres.json();
console.log(moviebod)
const body = await response.json();
console.log();
this.setState({ movies: body, isLoading: false, testmovie:moviebod});
}
render() {
const {movies, isLoading,testmovie} = this.state;
if (isLoading) {
return <p>Loading...</p>;
}
return (
<div> <AppNavbar/>
<div className="App">
<header className="App-header">
<div className="App-intro">
<h2>Movies</h2>
<Table>
<thead className= "Movies-table">
<tr>
<th>Title</th>
<th>Rating</th>
</tr>
</thead>
<tbody className= "Movies-table">
{movies.map(movie =>
<tr key={movie.id}>
<td>{movie.name}</td>
<td>{movie.rating}</td>
</tr>
)}
<tr>
<td>{testmovie.Title}</td>
<td>{testmovie.Ratings[0].Value}</td>
</tr>
</tbody>
</Table>
</div>
</header>
</div>
</div>
);
}
}
export default Movies;
|
Python
|
UTF-8
| 642
| 3.875
| 4
|
[] |
no_license
|
# converting to str method
# class Solution(object):
# def isPalindrome(self, x):
# x = str(x)
# rev = x[::-1]
# return x == rev
# without converting to str
class Solution(object):
def isPalindrome(self, x):
if x < 0:
return False
x_copy = x
rev = 0
while x > 0:
rev = rev * 10 + x % 10
x = x // 10
return rev == x_copy
solution = Solution()
print(solution.isPalindrome(1111))
print(solution.isPalindrome(-121))
print(solution.isPalindrome(10))
print(solution.isPalindrome(-101))
print(solution.isPalindrome(-101))
|
PHP
|
UTF-8
| 368
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
<?php namespace App\Models;
use CodeIgniter\Model;
class SettingsEmailTemplate extends Model
{
protected $table = 'settings_email_template';
protected $primaryKey = 'id';
protected $useSoftDeletes = false;
protected $returnType = "object";
protected $allowedFields = ["title","subject","email_body"];
protected $useTimestamps = true;
}
|
Ruby
|
UTF-8
| 44
| 2.5625
| 3
|
[] |
no_license
|
n = gets.to_i
puts (10000 + n * 10000) / 2
|
C++
|
UTF-8
| 648
| 2.640625
| 3
|
[] |
no_license
|
#include "Pir.h"
void Pir::begin(uint8_t _pin, Buzzer* buzzer, PubSubClient* client)
{
pin = _pin;
this->buzzer = buzzer;
this->client = client;
pinMode(pin, INPUT);
}
void Pir::loop(){
val = get();
Serial.println("val Pir: ");
Serial.println(val);
if(val == HIGH){
if(pirState == LOW){
Serial.println("PIR: Presencia detectada!");
pirState = HIGH;
client->publish("server/espino", "PIR Detection");
buzzer->set(true);
}
}else{
if(pirState == HIGH){
Serial.println("PIR: Se ha detenido la presencia!");
pirState = LOW;
}
}
}
bool Pir::get()
{
return digitalRead(pin);
}
|
C++
|
UTF-8
| 9,098
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
/*
* helper_functions.h
* Some helper functions for the path planning project.
* Created on: Nov 25, 2018
* Author: Michael Berner
*/
#ifndef HELPER_FUNCTIONS_H_
#define HELPER_FUNCTIONS_H_
#include <math.h>
#include <fstream>
#include <vector>
#include <iostream>
#include <string>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "json.hpp"
// #include <uWS/uWS.h>
// #include <thread>
// #include "spline.h"
using namespace std;
// for portability of M_PI (Vis Studio, MinGW, etc.)
#ifndef M_PI
const double M_PI = 3.14159265358979323846;
#endif //M_PI
// For converting back and forth between radians and degrees.
constexpr double pi() {
return M_PI;
}
double deg2rad(double x) {
return x * pi() / 180;
}
double rad2deg(double x) {
return x * 180 / pi();
}
// Signum function
template <typename T> int signum(T val) {
return (T(0) < val) - (val < T(0));
}
// Calculate distance between two x,y coordinates
double distance(double x1, double y1, double x2, double y2)
{
return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
// Calculate closest waypoint to x,y coordinate
int ClosestWaypoint(double x, double y, const vector<double> &maps_x, const vector<double> &maps_y)
{
double closestLen = 100000; //large number
int closestWaypoint = 0;
for(int i = 0; i < maps_x.size(); i++)
{
double map_x = maps_x[i];
double map_y = maps_y[i];
double dist = distance(x,y,map_x,map_y);
if(dist < closestLen)
{
closestLen = dist;
closestWaypoint = i;
}
}
return closestWaypoint;
}
// Provide next waypoint
int NextWaypoint(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
{
int closestWaypoint = ClosestWaypoint(x,y,maps_x,maps_y);
double map_x = maps_x[closestWaypoint];
double map_y = maps_y[closestWaypoint];
double heading = atan2((map_y-y),(map_x-x));
double angle = fabs(theta-heading);
angle = min(2*pi() - angle, angle);
if(angle > pi()/2)
{
closestWaypoint++;
if (closestWaypoint == maps_x.size())
{
closestWaypoint = 0;
}
}
return closestWaypoint;
}
// Provide next waypoint based on s coordinate
int PrevWaypoint_s(double s, const vector<double> &maps_s)
{
int prev_wp = -1;
// wrap around end of list
while(s > maps_s[prev_wp+1] && (prev_wp < (int)(maps_s.size()-1) ))
{
prev_wp++;
}
// return value
return prev_wp;
}
// Provide next waypoint based on s coordinate
int NextWaypoint_s(double s, const vector<double> &maps_s)
{
int prev_wp = PrevWaypoint_s(s, maps_s);
// calculate next waypoint: wrap-around at end of array
int next_wp = (prev_wp+1)%maps_s.size();
// return value
return next_wp;
}
// Transform from Cartesian x,y coordinates to Frenet s,d coordinates
vector<double> getFrenet(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
{
// Get previous and next waypoint
int next_wp = NextWaypoint(x,y, theta, maps_x,maps_y);
int prev_wp;
prev_wp = next_wp-1;
if(next_wp == 0)
{
prev_wp = maps_x.size()-1;
}
// Prepare variables
double n_x = maps_x[next_wp]-maps_x[prev_wp];
double n_y = maps_y[next_wp]-maps_y[prev_wp];
double x_x = x - maps_x[prev_wp];
double x_y = y - maps_y[prev_wp];
// find the projection of x onto n
double proj_norm = (x_x*n_x+x_y*n_y)/(n_x*n_x+n_y*n_y);
double proj_x = proj_norm*n_x;
double proj_y = proj_norm*n_y;
// calculate Frenet d value (lateral distance)
double frenet_d = distance(x_x,x_y,proj_x,proj_y);
// correct sign of d value: comparing it to a center point
double center_x = 1000-maps_x[prev_wp];
double center_y = 2000-maps_y[prev_wp];
double centerToPos = distance(center_x,center_y,x_x,x_y);
double centerToRef = distance(center_x,center_y,proj_x,proj_y);
if(centerToPos <= centerToRef)
{
frenet_d *= -1;
}
// calculate Frenet s value
double frenet_s = 0;
for(int i = 0; i < prev_wp; i++)
{
frenet_s += distance(maps_x[i],maps_y[i],maps_x[i+1],maps_y[i+1]);
}
frenet_s += distance(0,0,proj_x,proj_y);
// return Frenet s and d values
return {frenet_s,frenet_d};
}
// Transform from Frenet s,d coordinates to Cartesian x,y
vector<double> getXY(double s, double d,
tk::spline &s_x, tk::spline &s_y, tk::spline &s_dx, tk::spline &s_dy)
{
// Get interpolated x,y,dx,dy values from spline by referencing s-value
double path_x = s_x(s);
double path_y = s_y(s);
double dx = s_dx(s);
double dy = s_dy(s);
// Calculate final x,y pair by taking lateral displacement d into account
double x = path_x + d*dx;
double y = path_y + d*dy;
return {x,y};
}
// Calculate optimal lane line to pick
vector<double> getBestLane(vector<double>& cars_s_d, vector<double>& cars_d, vector<double>& cars_v_d)
{
// Initialize lane score with a high number
vector<double> lane_score;
int best_lane = 0;
double best_score = -9999.;
for (int j=0; j<3; j++){
lane_score.push_back(10000.);
}
if (cars_s_d.size() > 0) {
double horizon_max = 150.; // meters
double horizon_min = -20.; // meters
// Loop through all cars
for(int j = 0; j < cars_s_d.size(); j++) {
// Check if vehicle is within horizon
if ((cars_s_d[j] < horizon_max) && (cars_s_d[j] > horizon_min)) {
// Check which lane the vehicle is within
for (int lane = 0; lane < 3; lane++) {
// Is vehicle within current lane? If not, move on.
if ((cars_d[j] > lane*4) && (cars_d[j] <= (lane+1)*4)) {
// Calculate score. Optimization took place with www.desmos.com, see hyperlink
// https://www.desmos.com/calculator/7qhdrupbli - Formula j(x,v)
// Formula is rather complicated, but makes sure, that slower vehicles ahead and faster
// vehicles behind get punished. Vice versa, faster vehicles ahead and slower vehicles
// behind score higher. Highest score is achieved for an empty lane within horizon.
double dv = cars_v_d[j];
double ds = cars_s_d[j];
// double score = a * ds + b * dv*signum(ds) + c * exp(d * ds*ds);
double score = 0.1*ds+0.8*dv*signum(ds)-1000*exp(-0.04*ds*ds);
// Add offset for vehicles behind (negative delta_s values)
if (ds < 0) { score += 7.; } // variable e_0 in desmos
// Reduce score to lowest value within lane
lane_score[lane] = min(lane_score[lane],score);
}
}
}
}
for (int lane = 0; lane < 3; lane++) {
cout << "Lane " << lane << ": ";
for (int j = 0; j < cars_s_d.size(); j++) {
if ((cars_d[j] > lane*4) && (cars_d[j] <= (lane+1)*4)) {
printf(" | %i: dv=%2.0f,ds=%4.0f",j,cars_v_d[j],cars_s_d[j]);
}
}
cout << " || Lane score = " << lane_score[lane] << endl;
if (lane_score[lane] > best_score) {
best_score = lane_score[lane];
best_lane = lane;
}
}
}
return lane_score;
}
// Calculate optimal lane line to pick
vector<bool> getLaneFeasibility(vector<double>& cars_s_d, vector<double>& cars_d, vector<double>& cars_v_d)
{
// Initialize lane score with a high number
vector<double> lane_score;
int best_lane = 0;
double best_score = -9999.;
for (int j=0; j<3; j++){
lane_score.push_back(10000.);
}
if (cars_s_d.size() > 0) {
double horizon_max = 40.; // meters
double horizon_min = -20.; // meters
// Loop through all cars
for(int j = 0; j < cars_s_d.size(); j++) {
// Check if vehicle is within horizon
if ((cars_s_d[j] < horizon_max) && (cars_s_d[j] > horizon_min)) {
// Check which lane the vehicle is within
for (int lane = 0; lane < 3; lane++) {
// Is vehicle within current lane? If not, move on.
if ((cars_d[j] > lane*4) && (cars_d[j] <= (lane+1)*4)) {
// Calculate score. Optimization took place with www.desmos.com, see hyperlink
// https://www.desmos.com/calculator/7qhdrupbli - Formula j(x,v)
// Formula is rather complicated, but makes sure, that slower vehicles ahead and faster
// vehicles behind get punished. Vice versa, faster vehicles ahead and slower vehicles
// behind score higher. Highest score is achieved for an empty lane within horizon.
double dv = cars_v_d[j];
double ds = cars_s_d[j];
// double score = a * ds + b * dv*signum(ds) + c * exp(d * ds*ds);
double score = 0.15*ds+0.5*dv*signum(ds)-1000*exp(-0.04*ds*ds);
// Add offset for vehicles behind (negative delta_s values)
if (ds < 0) { score += 7.; } // variable e_0 in desmos
// Reduce score to lowest value within lane
lane_score[lane] = min(lane_score[lane],score);
}
}
}
}
}
// Create boolean output vector
vector<bool> lane_feasibility(3);
for (int lane = 0; lane < 3; lane++) {
if (lane_score[lane] > 0) {
lane_feasibility[lane] = true;
}
else {
lane_feasibility[lane] = false;
}
}
return lane_feasibility;
}
#endif /* HELPER_FUNCTIONS_H_ */
|
JavaScript
|
UTF-8
| 3,359
| 2.703125
| 3
|
[] |
no_license
|
if (!window.superskill) window.superskill = {};
if (!window.superskill.loader) window.superskill.loader = {};
// TODO: this.loading keeps parent-child references after load completes. Remove them to save memory
window.superskill.loader = new function() {
this.base = "things/";
this.loading = {}; // TODO: Rename to queuedItems
this.queuedScenes = {};
// Loads the scene and calls the callback with the loaded model. Returns true if loading is complete, and false if in progress
this.load = function(scene, callback) {
if (!this.queuedScenes[scene]) {
this.queuedScenes[scene] = { item: scene, loading: true };
console.log("Fetching data for scene", scene);
$.get(this.base + scene).done(function(data) {
var model = jsyaml.safeLoad(data);
let expandedModel = this.expandItem(model, {});
var tracker = function() {
var keys = Object.keys(this.loading);
for (var k in keys) {
if (this.loading[keys[k]].loading) {
window.setTimeout(tracker, 1000);
return;
}
}
this.queuedScenes[scene].item = expandedModel;
this.queuedScenes[scene].loading = false;
if (callback) callback(expandedModel);
}.bind(this);
tracker();
}.bind(this));
return false;
} else if (!this.queuedScenes[scene].loading) {
if (callback) callback(this.queuedScenes[scene].item);
return true;
} else {
return false;
}
}.bind(this);
this.expandItem = function(item, parts) {
let itemParts = { ...item.parts, ...parts };
let expandedItem = this.placeParts(item, itemParts);
if (expandedItem.item) {
this.fetchItem(expandedItem.item, expandedItem, itemParts);
} else if (expandedItem.items) {
let expandedItems = [];
for (var i in expandedItem.items) {
expandedItems.push(this.expandItem(expandedItem.items[i], itemParts));
}
expandedItem.items = expandedItems;
}
return expandedItem;
}.bind(this);
this.placeParts = function(item, parts) {
let newItem = {};
var keys = Object.keys(item);
for (var k in keys) {
var key = keys[k];
var value = item[key];
if (parts[value]) {
newItem[key] = parts[value];
} else {
newItem[key] = value;
}
}
return newItem;
};
this.fetchItem = function(item, parent, parts) {
if (!this.loading[item]) {
this.loading[item] = { item: item, loading: true, parents: [ { parent: parent, parts: parts } ] };
let itemParts = parts;
console.log("Fetching data for item", item);
$.get(this.base + item).done(function(data) {
var model = jsyaml.safeLoad(data);
var parents = this.loading[item].parents;
for (var p in parents) {
parents[p].parent.items = this.expandItem(model, parents[p].parts).items;
}
this.loading[item] = model;
}.bind(this));
} else if (this.loading[item].loading) {
this.loading[item].parents.push({ parent: parent, parts: parts });
} else {
parent.items = this.expandItem(this.loading[item], parts).items;
}
}.bind(this);
return this;
}();
|
PHP
|
UTF-8
| 2,200
| 2.75
| 3
|
[] |
no_license
|
<?php
/**
* User: haier
*/
namespace Home\Service;
class AdminService extends CommonService{
/**
* 管理员登录认证
* @param array $admin 管理员信息
* @return array
*/
public function login($admin) {
$Admin = $this->getM();
// 邮箱是否存在
if (!$this->existAccount($admin['email'])) {
return $this->errorResultReturn('账号不存在!');
}
$account = $Admin->getByEmail($admin['email']);
// 密码验证
if ($account['password'] != $admin['password']) {
return $this->errorResultReturn('密码不正确!');
}
// 是否启用
if (!$this->isActive($admin['email'])) {
return $this->errorResultReturn('账户已被禁用!');
}
$loginMarked = C('LOGIN_MARKED');
$shell = $this->genShell($account['id'], $account['password']);
// 生成登录session
$_SESSION[$loginMarked] = $shell;
// 生成登录cookie
$shell .= '_' . time();
setcookie($loginMarked, $shell, 0, '/');
$_SESSION['current_account'] = $account;
return $this->resultReturn(true,date('Y-m-d H:i:s', time()));
}
/**
* 账户是否启用
* @param string $email email
* @return boolean
*/
public function isActive($email) {
$where = array(
'email' => $email,
'is_active' => 1
);
if ($this->getM()->where($where)->count() > 0) {
return true;
}
return false;
}
/**
* 是否存在帐号
* @param string $email email
* @return boolean
*/
public function existAccount($email) {
if ($this->getM()->where("email='{$email}'")->count() > 0) {
return true;
}
return false;
}
/**
* 生成登录shell
* @param int $id shell的id
* @param string $password shell的密码
* @return string
*/
private function genShell($id, $password) {
return md5($password . C('AUTH_TOKEN')) . $id;
}
protected function getModelName() {
return 'Admin';
}
}
|
SQL
|
UTF-8
| 353
| 2.96875
| 3
|
[] |
no_license
|
-- Add NL search to topics table
ALTER TABLE topics
ADD COLUMN search_vector tsvector;
CREATE INDEX topics_search_index
ON topics
USING gin(search_vector);
CREATE TRIGGER topics_search_update BEFORE
UPDATE OR INSERT ON topics
FOR EACH ROW
EXECUTE PROCEDURE tsvector_update_trigger("search_vector", "pg_catalog.english", "text", "title");
|
Ruby
|
UTF-8
| 221
| 3.0625
| 3
|
[] |
no_license
|
threes = 0
fives = 0
fifteens = 0
sum = 0
while threes < 999 do
threes += 3
sum += threes
end
while fives < 995 do
fives += 5
sum += fives
end
while fifteens < 990 do
fifteens += 15
sum -= fifteens
end
puts sum
|
Markdown
|
UTF-8
| 19,536
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|

**todoist-shortcuts** is a browser extension or greasemonkey script which adds a
bunch of keyboard shortcuts to [Todoist](https://todoist.com). Along with this
repository, it is also available from the following places:
* [ Extension for Google Chrome

](https://chrome.google.com/webstore/detail/todoist-shortcuts/dehmghpdcahlffompjagejmgbcfahndp)
* [ Extension for Mozilla Firefox


](https://addons.mozilla.org/en-US/firefox/addon/todoist-shortcuts/)
These keyboard shortcuts are directly inspired by the shortcuts used for GMail,
which, in turn were inspired by vim-like keyboard interaction. I highly
recommend enabling the advanced keyboard shortcuts if you use GMail.
So, if the choices of keypresses seem strange, stick with it! Many of
the keypresses used here can also be used in GMail or even vim (or,
better yet, [evil-mode] ;) ).
[evil-mode]: https://github.com/emacs-evil/evil
# Keyboard shortcuts guide sheet
[**See this printable shortcuts guide**][google-sheet], created by
[kimaero] (see [#71]). This guide can also be brought up while using
Todoist by pressing `?`.
[google-sheet]: https://docs.google.com/spreadsheets/d/1AGh85HlDze19bWpCa2OTErv9xc7grmMOMRV9S2OS7Xk
[kimaero]: https://github.com/kimaero
[#71]: https://github.com/mgsloan/todoist-shortcuts/issues/71
# Keyboard shortcut details
## Add tasks
| keys | action |
|------|----------------------------------------|
| `q` | Add task |
| `a` | Add new task at the bottom of the list |
| `A` | Add new task at the top of the list |
See the "Task Quick Add shortcuts" section of [todoist's keyboard shortcuts
documentation](https://support.todoist.com/hc/en-us/articles/205063212) for
information about shorthands to use when adding tasks. "Adding or editing
tasks" is also a good section to read, which includes keyboard shortcuts not
described in this document.
## Navigation
| keys | action |
|----------------|-----------------------------------------------------------------------|
| `j` or `down` | move cursor down |
| `k` or `up` | move cursor up |
| `h` or `left` | collapse nested at cursor |
| `l` or `right` | expand nested at cursor |
| `^` | move cursor to first task |
| `$` | move cursor to last task |
| `{` | move cursor up to first section task |
| `}` | move cursor down to next section |
| `/` or `f` | focus search input |
| `g` | enter section navigation mode |
| `shift+g` | navigate to task's project, or select in agenda if already on project |
| `` ` `` | select the next left nav section |
| `~` | select the previous left nav section |
In "section navigation mode", the different selections in the left
pane are annotated with the keys to press to navigate to that
section. Sometimes the sidebar can have more than a screenful of
content. While in this mode, you can scroll the left pane down and up
with `space` and `shift+space`. For smaller scrolling jumps, you can
also use up arrow and down arrow.
When projects have sub-projects, they are automatically expanded when the
project is selected from the list. To collapse the sub-projects, just use
navigation mode to select the same project again.
## Manipulation of tasks at cursor
| keys | action |
|----------------------------|----------------------------------------------------------|
| `enter` | edit task at cursor |
| `o` | add task after cursor |
| `shift+o` | add task before cursor |
| `i` | open task side panel (see [side panel section][], below) |
| `c` | open comments for task at cursor |
| `shift+r` | open reminders for task at cursor |
| `+` | open assign dialog for task at cursor |
| `shift+j` or `shift+down` | move task at cursor downwards |
| `shift+k` or `shift+up` | move task at cursor upwards |
| `shift+l` or `shift+left` | dedent task at cursor |
| `shift+h` or `shift+right` | indent task at cursor |
| `shift+c` | clicks [toggl][] or [clockify][] time tracking button |
| `ctrl+c` | copy title and url of task(s) in markdown format |
| `ctrl+,` | copy task title(s) |
| `ctrl+shift+,` | copy task url(s) |
Note that there are some known bugs related to task motion - see
[#27](https://github.com/mgsloan/todoist-shortcuts/issues/27) and
[#29](https://github.com/mgsloan/todoist-shortcuts/issues/29).
`shift+c` clicking of time tracking buttons supports both the
[toggl-button extension][toggl] and [clockify extension][clockify].
[toggl]: https://toggl.com/toggl-button/
[clockify]: https://chrome.google.com/webstore/detail/clockify-time-tracker/pmjeegjhjdlccodhacdgbgfagbpmccpe
[side panel section]: #task-side-panel
## Selection
| keys | action |
|--------------------------|-----------------------------------------------|
| `x` | add task at cursor to selection |
| `* a` | select all tasks |
| `* n` or `escape` | clear selection |
| `* s` | add all tasks in current section to selection |
| `* o` | add all tasks in overdue section to selection |
| `* 1` | add all priority 1 tasks to selection |
| `* 2` | add all priority 2 tasks to selection |
| `* 3` | add all priority 3 tasks to selection |
| `* 4` or `* 0` | add all priority 4 tasks to selection |
| `* h` or `* left-arrow` | collapses all tasks |
| `* l` or `* right-arrow` | expands all tasks |
## Manipulation of selected items
If none are selected, then these will apply to the cursor instead.
| keys | action |
|------------|-----------------------------------|
| `t` | schedule |
| `T` | schedule by editing text |
| `alt+t` | open time-of-day scheduler |
| `d` | done: mark task as complete |
| `e` or `#` | delete |
| `&` | duplicate |
| `v` | move to project via search prompt |
| `@` or `y` | open label dialog |
| `1` | set priority to 1 |
| `2` | set priority to 2 |
| `3` | set priority to 3 |
| `4` or `0` | set priority to 4 |
Deleting a task via `e` or `#` is fairly similar to marking it
complete via `d`. Here are the differences:
1. Deleting a child task (nested under another task), it will be
removed from the list. Completing a child task will mark it
complete, but it will stay in the list.
2. Deleting a Recurring Task (e.g. every day) will cause the task to
no longer be scheduled.
## Scheduling
When scheduling is opened via `t`, the following keybindings will apply:
| keys | date |
|-------------------------|-------------------------------------------|
| `c` | today (mnemonic is "current day") |
| `t` | tomorrow |
| `w` | next week |
| `p` or `s` | postpone (recurring tasks) |
| `r` | remove |
| `backspace` or `delete` | clear and focus text date entry |
| `enter` | focus text date entry without clearing it |
| `alt+t` | open time of day scheduler |
| `escape` | exit scheduling |
The "Smart Scheduler" is opened by pressing `s` when scheduling
multiple items. Currently there are only two keybindings for the smart
scheduler: `enter` to apply the choices, and `escape` to cancel.
## Sorting
When viewing the inbox or a project, the following keybindings can be used to
sort the tasks:
| keys | sorted by |
|------|------------------|
| `s` | Sort by date |
| `p` | Sort by priority |
| `r` | Sort by assignee |
| `n` | Sort by name |
## Bulk reschedule mode
| keys | action |
|----------------|--------------------------------------|
| `* t` | enter bulk reschedule mode |
| `v` or `alt+v` | switch to bulk move mode (see below) |
| `escape` | exit bulk reschedule mode |
Once bulk reschedule mode is entered, it will repeatedly bring up the reschedule
dialog until there are no more tasks after the cursor. All of the normal cursor
navigation keys can be used while in this mode.
## Bulk move mode
| keys | action |
|----------|--------------------------------------------|
| `* v` | enter bulk move mode |
| `alt+t` | switch to bulk reschedule mode (see above) |
| `escape` | exit bulk move mode |
Once bulk move mode is entered, it will repeatedly bring up the move-to-project
dialog until there are no more tasks after the cursor. By holding down `alt`,
you can use the normal cursor navigation keys in this mode.
## Task view
NOTE: Some shortcuts may only work in the english translation, as the
DOM structure chosen by Todoist for this part of the UI has obfuscated
IDs.
The task side panel can be opened for the task under the cursor by
pressing `i`. Once the side panel is visible, you can use the
following shortcuts:
| keys | action |
|-----------------|----------------------------|
| `i` or `escape` | close the task side panel |
| `h` | navigate to parent task |
| `j` | navigate to next task |
| `k` | navigate to previous task |
The rest of the bindings match the shortcuts used in other contexts.
Listed here for completeness:
| keys | action |
|-------------------|---------------------------------------------------------------------------|
| `d` | done: mark task as complete |
| `q` or `a` or `A` | add a subtask |
| `t` | schedule |
| `v` | move to project via search prompt |
| `y` or `@` | open label dialog |
| `1` | set priority to 1 |
| `2` | set priority to 2 |
| `3` | set priority to 3 |
| `4` or `0` | set priority to 4 |
| `shift+r` | open reminders |
| `+` | open assignee dialog |
| `e` | archive |
| `#` | delete |
| `shift+c` | clicks [toggl-button (time tracking integration extension)][toggl-button] |
## Menus
| keys | action |
|------------------------|--------------------------------------------------------|
| `w` | open 'more actions' menu for current view |
| `shift+p` | open left nav menu for current project |
Once a menu is open, the following shortcuts can be used to interact with it:
| keys | action |
|----------------------------|--------------------------|
| `j` or `down` or `tab` | focus next menu item |
| `k` or `up` or `shift+tab` | focus previous menu item |
| `enter` or `space` | select current menu item |
## Other
| keys | action |
|------------------------|--------------------------------------------------------|
| `u` or `z` or `ctrl+z` | undo |
| `f` or `/` | open search |
| `shift+enter` | clicks first link in the task the cursor is on |
| `ctrl+s` | manually synchronize state with server |
| `?` | display [keyboard shortcuts guide sheet](google-sheet) |
| `!` | open notifications |
| `ctrl+k` | open Todoist command pallette |
| `ctrl+shift+/` | open random task from current view |
Note that undo only works when the "UNDO" button is visible at the bottom of the
screen. Some actions are not undo-able, such as [deletion or archiving multiple
tasks](https://github.com/mgsloan/todoist-shortcuts/issues/23)
# How to customize keyboard shortcuts
Ideally, there would be a UI for customizing keyboard shortcuts. However, it
seems like this would take a substantial amount of development effort
(PR contributions appreciated!). For now, you can do the following to customize
the keyboard shortcuts in Chrome:
1. Clone this repository (run `git clone https://github.com/mgsloan/todoist-shortcuts`)
2. Go to `chrome://extensions` in the url bar, and switch from the official
version of todoist-shortcuts to a local version.
- Disable the official version of todoist-shortcuts by unchecking "Enabled".
- Click the "Developer mode" box in the top right if it is not yet checked.
- Click the "Load unpacked extension..." button. In the directory selecter
navigate to the folder you cloned todoist-shortcuts to, and point it at the
`src` sub-directory.
2. Edit `src/todoist-shortcuts.js` in a text editor.
- You will probably just want to edit the definition of KEY_BINDINGS near the
top.
- To disable a keybinding, put `//` in front of it.
- The functions in the section marked `Actions` are intended to be bound
directly to keys. You can also combine multiple actions via use of the
`sequence` and `ifThenElse` action combiners.
- Multiple key sequences can be bound to the same action by using a list of
key sequences (like `['j', 'down']`) instead of a single string for it.
The docs for [mousetrap](https://craig.is/killing/mice) may be helpful in
figuring out how to express key sequences.
3. Use `ctrl+r` on `chrome://extensions`. This causes the extension to be
reloaded from your local files.
4. If you reload Todoist, you will now be using your modified version of the
extension.
I'm sure there is a similar mechanism for Firefox, but I do not use it for
developing the extension, so not sure of the details.
One thing to note is that you will no longer receive automated updates. To
update your locally modified extension, do the following:
1. `git stash` to store your changes.
2. `git pull` to fetch the most recent changes in this repository.
3. `git stash apply` to bring back your changes. This may cause merge conflicts.
See the git documentation. A miscellaneous aside is that I highly recommend
[git from the bottom up](https://jwiegley.github.io/git-from-the-bottom-up/) as
a guide to understanding git's data model.
# Extra functionality only available via manual editing
There are some extra functions that can be used to define your own
keybindings:
* `navigateToLeftMenuItem` selects a specific section from the left
menu. See [#239][].
* `moveToProjectNamed` moves the current selected tasks to a specific
project. See [#237][].
[#237]: https://github.com/mgsloan/todoist-shortcuts/issues/237
[#239]: https://github.com/mgsloan/todoist-shortcuts/issues/239
# `todoist-shortcuts` in [electron] application
This repository provides browser extentions for both Chrome and Firefox, and
therefore augments the browser's web client of Todoist. If you wanted the
`todoist-shortcuts` in the standalone Todoist desktop application it is not as
easy/straight-forward. The following article and associated repository outline
how you can achieve such a solution:
- https://kevinjalbert.com/todoist-with-keyboard-navigation-via-nativefier/
- https://github.com/kevinjalbert/todoist-shortcuts-nativefier
An alternative approach, suggested [here][#62], is to use [google
chrome's "open as window"
functionality](https://www.howtogeek.com/403399/how-to-make-chrome-open-as-window-shortcuts-now-that-google-killed-them/).
[electron]: https://electronjs.org/
[#62]: https://github.com/mgsloan/todoist-shortcuts/issues/62
# Development
Contributions are appreciated. See [development.md](./development.md) for more
information about development.
# Supported by bounty from Doist company
Much of the work on this has been kindly supported by Amir Salihefendic of Doist
company. They're awesome!
In response to a ["Need a way of buying beer"][] issue, I've created a
"Buy Me a Coffee" account. If you feel the urge to show some
appreciation for this project, feel free to send me a few dollars. If
not, that's fine too, I hope you enjoy using todoist-shortcuts :)
["Need a way of buying beer"]: https://github.com/mgsloan/todoist-shortcuts/issues/45
<a href="https://www.buymeacoffee.com/mgsloan" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: auto !important;width: auto !important;" ></a>
|
JavaScript
|
UTF-8
| 544
| 4.09375
| 4
|
[] |
no_license
|
//example 1
var colors = [ 'red', 'blue' , 'green' ,'pink'];
for(var i = 0; i <colors.length; i++){
console.log(colors)
}
colors.forEach(function(value){
console.log(value);
});
//example 2
var numbers = [ 1,2,3,4,5]
var sum = 0;
function adder(number){
sum += number;
}
numbers.forEach(adder);
sum;
//example 3
var images = [
{ height: 10, width: 30 },
{ height: 20, width: 90 },
{ height: 54, width: 32 }
];
var areas = [];
images.forEach(function(image){
areas.push(image.height * image.width);
})
|
JavaScript
|
UTF-8
| 774
| 3.03125
| 3
|
[] |
no_license
|
//document.addEventListener('DOMContentLoaded', check)
function check(){
//var btn = document.querySelector('#registerButton');
//btn.addEventListener('click', valid8);
//function valid8(){
var usernameInput = document.querySelector('#user');
var errdiv = document.querySelector("#error");
if (usernameInput === null){
errdiv.innerHTML = "<br/>Maybe fill in yr name there, ol' buddy ol' pal?";
//btn.preventDefault();
return false;
}
else{
username = usernameInput.value;
//console.log(username==="");
if (username === null || username=== "" || username === " "){
errdiv.innerHTML = "<br/>Maybe fill in yr name there, ol' buddy ol' pal?";
//btn.preventDefault();
return false;
}
}
return true;
//}
}
|
PHP
|
UTF-8
| 566
| 2.8125
| 3
|
[] |
no_license
|
<?php
$dsn = sprintf("%s:%s",$database['type'],$database['host']);
try {
$conn = new PDO($dsn);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
function hsql_query($conn,$sql , $params = array()) {
$sql = preg_replace("/\?/","__DATA__",$sql);
foreach( $params as $p) {
$p = preg_replace("/'/","'",$p);
$sql = preg_replace("/__DATA__/","'$p'",$sql,1);
}
return $conn->query($sql);
}
function hsql_fetch_data($res) {
return $res->fetch( PDO::FETCH_ASSOC);
}
?>
|
C#
|
UTF-8
| 2,972
| 3.15625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Password_Manager
{
class sql
{
private SqlConnection conn;
//ServerConnection Server = new ServerConnection();
public sql()
{
conn = new SqlConnection("Data Source=DESKTOP-6DB6D8B;Initial Catalog=passwordManager;Integrated Security=True");
}
public void AddUser(string username,string password)
{
string yourSql = "SELECT Username FROM UserTbl WHERE Username = @Username";
SqlCommand cmd1 = new SqlCommand(yourSql, conn);
cmd1.Parameters.AddWithValue("@Username", username);
conn.Open();
var rezult = cmd1.ExecuteScalar();
conn.Close();
if (rezult != null)
{
throw new Exception("This username alrady exists , sry plz try new one");
}
else
{
string mySQL = string.Empty;
mySQL += "INSERT INTO UserTbl (Username, Password)";
mySQL += "VALUES (@Username,@Password)";
SqlCommand cmd = new SqlCommand(mySQL, conn);
cmd.Parameters.AddWithValue("@Username", username);
cmd.Parameters.AddWithValue("@Password", password);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
throw new Exception("You have created an account successfully");
}
}
public void login(string Username, string Password)
{
if (!string.IsNullOrEmpty(Username) &&
!string.IsNullOrEmpty(Password))
{
string mySQL = string.Empty;
//get info from data base
mySQL += "SELECT * FROM UserTbl ";
mySQL += "WHERE Username = @Username";
mySQL += " AND password = @password";
SqlCommand cmd = new SqlCommand(mySQL, conn);
cmd.Parameters.AddWithValue("@Username", Username);
cmd.Parameters.AddWithValue("@password", Password);
conn.Open();
cmd.ExecuteNonQuery();
DataTable userData = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(userData);
conn.Close();
if (userData.Rows.Count > 0)
{
return;
}
else
{
throw new Exception("The username or password is in correct. Try again");
}
}
else
{
throw new Exception("Please Enter your data");
}
}
}
}
|
Shell
|
UTF-8
| 86,874
| 3.21875
| 3
|
[] |
no_license
|
#!/bin/bash
declare -i PIDscript=$!
declare -a argumentosEntrada=$@
# Nombre: global
# Descripción: Es el bloque de código que alberga todas las variables globales
# ¿Por qué usar una función global?
# No hay mucho beneficio más allá del estético, poder minimazar el bloque de código de global (200 líneas aprox)
# mejora muchísimo la navegabilidad del código.
# Todas las funciones que quieran usar variables de global tienen que ser llamdas desde: GLOBAL...
# Date: Pues no lo sé
global(){
#Colores de texto -> Los asignamos ahora porque hay variables globales que los utilizan
#ejemplo: echo -e "${B_RED}texto en rojo negrita${GREEN}texto en verde${NC}"
declare -a coloresLetras
declare -r DEFAULT='\e[39m' #Color por defecto
declare -r BLACK='\e[30m'
declare -r RED='\e[31m'
declare -r GREEN='\e[32m'
declare -r YELLOW='\e[33m'
declare -r BLUE='\e[34m'
declare -r MAGENTA='\e[35m'
declare -r CYAN='\e[36m'
declare -r L_GRAY='\e[36m' #Gris claro
declare -r D_GRAY='\e[90m' #Gris oscuro
declare -r L_RED='\e[91m' #Rojo claro
declare -r L_GREEN='\e[92m' #Verde claro
declare -r L_YELLOW='\e[93m' #Amarillo claro
declare -r L_BLUE='\e[94m' #Azul claro
declare -r L_MAGENTA='\e[95m' #Magenta claro
declare -r L_CYAN='\e[96m' #Cyan claro
declare -r WHITE='\e[97m'
coloresLetras=("$RED" "$GREEN" "$YELLOW" "$BLUE" "$MAGENTA" "$CYAN")
#Colores en negrita
declare -r BOLD='\e[1;39m'
declare -r B_BLACK='\e[1;30m'
declare -r B_RED='\e[1;31m'
declare -r B_GREEN='\e[1;32m'
declare -r B_YELLOW='\e[1;33m'
declare -r B_BLUE='\e[1;34m'
declare -r B_MAGENTA='\e[1;35m'
declare -r B_CYAN='\e[1;36m'
declare -r B_L_GRAY='\e[1;36m' #Gris claro
declare -r B_D_GRAY='\e[1;90m' #Gris oscuro
declare -r B_L_RED='\e[1;91m' #Rojo claro
declare -r B_L_GREEN='\e[1;92m' #Verde claro
declare -r B_L_YELLOW='\e[1;93m' #Amarillo claro
declare -r B_L_BLUE='\e[1;94m' #Azul claro
declare -r B_L_MAGENTA='\e[1;95m' #Magenta claro
declare -r B_L_CYAN='\e[1;96m' #Cyan claro
declare -r B_WHITE='\e[1;97m'
#Fin de color
declare -r NC='\e[0m'
#Colores de FONDO:
declare -a coloresFondo
declare -r _DEFAULT='\e[49m' #Color por defecto
declare -r _BLACK='\e[40m'
declare -r _RED='\e[41m'
declare -r _GREEN='\e[42m'
declare -r _YELLOW='\e[43m'
declare -r _BLUE='\e[44m'
declare -r _MAGENTA='\e[45m'
declare -r _CYAN='\e[46m'
declare -r _L_GRAY='\e[47m' #Gris claro
declare -r _D_GRAY='\e[100m' #Gris oscuro
declare -r _L_RED='\e[101m' #Rojo claro
declare -r _L_GREEN='\e[102m' #Verde claro
declare -r _L_YELLOW='\e[103m' #Amarillo claro
declare -r _L_BLUE='\e[104m' #Azul claro
declare -r _L_MAGENTA='\e[105m' #Magenta claro
declare -r _L_CYAN='\e[106m' #Cyan claro
declare -r _WHITE='\e[107m'
coloresFondo=("$_RED" "$_GREEN" "$_YELLOW" "$_BLUE" "$_MAGENTA" "$_CYAN")
# VARIABLES GLOBALES
# Variable que almacena el estado del apropiativo (s/n) -> introducido por teclado o fichero
#
declare opcionApropiativo
#
# Variable que almacena la opción de estático/dinámico / sin implementar.
#
declare opcionEstatico
#Array con la cola | Empieza en 1, por lo que el valor 0 siempre se podrá saltar
#(nota alumno 2020: Lo arrays empiezan siempre en 0, pero paso de cambiarlo, ten en cuenta que la mayoría de los arrays de esta práctica empiezan en 1, además igual en bash da problemas)
declare -a cola
# Constante:
# Numúmero de columnas -> Número de columnas que hay en la carga de archivos
declare -r numCol=5
# Número de procesos introducido / a ser ejecutados
#
declare -i numProc=0
# Índice que almacena el proceso que está ejécutándose en CPU
# Se ajusta sólo durante la entrada de datos
declare -i procesoCPU=0
# Prioridades: Almacenan la prioridad mínima y máxima, introducidos durante la entrada.
#
declare -i priorMin
declare -i priorMax
# String que almacena el tipo de prioridad -gt o -lt -> ya que la p.Máx puede ser un número más pequeño qpe p.Min
# Modificado en establecerPrioridad()
declare tipoPrioridad
# Tamaño de la cola ordena con los procesos que han entrado al sistema y están esperando para entrar a memoria.
#
declare -i tamCola=0
# Tamaño de la memoria que vamos a usar durante la ejecución, se introduce en la entrada,
#
declare tamMemoria
# Entero que almacena la memoria libre, varía con la introucción o el borrado de procesos de memoria
#
declare memoriaLibre
# Array que almacena por cada posición ( de 0 a infinito ) el número correspondiente al proceso que se encuentra en dicho intervalo en CPU.
# Se usa para dibujar más adelante la barra de CPU/tiempo
declare -a lineaEstadoCPU
# Memoria según necesidades es el array bidimensional en el que se almacenará la información de la memoria.
# El array tiene DOS capas ($MEM_INDICE que es la capa 0) y (MEM_TOSTRING que es la capa 1)
# El array tiene M huecos, cada hueco corresponde a una posición de memoria. Las posiciones empiezan en 1
# Ejemplo de acceso/mod array para asignar un proceso:
# memoriaSegunNecesidades[1,0]==memoriaSegunNecesidades[1,$MEM_INDICE]=8 -> en la pos 1 hay una unidad de mem del proceso 8
# Es necesario asignar el string a imprimir
# memoriaSegunNecesidades[1,$MEM_TOSTRING]=${FondoRojo}$MEM_STRING_HUECOSINCOLOR${FondoNeutro}
# Como se puede observar, asignamos el color, y el string que queremos imprimir, en nuestro caso dicho string lo tenemos como variable global,
# para que al modificar el string, se cambien todas las asignaciones (comodidad)
#
declare -A memoriaSegunNecesidades
#Capa donde se guardaran los índices/Apuntadores/punteros de el proceso que se encuentra en cada posición de memoria respecto a la tabla de $procesos[]
declare -r MEM_INDICE=0
#Capa donde se almacena el texto a imprimir
declare -r MEM_TOSTRING=1
# Declares de los contenidos por defecto de la MEMORIA -> igual se podría poner un 0, pero no lo he probado, y funciona bien de momento.
declare -r MEM_HUECO_VACIO="null"
# Strings de memoria que se imprimirán
# Hueco vacío, se imprimen unos corchetes blancos con fondo blanco
declare -r MEM_STRING_HUECO_VACIO="$_WHITE${WHITE}[ ]${_DEFAULT}"
# Hueco con proceso: Se imrprimen unos corchetes con gorritos, es necesario colorearlos.
declare -r MEM_STRING_HUECOSINCOLOR="[^]" #Se colorea con el color del proceso
#Tabla PROCESOS:
declare -A procesos
declare -a cabeceraProcesos=("PID" "Ref" "TLl" "TEj" "Pri" "Mem" "Trej" "Tesp" "Tret" "Estado" "Color Fondo" "Color Letras" "DirI" "DirF")
#Valores de la estructura/struc (El array bidimensional procesos)
#//@see procesos
#Los siguientes valores (1-9) son las posiciones del struct existentes a las versiones previas a 2020
declare -r P_NOMBRE=1 # $P_NOMBRE
declare -r P_TLLEGADA=2 # $P_TLLEGADA
declare -r P_TEJECUCION=3 # $P_TEJECUCION
declare -r P_PRIORIDAD=4 # $P_PRIORIDAD
declare -r P_TAMANIO=5 # $P_TAMANIO
declare -r P_TRESTANTE=6 # $P_TRESTANTE
declare -r P_TESPERA=7 # $P_TESPERA
declare -r P_TRETORNO=8 # $P_TRETORNO -> Tespera + Tejecución = Tfinal – Tllegada
declare -r P_ESTADO=9 # $P_ESTADO
#Valores 2020:
declare -r P_COLOR=10 #Color del Fondo
declare -r P_COLORLETRA=11 #Colod de las letras
declare -r P_POSINI=12 #Posición de inicio en la memoria
declare -r P_POSFIN=13 #Posición donde termina el proceso en la memoria
#Strings de estados/STATUS (Valores a asignar a P_ESTADO)
declare -r STAT_MEMO="En Memoria"
declare -r STAT_ENCPU="En Ejecución"
declare -r STAT_COLA="En Espera"
declare -r STAT_FIN="Terminado"
declare -r STAT_SISTEMA="Fuera del Sistema"
declare -r STAT_APROP_PAUSA="En Pausa" #Estado cuando un proceso es extraido de la CPU (En el modo apropiativo)
#Ficheros y directorios:
declare -r DATA_DIRECTORY="Datos/"
declare -r LOG_DIRECTORY="Informes/"
declare -r INFORME_FILENAME="${LOG_DIRECTORY}informePrioridadMayor.ANSI"
declare -r INFORMEBN_FILENAME="${LOG_DIRECTORY}informePrioridadMayorBN.txt"
#DEBUG (Variables globales):
# Son variables utilizadas en las funciones debug(), controlan el flujo de dichas funciones
declare -r DEFAULT_DEBUG_OUTPUT_FILE_NAME="debug.txt"
declare -r DEBUG_ENABLE=true
declare DEBUG_FIRST_EXECUTION=true
declare -r DEBUG_PERSISTENT_FILE=false
# Variable de control de BREAKPOINTS
# utilizados en breakpoints(), perfectos para el desarrollo del programa.
declare -r BREAKPOINT_ENABLED=true
declare -r BREAKPOINT_AUTO=false
declare -r BREAKPOINT_AUTO_TIMEOUT="0.5"
#
# Llamadas a funcioones de GLOBAL:
#
creacionDeDirectorios
main | tee "$INFORME_FILENAME" #Por la naturaleza de bash, si llamamos desde una función a otra, las variables de la primera función son accesibles desde la segunda
#Si llamamos a main desde global, podemos tener el GLOBAL como una función, y mantener sus funciones como globales
finMain
}
# _____ _ _ ____ _
# | ____|_ __ | |_ _ __ __ _ __| | __ _ _ _ / ___|__ _| |__ ___ ___ ___ _ __ __ _
# | _| | '_ \| __| '__/ _` |/ _` |/ _` | | | | | | | / _` | '_ \ / _ \/ __/ _ \ '__/ _` |
# | |___| | | | |_| | | (_| | (_| | (_| | | |_| | | |__| (_| | |_) | __/ (_| __/ | | (_| |
# |_____|_| |_|\__|_| \__,_|\__,_|\__,_| \__, | \____\__,_|_.__/ \___|\___\___|_| \__,_|
# |___/
# Nombre: scanfSiNo
# Descripcion: asigna un valor valido a una variable desde el teclado
# @param $1: texto a imprimir en pantalla para pedir si o no
# @param $2: variable al que se asigna si o no
scanfSiNo() {
local opcionSiNo
imprimirLCyan "$1" -n
read -r opcionSiNo
until [[ $opcionSiNo = s || $opcionSiNo = n || $opcionSiNo = S || $opcionSiNo = N ]]; do
imprimirAviso "El valor '$opcionSiNo' introducido no válido, tiene que ser 's' o 'n'. Vuelve a intentarlo."
imprimirLCyan "$1" -n
read -r opcionSiNo
done
eval ${2}=$opcionSiNo #asignamos la opcionSiNo valida al variable $2 pasado como parametro
}
# Nombre: scanfNum
# Descripcion: asigna un valor mayor que un numero pasado como parametro a una variable desde el teclado
# @param $1: texto a imprimir en pantalla para pedir
# @param $2: variable al que se asigna el numero valido
# @param $3: numero minimo valido
scanfNum(){
local opcionN
imprimirLCyan "$1" -n
read -r opcionN
#$opcionN -eq $opcionN comprueba si es un numero, si es una letra da error enviado al vacio
until [ $opcionN -eq $opcionN -a $opcionN -ge $3 ] 2>/dev/null; do
imprimirAviso "El valor '$opcionN' introducido no válido, tiene que ser mayor que $3."
imprimirLCyan "$1" -n
read -r opcionN
done
eval ${2}=$opcionN
}
# Nombre: esEntero
# Descripción: Comprueba si el parámetro $1 es entero, y lanza un "true" al stdout
# @param $1: Número a comprobar
# return: "true o false" por un echo, hay que capturalo
esEntero(){
if [[ "$1" =~ ^[0-9]+$ ]]; then
echo "true"
else
echo "false"
fi
}
# Nombre: scanfNumMinMax
# Descripcion: asigna un valor entre un rango de numeros desde el teclado
# @param $1: texto a imprimir para pedir el numero
# @param $2: variable al que se asigna el numero valido
# @param $3: numero mínimo del rango (incluido)
# @param $4: numero máximo del rango (incluido)
scanfNumMinMax(){
local opcionN
local numMinimo=$3
local numMaximo=$4
#si el numMinimo es mas grande que numMaximo intercambia las variables
if [[ "$numMinimo" -gt "$numMaximo" ]]; then
numMinimo=$4
numMaximo=$3
fi
imprimirLCyan "$1" -n
read -r opcionN
until [ $opcionN -eq $opcionN -a $opcionN -le $numMaximo -a $opcionN -ge $numMinimo ] 2>/dev/null; do
imprimirAviso "El valor '$opcionN' introducido no válido, intervalo válido [ $numMinimo, $numMaximo ]."
imprimirLCyan "$1" -n
read -r opcionN
done
eval ${2}=$opcionN
}
# Nombre: scanfString
# Descripcion: asigna un valor cadena de caracteres a una variable pasado como parametro
# @param $1: texto a imprimir para pedir la cadena de caracteres
# @param $2: variable al que se asigna la cadena valida
scanfString(){
local opcionNombre
local -i palabra
imprimirLCyan "$1" -n
read -r opcionNombre
palabra=`echo $opcionNombre | wc -w`
while [ $palabra -ne 1 ]; do #comprueba si está vacío o tiene un espacio
imprimirAviso "No puede ser vacío ni tener espacios."
imprimirLCyan "$1" -n
read -r opcionNombre
palabra=`echo $opcionNombre | wc -w`
done
eval ${2}=$opcionNombre
}
# Nombre: numAleatorio
# Descripcion: genera un numero aleatorio de un rango de dos numeros pasado como parametro
# @param $1: variable a asignar el número aleatorio
# @param $2: número mmáximo del rango incluido
# @param $3: número máximo del rango incluido
numAleatorio(){
local num
local numMinimo=$2
local numMaximo=$3
if [ $numMinimo -gt $numMaximo ]; then
numMinimo=$3
numMaximo=$2
fi
num=$(( $RANDOM % ($numMaximo+1-$numMinimo) + $numMinimo ))
eval ${1}=$num
}
# Nombre: comprobarRango
# Descripcion: comprueba número se encuentra dentro de un rango de dos números,
# si no se encuetra dentro llama a scanfNumMinMax para modificarlo
# @param $1: el texto que se imprime en caso de que el número no se encuentre dentro del rango o no sea un número
# @param $2: el número a comprobar si encuentra dentro del rango
# @param $3: variable a modificar si el numero no se encuentra dentro del rango
# @param $4: numero mínimo del rango incluido
# @param $5: numero máximo del rango incluido
comprobarRango(){
local numMinimo=$4
local numMaximo=$5
if [[ "$numMinimo" -gt "$numMaximo" ]]; then
numMinimo=$5
numMaximo=$4
fi
if ! [ $2 -eq $2 -a $2 -ge $numMinimo -a $2 -le $numMaximo ] 2>/dev/null; then
scanfNumMinMax "$1" $3 $numMinimo $numMaximo
fi
}
# Nombre: comprobarRepite
# Descripcion: comprueba el nombre del proceso se esta repitiendo
# @param $1: posicion del proceso del array procesos
comprobarRepite(){
local -i i
local boolean=1
for (( i=1; i<=numProc&&boolean==1; i++)) do
if [ ${procesos[$i,$P_NOMBRE]} = ${procesos[$1,$P_NOMBRE]} -a $i -ne $1 ] 2>/dev/null; then
boolean=0
scanfString "El nombre del proceso ${procesos[$1,$P_NOMBRE]} ya existe. Introduce otro nombre: " procesos[$1,$P_NOMBRE]
comprobarRepite $1
fi
done
}
# Nombre: comprobarSN
# Descripcion: comprueba si un número es un s o un n. Solo se usa en datos por fichero
# @param $1: el texto a imprimir en pantalla en caso de valor no válido
# @param $2: valor de la variable a comprobar
# @param $3: variable a modificar en caso de valor no válido
comprobarSN(){
if ! [[ $2 = "s" || $2 = "n" || $2 = "S" || $2 = "N" ]]; then
scanfSiNo "$1" "$3"
fi
}
# Nombre: imprimirCabecera
# Descripción: Imprime la cabecera del programa
# Date: 7/03/2020
imprimirCabecera(){
clear
echo -e "\e[0;36m ╔══════════════════════════════════════════════════════════╗\e[0m"
echo -e "\e[0;36m ║\e[0m Creative Commons \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m BY - Atribución (BY) \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m NC - No uso Comercial (NC) \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m SA - Compartir Igual (SA) \e[0;36m║\e[0m"
echo -e "\e[0;36m ╚══════════════════════════════════════════════════════════╝\e[0m\n"
echo -e "\e[0;36m ╔═══════════════════════════════════════════════════════════════════════════════╗\e[0m"
echo -e "\e[0;36m ║\e[0m \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m Algoritmo de Prioridad Mayor \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m Memoria Según Necesidades: Contínua y Reubicable \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m Base: Omar Santos Bernabé (Pri. Men. - Part. Fijas e Iguales) \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m Alumnos 2016-2017: \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m Xing Long Ji - Yi Peng Ji \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m Alumno 2019-2020: \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m Jorge Ruiz Gómez \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m Asignatura: Sistemas Operativos \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m Curso 2019-2020 \e[0;36m║\e[0m"
echo -e "\e[0;36m ║\e[0m \e[0;36m║\e[0m"
echo -e "\e[0;36m ╚═══════════════════════════════════════════════════════════════════════════════╝\e[0m\n"
}
# Nombre: menuAlgoritmo
# Descripcion: menu para elegir las opciones del algoritmo, más info en la opcion 5 Ayuda (glosario)
menuAlgoritmo(){
local -i i
local opcion
clear
echo -e "\n ${L_YELLOW}╔════════════════════════════════════════════╗
║${NC}${B_BLUE} ¿Como quieres el algoritmo? ${NC}${L_YELLOW}║
║ ║
║${NC} 1-Estándar ${L_YELLOW}║
║${NC} 2-Apropiativo ${L_YELLOW}║
║${NC} 5-Ayuda (glosario) ${L_YELLOW}║
║${NC} 6-Salir del programa ${L_YELLOW}║
║ ║
╚════════════════════════════════════════════╝${NC}\n"
scanfNumMinMax "Elige opción: " opcion 1 7
case $opcion in
1) opcionApropiativo="n"
opcionEstatico="s";;
2) opcionApropiativo="s"
opcionEstatico="s";;
3) opcionApropiativo="n"
opcionEstatico="n";;
4) opcionApropiativo="s"
opcionEstatico="n";;
5) clear
echo -e "\n ${L_YELLOW}╔═════════════════════════════════════════════════════════════════════════════════╗
║ ║
║${NC}${B_L_GREEN} Apropiativo:${NC} El proceso que se está ejecutando puede ser expulsado ${L_YELLOW}║
║${NC} de la CPU cuando haya otro proceso con menor prioridad en la memoria. ${L_YELLOW}║
║ ║
║${NC}${B_L_GREEN} No apropiativo:${NC} El proceso que se está ejecutando no puede ser ${L_YELLOW}║
║${NC} expulsado de la memoria, solo sale cuando termina su tiempo de ejecución. ${L_YELLOW}║
║ ║
╚═════════════════════════════════════════════════════════════════════════════════╝${NC}\n"
#║${NC}${B_L_GREEN} Estático:${NC} La prioridad de los procesos en memoria no disminuyen ${L_YELLOW}║
#║${NC} a lo largo de la ejecución de los procesos. ${L_YELLOW}║
#║ ║
#║${NC}${B_L_GREEN} Dinámico:${NC} La prioridad de los procesos en memoria disminuyen ${L_YELLOW} ║
#║${NC} a lo largo de la ejecución de los procesos. En este script se ${L_YELLOW}║
#║${NC} disminuirá (prioridad Menor) en uno al finalizar la ejecución de un proceso. ${L_YELLOW}║
#║${NC} En caso contrario aumentará al finalizar la ejecución de un proceso. ${L_YELLOW}║
#║ ║
imprimirLCyan "Pulse [Intro] para salir de la ayuda" -n
read -ers
menuAlgoritmo;;
6) fin_programa;;
esac
}
# Nombre cargaDatos
# Descripcion: muestra las opciones de inicio del programa si los datos es por fichero, teclado o automáticos
cargaDatos(){
local -i opcionUsuario
local masProc="s"
local -i i
echo -e " ${L_YELLOW}╔════════════════════════════════════╗
║${NC}${B_BLUE}¿Como quieres introducir los datos? ${NC}${L_YELLOW}║
║ ║
║${NC} 1-Por teclado ${L_YELLOW}║
║${NC} 2-Por fichero ${L_YELLOW}║
║${NC} 3-Datos automáticos ${L_YELLOW}║
║${NC} 4-Salir del programa ${L_YELLOW}║
║ ║
╚════════════════════════════════════╝${NC}\n"
scanfNumMinMax "Elige opción: " opcionUsuario 1 4
case $opcionUsuario in
1)
menuAlgoritmo
clear
imprimirLCyan "Has elegido Apropiativo: $opcionApropiativo"
#imprimirLCyan "Has elegido Apropiativo: $opcionApropiativo y Estatico: $opcionEstatico"
scanfNum "¿Tamaño de la memoria?: " tamMemoria 1
scanfNumMinMax "¿Prioridad mínima?" priorMin -10000 10000
scanfNumMinMax "¿Prioridad máxima?" priorMax -10000 10000
establecerPrioridad
while [ $masProc = "s" ]; do
((numProc++))
datosManualProcesos $numProc
scanfSiNo "¿Quieres meter mas procesos? [s/n]:" masProc
done
;;
2)
datosFichero
;;
3)
menuAlgoritmo
datosAleatorios
;;
4)
fin_programa
;;
esac
}
# Nombre: establecerPrioridad
# Descripcion: establece el tipo de prioridad considerando priorMin y priorMax. El valor se usara para comparar en la ejecución
# Globales: tipoPrioridad
establecerPrioridad(){
#si priorMin es un número más pequeño que priorMax el tipo de prioridad es menor
if [ $priorMin -le $priorMax ]; then
tipoPrioridad="-lt"
else #si priorMin es un número más grande que priorMax el tipo de prioridad es técnicamente mayor
tipoPrioridad="-gt"
fi
}
# Nombre: datosManualProcesos
# Descripcion: el usuario rellena los datos de cada proceso por teclado: nombre, t.llegada, t.ejecución, prioridad y tamaño
# @param $1: índice del proceso dentro del array procesos
datosManualProcesos(){
local seguro
local -i j
clear
asignarColorProceso "$1" "$1"
if [[ $1 -lt 10 ]]; then
procesos[$1,$P_NOMBRE]="P0$1"
else
procesos[$1,$P_NOMBRE]="P$1"
fi
clear
imprimirTabla 1 2 3 4 5
scanfNum "¿Tiempo de llegada del proceso $1?: " procesos[$1,$P_TLLEGADA] 0
clear
imprimirTabla 1 2 3 4 5
scanfNum "¿Tiempo de ejecución del proceso $1?: " procesos[$1,$P_TEJECUCION] 1
clear
imprimirTabla 1 2 3 4 5
scanfNumMinMax "¿Prioridad del proceso $1?: " procesos[$1,$P_PRIORIDAD] $priorMin $priorMax
clear
imprimirTabla 1 2 3 4 5
scanfNumMinMax "¿Tamaño del proceso $1? (Menor o igual del tamaño de memoria [$tamMemoria] ): " procesos[$1,$P_TAMANIO] 1 $tamMemoria
clear
imprimirTabla 1 2 3 4 5
scanfSiNo "¿Estas seguro de los datos del último proceso introducido? [s/n]: " seguro
if [ $seguro = "n" ]; then #si se cumple se borra la fila que acaba de introducir los datos
for ((j=1; j<=numCol;j++)) do
unset procesos[$1,$j]
done
datosManualProcesos $1
fi
ordenarProcesos # -> se reordena la tabla mediante el tiempo de llegada. Se hace en este punto para saber la pos. del proceso
}
# Nombre: selectorFichero
# Descripción: muestra por pantalla los ficheros correspondientes a la secuencia de escape $1
# y devuelve el string del fichero obtenido
# Nota: Esta función utiliza un fichero temporal que se almacena en /tmp
# Se requiere de la función mktemp que no es POSIX. Está instalada en muchos sitemas, pero ojo cuidado!
#
# --NO------@Param $1: secuencia de escape: por ejemplo $1='*.txt' muestra sólo los ficheros que terminen con 'txt', es el resultado de un ls--------
# @Param $2: variable en la que vamos a almacenar el string de resultado
# GLOBAL: los valores se asignan también a $nomFile, ya que eval no permite hacer return de un string con espacios
# Paso de comerme la cabeza, es una chapuza pero no hay otra, bash tiene muchas limitaciones en este aspecto.
# Date: 19/03/2020
selectorFichero(){
local tmp=$(mktemp) #Fichero temporal
local -i seleccion
local -i nFicheros
local stringReturn
imprimirLCyan "Seleccione el archivo que desea leer:"
ls $1 | tee "$tmp" | cat -n
nFicheros=$(wc -l < "$tmp")
scanfNumMinMax "Valor entre 0 y $nFicheros: 0 permite introducir un nombre de forma manual: " "seleccion" 0 $nFicheros
if [[ $seleccion = 0 ]]; then
eval ${2}="null"
rm "$tmp"
else
stringReturn=$(sed -n ${seleccion}p $tmp)
rm "$tmp"
nomFile="${stringReturn}"
#eval "${2}"="${stringReturn}"
fi
}
# Nombre: datosFichero
# Descripcion: Opción 2: Por datos. Recoge todos los datos a través del fichero
# Date: 24/03/2020 Actualización: Añadida memoria + apropiativo
datosFichero(){
local -i i
local -i j
local -i k #linea del fichero de los datos de procesos
local nomFile=${DATA_DIRECTORY}datos.txt
local respuesta
local numLineas
scanfSiNo "Por defecto se usa ${DATA_DIRECTORY}datos.txt ¿Quieres cambiarlo? [s/n]: " respuesta
if [ "$respuesta" = "s" ]; then
selectorFichero "${DATA_DIRECTORY}*.txt" "nomFile" #Muestra los ficheros que terminen en .txt
if [[ $nomFile = "null" ]]; then
scanfString "Nombre del fichero: " nomFile
fi
fi
if [[ -f "$nomFile" ]]; then #si el fichero existe
imprimirLCyan "Cargando datos desde $nomFile"
sleep 1
numLineas=`cat "$nomFile" | wc -l`
#sed -n 1p coge la linea 1 y cut -d ":" -f 2 la columna 2 delimitado por :
tamMemoria=`sed -n 1p "$nomFile" | cut -d ":" -f 2`
opcionApropiativo=`sed -n 2p "$nomFile" | cut -d ":" -f 2`
#opcionEstatico=`sed -n 3p "$nomFile" | cut -d ":" -f 2`
priorMin=`sed -n 3p "$nomFile" | cut -d ":" -f 2`
priorMax=`sed -n 4p "$nomFile" | cut -d ":" -f 2`
for (( i=1,k=6; k<=numLineas; i++,k++)) do
((numProc++))
#Asignación del nombre del proceso
if [[ $numProc -lt 10 ]]; then
procesos[$i,$P_NOMBRE]="P0${numProc}"
else
procesos[$i,$P_NOMBRE]="P${numProc}"
fi
for (( j=1; j<numCol; j++ )) do
#j es una más, porque la columna de los procesos no se lee de archivo
procesos[$i,$((j+1))]=$(sed -n ${k}p "$nomFile"| cut -d " " -f $j)
done
done
comprobarDatosFichero
establecerPrioridad
asignarColoresTabla
else #si no existe el fichero vuelve a mandar al menú de inicio
imprimirAviso "$nomFile no existe. Volviendo al menú de inicio..."
sleep 2
clear
cargaDatos
fi
}
# Nombre: comprobarDatosFichero
# Descripcion: comprueba si los datos del fichero son correctos. Si se repite el nombre de los procesos, fuera de rango en tamaño de procesos etc.
comprobarDatosFichero(){
local -i i
local -i j
comprobarRango "El tamaño de memoria es incorrecto, tendrás que introducirlo por teclado: " "$tamMemoria" tamMemoria 1 999
comprobarSN "Opcion apropiativo incorrecto, tendrás que introducir por teclado [s/n]:" "$opcionApropiativo" opcionApropiativo
for ((i=1;i<=numProc;i++)) do
for((j=1;j<=numCol;j++)) do
case "$j" in
1)
comprobarRepite $i
;;
2)
comprobarRango "El tiempo de llegada del proceso ${procesos[$i,$P_NOMBRE]} es incorrecto, introduce otro número: " ${procesos[$i,$j]} procesos[$i,$j] 0 999
;;
3)
comprobarRango "El tiempo de ejecución del proceso ${procesos[$i,$P_NOMBRE]} es incorrecto, introduce otro número: " ${procesos[$i,$j]} procesos[$i,$j] 1 999
;;
4)
comprobarRango "La prioridad del proceso ${procesos[$i,$P_NOMBRE]} es incorrecto, introduce otro número: " ${procesos[$i,$j]} procesos[$i,$j] $priorMin $priorMax
;;
5)
comprobarRango "El tamaño del proceso ${procesos[$i,$P_NOMBRE]} es incorrecto, introduce otro número: " ${procesos[$i,$j]} procesos[$i,$j] 1 $tamMemoria
;;
esac
done
done
}
# Nombre: datosAleatorios
# Descripcion: Opción 3: Datos Aleatorios. Carga datos del número y tamaño de partición,
# número de procesos, etc con números aleatorios llamando a la función numAleatorio
datosAleatorios(){
local -i i
local -i tamMaxProc
numAleatorio tamMemoria 5 35
numAleatorio numProc 5 13
numAleatorio priorMin -30 30
numAleatorio priorMax -30 30
establecerPrioridad
for ((i=1; i<=numProc; i++)) do
if [[ $i -lt 10 ]]; then #Nombres que siempre ocupen 3 chars (p01 - p99)
procesos[$i,$P_NOMBRE]="P0$i"
else
procesos[$i,$P_NOMBRE]="P$i"
fi
numAleatorio procesos[$i,$P_TLLEGADA] 0 15 #numero aleatorio de t.llegada entre 0 y 15
numAleatorio procesos[$i,$P_TEJECUCION] 1 10 #numero aleatorio de t.ejec entre 0 y 10
numAleatorio procesos[$i,$P_PRIORIDAD] $priorMin $priorMax #numero aleatorio de prioridad entre prioriMin y priorMax
numAleatorio procesos[$i,$P_TAMANIO] 1 $((tamMemoria * 75 / 100)) #numero aleatorio de tamaño entre 1 y tamMemoria + 0.75
done
asignarColoresTabla
}
# Nombre: escribeDatos
# Descripcion: sobrescribe los datos en datos.txt, si no existe lo crea
escribeDatos(){
local -i i
local -i j
# Nombre: ordenarProcesosNombre
# Descripción: Reordena toda la tabla de procesos por nombre.
# Detalles: función escribeDatos(), en el curso 19/20 se exige que el fichero
# tenga los datos ordenados por nombre de proceso/añadido, para que sea más simple añadir nuevos datos
# como no es necesario almacenar el nombre, igual también se podría haber eliminado, pero bueno (es un cambio necesario, y paso de hacer lo otro)
# Date: 17/03/2020
ordenarProcesosNombre(){
local -i i
local -i j
local -i minLlegada #índice al proceso que es menor en llegada
for((i=1;i<numProc;i++)) do
minLlegada=$i
for((j=i+1;j<=numProc;j++)) do
if [[ ${procesos[$j,$P_NOMBRE]} < ${procesos[$minLlegada,$P_NOMBRE]} ]]; then #compara el tiempo de llegada
minLlegada=$j
fi
done
#intercambio de elementos
for((k=1;k<=13;k++)) do
aux=${procesos[$i,$k]}
procesos[$i,$k]=${procesos[$minLlegada,$k]}
procesos[$minLlegada,$k]=$aux
done
done
}
#Ordenanmos los procesos por nombre para la ejecución
ordenarProcesosNombre
echo "Tamaño Memoria:$tamMemoria" > ${DATA_DIRECTORY}datos.txt
echo "Apropiativo:$opcionApropiativo" >> ${DATA_DIRECTORY}datos.txt
#echo "Estatico:$opcionEstatico" >> ${DATA_DIRECTORY}datos.txt
echo "Prioridad Mínima:$priorMin" >> ${DATA_DIRECTORY}datos.txt
echo "Prioridad Máxima:$priorMax" >> ${DATA_DIRECTORY}datos.txt
#echo -e "Nombre\tT.Lleg\tT.Ejec\tPrior\tTamaño" >> ${DATA_DIRECTORY}datos.txt
echo -e "T.Lleg\tT.Ejec\tPrior\tTamaño" >> ${DATA_DIRECTORY}datos.txt
for (( i=1; i<=numProc; i++ )) do
for(( j=2; j<=numCol; j++ )) do
echo -e -n "${procesos[$i,$j]}\t" >> ${DATA_DIRECTORY}datos.txt
done
echo >> ${DATA_DIRECTORY}datos.txt
done
#Ordenamos de nuevo para la ejecución:
ordenarProcesos
}
# Nombre: creacionDeDirectorios()
# Descripción: Crea los directorios para los ficheros de entrada y los informes si no existen
# Date: 21/03/2020
creacionDeDirectorios(){
if [[ ! -d $DATA_DIRECTORY ]]; then
mkdir $DATA_DIRECTORY
fi
if [[ ! -d $LOG_DIRECTORY ]]; then
mkdir "$LOG_DIRECTORY"
fi
}
# __ __ _ _
# | \/ (_)___ ___ ___| | __ _ _ __ ___ __ _
# | |\/| | / __|/ __/ _ \ |/ _` | '_ \ / _ \/ _` |
# | | | | \__ \ (_| __/ | (_| | | | | __/ (_| |
# |_| |_|_|___/\___\___|_|\__,_|_| |_|\___|\__,_|
#
# Nombre: DEV_medirTiempos
# Descripción: Permite comparar el tiempo que transcurre entre las dos últimas llamas a esta función.
# Si no se ha ejecutado, imprime el tiempo del sistema
# @Param $1: String a imprmir
# @Param $2: Fichero en el que sacar el resultado. No pasar nada para no guardar
# Date: 22/03/2020
#
# Variable global que almacena el último instante en ele que se ha llamado a la función (en ms)
declare -i ultimoInstanteMedido=0
DEV_medirTiempos(){
local -i tiempoActualMS=$(($(date +%s%N)/1000000))
echo "$1 : $((tiempoActualMS - ultimoInstanteMedido))ms" | tee -a $2
ultimoInstanteMedido=$tiempoActualMS
}
# Nombre: ComprobaciónDirectorio
# Date: 07/03/2020
# Descripción: Comprueba que el script está siendo ejécutandose desde ./algo.sh
# y no desde una dirección distinta (./test/priMayor/algo.sh),
# ya que crearía los archivos de salida en ./____/algo.sh y no en el mismo directorio de ./algo.sh
#
comprobacionDirectorio(){
local -i nPuntosBarras
local -i nDirectorios
nDirectorios=$(echo $0 | grep -oF '/' | wc -l)
nPuntosBarras=$(echo $0 | grep -oF './' | wc -l)
if [[ $nDirectorios -gt $nPuntosBarras ]]; then
echo "Directorio de ejecución: $0"
imprimirLCyan "Si cree que este mensaje no debería salir, por favor, borre ó comente la última línea:"
cat $0 | grep -n "comprobacionDirectorio stringDeBúsqueda, no tiene valor alguno"
salirPorErrorCritico "Por favor, ejecute el script desde la ruta ./script.sh y no desde otro directorio o carpetas"
fi
}
# Nombre: convertirFicheroColorEnBlancoNegro
# Descripción: Lee un fichero formateado con ASCII Color Schemes y lo convierte en Blanco y negro
# Elimina los colores usados en este script y otros chars de escape para poder ser visualizados en cualquier editor de texto
# Date: 29/02/2020
# Documentation: https://stackoverflow.com/questions/19296667/remove-ansi-color-codes-from-a-text-file-using-bash
# @Param $1: Direccion del fichero 1 a convertir
# @Param $2: Dirección del fichero 2 en el que se volcará el resultado
# @Param $3: String boolano ("true"), en el que se indica si se quiere borrar el fichero original
convertirFicheroColorEnBlancoNegro(){
sed -r "s/\x1B\[(([0-9]{1,2})?(;)?([0-9]{1,2})?)?[m,K,H,f,J]//g" "$1" > "$2"
if [[ $3 = "true" ]];then
rm "$1" && echo "El fichero $1 ha sido borrado"
fi
}
# Nombre: abrirInforme
# Descripción: Función con distintas opciones para abrir el informe
# Date: 20/03/2020
abrirInforme(){
local opcion
imprimirLCyan "Qué desea visualizar?"
echo " 1) Informe a color completo (con \$cat)"
echo " 2) Informe a color con scroll (con \$less, estilo Editor VI)"
echo " 3) Informe a color secuencial (con \$more)"
echo " 4) Informe en blanco y negro completo(con \$cat)"
echo " 5) Informe en blanco y negro con scroll (con \$less, estilo Editor VI)"
echo " 6) Informe en blanco y negro secuencial (con \$more)"
echo " 7) Editar Informe blanco y negro con VIM"
echo " 8) Editar Informe blanco y negro con NANO"
echo " *) Salir"
read -r opcion
case $opcion in
1)
cat "$INFORME_FILENAME"
;;
2)
less -R "$INFORME_FILENAME"
;;
3)
more "$INFORME_FILENAME"
;;
4)
cat "$INFORMEBN_FILENAME"
;;
5)
less "$INFORMEBN_FILENAME"
;;
6)
more "$INFORME_FILENAME"
;;
7)
vim "$INFORMEBN_FILENAME"
;;
8)
nano "$INFORMEBN_FILENAME"
;;
*)
echo -n ""
;;
esac
}
# Nombre: renombrarDatosEntrada
# Descripción: Renombra el archivo datos.txt para que los datos no sean borrados en la proxima ejecución
# Date: 19/03/2020
renombrarDatosEntrada(){
local opcion
local nombreArchivo
local -i haFallado=0
scanfSiNo "¿Desea guardar los datos de entrada con otro nombre? [s/n]:" "opcion"
if [[ $opcion = s ]]; then
echo "Introduzca el nuevo nombre"
echo "Recordatorio: Es necesario añadir el formato (.txt) y evitar usar Slashes [ / ], ya que son tomadas como un directorio"
read -r "nombreArchivo"
cat "${DATA_DIRECTORY}datos.txt" > "${DATA_DIRECTORY}$nombreArchivo" || haFallado=1 #Se podría hacer con un cp o un move, pero con esto nos ahorramos problemas
if [[ $haFallado -eq 1 ]];then
renombrarDatosEntrada
fi
fi
}
# ____ _ _ _ _____ _ _
# / ___|___ _ __ | |_ _ __ ___ | | __| | ___ | ___| |_ _ (_) ___
# | | / _ \| '_ \| __| '__/ _ \| | / _` |/ _ \ | |_ | | | | || |/ _ \
# | |__| (_) | | | | |_| | | (_) | | | (_| | __/ | _| | | |_| || | (_) |
# \____\___/|_| |_|\__|_| \___/|_| \__,_|\___| |_| |_|\__,_|/ |\___/
# |__/
#
# Nombre: salirPorErroCritico
# Descripcion: imprime en pantalla un aviso de error al introducir un dato con letras y para la ejecucion.
# @param $1: texto de aviso
# Date 21/02/2020
salirPorErrorCritico(){
imprimirErrorCritico "$1"
forzarCierre
}
# Nombre: fin_programa
# Descripcion: se termina la ejecición del script
fin_programa(){
imprimirLCyan "Saliendo del programa..."
kill -13 $PIDscript > /dev/null 2>&1
}
# Nombre: forzarCierre
# Descripcion: Ejecuta una serie de comandos antes de salir, perfecta para borrar archivo u otras cosas por si no es válida la ejecución!
# Date: 21/02/2020
# //@see deleteGeneratedFiles
forzarCierre(){
imprimirErrorCritico "Cerrando por fallo, pulse [Enter] para continuar"
read -ers
#Funciones a ejecutar aquí abajo: {
deleteGeneratedFiles
# }
clear
fin_programa
}
# Nombre: breakpoint
# Date: 21/02/2020
# Descripción: Permite realizar una parada del programa en cualquier punto del código hasta que no se realizar una entrada por teclado.
# Uso: Activar o desactivar la variable global $BREAKPOINT_ENABLED para activar o desactivar los breakpoints.
# Nota: En algunos puntos del programa, si ocurre un fallo específico, se lanza un breakpoint, fueron usados durante el desarrollo.
# Globales: BREAKPOINT_ENABLED
# @param $@: Imprime todos los stings pasados como argumento, por si se quieren visualizar variables.
breakpoint(){
if [[ $BREAKPOINT_ENABLED == true ]]; then
if (($# == 0));then
echo -n ">"
else
echo -n "Breakpoint > $1"
fi
if [[ $BREAKPOINT_AUTO == "true" ]];then
sleep $BREAKPOINT_AUTO_TIMEOUT
else
read -ers
fi
fi
}
# Nombre: debug (y sus muchas funciones)
# Date: 21/02/2020
# Descripción: Permite imprimir un string en un fichero a parte, y que este sea visualizado desde otro terminal
# Uso: alternar los booleanos globales
# Globales:DEFAULT_DEBUG_OUTPUT_FILE_NAME, DEBUG_ENABLE, DEBUG_FIRST_EXECUTION, DEBUG_PERSISTENT_FILE
# @param $1: String a imprimir
debug(){
if [[ $DEBUG_ENABLE == false ]]; then
return 0
fi
mensajeEntadaDebug(){
printf "Introduzca el comando \$tail -f $DEFAULT_DEBUG_OUTPUT_FILE_NAME para obtener el debug\n"
}
cleanDebugFile(){
if [[ $DEBUG_PERSISTENT_FILE == false ]]; then
echo "" > $DEFAULT_DEBUG_OUTPUT_FILE_NAME
fi
}
cabeceraDebug(){
printf "%s\n-----------------------------------------------\n" "$(date '+%d/%m/%Y %H:%M:%S')" >> $DEFAULT_DEBUG_OUTPUT_FILE_NAME
}
if [[ $DEBUG_FIRST_EXECUTION == true ]]; then
cleanDebugFile
mensajeEntadaDebug
cabeceraDebug
DEBUG_FIRST_EXECUTION=false
fi
echo -e "$1" >> $DEFAULT_DEBUG_OUTPUT_FILE_NAME
}
# Nombre: deleteGeneratedFiles
# Date: 21/02/2020
# Descripción: Borra aquellos archivos que han sido generados por el programa. Es necesario indicar los archivos a borrar
# Uso: Añadir los archvios, pereferiblemente, comprobar antes de borrar si existen
deleteGeneratedFiles(){
if [[ -f $DEFAULT_DEBUG_OUTPUT_FILE_NAME ]]; then
rm $DEFAULT_DEBUG_OUTPUT_FILE_NAME >> /dev/null
fi
if [[ -f $DEFAULT_LOG_FILE_NAME ]]; then
rm $DEFAULT_LOG_FILE_NAME >> /dev/null
fi
#TOFILL
}
# ____ _ _ _ ____ _ _ _
# / ___| __ _| (_) __| | __ _ ___ _ __ ___ _ __ | _ \ __ _ _ __ | |_ __ _| | | __ _
# \___ \ / _` | | |/ _` |/ _` / __| | '_ \ / _ \| '__| | |_) / _` | '_ \| __/ _` | | |/ _` |
# ___) | (_| | | | (_| | (_| \__ \ | |_) | (_) | | | __/ (_| | | | | || (_| | | | (_| |
# |____/ \__,_|_|_|\__,_|\__,_|___/ | .__/ \___/|_| |_| \__,_|_| |_|\__\__,_|_|_|\__,_|
# |_|
# Nombre: imprimirAviso
# Descripcion: imprime en pantalla un aviso de error al introducir un dato con letras.
# @param $1: texto de aviso
# Cambios 2020: Como hemos añadido la funcion imprimirErrorCritico, he cambiado el color de fondo de ROJO a AMARILLO/NARANJA (Depende del terminal)
imprimirAviso(){
echo -e "\n${B_BLACK}${_YELLOW}\xE2\x9A\xA0 $1 ${NC}\n" #\xE2\x9A\xA0 significa icono de alerta
}
# Nombre: imprimirErrorCritico
# Descripcion: imprime en pantalla un aviso de error al introducir un dato con letras.
# @param $1: texto de aviso
imprimirErrorCritico(){
echo -e "\n${B_BLACK}${_RED}❌ $1 ${NC}\n"
}
# Nombre: imprimirLCyan
# Descripcion: imprime en pantalla el text de color cyan claro
# @param $1: texto a imprimir en cyan claro
# @param $2 (opcional): argumento adicional para el echo como -n si no se quiere introducir un salto de linea
imprimirLCyan(){
echo -e $2 ${L_CYAN}$1${NC}
}
# Nombre: imprimirTiemposMedios
# Descripción: Imprime los tiempos medios del sistema.
#
imprimirTiemposMedios(){
#Tiempos Acumulados
#local tEjecAcumulado=0
local tEsperaAcumulado=0
local tRetornoAcumulado=0
#local nProcesosEjecucion=0
local nProcesosEspera=0
local nProcesosRetorno=0
#Tiempos medios
local tEjecMedio
local tEsperaMedio
local tRetornoMedio
if [[ $memoriaLibre -eq $tamMemoria ]] && [[ $procEjecutados -eq 0 ]]; then
echo No hay tiempos medios al no haber procesos en el sistema.
return
fi
calcularTiemposMedios(){
#Acumulador
for ((i=1; i<=numProc; i++));do
#Tiempo Espera Acumulado
if [[ $(esEntero "${procesos[$i,8]}") = "true" ]]; then
tEsperaAcumulado=$(( tEsperaAcumulado + ${procesos[$i,$P_TESPERA]}))
((nProcesosEspera++))
fi
#Tiempo Retorno Acumulado
if [[ $(esEntero "${procesos[$i,8]}") = "true" ]]; then
tRetornoAcumulado=$(( tRetornoAcumulado + ${procesos[$i,8]}))
((nProcesosRetorno++))
fi
done
tEsperaMedio=$(echo "scale=2;$tEsperaAcumulado/$nProcesosEspera" | bc -l)
tRetornoMedio=$(echo "scale=2;$tRetornoAcumulado/$nProcesosRetorno" | bc -l)
#Ejecución medio como la suma de espera + retorno
tEjecMedio=$(echo "scale=2;$tEsperaMedio+$tRetornoMedio" | bc -l)
}
calcularTiemposMedios # > /dev/null 2>&1
imprimirLCyan "Tiempo de espera medio: $BOLD$tEsperaMedio || " "-n"
imprimirLCyan "Tiempo de retorno medio: $BOLD$tRetornoMedio"
}
# Nombre: truncarMemoria
# Date: 08/03/2020
# Parámetros: Utiliza la variable memoriaTruncada declarada en dibujarMemoria
# Descripción: rellena un array bidimensional con el string de memoria a imprimir.
# este nuevo string permite representar la memoria de forma dínamica, dependiendo del ancho del terminal.
truncarMemoria(){
local -i ultimaPosMemEmplazada=1
local ultimoIndiceEncontrado=-1
local -i i
local -i j
#Últimas i,j -> Almacena la última posición en la que se dibuja memoria, para añadir al final de la barra el número con la memoria total
local -i ultimaI
local -i ultimaJ
for (( i=1; i<= (altoMemoriaTruncada*3); i+=3 )); do
for ((j=1; j <= anchoTerminalBloques; j++)); do #La línea de memoria empieza en 1
memoriaTruncada[$i,$j]=${memoriaSegunNecesidades[$ultimaPosMemEmplazada,$MEM_TOSTRING]}
if [[ ${memoriaSegunNecesidades[$ultimaPosMemEmplazada,$MEM_INDICE]} -ne $ultimoIndiceEncontrado ]];then
ultimoIndiceEncontrado=${memoriaSegunNecesidades[$ultimaPosMemEmplazada,$MEM_INDICE]}
#Fila de los nombres
if [[ $ultimoIndiceEncontrado -eq $MEM_HUECO_VACIO ]]; then #Si el hueco está vacío
memoriaTruncada[$((i-1)),$j]="${NC}---"
else #Nombre del proceso
memoriaTruncada[$((i-1)),$j]=${procesos[$ultimoIndiceEncontrado,$P_COLORLETRA]}${procesos[$ultimoIndiceEncontrado,$P_NOMBRE]}${NC} #ASIGNAMOS EL NOMBRE ARRIBA DE LA BARRA
fi
#Fila de las posiciones
if [[ $ultimaPosMemEmplazada -le 10 ]]; then
memoriaTruncada[$((i+1)),$j]="$((ultimaPosMemEmplazada-1)) " #Metemos espacios al final para que no se descuadre, si el tamaño es >=100, se descuadra
else #Sería poner un elif con el tamaño del int, pero me da pereza, pd: he tardado más escribiendo esto
memoriaTruncada[$((i+1)),$j]="$((ultimaPosMemEmplazada-1)) " #que haciendolo, un saludo: Jorge (09/03/2020 - 13:17)
fi
else
memoriaTruncada[$((i-1)),$j]=" " #No hay proceso -> Vacío
memoriaTruncada[$((i+1)),$j]=" " #No hay dirección al no haber cambio de proceso -> Vacío
fi
((ultimaPosMemEmplazada++))
ultimaI=$i
ultimaJ=$j
if [[ $ultimaPosMemEmplazada -gt $tamMemoria ]];then break; fi
done
ultimoIndiceEncontrado=-1 #reseteo para que se imprima siempre en cada línea la dirección y el proceso
done
#Añade los elementos al margen izquierdo
for (( i=1; i<= (altoMemoriaTruncada*3); i+=3 )); do
memoriaTruncada[$((i-1)),0]=" "
memoriaTruncada[$((i )),0]=" "
memoriaTruncada[$((i+1)),0]=" "
done
#Añade el título de la barra
memoriaTruncada[1,0]="${NC}BM|"
#Añade el fin de la barra (tamaño de memoria final)
memoriaTruncada[$((ultimaI-1)),$ultimaJ]=" ${NC}|"
memoriaTruncada[$ultimaI,$ultimaJ]="${memoriaTruncada[$ultimaI,$ultimaJ]}${NC}|$tamMemoria"
memoriaTruncada[$((ultimaI+1)),$ultimaJ]=" ${NC}|"
}
# Nombre: dibujarMemoria
# Descripción: Muestra por pantalla la memoria truncada
# @Param: $1 string de control: si el string es "mostrarStatsMemoria", se muestra por pantalla el uso de memoria y el
dibujarMemoria(){
local -i memoriaEnUso
local memoriaEnUsoPorciento #Es un string al ser float
declare -A memoriaTruncada
declare -i anchoTerminal=$(tput cols) #En columnas
declare -i anchoTerminalBloques=$(( anchoTerminal/3 - 2)) #Bloques -> bloques de memoria. Un bloque/unidad de memoria se representa con 3 espacios/columnas de un color || restamos unidades para dejar margen para maniobrar
declare -i altoMemoriaTruncada
#Calculamos el alto de memoria (el número de filas que ocupará truncada)
if [[ $((tamMemoria%anchoTerminalBloques)) == 0 ]];then
altoMemoriaTruncada=$((tamMemoria/anchoTerminalBloques))
else #Si la memoria ocupa parte de una líena, la asignamos entera
altoMemoriaTruncada=$(( ( tamMemoria/anchoTerminalBloques ) + 1 ))
fi
#Stats mememoria:
if [[ $1 = "mostrarStatsMemoria" ]]; then
memoriaEnUso=$((tamMemoria-memoriaLibre))
memoriaEnUsoPorciento=$(echo "scale=2;100*$memoriaEnUso/$tamMemoria" | bc -l)
imprimirLCyan "Uso de memoria: $memoriaEnUso/$tamMemoria ($memoriaEnUsoPorciento%) -> Memoria libre: $memoriaLibre"
fi
truncarMemoria #Imprimimos la memoria truncada
for (( i=0; i< 3*altoMemoriaTruncada; i++ ));do
for (( j=0; j<=anchoTerminalBloques; j++));do
echo -en "${memoriaTruncada[$i,$j]}"
done
echo ""
done
}
# Nombre: truncarBarraCPU
# Date: 09/03/2020
# Descripción: Trunca la barra de CPU, y añade el tiempo de inicio y fin de cada proceso, así como el nombre correspondiente.
# Nota: Tiene un uso similar al truncado de memoria. Los cálculos de las distintas variables aquí referenciadas han sido realizados en dibujarEstadoCPU()
# ya que es necesario saber de antemano el ancho y alto del array a imprimir y a generar, y puede variar si se calcula 2 veces, una en cada función.
# Además, aquí no tenemos un vector.length para saber cuanto mide un array, bash-ura de lenguaje.
# Podría hacerse en una misma función, pero los parámetros en Bash son un dolor, y paso de perder el tiempo haciendo un código de muy alta calidad.
#
truncarBarraCPU(){
declare -a barraTiempoColor #Array que contiene los string a imprimir, generado en: colorearBarraMemoria. En este caso hemos trabajado con 2 arrays y no con uno, porque soy bobo.
#PD: no es lo más eficiente, ya que se colorea cada vez, quizá debería hacerlo en el momento, como con la memoria? Dunno m8
local -i i
local -i j
local -i ultimaPosMemEmplazada=0
local ultimoIndiceEncontrado=-1
#Últimas i,j -> Almacena la última posición en la que se dibuja memoria, para añadir al final de la barra el número con la memoria total
local -i ultimaI
local -i ultimaJ
colorearBarraCPU
for (( i=1; i<= (altoLineaTiempoTruncada*3); i+=3 )); do
for ((j=1; j <= anchoTerminalBloques; j++)); do #La barra de CPU empieza en 0
#Volcamos la fila intermedia (barras de color)
lineaTiempoTruncada[$i,$j]=${barraTiempoColor[$ultimaPosMemEmplazada]}
#Si no coincide con la última posición: Significa que hay otro proceso -> añadimos ref y tiempo en las líneas.
if [[ ${lineaEstadoCPU[$ultimaPosMemEmplazada]} -ne $ultimoIndiceEncontrado ]];then
ultimoIndiceEncontrado=${lineaEstadoCPU[$ultimaPosMemEmplazada]}
#Fila de los nombres
if [[ $ultimoIndiceEncontrado -eq 0 ]]; then #Si el hueco está vacío (al no haber proceso, CPU vacía en ese instante)
lineaTiempoTruncada[$((i-1)),$j]="${NC}---"
else
lineaTiempoTruncada[$((i-1)),$j]="${procesos[$ultimoIndiceEncontrado,$P_COLORLETRA]}${procesos[$ultimoIndiceEncontrado,$P_NOMBRE]}${NC}" #ASIGNAMOS EL NOMBRE ARRIBA DE LA BARRA
fi
#Fila de las posiciones
if [[ $ultimaPosMemEmplazada -lt 10 ]]; then
lineaTiempoTruncada[$((i+1)),$j]="$ultimaPosMemEmplazada " #Metemos espacios al final para que no se descuadre, si el tamaño es >=100, se descuadra
else #Sería poner un elif con el tamaño del int, pero me da pereza, pd: he tardado más escribiendo esto
lineaTiempoTruncada[$((i+1)),$j]="$ultimaPosMemEmplazada " #que haciendolo, un saludo: Jorge (09/03/2020 - 13:17)
fi
else
lineaTiempoTruncada[$((i-1)),$j]=" " #No hay cambio de proceso-> Vacío
lineaTiempoTruncada[$((i+1)),$j]=" " #No hay dirección al no haber cambio de proceso -> Vacío
fi
((ultimaPosMemEmplazada++))
ultimaI=$i
ultimaJ=$j
if [[ $ultimaPosMemEmplazada -gt $tiempoEjecucion ]];then break; fi #Se ha emplazado toda la memoria
done
ultimoIndiceEncontrado=-1 #reseteo para que se imprima siempre en cada línea la dirección y el proceso
done
#Añade los elementos al margen izquierdo
for (( i=1; i<= (altoLineaTiempoTruncada*3); i+=3 )); do
lineaTiempoTruncada[$((i-1)),0]=" "
lineaTiempoTruncada[$((i )),0]=" "
lineaTiempoTruncada[$((i+1)),0]=" "
done
lineaTiempoTruncada[$((1 )),0]="${NC}BT|${NC}"
#Fin barra (pone el proceso actual en CPU pero no dibuja la barra)
if [[ $procesoCPU -ne 0 ]]; then
lineaTiempoTruncada[$((ultimaI-1)),$ultimaJ]="${NC}${procesos[$procesoCPU,$P_NOMBRE]}${NC}"
lineaTiempoTruncada[$ultimaI,$ultimaJ]="${NC}${lineaTiempoTruncada[$ultimaI,$ultimaJ]}${NC} "
lineaTiempoTruncada[$((ultimaI+1)),$ultimaJ]="${NC}$tiempoEjecucion"
elif [[ $numProc -eq $procEjecutados ]]; then #Si es el final de la ejecución (Se han ejecutado todos los procesos)
#Se ponen las 3 barras verticales para marcar el final
lineaTiempoTruncada[$((ultimaI-1)),$ultimaJ]="${NC}|"
lineaTiempoTruncada[$ultimaI,$ultimaJ]="${NC}|$tiempoEjecucion${NC}" # ponemos al final de la barra | tamaño memoria
lineaTiempoTruncada[$((ultimaI+1)),$ultimaJ]="${NC}|"
fi
}
# Nombre: colorearBarraCPU
# Descripción: Rellena el array barraTiempoColor[] con la barra de tiempo coloreada, donde cada posición es un proceso en una unidad de tiempo.
# Date: 09/03/2020
colorearBarraCPU(){
local colorProceso
local colorLetraProceso
local stringProceso
for ((i=0; i< tiempoEjecucion; i++)); do
if [[ ${lineaEstadoCPU[$i]} -ne 0 ]]; then
colorProceso=${procesos[${lineaEstadoCPU[$i]},$P_COLOR]}
colorLetraProceso=${procesos[${lineaEstadoCPU[$i]},$P_COLORLETRA]}
stringProceso="[=]"
else
colorProceso=$_WHITE
colorLetraProceso=$WHITE
stringProceso="[ ]"
fi
barraTiempoColor+=("${colorProceso}${colorLetraProceso}${stringProceso}${NC}") #3 espacios porque es el ancho del proceso que desea el profesor
done
}
# Nombre: dibujarEstadoCPU
# Date: 09/03/2020
# Descripción: Imprime el estado de la CPU por pantalla
dibujarEstadoCPU(){
local -i
declare -i anchoTerminal=$(tput cols) #En columnas
declare -i anchoTerminalBloques=$((anchoTerminal/3 - 2)) #Bloques -> bloques de memoria. Un bloque/unidad de memoria se representa con 3 espacios/columnas de un color || restamos 1 unidad para dejar margen para maniobrar
declare -A lineaTiempoTruncada
declare -i altoLineaTiempoTruncada
#Calculamos el alto de memoria (el número de filas que ocupará truncada)
if [[ $((tiempoEjecucion%anchoTerminalBloques)) == 0 ]];then
if [[ tiempoEjecucion -eq 0 ]]; then #Con tiempo 0 la CPU está vacía, pero queremos mostrarla, por lo que hay que forzar el valor a 1
altoLineaTiempoTruncada=1
else
altoLineaTiempoTruncada=$((tiempoEjecucion/anchoTerminalBloques))
fi
else #Si la memoria ocupa parte de una líena, la asignamos entera
altoLineaTiempoTruncada=$(( ( tiempoEjecucion/anchoTerminalBloques ) + 1 ))
fi
truncarBarraCPU
for (( i= 0; i<= 3*altoLineaTiempoTruncada; i++ ));do
for (( j=0; j<=anchoTerminalBloques ; j++));do
echo -en "${lineaTiempoTruncada[$i,$j]}"
done
echo ""
done
}
# Nombre: imprimirTiemposMedios
# Descripción: Imprime el tiempo medio de Ejecución, Espera y Retorno con decimales
# Date: 23/09/2020
# @Param $1: Si es "mostrarEjecución" muestra el tiempo medio de ejecución
# _____ _ _
# |_ _|_ _| |__ | | __ _
# | |/ _` | '_ \| |/ _` |
# | | (_| | |_) | | (_| |
# |_|\__,_|_.__/|_|\__,_|
#
# Nombre: ordenarProcesos
# Descripcion: ordena el array procesos en función del tiempo de llegada.
# Se usa selection sort como algortimo de ordenamiento
# Version 2.0
# Date 17/03/2020
# Detalles de modificación: Si dos prioridades son iguales, el que haya sido introducido antes tiene prioridad
# EJ: PO1 entra antes que P03, aunque tengan el mismo t.llegada.
ordenarProcesos(){
local -i i
local -i j
local -i minLlegada #índice al proceso que es menor en llegada
for((i=1;i<numProc;i++)) do
minLlegada=$i
for((j=i+1;j<=numProc;j++)) do
if [ ${procesos[$j,$P_TLLEGADA]} -lt ${procesos[$minLlegada,$P_TLLEGADA]} ]; then #compara el tiempo de llegada
minLlegada=$j
elif [[ ${procesos[$j,$P_TLLEGADA]} -eq ${procesos[$minLlegada,$P_TLLEGADA]} ]]; then #Si son igaules
if [[ ${procesos[$j,$P_NOMBRE]} < ${procesos[$minLlegada,$P_NOMBRE]} ]]; then #Compara los nombres
minLlegada=$j
fi
fi
done
#intercambio de elementos
for((k=1;k<=13;k++)) do
aux=${procesos[$i,$k]}
procesos[$i,$k]=${procesos[$minLlegada,$k]}
procesos[$minLlegada,$k]=$aux
done
done
}
# Nombre: imprimirTablaPredeterminada
# Date; 06/03/2020
# Descripción: Función que llama a la función "imprimirTabla()" con unos parámetros específicos
# Además, la función imprime una cabecera inicial.
# Nota: La tabla original era muy grande, y permitía imprimir las columnas seleccionadas.
# En la versión de 2020 se exige que se impriman casi todas las columnas del struct, y tener que hacer una llamada
# con todos los parámtros, puede ser muy pesado.
# He decidido hacer esto por dos razones: 1º: Puedo reutilizar la tabla en la entrada de datos con 4 columnas 2º: Puedo poner la cabecera fija cómodamente.
imprimirTablaPredeterminada(){
echo " │ DAT.INICIALES │ TIEMPOS │ MEMORIA │ OTROS DATOS │"
echo "┌───┼───┬───┬───┬───┼────┬────┬────┼────┬────┼──────────────────┤"
imprimirTabla "$P_NOMBRE" "$P_TLLEGADA" "$P_TEJECUCION" "$P_TAMANIO" "$P_PRIORIDAD" "$P_TESPERA" "$P_TRETORNO" "$P_TRESTANTE" "$P_POSINI" "$P_POSFIN" "$P_ESTADO"
#echo "└───┴───┴───┴───┴───┴────┴────┴────┴────┴────┴──────────────────┘"
}
# Nombre: imprimirTabla
# Descripcion: imprime las columnas del array procesos pasado como parámetro
# Versión 2.0
# Date: 6/03/2020
# Nota 2020: Adaptada a los requisitos exigidos en el curso 18-19 y 19-20 (Tabla compacta roñosa)
# @param $@ (todos): índice de las columnas que se quiere imprimir en pantalla
imprimirTabla(){
local -i i
local -i j
local -i k
local separadorHorizontal="───────────────────────────" #Cualquier tamaño, luego se recorta y se ajusta.
#Array que almacena el número de huecos máximo que puede ocupar el string a imprimir de cada proceso.
#Por ejemplo, la referencia (columna/posArray nº 1) del proceso puede ocupar como máximo 3 huecos (p01 a p99), por lo que en la tabla imprimiremos 3 huecos máximo
declare -a anchosTabla=(0 3 3 3 3 3 4 4 4 17 0 0 4 4)
for k in "$@"; do #imprime la cabecera de la tabla
printf " %*b" "${anchosTabla[$k]}" "${B_L_YELLOW}${cabeceraProcesos[$k]}${NC}"
done
echo ""
for (( i=1; i<=numProc; i++ )) do
if [[ $((($i-1) % 5 )) -eq 0 ]] && [[ $i -ne 1 ]]; then #imprime una línea de separación cada 5 procesos (pero no en la primera ejecución)
for k in "$@"; do
printf "${BLUE}%s" ${separadorHorizontal:0:${anchosTabla[$k]}+1}
done
echo -e "──${NC}"
fi
for j in "$@";do #imprime los datos de los procesos
printf " ${procesos[$i,$P_COLORLETRA]}%-*s${NC}" "${anchosTabla[$j]}" "${procesos[$i,$j]:0:${anchosTabla[$j]}}"
done
echo -e "${NC}"
done
}
# Nombre: nularColumna
# Date: 05/03/2020
# Descripción: Actualiza toda una columna del STRUCT/${procesos[]} con el valor "-"
# Ejemplo de uso: Nulado inicial de las columnas que no han sido introducidas mediante la entrada.
# @Param $@: Todos los enteros/valores del struct que queremos vaciar
nularColumna(){
local -r valorNull="-"
local -i columna
for columna in "$@"; do
for ((i=1; i<=numProc; i++));do
if [[ $columna -eq $P_ESTADO ]];then
procesos[$i,$columna]=$STAT_SISTEMA
else
procesos[$i,$columna]=$valorNull
fi
done
done
}
# Nombre: DEV_ImprimirColores
# Date: 05/03/2020
# Descripción: Imprime por todos los procesos en el sistema: El color del string y de fondo asignado
DEV_ImprimirColores(){
local string1="test"
local string2=987023
for ((i = 1; i<= numProc; i++)); do
echo -e "Índice $i: ${procesos[$i,$P_COLORLETRA]}STRING${NC} ${procesos[$i,$P_COLOR]}FONDO${NC} |"
done
for ((i = 1; i<= numProc; i++)); do
printf "${procesos[$i,$P_COLORLETRA]}%-.*s${NC} ${procesos[$i,$P_COLOR]}%-.*s${NC} |\n" $i "printf" $i "printf"
done
for ((i = 1; i<= numProc; i++)); do
printf "${procesos[$i,$P_COLORLETRA]}%*s${NC} ${procesos[$i,$P_COLOR]}%-*s${NC} |\n" $i "${string1:0:$i}" $i "${string2%:0:$i}"
done
read -ers
}
# Nombre: asignarColorProceso.
# Date: 05/03/2020
# Descripción: Pasado el índce del proceso y un entero, se asignará a dicho proceso el color correspondiente al entero.
# Ejemplo de uso: Al introducir un proceso manualmente, se le asigna el color al momento!
# Nota: Los arrays de colores deben tener el mismo tamaño y los colores en la misma posición.
# @Param $1: índice/puntero al proceso en la tabla procesos
# @Param $2: entero cualquiera
asignarColorProceso(){
if [[ $1 -gt 0 ]] && [[ $1 -le $numProc ]]; then
procesos[$1,$P_COLOR]=${coloresFondo[$2%${#coloresFondo[@]}]}
procesos[$1,$P_COLORLETRA]=${coloresLetras[$2%${#coloresLetras[@]}]}
else
imprimirErrorCritico "El proeso intorudcido no se encuentra en la tabla"
fi
}
# Nombre: asignarColoresTabla
# Date: 05/03/2020
# Descripción: Rellena las columnas $P_COLOR y $P_COLORLETRA de la tabla procesos con colores
# Ejemplo de uso: Al introducir los procesos por fichero/Random, podemos asignar a todos los procesos colores!
asignarColoresTabla(){
local -i i
for ((i=1; i <= numProc; i++)); do
asignarColorProceso "$i" "$i"
done
}
# __ __ _
# | \/ | ___ _ __ ___ ___ _ __(_) __ _
# | |\/| |/ _ \ '_ ` _ \ / _ \| '__| |/ _` |
# | | | | __/ | | | | | (_) | | | | (_| |
# |_| |_|\___|_| |_| |_|\___/|_| |_|\__,_|
#
# Nombre: inicializarArrays
# Descripción: inicializa arrays necesario antes de la ejecución
inicializarArrays(){
local -i i
cola[1]=0
#inicializamos de datos predeterminados los de la fila 0, fila usada como indice en caso de que una memoria o cpu este vacio
procesos[0,$P_TLLEGADA]=0
procesos[0,$P_TAMANIO]=0
procesos[0,$P_TRESTANTE]=-1
if [ $tipoPrioridad = "-lt" ]; then
procesos[0,$P_PRIORIDAD]=$((priorMax + 1))
else
procesos[0,$P_PRIORIDAD]=$((priorMax - 1))
fi
}
# Nombre: anadirCola
# Descripcion: añade el indice de un proceso del array procesos al final de la cola,
# cambia el estado del proceso a "cola"
# @param $1: indice del proceso a meter en cola
anadirCola(){
((tamCola++))
cola[$tamCola]=$1
#Actualizamos el estado del proceso a "En cola"
procesos[$1,$P_ESTADO]=$STAT_COLA
procesos[$i,$P_TESPERA]=0
}
# Nombre: eliminarCola
# Descripcion: elimina el primer elemento de la cola y mueve los demas elementos a la izquierda
eliminarCola(){
local -i i
local -i j
for((i=1;i<=tamCola;i++)) do #mueve los elementos a la izquierda
cola[$i]=${cola[$i+1]}
done
((tamCola--))
}
# Nombre: calcularPosProceso
# Descripción: Actualiza las variables $P_POSINI y $P_POSFIN del proceso indicado
# Date: 05/03/2020
# Ejemplo de USO: Si tuviese tiempo para hacer un programa eficiente, habría que actualizar la tabla a paritr
# de esta función cuando: Se añade un proceso en mem -> se reubica. Como no hay tiempo y no se valora, se recalcula en cada bucle
# la de todos los procesos en memoria.
# @Param $1: Índice del proceso a recalcular
#
#NOTA: Sin uso en todo el programa, no había presupuesto, posiblemente nunca se haya probado.
calcularPosProceso(){
for (( i=1; i<=tamMemoria; i++)); do
if [[ ${memoriaSegunNecesidades[$i,$MEM_INDICE]} -eq $1 ]]; then #Está en memoria
procesos[$1,$P_POSINI]=$i
procesos[$1,P_POSFIN]=$((i+${procesos[$1,$P_TAMANIO]}))
break
fi
done
}
# Nombre: calcularPosTodosProcesos
# Descripción: Actualiza las variables $P_POSINI y $P_POSFIN de todos los procesos que estén en memoria
# Date: 05/03/2020
calcularPosTodosProcesos(){
local -i ultimoProEncontrado=-1
local -i procesoActual
for (( i=1; i<=tamMemoria; i++)); do
procesoActual=${memoriaSegunNecesidades[$i,$MEM_INDICE]}
if [[ $procesoActual -ne $ultimoProEncontrado ]] && [[ $procesoActual != "$MEM_HUECO_VACIO" ]]; then #Está en memoria
ultimoProEncontrado=$procesoActual
procesos[$procesoActual,$P_POSINI]=$((i-1))
procesos[$procesoActual,$P_POSFIN]=$((i - 2 + ${procesos[$procesoActual,$P_TAMANIO]}))
fi
done
}
# Nombre: eliminarPosProceso
# Date: 05/03/2020
# Descripción: Actualiza las variables $P_POSINI y $P_POSFIN del proceso indicado a "-"
# @Param $1: índice del proces cuyas posiciones queremos eliminar.
eliminarPosProceso(){
local -r valorNull="-"
procesos[$1,$P_POSINI]=$valorNull
procesos[$1,$P_POSFIN]=$valorNull
}
# Nombre: vaciarMemoria
# Date: 22/02/2020
# Funcinamiento: Vacía la memoria segúnNcesidades, o la pone en su estado por defecto.
vaciarMemoria(){
for((i=1;i<=tamMemoria;i++)); do
memoriaSegunNecesidades[$i,$MEM_INDICE]=$MEM_HUECO_VACIO
memoriaSegunNecesidades[$i,$MEM_TOSTRING]=$MEM_STRING_HUECO_VACIO
done
}
# Si el proceso tiene un tamaño igual o menor a la memoria libre:
# -Se introduce el proceso en memoria
# -Se actualiza su estado a "STAT_MEMO"
# -Se actualiza la cantidad de memoria libre
# Date: 22/02/2020
# @param $1: indice del proceso a guardar en la particion
aniadirProcesoAMemoria(){
local posicionEnLaQueEmpiezaElHuecoEnMemoriaParaEmplazar
#Si el param1 está vacío, no hacemos nada.
if [[ $1 = "" ]] || [[ $tamCola -le 0 ]];then
return
fi
if [[ ${procesos[$1,$P_TAMANIO]} -le $memoriaLibre ]]; then
procesos[$1,$P_ESTADO]=$STAT_MEMO
eliminarCola #sacamos al primer proceso de la cola (el que acabamos de introducir)
ajustarMemoriaParaElProceso "${procesos[$1,$P_TAMANIO]}" "posicionEnLaQueEmpiezaElHuecoEnMemoriaParaEmplazar"
if [[ $posicionEnLaQueEmpiezaElHuecoEnMemoriaParaEmplazar == "null" ]] || [[ $posicionEnLaQueEmpiezaElHuecoEnMemoriaParaEmplazar == "" ]];then
breakpoint "Amigo, tenemos un problemón en la función aniadirAMemoria(), el return de ajustarMemoriaParaElProceso() no es posible ($posicionEnLaQueEmpiezaElHuecoEnMemoriaParaEmplazar) || PROGRAMACIÓN DEFENSIVA"
imprimirErrorCritico "Lo de arriba, mostrando estado de memoria para diagnóstico:"
dibujarMemoria
breakpoint "El error ha sido impreso."
fi
local -i ultimaPosicionADibujarElProceso=$((posicionEnLaQueEmpiezaElHuecoEnMemoriaParaEmplazar + ${procesos[$1,$P_TAMANIO]}))
for((i=posicionEnLaQueEmpiezaElHuecoEnMemoriaParaEmplazar; i<ultimaPosicionADibujarElProceso; i++)); do
#añadimos el indice
memoriaSegunNecesidades[$i,$MEM_INDICE]=$1
#Añadimos la salida por pantalla con COLOR
memoriaSegunNecesidades[$i,$MEM_TOSTRING]="${procesos[$1,${P_COLOR}]}${procesos[$1,${P_COLORLETRA}]}$MEM_STRING_HUECOSINCOLOR${_DEFAULT}"
if [[ $i -gt $tamMemoria ]];then
breakpoint "Amigo, tenemos un problemón en la función aniadirAMemoria(), has añadido a más memoria de la existente || PROGRAMACIÓN DEFENSIVA"
salirPorErrorCritico "Lo de arriba"
fi
done
memoriaLibre=$((memoriaLibre - ${procesos[$1,$P_TAMANIO]}))
fi
}
# Si el proceso se encuentra en memoria
# -Se elimina el proceso en memoria
# -Se actualiza su estado a "FIN"
# -Se actualiza la cantidad de memoria libre
# Date: 22/02/2020
# @param $1: indice del proceso a borrar de memoria
eliminarProcesoDeMemoria(){
local -i estabaEnMemoria=0
for((i=1;i<=tamMemoria;i++)); do
#Si el proceso de una dirección coincide con el del índice pasado, borramos dicho proceso
if [[ $1 -eq ${memoriaSegunNecesidades[$i,$MEM_INDICE]} ]];then
estabaEnMemoria=1
memoriaSegunNecesidades[$i,$MEM_INDICE]=$MEM_HUECO_VACIO
memoriaSegunNecesidades[$i,$MEM_TOSTRING]=$MEM_STRING_HUECO_VACIO
fi
done
if (( estabaEnMemoria == 1)); then
procesos[$1,$P_ESTADO]=$STAT_FIN
memoriaLibre=$((memoriaLibre + ${procesos[$1,$P_TAMANIO]}))
fi
}
# Funcion que comprueba si un proces cabe en la memoria TOTAL, o es necesario reubicar.
# Si es necesario, reubica la memoria.
# Date: 22/02/2020
# @param $1: Tamaño del proceso
# @param $2/return: Variable en la que se almacenará el valor de salida de esta función
# @return posición en la que empieza el hueco ó null si no hay suficiente hueco.
ajustarMemoriaParaElProceso(){
local posicionEnLaQueEmpiezaElHuecoEnMemoria
encontrarHuecoEnMemoria "$1" posicionEnLaQueEmpiezaElHuecoEnMemoria
if (( posicionEnLaQueEmpiezaElHuecoEnMemoria == "null")); then
dibujarMemoria #Dibujamos la memoria una vez para ver la diferencia.
reubicarProcesos
imprimirAviso "AVISO: La memoria ha sido reubicada"
dibujarMemoria #Dibujamos la memoria para ver el después
encontrarHuecoEnMemoria "$1" posicionEnLaQueEmpiezaElHuecoEnMemoria
fi
eval $2="$posicionEnLaQueEmpiezaElHuecoEnMemoria"
}
# Nombre: encontrarHuecoEnMemoria
# Descripción: Función que calcula la posición / si es posible introducir $1 unidades de memoria continuas en memoria.
# Date 22/02/2020
# @param1 tamaño del hueco a encontrar / tamaño del proceso a emplazar
# @param $2/return: Variable en la que se almacenará el valor de salida de esta función
# @return posición en la que empieza el huevo ó null si no hay suficiente hueco.
# return por stdout, es necesario = la llamada de la función a una variable para "capturar" el return.
encontrarHuecoEnMemoria(){
local -i numeroDeHuecosLibresConsecutivos=0
local -i cabeEnMemoria=0 #boolean
local -i posicionInicialEnLaQueEmpiezaElHueco=1
local -i sePuedeGuardarLaPosicioneEnLaQueEmpiezaElHueco=1
if [[ $1 -le $memoriaLibre ]]; then
#Contamos el número de posiciones vacias consecutivas
#Si tienen el mismo tamaño que la memoria, metemos el proceso en ese hueco.
#si hemos recorrido todo el array, y no cabe en ningun lado, reubicamos.
for((i=1;i<=tamMemoria;i++)); do
if [[ ${memoriaSegunNecesidades[$i,$MEM_INDICE]} -eq $MEM_HUECO_VACIO ]]; then #Si hueco esta vacio
((numeroDeHuecosLibresConsecutivos++))
if ((sePuedeGuardarLaPosicioneEnLaQueEmpiezaElHueco == 1)); then
posicionInicialEnLaQueEmpiezaElHueco=$i
sePuedeGuardarLaPosicioneEnLaQueEmpiezaElHueco=0
fi
if ((numeroDeHuecosLibresConsecutivos == $1)); then #Si el proceso tiene el tamaño mínimo del hueco comprobado
cabeEnMemoria=1
break
fi
else #La posición estaba ocupada (miss): Reiniciamos el contador del primer hit
numeroDeHuecosLibresConsecutivos=0
sePuedeGuardarLaPosicioneEnLaQueEmpiezaElHueco=1
fi
done
fi
if [[ $cabeEnMemoria -eq 0 ]]; then
eval ${2}="null"
else
eval ${2}="$posicionInicialEnLaQueEmpiezaElHueco"
fi
}
# Nombre: reubicarProcesos
# date: 22/02/2020
# Descripción: Reubica la memoria
# Nota del autor: Si no hubiese hecho el array bidimensional, esto podría haber sído un simple oneLiner que ordenase el array de menor a mayor
# (No he tenido en cuenta donde irían los nulls, pero podrían haber sido sustiutidos por 0 )
# indepentientemente, bash es una chusta, e igual no va tan bien como debería.
reubicarProcesos(){
local ultimoIndiceEncontrado="/"
# Buffer destinado a guardar los elementos que se encuentran en este momento en memoria
# Almacenará: Un puntero a la fila de la tabla correspondiente a cada proceso
# Leerá dicho puntero/indice de la tabla de memoria, de la capa MEM_INDICE
unset bufferReubicacion
declare -a bufferReubicacion
#Almacenamos los procesos que están en memoria
for((i=1;i<=tamMemoria;i++)); do
#Si el índice que hay en i posición de memoria NO es NI el indice vacío, ni el último indice encontrado, guardamos el índice en un array
if [[ ${memoriaSegunNecesidades[$i,$MEM_INDICE]} != "$ultimoIndiceEncontrado" ]] && [[ ${memoriaSegunNecesidades[$i,$MEM_INDICE]} != "$MEM_HUECO_VACIO" ]]; then
bufferReubicacion+=("${memoriaSegunNecesidades[$i,$MEM_INDICE]}") #Guardamos el índice
ultimoIndiceEncontrado=${memoriaSegunNecesidades[$i,$MEM_INDICE]}
fi
done
vaciarMemoria
local -i ultimaPosicionMemoria=1 #Variable que almacenará la última posición en la que se ha "creado" memoria
#Rellenamos la memoria!
for indice in "${bufferReubicacion[@]}"; do
#Para i iteraciones siendo i = tamaño del proceso
for((i=0;i<procesos[$indice,$P_TAMANIO];i++)); do
#añadimos el indice
memoriaSegunNecesidades[$ultimaPosicionMemoria,$MEM_INDICE]=$indice
#Añadimos la salida por pantalla con COLOR
memoriaSegunNecesidades[$ultimaPosicionMemoria,$MEM_TOSTRING]="${procesos[$indice,$P_COLOR]}${procesos[$indice,$P_COLORLETRA]}$MEM_STRING_HUECOSINCOLOR${NC}"
if (( ultimaPosicionMemoria > tamMemoria)); then
breakpoint "Colega, tenemos un problemón en reubicarProcesos(), te has salido del array de memoria"
fi
((ultimaPosicionMemoria++))
done
done
}
# Nombre: DEV_modificarMemoria
# Date: 27/02/2020
# Descripción: Función que permite manipular la memoria de forma manual. Diseñada para testear el comportamiento de esta.
DEV_modificarMemoria(){
local -i opcion
local -i index
local -i volverAIntroducir
local -i finDeEjecucion=false
echo "Función de desarrollo para la modificación de memoria"
echo "1) Añadir el último elemento de la cola (${procesos[${cola[1]},$P_NOMBRE]}) a memoria"
echo "2) Eliminar un proceso de memoria (A partir de su posición en la tabla)"
echo "3) Reubicar memoria"
echo "4) Añadir siguiente proceso a CPU (El que tenga la prioridad más alta de los que estan en memoria)"
echo "*) Nada"
read -r opcion
case $opcion in
1)
if [[ ${procesos[${cola[1]},$P_TAMANIO]} -le $memoriaLibre ]];then
aniadirProcesoAMemoria "${cola[1]}"
else
imprimirAviso "No se puede introducir el proceso a memoria porque esta no tiene hueco"
fi
;;
2)
echo -n "Introduzca el índice del proceso: "
read -r index
eliminarProcesoDeMemoria $index
;;
3)
reubicarProcesos
;;
4)
aniadirSiguienteProcesoACPU
;;
*)
finDeEjecucion=true
;;
esac
if [[ $finDeEjecucion = "false" ]];then
scanfSiNo "Desea introducir otro proceso?" volverAIntroducir
if [[ $volverAIntroducir = 's' ]]; then
DEV_modificarMemoria
fi
fi
}
# ____ ____ _ _
# / ___| _ \| | | |
# | | | |_) | | | |
# | |___| __/| |_| |
# \____|_| \___/
#
# Nombre: obtenerProcesoConMayorPrioridad
# Descripción: De entre todos los procesos qeu están en memoria, selecciona el proceso con la prioridad más alta.
# Nota: De entre dos procesosos con la misma prioridad, entra el que haya llegado antes a memoria.
# Date: 23/03/2020
# @Param $1: [return] Variable en la que almacenar el índice del proceso
obtenerProcesoConMayorPrioridad(){
#Si la prioridad menor es más baja que la mayor
local -i prioridadMasAlta
local -i procesoConPrioridadMasAlta
if [[ $tipoPrioridad = "-lt" ]]; then
prioridadMasAlta=$((priorMin - 1))
elif [[ $tipoPrioridad = "-gt" ]]; then
prioridadMasAlta=$((priorMin + 1))
else
breakpoint "$(imprimirErrorCritico "aniadirSiguienteProcesoACPU(): No existe dicha ($tipoPrioridad) prioridad crack!")"
fi
# Valores de $tipoPrioridad
# -lt significa que la prioridad minima es un número menor que la prioridad máxima
# -gt significa que la prioridad mínima es mayor que la prioridad máxima
# Más información sobre el porqué de estos valores en la cabezera de la función establecerPrioridad()
for ((i=0; i<=tamMemoria; i++)); do
#Si la prioridad del proceso es mayor a la prioridad más alta encontrada
if [[ ${memoriaSegunNecesidades[$i,$MEM_INDICE]} -ne $MEM_HUECO_VACIO ]]; then
if (( ${procesos[${memoriaSegunNecesidades[$i,$MEM_INDICE]},$P_PRIORIDAD]} > $prioridadMasAlta )); then
if [[ $tipoPrioridad = "-lt" ]]; then
procesoConPrioridadMasAlta=${memoriaSegunNecesidades[$i,$MEM_INDICE]}
prioridadMasAlta=${procesos[${memoriaSegunNecesidades[$i,$MEM_INDICE]},$P_PRIORIDAD]}
fi
elif (( ${procesos[${memoriaSegunNecesidades[$i,$MEM_INDICE]},$P_PRIORIDAD]} < $prioridadMasAlta )); then
if [[ $tipoPrioridad = "-gt" ]]; then
procesoConPrioridadMasAlta=${memoriaSegunNecesidades[$i,$MEM_INDICE]}
prioridadMasAlta=${procesos[${memoriaSegunNecesidades[$i,$MEM_INDICE]},$P_PRIORIDAD]}
fi
elif ((${procesos[${memoriaSegunNecesidades[$i,$MEM_INDICE]},$P_PRIORIDAD]} == $prioridadMasAlta)); then
#Si tienen la misma prioridad ^
#Si su índice es menor (Significa que entró antes en memoria porque su t.llegada era menor)
if (( ${memoriaSegunNecesidades[$i,$MEM_INDICE]} < procesoConPrioridadMasAlta)); then
procesoConPrioridadMasAlta=${memoriaSegunNecesidades[$i,$MEM_INDICE]}
fi
fi
fi
done
eval ${1}=${procesoConPrioridadMasAlta}
}
# Nombre: aniadirSiguienteProcesoACPU
# Date: 27/02/2020
# Descripción: De entre todos los procesos en memoria, añade el proces con la prioridad más alta a CPU
aniadirSiguienteProcesoACPU(){
local -i siguienteProceso
obtenerProcesoConMayorPrioridad "siguienteProceso"
#Guardamos el índice del proceso y actualizamos sus estados y tiempos
procesoCPU=$siguienteProceso
procesos[$procesoCPU,$P_ESTADO]="$STAT_ENCPU"
}
# Nombre: ejecutarUnCicloDeCPU
# Date: 27/02/2020
# Descripción: Simula el comportamiento repetitivo de algunos momentos del programa
# -Calcula ciertos valores
# -Aumenta el tiempo de ejecución
# -Actualiza la línea de estado de CPU
ejecutarUnCiloDeCPU(){
#Decrementamos en una unidad el tiempo restante del proceso en ejecución
procesos[$procesoCPU,$P_TRESTANTE]=$(( ${procesos[$procesoCPU,$P_TRESTANTE]}-1))
lineaEstadoCPU+=("$procesoCPU")
#aumenta el tiempo de espera de los procesoso en memoria y en cola
for((i=1;i<=numProc;i++)); do
#Incremento de ESPERA y tiempo de retorno = tiempo espera
if [[ ${procesos[$i,$P_ESTADO]} == "$STAT_MEMO" ]] || [[ ${procesos[$i,$P_ESTADO]} == "$STAT_COLA" ]]; then
((procesos[$i,$P_TESPERA]++))
procesos[$i,$P_TRETORNO]=${procesos[$i,$P_TESPERA]}
fi
#Incremento de tiempos cuando un proceso está en pausa
if [[ ${procesos[$i,$P_ESTADO]} == "$STAT_APROP_PAUSA" ]]; then
((procesos[$i,$P_TRETORNO]++))
((procesos[$i,$P_TESPERA]++))
fi
#Incremento de retorno durante la ejecución
if [[ ${procesos[$i,$P_ESTADO]} == "$STAT_ENCPU" ]]; then
((procesos[$i,$P_TRETORNO]++))
fi
done
((tiempoEjecucion++))
}
# Nombre: comprobarSiElProcesoEnCPUHaTerminado
# Date: 29/02/2020
# Descripción: Si un proceso ha termiando en CPU -> Actualiza su línea en la tabla y lo saca de CPU y memoria
comprobarSiElProcesoEnCPUHaTerminado(){
if [[ ${procesos[$procesoCPU,$P_TRESTANTE]} -eq 0 ]];then
printf "${L_RED}%s ${procesos[$procesoCPU,$P_COLORLETRA]}%s ${L_RED}%s ${NC}%d ${L_RED}%s\n${NC}" "El proceso" "${procesos[$procesoCPU,$P_NOMBRE]}" "ha terminado de ejecutarse en el instante" $tiempoEjecucion "y está siendo desalojado de memoria y CPU"
((procEjecutados++))
#Eliminamos el proceso de la CPU
eliminarPosProceso "$procesoCPU"
eliminarProcesoDeMemoria "$procesoCPU"
procesos[$procesoCPU,$P_ESTADO]=$STAT_FIN
procesoCPU=0
fi
}
# Nombre: ejecucionApropiativo
# Descripción: Realiza los cambios en CPU de los procesos si el modo apropiativo está activado ($opcionApropiativo = s)
# Date: 23/03/2020
ejecucionApropiativo(){
if [[ ! $opcionApropiativo = "s" ]]; then
return 0
fi
local -i procesoCandidato=0
local -i procesoExpulsado=$procesoCPU
obtenerProcesoConMayorPrioridad procesoCandidato
#Si tienen la misma prioridad, no hacemos nada
if [[ ${procesos[$procesoCandidato,$P_PRIORIDAD]} -eq ${procesos[$procesoCPU,$P_PRIORIDAD]} ]]; then
return 0
fi
haHabidoUnCambio=1
imprimirAviso "AVISO: Un proceso ha sido expulsado de CPU"
printf "${L_CYAN}%s ${procesos[$procesoExpulsado,$P_COLORLETRA]}%s ${L_CYAN}%s ${procesos[$procesoCandidato,$P_COLORLETRA]}%s ${L_CYAN}%s ${NC}\n" \
"El proceso" "${procesos[$procesoExpulsado,$P_NOMBRE]}" "ha sido expulsado de CPU y ahora" "${procesos[$procesoCandidato,$P_NOMBRE]}" "está en ejecución."
procesoCPU=$procesoCandidato
#Actualizamos el proceso que estaba en CPU
procesos[$procesoExpulsado,$P_ESTADO]="$STAT_APROP_PAUSA"
#Actualizamos el proceso que hemos metido en CPU
procesos[$procesoCPU,$P_ESTADO]="$STAT_ENCPU"
#NOTA: El apropiativo también cambia los tiempos de retorno y espera, pero eso se ejecuta en ejecutarUnCicloDeCPU
}
# _
# _ __ ___ __ _(_)_ __
# | '_ ` _ \ / _` | | '_ \
# | | | | | | (_| | | | | |
# |_| |_| |_|\__,_|_|_| |_|
#
# Nombre: ejecucion
# Descripción: Loop central con la ejecución de los procesos
ejecucion(){
local -i procEjecutados=0
local -i tiempoEjecucion=0
local -i i
local -i haHabidoUnCambio #bool que se usa para ver cuando ha ocurrido un evento. Los eventos suelen imprimir STRINGS especiales!
archivoMensajes=$(mktemp) #archivo temporal que almacenará los textos que han aparecido durante la ejecución / es necesario para que el Tiempo (T=algo) salga antes que estos textos si ha habido un cambio
procesoCPU=0 #int que almacena/apunta a la fila correspondiente al proceso que está en ejecución
#Empieza la ejecucion del programa
memoriaLibre=$tamMemoria
vaciarMemoria
while [[ $procEjecutados -lt $numProc ]]; do # mientras el numero de procesos ejecutados sea menor a procesos total
echo -n "" > "$archivoMensajes" #vaciamos el archivo con los mensajes que aparecen durante la ejecución
haHabidoUnCambio=0
comprobarSiElProcesoEnCPUHaTerminado >> "$archivoMensajes" #este método imprime un mensaje al sacar un proceso de CPU!
#Si se ha ejecutado el último proceso, paramos el bucle para no tener ejecuciones en blanco
if [[ $procEjecutados -eq $numProc ]];then
imprimirLCyan "El último proceso ha sido desalojado con éxito de CPU y Memoria!" >> "$archivoMensajes"
break
fi
#Introducimos a la cola los procesos que han llegado a memoria
for((i=1;i<=numProc;i++)) do
if [[ ${procesos[$i,$P_TLLEGADA]} -eq "$tiempoEjecucion" ]]; then
anadirCola $i
procesos[$i,$P_TRETORNO]=0
printf "${L_MAGENTA}%s ${procesos[$i,$P_COLORLETRA]}%s ${L_MAGENTA}%s ${NC}%d\n" "El proceso" "${procesos[$i,$P_NOMBRE]}" "ha entrado en el sistema en el instante" "$tiempoEjecucion" >> "$archivoMensajes"
haHabidoUnCambio=1
fi
done
#Volcamos toda la cola en memoria (si cabe)
while (( tamCola >= 1 )); do
if [[ ${procesos[${cola[1]},$P_TAMANIO]} -le $memoriaLibre ]]; then
local -i procesoMem="${cola[1]}" #lo guardamos para poder hacer el printf tras añadir el procesos: Meramente estético (por si hay reubicabilidad, que salga después del mensaje)
aniadirProcesoAMemoria "$procesoMem" >> "$archivoMensajes" #al reubicar se imprime un mensaje!
procesos[$procesoMem,$P_TRESTANTE]=${procesos[$procesoMem,$P_TEJECUCION]} #Inicializamos el tiempo de ejecución restante
printf "${L_GREEN}%s ${procesos[$procesoMem,$P_COLORLETRA]}%s ${L_GREEN}%s ${NC}%d\n" \
"El proceso" "${procesos[$procesoMem,$P_NOMBRE]}" "ha sido introducido en memoria en el instante" "$tiempoEjecucion" >> "$archivoMensajes"
haHabidoUnCambio=1
else
break
fi
done
#Comprobaciones de CPU
#Si no hay ningún proceso en CPU, o el proceso ha terminado && hay al menos 1 proc en mem.
if [[ $procesoCPU -eq 0 ]] && [[ $memoriaLibre -lt $tamMemoria ]]; then
aniadirSiguienteProcesoACPU
printf "${L_CYAN}%s ${procesos[$procesoCPU,$P_COLORLETRA]}%s ${L_CYAN}%s${NC} %d ${L_CYAN}%s\n${NC}" "El proceso" "${procesos[$procesoCPU,$P_NOMBRE]}" "ha sido introducido en la CPU en el instante" "$tiempoEjecucion" "y ahora se está ejecutando" >> "$archivoMensajes"
haHabidoUnCambio=1
elif [[ $memoriaLibre -lt $tamMemoria ]]; then
ejecucionApropiativo >> "$archivoMensajes" #La función lanza un mensaje
fi
calcularPosTodosProcesos
#Si ha habido un cambio/evento en el estado de algún proceso -> Salida por pantalla
if [[ $haHabidoUnCambio -eq 1 ]] || [[ $tiempoEjecucion -eq 0 ]]; then
echo -e "${B_WHITE}T: $tiempoEjecucion${NC}"
cat "$archivoMensajes" #Visualizamos por pantalla los mensajes
imprimirTablaPredeterminada
echo -e "${B_WHITE}P. más alta: $priorMax | P. más baja: $priorMin ${NC}"
dibujarMemoria "mostrarStatsMemoria"
dibujarEstadoCPU
imprimirTiemposMedios
echo -e "${L_CYAN}Número de procesos ejecutados: ${B_WHITE}$procEjecutados/$numProc ${NC}"
#breakpoint "Fin del loop $tiempoEjecucion del WHILE"
read -ers -p "Pulse [enter] para continuar "
echo "═════════════════════════════════════════════════════════════════"
clear
fi
ejecutarUnCiloDeCPU
done
pantallaFinal(){
local -i
echo -e "${B_WHITE}T: $tiempoEjecucion${NC}"
imprimirTablaPredeterminada
echo "═════════════════════════════════════════════════════════════════"
dibujarMemoria
dibujarEstadoCPU
echo ""
imprimirTiemposMedios "mostrarEjecución"
echo -e "${L_CYAN}Tiempo de ejecución Total: ${B_WHITE}$tiempoEjecucion ${NC}"
echo -e "${L_CYAN}Prioridad más alta: ${B_WHITE}$priorMax ${NC}"
echo -e "${L_CYAN}Prioridad más baja: ${B_WHITE}$priorMin ${NC}"
echo -e "\n\n"
}
rm "$archivoMensajes"
pantallaFinal
}
# Nombre: main
# Descripción: Main del programa
# Se llama desde global para poder cargar todas las variables globales
#
main(){
imprimirCabecera
cargaDatos
escribeDatos
ordenarProcesos
inicializarArrays
nularColumna "$P_TRETORNO" "$P_POSINI" "$P_POSFIN" "$P_ESTADO" "$P_TRESTANTE" "$P_TESPERA"
clear
imprimirTabla 1 2 3 4 5
echo -e "
╔═══════════════════════════════════════╗
${L_GREEN} Apropiativo: ${NC}${B_BLUE}$opcionApropiativo${NC}
${L_GREEN} Tamaño de Memoria: ${NC}${B_BLUE}$tamMemoria${NC}
${L_GREEN} Número de Procesos: ${NC}${B_BLUE}$numProc ${NC}
${L_GREEN} Prioridad Mínima: ${NC}${B_BLUE}$priorMin${NC}
${L_GREEN} Prioridad Máxima: ${NC}${B_BLUE}$priorMax${NC}
╚═══════════════════════════════════════╝"
imprimirLCyan "Pulse [enter] para continuar" -n
read -ers
clear
ejecucion
}
# Nombre: finMain
# Descripción: Es la función que se ejecuta tras el main (en global)
# Todas las salidas de main se ven reflejadas en el archivo $INFORME_FILENAME, pero como no queremos todas, aislamos el final del programa
# Nota:Si haces el | tee sobre algunas funciones de main, se rompe la ejecución, y si el finMain no se ejecuta desde global, se pierden los parámetros globales como colores o nombres de archivo
finMain(){
convertirFicheroColorEnBlancoNegro $INFORME_FILENAME $INFORMEBN_FILENAME "false"
renombrarDatosEntrada
abrirInforme
}
comprobacionDirectorio stringDeBúsqueda, no tiene valor alguno
global #Carga las variables globales y ejecuta el main -> Está hecho así para poder minimizar todas las variables de global en el outline de VSCODE
|
SQL
|
UTF-8
| 6,080
| 3.265625
| 3
|
[] |
no_license
|
drop table ea_category cascade constraints
delete from ea_category cascade constraints
create table ea_category(
ey_categorynum number(4) primary key,
ey_bigcategory varchar2(100) not null, --대분류
ey_smallcategory varchar2(100) not null --소분류
);
select distinct(ey_bigcategory) from ea_category
select * from ea_board b, ea_category c
where b.eb_state = '특별오픈' and
b.ey_categorynum = c.ey_categorynum and
c.ey_bigcategory = '식품'
select * from ea_category
insert into ea_category
values(1, '패션의류', '여성의류');
insert into ea_category
values(2, '패션의류', '남성의류');
insert into ea_category
values(3, '패션의류', '여성언더웨어/잠옷');
insert into ea_category
values(4, '패션의류', '남성언더웨어/잠옷');
--------------------------------------------------
insert into ea_category
values(101, '패션잡화', '남성신발');
insert into ea_category
values(102, '패션잡화', '여성신발');
insert into ea_category
values(103, '패션잡화', '남성가방/잡화');
insert into ea_category
values(104, '패션잡화', '남성가방/잡화');
insert into ea_category
values(105, '패션잡화', '쥬얼리/시계/선글라스');
insert into ea_category
values(106, '패션잡화', '수입명품');
---------------------------------------------------
insert into ea_category
values(201, '유아용품', '기저귀/분유/유아식');
insert into ea_category
values(202, '유아용품', '임부복/출산/유아용품');
insert into ea_category
values(203, '유아용품', '장난감/인형/교육완구');
insert into ea_category
values(204, '유아용품', '유아동의류');
insert into ea_category
values(205, '유아용품', '유아동신발/잡화/가방');
----------------------------------------------------
insert into ea_category
values(301, '가구생활', '가구/DIY');
insert into ea_category
values(302, '가구생활', '조명/인테리어');
insert into ea_category
values(303, '가구생활', '침구/커튼');
insert into ea_category
values(304, '가구생활', '생활/욕실/수납용품');
insert into ea_category
values(305, '가구생활', '주방용품');
insert into ea_category
values(306, '가구생활', '화장지/물티슈/생리대');
insert into ea_category
values(307, '가구생활', '세제/구강');
-------------------------------------------------
insert into ea_category
values(401, '식품', '쌀/과일/농수축산물');
insert into ea_category
values(402, '식품', '건강식품/다이어트');
insert into ea_category
values(403, '식품', '커피/음료');
insert into ea_category
values(404, '식품', '즉석/간식/가공식품');
-------------------------------------------------------
insert into ea_category
values(501, '취미', '건강/의료용품');
insert into ea_category
values(502, '취미', '반려동물용품');
insert into ea_category
values(503, '취미', '악기/취미/키덜트');
insert into ea_category
values(504, '취미', '디자인/문구/사무용품');
insert into ea_category
values(505, '취미', '꽃/이벤트용품');
-------------------------------------------------------
insert into ea_category
values(601, '디지털컴퓨터', '카메라');
insert into ea_category
values(602, '디지털컴퓨터', '음향기기');
insert into ea_category
values(603, '디지털컴퓨터', '게임');
insert into ea_category
values(604, '디지털컴퓨터', '휴대폰');
insert into ea_category
values(605, '디지털컴퓨터', '태블릿');
insert into ea_category
values(606, '디지털컴퓨터', '노트북/PC');
insert into ea_category
values(607, '디지털컴퓨터', '모니터/프린터');
insert into ea_category
values(608, '디지털컴퓨터', 'PC주변기기');
insert into ea_category
values(609, '디지털컴퓨터', '저장장치');
----------------------------------------------------
insert into ea_category
values(701, '스포츠레저', '휘트니스/수영');
insert into ea_category
values(702, '스포츠레저', '스포츠의류/운동화');
insert into ea_category
values(703, '스포츠레저', '골프클럽/의류/용품');
insert into ea_category
values(704, '스포츠레저', '등산/아웃도어');
insert into ea_category
values(705, '스포츠레저', '캠핑/낚시');
insert into ea_category
values(706, '스포츠레저', '구기/라켓');
insert into ea_category
values(707, '스포츠레저', '자전거/보드');
----------------------------------------------------
insert into ea_category
values(801, '뷰티', '스킨케어');
insert into ea_category
values(802, '뷰티', '메이크업');
insert into ea_category
values(803, '뷰티', '향수');
insert into ea_category
values(804, '뷰티', '바디/헤어');
insert into ea_category
values(805, '뷰티', '기타화장품');
----------------------------------------------------
insert into ea_category
values(901, '생활가전', '대형가전');
insert into ea_category
values(902, '생활가전', '계절가전');
insert into ea_category
values(903, '생활가전', '주방가전');
insert into ea_category
values(904, '생활가전', '생활/미용가전');
-------------------------------------------------------
insert into ea_category
values(1001, '자동차공구', '자동차용품/블랙박스');
insert into ea_category
values(1002, '자동차공구', '타이어/오일/부품');
insert into ea_category
values(1003, '자동차공구', '공구/안전/산업용품');
-------------------------------------------------------
insert into ea_category
values(1101, '도서기타', '도서/교육/음반');
insert into ea_category
values(1102, '도서기타', '백화점/제화상품권');
insert into ea_category
values(1103, '도서기타', '여행/항공권');
insert into ea_category
values(1104, '도서기타', 'e쿠폰/모바일상품권');
|
Java
|
UTF-8
| 3,696
| 2.015625
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.gcp.common;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.ServiceOptions;
import com.google.common.base.Strings;
import io.cdap.cdap.api.annotation.Description;
import io.cdap.cdap.api.annotation.Macro;
import io.cdap.cdap.api.annotation.Name;
import io.cdap.cdap.api.plugin.PluginConfig;
import java.io.IOException;
import javax.annotation.Nullable;
/**
* Contains config properties common to all GCP plugins, like project id and service account key.
*/
public class GCPConfig extends PluginConfig {
public static final String NAME_PROJECT = "project";
public static final String NAME_SERVICE_ACCOUNT_FILE_PATH = "serviceFilePath";
public static final String AUTO_DETECT = "auto-detect";
@Name(NAME_PROJECT)
@Description("Google Cloud Project ID, which uniquely identifies a project. "
+ "It can be found on the Dashboard in the Google Cloud Platform Console.")
@Macro
@Nullable
protected String project;
@Name(NAME_SERVICE_ACCOUNT_FILE_PATH)
@Description("Path on the local file system of the service account key used "
+ "for authorization. Can be set to 'auto-detect' when running on a Dataproc cluster. "
+ "When running on other clusters, the file must be present on every node in the cluster.")
@Macro
@Nullable
protected String serviceFilePath;
/**
* Attempts to get project id if 'auto-detect' was defined
* @return Returns null if project is an undefined macro, or returns defaultProjectId if project is null/empty or
* 'auto-detect'
*/
@Nullable
public String getProject() {
if (containsMacro(NAME_PROJECT) && Strings.isNullOrEmpty(project)) {
return null;
}
String projectId = project;
if (Strings.isNullOrEmpty(project) || AUTO_DETECT.equals(project)) {
projectId = ServiceOptions.getDefaultProjectId();
}
return projectId;
}
/**
* Checks that serviceAccountPath is non-null/empty and returns it
*
* @return Returns null if serviceAccountPath is 'auto-detect' or null/empty, otherwise return serviceAccountPath
*/
@Nullable
public String getServiceAccountFilePath() {
if (containsMacro(NAME_SERVICE_ACCOUNT_FILE_PATH) || serviceFilePath == null ||
serviceFilePath.isEmpty() || AUTO_DETECT.equals(serviceFilePath)) {
return null;
}
return serviceFilePath;
}
/**
* Return true if the service account is set to auto-detect but it can't be fetched from the environment. This
* shouldn't result in a deployment failure, as the credential could be detected at runtime if the pipeline runs on
* dataproc. This should primarily be used to check whether certain validation logic should be skipped.
*
* @return true if the service account is set to auto-detect but it can't be fetched from the environment.
*/
public boolean autoServiceAccountUnavailable() {
if (getServiceAccountFilePath() == null) {
try {
ServiceAccountCredentials.getApplicationDefault();
} catch (IOException e) {
return true;
}
}
return false;
}
}
|
JavaScript
|
UTF-8
| 220
| 3.28125
| 3
|
[] |
no_license
|
function trocaCedulas(valor){
let c100
let r100
let cedulas
if(valor > 100){
let c100 = parseInt(valor / 100)
let r100 = valor % 100
}
}
console.log(trocaCedulas(200))
|
Java
|
UTF-8
| 1,857
| 3.015625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.hasancaslan;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
public class JavaHttpClientDemo {
public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
synchronousRequest();
asynchronousRequest();
}
private static void asynchronousRequest() throws InterruptedException, ExecutionException {
// create a client
var client = HttpClient.newHttpClient();
// create a request
var request = HttpRequest.newBuilder(
URI.create("https://api.nasa.gov/planetary/apod?api_key=h9p5CHTIu68oI22fGSVs9wgYaw67wL6JdK0yQucY"))
.header("accept", "application/json")
.build();
// use the client to send the request
var responseFuture = client.sendAsync(request, new JsonBodyHandler<>(APOD.class));
// We can do other things here while the request is in-flight
// This blocks until the request is complete
var response = responseFuture.get();
// the response:
System.out.println(response.body().get().url);
}
private static void synchronousRequest() throws IOException, InterruptedException {
// create a client
var client = HttpClient.newHttpClient();
// create a request
var request = HttpRequest.newBuilder(
URI.create("https://api.nasa.gov/planetary/apod?api_key=h9p5CHTIu68oI22fGSVs9wgYaw67wL6JdK0yQucY")
).build();
// use the client to send the request
HttpResponse<Supplier<APOD>> response = client.send(request, new JsonBodyHandler<>(APOD.class));
// the response:
System.out.println(response.body().get().title);
}
}
|
JavaScript
|
UTF-8
| 2,320
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
$(document).ready(() => {
function updateUI(postId, voteType){
console.log("more stuff");
let gifScoreSpan = $(`#gifScoreSpan${postId}`);
let jellyScoreSpan = $(`#jellyScoreSpan${postId}`);
$.ajax({
method: "GET",
url: "/api/updateVotes/" + postId,
}).then( (results) => {
let oldGifScore = $(gifScoreSpan).text();
let oldJellyScore = $(jellyScoreSpan).text();
oldGifScore = parseInt(oldGifScore);
oldJellyScore = parseInt(oldJellyScore);
let newGifScore = results.gifScore;
let newJellyScore = results.jellyScore;
$(gifScoreSpan).text(newGifScore);
$(jellyScoreSpan).text(newJellyScore);
console.log (`new score: ${newGifScore} ${newJellyScore}`);
console.log (`new score: ${oldGifScore} ${oldJellyScore}`);
console.log(voteType);
if(newGifScore === oldGifScore && newJellyScore === oldJellyScore && voteType === "gif") {
console.log("gif error");
Swal.fire({
imageUrl: "/Images/jelly-splat.png",
imageHeight: 80,
imageAlt: "Jelly Error Icon",
title: "You already gifed this!",
});
} else if(newGifScore === oldGifScore && newJellyScore === oldJellyScore && voteType === "jelly") {
console.log("jelly error");
Swal.fire({
imageUrl: "/Images/jelly-splat.png",
imageHeight: 80,
imageAlt: "Jelly Error Icon",
title: "You already jellied this!",
});
}
});
}
function postVote(voteType, postId){
let gif;
let jelly;
if (voteType === "gif"){
gif = true;
jelly = false;
} else {
jelly = true;
gif = false;
}
let gifOrJelly = {
gif: gif,
jelly: jelly
};
$.ajax({
method: "POST",
url: "/api/vote/" + postId,
data: gifOrJelly
}).then ( function(){
updateUI(postId, voteType);
}
);
}
let postId;
$(".gifVote").click(function(event) {
event.preventDefault();
postId = $(this).attr("data-id");
postVote("gif", postId);
});
$(".jellyVote").click(function(event) {
event.preventDefault();
postId = $(this).attr("data-id");
postVote("jelly", postId);
});
$("#returnButton").click(function(){
location.href = "/members";
});
});
|
Swift
|
UTF-8
| 3,617
| 2.875
| 3
|
[] |
no_license
|
//
// ContentView.swift
// MisDatos
//
// Created by David A Cantú Delgado on 19/02/20.
// Copyright © 2020 Tec de Monterrey. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State private var infoSheet = false
@State private var esFormal = true
@State private var menuIzq = "Informal"
@State private var mifoto = "mifoto"
@EnvironmentObject private var usuario: User
// @State var telefono = "1111111111"
// @State var correo = "david@tec.mx"
// @State var nombre = "David Alonso Cantú Delgado"
// @State var estatura = 1.80
// @State var peso = 80
// @State var fechaNacimiento = Date()
var dateFormatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
return dateFormatter
}
var body: some View {
NavigationView{
ZStack {
Color.fondo
.edgesIgnoringSafeArea(.all)
VStack {
Text(usuario.nombre)
.foregroundColor(Color.principal)
.font(.Galada(size: 24))
.padding([.leading,.trailing],20)
Image(mifoto)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 160)
.clipShape(Circle())
.overlay(
Circle()
.stroke(ColorSalud(indSalud: usuario.salud), lineWidth: 4)
)
.shadow(radius: 10)
.padding([.bottom],40)
DisplayView(texto: usuario.telefono, imagen: "phone.fill", tamaño: 20)
DisplayView(texto: usuario.correo, imagen: "envelope.fill", tamaño: 20)
DisplayView(texto: "\(dateFormatter.string(from: usuario.fechaNacimiento))", imagen: "calendar", tamaño: 20)
DisplayView(texto: "\(usuario.peso)kg - \(FormatoEstatura(estatura: usuario.estatura))mts", imagen: "heart.fill", tamaño: 20)
}
}
.navigationBarItems(
leading: Button(
action: {
self.esFormal.toggle()
if self.esFormal {
self.mifoto = "mifoto"
self.menuIzq = "Informal"
} else {
self.mifoto = "mifoto_informal"
self.menuIzq = "Formal"
}
},
label: {
Text(self.esFormal ? "Informal" : "Formal")
.foregroundColor(Color.principal)
.font(.Galada(size: 24))
}
),
trailing:
Button(action: {
self.infoSheet.toggle()
}, label: {
Image(systemName: "person.fill")
.foregroundColor(Color.principal)
.imageScale(.large)
}))
.sheet(isPresented: $infoSheet, content: {
// InfoView(nombre: self.$nombre, telefono: self.$telefono, correo: self.$correo, estatura: self.$estatura, peso: self.$peso, fechaNacimiento: self.$fechaNacimiento)
InfoView(usuario: self.usuario)
})
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
Java
|
UTF-8
| 1,707
| 2.25
| 2
|
[] |
no_license
|
package com.example.demo.jdbc;
import com.example.demo.bean.ApiVarBean;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ApiVarBeanRowMapper implements RowMapper<ApiVarBean> {
@Override
public ApiVarBean mapRow(ResultSet resultSet, int i) throws SQLException {
//此处要使用表中的字段,不能使用属性
int apivar_id = resultSet.getInt("apivar_id");
int api_id = resultSet.getInt("api_id");
String apivar_name = resultSet.getString("apivar_name");
String apivar_sample = resultSet.getString("apivar_sample");
int apivar_inputflag = resultSet.getInt("apivar_inputflag");
String apivar_inputdatatype = resultSet.getString("apivar_inputdatatype");
int apivar_inputtype = resultSet.getInt("apivar_inputdatatypeid");
int apivar_inputlenght =resultSet.getInt("apivar_inputlength");
String apivar_scope = resultSet.getString("apivar_inputscope");
String apivar_inputnote =resultSet.getString("apivar_inputnote");
String createdt = resultSet.getString("apivar_createdt");
String updatedt = resultSet.getString("apivar_updatedt");
ApiVarBean apiVarBean = new ApiVarBean();
apiVarBean.setNum(apivar_id);
apiVarBean.setVal(apivar_name);
apiVarBean.setVal_sample(apivar_sample);
apiVarBean.setInputFlag(apivar_inputflag);
apiVarBean.setInputDataType(apivar_inputdatatype);
apiVarBean.setInputTypeID(apivar_inputtype);
apiVarBean.setInputLenght(apivar_inputlenght);
apiVarBean.setInputNote(apivar_inputnote);
return apiVarBean;
}
}
|
Swift
|
UTF-8
| 2,762
| 3
| 3
|
[] |
no_license
|
//
// PokemonDetailTypesTableViewCell.swift
// PokemonApp
//
// Created by Juan Santiago Martín Balbás on 14/10/2018.
// Copyright © 2018 Juan Santiago Martín Balbás. All rights reserved.
//
import UIKit
class PokemonDetailTypesTableViewCell: UITableViewCell {
static let reuseIdentifier = "PokemonDetailTypesTableViewCellId"
private var types: [PokemonType] = []
private let stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.spacing = 15
return stackView
}()
func setup(with types: [PokemonType]?) {
self.types = types ?? [.unknown]
setupUILayout()
}
private func setupUILayout() {
addSubview(stackView)
stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8).isActive = true
stackView.topAnchor.constraint(equalTo: topAnchor, constant: 8).isActive = true
stackView.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: -8).isActive = true
stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8).isActive = true
for type in types {
let typeView = createView(for: type)
stackView.addArrangedSubview(typeView)
}
}
private func createView(for type: PokemonType) -> UIView {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 10
if let colorCode = type.getRGBColorCode() {
view.backgroundColor = UIColor(red: CGFloat(integerLiteral: colorCode.red) / 255,
green: CGFloat(integerLiteral: colorCode.green) / 255,
blue: CGFloat(integerLiteral: colorCode.blue) / 255,
alpha: 1)
}
let colorNameLabel = UILabel()
colorNameLabel.translatesAutoresizingMaskIntoConstraints = false
colorNameLabel.textColor = .white
colorNameLabel.text = type.rawValue.localizedUppercase
view.addSubview(colorNameLabel)
colorNameLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
colorNameLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8).isActive = true
colorNameLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8).isActive = true
colorNameLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
colorNameLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 8).isActive = true
return view
}
}
|
Java
|
UTF-8
| 4,831
| 2.078125
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2020. Hartmut Lang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.hartmut.schelde.core.loader;
import de.hartmut.schelde.core.db.FileInfo;
import de.hartmut.schelde.core.db.FileInfoRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import reactor.core.publisher.Flux;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
/**
* hartmut on 10.02.18.
*/
@Service
public class FileService {
private static final Logger LOGGER = LoggerFactory.getLogger(FileService.class);
private final FileInfoRepository fileInfoRepository;
private Flux<FileEvent> eventFlux;
private List<FileEventListener> listeners = new ArrayList<>();
public FileService(FileInfoRepository fileInfoRepository) {
this.fileInfoRepository = fileInfoRepository;
}
@PostConstruct
public void init() {
LOGGER.debug("init()");
eventFlux = Flux.push(sink -> {
registerListener(new FileEventListener() {
@Override
public void onDataChunk(List<FileEvent> chunk) {
chunk.forEach(event -> sink.next(event));
}
@Override
public void processComplete() {
sink.complete();
}
});
});
}
private void registerListener(FileEventListener listener) {
listeners.add(listener);
}
public void addOrUpdate(Path path) {
LOGGER.debug("addOrUpdate(): {}", path);
try {
if (Files.isRegularFile(path) && !Files.isHidden(path)) {
String md5Digest = DigestUtils.md5DigestAsHex(path.toAbsolutePath().toString().getBytes(StandardCharsets.UTF_8));
FileInfo fileInfo = new FileInfo();
fileInfo.setFileName(path.getFileName().toString());
fileInfo.setFileSize(Files.size(path));
fileInfo.setModTime(
Date.from(Files.getLastModifiedTime(path).toInstant()));
fileInfo.setPath(path.toAbsolutePath().toString());
fileInfo.setDigest(md5Digest);
addOrUpdate(fileInfo);
}
} catch (IOException ex) {
LOGGER.warn("addOrUpdate(): failed!", ex);
}
}
private void addOrUpdate(FileInfo fileInfo) {
Optional<FileInfo> fileInfoOpt = fileInfoRepository.findByFileName(fileInfo.getFileName());
if (fileInfoOpt.isPresent()) {
FileInfo fileInfoExisting = fileInfoOpt.get();
if (!fileInfoExisting.equals(fileInfo)) {
LOGGER.debug("addOrUpdate(): update {}", fileInfo.getFileName());
fileInfoExisting.setModTime(fileInfo.getModTime());
fileInfoExisting.setFileSize(fileInfo.getFileSize());
fileInfoRepository.save(fileInfoExisting);
}
} else {
LOGGER.debug("addOrUpdate(): add {}", fileInfo.getFileName());
fileInfoRepository.save(fileInfo);
}
publishEvent(fileInfo.getFileName());
}
public void removeFile(Path path) {
LOGGER.debug("removeFile(): {}", path);
String filename = path.getFileName().toString();
Optional<FileInfo> fileInfoOpt = fileInfoRepository.findByFileName(filename);
if (fileInfoOpt.isPresent()) {
fileInfoRepository.delete(fileInfoOpt.get());
publishEvent(filename);
}
}
private void publishEvent(String fileName) {
LOGGER.trace("publishEvent(): for {}", fileName);
FileEvent fileEvent = new FileEvent();
fileEvent.setFilename(fileName);
listeners.forEach(listener -> listener.onDataChunk(Collections.singletonList(fileEvent)));
}
public Flux<FileEvent> getEventFlux() {
return eventFlux;
}
private interface FileEventListener {
void onDataChunk(List<FileEvent> chunk);
void processComplete();
}
}
|
C
|
UTF-8
| 335
| 2.953125
| 3
|
[] |
no_license
|
#include<stdio.h>
int main()
{
int n,i,y;
scanf("%d",&n);
int a[2*n];
for(i=0;i<2*n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<2*n;i=i+2)
{
y=a[i];
a[i]=a[i+1];
if(y>a[i])printf(">\n");
else if(y<a[i])printf("<\n");
else
printf("=\n");
}
}
|
TypeScript
|
UTF-8
| 793
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
const uuidRegExp = new RegExp('UUID="([^"]+)"');
const locationRegExp = new RegExp('Location="([^"]+)"');
const zonenameRegExp = new RegExp('ZoneName="([^"]+)"');
const invisibleRegExp = new RegExp('Invisible="([^"]+)"');
export default class ZoneGroupMember {
public static fromXML(xml: string): ZoneGroupMember {
if (invisibleRegExp.exec(xml)) {
return null;
}
const uuid = uuidRegExp.exec(xml)[1];
const location = locationRegExp.exec(xml)[1];
const zonename = zonenameRegExp.exec(xml)[1];
return new ZoneGroupMember(uuid, location, zonename);
}
constructor(public uuid: string, public location: string, public zonename: string) {}
public getIp(): string {
return this.location.split("/")[2];
}
}
|
Markdown
|
UTF-8
| 1,002
| 2.859375
| 3
|
[] |
no_license
|
# hbo-newsletter v-1
This program is responsible for newsletter preparation. It automaticly creates new html files, containing static links in place of photos delivered by template. All it needs, is delivered html templates and csv files with names and urls from static cms storage.
- To use this script, you need to run npm install first.
- Paste 3 html template files inside main folder of app. Name them hbo-3.html, hbo-4.html and hbo-5.html.
- Upload to cms all photos, that need to be placed in newsletter.
- Export all photos from cms for one newsletter only, and keep just file_name and url datas. You need 3 seperate files.
- Paste 3 exported csv files inside main folder. Name them data-3.csv, data-4.csv and data-5.csv.
- From main directory, run node runner.js.
- Program will generate 3 new html files in main folder. Those files has all photos exchanged for static links.
This is program is during development. Will be improved asap. This verison is stable.
Good Luck & Have Fun
|
Python
|
UTF-8
| 1,306
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
from matplotlib import pyplot as plt
import csv
import numpy as np
filename = r"C:\Users\cmcpa\OneDrive\Desktop\cte_data2_short.txt"
file = open(filename, 'r')
data = csv.reader(file)
data_points = []
for line in data:
data_points.append(float(line[0].split(' ')[-1]))
cte_values = np.array(data_points)
time_values = np.arange(len(cte_values))
Kp = 0.19
Ki = 0.0016
Kd = 4.3
prev_cte = 0;
p_contribution = []
i_contribution = []
i_sum = 0
d_contribution = []
steer_values = []
for cte in cte_values:
p_contribution.append(-cte*Kp)
i_sum += cte
if i_sum < -150 or i_sum > 150:
i_sum -= cte
i_contribution.append(-i_sum*Ki)
d_contribution.append(-Kd*(cte-prev_cte))
steer_values.append(-cte*Kp -i_sum*Ki -Kd*(cte-prev_cte))
prev_cte = cte
plt.ylim(-3.0, 3.0)
cte_plot, = plt.plot(time_values, cte_values, linewidth=2.0, label='CTE',color='r')
p_plot, = plt.plot(time_values, p_contribution, color='blue', linestyle='--', label='P')
i_plot, = plt.plot(time_values, i_contribution, color='gray', linestyle='--', label='I')
d_plot, = plt.plot(time_values, d_contribution, color='green', linestyle='--', label='D')
steer_plot, = plt.plot(time_values, steer_values, color='purple', label='Steer value')
plt.legend(handles=[cte_plot, p_plot, i_plot, d_plot, steer_plot])
plt.grid(True)
plt.show()
|
Markdown
|
UTF-8
| 2,217
| 2.921875
| 3
|
[] |
no_license
|
---
title: "Random Dentist Experience"
date: 2019-08-05T12:22:22+05:00
draft: false
author: Alexander
tags:
- random
- dentist
- experience
---
## This time
So I was about to visit a dentist today.
It was my last visit in this "session".
And I needed to fix a wisdom tooth.
And I randomly recollected that at some point in the past when a dentist was injecting anesthesia
it felt like they are injecting the needle right into the bone.
And since this was my last visit I felt like experimentating and not injecting anything this time.
But I wasn't sure if I will really decide to not use it.
In the end the decision was not that hard.
And I got two observations from it.
### 1. Danger overrides pain
(needle + hard to access tooth + recollection ~ danger);
Experimenting thing would not overwrite it in my case. I am not that hardcore.
But it was not danger by itself what informed my decision.
It only kept me from flaking :).
### 2. Middle-ish-intensity not-long pain was more like an attention signal, not like something important at all
I was focused on two other things - jaw position and throat state.
So pain was more like a signal to give attention there but there was nothing unexpected anyway.
## Some previous time
I do not plan to have a series of dentist posts at this point.
But I'd like to record previous experiences as well.
One was when I was really affected by it.
So I felt like I'm surrounded by enemies and every time after they were stopping
I had to remind myself that everybody around is acting in my interests as well.
I probably also was kind of vividly focusing on pain and what exactly they were doing.
And you get some kind of high after it is over.
Another time I got anesthesia and it didn't really work.
So I felt it but I was content.
Either because I was relaxed because I expected it to work (and there was nothing else to do anyway).
Or because the nature of that anesthesia - but that is unlikely.
## Summary
- experimenting/relaxed mindset is probably a good idea;
- pain fear/avoidance is overrided by expectation of danger;
- keeping track of dentist but not focusing exactly on their "working area" but on other bodily matters instead seems to be a good idea;
|
Markdown
|
UTF-8
| 785
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
# UNO
Uno is an American shedding-type card game that is played with a specially printed deck. The game's general principles put it into the Crazy Eights family of card games, and it is similar to the traditional European game Mau-Mau.
# Description
This game was developed in the spring of 2020 for AP assignment.
# Code
I used object-oriented programming to develop this game.
# Screenshots





# Abilities
1. Playing with Bots
2. MultiPlayer
# Note
This is not a GUI. This is just a console application.
Enjoy!
|
C#
|
UTF-8
| 1,788
| 2.546875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace GDLibrary
{
public class RailCamera3D : Camera3D
{
private RailParameters railParameters;
private Actor targetActor;
public RailCamera3D(string id, ObjectType objectType,
Transform3D transform, ProjectionParameters projectionParameters,
Viewport viewPort, RailParameters railParameters, Actor targetActor)
: base(id, objectType, transform, projectionParameters, viewPort)
{
this.railParameters = railParameters;
this.targetActor = targetActor;
//put the camera on the rail mid point
this.Transform3D.Translation = railParameters.MidPoint;
}
public override void Update(GameTime gameTime)
{
//get look vector to target
Vector3 cameraToTarget = CameraUtility.GetCameraToTarget(this.targetActor.Transform3D, this.Transform3D);
//new position for camera if it is positioned between start and the end points of the rail
Vector3 projectedCameraPosition = this.Transform3D.Translation
+ Vector3.Dot(cameraToTarget, railParameters.Look) * railParameters.Look * gameTime.ElapsedGameTime.Milliseconds;
//do not allow the camera to move outside the rail
if (railParameters.InsideRail(projectedCameraPosition))
this.Transform3D.Translation = projectedCameraPosition;
//set the camera to look at the object
this.Transform3D.Look = cameraToTarget;
//bug - set the up vector???
base.Update(gameTime);
}
}
}
|
C#
|
UTF-8
| 1,264
| 2.640625
| 3
|
[] |
no_license
|
using System.Collections.Generic;
using System.Linq;
using DAL.Entities;
using DAL.Interfaces;
using MyMenu.DAL.EF;
namespace DAL.Repositories
{
public class RecipeClientProfileManager:IRecipeClientProfileManager
{
public ApplicationContext Database { get; set; }
public RecipeClientProfileManager(ApplicationContext db)
{
Database = db;
}
public void Create(RecipeClientProfile item)
{
Database.RecipeClientProfiles.Add(item);
Database.SaveChanges();
}
public void Dispose()
{
Database.Dispose();
}
public RecipeClientProfile FindByRecipeAndUserId(string userId, int recipeId)
{
var result = Database.RecipeClientProfiles.Find( userId, recipeId);
return result;
}
public List<RecipeClientProfile> FindRecipesByUserId(string userId)
{
var result = Database.RecipeClientProfiles.Where(x => x.Id == userId).ToList();
return result;
}
public void Remove(RecipeClientProfile recipeUser)
{
Database.RecipeClientProfiles.Remove(recipeUser);
Database.SaveChanges();
}
}
}
|
JavaScript
|
UTF-8
| 2,931
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
function doExample1() {
doFlipAnimation();
}
function doFlipAnimation( ) {
if ( myVarFlip === undefined ) {
var makeAnimation = function ( ) {
myContext2.translate( myImage.width, myImage.height );
myContext2.rotate( Math.PI );
myContext2.drawImage( myImage, 0, 0, myImage.width, myImage.height );
myVarFlip = setTimeout( makeAnimation, 500 );
}
myVarFlip = setTimeout( makeAnimation, 500 );
}
else myVarFlip = clearTimeout( myVarFlip );
}
var dAngle = Math.PI / 180;
function doExample2() {
doRotationAnimation();
}
function doRotationAnimation( ) {
if ( myVarRotation === undefined ) {
const makeAnimation = function ( ) {
myContext2.fillStyle = "#CCCCCC";
myContext2.fillRect( 0, 0, myCanvas2.width, myCanvas2.height );
myContext2.translate( myImage.width / 2, myImage.height / 2 );
myContext2.rotate( dAngle );
myContext2.translate( -myImage.width / 2, -myImage.height / 2 );
myContext2.drawImage( myImage, 0, 0, myImage.width, myImage.height );
myVarRotation = setTimeout( makeAnimation, 200 );
}
myVarRotation = setTimeout( makeAnimation, 200 );
}
else myVarRotation = clearTimeout( myVarRotation );
}
function doExample3() {
doRotation1();
}
function doRotation1( ) {
doClear( );
for ( let xe = 0; xe < myWidth; xe++ ) { // ( x, y ) -> ( 255 - y, x )
for ( let ye = 0; ye < myHeight; ye++ ) {
let pixel = myContext1.getImageData( xe, ye, 1, 1 );
let DataIN = pixel.data;
let r = DataIN[ 0 ];
let g = DataIN[ 1 ];
let b = DataIN[ 2 ];
myContext2.fillStyle = "rgba( " + r + "," + g + "," + b + "," + 1 + " )";
myContext2.fillRect( 255 - ye, xe, 1, 1 );
}
}
}
function doExample4() {
doRotation2();
}
function doRotation2( ) {
doClear( );
var myImageDataIN = myContext1.getImageData( 0, 0, myCanvas1.width, myCanvas1.height );
var myImageDataOUT = myContext1.getImageData( 0, 0, myCanvas1.width, myCanvas1.height );
var myDataIN = myImageDataIN.data;
var myDataOUT = myImageDataOUT.data;
for ( let i = 0; i < myDataIN.length; i += 4 ) { // ( x, y ) -> ( 255 - y, x )
let xe = Math.floor( i / 4 ) % myWidth;
let ye = Math.floor( Math.floor( i / 4 ) / myWidth );
myDataOUT[ ( ( myWidth * xe ) + ( 255 - ye ) ) * 4] = myDataIN[i];
myDataOUT[ ( ( myWidth * xe ) + ( 255 - ye ) ) * 4 + 1 ] = myDataIN[ i + 1 ];
myDataOUT[ ( ( myWidth * xe ) + ( 255 - ye ) ) * 4 + 2 ] = myDataIN[ i + 2 ];
myDataOUT[ ( ( myWidth * xe ) + ( 255 - ye ) ) * 4 + 3 ] = myDataIN[ i + 3 ];
}
myContext2.putImageData( myImageDataOUT, 0, 0 );
}
|
Java
|
UTF-8
| 4,558
| 2.328125
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package com.sjwitservices.guiceutils.childinjectortools.destroyable;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PreDestroy;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class DestroyableComponentLifecycleManagerTest {
@Mock
DestroyableComponentSingletonSource singletonSource;
@Mock
PreDestroyMethodFinder preDestroyFinder;
@Mock IllegalArgumentException illegalArgException;
@Mock InvocationTargetException methodInvokationException;
ClassWithAnnotatedPreDestroy preDestroyClass = new ClassWithAnnotatedPreDestroy();
Method method;
Method exceptionMethod;
List<Object> singletonList;
DestroyableComponentLifecycleManager manager;
@Before
public void find_test_methods() throws NoSuchMethodException {
method = preDestroyClass.getClass().getDeclaredMethod("destroy");
exceptionMethod = preDestroyClass.getClass().getDeclaredMethod("throwError");
}
@Before
public void initialise_singleton_list() {
singletonList = new ArrayList<Object>();
singletonList.add(preDestroyClass);
when(singletonSource.getDestroyableComponents()).thenReturn(singletonList);
}
@Test
public void calling_start_invokes_getDestroyableComponentSingletons_from_singletonSource() {
initialise_manager();
manager.start();
verify(singletonSource).getDestroyableComponents();
}
@Test
public void calling_end_before_calling_start_does_not_interact_with_the_preDestroyFinder() {
initialise_manager();
manager.end();
Mockito.verifyNoMoreInteractions(preDestroyFinder);
}
@Test
public void calling_end_destroys_any_scoped_objects_with_pre_destroy_annotated_methods() throws Exception {
when_getPreDstroy_method_for_pre_destroy_class_return(method);
initialise_manager_and_destroy_component_singletons();
assertThat(preDestroyClass.isDestroyed, is(true));
}
private void initialise_manager() {
manager = new DestroyableComponentLifecycleManager(singletonSource, preDestroyFinder);
}
@Test
public void calling_end_does_not_destroy_scoped_object_without_a_predestroy_annotation() throws Exception {
when_getPreDstroy_method_for_pre_destroy_class_return(null);
initialise_manager_and_destroy_component_singletons();
assertThat(preDestroyClass.isDestroyed, is(false));
}
@Test
public void when_call_end_and_the_preDestroyFinder_get_method_throws_illegal_arg_exception_then_a_destroying_component_singleton_exception_is_thrown_containing_illegal_arg_exception() {
when(preDestroyFinder.getMethod(any(Class.class))).thenThrow(illegalArgException);
try {
initialise_manager_and_destroy_component_singletons();
} catch (DestroyingSingletonComponentException e) {
assertThat(e.getThrownExceptions(), contains((Exception) illegalArgException));
}
}
@Test
public void when_call_end_and_method_invokation_throws_exception_then_a_destroying_component_singleton_exception_is_thrown_containing_method_exception() {
when_getPreDstroy_method_for_pre_destroy_class_return(exceptionMethod);
try {
initialise_manager_and_destroy_component_singletons();
} catch (DestroyingSingletonComponentException e) {
assertEquals(e.getThrownExceptions().get(0).getClass(), InvocationTargetException.class);
}
}
private void initialise_manager_and_destroy_component_singletons() {
initialise_manager();
manager.start();
manager.end();
}
private void when_getPreDstroy_method_for_pre_destroy_class_return(Method method) {
when(preDestroyFinder.getMethod(Mockito.any(Class.class))).thenReturn(method);
}
private class ClassWithAnnotatedPreDestroy {
boolean isDestroyed = false;
@PreDestroy
public void destroy() {
isDestroyed = true;
}
//This is actually used but IDE complained about it not being used. Just leave the supress
//and all is well.
@SuppressWarnings("unused")
public void throwError() throws Exception {
throw new Exception();
}
}
}
|
C
|
UTF-8
| 1,625
| 4.15625
| 4
|
[] |
no_license
|
/* Gabriel Pellegrino da Silva Ra - 172358
O programa a seguir armazena dinamicamente os valores de uma
matriz triangular inferior. Calcula a sua normalizacao e em seguida
imprime o resultado, bem como o valor da media e o desvio padrao.
Sendo a[ij] a matriz lida, e b[ij] a matriz impressa.
(2) b[ij]= (a[ij]- media)/desvio;
(1) desvio padrao = ((somatorio(x[i]-media)^2)/(n*n+n)/2)^(1/2);
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
int n, i, j; // n eh o numero de linhas da matriz, i e j sao auxiliares para percorrer essa matriz
double **vetor, media=0, desvio=0;
scanf("%d", &n);
vetor = malloc(sizeof(double*)*n); // alocando dinamicamente apontadores de apontadores para double
for(i=0, j=1; j<=n; i++, j++)
*(vetor+i) = malloc(sizeof(double)*j); // alocando os apontadores para double
for(i=0; i<n; i++)
for(j=0; j<(i+1); j++) {
scanf("%lf", &vetor[i][j]); // preenchendo as regioes dos apontadores com doubles
media+=vetor[i][j]; // somando os valores
}
media/=(n*n+n)/2; // ...dividir e calcular a media
for(i=0; i<n; i++)
for(j=0; j<(i+1); j++)
desvio+=pow((vetor[i][j]-media),2); // utilizando a formula do cabecalho para desvio padrao(1)
desvio/=(n*n+n)/2;
desvio=sqrt(desvio);
for(i=0; i<n; i++) {
for(j=0; j<(i+1); j++)
printf("%.12lf ",(vetor[i][j]-media)/desvio); // usando (2) para normalizar os valores a serem impressos
free(vetor[i]); // liberando cada apontar de double
printf("\n");
}
free(vetor); // liberando o apontador de apontadores de double
printf("\n%.12lf %.12lf \n", media, desvio);
return 0;
}
|
JavaScript
|
UTF-8
| 182
| 3.140625
| 3
|
[] |
no_license
|
const outra = []
for (let loka = 0; loka <10; loka++){
outra.push(function() {
console.log(loka)
console.log(typeof loka)
})
}
outra[2]()
outra[8]()
|
Java
|
UTF-8
| 375
| 3.21875
| 3
|
[] |
no_license
|
package package1;
public class compareArray1Element
{
public static void main(String[] args)
{
int [] a = {10,45,12,47,50,55};
int [] b = {15,10,12,49,55,75,56};
int l1 = a.length;
int l2 = b.length;
for(int i=0; i< l1; i++)
{
for(int j =0; j< l2; j++)
{
if(a[i] == b[j])
{
System.out.println(a[i]);
}
}
}
}
}
|
Java
|
UTF-8
| 283
| 1.789063
| 2
|
[] |
no_license
|
package com.github;
import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;
public class App3 {
public static void main(String[] args) {
ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
System.out.println(iLoggerFactory);
}
}
|
PHP
|
UTF-8
| 686
| 2.65625
| 3
|
[] |
no_license
|
<?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* Pertanyaan Entity
*
* @property int $key_pertanyaan
* @property int $key_materi
* @property string $pertanyaan
*/
class Pertanyaan extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* @var array
*/
protected $_accessible = [
'key_materi' => true,
'pertanyaan' => true
];
}
|
Python
|
UTF-8
| 159
| 3.609375
| 4
|
[
"Apache-2.0"
] |
permissive
|
# append token to a file newline
def append_to_file(file, token):
file_object = open(file, "a")
file_object.write(token + "\n")
file_object.close()
|
C++
|
UTF-8
| 5,034
| 3.59375
| 4
|
[] |
no_license
|
#include <iostream>
#include <string>
#include <limits>
#include <Windows.h>
#define OFFSET 3
using namespace std;
class Member
{
private:
string name;
char group;
string habitat;
int population;
public:
string GetName()
{
return name;
}
void SetName(string value)
{
if(value != "")
name = value;
}
char GetGroup()
{
return group;
}
void SetGroup(char value)
{
if (value != ' ')
group = value;
}
string GetHabitat()
{
return habitat;
}
void SetHabitat(string value)
{
if (value != "")
habitat = value;
}
int GetPopulation()
{
return population;
}
void SetPopulation(int value)
{
if (value >= 0)
population = value;
}
void Show()
{
cout << "Имя: " << name;
cout << "Группа: " << group;
cout << "Место обитания: " << habitat;
cout << "Популяция: " << population;
}
friend istream& operator >>(istream& is, Member& m)
{
while (true)
{
is >> m.name >> m.group >> m.habitat >> m.population;
if (is.fail())
{
cout << "Ошибка ввода данных, попробуйте еще раз\n";
is.clear();
is.ignore(INT16_MAX, '\n');
continue;
}
break;
}
return is;
}
};
void DrawLine(int width);
void DrawMember(string text, int width);
void FindWidth(Member* members, int membersSize, int& first, int& third, int& fourth);
void DrawNote(string note, int totalWidth);
int main()
{
setlocale(LC_ALL, "Russian");
int size;
string name = "Название", group = "Группа", habitat = "Место обитания", population = "Популяция", note = "Групи: А - настоящие антилопы, B - коровьи антилопы, H - лошадиные антилопи";
int firstMemberWidth = name.size(), secondMemberWidth = group.size(), thirdMemberWidth = habitat.size(), fourthMemberWidth = population.size();
cout << "Введите количество элементов:\n";
while (true)
{
cin >> size;
if (cin.fail())
{
cout << "Ошибка ввода данных, попробуйте еще раз\n";
cin.clear();
cin.ignore(INT16_MAX, '\n');
continue;
}
break;
}
Member* members = new Member[size];
for (int i = 0; i < size; ++i)
{
cout << i + 1 << ". Введите данные -> Имя -> Группа -> Место обитания -> Популяция:\n";
cin >> members[i];
}
FindWidth(members, size, firstMemberWidth, thirdMemberWidth, fourthMemberWidth);
int totalWidth = firstMemberWidth + secondMemberWidth + thirdMemberWidth + fourthMemberWidth;
int noteSize = note.size();
totalWidth = totalWidth < noteSize ? noteSize : totalWidth;
fourthMemberWidth = totalWidth - (firstMemberWidth + secondMemberWidth + thirdMemberWidth);
DrawLine(totalWidth);
cout << '|';
DrawMember(name, firstMemberWidth);
DrawMember(group, secondMemberWidth);
DrawMember(habitat, thirdMemberWidth);
DrawMember(population, fourthMemberWidth);
cout << '\n';
for (int i = 0; i < size; ++i)
{
DrawLine(totalWidth);
cout << '|';
DrawMember(members[i].GetName(), firstMemberWidth);
DrawMember(string(1, members[i].GetGroup()), secondMemberWidth);
DrawMember(members[i].GetHabitat(), thirdMemberWidth);
DrawMember(to_string(members[i].GetPopulation()), fourthMemberWidth);
cout << '\n';
}
DrawNote(note, totalWidth);
return 0;
}
void FindWidth(Member* members, int membersSize, int& first, int& third, int& fourth)
{
for (int i = 0; i < membersSize; ++i)
{
if (members[i].GetName().size() > first)
first = members[i].GetName().size();
}
for (int i = 0; i < membersSize; ++i)
{
if (members[i].GetHabitat().size() > third)
third = members[i].GetHabitat().size();
}
for (int i = 0; i < membersSize; ++i)
{
if (to_string(members[i].GetPopulation()).size() > fourth)
fourth = to_string(members[i].GetPopulation()).size();
}
}
void DrawMember(string text, int width)
{
cout << text;
for (int i = 0; i < width - text.size(); i++)
cout << ' ';
cout << '|';
}
void DrawLine(int width)
{
cout << '|';
width += OFFSET;
for (int i = 0; i < width; ++i)
cout << '=';
cout << "|\n";
}
void DrawNote(string note, int totalWidth)
{
DrawLine(totalWidth);
cout << '|' << note;
for (int i = 0; i < totalWidth - note.size() + OFFSET; i++)
cout << ' ';
cout << "|\n";
DrawLine(totalWidth);
}
|
PHP
|
UTF-8
| 573
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Middleware;
use Closure;
class API
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// dump($request);die;
$user = \App\Models\UsersAPI::findOneBy([ 'username' => $request->input('username'), 'token' => $request->input('token') ]);
if (!$user) {
return response('Unauthorized.', 401);
}
return $next($request);
}
}
|
Markdown
|
UTF-8
| 16,809
| 2.6875
| 3
|
[] |
no_license
|
# Laporan Praktikum #4 - Relasi Kelas
## Kompetensi
Setelah menempuh pokok bahasan ini, mahasiswa mampu:
1. Memahami konsep relasi kelas.
2. Mengimplementasikan relasi has‑a dalam program.
## Ringkasan Materi
Pada bagian tugas saya hanya kebingunan mengapa untuk mendeklarasikan kode kamar apakah perlu membuat class Hotel1? Sebab saya sudah mencoba agar program tersebut berjalan namun hasilnya sama saja

## Percobaan
### Percobaan 1
Pada percobaan pertama saya membuat dua buah class bernama Processor1841720085Falaah dan Laptop1841720085Falaah. Pada class Processor1841720085Falaah memiliki konstruktor default dan juga konstruktor berparameter yang memiliki nama sama dengan nama classnya selain itu terdapat juga atribut bernama merk dengan tipe data string dan cache dengan tipe data double, dan juga memiliki method getter dan setter dengan nama getMerkFalaah(), getCacheFalaah(), setMerkFalaah(), setCacheFalaah(), dan infoFalaah() untuk menampilkan status pada class processor. Class Laptop1841720085Falaah memiliki konstruktor berparameter dengan nama yang juga sama dengan classnya dan atribut bernama merk dengan tipe data integer dan atribut proc dengan tipe data Processor1841720085Falaah yang merupakan class yang digunakan sebagai tipe data atribut tersebut, untuk method yang terdapat pada class ini terdapat method getter dan setter juga, nama method tersebut adalah getMerkFalaah(), getProcFalaah(), setMerkFalaah(), setProcFalaah(), dan infoFalaah(). Selain itu saya juga membuat main class yang bernama MainPercobaan1 untuk memanggil fungsi method yang ada pada class Processor1841720085Falaah dan juga Laptop1841720085Falaah.

Contoh link kode program pada class Processor1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/P1/Processor1841720085Falaah.java)
Contoh link kode program pada class Laptop1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/P1/Laptop1841720085Falaah.java)
Contoh link kode program pada main class MainPercobaan1.java : [Klik disini](../../src/4_Relasi_Class/P1/MainPercobaan1.java)
### Pertanyaan
Berdasarkan percobaan 1, jawablah pertanyaan‑pertanyaan yang terkait:
1. Di dalam class Processor dan class Laptop1841720085Falaah, terdapat method setter dan getter untuk masing‑masing atributnya. Apakah gunanya method setter dan getter tersebut ?
Jawab:
Kegunaan dari method Setter adalah mengambil nilai dari atribut yang ada pada main class dan kegunaan method getter adalah untuk mengembalikan atau menampilkan nilai dari class yang sebelumnya telah mengambil nilai dari atribut main class.
2. Di dalam class Processor dan class Laptop1841720085Falaah, masing‑masing terdapat konstruktor default dan konstruktor berparameter. Bagaimanakah beda penggunaan dari kedua jenis konstruktor tersebut ?
Jawab:
Kegunaan dari kedua konstruktor adalah jika konstruktor default digunakan pada saat melakukan inisialisasi objek maka yang di inisialisasi adalah semua objek yang ada pada class.
Sedangkan konstruktor berparameter digunakan pada saat melakukan inisialisasi objek dengan ketentuan tertentu yang hanya beberapa objek saja yang akan di inisialisasikan.
3. Perhatikan class Laptop1841720085Falaah, di antara 2 atribut yang dimiliki (merk dan proc), atribut manakah yang bertipe object ?
Jawab:
Yang merupakan atribut bertipe objek adalah atribut bernama proc
4. Perhatikan class Laptop1841720085Falaah, pada baris manakah yang menunjukan bahwa class Laptop1841720085Falaah memiliki relasi dengan class Processor1841720085Falaah ?
Jawab:
Baris yang memiliki menunjukkan bahwa class Laptop1841720085Falaah memiliki relasi dengan class Processor1841720085Falaah adalah pada baris ke 14 yang bertuliskan
private Processor1841720085Falaah proc;

5. Perhatikan pada class Laptop1841720085Falaah , Apakah guna dari sintaks proc.infoFalaah() ?
Jawab:
Fungsi dari sintaks infoFalaah.info() adalah digunakan untuk memanggil method infoFalaah() yang ada pada class Processor1841720085Falaah.
6. Pada class MainPercobaan1, terdapat baris kode: Laptop1841720085Falaah l = new Laptop1841720085Falaah("Thinkpad", p);. Apakah p tersebut ? Dan apakah yang terjadi jika baris kode tersebut diubah menjadi:
Laptop1841720085Falaah l = new Laptop1841720085Falaah("Thinkpad", new Processor("Intel i5", 3)); Bagaimanakah hasil program saat dijalankan, apakah ada perubahan ?
Jawab:
Huruf p yang ada pada baris kode
Laptop1841720085Falaah l = new Laptop1841720085Falaah("Thinkpad", p);
memiliki fungsi : untuk menginputakan pada konstruktor Processor1841720085Falaah kedalam konstruktor Laptop1841720085Falaah dengan melakukan inisialisasinya, jika baris diubah menjadi
Laptop1841720085Falaah l = new Laptop1841720085Falaah("Thinkpad", new Processor("Intel i5", 3));
yang terjadi adalah sama dengan yang dibuat pada awalnya.
### Percobaan 2
Pada percobaan kedua yang akan saya lakukan adalah membuat tiga buah class dan satu buah Main class yang pertama adalah class yang bernama Mobil1841720085Falaah yang memiliki atribut merk dengan tipe data String dan biaya dengan tipe data integer, terdapat pula onstruktor default, method getter setter, dan juga method hitungBiayaMobilFalaah() untuk menghitung biaya mobil, kedua adalah class bernama Sopir1841720085Falaah yang memiliki atribut nama dengan tipe data String dan biaya dengan tipe data integer, selain atribut terdapat konstruktor default, method getter setter, dan juga method hitungBiayaSopirFalaah() untuk menghitung biaya pada class Sopir1841720085Falaah, ketiga adalah class Pelanggan1841720085Falaah terdapat empat atribut yaitu antara lain nama dengan tipe data String, mobil dengan tipe data class Mobil1841720085Falaah, sopir dengan tipe data class Sopir1841720085Falaah, hari dengan tipe data integer, selain atribut terdapat juga method getter setter dan method hitungBiayaTotal() untuk menghitung biaya total dari penjumlahan antara method hitungBiayaMobilFalaah() dan hitungBiayaSopirFalaah(). Untuk Main class sendiri memiliki nama MainPercobaan2 yang berfungsi untuk menginputkan nilai pada atribut dan menampilkan hasil akhir yang telah dieksekusi oleh setiap method pada setiap class.

Contoh link kode program pada class Mobil1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/P2/Mobil1841720085Falaah.java)
Contoh link kode program pada class Sopir1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/P2/Sopir1841720085Falaah.java)
Contoh link kode program pada class Pelanggan1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/P2/Pelanggan1841720085Falaah.java)
Contoh link kode program pada main class MainPercobaan2.java : [Klik disini](../../src/4_Relasi_Class/P2/MainPercobaan2.java)
### Pertanyaan
1. Perhatikan class Pelanggan. Pada baris program manakah yang menunjukan bahwa class Pelanggan1841720085Falaah memiliki relasi dengan class Mobil1841720085Falaah dan class Sopir1841720085Falaah ?
Jawab:
Yang menunjukkan bahwa class Pelanggan1841720085Falaah memiliki relasi dengan class Mobil1841720085Falaah dan class Sopir1841720085Falaah adalah pada baris ke 14 dan 15 dengan sintaks
private Mobil1841720085Falaah mobil;
private Sopir1841720085Falaah sopir;

2. Perhatikan method hitungBiayaSopirFalaah pada class Sopir1841720085Falaah, serta method hitungBiayaMobilFalaah pada class Mobil1841720085Falaah. Mengapa menurut Anda method tersebut harus memiliki argument hari ?
Jawab:
Alasan mengapa harus memiliki argumen hari adalah karena pada method karena biaya yang dibayar tergantung pada harinya sehingga inputan hari sebagai patokan atau inputan untuk menentukan berapa biaya total yang harus dibayarkan.
3. Perhatikan kode dari class Pelanggan1841720085Falaah. Untuk apakah perintah mobil.hitungBiayaMobilFalaah(hari) dan sopir.hitungBiayaSopirFalaah(hari) ?
Jawab:
Untuk menghitung berapa biaya yang harus dibayarkan dari kedua class, dengan cara nilai dari atribut biaya dikalikan dengan atribut hari.
4. Perhatikan class MainPercobaan2. Untuk apakah sintaks p.setMobilFalaah(m) dan p.setSopirFalaah(s) ?
Jawab:
Untuk menginputkan nilai dari atribut m dan juga s yang sebelumnya sudah diisikan pada konstruktor Mobil1841720085Falaah dan juga Sopir1841720085Falaah.
5. Perhatikan class MainPercobaan2. Untuk apakah proses p.hitungBiayaTotalFalaah() tersebut ?
Jawab:
Untuk menghitung biaya total dari kedua method dari class Mobil1841720085Falaah dan juga Sopir1841720085Falaah yang sebelumya sudah dihitung dan tinggal menjumlahkan hasilnya dari kedua method yaitu hitungBiayaMobilFalaah dan hitungBiayaSopirFalaah.
6. Perhatikan class MainPercobaan2, coba tambahkan pada baris terakhir dari method main dan amati perubahan saat di‑run!
System.out.println(p.getMobilFalaah().getMerkFalaah());
Jadi untuk apakah sintaks p.getMobilFalaah().getMerkFalaah() yang ada di dalam method main tersebut?
Jawab:
Perubahan yang terjadi setelah di run adalah akan muncul keluaran selain hasil dari biaya total yaitu memunculkan kata berupa "Avanza", fungsi dari sintaks itu sendiri adalah untuk memanggil nilai atribut pada merk.
### Percobaan 3
Pada percobaan ketiga ini saya membuat dua buah class yang bernama Pegawai1841720085Falaah dan KeretaApi1841720085Falaah dan juga saya membuat satu buah main class bernama MainPercobaan3. Pada Pegawai1841720085Falaah terdapat dua buah atribut yaitu atribut bernama nip dengan tipe data String dan nama dengan tipe data String. Selain atribut terdapat konstruktor berparameter, method getter setter dan juga method infoFalaah() untuk menampilkan nilai pada kedua atribut. Class KeretaApi1841720085Falaah mempunya 4 atribut yaitu nama dengan tipe data String, kelas dengan tipe data String, masinis dengan tipe data class Pegawai1841720085Falaah dan yang terakhir asisten dengan tipe data class Pegawai1841720085Falaah, selain atribut juga terdapat konstruktor 2 konstruktor berparameter 3 dan berparameter 4, method getter setter, juga method infoFalaah() untuk menampilkan informasi nilai pada setiap atribut.

Contoh link kode program pada class Pegawai1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/P3/Pegawai1841720085Falaah.java)
Contoh link kode program pada class KeretaApi1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/P3/KeretaApi1841720085Falaah.java)
Contoh link kode program pada main class MainPercobaan3.java : [Klik disini](../../src/4_Relasi_Class/P3/MainPercobaan3.java)
### Pertanyaan
1. Di dalam method infoFalaah() pada class KeretaApi, baris this.masinis.infoFalaah() dan this.asisten.infoFalaah() digunakan untuk apa ?
Jawab:
Dalam method infoFalaah() pada class KeretaApi1841720085Falaah, baris this.masinis.info() digunakan untuk memanggil infoFalaah pada class Pegawai1841720085Falaah dan this.asisten.infoFalaah() digunakan untuk memanggil info pada class Pegawai1841720085Falaah.
2. Buatlah main program baru dengan nama class MainPertanyaan pada package yang sama. Tambahkan kode berikut pada method main() !
Pegawai masinis = new Pegawai("1234", "Spongebob Squarepants");
KeretaApi keretaApi = new KeretaApi("Gaya Baru", "Bisnis", masinis);
System.out.println(keretaApi.info());
Jawab:

3. Apa hasil output dari main program tersebut ? Mengapa hal tersebut dapat terjadi ?
Jawab:
Output dari hasil program tersebut adalah terjadi error, hal tersebut terjadi adalah karena kesalahan dalam membuat konstruktor beserta nilai dari atributnya.
4. Perbaiki class KeretaApi sehingga program dapat berjalan !
jawab:

### Percobaan 4
Pada percobaan keempat ini saya membuat tiga buah class dan satu buah main class. Class yang pertama bernama Penumpang1841720085Falaah yang memiliki dua buah atribut yaitu ktp dengan tipe data String, nama dengan tipe data String, selain atribut terdapat konstruktor berparameter, method getter setter dan juga method infoFalaah() untuk menampilkan nilai dari kedua atribut. class yang kedua bernama Kursi1841720085Falaah memiliki dua atribut yaitu nomer dengan tipe data String dan penumpang dengan tipe data class Penumpang1841720085Falaah, ada satu konstruktor berparameter satu, method getter setter dan juga method infoFalaah() untuk menampilkan isi atau nilai pada atribut. class yang ketiga bernama Gerbong1841720085Falaah memiliki dua atribut yaitu kode dengan tipe data String dan arrayKursi dengan tipe data Kursi1841720085Falaah, terdapat satu konstruktor berparameter dua, method getter setter, method untuk array dengan nama initKursiFalaah(), method setPenumpangFalaah() dan juga infoFalaah() untuk menampilkan nilai dari atribut. Satu buah main class bernama MainPercobaan4 sebagai eksekusi untuk menginputkan dan menampilkan hasil dari pengolahan pada setiap class.

Contoh link kode program pada class Penumpang1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/P4/Penumpang1841720085Falaah.java)
Contoh link kode program pada class Kursi1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/P4/Kursi1841720085Falaah.java)
Contoh link kode program pada class Gerbong1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/P4/Gerbong1841720085Falaah.java)
Contoh link kode program pada class main MainPercobaan4.java : [Klik disini](../../src/4_Relasi_Class/P4/MainPercobaan4.java)
### Pertanyaan
1. Pada main program dalam class MainPercobaan4, berapakah jumlah kursi dalam Gerbong A ?
Jawab:
Jumlah kursi dalam gerbong sebanyak 10 kursi
2. Perhatikan potongan kode pada method infoFalaah() dalam class Kursi. Apa maksud kode tersebut ?
... if (this.penumpang != null) { info += "Penumpang: " + penumpang.infoFalaah() + "\n"; } ...
Jawab:
Maksud dari sintaks tersebut adalah jika atribut penumpang tidak sama dengan null maka info ditambahkan sama dengan penumpang dengan method infoFalaah().
3. Mengapa pada method setPenumpangFalaah() dalam class Gerbong1841720085Falaah, nilai nomor dikurangi dengan angka 1 ?
Jawab:
Karena index array sendiri dimulai dari angka nol
4. Instansiasi objek baru budi dengan tipe Penumpang, kemudian masukkan objek baru tersebut pada gerbong dengan gerbong.setPenumpang(budi, 1). Apakah yang terjadi ?
Jawab:
Data budi tetap akan keluar namun menggunakan urutan kursi yang digunakan oleh data lain atau orang lain
5. Modifikasi program sehingga tidak diperkenankan untuk menduduki kursi yang sudah ada penumpang lain !
Jawab:

## Tugas
Buatlah sebuah studi kasus, rancang dengan class diagram, kemudian implementasikan ke dalam program! Studi kasus harus mewakili relasi class dari percobaan‑percobaan yang telah dilakukan pada materi ini, setidaknya melibatkan minimal 4 class (class yang berisi main tidak dihitung).

Contoh link kode program pada class Kamar1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/Tugas/Kamar1841720085Falaah.java)
Contoh link kode program pada class Pegawai1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/Tugas/Pegawai1841720085Falaah.java)
Contoh link kode program pada class Pelanggan1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/Tugas/Pelanggan1841720085Falaah.java)
Contoh link kode program pada class Hotel1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/Tugas/Hotel1841720085Falaah.java)
Contoh link kode program pada main class MainTugas1841720085Falaah.java : [Klik disini](../../src/4_Relasi_Class/Tugas/MainTugas1841720085Falaah.java)
## Kesimpulan
Hal yang dapat saya simpulkan dari praktikum dan juga tugas yang telah dilakukan adalah dalam melaukakan suatu relasi kelas adalah dimana kita terlebih dahulu memperhatikan serta menentukan class diagram sebelum membuat sebuah program, karena class diagram merupakan dasar dalam perancangan atau pembuatan sebuah program.
## Pernyataan Diri
Saya menyatakan isi tugas, kode program, dan laporan praktikum ini dibuat oleh saya sendiri. Saya tidak melakukan plagiasi, kecurangan, menyalin/menggandakan milik orang lain.
Jika saya melakukan plagiasi, kecurangan, atau melanggar hak kekayaan intelektual, saya siap untuk mendapat sanksi atau hukuman sesuai peraturan perundang-undangan yang berlaku.
Ttd,
***Mukhammad Falaah Azmi***
|
Java
|
UTF-8
| 4,771
| 2.46875
| 2
|
[] |
no_license
|
package com.technolosea.sailwinder;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.GeoPoint;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DbLayer {
private static final String TAG = "DbLayer";
private List<Mark> marks = new ArrayList();
private static Mark lastMark;
FirebaseFirestore db;
public DbLayer() {
db = FirebaseFirestore.getInstance();
}
public void updateMarks() {
db.collection("gates")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
Mark m = new Mark();
m.coordinate1 = document.get("coordinate1", GeoPoint.class);
m.coordinate2 = document.get("coordinate2", GeoPoint.class);
m.time = document.getTimestamp("time");
m.gateType = GateType.valueOf(document.getString("gateType"));
m.order = document.getLong("order");
getMarks().add(m);
if (m.gateType == GateType.FinishLine)
lastMark = m;
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
}
public void addTrackPoint(String userId, GeoPoint coordinate, Timestamp timeStamp) {
// Create a new user with a first and last name
Map<String, Object> track = new HashMap<>();
track.put("coordinate", coordinate);
track.put("time", timeStamp);
track.put("userId", userId);
// Add a new document with a generated ID
db.collection("track")
.add(track)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
}
// public Map<String, Object> getTrackByUserId(final String userId)
// {
// db.collection("track").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
// @Override
// public void onComplete(@NonNull Task<QuerySnapshot> task) {
// if (task.isSuccessful()) {
// List<Map<String, Object>> tracks = new ArrayList<>();
// for (QueryDocumentSnapshot document : task.getResult()) {
// Map<String, Object> m = new HashMap<>();
// m.put("userId",document.getString("userId"));
// m.put("time", document.getTimestamp("time"));
// m.put("coordinate", document.getGeoPoint("coordinate"));
// tracks.add(m);
// }
// for (int track_index = 0; track_index < tracks.size(); ++track_index)
// {
// Map<String, Object> examined_track = tracks.get(track_index);
// if (examined_track.get("userId") == userId)
// return tracks.get(track_index);
// }
// } else {
// Log.w(TAG, "Error getting documents.", task.getException());
// }
// }
// });
// }
public List<Mark> getMarks() {
return marks;
}
public static Mark getEndingMark()
{
return lastMark;
}
}
|
C++
|
UTF-8
| 980
| 2.734375
| 3
|
[] |
no_license
|
#pragma once
#include <Windows.h>
#include <utility>
#include <stdexcept>
#define RETURN_IF_FAILED(hr) do { if (FAILED(hr)) { return hr; } } while(0)
#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))
inline void THROW_IF_FAILED(HRESULT hr, const char* message)
{
if (FAILED(hr))
{
DebugBreak();
throw std::runtime_error(message);
}
}
template <typename T>
class lambda_call
{
public:
explicit lambda_call(T&& lambda) : m_lambda(std::move(lambda))
{
}
~lambda_call()
{
m_lambda();
}
protected:
T m_lambda;
};
template <typename T>
inline auto scope_exit(T&& lambda)
{
return lambda_call<T>(std::forward<T>(lambda));
}
inline float RandomInRange(float min, float max)
{
return static_cast<float>(rand()) / (RAND_MAX + 1) * (max - min) + min;
}
template <typename T>
bool IsInRange(T value, T min, T max)
{
return (min <= value && value <= max);
}
|
C++
|
SHIFT_JIS
| 1,313
| 2.859375
| 3
|
[] |
no_license
|
#pragma once
#include"DxControl.h"
class DxKeyBoard : public DxControl
{
protected:
char KeyState[256]; //L[̉ێ
char OldKeyState[256]; //Ot[ł̃L[̉ێ
int KeepTime[256]; //݂̉Ԃt[ێĂ̂ێ
public:
//RXgN^
DxKeyBoard();
//L[ZbgiS0jɂ
void ResetKeyData();
//ԂXV
void UpDate();
//w肵L[Ă邩ǂ@L[z̓YkeyCodeɂ̂Ԃ
//G[ȂfalseԂ trueĂ falseĂȂ
bool CheckPress(int) const;
//Ot[̃L[ƌ݂̃L[ׁAw肵L[ꂽuԂǂׂ
//G[ȂAfalseԂ
bool CheckPressMoment(int) const;
//Ot[̃L[ƌ݂̃L[w肵L[ꂽuԂł邩ǂׂ
//G[ȂAfalseԂ
bool CheckFreeMoment(int) const;
//w肵L[݂̉Ԃt[ێĂ̂擾
//keyCodesȂA0Ԃ
int GetTime(int) const;
};
|
Java
|
UTF-8
| 2,488
| 3.453125
| 3
|
[] |
no_license
|
package Jogo;
import jplay.Keyboard;
import jplay.Sprite;
import jplay.URL;
import jplay.Window;
public class Jogador extends Sprite{
private double velocidade = 0.5;
private int direcao=3;
private Keyboard teclado;
private boolean movendo= false;
//Codigo Inicia a criação do personagem
public Jogador(int x,int y) {
super(URL.sprite("jogador.png"), 20);
this.x = x;
this.y = y;
this.setTotalDuration(2000);/*Tempo em milisegundos que será alterado
os frames do personagem*/
}
//Codigo de movimentaçao do personagem
public void mover(Window janela){
if(teclado == null){
teclado=janela.getKeyboard();
}
//Aqui começa os ifs pra delimitar e mover os frames do personagem no cenario
if(teclado.keyDown(Keyboard.LEFT_KEY)){//Movendo para a esquerda
if( this.x > 0){
this.x -=velocidade;
}
if(direcao != 1){
setSequence(4 , 8); /*Posiçao de frame utilizado, total
de 20 frames ele ira utilizar do 4º ao 8º*/
direcao = 1;
}movendo = true;
}else if(teclado.keyDown(Keyboard.RIGHT_KEY)){//Movendo para a direita
if( this.x < janela.getWidth()- 60 ){
this.x +=velocidade;
}
if(direcao != 2){
setSequence(8 , 12);
direcao = 2;
}movendo = true;
}else if(teclado.keyDown(Keyboard.UP_KEY)){//Movendo para cima
if( this.y > 0){
this.y -=velocidade;
}
if(direcao != 4){
setSequence(12 , 16);
direcao = 4;
}movendo = true;
}else if(teclado.keyDown(Keyboard.DOWN_KEY)){//Movendo para baixo
if( this.y < janela.getHeight()- 60){
this.y +=velocidade;
}
if(direcao != 5){
setSequence(0 , 4);
direcao = 5;
}movendo = true;
}
if(movendo){
update();
movendo = false;
}
}
}
|
Java
|
UTF-8
| 640
| 1.882813
| 2
|
[] |
no_license
|
package com.tyss.taskmanagement.dto;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.GeneratedValue;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import lombok.Data;
@Data
@Embeddable
@SuppressWarnings("serial")
public class ProjectPKBean implements Serializable {
public static final AtomicInteger count = new AtomicInteger(0);
@GeneratedValue
@Column(name = "project_id")
private int projectId;
@JoinColumn(name = "emp_id")
@ManyToOne
private UserBean userBean;
}
|
Python
|
UTF-8
| 6,835
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
#Author: Christopher Ivie
#Description: Downloads the most recent NIST CVE feed, stores the information into a database!
import requests
import zipfile
import json
import os
import os.path
from os import path
import sqlite3
from datetime import datetime
import pytz
import tzlocal
#Get local time zone
local_timezone = tzlocal.get_localzone()
#Creating a step to match the year in the NIST URL.
step = 2003
while step < 2022:
nextyear = str(step)
if nextyear == 2021:
nextyear = "recent"
print(nextyear)
step += 1
print(step)
#recent vuln feeds from nist
url = 'https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-' + nextyear + '.json.zip'
target_path = 'recent.zip'
#request feed file
response = requests.get(url, stream=True)
#download feed file
handle = open(target_path, "wb")
for chunk in response.iter_content(chunk_size=512):
if chunk:
handle.write(chunk)
handle.close()
#unzip recent.zip
with zipfile.ZipFile(target_path, 'r') as zip_ref:
zip_ref.extractall()
#Remove old zip file
os.remove("recent.zip")
#open json file
with open('nvdcve-1.1-' + nextyear +'.json', 'rb') as f:
data = json.load(f)
#database connection
db = 'cves.db'
conn = sqlite3.connect(db)
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS cveinfo (CVEID text UNIQUE, lastmodidate json, pubdate json, description json, timestap json, refurl json, name json, refsource json, tags json, metricversion json, vectorstring json, attackvector json, attackcomplexity json, privilegesrequired json, userinteraction json, scope json, confidentialityimpact json, integrityimpact json, availabilityimpact json, basescore json, baseseverity json, CVEsinSet json, cveurl json)") #22
#BASE of API
CVEnumof = data['CVE_data_numberOfCVEs']
numofcveint = int(CVEnumof)
print(numofcveint)
CVEtimestamp = data['CVE_data_timestamp']
print(CVEtimestamp)
count = 1
#Write to download log
utc_time = datetime.strptime(CVEtimestamp, "%Y-%m-%dT%H:%M%fZ")
print(utc_time)
local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(local_timezone)
firstlog = open("zip-download.log", "a")
firstlog.write(str("=======================================") + "\n")
firstlog.write(str("Timestamp: ") + str(local_time) + " MST" + "\n")
firstlog.write(str("HTTP Response: ") + str(response) + "\n")
firstlog.write(str("Link location: ") + url + "\n")
firstlog.write(str("Number of CVEs in this set: ") + str(CVEnumof) + "\n")
firstlog.close()
#Get the numer of CVEs in set and write to database
while count < numofcveint:
try:
CVEapiroot = data['CVE_Items'][count]
count += 1
try:
#Start of CVEapiroot['cve']
CVEapicve = CVEapiroot['cve']
print(CVEapiroot['cve']['CVE_data_meta']['ID'])
CVEID = CVEapicve['CVE_data_meta']['ID']
CVEdesc = CVEapicve['description']['description_data'][0]['value']
CVEurl = CVEapicve['references']['reference_data'][0]['url']
CVEname = CVEapicve['references']['reference_data'][0]['name']
CVErefsource = CVEapicve['references']['reference_data'][0]['refsource']
CVEtags = CVEapicve['references']['reference_data'][0]['tags']
except IndexError:
continue
#Start of CVEapiroot['impact']['baseMetricV3']['cvssV3']
CVEapiimpact = CVEapiroot['impact']['baseMetricV3']['cvssV3']
CVEmetricVersion = CVEapiimpact['version']
CVEvectorString = CVEapiimpact['vectorString']
CVEattackVector = CVEapiimpact['attackVector']
CVEattackComplexity = CVEapiimpact['attackComplexity']
CVEprivilegesRequired = CVEapiimpact['privilegesRequired']
CVEuserInteraction = CVEapiimpact['userInteraction']
CVEscope = CVEapiimpact['scope']
CVEconfidentialityImpact = CVEapiimpact['confidentialityImpact']
CVEintegrityImpact = CVEapiimpact['integrityImpact']
CVEavailabilityImpact = CVEapiimpact['availabilityImpact']
CVEbaseScore = CVEapiimpact['baseScore']
CVEbaseSeverity = CVEapiimpact['baseSeverity']
print(CVEbaseSeverity)
#start of CVEapiroot['lastModifiedDate']
CVEapilastmodidate = CVEapiroot['lastModifiedDate']
#start of CVEapiroot['publishedDate']
CVEapipubdate = CVEapiroot['publishedDate']
#print CVEapilastmodidate.strftime("%Y-%m-%dT%H:%M%fZ")
#print(timemstmodi)
#print(timemstpub)
#Write to database
c.execute("insert or ignore into cveinfo values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", #22
[
json.dumps(CVEID),
json.dumps(CVEapilastmodidate),
json.dumps(CVEapipubdate),
json.dumps(CVEdesc),
json.dumps(CVEtimestamp),
json.dumps(CVEurl),
json.dumps(CVEname),
json.dumps(CVErefsource),
json.dumps(CVEtags),
json.dumps(CVEmetricVersion),
json.dumps(CVEvectorString),
json.dumps(CVEattackVector),
json.dumps(CVEattackComplexity),
json.dumps(CVEprivilegesRequired),
json.dumps(CVEuserInteraction),
json.dumps(CVEscope),
json.dumps(CVEconfidentialityImpact),
json.dumps(CVEintegrityImpact),
json.dumps(CVEavailabilityImpact),
json.dumps(CVEbaseScore),
json.dumps(CVEbaseSeverity),
json.dumps(CVEnumof),
json.dumps(url),
])
conn.commit()
except KeyError:
continue
print('nvdcve-1.1-' + nextyear +'.json')
os.remove('nvdcve-1.1-' + nextyear +'.json')
|
JavaScript
|
UTF-8
| 787
| 2.546875
| 3
|
[] |
no_license
|
var firebase = require("firebase-admin");
var sleep = require('sleep')
var serviceAccount = require("./firebasekey.json");
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "https://voyager01.firebaseio.com"
});
var refS = firebase.database().ref('samples/')
function writeSampleData(sample, timestamp, lat, lon, cpm, temp, elev, uv, img, lidar) {
refS.push({
sample: sample,
timestamp: timestamp,
lat: lat,
lon: lon,
cpm: cpm,
temp: temp,
elev: elev,
uv: uv,
img: img,
lidar: lidar
});
sleep.sleep(1);
}
for (var i = 25; i >= 0; i--) {
var d = new Date().toString();
console.log(d);
writeSampleData(i, d , "8.7544583","-75.8713815", 120 + i, 35 + i, 200 + i, 19 + i, "null", "OK");
}
|
Java
|
UTF-8
| 1,904
| 3.078125
| 3
|
[] |
no_license
|
package com.farbig.practice.dsa.algorithms.sort.old;
public class TestSort {
public static boolean isdatasorted = true;
public static boolean display = true;
public static boolean detaildisplay = true;
static int factor = 1;
//static int sample[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
//static int sample[] = { 11, 18, 99, 44, 25, 67, 71,53,85,35 };
//static int sample[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
static int sample[] = { 1, 2, 3, 4 };
static int a[] = new int[sample.length*factor];
static int b[] = new int[sample.length*factor];
static int c[] = new int[sample.length*factor];
public static void testSort() {
if(isdatasorted)
for (int i = 0; i < sample.length*factor; i++) {
a[i]=i;
b[i]=i;
c[i]=i;
}
else
for (int i = 1; i <= factor; i++) {
System.arraycopy(sample, 0, a, (i-1)*sample.length, sample.length);
System.arraycopy(sample, 0, b, (i-1)*sample.length, sample.length);
System.arraycopy(sample, 0, c, (i-1)*sample.length, sample.length);
}
BubbleSort.sort(a);
System.out.println("TOTAL TIME TAKEN :" + BubbleSort.t+"\n");
SelectionSort.sort(b);
System.out.println("TOTAL TIME TAKEN :" + SelectionSort.t+"\n");
InsertionSort.sort(c);
System.out.println("TOTAL TIME TAKEN :" + InsertionSort.t+"\n");
System.out.println("SORT \t\t\tCOMPARISIONS\t\tCOPIES\t\tTIME\n");
System.out.println(BubbleSort.SORT_NAME+"\t\t" + BubbleSort.comps+"\t\t"+BubbleSort.copies+"\t\t"+BubbleSort.t+"\n");
System.out.println(SelectionSort.SORT_NAME+"\t\t" + SelectionSort.comps+"\t\t"+SelectionSort.copies+"\t\t"+SelectionSort.t+"\n");
System.out.println(InsertionSort.SORT_NAME+"\t\t" + InsertionSort.comps+"\t\t"+InsertionSort.copies+"\t\t"+InsertionSort.t+"\n");
}
public static void main(String a[])
{
for (int i = 0; i < 1; i++) {
testSort();
}
}
}
|
C++
|
UTF-8
| 1,417
| 2.859375
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
#ifndef LOCATION_H
#define LOCATION_H
/*
This file is part of VROOM.
Copyright (c) 2015-2022, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include <cassert>
#include "structures/typedefs.h"
namespace vroom {
class Location {
private:
// Index of this location in the matrix.
Index _index;
// Coordinates (not mandatory).
OptionalCoordinates _coords;
bool _user_index;
public:
Location(Index index);
Location(Index index, const Coordinates& coords);
Location(const Coordinates& coords);
void set_index(Index index);
bool has_coordinates() const;
Index index() const {
return _index;
}
Coordinate lon() const;
Coordinate lat() const;
bool user_index() const;
// Locations are considered identical if they have the same
// user-provided index or if they both have coordinates and those
// are equal. The last part is required for situations with no
// explicit index provided in input.
bool operator==(const Location& other) const;
};
} // namespace vroom
namespace std {
template <> struct hash<vroom::Location> {
std::size_t operator()(const vroom::Location& l) const noexcept {
if (l.user_index()) {
return hash<vroom::Index>()(l.index());
}
assert(l.has_coordinates());
return ((hash<vroom::Coordinate>()(l.lon()) ^
(hash<vroom::Coordinate>()(l.lat()) << 1)) >>
1);
}
};
} // namespace std
#endif
|
Ruby
|
UTF-8
| 2,028
| 3.0625
| 3
|
[] |
no_license
|
require 'spec_helper'
describe Elevator do
describe "#new" do
it "sets the elevator number" do
@elevator = Elevator.new(3, 10)
expect(@elevator.number).to eq(3)
end
it "sets the number of floors" do
@elevator = Elevator.new(2, 8)
expect(@elevator.no_floors).to eq(8)
end
end
describe "#status" do
it "shows the elevator number" do
@elevator = Elevator.new(2, 8)
expect(@elevator.status).to include("2")
end
it "shows the floor number" do
@elevator = Elevator.new(2, 8)
@elevator.go_to_floor(6)
expect(@elevator.status).to include("6")
end
it "shows the status of the door" do
@elevator = Elevator.new(2, 8)
expect(@elevator.status).to include("closed")
end
end
describe "#go_to_floor" do
it "sends the elevator to a floor" do
@elevator = Elevator.new(0, 8)
@elevator.go_to_floor(6)
expect(@elevator.floor).to eq(6)
end
end
describe "#random_floor" do
it "send the elevator to a floor that exists" do
@elevator = Elevator.new(0, 8)
expect(1..@elevator.no_floors).to include(@elevator.random_floor)
end
end
describe "#accessible?" do
context "when elevator is on the same floor given floor" do
it "returns true" do
@elevator = Elevator.new(0, 8)
expect(@elevator.accessible?(1)).to eq(true)
end
end
context "when elevator is not on the same floor given floor" do
it "returns false" do
@elevator = Elevator.new(0, 8)
@elevator.go_to_floor(2)
expect(@elevator.accessible?(1)).to eq(false)
end
end
end
describe "#open_door" do
it "opens the door" do
@elevator = Elevator.new(0, 8)
@elevator.open_door
expect(@elevator.door_open?).to eq(true)
end
end
describe "#close_door" do
it "opens the door" do
@elevator = Elevator.new(0, 8)
@elevator.close_door
expect(@elevator.door_open?).to eq(false)
end
end
end
|
PHP
|
UTF-8
| 1,152
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
<?php
// Passando os dados obtidos pelo formulário para as variáveis abaixo
$nomeremetente = $_POST['nome'];
$emailremetente = trim($_POST['email']);
$emaildestinatario = 'brazil@pyladies.com'; // Digite seu e-mail aqui, lembrando que o e-mail deve estar em seu servidor web
$assunto = $_POST['assunto'];
$mensagem = $_POST['mensagem'];
/* Montando a mensagem a ser enviada no corpo do e-mail. */
$mensagemHTML = '<P>FORMULARIO PREENCHIDO NO SITE PYLADIES</P>
<p><b>Nome:</b> '.$nomeremetente.'
<p><b>E-Mail:</b> '.$emailremetente.'
<p><b>Assunto:</b> '.$assunto.'
<p><b>Mensagem:</b> '.$mensagem.'</p>
<hr>';
// O remetente deve ser um e-mail do seu domínio conforme determina a RFC 822.
// O return-path deve ser ser o mesmo e-mail do remetente.
$headers = "MIME-Version: 1.1\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: $emailremetente\r\n"; // remetente
$headers .= "Return-Path: $emaildestinatario \r\n"; // return-path
$envio = mail($emaildestinatario, $assunto, $mensagemHTML, $headers);
if($envio)
echo "<script>location.href=''</script>"; // Página que será redirecionada
?>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.