language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 2,422
| 2.84375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static string GetMd5Hash(MD5 md5Hash, string input)
{
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 forms = new Form2();
Form1 forms1 = new Form1();
string[,] tablica = new string[5, 2];
tablica[0,0] = "Jan";
tablica[0,1] = "Kowalski";
tablica[1, 0] = "admin";
tablica[1, 1] = "admin";
string path = @"c:\pliki/x.txt";
StreamWriter sw = new StreamWriter(path);
if (textBox1.Text==tablica[0,0] && textBox2.Text==tablica[0,1] || textBox1.Text == tablica[1, 0] && textBox2.Text == tablica[1, 1])
{
MD5 md5Hash = MD5.Create();
MD5 md5Hash1 = MD5.Create();
string login = GetMd5Hash(md5Hash, textBox1.Text);
string haslo = GetMd5Hash(md5Hash, textBox2.Text);
sw.WriteLine(login);
sw.WriteLine(haslo);
sw.Close();
forms.Show();
}
else
{
string message = "Wpisałeś zły login lub hasło. Jeżeli chcesz wyjść z aplikacji wciśnij tak a jeżeli ponownie zalogować wciśnij nie";
string caption = "Zły login lub hasło";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
this.Close();
}
}
}
}
}
|
Java
|
UTF-8
| 174
| 1.828125
| 2
|
[
"MIT"
] |
permissive
|
package cd.belhanda.imbishavideostream.Adapters;
import cd.belhanda.imbishavideostream.Modele.Chanson;
public interface itemClick {
void onItemClick(Chanson chanson);
}
|
JavaScript
|
UTF-8
| 5,808
| 2.640625
| 3
|
[] |
no_license
|
const db = require('../../database/models');
const { validationResult } = require('express-validator')
class Operation{
constructor(userId, typeId, concept, mount, date) {
this.userId = userId,
this.typeId = typeId,
this.concept = concept,
this.mount = mount,
this.date = date
}
}
module.exports = {
once: async (req, res) => {
try {
const { id, userId } = req.body;
console.log('ONCE BODY: ', req.body);
const operation = await db.Operation.findByPk(id);
if (operation) {
if (operation.userId === userId) {
console.log('SIIIIIIIIIIIIIIIIIIII');
res.json({
msg: "You are able to acces this op",
operation,
})
} else {
console.log("NOOOOOOOOOOOOOO");
res.json({
msg: "You cant acces to this info"
})
}
} else {
res.json({
error: {
msg: "Couldn't find Op. in db"
},
})
}
} catch (err) {
res.json({
error: {
msg: "There was an error",
err
}
})
}
},
store: async (req, res) => {
let resultValidation = validationResult(req);
try {
if (resultValidation.errors.length > 0) {
res.json({
errors: resultValidation,
})
} else {
console.log('STORE');
const {
userId,
typeId,
concept,
mount,
date
} = req.body;
console.log(req.body);
const operation = new Operation(userId, typeId, concept, mount, date)
const opInDb = await db.Operation.create(
operation
)
res.json({
opInDb
})
}
} catch (err) {
res.json({
error: {
msg: "There was an error",
err
}
})
}
},
all: async (req, res) => {
try {
const operations = await db.Operation.findAll({
where: {
userId: req.body.id
},
})
if (operations) {
let accum = 0;
operations.forEach((element) => {
if (element.typeId == 1) {
return accum += element.mount
} else if(element.typeId == 2){
return accum -= element.mount
}
})
res.json({
operations,
total: accum
})
}
} catch (err) {
res.json({
error:{
msg:"There was an error"
}
})
}
},
lastOps: async (req, res) => {
console.log('LAST OP');
try {
const operations = await db.Operation.findAll({
where: {
userId: req.body.id
},
limit: 10,
order: [['id', 'DESC']]
})
if (operations) {
let accum = 0;
operations.forEach((element) => {
if (element.typeId == 1) {
return accum += element.mount
} else if(element.typeId == 2){
return accum -= element.mount
}
})
res.json({
operations,
total: accum
})
}
} catch (err) {
res.json({
error:{
msg:"There was an error"
}
})
}
},
update: async (req, res) => {
try {
let resultValidation = validationResult(req);
if (resultValidation.errors.length > 0) {
res.json({
errors: resultValidation
})
} else {
const {
concept,
mount,
date
} = req.body;
const id = Number(req.body.id)
console.log("UPDATE BODY: ", req.body)
const operationToUpdate = await db.Operation.findByPk(req.body.id);
if (operationToUpdate) {
const updatedOperation = await db.Operation.update({
concept: concept,
mount: mount,
date: date
}, {
where: {id: Number(id)}
})
res.json({
updatedOperation
})
}
}
} catch (err) {
res.json({
error:{
msg:"There was an error"
}
})
}
},
destroy:(req, res) => {
console.log("DELETE METHOD")
console.log(req.body);
const { id } = req.body;
db.Operation.destroy({
where:{id}
})
.then((resp) => {
res.json({
msg:"succefully deleted"
})
})
}
}
|
Python
|
UTF-8
| 3,407
| 2.734375
| 3
|
[] |
no_license
|
from django import template
from django.conf import settings
register = template.Library()
@register.tag
def session_value(parser, token):
"""
For each template tag the template parser encounters, it calls a Python function with the tag
contents and the parser object itself. This function is responsible for returning a Node
instance based on the contents of the tag.
The main function of session_value is that it checks and parses the format of the
command when been used.
Make some template tags to be available to a particular view alone.
If the view name of the current url is ..., get its session variable called 'consumer'
and parse it to get out its values. return a dict to do a dot reference on.
- inside render, define the context to be the view name (probably its reverse name)
For example, # arguments are the view name and session variable name.
{% session_value [view_name] [session_variable] %}
Returns a dict or string (to be decided)
"""
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError("'%s' takes at least one argument"
" (path to a view)" % bits[0])
view_name = bits[1]
session_variable = '' # or args - bits at session_variable
kwargs = None # bits as argument to session_variable
return SessionNode(view_name, session_variable, kwargs, legacy_view_name=True)
session_value = register.tag(session_value)
class SessionNode(template.Node):
def __init__(self, view_name, session_variable, kwargs=None, legacy_view_name=True): #session_variable is used as args
self.view_name = view_name
self.session_variable = session_variable
#self.args = args
if kwargs is not None:
self.kwargs = kwargs
if not legacy_view_name:
self.legacy_view_name = legacy_view_name
def render(self, context):
from django.core.urlresolvers import reverse, NoReverseMatch
session_variable = [arg.resolve(context) for arg in self.session_variable]
kwargs = 'institution_name' # a key from session_variable
view_name = self.view_name
if not self.legacy_view_name:
view_name = view_name.resolve(context)
url = ''
try:
url = reverse(view_name, args=session_variable, kwargs=kwargs, current_app=context.current_app)
except NoReverseMatch, e:
if settings.SETTINGS_MODULE:
project_name = settings.SETTINGS_MODULE.split('.')[0]
try:
url = reverse(project_name + '.' + view_name,
args=session_variable, kwargs=kwargs,
current_app=context.current_app)
except NoReverseMatch:
pass
session_value = None
# check the view_name if it exists
# if it exists, look in the session object for session_variable
# hint: inside HttpResponse, there's a context object and a context_instance of
# RequestContext type. Check in here for the session_variable. Alternatively,
# use context[request].page to get the page_obj see: pagination tags
# if it exists, check it's type
# if its type is a dict, check if session_variable has another arg passed into it
# if yes, use it as a key to look up the right value in the dict (session_variable)
# if the type of the session_variable is a string, return the string
return session_value
|
PHP
|
UTF-8
| 912
| 2.921875
| 3
|
[] |
no_license
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use App\Services\Weather\OpenWeatherApiService;
class WeatherController extends Controller
{
protected $weatherService;
public function __construct(OpenWeatherApiService $weatherService)
{
$this->weatherService = $weatherService;
}
/**
* Create a weather report for the given location.
*
* @param Request $request
* @return string
*/
public function create (Request $request) {
$zip = $request->input('zip');
$validator = Validator::make($request->all(), [
'zip' => 'required|digits:5'
]);
if ($validator->fails()) {
return "Please enter a 5 digit zip code.";
}
$location = $zip . ",us";
return $weather = $this->weatherService->full_weather_report($location);
}
}
|
PHP
|
UTF-8
| 932
| 2.796875
| 3
|
[
"BSD-3-Clause",
"MIT"
] |
permissive
|
<?php
namespace AppBundle\Entity;
/*chemin permettant d'identifier cette classe et permet de l'utiliser plus tard*/
use Doctrine\ORM\Mapping as ORM;
/* utilisation dans le fichier de la classe mapping
'as' permet d'utiliser @ORM au lieu d'@Mapping, le nom de la classe*/
/**
* @ORM\Entity
* @ORM\Table(name="guide")
* !!!!!!!voir l'appel au repository pour les fcts en read supplémentaires (ex:recherche d'un nom !!!!!
*/
/* la classe article est une entité qui vient travailler avec la table de la bdd identifié Guide (son miroir)*/
class Guide
{
/**
* Ce bout de code sera toujours le même pour chaque entité
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=250)
*/
private $guide_logo;
/**
* @ORM\Column(type="string", length=150)
*/
private $guide_name;
}
|
Python
|
UTF-8
| 3,888
| 2.546875
| 3
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
# -*- coding: utf-8 -*-
from gluon import current
from gluon.http import HTTP
import csv
import ntpath
import os
class Importer(object):
""" Importer class to import the prepop data """
# -------------------------------------------------------------------------
def __init__(self, filename=None):
if not filename:
current.auth.permission.fail()
self.path = os.path.join(current.app_settings["prepop_files_path"], filename)
if not os.path.isfile(self.path):
raise(HTTP(404, "The prepop %s file does not exist!!!" % self.path))
self.filename = filename
tablename = self.check_table()
if not tablename:
raise(HTTP(404, "Some table(s) are not present for the prepop file!!!"))
self.tablename = tablename
import_file = csv.DictReader(open(self.path))
self.import_file = import_file
# -------------------------------------------------------------------------
def check_table(self):
tablename = self.filename.split(".csv")[0]
if tablename in current.db.tables:
return tablename
return None
# -------------------------------------------------------------------------
def import_permission(self):
auth = current.auth
create_or_update_group = auth.create_or_update_group
def parseACL(acl, rules, type=""):
if not type or type not in ["uacl", "oacl"]:
raise(HTTP(500, "error with permissions!!!"))
permissions = acl.split("|")
if type == "uacl":
for permission in permissions:
if permission == "CREATE":
rules["user_create"] = True
if permission == "READ":
rules["user_read"] = True
if permission == "UPDATE":
rules["user_update"] = True
if permission == "DELETE":
rules["user_delete"] = True
if type == "oacl":
for permission in permissions:
if permission == "CREATE":
rules["owner_create"] = True
if permission == "READ":
rules["owner_read"] = True
if permission == "UPDATE":
rules["owner_update"] = True
if permission == "DELETE":
rules["owner_delete"] = True
roles = {}
acls = {}
for row in self.import_file:
if row != None:
role = row["role"]
description = row["description"]
hidden = row.get("hidden", False)
rules = {}
controller = row["controller"]
if controller:
rules["controller"] = controller
function = row["function"]
if function:
rules["function"] = function
tablename = row["table"]
if tablename:
rules["tablename"] = tablename
uacl = row["uacl"]
if uacl:
parseACL(uacl, rules, type="uacl")
oacl = row["oacl"]
if oacl:
parseACL(oacl, rules, type="oacl")
if role in roles:
acls[role].append(rules)
else:
roles[role] = [role, description, hidden]
acls[role] = [rules]
for role in roles.values():
create_or_update_group(role[0],
role[1],
role[2],
*acls[role[0]])
# END =========================================================================
|
C
|
UTF-8
| 4,577
| 2.921875
| 3
|
[
"WTFPL"
] |
permissive
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
typedef int (*nmsql_callback)(void *, const int, const char *const *,
const char *const *);
extern void hs_init(int *, char ***);
extern void hs_exit();
extern int exec(const char *ir, nmsql_callback callback, void *args);
extern char *compile(char *sql);
extern void openDb(const char *dbName);
extern void closeDb();
static struct option long_options[] = {
{"database-file", required_argument, 0, 'f'},
{"help", no_argument, 0, 'h'},
{"sql", required_argument, 0, 's'},
{0, 0, 0, 0},
};
struct NMSqL_Options {
char *dbFile;
char *sql;
} options;
int callback(void *pArgs, const int colNumber, const char *const *colData,
const char *const *colNames) {
for (int i = 0; i < colNumber; i++) {
printf("name={%s},", colNames[i]);
int len = ((int)colData[i][0]) << 8 | (colData[i][1]);
int flag = colData[i][2];
if (flag == 1) {
int value = ((int)colData[i][4] << 24) |
((int)colData[i][5] << 16) | ((int)colData[i][6] << 8) |
((int)colData[i][7]);
printf("type=int,value={%d}\n", value);
} else if (flag == 2) {
unsigned long long value = 0;
for (int j = 0; j < 8; j++) {
value = (value << 8) | (colData[i][j + 4] & 0xff);
}
printf("type=double,value={%f}\n", *(double *)&value);
} else if (flag == 3) {
printf("type=string,value={");
for (int j = 0; j < len; j++) printf("%c", colData[i][j + 4]);
printf("}\n");
} else {
printf("type=null");
}
}
return 0;
}
char *ReadSQL() {
int len = 2, i = 0;
char *res = malloc(len + 1);
printf("SQL> ");
while (1) {
char c;
while (1) {
c = getchar();
if (c == -1) return 0;
if (c == '\n') break;
if (i >= len) {
len *= 2;
res = realloc(res, len + 1);
}
res[i++] = c;
}
while (1) {
if (i == 0) break;
if (res[i - 1] == ' ' || res[i - 1] == '\t')
i--;
else
break;
}
if (res[i - 1] != ';') {
res[i++] = ' ';
printf("...> ");
} else
break;
}
res[i - 1] = '\0';
return res;
}
void usage() {
fputs(
"NMSqL version 0.1.0\n"
"\n"
"Usage :\n"
"NMSqL [options]\n"
"\n"
"OPTIONS\n"
" -h --help Show help and exit\n"
" -f FILE --database-file FILE Specify to use FILE as the database file\n"
" -s SQL --sql SQL Specify SQL as the sql to be executed,\n"
" if this option is not set, we will open a shell\n"
"\n"
"EXAMPLE\n"
" NMSqL -f tmp.db -s \"select * from xxx\"\n"
" NMSqL -f tmp.db\n"
"\n"
,stdout);
}
void ParseOptions(int argc, char **argv) {
options.dbFile = NULL;
options.sql = NULL;
char isOptSet = 0;
int optret, l_optidx;
while (1) {
optret = getopt_long(argc, argv, "hf:s:", long_options, &l_optidx);
if (optret == -1) break;
isOptSet = 1;
switch (optret) {
case 'f':
options.dbFile = argv[optind - 1];
break;
case 's':
options.sql = argv[optind - 1];
break;
case 'h':
default:
usage();
exit(0);
}
}
if (!isOptSet) {
usage();
exit(0);
}
if (options.dbFile == NULL) {
usage();
fputs("ERROR: database file is required.", stdout);
exit(-1);
}
}
int main(int argc, char **argv) {
ParseOptions(argc, argv);
hs_init(&argc, &argv);
openDb(options.dbFile);
int rt = 1;
if (options.sql != NULL) {
char *ir = compile(options.sql);
if (ir[0] == 'S') {
printf("%s\n", ir);
} else {
rt = exec(ir, callback, NULL);
}
} else {
char *sql;
while ((sql = ReadSQL())) {
char *ir = compile(sql);
if (ir[0] == 'S') {
printf("%s\n", ir);
break;
}
rt = exec(ir, callback, NULL);
}
}
closeDb();
hs_exit();
return rt;
}
|
Python
|
UTF-8
| 817
| 2.609375
| 3
|
[] |
no_license
|
# CS390Z - Introduction to Data Minining - Fall 2021
# Instructor: Thyago Mota
# Description: A Simple Web Scraper
import json
import re
import os
import requests
from bs4 import BeautifulSoup
# definitions/parameters
DATA_FOLDER = '../data'
JSON_FILE_NAME = 'covid_testing_denver.json'
BASE_URL = 'https://covidcheckcolorado.org/find-our-sites-testing/'
HEADERS = {"User-Agent": "Mozilla/5.0 (X11; CrOS x86_64 12871.102.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36"}
def remove_tags(s):
tag = re.compile('<.*?>')
return re.sub(tag, '', s)
if __name__ == "__main__":
# TODO: get list of covid-19 testing centers in Denver from BASE_URL, saving them in a dictionary with the structure described in README
# TODO: save covid-19 testing centers in Denver to json
|
C
|
UTF-8
| 302
| 3.625
| 4
|
[] |
no_license
|
#include<stdio.h>
int main()
{
int arr[3][3];
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
printf(" Enter Array of arr[%d][%d]:-",i,j);
scanf("%d",&arr[i][j]);
}
}
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
printf(" Array of arr[%d][%d]:- %d\n",i,j,arr[i][j]);
}
}
}
|
Python
|
UTF-8
| 1,843
| 2.65625
| 3
|
[] |
no_license
|
import os, sys, random, struct, os.path, shutil, binascii
import pgpy
import pyAesCrypt
from typing import ValuesView
from hashlib import new
from struct import pack
from Crypto.Cipher import DES
from bitstring import ConstBitStream
from pgpy.constants import PubKeyAlgorithm, KeyFlags, HashAlgorithm, SymmetricKeyAlgorithm, CompressionAlgorithm
'''
IV = CryptoRandom.new().read(DES.block_size)
des = self.get_des(IV)
padding = DES.block_size - len(format) % DES.block_size
format += bytes([padding]) * padding
data = IV + des.encrypt(format)
self.set_salt()
encoded = base64.b64encode(data)
'''
format = 'whateverthehexk2232408358q45798345709437509475294835rghfjsiuytpghf'
characters = ('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*') # Available characters for password
password_des = '' # Creates the password
for i in range(16):
password_des += random.choice(characters)
des = DES.new(password_des, DES.MODE_ECB)
text = format
text = text + (8 - (len(text) % 8)) * '='
encrypto_text = des.encyrypt(text.encode())
encrypto_text = binascii.b2a_hex(encrypto_text)
print(encrypto_text)
'''
def pad_message(message):
while len(message) % 7 != 0:
message = message + ' '
return message
characters = ('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*') # Available characters for password
password_des = '' # Creates the password
for i in range(16):
password_des += random.choice(characters)
message = format
message = pad_message(message)
cipher = DES.new(password_des, DES.MODE_ECB)
cipher_text = cipher.encrypt(message.encode('utf-8'))
print('Encrpyted message is ', cipher_text)
print('Hex of text is ', cipher_text.hex())
decrypted_message = cipher.decrypt(cipher_text)
print('Decrypted message is ', decrypted_message)'''
|
PHP
|
UTF-8
| 2,442
| 3.421875
| 3
|
[] |
no_license
|
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<title>Operações com exception em PHP.</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/style.css" media="screen,projection">
</head>
<body>
<?php
function myException($exception) {
echo "<b>Exception:</b> " . $exception->getMessage();
}
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
//Create function with exception
function checkNum($number){
if ($number > 1) {
# code...
throw new Exception("Value must be 1 or below!");
}
return true;
}
//Variables
$email = "johndoe@example....com";
$email2 = "johndoe@example.com";
//Trigger exception
checkNum(2);
//Trigger exception in a "try" block.
try {
checkNum(2);
//if the exception is throw, this text will not be shown.
echo "If you see this, the number is 1 or below!";
//catch exception.
} catch (Exception $e) {
echo "Message: ".$e->getMessage();
}
try {
//check if
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
# code...
throw new customException($email);
}
} catch (customException $e) {
//Display custom message.
echo $e->errorMessage();
}
try {
//check if
if (filter_var($email2,FILTER_VALIDATE_EMAIL) === false) {
# code...
throw new customException($email2);
}
if (strpos($email2,"example") !== false) {
# code...
throw new Exception("$email2 is a example e-mail.");
}
}
catch(customException $e){
echo $e->errorMessage();
}
catch (Exception $e) {
echo $e->errorMessage();
}
try {
try {
//check for "example" in mail address
if(strpos($email2, "example") !== FALSE) {
//throw exception if email is not valid
throw new Exception($email2);
}
}
catch(Exception $e) {
//re-throw exception
throw new customException($email2);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage();
}
set_exception_handler("myException");
throw new Exception("Uncaught Exception occurred!");
?>
<!-- JQuery -->
<script src="js/jquery-3.1.0.min.js"></script>
</body>
</html>
|
Java
|
UTF-8
| 51,997
| 2.5
| 2
|
[] |
no_license
|
package edu.princeton.cs.roasolver;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Formatter;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Scanner;
import ilog.concert.*;
import ilog.cplex.*;
// finds the revenue-optimal auction!
public class RoaSolver {
// input parameters
private final int b; // number of bidder classes
private final int m; // number of items
private final int c; // number of types
private final int[] n_b; // n_b[bi] = number of bidders in bidder class bi
private final int[] t_c; // t_c[ci] = type class for type ci
private final double[][] p_bc; // p_bc[bi][ci] = probability for a bidder in bidder class bi to have type ci
private final double[][] v_cm; // v_cm[ci][mi] = value of item mi for type ci
// solver
private final IloCplex cplex; // cplex instance
private final IloNumVar[][][] pi_bcm; // pi_bcm[bi][ci][mi] = interim probability for a bidder in bidder class bi to
// get item mi when reporting type ci
private final IloNumVar[][] q_bc; // q_bc[bi][ci] = interim expected price a bidder in bidder class bi pays when
// reporting type ci
// solution to be output
private final double[][][] pi_sol_bcm;
private final double[][] q_sol_bc;
// timing in nanoseconds
private final long startTime;
private final long endTime;
private final long runTime;
// number of iterations of separation oracle
private int soCount;
// encapsulates all internal exceptions
public static class RoaSolverError extends Exception {
// required by Java
private static final long serialVersionUID = 1L;
public RoaSolverError(String message) {
super(message);
}
}
// encapsulates the input needed for a trial
public static class RoaSolverInput {
public final int b; // number of bidder classes
public final int m; // number of items
public final int c; // number of types
public final int[] n_b; // n_b[bi] = number of bidders in bidder class bi
public final int[] t_c; // t_c[ci] = type class for type ci
public final double[][] p_bc; // p_bc[bi][ci] = probability for a bidder in bidder class bi to have type ci
public final double[][] v_cm; // v_cm[ci][mi] = value of item mi for type ci
// simple constructor
public RoaSolverInput(int b, int m, int c, int[] n_b, int[] t_c, double[][] p_bc, double[][] v_cm) {
this.b = b;
this.m = m;
this.c = c;
this.n_b = n_b;
this.t_c = t_c;
this.p_bc = p_bc;
this.v_cm = v_cm;
}
// generates the inputs for all trials by expanding all type classes and
// multiplicity profiles from the given parser
public static RoaSolverInput[] getInputs(RoaSolverParser parser) {
// first half: expand all type classes to explicit types
// temporary variables to iteratively build p_bc, v_cm, t_c
ArrayList<Integer> t_temp_c = new ArrayList<Integer>(); // to build t_c
ArrayList<double[]> p_temp_cb = new ArrayList<double[]>(); // to build p_bc
ArrayList<double[]> v_temp_cm = new ArrayList<double[]>(); // to build v_cm
// expand each type class in turn
for (int ti = 0; ti < parser.t; ti++) {
// iterate through the items, building up the types and the associated
// probabilities
// contains the incomplete types from expanding the items seen so far
// each element is an incomplete type (up to m values, one for each item seen so
// far)
ArrayList<double[]> v_curr_ym = new ArrayList<double[]>();
// contains the probabilities for the corresponding incomplete type
// each element is the probability conditioned on being in this type class
ArrayList<Double> p_curr_y = new ArrayList<Double>();
// base case: empty type with (conditional) certainty
v_curr_ym.add(new double[parser.m]); // empty type
p_curr_y.add(1.0); // full conditional probability
// iterate through items
for (int mi = 0; mi < parser.m; mi++) {
// incomplete types at next iteration
ArrayList<double[]> v_next_ym = new ArrayList<double[]>();
ArrayList<Double> p_next_y = new ArrayList<Double>();
// for every incomplete type so far...
int y = v_curr_ym.size();
for (int yi = 0; yi < y; yi++) {
// get the incomplete type and associated probability
double[] v_curr_m = v_curr_ym.get(yi);
double p_curr = p_curr_y.get(yi);
// case 1: this type class uses a single value for this item
if (parser.d_mt[mi][ti].charAt(0) != 'D') {
// copy previous incomplete type
double[] v_next_m = v_curr_m;
double p_next = p_curr;
// update the incomplete type by adding an entry for this item
// (only one possible updated type so we just override the old array)
v_next_m[mi] = Double.parseDouble(parser.d_mt[mi][ti]);
// add updated incomplete type to collection
v_next_ym.add(v_next_m);
p_next_y.add(p_next);
}
// case 2: this type class uses a valuation distribution for this item
else {
// the valuation distribution used
int ri = Integer.parseInt(parser.d_mt[mi][ti].substring(1)) - 1;
// go through all possible values/probabilities for this item (in the support)
for (int si = 0; si < parser.s; si++) {
// skip impossible values for this valuation distribution
if (parser.phi_rs[ri][si] == 0.0)
continue;
// copy previous incomplete type
double[] v_next_m = v_curr_m.clone();
double p_next = p_curr;
// update the incomplete type by adding an entry for this item
v_next_m[mi] = parser.u_s[si];
p_next *= parser.phi_rs[ri][si];
// add updated incomplete type to collection
v_next_ym.add(v_next_m);
p_next_y.add(p_next);
}
}
// finished iterating through this incomplete type
}
// finished iterating through this item, so update and continue
v_curr_ym = v_next_ym;
p_curr_y = p_next_y;
}
// finished calculating all types and probabilities for this type class
// now iterate through each type in this type class and expand
int y = v_curr_ym.size();
for (int yi = 0; yi < y; yi++) {
// type and associated probability
double[] v_m = v_curr_ym.get(yi);
double p = p_curr_y.get(yi);
// actual probabilities for this type (removing conditioning on being from this
// type class)
double[] p_b = new double[parser.b];
for (int bi = 0; bi < parser.b; bi++) {
p_b[bi] = p * parser.p_bt[bi][ti];
}
// add these types and probabilities to the collections
t_temp_c.add(ti);
p_temp_cb.add(p_b);
v_temp_cm.add(v_m);
}
// finished with this type class
}
// finished with expanding all type classes
// calculate c, t_c, p_bc, v_cm
int c = p_temp_cb.size();
int[] t_c = new int[c];
for (int ci = 0; ci < c; ci++) {
t_c[ci] = t_temp_c.get(ci);
}
double[][] p_bc = new double[parser.b][c];
for (int bi = 0; bi < parser.b; bi++) {
for (int ci = 0; ci < c; ci++) {
p_bc[bi][ci] = p_temp_cb.get(ci)[bi];
}
}
double[][] v_cm = new double[c][parser.m];
for (int ci = 0; ci < c; ci++) {
for (int mi = 0; mi < parser.m; mi++) {
v_cm[ci][mi] = v_temp_cm.get(ci)[mi];
}
}
// second half: expand all possible multiplicity profiles
// iterate through the bidder classes, building up the multiplicity profiles
// contains the multiplicity profiles from expanding the bidder classes so far
// each element is an incomplete multiplicity profile (up to b values, one for
// each bidder class seen so far)
ArrayList<int[]> n_curr_yb = new ArrayList<int[]>();
// base case: empty multiplicity profile
n_curr_yb.add(new int[parser.b]);
// iterate through each bidder class
for (int bi = 0; bi < parser.b; bi++) {
// multiplicity profiles at next iteration
ArrayList<int[]> n_next_yb = new ArrayList<int[]>();
// for every incomplete multiplicity profile so far...
int y = n_curr_yb.size();
for (int yi = 0; yi < y; yi++) {
// get the current incomplete multiplicity profile
int[] n_curr_b = n_curr_yb.get(yi);
// go through all possible multiplicities for this bidder class
int z = parser.n_bz[bi].length;
for (int zi = 0; zi < z; zi++) {
// copy previous incomplete multiplicity profile
int[] n_next_b = n_curr_b.clone();
// update the incomplete multiplicity profile by adding a multiplicity for this
// bidder class
n_next_b[bi] = parser.n_bz[bi][zi];
// add updated multiplicity profile to the collection
n_next_yb.add(n_next_b);
}
}
// finished iterating through this bidder class, so update and continue
n_curr_yb = n_next_yb;
}
// finished calculating all multiplicity profiles
// finally: return all possible outputs
int y = n_curr_yb.size();
RoaSolverInput[] inputs = new RoaSolverInput[y];
for (int yi = 0; yi < y; yi++) {
inputs[yi] = new RoaSolverInput(parser.b, parser.m, c, n_curr_yb.get(yi), t_c, p_bc, v_cm);
}
return inputs;
}
}
// encapsulates the output from a trial
public static class RoaSolverOutput {
// input parameters
public final int b; // number of bidder classes
public final int m; // number of items
public final int c; // number of types
public final int[] n_b; // n_b[bi] = number of bidders in bidder class bi
public final int[] t_c; // t_c[ci] = type class for type ci
public final double[][] p_bc; // p_bc[bi][ci] = probability for a bidder in bidder class bi to have type ci
public final double[][] v_cm; // v_cm[ci][mi] = value of item mi for type ci
// solution
public final double J; // expected revenue
public final double[][][] pi_bcm; // pi_bcm[bi][ci][mi] = interim probability for a bidder in bidder class bi to
// get item mi when reporting type ci
public final double[][] q_bc; // q_bc[bi][ci] = interim expected price a bidder in bidder class bi pays when
// reporting type ci
// timing
public final long runTime; // how long the trial ran for, in nanoseconds
// separation oracle count
public final int soCount; // how many times the separation oracle ran
// simple constructor
public RoaSolverOutput(int b, int m, int c, int[] n_b, int[] t_c, double[][] p_bc, double[][] v_cm, double J,
double[][][] pi_bcm, double[][] q_bc, long runTime, int soCount) {
this.b = b;
this.m = m;
this.c = c;
this.n_b = n_b;
this.t_c = t_c;
this.p_bc = p_bc;
this.v_cm = v_cm;
this.J = J;
this.pi_bcm = pi_bcm;
this.q_bc = q_bc;
this.runTime = runTime;
this.soCount = soCount;
}
// a string representation of the problem and solution, suitable for printing to
// the terminal
public String toFullText() {
StringBuilder sb = new StringBuilder();
Formatter f = new Formatter(sb);
// explicit problem statement
f.format("%d %d %d\n", b, m, c);
for (int ci = 0; ci < c; ci++) {
if (ci != 0)
f.format(" ");
f.format("%8d", t_c[ci] + 1);
}
f.format("\n");
for (int bi = 0; bi < b; bi++) {
for (int ci = 0; ci < c; ci++) {
if (ci != 0)
f.format(" ");
f.format("%8.4f", p_bc[bi][ci]);
}
f.format(" %d\n", n_b[bi]);
}
for (int mi = 0; mi < m; mi++) {
for (int ci = 0; ci < c; ci++) {
if (ci != 0)
f.format(" ");
f.format("%8.4f", v_cm[ci][mi]);
}
f.format("\n");
}
// solution
f.format("\n\n%8.4f\n", J);
for (int bi = 0; bi < b; bi++) {
f.format("\n");
for (int mi = 0; mi < m; mi++) {
for (int ci = 0; ci < c; ci++) {
if (ci != 0)
f.format(" ");
f.format("%8.4f", pi_bcm[bi][ci][mi]);
}
f.format("\n");
}
for (int ci = 0; ci < c; ci++) {
if (ci != 0)
f.format(" ");
f.format("%8.4f", q_bc[bi][ci]);
}
f.format("\n");
}
f.format("\n");
f.format("%8.4f\n", runTime / 1e9d);
f.format("\n");
f.format("\n");
f.close();
return sb.toString();
}
// a string representation of the problem and solution, suitable for viewing as
// a CSV file
public String toFullCSV() {
StringBuilder sb = new StringBuilder();
// explicit problem statement
sb.append(b);
sb.append(',');
sb.append(m);
sb.append(',');
sb.append(c);
sb.append('\n');
for (int ci = 0; ci < c; ci++) {
sb.append(ci == 0 ? "" : ',');
sb.append(t_c[ci] + 1);
}
sb.append('\n');
for (int bi = 0; bi < b; bi++) {
for (int ci = 0; ci < c; ci++) {
sb.append(ci == 0 ? "" : ',');
sb.append(p_bc[bi][ci]);
}
sb.append(',');
sb.append(n_b[bi]);
sb.append('\n');
}
for (int mi = 0; mi < m; mi++) {
for (int ci = 0; ci < c; ci++) {
sb.append(ci == 0 ? "" : ',');
sb.append(v_cm[ci][mi]);
}
sb.append('\n');
}
sb.append('\n');
sb.append('\n');
// solution
sb.append(J);
sb.append('\n');
for (int bi = 0; bi < b; bi++) {
sb.append('\n');
for (int mi = 0; mi < m; mi++) {
for (int ci = 0; ci < c; ci++) {
sb.append(ci == 0 ? "" : ',');
sb.append(pi_bcm[bi][ci][mi]);
}
sb.append('\n');
}
for (int ci = 0; ci < c; ci++) {
sb.append(ci == 0 ? "" : ',');
sb.append(q_bc[bi][ci]);
}
sb.append('\n');
}
sb.append('\n');
sb.append(runTime / 1e9d);
sb.append('\n');
return sb.toString();
}
// a string representation of only the bidder counts and the expected revenue,
// suitable for printing to the terminal
public String toBriefText() {
StringBuilder sb = new StringBuilder();
Formatter f = new Formatter(sb);
for (int bi = 0; bi < b; bi++) {
f.format("%8d ", n_b[bi]);
}
f.format("%8.4f ", J);
f.format("%8.4f\n", runTime / 1e9f);
f.close();
return sb.toString();
}
// a string representation of only the bidder counts and the expected revenue,
// suitable for viewing as a CSV file
public String toBriefCSV() {
StringBuilder sb = new StringBuilder();
for (int bi = 0; bi < b; bi++) {
sb.append(n_b[bi]);
sb.append(',');
}
sb.append(J);
sb.append(',');
sb.append(runTime / 1e9f);
sb.append('\n');
return sb.toString();
}
// a string identifying this output, for use in file names
public String toID() {
StringBuilder sb = new StringBuilder();
for (int bi = 0; bi < b; bi++) {
sb.append('_');
sb.append(n_b[bi]);
}
return sb.toString();
}
}
// helper class to parse, validate, and normalize input
public static class RoaSolverParser {
// parsing location
private final Scanner sc; // scanner to draw input from
private int lineNumber = 0; // number of lines seen so far
private String[] lineTokens; // all the tokens in the current line
private int index; // index of current token in in lineTokens
// parsed inputs
public final int b; // number of bidder classes
public final int m; // number of items
public final int t; // number of type classes
public final int r; // number of valuation distributions
public final int s; // number of values in the support of the valuation distributions
public final int[][] n_bz; // n_bz[bi][zi] possible number of bidders in bidder class bi
public final double[][] p_bt; // p_bt[bi][ti] = (normalized) prob. for bidder class bi to have type class ti
public final String[][] d_mt; // d_mt[mi][ti] = valuation distribution that type class ti has for item mi
public final double[][] phi_rs; // phi_rs[li][si] = (normalized) prob. that valuation distribution li draws
// value u_s[si]
public final double[] u_s; // u_s[si] = value si in the support of the valuation distributions
// advances scanner to next line
private void nextLine() throws RoaSolverError {
try {
lineNumber++;
lineTokens = sc.nextLine().trim().split("\\s+");
index = 0;
} catch (NoSuchElementException e) {
throw new RoaSolverError(String.format("Cannot find line %d!", lineNumber)); // validation_01.txt
}
}
// checks that a line is complete
private void endLine() {
if (index < lineTokens.length)
System.err.printf("Warning: line %d of input has %d unused tokens!\n", lineNumber,
lineTokens.length - index); // validation_02.txt
index = lineTokens.length;
}
// parses the next token as a double
private double nextDouble(String id) throws RoaSolverError {
try {
return Double.parseDouble(lineTokens[index++]);
} catch (NumberFormatException e) {
throw new RoaSolverError(
String.format("Error parsing %s (line %d, token %d) as a double", id, lineNumber, index)); // validation_03.txt
} catch (ArrayIndexOutOfBoundsException e) {
throw new RoaSolverError(String.format("Cannot find %s: line %d is too short!", id, lineNumber)); // validation_04.txt
}
}
// parses the next token as an int
private int nextInt(String id) throws RoaSolverError {
try {
return Integer.parseInt(lineTokens[index++]);
} catch (NumberFormatException e) {
throw new RoaSolverError(
String.format("Error parsing %s (line %d, token %d) as an integer", id, lineNumber, index)); // validation_05.txt
} catch (ArrayIndexOutOfBoundsException e) {
throw new RoaSolverError(String.format("Cannot find %s: line %d is too short!", id, lineNumber)); // validation_06.txt
}
}
// parses the next token as a list of range of ints
// the list is delimited by semicolons
// each range of ints is either x~y or x (e.g. 1~2 or 3)
private int[] nextIntRangeList(String id) throws RoaSolverError {
try {
ArrayList<Integer> rangeList = new ArrayList<Integer>();
String[] tokens = lineTokens[index++].split(";");
for (String token : tokens) {
String[] values = token.split("~");
if (values.length < 1 || values.length > 2)
throw new RoaSolverError(
String.format("Error parsing %s (line %d, token %d) as a valid integer range list", id,
lineNumber, index)); // validation_07.txt
int[] bounds = new int[2];
bounds[0] = Integer.parseInt(values[0]);
bounds[1] = Integer.parseInt(values[values.length == 1 ? 0 : 1]);
if (bounds[0] > bounds[1])
throw new RoaSolverError(
String.format("Error parsing %s (line %d, token %d) as a valid integer range list", id,
lineNumber, index)); // validation_08.txt
for (int yi = bounds[0]; yi <= bounds[1]; yi++) {
rangeList.add(yi);
}
}
int y = rangeList.size();
int[] next = new int[y];
for (int yi = 0; yi < y; yi++) {
next[yi] = rangeList.get(yi);
}
return next;
} catch (NumberFormatException e) {
throw new RoaSolverError(String.format(
"Error parsing %s (line %d, token %d) as a valid integer range list", id, lineNumber, index)); // validation_09.txt
} catch (ArrayIndexOutOfBoundsException e) {
throw new RoaSolverError(String.format("Cannot find %s: line %d is too short!", id, lineNumber)); // validation_10.txt
}
}
// parses the next token as a String
private String nextString(String id) throws RoaSolverError {
try {
return lineTokens[index++];
} catch (ArrayIndexOutOfBoundsException e) {
throw new RoaSolverError(String.format("Cannot find %s: line %d is too short!", id, lineNumber)); // validation_11.txt
}
}
// validates bounds on b, m, t, r, s
private void validateFirstRow() throws RoaSolverError {
if (b < 1)
throw new RoaSolverError("n must be at least 1"); // validation_12.txt
if (m < 1)
throw new RoaSolverError("m must be at least 1"); // validation_13.txt
if (t < 1)
throw new RoaSolverError("c must be at least 1"); // validation_14.txt
if (r < 0)
throw new RoaSolverError("r must be at least 0"); // validation_15.txt
if (s < 0)
throw new RoaSolverError("s must be at least 0"); // validation_16.txt
}
// validates bounds on n_b, p_bt, d_mt, phi_rs, u_s
private void validate() throws RoaSolverError {
// validate contents of n_b
int n = 0;
for (int bi = 0; bi < b; bi++) {
int z = n_bz[bi].length;
if (z < 1)
throw new RoaSolverError(String.format("N_%d cannot be empty", bi + 1)); // validation_17.txt
int min = Integer.MAX_VALUE;
for (int zi = 0; zi < z; zi++) {
if (n_bz[bi][zi] < 0)
throw new RoaSolverError(String.format("n_%d must have a lower bound of at least 0", bi + 1)); // validation_18.txt
if (n_bz[bi][zi] < min)
min = n_bz[bi][zi];
}
n += min;
}
if (n < 1)
throw new RoaSolverError("sum_i n_i must have a lower bound of at least 1"); // validation_19.txt
// validate contents of p_bt
for (int bi = 0; bi < b; bi++) {
double rowSum = 0.0;
for (int ti = 0; ti < t; ti++) {
if (p_bt[bi][ti] < 0.0)
throw new RoaSolverError(String.format("p_{%d,%d} must be nonnegative", bi + 1, ti + 1)); // validation_20.txt
rowSum += p_bt[bi][ti];
}
if (rowSum <= 0.0)
throw new RoaSolverError(String.format("sum_i p_{%d,i} must be positive", bi + 1)); // validation_21.txt
}
// validate contents of d_mt
for (int mi = 0; mi < m; mi++) {
for (int ti = 0; ti < t; ti++) {
// safety check, should be impossible
if (d_mt[mi][ti].length() < 1)
throw new RoaSolverError(String.format("d_{%d,%d} must be nonempty", mi + 1, ti + 1)); // validation_22.txt
// if valuation distribution is specified
if (d_mt[mi][ti].charAt(0) == 'D') {
try {
int li = Integer.parseInt(d_mt[mi][ti].substring(1));
if (li < 1 || r < li)
throw new RoaSolverError(String
.format("d_{%d,%d} is not a valid valuation distribution", mi + 1, ti + 1)); // validation_23.txt
}
catch (NumberFormatException e) {
throw new RoaSolverError(
String.format("d_{%d,%d} is not a valuation distribution", mi + 1, ti + 1)); // validation_24.txt
}
continue;
}
// special case: should be float
try {
Double.parseDouble(d_mt[mi][ti]);
}
catch (NumberFormatException e) {
throw new RoaSolverError(String.format("d_{%d,%d} is not a valid float", mi + 1, ti + 1)); // validation_25.txt
}
}
}
// validate contents of phi_rs
for (int li = 0; li < r; li++) {
double rowSum = 0.0;
for (int si = 0; si < s; si++) {
if (phi_rs[li][si] < 0.0)
throw new RoaSolverError(String.format("phi_{%d,%d} must be nonnegative", li + 1, si + 1)); // validation_26.txt
rowSum += phi_rs[li][si];
}
if (rowSum <= 0.0)
throw new RoaSolverError(String.format("sum_i phi_{%d,i} must be positive", li + 1)); // validation_27.txt
}
// validate the contents of u_s
/* nothing to validate */
}
// normalizes p_bt, phi_rs
private void normalize() {
// normalize p_bt
for (int bi = 0; bi < b; bi++) {
double rowSum = 0.0;
for (int ti = 0; ti < t; ti++) {
rowSum += p_bt[bi][ti];
}
for (int ti = 0; ti < t; ti++) {
p_bt[bi][ti] /= rowSum;
}
}
// normalize phi_rs
for (int ri = 0; ri < r; ri++) {
double rowSum = 0.0;
for (int si = 0; si < s; si++) {
rowSum += phi_rs[ri][si];
}
for (int si = 0; si < s; si++) {
phi_rs[ri][si] /= rowSum;
}
}
}
// parses, validates, and normalizes input
public RoaSolverParser(Scanner sc) throws RoaSolverError {
// save scanner
this.sc = sc;
nextLine();
// first row
b = nextInt("b");
m = nextInt("m");
t = nextInt("t");
r = nextInt("l");
s = nextInt("s");
endLine();
validateFirstRow();
n_bz = new int[b][];
p_bt = new double[b][t];
d_mt = new String[m][t];
phi_rs = new double[r][s];
u_s = new double[s];
// first matrix (p_bt, n_bz)
for (int bi = 0; bi < b; bi++) {
nextLine();
for (int ti = 0; ti < t; ti++) {
p_bt[bi][ti] = nextDouble(String.format("p_{%d,%d}", bi + 1, ti + 1));
}
n_bz[bi] = nextIntRangeList(String.format("n_%d", bi + 1));
endLine();
}
// second matrix (d_mt)
for (int mi = 0; mi < m; mi++) {
nextLine();
for (int ti = 0; ti < t; ti++) {
d_mt[mi][ti] = nextString(String.format("d_{%d,%d}", mi + 1, ti + 1));
}
endLine();
}
// third matrix (phi_rs)
for (int ri = 0; ri < r; ri++) {
nextLine();
for (int si = 0; si < s; si++) {
phi_rs[ri][si] = nextDouble(String.format("r_{%d,%d}", ri + 1, si + 1));
}
endLine();
}
// last row (u_s)
if (s > 0) {
nextLine();
for (int si = 0; si < s; si++) {
u_s[si] = nextDouble(String.format("u_%d", si + 1));
}
endLine();
}
validate();
normalize();
sc.close();
}
// returns the heading line for printing to the terminal
public String getBriefTextHeading() {
StringBuilder sb = new StringBuilder();
for (int bi = 0; bi < b; bi++) {
String name = " n_" + (bi + 1) + " ";
name = name.substring(name.length() - 9);
sb.append(name);
}
sb.append(" rev ");
sb.append(" time\n");
return sb.toString();
}
// returns the heading line for viewing as a CSV file
public String getBriefCSVHeading() {
StringBuilder sb = new StringBuilder();
for (int bi = 0; bi < b; bi++) {
sb.append("n_" + (bi + 1) + ",");
}
sb.append("rev,");
sb.append("time\n");
return sb.toString();
}
}
// creates and solves a trial from the given input
public RoaSolver(RoaSolverInput in) throws RoaSolverError, IloException {
startTime = System.nanoTime();
// instantiate input parameters
this.b = in.b;
this.m = in.m;
this.c = in.c;
this.n_b = in.n_b;
this.t_c = in.t_c;
this.p_bc = in.p_bc;
this.v_cm = in.v_cm;
// instantiate cplex instance
this.cplex = new IloCplex();
this.pi_bcm = new IloNumVar[b][c][m];
this.q_bc = new IloNumVar[b][c];
// shh, quiet!
cplex.setOut(null);
cplex.setWarning(null);
// instantiate solutions
pi_sol_bcm = new double[b][c][m];
q_sol_bc = new double[b][c];
soCount = 0;
// solve!
solve();
// calculate timing
endTime = System.nanoTime();
runTime = endTime - startTime;
}
// returns the output from the solution
public RoaSolverOutput getOutput() throws RoaSolverError {
try {
double J = cplex.getObjValue();
return new RoaSolverOutput(b, m, c, n_b, t_c, p_bc, v_cm, J, pi_sol_bcm, q_sol_bc, runTime, soCount);
} catch (IloException e) {
throw new RoaSolverError("Cannot obtain objective value!");
}
}
// sets up the cplex model and solves it
private void solve() throws IloException {
// create the variables for pi_bcm
for (int bi = 0; bi < b; bi++) {
for (int ci = 0; ci < c; ci++) {
for (int mi = 0; mi < m; mi++) {
String name = "pi_" + (bi + 1) + "_" + (ci + 1) + "_" + (mi + 1);
pi_bcm[bi][ci][mi] = cplex.numVar(0.0, 1.0, name);
}
}
}
// create the variables for q_
for (int bi = 0; bi < b; bi++) {
for (int ci = 0; ci < c; ci++) {
String name = "q_" + (bi + 1) + "_" + (ci + 1);
q_bc[bi][ci] = cplex.numVar(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, name);
}
}
// define the model with constraints, objective, and separation oracle
addIRConstraints();
addBICConstraints();
addObjective();
addSO();
// execute cplex solver
cplex.solve();
// extract solution for pi_bcm
for (int bi = 0; bi < b; bi++) {
for (int ci = 0; ci < c; ci++) {
for (int mi = 0; mi < m; mi++) {
pi_sol_bcm[bi][ci][mi] = cplex.getValue(pi_bcm[bi][ci][mi]);
}
}
}
// extract solution for q_sol
for (int bi = 0; bi < b; bi++) {
for (int ci = 0; ci < c; ci++) {
q_sol_bc[bi][ci] = cplex.getValue(q_bc[bi][ci]);
}
}
}
// adds constraints to ensure that the mechanism is interim IR:
// for each bi, ci, we ensure that
// sum_{mi} (v_cm[ci][mi] * pi_bcm[bi][ci][mi]) - q_bc[bi][ci] >= 0
private void addIRConstraints() throws IloException {
for (int bi = 0; bi < b; bi++) {
for (int ci = 0; ci < c; ci++) {
double[] v_m = v_cm[ci];
IloNumVar[] pi_m = pi_bcm[bi][ci];
IloNumVar q = q_bc[bi][ci];
cplex.addGe(cplex.scalProd(v_m, pi_m), q);
}
}
}
// adds constraints to ensure that the mechanism is BIC:
// for each bi, ci1, ci2, we ensure that
// sum_{mi} (v_cm[ci1][mi] * pi_bcm[bi][ci1][mi]) - q_bc[bi][ci1] >= sum_{mi}
// (v_cm[ci1][mi] * pi_bcm[bi][ci2][mi]) - q_bc[bi][ci2]
private void addBICConstraints() throws IloException {
for (int bi = 0; bi < b; bi++) {
for (int ci1 = 0; ci1 < c; ci1++) {
double[] v_m = v_cm[ci1];
IloNumVar[] pi1_m = pi_bcm[bi][ci1];
IloNumVar q1 = q_bc[bi][ci1];
IloNumExpr expr1 = cplex.diff(cplex.scalProd(v_m, pi1_m), q1);
for (int ci2 = 0; ci2 < c; ci2++) {
if (ci2 == ci1)
continue;
IloNumVar[] pi2_m = pi_bcm[bi][ci2];
IloNumVar q2 = q_bc[bi][ci2];
IloNumExpr expr2 = cplex.diff(cplex.scalProd(v_m, pi2_m), q2);
cplex.addGe(expr1, expr2);
}
}
}
}
// adds the objective function:
// maximize the expected revenue given by
// sum_{bi, ci} (n_b[bi] * q_bc[bi][ci] * p_bc[bi][ci])
private void addObjective() throws IloException {
IloNumExpr[] prods_b = new IloNumExpr[b];
for (int bi = 0; bi < b; bi++) {
double[] p_c = p_bc[bi];
IloNumVar[] q_c = q_bc[bi];
double n = n_b[bi];
prods_b[bi] = cplex.prod(n, cplex.scalProd(q_c, p_c));
}
IloNumExpr J = cplex.sum(prods_b);
// require integer variable to use separation oracle
IloNumVar dummy = cplex.intVar(0, 0, "d");
cplex.addMaximize(cplex.sum(J, dummy));
}
// inner class for separation oracle
// we define the x values as
// x_bcm[bi][ci][mi] = pi_bcm[bi][ci][mi] * sum_{ci' <= ci} (p_bc[bi][ci'])
// for use in the shaded index sets
// S_bmx[bi][mi](x) = { ci | x_bcm[bi][ci][mi] >= x }
// so that we can make sure that for each bi, mi, we have
// sum_{bi, ci in S_bmx[bi][mi](x)} (n_b[bi] * pi_bcm[bi][ci][mi] *
// p_bc[bi][ci]) <= 1 - prod_{bi} (1 - sum_{ci in S_bmx[bi][mi](x)}
// (p_bc[bi][ci]))^(n_b[bi])
// the separation oracle adds any broken constraints to the problem
private class SeparationOracle extends IloCplex.LazyConstraintCallback {
// margin of error for separation oracle
private static final double EPSILON = 1e-5;
// inner class to sort pi values in ascending order
private class PiNode implements Comparable<PiNode> {
public double pi;
public int ci;
public PiNode(double pi, int ci) {
this.pi = pi;
this.ci = ci;
}
public int compareTo(PiNode that) {
if (this.pi > that.pi)
return 1;
if (this.pi < that.pi)
return -1;
return 0;
}
}
// inner class to sort x values in descending order
private class XNode implements Comparable<XNode> {
public double x;
public int bi;
public int ci;
public XNode(double x, int bi, int ci) {
this.x = x;
this.bi = bi;
this.ci = ci;
}
public int compareTo(XNode that) {
if (this.x > that.x)
return -1;
if (this.x < that.x)
return 1;
return 0;
}
}
// executes the separation oracle, adding any broken constraint
protected void main() throws IloException {
soCount++;
// extract pi values at current node
double[][][] pi_mbc = new double[m][b][c];
for (int bi = 0; bi < b; bi++) {
for (int ci = 0; ci < c; ci++) {
for (int mi = 0; mi < m; mi++) {
pi_mbc[mi][bi][ci] = getValue(pi_bcm[bi][ci][mi]);
}
}
}
// iterate through each item, checking that the allocation for that item is
// feasible
for (int mi = 0; mi < m; mi++) {
// create max-heap to sort x nodes in descending order
PriorityQueue<XNode> xn_y = new PriorityQueue<XNode>();
// calculate x node values
for (int bi = 0; bi < b; bi++) {
// create increasing array of pi nodes
PiNode[] pn_c = new PiNode[c];
for (int ci = 0; ci < c; ci++) {
pn_c[ci] = new PiNode(pi_mbc[mi][bi][ci], ci);
}
Arrays.sort(pn_c);
// calculate x values iteratively
// base case
double pi_curr = -1.0; // the largest pi seen so far
double p_sum = 0.0; // sum of all p for all pi <= pi_current
// iterate through each pi node
for (int ci1 = 0; ci1 < c; ci1++) {
PiNode pn = pn_c[ci1];
// if we have a higher pi value
if (pn.pi > pi_curr) {
// update the highest value so far
pi_curr = pn.pi;
// update the sum to include all pi nodes with this value of pi
for (int ci2 = ci1; ci2 < c; ci2++) {
// exhausted all pi nodes with this pi value
if (pn_c[ci2].pi > pi_curr)
break;
p_sum += p_bc[bi][pn_c[ci2].ci];
}
}
// calculate x value and insert into max-heap
xn_y.add(new XNode(pn.pi * p_sum, bi, pn.ci));
}
}
// iterate through the threshold values of x in xn_pq and check the constraint
// base case
ArrayList<XNode> xn_curr_y = new ArrayList<XNode>(); // all x nodes seen so far
double x_curr = Double.POSITIVE_INFINITY; // the smallest x seen so far
double lhs_sum = 0.0; // current value of left hand side
double ln_rhs_prod = 0.0; // natural log of the current value of the product in the right hand side
double[] rhs_b = new double[b]; // current value of multiplicands in the right hand side
for (int bi = 0; bi < b; bi++) {
rhs_b[bi] = 1.0;
}
// iterate through x nodes in decreasing order
while (!xn_y.isEmpty()) {
// next x node
XNode xn_curr = xn_y.poll();
xn_curr_y.add(xn_curr);
x_curr = xn_curr.x;
// update left hand side of constraint
lhs_sum += n_b[xn_curr.bi] * pi_mbc[mi][xn_curr.bi][xn_curr.ci] * p_bc[xn_curr.bi][xn_curr.ci];
// update right hand side of constraint
double prod_prev = rhs_b[xn_curr.bi];
double prod_next = prod_prev - p_bc[xn_curr.bi][xn_curr.ci];
rhs_b[xn_curr.bi] = prod_next;
if (prod_prev != 0.0) { // only updates if still was nonzero
ln_rhs_prod += n_b[xn_curr.bi] * (Math.log(prod_next) - Math.log(prod_prev));
}
// if there are more x nodes with same x value, don't check constraint yet!
if (!xn_y.isEmpty() && xn_y.peek().x == x_curr)
continue;
// if constraint is fine, keep going!
if (lhs_sum <= 1.0 - Math.exp(ln_rhs_prod) + EPSILON)
continue;
// found broken constraint, add it to the problem!
int y = xn_curr_y.size();
IloNumVar[] pi_y = new IloNumVar[y];
double[] np_y = new double[y];
for (int yi = 0; yi < y; yi++) {
XNode xn = xn_curr_y.get(yi);
pi_y[yi] = pi_bcm[xn.bi][xn.ci][mi];
np_y[yi] = n_b[xn.bi] * p_bc[xn.bi][xn.ci];
}
add(cplex.le(cplex.scalProd(pi_y, np_y), 1.0 - Math.exp(ln_rhs_prod)));
return;
}
}
}
}
// adds the separation oracle
private void addSO() throws IloException {
SeparationOracle separationOracle = new SeparationOracle();
cplex.use(separationOracle);
}
// main entry point for RoaSolver
// parses the command line arguments and executes the solver for all trials of
// all problem settings
public static void main(String[] args) throws Exception {
// command-line flags
boolean fullTerminalFlag = false;
boolean fullFileFlag = false;
boolean briefTerminalFlag = false;
boolean briefFileFlag = false;
ArrayList<String> fileNames = new ArrayList<String>();
// process flags
for (String arg : args) {
// not a flag, so it must be a file name
if (arg.charAt(0) != '-') {
fileNames.add(arg);
continue;
}
if (arg.equals("-ft")) {
fullTerminalFlag = true;
continue;
}
if (arg.equals("-ff")) {
fullFileFlag = true;
continue;
}
if (arg.equals("-bt")) {
briefTerminalFlag = true;
continue;
}
if (arg.equals("-bf")) {
briefFileFlag = true;
continue;
}
System.err.println("Error processing input due to unrecognized flag: " + arg);
return;
}
// ensure at least some input
if (!fullTerminalFlag && !fullFileFlag && !briefTerminalFlag && !briefFileFlag) {
briefTerminalFlag = true;
}
// ensure at least one input file
if (fileNames.size() == 0) {
System.err.println("Error: no input file(s) specified!");
return;
}
// iterate through each file to read and solve, writing according to flags
for (String fileName : fileNames) {
// header in terminal
System.out.println();
System.out.println("========================================");
System.out.println("File: " + fileName);
System.out.println();
System.out.flush();
try {
// parse file
Scanner sc = new Scanner(new File(fileName));
RoaSolverParser parser = new RoaSolverParser(sc);
// start accumulating brief output
StringBuilder briefText = new StringBuilder(parser.getBriefTextHeading());
StringBuilder briefCSV = new StringBuilder(parser.getBriefCSVHeading());
// iterate through each trial
for (RoaSolverInput input : RoaSolverInput.getInputs(parser)) {
// execute the trial
RoaSolver solver = new RoaSolver(input);
RoaSolverOutput output = solver.getOutput();
// accumulte brief output
briefText.append(output.toBriefText());
briefCSV.append(output.toBriefCSV());
// for full terminal output
if (fullTerminalFlag) {
System.out.println(output.toFullText());
}
// for full file output
if (fullFileFlag) {
String newFileName = fileName + output.toID() + "_solution.csv";
FileWriter fileWriter = new FileWriter(newFileName);
PrintWriter out = new PrintWriter(fileWriter);
out.print(output.toFullCSV());
out.close();
System.out.println();
System.out.println("Wrote full solution to " + newFileName);
System.out.println();
}
}
// for brief terminal output
if (briefTerminalFlag) {
System.out.println();
System.out.println("========================================");
System.out.println("Summary of file: " + fileName);
System.out.println();
System.out.println(briefText.toString());
}
// for brief file output
if (briefFileFlag) {
String newFileName = fileName + "_solutions.csv";
FileWriter fileWriter = new FileWriter(newFileName);
PrintWriter out = new PrintWriter(fileWriter);
out.print(briefCSV);
out.close();
System.out.println();
System.out.println("Wrote brief solution to " + newFileName);
System.out.println();
}
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (RoaSolverError e) {
System.err.println(e.getMessage());
}
}
}
}
|
Java
|
UTF-8
| 1,297
| 2.171875
| 2
|
[] |
no_license
|
package com.neueda.tinyurl.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.ToString;
/**
* This is entity class for TinyUrl.
*/
@Entity
@Table(name = "url_process")
@ToString
public class TinyUrl {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long urlPrivacyid;
@Column(nullable = false)
private String longUrl;
@Column(nullable = false)
private Timestamp expiryTimestamp;
private Timestamp createdTimestamp;
public long getUrlPrivacyid() {
return urlPrivacyid;
}
public void setUrlPrivacyid(long urlPrivacyid) {
this.urlPrivacyid = urlPrivacyid;
}
public String getLongUrl() {
return longUrl;
}
public void setLongUrl(String longUrl) {
this.longUrl = longUrl;
}
public Timestamp getExpiryTimestamp() {
return expiryTimestamp;
}
public void setExpiryTimestamp(Timestamp expiryTimestamp) {
this.expiryTimestamp = expiryTimestamp;
}
public Timestamp getCreatedTimestamp() {
return createdTimestamp;
}
public void setCreatedTimestamp(Timestamp createdTimestamp) {
this.createdTimestamp = createdTimestamp;
}
}
|
Swift
|
UTF-8
| 659
| 2.734375
| 3
|
[] |
no_license
|
//
// AEFontType.swift
// SampleAgentExpo
//
// Created by Sriram, Krishnan on 3/20/17.
// Copyright © 2017 Sriram, Krishnan. All rights reserved.
//
import Foundation
import UIKit
class AEFontType {
var fontType: String!
var font: AEFont!
init(fontType: String, font: AEFont) {
self.fontType = fontType
self.font = font
}
func fontFromType() -> UIFont {
var fontName = self.font.fontName
if self.font.fontStyle != nil && self.font.fontStyle.characters.count > 0 {
fontName = fontName! + "-" + self.font.fontStyle
}
return UIFont(name: fontName!, size: self.font.fontSize)!
}
}
|
Python
|
UTF-8
| 85
| 3.078125
| 3
|
[] |
no_license
|
a, b = int(input()), int(input())
my_range = range(a, b + 1)
print(*tuple(my_range))
|
JavaScript
|
UTF-8
| 1,042
| 3.046875
| 3
|
[] |
no_license
|
window.onload = () => {
var gridSize = { x:32, y:32 };
var grid = Array.from(Array(gridSize.x), () => new Array(gridSize.y));
for (let x = 0; x < gridSize.x; x++) for (let y = 0; y < gridSize.y; y++) grid[x][y] = new Cell({ x:x, y:y }, (Math.floor(Math.random()*10) < 3) ? 'wall' : 'floor');
grid.forEach(row => row.forEach(cell => cell.addNeighbors(grid)));
var gridStart = grid[0][0];
gridStart.tile = 'floor';
var gridEnd = grid[gridSize.x-1][gridSize.y-1];
gridEnd.tile = 'floor';
var pathFinder = new Astar(grid, gridStart, gridEnd);
var display = new Display(pathFinder);
display.drawGrid();
var startTime = Date.now();
var frame = () => {
if (pathFinder.isSearching) {
pathFinder.search();
display.drawFrame(pathFinder);
requestAnimationFrame(frame);
}
else display.drawMessage(pathFinder.isSolvable ? Math.floor(Date.now() - startTime) / 1000 + 's' : 'NOT SOLVABLE');
}
requestAnimationFrame(frame);
}
|
Go
|
UTF-8
| 2,263
| 2.8125
| 3
|
[
"AGPL-3.0-only",
"Apache-2.0"
] |
permissive
|
package registry
import (
"testing"
"github.com/replicatedhq/kots/pkg/kotsutil"
"github.com/replicatedhq/kots/pkg/registry/types"
)
func Test_shouldGarbageCollectImages(t *testing.T) {
type args struct {
isKurl bool
kurlRegistryHost string
installParams kotsutil.InstallationParams
registrySettings types.RegistrySettings
}
tests := []struct {
name string
args args
want bool
}{
{
name: "return false if image garbage collection is disabled",
args: args{
installParams: kotsutil.InstallationParams{
EnableImageDeletion: false,
},
},
want: false,
},
{
name: "return false if registry is read only",
args: args{
installParams: kotsutil.InstallationParams{
EnableImageDeletion: true,
},
registrySettings: types.RegistrySettings{
IsReadOnly: true,
},
},
want: false,
},
{
name: "return false if cluster is not kurl cluster",
args: args{
isKurl: false,
installParams: kotsutil.InstallationParams{
EnableImageDeletion: true,
},
registrySettings: types.RegistrySettings{
IsReadOnly: false,
},
},
want: false,
},
{
name: "return false registry is not kurl registry/ when external registry is configured",
args: args{
isKurl: true,
kurlRegistryHost: "registry.kurl.sh",
installParams: kotsutil.InstallationParams{
EnableImageDeletion: true,
},
registrySettings: types.RegistrySettings{
IsReadOnly: false,
Hostname: "registry.replicated.com",
},
},
want: false,
},
{
name: "return true when image garbage collection is enabled",
args: args{
isKurl: true,
kurlRegistryHost: "registry.kurl.sh",
installParams: kotsutil.InstallationParams{
EnableImageDeletion: true,
},
registrySettings: types.RegistrySettings{
IsReadOnly: false,
Hostname: "registry.kurl.sh",
},
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := shouldGarbageCollectImages(tt.args.isKurl, tt.args.kurlRegistryHost, tt.args.installParams, tt.args.registrySettings); got != tt.want {
t.Errorf("shouldGarbageCollectImages() = %v, want %v", got, tt.want)
}
})
}
}
|
Java
|
UTF-8
| 1,597
| 1.953125
| 2
|
[] |
no_license
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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 com.castlabs.appdemo;
import java.util.Locale;
/**
* Holds statically defined sample definitions.
*/
class StreamSamples {
public static class StreamSample {
public final String name;
public final String contentId;
public final String provider;
public final String uri;
public StreamSample(String name, String uri) {
this(name, name.toLowerCase(Locale.US).replaceAll("\\s", ""), "FOX", uri);
}
public StreamSample(String name, String contentId, String provider, String uri) {
this.name = name;
this.contentId = contentId;
this.provider = provider;
this.uri = uri;
}
}
public static final StreamSample[] DASH_MP4 = new StreamSample[] {
new StreamSample("Smurfs",
" http://demo.unified-streaming.com/video/smurfs/smurfs.ism/smurfs.mpd"),
new StreamSample("Formula 1",
"http://dash.edgesuite.net/envivio/dashpr/clear/Manifest.mpd"),
};
private StreamSamples() {}
}
|
Java
|
UTF-8
| 9,281
| 2.390625
| 2
|
[] |
no_license
|
package ru.betnews.service.news;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.betnews.criteria.NewsCriteria;
import ru.betnews.dao.BetDao;
import ru.betnews.dao.CommentDao;
import ru.betnews.dao.NewsDao;
import ru.betnews.dao.OutcomeDao;
import ru.betnews.entity.*;
import ru.betnews.entity.dto.*;
import ru.betnews.service.user.RemittanceService;
import ru.betnews.service.user.UserService;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: Евгений
* Date: 20.03.15
* Time: 22:16
* Сервис новостей
*/
@Service
public class NewsServiceImpl implements NewsService{
@Resource
private NewsDao newsDao;
@Resource
private OutcomeDao outcomeDao;
@Resource
private CommentDao commentDao;
@Resource
private BetDao betDao;
@Resource
private RemittanceService remittanceService;
@Override
@Transactional(readOnly = true)
public List<News> list(NewsCriteria newsCriteria) {
return newsDao.getByCriteria(newsCriteria);
}
@Override
@Transactional(readOnly = true)
public News getById(long id) {
return newsDao.read(id);
}
@Override
@Transactional
public NewsDTO create(NewsDTO newsDTO, User user) {
News news = new News();
news.setTitle(newsDTO.getTitle());
news.setDescription(newsDTO.getDescription());
news.setNewsTopic(newsDTO.getNewsTopic());
news.setNewsType(newsDTO.getNewsType());
news.setUser(user);
if(newsDTO.getNewsType() == NewsType.PUBLIC)
news.setArbiter(user);
news = newsDao.create(news);
for(OutcomeDTO outcomeDTO: newsDTO.getOutcomes()){
Outcome outcome = new Outcome();
outcome.setDescription(outcomeDTO.getDescription());
outcome.setNumber(outcomeDTO.getNumber());
outcome.setNews(news);
outcome = outcomeDao.create(outcome);
news.getOutcomes().add(outcome);
}
return new NewsDTO(news);
}
@Override
@Transactional
public void delete(long newsId) {
News news = getById(newsId);
news.setArchive(true);
news.setArchiveDate(new Date());
newsDao.saveOrUpdate(news);
}
@Override
@Transactional(readOnly = true)
public List<NewsDTO> getNewsList(NewsCriteria newsCriteria) {
List<NewsDTO> newsDTOList = new ArrayList<>();
for(News news : newsDao.getByCriteria(newsCriteria)){
NewsDTO newsDTO = new NewsDTO(news);
newsDTOList.add(newsDTO);
}
return newsDTOList;
}
@Override
@Transactional
public CommentDTO addComment(long newsId, String description, User user, Long replayComment) {
News news = newsDao.read(newsId);
Comment comment = new Comment();
comment.setDate(new Date());
comment.setDescription(description);
comment.setNews(news);
comment.setUser(user);
if(replayComment != null){
Comment replay = commentDao.read(replayComment);
if(replay != null){
comment.setReplay(replay);
}
}
comment = commentDao.create(comment);
return new CommentDTO(comment);
}
@Override
@Transactional
public OutcomeDTO outcomeVote(long newsId, long outcomeId, double value, User user) throws Exception {
Outcome outcome = outcomeDao.read(outcomeId);
News news = newsDao.read(newsId);
if(news.getArbiter().equals(user)) throw new Exception("can.not.vote.arbiter");//Арбитр не может голосовать за новость!
if(news.isArchive()) throw new Exception("can.not.vote.archive");//Нельзя голосовать за архивную новость!
if(news.getNewsType().equals(NewsType.PRIVATE) && !news.getCanVoteUsers().contains(user)) throw new Exception("can.not.vote.private");//За эту новость Вам нельзя голосовать!
if(user.getAccount().getBalance() < value) throw new Exception("can.not.vote.money");//Вам не хватает срадств, что бы сделать такую ставку!
for(Outcome o : news.getOutcomes()){
for(Bet bet : o.getBets())
if(bet.getUser().equals(user))
throw new Exception("can.not.vote.already");//Вы уже голосовали за эту новость!
}
remittanceService.payToSystem(user, value);
Bet bet = new Bet();
bet.setUser(user);
bet.setOutcome(outcome);
bet.setBetValue(value);
bet = betDao.create(bet);
outcome.getBets().add(bet);
return new OutcomeDTO(outcome);
}
@Override
public NewsDTO edit(NewsDTO newsDTO) throws Exception {
News news = newsDao.read(newsDTO.getId());
if(news != null){
news.setTitle(newsDTO.getTitle());
news.setDescription(newsDTO.getDescription());
news.setNewsTopic(newsDTO.getNewsTopic());
news.setNewsType(newsDTO.getNewsType());
//TODO edit outcomes, проверка, что новость не отркрыта
newsDao.saveOrUpdate(news);
} else throw new Exception("news.not.found");
return new NewsDTO(news);
}
@Override
public void approve(long newsId, User user) {
News news = newsDao.read(newsId);
if(news != null){
}
}
@Override
@Transactional
public void confirm(long outcomeId, User user, String confirmation, String commentDesc) {
Outcome outcome = outcomeDao.read(outcomeId);
if(outcome != null){
outcome.setConfirmed(true);
outcomeDao.saveOrUpdate(outcome);
//Добавить комментарий
String description = "Арбитр " + user.getUserNick() + "подтвердил исход новости \"" + outcome.getDescription() + "\".";
description = confirmation != null? description + "<br/>Cсылка на подтверждение: " + confirmation : description;
description = commentDesc != null? description + "<br/>Комментарий: " + commentDesc : description;
addComment(outcome.getNews().getId(), description, user, null);
//Рассчитать награду
//Рассчитать рейтинг
outcome.getNews().setArchive(true);
newsDao.saveOrUpdate(outcome.getNews());
}
}
@Override
public List<NewsDTO> getUserNews(User user) {
List<NewsDTO> newsDTOList = new ArrayList<>();
for(News news : newsDao.getUserNews(user)){
NewsDTO newsDTO = new NewsDTO(news);
newsDTOList.add(newsDTO);
}
return newsDTOList;
}
@Override
@Transactional
public CommentDTO likeComment(long commentId, User user) {
Comment comment = commentDao.read(commentId);
if(!comment.getLikes().contains(user)) {
comment.getLikes().add(user);
if(comment.getDislikes().contains(user))
comment.getDislikes().remove(user);
commentDao.saveOrUpdate(comment);
}
return new CommentDTO(comment);
}
@Override
@Transactional
public CommentDTO dislikeComment(long commentId, User user) {
Comment comment = commentDao.read(commentId);
if(!comment.getDislikes().contains(user)) {
comment.getDislikes().add(user);
if(comment.getLikes().contains(user))
comment.getLikes().remove(user);
commentDao.saveOrUpdate(comment);
}
return new CommentDTO(comment);
}
@Override
@Transactional
public NewsDTO likeNews(long newsId, User user) {
News news = newsDao.read(newsId);
if(!news.getLikes().contains(user)) {
news.getLikes().add(user);
if(news.getDislikes().contains(user))
news.getDislikes().remove(user);
newsDao.saveOrUpdate(news);
}
return new NewsDTO(news);
}
@Override
@Transactional
public NewsDTO dislikeNews(long newsId, User user) {
News news = newsDao.read(newsId);
if(!news.getDislikes().contains(user)) {
news.getDislikes().add(user);
if(news.getLikes().contains(user))
news.getLikes().remove(user);
newsDao.saveOrUpdate(news);
}
return new NewsDTO(news);
}
public List<NewsDTO> getCarousel(){
List<NewsDTO> newsDTOList = new ArrayList<>();
for(News news : newsDao.getCarousel()){
newsDTOList.add(new NewsDTO(news));
}
return newsDTOList;
}
@Override
public List<NewsDTO> getPopularNews() {
List<NewsDTO> newsDTOList = new ArrayList<>();
for(News news : newsDao.getPopularNews()){
newsDTOList.add(new NewsDTO(news));
}
return newsDTOList;
}
}
|
Java
|
UTF-8
| 2,592
| 2.5
| 2
|
[] |
no_license
|
package uk.org.cse.stockimport.imputation.walls;
import java.util.Map;
import java.util.Set;
import org.joda.time.DateTime;
import uk.org.cse.nhm.energycalculator.api.types.WallConstructionType;
import uk.org.cse.nhm.energycalculator.api.types.WallInsulationType;
import uk.org.cse.nhm.energycalculator.api.types.RegionType.Country;
import uk.org.cse.nhm.energycalculator.api.types.SAPAgeBandValue;
import uk.org.cse.nhm.energycalculator.api.types.SAPAgeBandValue.Band;
/**
* Interface for thing which imputes the u-values, k-values etc. for walls.
*
* @author hinton
* @since 1.0
*/
public interface IWallPropertyImputer {
/**
* Get the U-value for a wall based on these attributes for the wall and the property
* @param earliestBuild earliest possible build date for the house
* @param latestBuild latest possible build date for the house
* @param constructionType wall's construction type
* @param country where the house is
* @param insulationThicknesses a map from applied insulation types to thicknesses in mm
* @param wallThickness thickness of the wall, or zero if missing or whatever.
* @return a u value for the wall
* @since 1.0
*/
public double getUValue(final Band ageBand,
final Country country,
final WallConstructionType constructionType,
final Map<WallInsulationType, Double> insulationThicknesses,
final double wallThickness);
/**
* Get the U-value for a wall based on these attributes for the wall and the property.
*
* Use {@link #getWallThickness(DateTime, DateTime, RegionType, WallConstructionType, Set)} to get thickness.
*
* @param earliestBuild earliest possible build date for the house
* @param latestBuild latest possible build date for the house
* @param constructionType wall's construction type
* @param country where the house is
* @param insulations a set of insulations present
* @return a u value for the wall
* @since 1.0
*/
public double getUValue(final SAPAgeBandValue.Band ageBand,
final Country country,
final WallConstructionType constructionType,
final Set<WallInsulationType> insulations);
/**
* Get the thickness of a wall based on the given set of attributes
* @param earliestDate
* @param latestDate
* @param country
* @param construction
* @param insulations
* @return
* @since 1.0
*/
public double getWallThickness(SAPAgeBandValue.Band ageBand, Country country,
WallConstructionType construction,
Set<WallInsulationType> insulations);
/**
* @since 1.0
*/
double getAirChangeRate(WallConstructionType constructionType);
}
|
Python
|
UTF-8
| 1,332
| 3.234375
| 3
|
[] |
no_license
|
#And this is the third solution, don't quite understand it, but I have figured out the math/code
from time import clock
def convertBase(n,base):
base10 = n
digitLoc=0
converted={}
while base**(digitLoc+1) < base10:
digitLoc += 1
while digitLoc >= 0:
converted.update({digitLoc:base10 / (base**digitLoc)})
base10 = base10 % (base**digitLoc)
digitLoc -= 1
numberStr = ''
revTable = []
for a in converted:
revTable.insert(0,converted[a])
for b in revTable:
numberStr += str(b)
return numberStr
def run(base10,solveFor):
rowBase10 = base10
solveNum = solveFor
rows = convertBase(rowBase10, solveNum) # this is 10**9 in base 7
power = len(rows)-1
count = 0
endCount = 0
product = 1
baseTri = (solveNum*(solveNum+1))/2
for digit in rows:
dig = int(digit)
tri = (dig*(dig+1))/2
#print product, power, tri, dig
count = product*(baseTri**power)*tri
endCount += count
#print count
product *= dig+1
power -= 1
return endCount
runTime = 0
for a in xrange(3000):
b = 10**a
start = clock()
run(b,7)
runTime += clock()-start
#print 'Runtime:', clock()-start, 'seconds'
print runTime
|
Python
|
UTF-8
| 3,386
| 3.421875
| 3
|
[] |
no_license
|
#! python3
import re
import pyperclip
# HOWTO
# create a regex for phone numbers
# create a regex for email addressed
# get the text off the clipboard
# extract email/phone numbers from this list
# copy the extracted email/phone to the clipboard
phone_regex = re.compile(r''
r'(' # greate everything as one group so we can loop the tuple later
r'((\d\d\d) | (\(\d\d\d\)))?' # area code with or without (). area code optional
r'(\s|-)' # space or dash
r'\d\d\d'
r'-'
r'\d\d\d\d' # last 4 digits
r'(((ext (\.)?\s) | x)' # searches for "x" or "ext. " and the collects digits after
r' (\d{2,5))?' # extension number-part (optional)
r')' # end first group
'', re.VERBOSE)
email_regex = re.compile(r''
r'[a-z0-9_.+]+' # Name. one or more
r'@' # @ symbol
r'[a-z0-9_.+]+' # domain name
'', re.VERBOSE | re.IGNORECASE)
def remove_phone_duplicates(removed_duplicates):
"""
created as a function in case lists should not be filtered
removed duplicates from the copied text
:param removed_duplicates: list from find_email_numbers()
:return: removed: list containing no duplicates
"""
removed_items = []
for item in removed_duplicates:
if item not in removed_items:
removed_items.append(item) # append removed_items with non-duplicate information
removed = '\n'.join(removed_items)
return removed
def find_email_numbers():
"""
first half of function finds all the phone numbers and emails from the clipboard.
create all_phone_number list to append all phone numbers to.
second half removes duplicate phone and email addresses
:return: Void
"""
# snippet contains duplicates
text = pyperclip.paste() # copy text from clipboard
extracted_numbers = phone_regex.findall(text) # search clipboard for phone numbers using text var
extracted_email = email_regex.findall(text) # search clipboard for email using text var
all_phone_numbers = [] # since phone numbers are returned as a tuple, we need to append to list
for phone_number in extracted_numbers: # loop over the extracted_numbers and append them to all_phone_numbers
# append only the first string in the tuple as extracted_numbers contains a bunch of useless strings
all_phone_numbers.append(phone_number[0])
results = '\n'.join(all_phone_numbers) + '\n' + '\n'.join(extracted_email) # prints one email / number per line
# pyperclip.copy(results) # copy updated results to clipboard. Not keeping since it contains duplicates
# end duplicates
# remove duplicates
removed_numbers = [remove_phone_duplicates(all_phone_numbers)] # create list and append list with no-dup numbers
removed_emails = [remove_phone_duplicates(extracted_email)] # create email list and append list with no-dup address
updated_list = '\n'.join(removed_numbers) + '\n' + '\n'.join(removed_emails) # combine the two list above
pyperclip.copy(updated_list) # copy list with no duplicate information
find_email_numbers()
|
JavaScript
|
UTF-8
| 2,228
| 3.265625
| 3
|
[] |
no_license
|
function randomRgbColor() { //随机生成RGB颜色
var r = Math.floor(Math.random() * 256); //随机生成256以内r值
var g = Math.floor(Math.random() * 256); //随机生成256以内g值
var b = Math.floor(Math.random() * 256); //随机生成256以内b值
return "rgb(" + r + "," + g + "," + b + ")"; //返回rgb(r,g,b)格式颜色
}
window.onload = function () {
getCheckNum();
document.getElementById("changeImg").onclick=function(){
getCheckNum();
}
}
function draw(checkNum){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = 120;
canvas.height = 40;
context.strokeRect(0, 0, 120, 40);
for (var i = 0; i <= 3; i++) {
var x = 20 + i * 20;
var y = 20 + Math.random() * 10;
var j = Math.floor(Math.random() * 30);
var deg = Math.random() * 90 * Math.PI / 180;//随机弧度
context.fillStyle = randomRgbColor();
context.font = "bold 20px 微软雅黑";
//修改坐标原点和旋转角度
context.translate(x, y);
context.rotate(deg);
context.fillText(checkNum.charAt(i), 0, 0);
//恢复坐标原点和旋转角度
context.rotate(-deg);
context.translate(-x, -y);
}
//干扰线
for (var i = 0; i < 8; i++) {
context.strokeStyle = randomRgbColor();
context.beginPath();
context.moveTo(Math.random() * 120, Math.random() * 40);
context.lineTo(Math.random() * 120, Math.random() * 40);
context.stroke();
}
/**绘制干扰点**/
for (var i = 0; i < 20; i++) {
context.fillStyle = randomRgbColor();
context.beginPath();
context.arc(Math.random() * 120, Math.random() * 40, 1, 0, 2 * Math.PI);
context.fill();
}
}
function getCheckNum() {
$.ajax({
url:"./getCheckNum.do",
type:"post",
dataType:"json",
success:function (result) {
if (result.code === 1) {
draw(result.obj);
}else {
alert("获取验证码失败");
}
},
error:function () {
alert("内部错误");
}
});
}
|
C#
|
UTF-8
| 2,895
| 3.125
| 3
|
[] |
no_license
|
using Sample.Items;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Sample
{
public partial class Form1 : Form
{
private Levenshtein levenshtein;
private List<string> dictionary;
private string inputWord, lastword;
private char[] delimiters = new char[] { '\n', ' ', '.', ',', ';', '?', '!' };
public Form1()
{
InitializeComponent();
levenshtein = new Levenshtein();
dictionary = new List<string>(File.ReadAllLines(@"D:\Projects\words"));
dictionary.ForEach(word => word = word.Trim());
}
private void TextBox_TextChanged(object sender, EventArgs e)
{
try
{
inputWord = TextBox.Text.ToString();
int position = TextBox.SelectionStart;
StringBuilder outputString = new StringBuilder();
position--;
if (position > 1 && delimiters.Contains(inputWord[position]))
{
for (int i = position - 1; i >= 0; i--)
{
if (delimiters.Contains(inputWord[i])) { break; }
outputString.Append(inputWord[i]);
}
inputWord = Reverse(outputString.ToString());
if (!Check(inputWord))
{
List<Tuple<int, string>> comparator = new List<Tuple<int, string>>();
foreach (string word in dictionary)
{
comparator.Add(new Tuple<int, string>(levenshtein.calculate(inputWord, word), word));
}
comparator.Sort((x, y) => x.Item1.CompareTo(y.Item1));
lastword = comparator[0].Item2.ToString();
TextBox.Text = TextBox.Text.Replace(inputWord, lastword);
}
}
TextBox.SelectionStart = TextBox.Text.Length;
} catch(Exception exception)
{
MessageBox.Show("Something went wrong:\n" + exception.ToString());
}
}
public static string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public Boolean Check (string word)
{
foreach (string archiveWord in dictionary)
{
if (archiveWord.Equals(inputWord))
{
return true;
}
}
return false;
}
}
}
|
C#
|
UTF-8
| 1,030
| 3.125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
public class TileNode
{
private Tile _tile;
private TileNode _next;
private double _x;
private double _y;
public TileNode(Tile tile, double x, double y) {
_tile = tile;
_x = x;
_y = y;
}
public Tile CurrentTile
{
get
{
return _tile;
}
}
public double X
{
get
{
return _x;
}
}
public double Y
{
get
{
return _y;
}
}
public TileNode Next
{
get
{
return _next;
}
}
public void AttachTile(TileNode nextNode)
{
_next = nextNode;
}
}
}
|
Python
|
UTF-8
| 1,159
| 2.8125
| 3
|
[] |
no_license
|
import pytest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener
class MyListener(AbstractEventListener):
def before_find(self, by, value, driver):
print(by, value)
def after_find(self, by, value, driver):
print(by, value, "found")
def on_exception(self, exception, driver):
print(exception)
@pytest.fixture
def driver(request):
wd = EventFiringWebDriver(webdriver.Chrome(), MyListener())
request.addfinalizer(wd.quit)
return wd
def test_example(driver):
driver.get('http://www.google.com')
driver.find_element_by_name('btnK')
driver.get_screenshot_as_file('screen0.png')
driver.find_element_by_name('nbtnI')
driver.get_screenshot_as_file('screen1.png')
driver.find_element_by_name('q').send_keys('webdriver')
driver.find_element_by_name('q').send_keys(Keys.RETURN)
WebDriverWait(driver, 5).until(EC.title_contains('webdriver'))
|
C
|
UTF-8
| 381
| 2.984375
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv){
char str1[100], str2[100];
char str3[200] = {0};
printf("Enter first text: ");
gets(str1);
printf("Enter second text: ");
gets(str2);
strcat(str3,str1);
strcat(str3, str2);
printf("The merged text is: %s\n", str3);
return 0;
}
|
JavaScript
|
UTF-8
| 2,000
| 2.984375
| 3
|
[] |
no_license
|
var assert = require('assert');
var Hero = require('../hero.js');
var Food = require('../food.js');
var Task = require('../task.js');
describe('Hero', function() {
var hero;
var foodA;
var foodB;
var taskA;
var taskB;
var taskC;
beforeEach( function() {
hero = new Hero( 'Link', 100, 'Apple' );
foodA = new Food( 'Chocolate' );
foodB = new Food( 'Crisps' );
taskA = new Task( 3, 4, 150, true );
new Person("Alex", 1.80)
var params =
new Task({difficultyLevel: 0, urgencyRating:1 });
taskB = new Task( 5, 1, 250, false );
taskC = new Task( 4, 3, 100, true );
});
it('should have a name', function() {
assert.strictEqual( hero.name, 'Link' );
});
it('should have a health value', function() {
assert.strictEqual( hero.healthValue, 100 );
});
it('should have a favourite food', function() {
assert.strictEqual( hero.favouriteFood, 'Apple' );
});
it('should have an empty task array', function() {
assert.strictEqual( hero.tasks.length, 0 );
});
it('should be able to talk and say their name', function() {
assert.strictEqual( hero.talk(), "My name is Link" );
});
it('should replenish energy when eating food', function() {
var newHero = new Hero( 'Solid Snake', 80, 'Crisps');
newHero.eatFood( foodA );
assert.strictEqual( newHero.healthValue, 90 );
});
it('should replenish extra energy if food is favourite', function() {
var newHero = new Hero('Solid Snake', 85, 'Crisps');
newHero.eatFood( foodB );
assert.strictEqual( newHero.healthValue, 100 );
});
it('should be able to add a task to tasks', function() {
hero.addTask( taskA );
hero.addTask( taskB );
assert.strictEqual( hero.tasks.length, 2 );
});
it('should be able to sort tasks by urgency', function() {
hero.addTask( taskA );
hero.addTask( taskB );
hero.addTask( taskC );
hero.sortUrgency();
assert.deepEqual( hero.tasks, [ taskB, taskC, taskA ] );
});
hero.getIn
})
|
Python
|
UTF-8
| 155
| 3.515625
| 4
|
[] |
no_license
|
#!/usr/bin/env python3
hungry = True
x = 'Feed the bear now!' if hungry else 'Do not feed the bear.' # must have both if and else statements
print(x)
|
PHP
|
UTF-8
| 876
| 2.640625
| 3
|
[] |
no_license
|
<?php
namespace Etcpasswd\OAuthBundle\Provider\Token;
/**
*
* @author Marcel Beerta <marcel@etcpasswd.de>
*/
interface TokenResponseInterface
{
/**
* Return the username attached to this token
*
* @return string
*/
function getUsername();
/**
* Return the access token which can be used for
* further api calls
*
* @return string
*/
function getAccessToken();
/**
* Returns the unix timestamp when this token will expire
* and api calls are no longer be possible
*
* @return int
*/
function getExpires();
/**
* Returns wether or not this token is expiring at all
*
* @return bool
*/
function isLongLived();
/**
* Returns the provider id used to generate the access
* token
*
* @returun string
*/
function getProviderKey();
}
|
JavaScript
|
UTF-8
| 738
| 3.796875
| 4
|
[] |
no_license
|
/*
* Variabel yang dapat diakses dari seluruh script disebut dengan “globally scoped”,
* sementara variabel yang hanya diakses hanya pada fungsi tertentu disebut dengan “locally scoped”.
* Perlu kita perhatikan, jika kita lupa menuliskan keyword let, const, atau var pada script ketika membuat sebuah variabel,
* maka variabel tersebut akan menjadi global.
*/
// global variable, dapat diakses pada parent() dan child()
const a = 'a';
function parent() {
// local variable, dapat diakses pada parent() dan child(), tetapi tidak dapat diakses di luar dari fungsi tersebut.
const b = 'b';
function child() {
// local variable, dapat diakses hanya pada fungsi child().
const c = 'c';
}
}
|
C++
|
UTF-8
| 2,552
| 2.9375
| 3
|
[] |
no_license
|
#include <GL/glut.h> // GLUT, include glu.h and gl.h
#include <iostream>
using namespace std;
void reshape(int width, int height){
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, height, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
}
//Incremental
void line3d(int x1, int y1, int x2, int y2){
int x, y;
float a;
//int valor;
a=static_cast<float>(y2-y1)/static_cast<float>((x2-x1));
for (x=x1;x<=x2;x++){
y = static_cast<int>(y1 + a*(x - x1));
glVertex3f(x, y, 0.0f); //write_pixel(x, y, color);
}
}
//Incremental
void line(int x1, int y1, int x2, int y2){
int x, y;
float a;
//int valor;
a=static_cast<float>(y2-y1)/static_cast<float>((x2-x1));
for (x=x1;x<=x2;x++){
y = static_cast<int>(y1 + a*(x - x1));
glVertex2f(x, y); //write_pixel(x, y, color);
}
}
//Punto medio
void lineM(int x1, int y1, int x2, int y2){
GLfloat dx, dy, incE, incNE, d, x, y;
dx = x2 - x1;
dy = y2 - y1;
d = 2 * dy-dx;
incE = 2 * dy;
incNE = 2 * (dy-dx);
x=x1;
y=y1;
glVertex2f(x,y);
while(x<x2){
if(d<=0){
d = d + incE;
x++;
}else{
d = d + incNE;
x++;
y++;
}
glVertex2f(x,y);
}
}
void display() {
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer (background)
glColor3f(1.0f, 0.0f, 0.0f); // Red
glLoadIdentity();
glBegin(GL_POINTS);
//line(100, 150, 300, 250); //line(x1, y1, x2, y2) Incremental
line3d(100, 150, 300, 250);
//lineM(100, 150, 300, 250); //lineM(x1, y1, x2, y2) Punto medio
glEnd();
glFlush(); // Render now
}
void Init(){
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
}
/* Main function: GLUT runs as a console application starting at main() */
int main(int argc, char** argv) {
glutInit(&argc, argv); // Initialize GLUT
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(50, 50); // Position the window's initial top-left corner
glutInitWindowSize(400, 400); // Set the window's initial width & height
glutCreateWindow("OpenGL Setup Test"); // Create a window with the given title
Init();
glutDisplayFunc(display); // Register display callback handler for window re-paint
glutReshapeFunc(reshape);
glutMainLoop(); // Enter the event-processing loop
return 0;
}
|
SQL
|
UTF-8
| 3,104
| 3.4375
| 3
|
[] |
no_license
|
SET SERVEROUTPUT ON
SET SERVEROUTPUT OFF
--UNDEFINE p_test
DECLARE
--v_test NUMBER(5) := &p_test;
--v_test2 VARCHAR(40) := '&p_test2';
v_cod departments.department_id%TYPE := &p_cod;
v_location_id departments.location_id%TYPE;
BEGIN
--v_test := v_test + 25;
DBMS_OUTPUT.PUT_LINE('Test' || ' ' || v_test || ' ' || v_test2);
SELECT location_id
INTO v_location_id
FROM departments
WHERE department_id = v_cod;
DBMS_OUTPUT.PUT_LINE('Departamenul cu codu: ' || v_cod || ' are locatia ' || v_location_id);
END;
/
--- ||| ---
DECLARE
v_salariu employees.salary%type;
v_cod employees.employee_id%type := &p_cod2;
v_bonus number(10);
BEGIN
select salary
into v_salariu
from employees
where employee_id = v_cod;
if v_salariu > 10000 then v_bonus := 2000;
elsif v_salariu between 5000 and 10000 then v_bonus := 1000;
else v_bonus := 500;
end if;
DBMS_OUTPUT.PUT_LINE('Salariatul cu codul ' || v_cod || ' v-a primi un bonus de ' || v_bonus);
END;
/
--- ||| ---
DECLARE
v_salariu employees.salary%type;
v_cod employees.employee_id%type := &p_cod2;
v_bonus v_salariu%type;
BEGIN
select salary
into v_salariu
from employees
where employee_id = v_cod;
case
when v_salariu > 10000 then v_bonus := 2000;
when v_salariu between 5000 and 10000 then v_bonus := 1000;
else v_bonus := 500;
end case;
--v_salariu := v_salariu + bonus;
DBMS_OUTPUT.PUT_LINE('Salariatul cu codul ' || v_cod || ' v-a primi un bonus de ' || v_bonus);
END;
/
--- ||| ---
DECLARE
v_salariu employees.salary%type;
v_cod employees.employee_id%type := &p_cod2;
v_bonus2 v_salariu%type;
BEGIN
select salary
into v_salariu
from employees
where employee_id = v_cod;
v_bonus2 := case
when v_salariu > 10000 then 2000
when v_salariu between 5000 and 10000 then 1000
else 500
end;
DBMS_OUTPUT.PUT_LINE('Salariatul cu codul ' || v_cod || ' v-a primi un bonus de ' || v_bonus2);
END;
/
--- ||| ---
DECLARE
contor NUMBER:=10;
BEGIN
LOOP
contor := contor - 1;
DBMS_OUTPUT.PUT_LINE(contor);
exit when contor <= 0;
END LOOP;
END;
/
--- ||| ---
DECLARE
contor NUMBER:=10;
BEGIN
while contor > 0 loop
contor := contor - 2;
DBMS_OUTPUT.PUT_LINE(contor);
END LOOP;
END;
/
--- ||| ---
BEGIN
for contor in 0..10 loop -- REVERSE
DBMS_OUTPUT.PUT_LINE(contor);
end loop;
END;
/
<<bloc_1>>
declare
v1 number(10):=5;
begin
v1:=10;
<<bloc_2>>
declare
v1 varchar2(30);
begin
v1:='test';
DBMS_OUTPUT.PUT_LINE('Bloc 2 ' || v1 || ' ' || bloc_1.v1);
end;
DBMS_OUTPUT.PUT_LINE('Bloc 1 ' || v1 || ' ');
end;
/
------------- ||||||||||||||||||||| -------------
CREATE TABLE octombrie_isp(id number(10), data date);
DECLARE
v_nr number(10);
contor date := TO_DATE('01-10-2016','dd-mm-yyyy');
v_cod number(10);
BEGIN
loop
select count(*)
into v_nr
from rental
where book_date like contor;
v_cod := contor - TO_DATE('01-10-2016','dd-mm-yyyy');
insert into octombrie_isp VALUES(v_cod, contor);
DBMS_OUTPUT.PUT_LINE('Data: ' || contor || ' Numar imprumuturi: ' || v_nr);
contor := contor + 1;
exit when contor > TO_DATE('31-10-2016','dd-mm-yyyy');
end loop;
END;
/
drop table octombrie_isp;
|
Python
|
UTF-8
| 3,452
| 2.6875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env python
#
# Copyright 2019 Google 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.
"""Convert CAI Assets to match API names.
There are some Cloud Asset Inventory (CAI) properties which don't match the
properties in the API discovery documents. This converts those CAI properties to
match those in the API. The property mappings are supplied by
the 'cai_to_api_mapping.json' configuration file which needs to be
regenerated if new properties are added to assets that don't aren't mapped
correctly.
The entrypoint is the `CAIToAPI.cai_to_api_properties` method.
"""
import json
import os
class CAIToAPI(object):
"""Convert CAI properties names to API properties."""
_cai_to_api_dict = None
@classmethod
def _get_cai_to_api_properties(cls):
"""Get the dict containing current mappings."""
# To regnerate the configs see:
# https://colab.corp.google.com/drive/183eM8uKO0V-HD2ldx7AMJ8H6UQnh3JHt
if cls._cai_to_api_dict is None:
with open(os.path.join(os.path.dirname(__file__),
'cai_to_api_properties.json')) as f:
cls._cai_to_api_dict = json.load(f)
return cls._cai_to_api_dict
@classmethod
def _apply_cai_to_api(cls, cai_properties, cai_to_api):
"""Recursively map CAI to API properties.
Args:
cai_properties: dict of cai properties at current level of
recursion.
cai_to_api: dict of cai to api mappings for the current level of
recursion.
"""
# `cai_properties is either a list of dicts or a dict.
# if a list, apply for each dict in the list.
if isinstance(cai_properties, list):
for item in cai_properties:
cls._apply_cai_to_api(item, cai_to_api)
return
# if a dict, recurse into each property that requires modification
for cai_property in cai_to_api:
if cai_property in cai_properties:
cls._apply_cai_to_api(cai_properties[cai_property],
cai_to_api[cai_property])
# and apply the necessary modifications.
if 'cai_to_api_names' in cai_to_api:
cai_to_api_names = cai_to_api['cai_to_api_names']
for cai_property, r_property in cai_to_api_names.items():
if cai_property in cai_properties:
cai_properties[r_property] = cai_properties.pop(
cai_property)
@classmethod
def cai_to_api_properties(cls, resource_name, cai_properties):
"""Convert CAI properties that should match API properties."""
cai_to_api_properties = cls._get_cai_to_api_properties()
if resource_name in cai_to_api_properties:
cai_to_api = cai_to_api_properties[resource_name]
cls._apply_cai_to_api(cai_properties, cai_to_api)
return cai_properties
|
Markdown
|
UTF-8
| 3,362
| 3.375
| 3
|
[] |
no_license
|
# Static Driver
A dynamic web application for powering the dynamic features of static web sites.
## Background
Most modern web sites are dynamic. When you request a URL, a web server passes your request to a
web application that queries a database and dynamically generates a web page and then sends it to
you.
That takes precious time, and it costs a lot of money because you have to provide enough server
power to handle all of your web requests. It introduces downtime risk, because your server might
get overloaded from too much traffic. Or somebody might exploit vulnerabilities in the dynamic
web application to breach your security and steal your data.
Why assume that risk? Most web sites don't really need to be powered by dynamic web applications.
Most web sites can be structured so that the web pages have already been generated long before any
web visitor requests them. If your web site is a static collection of web pages and asset files,
then you can host it very cheaply on a system like Amazon S3. Your pages will be served to visitors
much more quickly than if they had to be dynamically generated before being served. Your site will
be far cheaper to host. It will not be at any risk of downtime from server overload. And there
will be no web server or web application for hackers to attack.
So then why are most sites dynamic? It's because most web sites have a small handful of features
that require a dynamic back end. For example, if your site has a "contact" web form, then you need
some dynamic web app to handle those form submissions. And you might need a web-based admin
system for managing content.
This app is for powering those few dynamic features in a web site, so that the rest of the site can
be static.
## Development
### Prerequisites
Static Driver is packaged in Docker containers, for portability. To run it, you'll need Docker
version 1.7.1 at least. Please see the Docker installation instructions at:
https://docs.docker.com/engine/installation/ubuntulinux/
All other prerequisites are packaged inside of the containers. Docker is the only thing to
install.
### Build your containers
This project uses [Docker Compose](https://docs.docker.com/compose/) to orchestrate multiple
containers. One container provides your database, and one provides your Rails app. The
configuration is in the file docker-compose.yml.
When you first start development, and any time that your Gemfile changes, you'll need to build
your containers with:
sudo docker-compose build
### Run your Ruby code
Use your containers to run your Ruby code:
sudo docker-compose run web rake -T
That tells Docker Compose to run the web and db containers and run "rake -T" in the web
container. You don't need the database to do that, but next you'll see how you can also access
the database container from your Ruby code.
### Build your databases
Create your database in your db container with Ruby code in your web container:
sudo docker-compose run web rake db:create
Now create your database structure:
sudo docker-compose run web rake db:migrate
And don't forget to create a test database:
sudo docker-compose run web db:test:prepare
### Do stuff
You can do your standard Rails stuff:
sudo docker-compose run web rails console
sudo docker-compose run web rails server
|
Shell
|
UTF-8
| 471
| 3.34375
| 3
|
[] |
no_license
|
#!/usr/bin/env bash
REPOSITORYNAME=order-management-service
BRANCHNAME=temp-production
USERNAME=username
PASSWORD=password
# Remove the existing directory
if [ -d "$REPOSITORYNAME" ]; then
printf '%s\n' "Removing DIrectory ($REPOSITORYNAME)"
rm -rf "$REPOSITORYNAME"
fi
# Clone the repository
git clone -b ${BRANCHNAME} https://${USERNAME}:${PASSWORD}@github.com/Maveric-Digital/order-management-service.git
# docker buil and update
docker-compose up -d
|
Python
|
UTF-8
| 1,366
| 2.9375
| 3
|
[] |
no_license
|
from bs4 import BeautifulSoup
import requests
response = requests.get("https://news.ycombinator.com/news")
yc_web_page = response.text
soup = BeautifulSoup(yc_web_page, "html.parser")
articles = soup.find_all(name="a", class_="storylink")
article_texts = []
articles_links = []
for article_tag in articles:
text = article_tag.getText()
article_texts.append(text)
link = article_tag.get("href")
articles_links.append(link)
article_upvotes= [int(score.getText().split()[0]) for score in soup.find_all(name="span", class_="score")]
largest_number = max(article_upvotes)
largest_index = article_upvotes.index(largest_number)
print(article_texts[largest_index])
print(articles_links[largest_index])
# print(article_texts)
# print(articles_links)
# print(article_upvotes)
# # import lxml
#
#
# with open("website.html") as file:
# contents = file.read()
#
#
# soup = BeautifulSoup(contents, "html.parser")
# # print(soup.title)
# # print(soup.title.string)
#
# # print(soup.prettify())
#
#
# # print(soup.p)
#
# all_anchor_tags = soup.find_all(name="a")
# #
#
#
# # heading = soup.find(name="h1", id="name")
# # print(heading)
#
# # section_heading = soup.find(name="h3", class_="heading")
# # print(section_heading)
#
# name= soup.select_one(selector="#name")
# print(name)
#
# headings = soup.select(".heading")
# print(headings)
|
JavaScript
|
UTF-8
| 552
| 4.21875
| 4
|
[] |
no_license
|
/*
Exercício 1
-----------
A função insertion cria elementos no DOM e para isso recebe três argumentos, o elemento, o ID de um elemento
já existente no seu HTML e o texto que será inserido no elemento criado.
*/
function insereElementoDeTexto(elemento,id,texto){
const elementoNovo = document.createElement(elemento);
elementoNovo.innerText = texto;
const elementoExistente = document.querySelector(id);
elementoExistente.appendChild(elementoNovo);
}
insereElementoDeTexto('p','#container',"Fui criado com Javascript");
|
Java
|
UTF-8
| 1,024
| 2.53125
| 3
|
[] |
no_license
|
package com.and1droid.ecohack;
import diewald_shapeFile.files.dbf.DBF_File;
import diewald_shapeFile.files.shp.SHP_File;
import diewald_shapeFile.files.shp.shapeTypes.ShpPolygon;
import diewald_shapeFile.files.shx.SHX_File;
import diewald_shapeFile.shapeFile.ShapeFile;
public class ShapeFileReaderTest {
private static final String fileName = "Jardins_communautaires";
static String folder = System.getProperty("user.dir") + "/ecohack/garden/";
public static void main(String[] args) {
DBF_File.LOG_INFO = !false;
SHX_File.LOG_INFO = !false;
SHP_File.LOG_INFO = !false;
try {
// LOAD SHAPE FILE (.shp, .shx, .dbf)
ShapeFile<ShpPolygon> shapefile = new ShapeFile<ShpPolygon>(folder, fileName).read();
System.out.println(shapefile);
for (ShpPolygon shape : shapefile.getSHP_shapes()) {
System.out.println(shape);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
C
|
UTF-8
| 1,191
| 3.71875
| 4
|
[
"MS-PL"
] |
permissive
|
// Based off: http://stackoverflow.com/questions/3536153/c-dynamically-growing-array
#include "array.h"
// Intializes an array with specfied size, meant to hold type struct PidChangeTracker
void InitalizeArray(Array *a, size_t initialSize) {
a->array = (struct PidChangeTracker *)malloc(initialSize * sizeof(struct PidChangeTracker));
if (a->array == NULL) {
fprintf(stderr, "Failed to create array.");
exit(EXIT_FAILURE);
}
a->used = 0;
a->size = initialSize;
}
// Insert a new element of type struct PidChangeTracker, and expands the array size when it is full
void InsertElement(Array *a, struct PidChangeTracker *pTracker) {
if (a->used == a->size) {
a->size *= 2;
a->array = (struct PidChangeTracker *)realloc(a->array, a->size * sizeof(struct PidChangeTracker));
if (a->array == NULL) {
fprintf(stderr, "Failed to expand size of array.");
exit(EXIT_FAILURE);
}
}
a->array[a->used++] = *pTracker;
}
// Clean up all the memory used for the array once it's no longer needed
void FreeArray(Array *a) {
free(a->array);
a->array = NULL;
a->used = a->size = 0;
if (a->array != NULL) {
fprintf(stderr, "Failed to free up array.");
exit(EXIT_FAILURE);
}
}
|
Java
|
UTF-8
| 4,433
| 2.21875
| 2
|
[] |
no_license
|
package com.example.fickhd.view;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.fickhd.R;
import com.example.fickhd.adapter.ThemeAdapter;
import com.example.fickhd.model.Theme;
import com.jpardogo.android.googleprogressbar.library.ChromeFloatingCirclesDrawable;
import com.jpardogo.android.googleprogressbar.library.GoogleProgressBar;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Use the {@link FavoriteFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class FavoriteFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private RecyclerView gridView;
private List<Theme> themeList;
private ThemeAdapter themeAdapter;
private ProgressBar progressBar;
private GoogleProgressBar googleProgressBar;
public FavoriteFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FavoriteFragment.
*/
// TODO: Rename and change types and number of parameters
public static FavoriteFragment newInstance(String param1, String param2) {
FavoriteFragment fragment = new FavoriteFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_favorite, container, false);
getImageView(view);
getData();
return view;
}
private void getData() {
themeList = new ArrayList<>();
themeList.add(new Theme("https://1.bp.blogspot.com/-a-GO0cVmnuE/XcWkLlMcWrI/AAAAAAAATMY/3QfOrHzXeYoRS7qMAzVCa8BrHAwnmCncQCLcBGAsYHQ/s1600/hinh-anh-hot-girl-xinh-han-quoc-wap102-com%2B%25281%2529.jpg", "Beautiful Girl 002 4K"));
themeList.add(new Theme("https://gaixinh69.net/wp-content/uploads/2019/10/cropped-Girl-mini-P1-gaixinh69.net-045-1024x576.jpg", "Beautiful Girl 004 4K"));
themeList.add(new Theme("https://fsb.zobj.net/crop.php?r=m4W77IFixy3HOt-gm7ZX47CRDeM9VEzIJtgOh4QQBnEp5kER3Ek5LaWpsavqoaetWwFVNg8b5l1U-sYJnArsSrdByaLoMAhpRnGDEPSMHkyiH0YpqWX740wXMG_MV00bA6axqorLcoP3qKCz", "SPACE 4K"));
themeList.add(new Theme("https://images2.minutemediacdn.com/image/upload/c_crop,h_1689,w_3000,x_0,y_404/f_auto,q_auto,w_1100/v1563809078/shape/mentalfloss/28865-gettyimages-500694766.jpg", "Animal 4K"));
themeAdapter = new ThemeAdapter(themeList, getContext());
GridLayoutManager manager = new GridLayoutManager(getContext(), 1);
gridView.setLayoutManager(manager);
gridView.setHasFixedSize(false);
gridView.setAdapter(themeAdapter);
progressBar.setVisibility(View.GONE);
}
private void getImageView(View view) {
int[] color = {
R.color.red, R.color.yeallow, R.color.tim, R.color.xanhcay
};
progressBar = view.findViewById(R.id.favorite_progessbar);
gridView = view.findViewById(R.id.recleview);
progressBar.setIndeterminateDrawable(new ChromeFloatingCirclesDrawable.Builder(getContext())
.build());
}
}
|
PHP
|
UTF-8
| 1,746
| 2.890625
| 3
|
[] |
no_license
|
<?php
if(isset($_POST['submit'])) {
// echo "<pre>";
// print_r($_FILES['file_upload']);
// echo "<pre>";
$upload_errors = array(
UPLOAD_ERR_OK => "There is no error",
UPLOAD_ERR_INI_SIZE => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
UPLOAD_ERR_FORM_SIZE => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.",
UPLOAD_ERR_PARTIAL => "The uploaded file was only partially uploaded.",
UPLOAD_ERR_NO_FILE => "No file was uploaded.",
UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder.",
UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk.",
UPLOAD_ERR_EXTENSION => "A PHP extension stopped the file upload."
);
$tmp_name = $_FILES['file_upload']['tmp_name'];
$filename = $_FILES['file_upload']['name'];
$directory = "uploads";
if(move_uploaded_file($tmp_name, $directory . "/" . $filename)) {
$message = "File uploaded successfully";
} else {
$error = $_FILES['file_upload']['error'];
$message = $upload_errors[$error];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js"></script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<h2>
<?php
if(!empty($upload_errors)) {
echo $message;
}
?>
</h2>
<input type="file" name="file_upload"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
|
PHP
|
UTF-8
| 1,268
| 2.625
| 3
|
[] |
no_license
|
<?php
namespace Qihucms\PublishVideoPro\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ShortVideoRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'src' => ['required_without:link'],
'desc' => ['required'],
'link' => ['nullable','url'],
'price' => ['min:0','integer']
];
}
public function messages()
{
return [
'required_without' => '请上传视频或填写视频外链',
'required' => ':attribute必须填写',
'url' => ':attribute必须是视频地址',
'min' => ':attribute必须是大于等于0的整数',
'integer' => ':attribute必须是大于等于0的整数',
];
}
public function attributes()
{
return [
'src' => '视频',
'desc' => '视频介绍',
'link' => '视频外链',
'price' => '收费价格'
];
}
}
|
Python
|
UTF-8
| 1,080
| 2.71875
| 3
|
[] |
no_license
|
import cv2
import face_recognition
img1 = face_recognition.load_image_file('obama.jpg')
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
img1Test = face_recognition.load_image_file('obama2.jpg')
img1Test = cv2.cvtColor(img1Test, cv2.COLOR_BGR2RGB)
face = face_recognition.face_locations(img1)[0]
print(face)
encodeFace = face_recognition.face_encodings(img1)[0]
print(encodeFace)
cv2.rectangle(img1, (face[3], face[0]), (face[1], face[2]), (255, 0, 255), 2)
faceTest = face_recognition.face_locations(img1Test)[0]
encodeTestFace = face_recognition.face_encodings(img1Test)[0]
cv2.rectangle(img1Test, (faceTest[3], faceTest[0]), (faceTest[1], faceTest[2]), (255, 0, 255), 2)
results = face_recognition.compare_faces([encodeFace], encodeTestFace)
faceDis = face_recognition.face_distance([encodeFace], encodeTestFace)
print(results, faceDis)
cv2.putText(img1Test, f'{results} {round(faceDis[0], 2)}', (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 2)
cv2.imshow('Obama', img1)
cv2.imshow('Obama Test', img1Test)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
Python
|
UTF-8
| 4,692
| 2.53125
| 3
|
[] |
no_license
|
# This Python file uses the following encoding: utf-8
import sys
import os
from numpy.linalg import inv
from strings import hill_txt
from PyQt5.QtWidgets import (QWidget, QMessageBox, QCheckBox, QLabel, QSpinBox, QComboBox, QPlainTextEdit, QLineEdit, QHBoxLayout, QVBoxLayout, QGridLayout,QPushButton, QApplication, QFrame)
from PyQt5 import QtCore
from PyQt5 import QtGui
from frameTemplate import frameTemplate
from ciphers.hill import Hill
class hillFrame(frameTemplate):
def __init__(self):
super().__init__()
self.inputs = []
self.hl = Hill()
self.initUI()
def initUI(self):
super().initUI()
self.definition.insertPlainText(hill_txt)
self.cb_method.addItem("Encrypt")
self.cb_method.addItem("Decrypt")
self.btn_encrypt.clicked.connect(self.encrypt)
self.cb_method.currentIndexChanged.connect(self.selectionChange)
regex = QtCore.QRegExp("^[a-zA-Z]+$")
validator = QtGui.QRegExpValidator(regex, self.plaintext)
self.plaintext.setValidator(validator)
self.label_key = QLabel()
self.label_key.setText('Ključ:')
self.key_input = QGridLayout()
self.hbox_key = QHBoxLayout()
for row in range(3):
for col in range(3):
self.input_field = QLineEdit()
self.inputs.append(self.input_field)
self.input_field.setInputMask('D00;_')
self.input_field.setFixedWidth(40)
self.key_input.addWidget(self.input_field, row, col)
self.hbox_key.addStretch(1)
self.hbox_key.addLayout(self.key_input)
self.hbox_key.addStretch(1)
self.encryption_v_box.addWidget(self.label_key)
self.encryption_v_box.addLayout(self.hbox_key)
def selectionChange(self, index):
self.btn_encrypt.clicked.disconnect()
if (self.cb_method.itemText(index) == "Encrypt"):
self.label_plaintext.setText("Plaintext:")
self.label_ciphertext.setText("Ciphertext:")
self.btn_encrypt.clicked.connect(self.encrypt)
self.btn_encrypt.setText("Encrypt")
self.plaintext.clear()
self.ciphertext.clear()
elif(self.cb_method.itemText(index) == "Decrypt"):
self.label_plaintext.setText("Ciphertext:")
self.label_ciphertext.setText("Plaintext:")
self.btn_encrypt.clicked.connect(self.decrypt)
self.btn_encrypt.setText("Decrypt")
self.plaintext.clear()
self.ciphertext.clear()
def encrypt(self):
if(self.validateInput() and self.validateKey() and self.checkInvertibility()):
text = self.hl.encrypt(self.plaintext.text(), self.key)
self.ciphertext.setText(text)
self.plaintext.setStyleSheet('QLineEdit { border-color: #1e1e1e }')
def decrypt(self):
if(self.validateInput() and self.validateKey() and self.checkInvertibility()):
text = self.hl.decrypt(self.plaintext.text())
self.ciphertext.setText(text)
self.plaintext.setStyleSheet('QLineEdit { border-color: #1e1e1e }')
def getKey(self):
self.key = []
buffer = []
for input in self.inputs:
buffer.append(int(input.text()))
if(len(buffer) == 3):
self.key.append(buffer)
buffer = []
return self.key
def validateKey(self):
for input in self.inputs:
if(not input.hasAcceptableInput()):
return False
return True
def validateInput(self):
if(self.plaintext.text() == ''):
self.plaintext.setPlaceholderText("Input required")
self.plaintext.setStyleSheet('QLineEdit { border-color: #EC0505 }')
return False
return True
def checkInvertibility(self):
self.key = self.getKey()
minor_matrixA = (self.key[1][1] * self.key[2][2]) - (self.key[1][2] * self.key[2][1])
minor_matrixB = (self.key[1][0] * self.key[2][2]) - (self.key[1][2] * self.key[2][0])
minor_matrixC = (self.key[1][0] * self.key[2][1]) - (self.key[1][1] * self.key[2][0])
determinant = (self.key[0][0] * minor_matrixA) - (self.key[0][1] * minor_matrixB) - (self.key[0][2] * minor_matrixC)
if(determinant == 0):
self.showWarning()
return False
return True
def showWarning(self):
self.msg = QMessageBox()
self.msg.setIcon(QMessageBox.Critical)
self.msg.setText("Given matrix is not invertible")
self.msg.setStandardButtons(QMessageBox.Ok)
self.msg.show()
|
C++
|
UHC
| 1,198
| 2.890625
| 3
|
[] |
no_license
|
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
ifstream fp;
fp.open("input.txt");
int t = 0,i,j,n=0;
int arr[101] = { 0 };
int count[101] = { 0 };
int a, b, temp = 0;
int cnt=1,cnt1=0,max=0;
fp >> t;
for (i = 0; i < t; i++)
{
fp >> n;
for (j = 0; j < 101; j++) {
count[j] = 0;
arr[j] = 0;
}
max = count[0];
cnt1 = 0;
for (j = 0; j < n; j++) {
fp >> arr[j];
}
for (a = 0; a < n; a++) {
for (b = 0; b < n; b++) {
if (arr[a] < arr[b]) {
temp = arr[b];
arr[b] = arr[a];
arr[a] = temp;
}
}
}
for (j = 0; j < n; j++) {
if (arr[j] == arr[j + 1]) {
cnt++;
}
else if (arr[j] != arr[j + 1]) {
count[j] = cnt;
cnt = 1;
}
if (arr[n - 1] == arr[n]) {//0 ϰ
count[j] = cnt-1;//arr[n]° 0 Ѵ.
}
}
cnt = 1;
for(j = 0; j < n; j++) {
if (max < count[j]) {
max = count[j];
}
}
for (j = 0; j < n; j++) {
if (max == count[j]) {
cnt1++;
}
}
cout << cnt1 << " "<<max<<" ";
for (j = 0; j < n; j++) {
if (max == count[j]) {
cout << arr[j] << " ";
}
}
cout << endl;
}
fp.close();
}
|
Java
|
UTF-8
| 360
| 2.984375
| 3
|
[] |
no_license
|
package com.bit.test;
import java.util.Arrays;
public class Test10{
public static void main(String[] args) {
int[] arr= {1, 7, 2, 9, 6};
Arrays.sort(arr);
int[] newarr=new int[arr.length];
int k=0;
for(int i=0;i<arr.length-1;++i) {
if(arr[i] != arr[i+1]) {
newarr[k++]=arr[i];
}
}
System.out.println(arr[0]+arr[1]);
}
}
|
JavaScript
|
UTF-8
| 8,086
| 2.671875
| 3
|
[] |
no_license
|
/*!
* Datadaan
* Datavisualisation
* https://datadaan.nl
* @author Daan van der Zwaag
* @version 1.0.5
* Copyright 2017. MIT licensed.
*/
(function(){ 'use strict';
var svg = d3.select('#area1'),
margin = {top: 20, right: 20, bottom: 110, left: 40},
margin2 = {top: 430, right: 20, bottom: 30, left: 40},
width = +svg.attr('width') - margin.left - margin.right,
height = +svg.attr('height') - margin.top - margin.bottom,
height2 = +svg.attr('height') - margin2.top - margin2.bottom;
var parseDate = d3.timeParse('%b %Y');
var x = d3.scaleTime().range([0, width]),
x2 = d3.scaleTime().range([0, width]),
y = d3.scaleLinear().range([height, 0]),
y2 = d3.scaleLinear().range([height2, 0]);
var xAxis = d3.axisBottom(x),
xAxis2 = d3.axisBottom(x2),
yAxis = d3.axisLeft(y);
var brush = d3.brushX()
.extent([[0, 0], [width, height2]])
.on('brush end', brushed);
var zoom = d3.zoom()
.scaleExtent([1, Infinity])
.translateExtent([[0, 0], [width, height]])
.extent([[0, 0], [width, height]])
.on('zoom', zoomed);
var area = d3.area()
.curve(d3.curveMonotoneX)
.x(function(d) { return x(d.date); })
.y0(height)
.y1(function(d) { return y(d.price); });
var area2 = d3.area()
.curve(d3.curveMonotoneX)
.x(function(d) { return x2(d.date); })
.y0(height2)
.y1(function(d) { return y2(d.price); });
svg.append('defs').append('clipPath')
.attr('id', 'clip')
.append('rect')
.attr('width', width)
.attr('height', height);
var focus = svg.append('g')
.attr('class', 'focus')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var context = svg.append('g')
.attr('class', 'context')
.attr('transform', 'translate(' + margin2.left + ',' + margin2.top + ')');
d3.csv('assets/data/sp500.csv', type, function(error, data) {
if (error) throw error;
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.price; })]);
x2.domain(x.domain());
y2.domain(y.domain());
focus.append('path')
.datum(data)
.attr('class', 'area')
.attr('d', area);
focus.append('g')
.attr('class', 'axis axis--x')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
focus.append('g')
.attr('class', 'axis axis--y')
.call(yAxis);
context.append('path')
.datum(data)
.attr('class', 'area')
.attr('d', area2);
context.append('g')
.attr('class', 'axis axis--x')
.attr('transform', 'translate(0,' + height2 + ')')
.call(xAxis2);
context.append('g')
.attr('class', 'brush')
.call(brush)
.call(brush.move, x.range());
svg.append('rect')
.attr('class', 'zoom')
.attr('width', width)
.attr('height', height)
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.call(zoom);
});
function brushed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === 'zoom') return; // ignore brush-by-zoom
var s = d3.event.selection || x2.range();
x.domain(s.map(x2.invert, x2));
focus.select('.area').attr('d', area);
focus.select('.axis--x').call(xAxis);
svg.select('.zoom').call(zoom.transform, d3.zoomIdentity
.scale(width / (s[1] - s[0]))
.translate(-s[0], 0));
}
function zoomed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === 'brush') return; // ignore zoom-by-brush
var t = d3.event.transform;
x.domain(t.rescaleX(x2).domain());
focus.select('.area').attr('d', area);
focus.select('.axis--x').call(xAxis);
context.select('.brush').call(brush.move, x.range().map(t.invertX, t));
}
function type(d) {
d.date = parseDate(d.date);
d.price = +d.price;
return d;
}
/////////////////////// SPARKLINES //////////////////////
/* http://codepen.io/mginnard/pen/mkBEg?editors=1010 */
function displaySparkLines(id, width, height, interpolation, animate, updateDelay, transitionDelay) {
// create an SVG element inside the #graph div that fills 100% of the div
var graph = d3.select(id).append("svg:svg").attr("width", "100%").attr("height", "100%");
// create simple data arrays that we'll plot with a line (this array represents only the Y values, X will just be the index location)
var dataOne = [3, 6, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 9, 3, 6, 3, 6, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 9, 2, 7, 5, 2, 1, 3, 8, 9, 2, 5, 9, 3, 6, 2, 7, 5, 2, 1, 3, 8, 9, 2, 9];
var dataTwo = [33, 76, 67, 74, 32, 82, 62, 1, 78, 4, 13, 88, 61, 26, 58, 42, 79, 69, 3, 19, 10, 91, 94, 20, 27, 8, 51, 87, 85, 65, 17, 77, 35, 37, 93, 36, 60, 63, 39, 73, 43, 75, 9, 66, 25, 49, 97, 90, 47, 70, 18, 41, 50, 34, 53, 23, 30, 92, 14, 84, 16, 95, 28, 31, 96, 68, 80, 21, 72, 99, 15, 83, 6, 64, 59, 54, 86, 12, 55, 71, 7, 22, 52, 24, 5, 29, 56, 2, 100, 98, 48, 11, 40, 57, 45, 81, 89, 38, 46, 44];
var dataSet = [dataOne, dataTwo];
// var dataRandom = d3.range(50).map(function(){return Math.random()*10});
// X scale will fit values from 0-10 within pixels 0-100
var x = d3.scaleLinear().domain([0, 48]).range([-5, width]); // starting point is -5 so the first value doesn't show and slides off the edge as part of the transition
// Y scale will fit values from 0-10 within pixels 0-100
var y = d3.scaleLinear().domain([0, 10]).range([0, height]);
// create a line object that represents the SVG line we're creating
var line = d3.line()
// assign the X function to plot our line as we wish
.x(function(d, i) {
// verbose logging to show what's actually being done
// console.log('Plotting X value for data point: ' + d + ' using index: ' + i + ' to be at: ' + x(i) + ' using our xScale.');
// return the X coordinate where we want to plot this datapoint
return x(i);
})
.y(function(d) {
// verbose logging to show what's actually being done
//console.log('Plotting Y value for data point: ' + d + ' to be at: ' + y(d) + " using our yScale.");
// return the Y coordinate where we want to plot this datapoint
return y(d);
})
if (interpolation === "basis") {
line.curve(d3.curveCatmullRom.alpha(0.5))
}
// display the line by appending an svg:path element with the data line we created above
graph.append("svg:path").attr("d", line(dataSet[0]));
// or it can be done like this
//graph.selectAll("path").data([data]).enter().append("svg:path").attr("d", line);
function redrawWithAnimation() {
// update with animation
graph.selectAll("path")
.attr("transform", "translate(" + x(1) + ")") // set the transform to the right by x(1) pixels (6 for the scale we've set) to hide the new value
.data([dataSet[0]]) // set the new data
.attr("d", line) // apply the new data values ... but the new value is hidden at this point off the right of the canvas
.transition() // start a transition to bring the new value into view
.ease(d3.easeLinear)
.duration(transitionDelay*0.95) // for this demo we want a continual slide so set this to the same as the setInterval amount below
.attr("transform", "translate(" + x(0) + ")"); // animate a slide to the left back to x(0) pixels to reveal the new value
/* thanks to 'barrym' for examples of transform: https://gist.github.com/1137131 */
}
// Fallback if redrawWithAnimation doesn't work
function redrawWithoutAnimation() {
// static update without animation
graph.selectAll("path")
.data([dataSet[0]]) // set the new data
.attr("d", line); // apply the new data values
}
setInterval(function() {
var v = dataSet[0].shift(); // remove the first element of the array
dataSet[0].push(v); // add a new element to the array (we're just taking the number we just shifted off the front and appending to the end)
if (animate) {
redrawWithAnimation();
} else {
redrawWithoutAnimation();
}
}, updateDelay);
}
displaySparkLines("#graph1", 2000, 80, "basis", true, 1000, 1000);
displaySparkLines("#graph2", 2000, 80, "basis", true, 1000, 1000);
})();
|
Markdown
|
UTF-8
| 1,382
| 2.921875
| 3
|
[
"CC-BY-4.0"
] |
permissive
|
## markdown
markdown is a lightweight markup language with plain text formatting syntax. Its design allows it to be converted to many output formats, but the original tool by the same name only supports HTML.

## Rmarkdown
Extend the markdown concept to run `R` code.

Full tutorial at https://rmarkdown.rstudio.com/authoring_quick_tour.html
## Render
To render the Rmarkdown file to HTML or PDF, you can use the `knit` button or
```
rmarkdown::render("input.Rmd")
```
## Using parameters
Parameters in the header of the document define format of the output.
```
---
title: "Sample Document"
output:
html_document:
toc: true
theme: united
---
```
or to define variables used in the file at some point.

To render the Rmarkdown file to HTML or PDF with different parameters using the `rmarkdown` package:
```
rmarkdown::render("input.Rmd", params = list(filenames="otherfile.txt"))
```
## Example
Download this material from github:
https://github.com/pilm-bioinformatics/pilmbc104-best-of-r/archive/master.zip
Extract the content, you should have a folder with this name: `pilmbc104-best-of-r-master`.
Double click on `pilmbc104.Rproj`.
Open `tidyverse.Rmd` and click `knit`.
Then go to the `Console` and type `rmarkdown::render("ggplot2.Rmd")`.
You should see two HTML files now.
|
TypeScript
|
UTF-8
| 1,666
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
import { IMessageSerializer } from '@/interfaces/IMessageSerializer';
import { IMessage } from '@/interfaces/IMessage';
import messageTypeCache from './MessageTypeCache';
import { Message } from './Message';
/**
* Represents the MessageConstructor class.
*/
export default class MessageConstructor {
private readonly _textEncoder: TextEncoder = new TextEncoder();
private readonly _messageSerializer: IMessageSerializer;
/**
* Initializes a new instance of the MessageConstructor class.
*/
constructor(messageSerializer: IMessageSerializer) {
this._messageSerializer = messageSerializer;
}
public constructMessage(message: IMessage): Message {
const body: Uint8Array = this._messageSerializer.serialize(message);
const bodySizeBytes: Uint8Array = new Uint8Array(4);
let dv: DataView = new DataView(bodySizeBytes.buffer);
dv.setInt32(0, body.length, true);
const typeName: string = messageTypeCache.getMessageType(message.constructor.name);
if (typeName === '') {
console.log('Message type not found in cache for: ', message.constructor.name);
}
const typeNameBytes: Uint8Array = this._textEncoder.encode(typeName);
const headerSizeBytes: Uint8Array = new Uint8Array(4);
dv = new DataView(headerSizeBytes.buffer);
dv.setInt32(0, 8 + typeNameBytes.length, true);
const header: Uint8Array = this.concat(this.concat(headerSizeBytes, bodySizeBytes), typeNameBytes);
return new Message(header, body);
}
private concat(a: Uint8Array, b: Uint8Array): Uint8Array {
const tmp = new Uint8Array(a.length + b.length);
tmp.set(a, 0);
tmp.set(b, a.length);
return tmp;
}
}
|
Markdown
|
UTF-8
| 5,900
| 2.5625
| 3
|
[] |
no_license
|
---
description: "How to Make Any-night-of-the-week Duck Tacos, Radish-Lime Salad, Cumin-Roasted Squash"
title: "How to Make Any-night-of-the-week Duck Tacos, Radish-Lime Salad, Cumin-Roasted Squash"
slug: 80-how-to-make-any-night-of-the-week-duck-tacos-radish-lime-salad-cumin-roasted-squash
date: 2020-04-24T11:02:56.384Z
image: https://img-global.cpcdn.com/recipes/5635440360030208/751x532cq70/duck-tacos-radish-lime-salad-cumin-roasted-squash-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/5635440360030208/751x532cq70/duck-tacos-radish-lime-salad-cumin-roasted-squash-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/5635440360030208/751x532cq70/duck-tacos-radish-lime-salad-cumin-roasted-squash-recipe-main-photo.jpg
author: Christina Reed
ratingvalue: 4.6
reviewcount: 14
recipeingredient:
- "1 each butternut squash large dice"
- "2 tsp ground cumin"
- "1 tbsp olive oil"
- "4 oz radishes thinly sliced"
- "1/2 each lime juiced"
- "12 leaves cilantro chopped"
- "1 tsp sugar turbinado"
- "1 tsp cooking oil"
- "10 oz ground duck"
- "1 small onion diced small"
- "4 tsp taco seasoning"
- "3 oz water"
- "6 each tortillas"
- "1/2 each lime wedged"
- "2 oz Cotija cheese"
recipeinstructions:
- "Preheat your oven to 425°F. Toss the butternut squash in olive oil, salt, and ground cumin. Spread across a heavy baking sheet. Roast for 15-20 minutes, or until squash is browned & tender."
- "Combine the radish, lime juice, cilantro, and sugar. Set aside to use later as a garnish."
- "Heat a large sauté pan over medium-high heat. Add cooking oil, and heat until shimmering and wisping smoke. Add the ground duck meat in an even layer, and cook without stirring or turning to brown, about 2-3 minutes."
- "The duck will have rendered off a good amount of liquid, remove approximately half before proceeding. (You can reserve by chilling this liquid, and use it to cook with later, it has TERRIFIC flavor!)"
- "Stir in the diced onion, and cook while stirring until onion begins to turn translucent. Add the taco-seasoning blend, and continue to cook while stirring for 1-2 more minutes, then stir in water. Continue to cook while stirring for 2-3 more minutes. Combine the meat mixture with the cumin-roasted squash."
- "Warm the tortillas. Make tacos using the meat mixture, radish salad, and Cotija cheese."
- "Serve lime wedges as a garnish, and enjoy!"
categories:
- Recipe
tags:
- duck
- tacos
- radishlime
katakunci: duck tacos radishlime
nutrition: 168 calories
recipecuisine: American
preptime: "PT23M"
cooktime: "PT40M"
recipeyield: "3"
recipecategory: Lunch
---

Hello everybody, I hope you're having an amazing day today. Today, we're going to prepare a distinctive dish, duck tacos, radish-lime salad, cumin-roasted squash. It is one of my favorites. This time, I am going to make it a bit unique. This is gonna smell and look delicious.
Duck Tacos, Radish-Lime Salad, Cumin-Roasted Squash is one of the most well liked of recent trending foods in the world. It's enjoyed by millions every day. It is easy, it is quick, it tastes yummy. They are fine and they look wonderful. Duck Tacos, Radish-Lime Salad, Cumin-Roasted Squash is something that I've loved my entire life.
To get started with this recipe, we must prepare a few components. You can have duck tacos, radish-lime salad, cumin-roasted squash using 15 ingredients and 7 steps. Here is how you cook that.
<!--inarticleads1-->
##### The ingredients needed to make Duck Tacos, Radish-Lime Salad, Cumin-Roasted Squash:
1. Make ready 1 each butternut squash, large dice
1. Get 2 tsp ground cumin
1. Take 1 tbsp olive oil
1. Prepare 4 oz radishes, thinly sliced
1. Get 1/2 each lime, juiced
1. Take 12 leaves cilantro, chopped
1. Take 1 tsp sugar, turbinado
1. Make ready 1 tsp cooking oil
1. Get 10 oz ground duck
1. Prepare 1 small onion, diced small
1. Take 4 tsp taco seasoning
1. Make ready 3 oz water
1. Prepare 6 each tortillas
1. Get 1/2 each lime wedged
1. Make ready 2 oz Cotija cheese
<!--inarticleads2-->
##### Instructions to make Duck Tacos, Radish-Lime Salad, Cumin-Roasted Squash:
1. Preheat your oven to 425°F. Toss the butternut squash in olive oil, salt, and ground cumin. Spread across a heavy baking sheet. Roast for 15-20 minutes, or until squash is browned & tender.
1. Combine the radish, lime juice, cilantro, and sugar. Set aside to use later as a garnish.
1. Heat a large sauté pan over medium-high heat. Add cooking oil, and heat until shimmering and wisping smoke. Add the ground duck meat in an even layer, and cook without stirring or turning to brown, about 2-3 minutes.
1. The duck will have rendered off a good amount of liquid, remove approximately half before proceeding. (You can reserve by chilling this liquid, and use it to cook with later, it has TERRIFIC flavor!)
1. Stir in the diced onion, and cook while stirring until onion begins to turn translucent. Add the taco-seasoning blend, and continue to cook while stirring for 1-2 more minutes, then stir in water. Continue to cook while stirring for 2-3 more minutes. Combine the meat mixture with the cumin-roasted squash.
1. Warm the tortillas. Make tacos using the meat mixture, radish salad, and Cotija cheese.
1. Serve lime wedges as a garnish, and enjoy!
So that's going to wrap this up for this exceptional food duck tacos, radish-lime salad, cumin-roasted squash recipe. Thank you very much for reading. I'm confident that you can make this at home. There is gonna be more interesting food at home recipes coming up. Don't forget to bookmark this page in your browser, and share it to your family, colleague and friends. Thanks again for reading. Go on get cooking!
|
TypeScript
|
UTF-8
| 1,070
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
import { Request, Response } from "express";
import { validateRequest } from "src/core/validator";
import { Task } from "src/models/task";
/**
* @api {get} /tasks Get Tasks
* @apiName GetTasks
* @apiGroup Tasks
*
* @apiSuccessExample Success-Response:
* HTTP/1.1 200 OK
* [
* {
* "id": 1,
* "title": "task title",
* "done": true
* }
* ]
*/
export const get = async (request: Request, response: Response) => {
const validations = validateRequest(request, {
query: {
limit: {
numericality: {
message: "must be a number",
},
},
},
});
if (!validations.success) {
response.status(400);
response.send({ errors: validations.errors });
return;
}
const limit = request.query.limit ?? 10;
const tasks = await Task.find({ where: { user: response.locals.user }, take: limit }).catch(() => null);
if (!tasks) {
response.status(500);
response.send({ error: "Server error." });
return;
}
response.status(200);
response.send(tasks);
};
|
Java
|
UTF-8
| 1,693
| 4.21875
| 4
|
[] |
no_license
|
/* Java revision work sheet 2
* This is for revision learning OOP
* This program will random select a value between 0 and 9
* The user(s) will then attempt to guess that number
* 16/09/2019
*/
package javaHNDOOP;
// Importing required modules
import java.util.Scanner;
// New public class
public class BasicGuessingGame {
// Initialising imported modules
static Scanner kboard = new Scanner( System.in);
// Creating main function/method
public static void main( String[] args) {
String userInput;
System.out.println( "Welcome to G.M.N Basic Guessing Game..");
System.out.println( "I will pick a number, you must guess what it is...");
System.out.println( " ");
System.out.println( "Are you ready? [ press 'p' to play ]");
userInput = kboard.next();
if( userInput.equalsIgnoreCase( "P")) {
genNumber();
} // Closing if statement
} // Closing main function/method
// Creating a function to generate a random value (between 0 and 9)
static void genNumber( ) {
int number;
number = ( int)( Math.random()) +1;
System.out.println( "I have a number");
System.out.println( " ");
playerGuess( number);
} // Closing genNumber function/method
static void playerGuess( int number) {
int userGuess;
System.out.println( "What is your guess?");
userGuess = kboard.nextInt();
while( userGuess != number) {
System.out.println( "Nope, Sorry. Try Again");
userGuess = kboard.nextInt();
} // Closing if statement
if( userGuess == number) {
System.out.println( "That is correct");
} // Closing else statement
} // Closing playerGuess method/function
} // Closing BasicGuessing Game class
|
Python
|
UTF-8
| 1,005
| 3.34375
| 3
|
[] |
no_license
|
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
m, n = len(mat), len(mat[0]) #Get dimensions.
if m * n != r * c: #If total number of elements do not match, cannot reshape so return mat.
return mat
reshape = [[0 for _ in range(c)] for _ in range(r)] #Initialize the reshape matrix.
row, col = 0, 0 #Initialize the pointer to current row and column of pointer traversing reshape matrix.
for i in range(m): #Traverse mat.
for j in range(n):
reshape[row][col] = mat[i][j] #Set the current element of reshape to current element of mat.
row += (col + 1) // c #Update row.
col = (col + 1) % c #Update col.
return reshape
|
Python
|
UTF-8
| 265
| 3.6875
| 4
|
[] |
no_license
|
str = input().strip()
count = [0 for item in range(26)]
for char in str:
if(char.isalpha()):
count[ord(char.lower())-97] += 1
flag=True
for el in count:
if(el == 0):
flag=False
break
if(flag):
print("YES")
else:
print("NO")
|
Java
|
UTF-8
| 2,268
| 2.109375
| 2
|
[] |
no_license
|
package com.qshogun.uiPackage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import static com.qshogun.uiPackage.Help.*;
public class FlightFinderPage {
WebDriver driver;
public FlightFinderPage(WebDriver driver) {
this.driver = driver;
}
@FindBy(how = How.XPATH, using = roundTripXpath)
@CacheLookup
WebElement roundTripButton;
@FindBy(how = How.XPATH, using = onewayTripXpath)
@CacheLookup
WebElement onewayTripButton;
@FindBy(how = How.NAME, using = "passCount")
@CacheLookup
WebElement passCountBox;
@FindBy(how = How.NAME, using = "fromPort")
@CacheLookup
WebElement fromPortTable;
@FindBy(how = How.NAME, using = "toPort")
@CacheLookup
WebElement toPortTable;
@FindBy(how = How.NAME, using = "fromMonth")
@CacheLookup
WebElement fromMonthTable;
@FindBy(how = How.NAME, using = "fromDay")
@CacheLookup
WebElement fromDayTable;
@FindBy(how = How.NAME, using = "toMonth")
@CacheLookup
WebElement toMonthTable;
@FindBy(how = How.NAME, using = "toDay")
@CacheLookup
WebElement toDayTable;
@FindBy(how = How.NAME, using = "airline")
@CacheLookup
WebElement airlineBox;
@FindBy(how = How.NAME, using = "findFlights")
@CacheLookup
WebElement findFlightsButton;
@FindBy(how = How.XPATH, using = serviceClassXpath)
@CacheLookup
WebElement serviceClassTable;
public void continueWordPress(String passCount, String fromPort, String toPort, String fromMonth, String fromDay, String toMonth, String toDay, String airline, String serviceClass) {
roundTripButton.click();
passCountBox.sendKeys(passCount);
fromPortTable.sendKeys(fromPort);
toPortTable.sendKeys(toPort);
fromMonthTable.sendKeys(fromMonth);
fromDayTable.sendKeys(fromDay);
toMonthTable.sendKeys(toMonth);
toDayTable.sendKeys(toDay);
airlineBox.sendKeys(airline);
serviceClassTable.sendKeys(serviceClass);
findFlightsButton.click();
}
}
|
Python
|
UTF-8
| 1,833
| 2.84375
| 3
|
[] |
no_license
|
#!/home/codetc/anaconda3/bin/python
###########################################
# Name: robot.py #
# Author: Matas Lauzadis #
# Description: NASA 2020 Lunabotics Code #
###########################################
import socket # for sending data
import time # for sleeping
import os
import sys
from roboteq import RoboteqDevice # Motor Controller
from roboteq.roboteq_constants import _RWD, _G
if not os.geteuid() == 0:
sys.exit('Only root can run this script')
#### 1) CONNECT TO THE ROBOTEQ DEVICES ####
# Either device_path works, I prefer /serial/by-id because
# it's easier to see that it's a Roboteq Controller by the name
# device_path = '/dev/serial/by-id/usb-Roboteq_Motor_Controller_MDC2XXX-if00'
device_path = '/dev/ttyACM0'
device = RoboteqDevice()
device.connect(device_path)
if(device.is_roboteq_connected):
print('All connected!')
else:
print('Failed to find Roboteq')
raise KeyboardInterrupt
device.set_config(_RWD, 0) # Disable RS232 Watchdog
time.sleep(0.1)
# #### 2) CREATE A UDP SERVER CONNECTION TO THE LAPTOP ####
UDP_IP = '10.0.0.148'
UDP_PORT = 12345
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Specify IPV6, UDP protocol
sock.bind((UDP_IP, UDP_PORT)) # double parenthesis to pass as tuple
# #### 3) RECEIVE DATA! :) ####
data = ''
while True and data != 'stop':
data, addr = sock.recvfrom(1024) # Buffer size is 1024 bytes
data=data.decode('UTF-8')
print('received message:', data)
data = data.split(' ')
print(type(data[0]))
print(type(data[1]))
data[1] = int(data[1])
if data[0] == 'forward':
device.command_motor(_G, 1, data[1])
time.sleep(2)
elif data[0] == 'back':
device.command_motor(_G, 1, data[1])
print('Received stop command!')
sock.close()
|
C++
|
UTF-8
| 2,998
| 2.890625
| 3
|
[] |
no_license
|
#ifndef TEXTQUERY_H_INCLUDED
#define TEXTQUERY_H_INCLUDED
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <set>
#include <memory>
#include <sstream>
#include <algorithm>
using std::string;
using std::vector;
using std::shared_ptr;
using std::weak_ptr;
using std::make_shared;
using std::map;
using std::set;
using std::initializer_list;
using std::cout;
using std::endl;
using std::cin;
using std::ifstream;
using std::ostream;
using std::getline;
using std::stringstream;
using std::out_of_range;
using std::runtime_error;
class StrBlobPtr;
class StrBlob
{
public:
using size_type = vector<string>::size_type;
friend class StrBlobPtr;
StrBlobPtr begin();
StrBlobPtr end();
StrBlob():data(make_shared<vector<string>>()){}
StrBlob(initializer_list<string> il):data(make_shared<vector<string>>(il)){}
bool empty(){return data->empty();}
size_t size(){return data->size();}
void push_back(const string& s){data->push_back(s);}
void pop_back(){check(0, "pop_back on empty StrBlob"); data->pop_back();}
string& front()const{check(0, "front on empty StrBlob"); return data->front();}
string& back()const{check(0, "back on empty StrBlob"); return data->back();}
private:
shared_ptr<vector<string>>data;
void check(size_t i, const string& msg)const
{
if(i >= data->size())
{
throw out_of_range(msg);
}
}
};
class StrBlobPtr
{
public:
StrBlobPtr():curr(0){}
StrBlobPtr(const StrBlob& a, size_t sz = 0):wptr(a.data), curr(sz){}
bool operator!=(const StrBlobPtr& other)const{return curr != other.curr;}
string& operator*()
{
auto pq = check(curr, "drf past end");
return (*pq)[curr];
}
StrBlobPtr& operator++(){++curr; return* this;}
private:
weak_ptr<vector<string>> wptr;
size_t curr;
shared_ptr<vector<string>> check(size_t i, const string& msg)const
{
shared_ptr<vector<string>> ret = wptr.lock();
if(!ret){throw runtime_error("unbound StrBlob");}
if(i >= ret->size()){throw out_of_range(msg);}
return ret;
}
};
class QueryResult;
class TextQuery
{
public:
TextQuery(ifstream& ifs);
QueryResult query(const string& s)const;
private:
StrBlob input;
map<string, shared_ptr<set<StrBlob::size_type>>> dict;
};
class QueryResult
{
public:
QueryResult(const string& s, StrBlob sb, shared_ptr<set<StrBlob::size_type>>st)
:word(s), in(sb), nos(st){}
friend ostream& print(ostream& out, const QueryResult& qr);
set<StrBlob::size_type>::iterator begin()const{return nos->begin();}
set<StrBlob::size_type>::iterator end()const{return nos->end();}
shared_ptr<StrBlob> getFile()const{return make_shared<StrBlob>(in);}
private:
string word;
StrBlob in;
shared_ptr<set<StrBlob::size_type>> nos;
};
ostream& print(ostream& out, const QueryResult& qr);
#endif // TEXTQUERY_H_INCLUDED
|
C#
|
UTF-8
| 1,184
| 2.890625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Phase_1
{
class SolveLinearSwapGreedy : ISolve
{
public delegate void InfoDelegate(Suduku CurrentSuduku, int ProcessedCount);
public event InfoDelegate InfoEvent;
public event ErrorHappenedDelegate ErrorHappend;
public event ProblemSolvedDelegate ProblemSolved;
public bool Start(Suduku su)
{
Queue<Suduku> queue = new Queue<Suduku>();
while(queue.Count > 0)
{
if(Start(queue.Dequeue()))
return true;
}
return false;
}
private Suduku GetNext(Suduku su)
{
for(int i = 0;i < (int)su.SudukuType;i++)
{
for(int j = i+1;j < (int)su.SudukuType;j++)
{
var res = su.Swap(su.ValidRow + 1, i, su.ValidRow + 1, j);
if(res != null && !dic.ContainsKey(res.GetHashCode()))
return res;
}
}
return null;
}
}
}
|
JavaScript
|
UTF-8
| 1,084
| 4.75
| 5
|
[] |
no_license
|
var callFriend = function(){
var friend = 'Jake';
function callF(number){
return 'Calling ' + friend + ' at ' + number;
}
return callF;
};
//Above you're given a callFriend function that returns
//another function.
//Do what you need to do in order to call your function and
//get 'Calling Jake at 435-215-9248' in your console.
var test = callFriend();
test('435-215-9248');
/*
Write a function(one) that accepts a function(two) as it's first
//argument and returns a new function(returned) (which calls the
//original function(two) that was passed in) that can only ever
//be executed once(two).
Once completed, add a second arguments that allows the
//function to be executed N number of times. After the
//function has been called N number of times,
//console.log('STAHHP');
*/
var one = function(two, n) {
var counter = 0;
return function() {
if (counter < n) {
counter++;
return two();
}
else {
console.log('STAHHP')
}
}
}
var two = function() {
console.log("Its working")
}
var test = one(two);
|
C++
|
UTF-8
| 3,218
| 3.109375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause"
] |
permissive
|
#ifndef I_CPPTEST_TEST_H
#define I_CPPTEST_TEST_H
#include "Exception.h"
#include "TestDisplay.h"
#include <typeinfo>
#if TYPEINFO_IN_STD
using std::type_info;
#endif
#include <vector>
namespace CPPTest
{
class TestBase
{
public:
TestBase() : m_pException(0) { }
virtual ~TestBase() { delete m_pException; }
Exception* getException() const { return m_pException; }
virtual bool setup() = 0;
virtual void teardown() = 0;
virtual bool run( TestDisplay& ) = 0;
protected:
Exception *m_pException;
};
template<typename TClass> class Test : public TestBase
{
public:
Test() : m_pObject(0) {}
private:
bool setup()
{
bool result;
try
{
result = onSetup(m_pObject);
}
catch(...){ result = false; }
if( !result )
{
const type_info& type = typeid(this);
m_pException = new Exception
( (std::string) type.name(),
"no futher information available" );
}
return result;
}
void teardown()
{
try
{
onTeardown(m_pObject);
}
catch(...)
{
const type_info& type = typeid(this);
m_pException = new Exception
( (std::string) type.name(),
"no futher information available" );
}
}
bool run( TestDisplay& testDisplay )
{
try
{
const type_info& type = typeid(this);
testDisplay.onRun( type.name() );
onRun(*m_pObject);
testDisplay.onPass( *this );
return true;
}
catch(Exception& exception)
{
m_pException = new Exception(exception);
}
catch(std::exception& exception)
{
m_pException = new Exception(exception);
}
catch(...)
{
const type_info& type = typeid(this);
m_pException = new Exception
( (std::string) type.name(),
"no futher information available" );
m_pException->setError(true);
}
testDisplay.onFail( *this );
return false;
}
operator TClass&()
{
return m_pObject;
}
operator bool()
{
return m_pObject != 0;
}
virtual bool onSetup( TClass*& pObject ) = 0;
virtual void onTeardown( TClass* pObject ) {};
virtual void onRun( TClass& object ) = 0;
TClass* m_pObject;
};
template<typename TClass> class SimpleTest : public Test<TClass>
{
virtual bool onSetup( TClass*& pObject )
{ pObject = &m_object; return true; }
TClass m_object;
};
template<typename TClass> class EmptyTest : public Test<TClass>
{
virtual bool onSetup( TClass*& pObject )
{ return true; }
};
class VoidTest : public Test<void*>
{
bool onSetup( void**& pObject ) { return true; }
};
}
#endif
|
C++
|
UTF-8
| 148
| 2.75
| 3
|
[] |
no_license
|
int sumList( int theList[], int size )
{
int sum = 0;
int i = 0;
while( i < size ) {
sum += theList[ i ];
i += 1;
}
return sum;
}
|
Markdown
|
UTF-8
| 5,719
| 2.75
| 3
|
[] |
no_license
|
11장. 합성과 유연한 설계
=====
강의자의 강의 인트로(?)입니다.
* 11장에서 합성과 믹스인을 말하는 이유도 앞으로 펼쳐질 포인터의 포인터 연산이 언어문법으로 어떻게 제공되는지를 이해시키는 기반이 됩니다.
* 11장은 상속의 조합 폭발과 합성을 가르친다기보다는 그저 데코레이터 패턴을 가르치는 장에 가깝습니다.
- - -
## 목차
1. [참고](#참고)
* [관련자료](#관련자료)
* [책의 목차](#책의-목차)
2. [요약](#요약)
* [객체지향의 본질](#객체지향의-본질)
* [상속과 확장](#상속과-확장)
* [나쁜 확장과 좋은 확장](#나쁜-확장과-좋은-확장)
* 27:30 / 1:02:00
## 참고
### 관련자료
* [유투브 강의](https://www.youtube.com/watch?v=vSnFC2x-RYE)
* [강의 교안](./reference/84_1.pdf)
* [오브젝트 요약정리](../../../book/object/README.md)
### 책의 목차
* 상속을 합성으로 변경하기
* 불필요한 인터페이스 상속문제:
* java.util.Properties와 java.util.Stack
* 메서드 오버라이딩의 오작용 문제: InstrumentedHashSet
* 부모 클래스와 자식 클래스의 동시 수정 문제: PersonalPlaylist
* 상속으로 인한 조합의 폭발적인 증가
* 기본 정책과 부가 정책 조합하기
* 상속을 이용해서 기본 정책 구현하기
* 기본 정책에 세금 정책 조합하기
* 기본 정책에 기본 요금 할인 정책 조합하기
* 중복 코드의 덫에 걸리다
* 합성 관계로 변경하기
* 기본 정책 합성하기
* 부가 정책 적용하기
* 기본 정책과 부가 정책 합성하기
* 새로운 정책 추가하기
* 객체 합성이 클래스 상속보다 더 좋은 방법이다
* 믹스인
* 기본 정책 구현하기
* 트레이트로 부가 정책 구현하기
* 부가 정책 트레이트 믹스인하기
* 쌓을 수 있는 변경
##### [목차로 이동](#목차)
## 요약
### 객체지향의 본질
오브젝트2(코드스피츠84) 첫 강의다. 이 책은 일반적인 객체지향 도서와 비교해 순서가 역전되어 있다.
* 선: 객체지향 사고
* 후: 객체지향이 어떤 식으로 동작하는가(내부적 동작)
오브젝트2는 `내부적 동작`을 다루는 첫 강의다. 자바 다형성 구현의 핵심인 `lazy binding`에서 시작해본다.
| 외부 | 내부 |
| :--: | :--: |
| 키워드 | 포인터의 포인터 |
즉, 다형성은 코드 수준에선 `키워드`로 구현하지만 내부적으로는 `2중 혹은 3중 포인터`라는 것이다. 기본적으로는 메모리에 올라가면 `링크드리스트` 이상도 이하도 아니다.
##### [목차로 이동](#목차)
### 상속과 확장
객체지향 언어 중 상속(`inherit`)이 있는 유일한 언어가 자바다. 타 언어에서는 `inherit`가 아닌 확장, 즉 `extend`가 사용된다. 상속이 확장의 한 종류라고 할 수 있으니, ~~개인적으로~~ 상속을 통해 올바른 확장을 하는 방법을 다룬다고 이해했다.
우선 현실 세계를 예로 정성적인 느낌을 한 번 살펴보면, `확장`은 `자동차에게 날개를 다는 것`이 아니다(~~구분이 어렵긴 하지만~~). 더해, 프로그래밍 세계에서는 `오버로딩` 혹은 `오버라이딩` 같은 개념들도 확장이라고 할 수 있다. 즉 `확장`이라는 개념이 단지 늘리는 것만을 얘기하지 않는다는 것이다. 그렇다면 프로그래밍에서 확장을 위한 규칙은 무엇일까?
* 유산을 물려받지 않을 것
* `super` 및 `protected` 금지
* 단, `public`은 인터페이스의 개념이지 유산(부모-자식간 해당)과는 관계 없음
* 대리 역할을 하지 않을 것
* `override` 금지
* 단지 type만 같을 뿐, 기능하지 않음
즉, 프로그래밍 세계에서 `좋은 확장`이란 `확장하는 쪽이 부분 책임만 지는 것`이다.
##### [목차로 이동](#목차)
### 나쁜 확장과 좋은 확장
* 나쁜 확장
* `super` 사용
* 어떤 문제(부모)가 다른 문제(자식)의 부분 집합이라는 사고 전제(변화에 대응 힘듦)
* `override` 사용
* 미묘한 컨텍스트(부모) 제대로 반영해서 재정의 메소드 생성 힘듦(도메인 지식 필요)
* 나(부모)의 의미는 내 주변이 정의한다는 것이 컨텍스트 이해를 힘들게 함
* 좋은 확장
* `super` 배제 → 이걸 강제한 것이 `interface`
* 부모의 모든 메소드를 `final`, `private`, `abstract protected`로 선언(즉, 자식이 사용하지 못하게 만듦)
* `abstract protected`는 다시 말해, 부모에 동작 혹은 컨텍스트가 없음을 의미
* 이는 부모가 `타입`으로만 작동할 뿐 `기능`하진 않음을 의미
* 부모의 생성자는 인자를 받지 않음(`??`)
* 상속받은 자식이 부모 생성자를 호출하는 것을 방지(의존성 제거)
* `override` 배제
* 부모의 모든 메소드를 `final`, `private`, `abstract protected`로 선언
모던 랭기지는 좋은 확장의 규칙을 문법에 내장하고 있다. 예를 들면 코틀린은 모든 메소드의 디폴트 선언이 `public final`이다.
이 규칙을 지킬 수 없으면 상속을 포기하고 합성을 사용해야 한다. 단 [지난 강의]에 언급했듯, 규칙을 지켜서 상속을 사용하더라도 `클래스 조합 폭발`(`템플릿 메소드 패턴`과 `전략 패턴`의 차이)은 피할 수 없다. 따라서 조합 폭발이 일어나지 않는 경우의 수가 한정되어 있는 케이스에만 상속으로 구현하는 것이 좋다.
##### [목차로 이동](#목차)
### .
##### [목차로 이동](#목차)
|
Java
|
UTF-8
| 719
| 2.21875
| 2
|
[] |
no_license
|
package net.wavyway._02_security.oauth2;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LogoutPathHandler implements LogoutHandler {
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
authentication.setAuthenticated(false);
SecurityContextHolder.clearContext();
response.setStatus(HttpServletResponse.SC_OK);
}
}
|
Java
|
UTF-8
| 2,546
| 2.40625
| 2
|
[] |
no_license
|
package com.mdx.example;
import com.github.pagehelper.PageHelper;
import com.mdx.dao.StudentDao;
import com.mdx.entity.Student;
import com.mdx.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
import java.util.Map;
public class StudentTest {
@Test
public void testSelectStudentById(){
MyBatisUtils myBatisUtils = new MyBatisUtils();
SqlSession sqlSession = myBatisUtils.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Student stu = studentDao.selectStudentById(4);
System.out.println(stu);
sqlSession.close();
}
@Test
public void testSelectMultiParam(){
MyBatisUtils myBatisUtils = new MyBatisUtils();
SqlSession sqlSession = myBatisUtils.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Student stu = studentDao.selectMultiParam("张麻子",25);
System.out.println(stu);
sqlSession.close();
}
@Test
public void testselectResultMap(){
MyBatisUtils myBatisUtils = new MyBatisUtils();
SqlSession sqlSession = myBatisUtils.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
List<Map> stumap = studentDao.selectResultMap(2);
for(Map stu :stumap){
System.out.println(stu);
}
sqlSession.close();
}
@Test
public void testselectStudents(){
MyBatisUtils myBatisUtils = new MyBatisUtils();
SqlSession sqlSession = myBatisUtils.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
//使用PageHelper分页
//PageHelper.startPage(2,3);
List<Student> studentList = studentDao.selectStudents();
for(Student stu :studentList){
System.out.println(stu);
}
sqlSession.close();
}
@Test
public void testinsertStudents(){
MyBatisUtils myBatisUtils = new MyBatisUtils();
SqlSession sqlSession = myBatisUtils.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Student student = new Student();
student.setAge(20);
student.setEmail("guanyu@qq.com");
student.setName("关羽");
student.setId(2001);
String s;
int nums = studentDao.insertStudents(student);
System.out.println(nums==1 ? "新增成功":"新增失败");
sqlSession.close();
}
}
|
C++
|
UTF-8
| 878
| 2.875
| 3
|
[] |
no_license
|
锘�#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <sstream>
#include <algorithm>
using namespace std;
int main(){
string s1("hello");
s1.length();
string s2 = s1.substr(2, 3);
string s3;
s3.assign(s1, 2, 3);
int loc = s1.find("lo");
if (loc == (string::npos)) cout << "Search Failue" << endl;
for (int i = 0; i < s1.length(); i++)
cout << s1.at(i) << endl;
int loc2 = s1.find_first_of("abcde");
string inp("Input test 123 4.7 A");
istringstream inpString(inp);
string str1, str2;
int i; double d; char c;
inpString >> str1 >> str2 >> i >> d >> c;
if (inpString >> d)cout << "not em" << endl;
else cout << "empty" << endl;
ostringstream outString;
int a = 10;
outString << "This " << a << "OK" << endl;
cout << outString.str() << endl;
cout << "Hello World!" << endl;
return 0;
}
|
C++
|
UTF-8
| 2,534
| 2.921875
| 3
|
[] |
no_license
|
/*------------- Mars.h
*/
/***************************************************************
*
***************************************************************/
#pragma once
/*************************************************************/
/* 1. Standard types for AES cryptography source code */
typedef unsigned char u1byte; /* an 8 bit unsigned character type */
typedef unsigned short u2byte; /* a 16 bit unsigned integer type */
typedef unsigned long u4byte; /* a 32 bit unsigned integer type */
typedef signed char s1byte; /* an 8 bit signed character type */
typedef signed short s2byte; /* a 16 bit signed integer type */
typedef signed long s4byte; /* a 32 bit signed integer type */
/* 2. Standard interface for AES cryptographic routines */
/* These are all based on 32 bit unsigned values and may require */
/* endian conversion for big-endian architectures */
#ifndef LITTLE_ENDIAN
#define LITTLE_ENDIAN
#endif
class AES {
public:
virtual void set_key(const u1byte key[], const u4byte key_bits) = 0;
virtual void encrypt(const u1byte in_blk[16], u1byte out_blk[16]) = 0;
virtual void decrypt(const u1byte in_blk[16], u1byte out_blk[16]) = 0;
};
/* 3. Basic macros for speeding up generic operations */
/* Circular rotate of 32 bit values */
#ifdef _MSC_VER
# include <stdlib.h>
# pragma intrinsic(_lrotr,_lrotl)
# define rotr(x,n) _lrotr(x,n)
# define rotl(x,n) _lrotl(x,n)
#else
#define rotr(x, n) (((x) >> ((int)(n))) | ((x) << (32 - (int)(n))))
#define rotl(x, n) (((x) << ((int)(n))) | ((x) >> (32 - (int)(n))))
#endif
/* Invert byte order in a 32 bit variable */
#define bswap(x) (rotl(x, 8) & 0x00ff00ff | rotr(x, 8) & 0xff00ff00)
/* Extract byte from a 32 bit quantity (little endian notation) */
#define byte(x, n) ((u1byte)((x) >> (8 * n)))
/* Input or output a 32 bit word in machine order */
#ifdef LITTLE_ENDIAN
#define u4byte_in(x) (*(u4byte*)(x))
#define u4byte_out(x, v) (*(u4byte*)(x) = (v))
#else
#define u4byte_in(x) bswap(*(u4byte)(x))
#define u4byte_out(x, v) (*(u4byte*)(x) = bswap(v))
#endif
class mars : public AES {
private:
u4byte l_key[40];
public:
const char* name(void);
void set_key(const u1byte key[], const u4byte key_bits);
void encrypt(const u1byte in_blk[16], u1byte out_blk[16]);
void decrypt(const u1byte in_blk[16], u1byte out_blk[16]);
};
|
C#
|
UTF-8
| 2,728
| 3.375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace IntIntKeyedCollection
{
class Program
{
static void Main(string[] args)
{
Guid findGUID = Guid.NewGuid();
GUIDkeyCollection gUIDkeyCollection = new GUIDkeyCollection();
gUIDkeyCollection.Add(new GUIDkey(findGUID));
gUIDkeyCollection.Add(new GUIDkey(Guid.NewGuid()));
gUIDkeyCollection.Add(new GUIDkey(Guid.NewGuid()));
GUIDkey findGUIDkey = gUIDkeyCollection[findGUID]; // lookup by key (behaves like a dict)
Console.WriteLine(findGUIDkey.Key);
Console.WriteLine(findGUIDkey.GetHashCode());
Console.WriteLine(findGUID);
Console.WriteLine(findGUID.GetHashCode());
Console.ReadLine();
}
public class GUIDkeyCollection : KeyedCollection<Guid, GUIDkey>
{
// This parameterless constructor calls the base class constructor
// that specifies a dictionary threshold of 0, so that the internal
// dictionary is created as soon as an item is added to the
// collection.
//
public GUIDkeyCollection() : base() { }
// This is the only method that absolutely must be overridden,
// because without it the KeyedCollection cannot extract the
// keys from the items.
//
protected override Guid GetKeyForItem(GUIDkey item)
{
// In this example, the key is the part number.
return item.Key;
}
}
public class GUIDkey : Object
{
private Guid key;
public Guid Key
{
get
{
return key;
}
}
public override bool Equals(Object obj)
{
//Check for null and compare run-time types.
if (obj == null || !(obj is GUIDkey)) return false;
GUIDkey item = (GUIDkey)obj;
return (Key == item.Key);
}
public override int GetHashCode() { return Key.GetHashCode(); }
public GUIDkey(Guid guid)
{
key = guid;
}
}
}
}
|
Go
|
UTF-8
| 3,388
| 3.015625
| 3
|
[
"BSD-3-Clause",
"CC-BY-4.0",
"LicenseRef-scancode-google-patent-license-golang"
] |
permissive
|
// errorcheck -0 -m -l
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Test escape analysis when assigning to indirections.
package escape
var sink interface{}
type ConstPtr struct {
p *int
c ConstPtr2
x **ConstPtr
}
type ConstPtr2 struct {
p *int
i int
}
func constptr0() {
i := 0 // ERROR "moved to heap: i"
x := &ConstPtr{} // ERROR "&ConstPtr{} does not escape"
// BAD: i should not escape here
x.p = &i
_ = x
}
func constptr01() *ConstPtr {
i := 0 // ERROR "moved to heap: i"
x := &ConstPtr{} // ERROR "&ConstPtr{} escapes to heap"
x.p = &i
return x
}
func constptr02() ConstPtr {
i := 0 // ERROR "moved to heap: i"
x := &ConstPtr{} // ERROR "&ConstPtr{} does not escape"
x.p = &i
return *x
}
func constptr03() **ConstPtr {
i := 0 // ERROR "moved to heap: i"
x := &ConstPtr{} // ERROR "&ConstPtr{} escapes to heap" "moved to heap: x"
x.p = &i
return &x
}
func constptr1() {
i := 0 // ERROR "moved to heap: i"
x := &ConstPtr{} // ERROR "&ConstPtr{} escapes to heap"
x.p = &i
sink = x
}
func constptr2() {
i := 0 // ERROR "moved to heap: i"
x := &ConstPtr{} // ERROR "&ConstPtr{} does not escape"
x.p = &i
sink = *x // ERROR "\*x escapes to heap"
}
func constptr4() *ConstPtr {
p := new(ConstPtr) // ERROR "new\(ConstPtr\) escapes to heap"
*p = *&ConstPtr{} // ERROR "&ConstPtr{} does not escape"
return p
}
func constptr5() *ConstPtr {
p := new(ConstPtr) // ERROR "new\(ConstPtr\) escapes to heap"
p1 := &ConstPtr{} // ERROR "&ConstPtr{} does not escape"
*p = *p1
return p
}
// BAD: p should not escape here
func constptr6(p *ConstPtr) { // ERROR "leaking param content: p"
p1 := &ConstPtr{} // ERROR "&ConstPtr{} does not escape"
*p1 = *p
_ = p1
}
func constptr7() **ConstPtr {
p := new(ConstPtr) // ERROR "new\(ConstPtr\) escapes to heap" "moved to heap: p"
var tmp ConstPtr2
p1 := &tmp
p.c = *p1
return &p
}
func constptr8() *ConstPtr {
p := new(ConstPtr) // ERROR "new\(ConstPtr\) escapes to heap"
var tmp ConstPtr2
p.c = *&tmp
return p
}
func constptr9() ConstPtr {
p := new(ConstPtr) // ERROR "new\(ConstPtr\) does not escape"
var p1 ConstPtr2
i := 0 // ERROR "moved to heap: i"
p1.p = &i
p.c = p1
return *p
}
func constptr10() ConstPtr {
x := &ConstPtr{} // ERROR "moved to heap: x" "&ConstPtr{} escapes to heap"
i := 0 // ERROR "moved to heap: i"
var p *ConstPtr
p = &ConstPtr{p: &i, x: &x} // ERROR "&ConstPtr{...} does not escape"
var pp **ConstPtr
pp = &p
return **pp
}
func constptr11() *ConstPtr {
i := 0 // ERROR "moved to heap: i"
p := new(ConstPtr) // ERROR "new\(ConstPtr\) escapes to heap"
p1 := &ConstPtr{} // ERROR "&ConstPtr{} does not escape"
p1.p = &i
*p = *p1
return p
}
func foo(p **int) { // ERROR "p does not escape"
i := 0 // ERROR "moved to heap: i"
y := p
*y = &i
}
func foo1(p *int) { // ERROR "p does not escape"
i := 0 // ERROR "moved to heap: i"
y := &p
*y = &i
}
func foo2() {
type Z struct {
f **int
}
x := new(int) // ERROR "moved to heap: x" "new\(int\) escapes to heap"
sink = &x
var z Z
z.f = &x
p := z.f
i := 0 // ERROR "moved to heap: i"
*p = &i
}
var global *byte
func f() {
var x byte // ERROR "moved to heap: x"
global = &*&x
}
|
Python
|
UTF-8
| 1,071
| 2.84375
| 3
|
[] |
no_license
|
from socket import *
import struct
# 小端(3 --> 0x0003,低位内存地址对应小数据) 大端(3 --> 0x3000)
# ! 表示按照网络大端方式组织
# 后面的内容可以认为是占位符的使用
# H:两个字节长度
# 8:表示后面最近内容的个数
# s:bytes 多个字节
# b:byte 1个字节
# struct.pack('!H8sb5sb', 1, )
# struct.unpack()
# 服务器端
ss = socket(AF_INET, SOCK_STREAM)
'''
1.创建套接字SOCK_STREAM
2.绑定ip和port
3.服务器端开始监听端口listen
4.等待连接accept
- 连接对应发送方的套接字 和 发送方ip与port
- 注意:1.绑定的套接字用于接受新的客户端连接
2.创建新的套接字用于连接当前客户端
5.recv/send 收发数据
6.关闭套接字
'''
s_addr = ("192.168.145.128", 7788)
ss.bind(s_addr)
# backlog 表示队列大小
ss.listen(4)
new_s, c_addr = ss.accept()
# 客户端
'''
1.创建套接字
2.connect连接服务端
3.收发数据
4.关闭套接字
'''
cs = socket(AF_INET, SOCK_STREAM)
cs.connect(s_addr)
cs.send(b'haha')
cs.close()
|
Ruby
|
UTF-8
| 611
| 3.5
| 4
|
[] |
no_license
|
class Bob
def hey(inputRemark)
remark = Remark.new(inputRemark)
if remark.yell?
return "Whoa, chill out!"
elsif remark.question?
return "Sure."
elsif remark.silence?
return "Fine. Be that way!"
else
return "Whatever."
end
end
end
class Remark < String
def initialize(remark)
@remark = remark
end
def yell?
(@remark.upcase == @remark) && !(@remark.match(/[A-Z]/).nil?) && (@remark != "I?")
end
def question?
@remark.split(//).last == "?"
end
def silence?
@remark.sub(/\s+/,"") == ""
end
end
|
Python
|
UTF-8
| 99
| 3.546875
| 4
|
[] |
no_license
|
sum=0
squ=0
n=100
for i in range(1,n+1):
sum=sum+i
squ=squ+i**2
dif=sum**2-squ
print(dif)
|
Shell
|
UTF-8
| 952
| 3.0625
| 3
|
[] |
no_license
|
#!/bin/bash
#set -eo pipefail
source ../config/cluster.config
source ../config/kubernetes.config
source ../config/utils.sh
announce "Deleting Conjur Followers."
set_namespace $CONJUR_NAMESPACE_NAME
echo "Deleting Follower pods."
$CLI delete deployment/conjur-follower --force=true
$CLI delete svc/conjur-follower --force=true
echo "Deleting server-certificate config map."
$CLI delete --ignore-not-found cm $CONJUR_CONFIG_MAP
echo "Deleting cluster roles, role bindings and service accounts."
$CLI delete --ignore-not-found clusterrole conjur-authenticator-$CONJUR_NAMESPACE_NAME
$CLI delete --ignore-not-found rolebinding conjur-authenticator-role-binding-$CONJUR_NAMESPACE_NAME
$CLI delete --ignore-not-found sa conjur
$CLI delete --ignore-not-found sa conjur-cluster
echo "Waiting for Conjur pods to terminate..."
while [[ "$($CLI get pods 2>&1)" != "No resources found." ]]; do
echo -n '.'
sleep 3
done
echo
echo "Followers deleted."
|
Markdown
|
UTF-8
| 7,660
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
# Trakko Generation Language DSL Specification (TGL DSL)
| schema version | specification | status |
| :------------: | :-----------: | :------: |
| Arakesh | **below** | proposed |
## **1. About the project**
The Trakko Generation Language (in short TGL) is a markup DSL inspired by JSON and Groovy. It is designed to generate api clients and documentation as well as data classes and database connections from a simple markup language format, stored in a `.tgl` file. The TGL executor is in charge of interpreting the instructions of a file and as such can generate source files in all supported programming languages and can be extended with custom instructions via a plugin system.
---
## **2. General structures**
| name | usage | example |
| ------------------------ | -------------------------- | ---------------------- |
| task & struct | NAME { } | `create { }` |
| instruction | NAME | `documentation` |
| instruction with options | NAME: OPTION1, OPTION2 | `build-client: 'java'` |
| function | NAME(ARGUMENT1, ARGUMENT2) | `range(1, 5)` |
---
## **2.1 Tasks**
- `create {}`
- Task running when called via an executor's (CLI/GUI) create command.
- Contains instructions used to generate code and/or documentation files.
- `docs {}`
- Task defining properties for generating documentation files, for example to include custom css files.
- `data {}`
- Task defining the structure of data used to generate data classes/objects.
- It specifies which variables should be created including their name and data type.
---
## **2.2 Instructions**
### `CREATE` & `DOCS`
- output-dir: '*PATH*'
- Specifies the directory path the generated content should be written to.
- **`PATH`**: Either a relative file path starting with `./` or an absolute file path. If the path doesn't exists it will be created when the task is executed.
- output-filename: '*NAME*'
- Defines the filename the generated file will have.
- **`NAME`**: A valid filename string. It doesn't need to have a `.*` extension as the needed extensions will be added nontheless automatically.
### `CREATE`
- build-client: '*PLATFORM_1*', '*PLATFORM_2*', ...
- Instructs the executor to generate clients for the described api for the given platform or platforms if more then one or `all` is specified.
- **`PLATFORM`**: Platform descriptor or keyword e.g. `all` or `java`. The possible platforms are based on the executor and used plugins and, as such, may vary.
- build-data-object: '*PLATFORM_1*', '*PLATFORM_2*', ...
- Instructs the executor to generate data classes/objects for the described data structure for the given platform or platforms if more then one or `all` is specified.
- **`PLATFORM`**: Platform descriptor or keyword e.g. `all` or `java`. The possible platforms are based on the executor and used plugins and, as such, may vary.
- build-db-connector: '*DATABASE_1*', '*DATABASE_2*', ...
- Calls the executor to create an abstract database access object (dao) and implementation of such in for the specified database types.
- **`DATABASE`**: Database name or keyword e.g. `all`, `MySql` ,or `MongoDB`. The possible database types are based on the executor and used plugins and, as such, may vary.
- docs-api
- Instruction guiding the executor to generate documentation for the defined api structure.
- docs-client: '*PLATFORM_1*', '*PLATFORM_2*', ...
- Instructs the executor to generate documentation files for clients of the described api for the given platform or platform if more then one or `all` is specified.
- **`PLATFORM`**: Platform descriptor or keyword e.g. `all` or `java`. The possible platforms are based on the executor and used plugins and, as such, may vary.
### `DOCS`
- type: '*TYPE*'
- Specifing the file format which the documentation will be generated in.
- **`TYPE`**: Valid types are `markdown` (short form: `md`) [**default**] or `html`.
- include-css: '*PATH*'
- Defining the path of a custom css file which will be included in the generated documentation file. [**ONLY HTML**]
- **`PATH`**: Either a relative file path starting with `./` or an absolute file path.
### `DATA`
- field {*OPTION_1*, *OPTION_2*}
- Defining a field/variable to hold data.
- **`OPTIONS`**:
- name: '*NAME*'
- Specifing the field's name/variable name.
- **`NAME`**: String containing only letters.
- type: '*TYPE*'
- Declaring the data type the variable/field should hold.
- **`TYPE`**: Identifier for type information, which is looked up in the mapping files in `/tgl/lang-maps/` folder.
- get: 'default', return($+1)
- Specifies the way the value of this field is returned.
- TODO
- set: 'default', range(1,5), min(0) & max(18), ifNull('default')
- Defines the way and/or constrains used to asign a new value to the field.
- TODO
- equals: '*STRATEGY*'
- Specifies the way objects should be compared to equality.
- **`STRATEGY`**: Either `recursive` [**default**] comparing values and object types recursively whether they are equal, or `$FIELD_NAME` to compare the given field or fields (if multiple) to check for equality (`FIELD_NAME` needs to be substituted with the name of the desired field).
- endpoint {*OPTION_1*, *OPTION_2*}
- Giving details about an endpoint.
- **`OPTIONS`**:
- path: '*PATH*'
- Specifing the path where the endpoint is located at.
- **`PATH`**: Path string seperated by `/` characters.
- method: '*METHOD*'
- Defining the http method for the endpoint.
- **`METHOD`** A valid http method e.g. `GET` or `POST`.
- request-data-format: '*FORMAT*'
- If given a value, this will mark the endpoint to be in need of request data in the supplied format.
- **`FORMAT`**: Format string after the mime-type format e.g. `text/plain` or `application/json`.
- success-response: '*CODE*'
- Lists the response code which will be returned after a succesful operation.
- **`CODE`**: A http status code number e.g. `200` or `404`.
- response-data-format: '*FORMAT*'
- If given a value, this will give details about the response data format.
- **`FORMAT`**: Format string after the mime-type format e.g. `text/plain` or `application/json`.
---
## **2.3 Examples**
TODO
---
## **3. Plugins**
Plugins may extend the capabilities of the executor to further customise the behaviour of the code generation and include functionality not included in the overall standard already. For this purpose, plugins may define their own tasks, instructions and functions, which should integrate into standard functions without problems. Plugins are located in the `/tgl/` folder in the subdirectory `/plugins/`.
---
## **4. TGL Executor (CLI/GUI Tool)**
Runs through instructions listed in `.tgl` files and executes them.
Plugins can supply custom instructions to include.
---
## **4.1 Commands**
### `create`
Runs through all `.tgl` files in the current working directory an executes the instructions given in the `create` task.
### `create-recursive`
Is equal to running the `create` command for the current working directory and all its subdirectories recursively.
### `plugins`
Shows a list of all detected and usable plugins found in the `/plugins/` subfolder of the executor (system global plugins) and the current working directory (project plugins).
### `version`
Prints the build version of the executor and which schema version it's implementing.
|
Markdown
|
UTF-8
| 11,372
| 3.4375
| 3
|
[] |
no_license
|
---
title: 构建一个基于 Redux 的 react 应用
created: 2018/05/21
description: 构建一个基于 Redux 的 react 应用
author: lanqy
---
# 构建一个基于 Redux 的 react 应用
在这篇文章里,我们将深入理解以及学习为什么开发React应用的时候,使用Redux这么重要。我也将一步一步教你如何创建你的第一个Redux应用,包括怎样使用<a href="https://github.com/stormpath/stormpath-sdk-react">Stormpath React SDK </a>于<a href="https://stormpath.com/product/authentication/"> user authentication(用户认证)</a>。当你完成的时候,你将掌握这个知识并运用到你已有到React应用中。
###Redux是什么?
<a href="https://github.com/reactjs/redux">Redux</a>是一个用于帮助我们管理应用状态到的框架(library)。它的设计源于<a href="https://facebook.github.io/react/docs/flux-overview.html">Flux</a>,但是从编写Flux应用的痛苦中进化而来。如果你写过Flux应用,你将很快注意到Redux可以帮你自动做很多以前你需要手动做的事情,还有,你只有一个单一的状态容器,这是一个很大的优势,这样在你的应用中共享状态和重用代码会变得更加简单。
### Stores
store是一个简单的状态容器,这是存储你应用状态和actions调度和处理的地方。当你开始创建一个Redux应用时,你要想想你的应用程序的数据和状态应该如何存储。这是很重要的,因为Redux推荐一个应用只有一个store,而且由于状态是共享的,因此在开始创建应用的时候,想好这些尤为重要。
### Actions
Actions 是一些用于描述我们怎样改变我们应用状态的对象,你可以这么认为actions就是我们状态树的API。例如,一个添加用户的action可以像这样:
```javascript
{
type: 'ADD_USER',
data: {
name: 'Foo',
email: 'foo@bar.com',
password: 'Foobar123_'
}
}
```
为了让代码更清晰,更易于重用,通常是使用一个生成器(方法)生成操作对象,即,上面的例子,我们可以创建一个类似于```addUser(name, email, password) ```的函数来生成对象。如你所见,actions本身什么都不做,一个action仅仅是一个用于描述我们怎样改变我们应用状态的对象。
### Reducers
Actions很酷,但是它们并没有太大的意义。这就是reducers存在的意义。
Reducers是action处理器,用于在store中调度actions以及在状态变化中简化actions操作。如果我们要在store中调度action(ADD_USER),我们将拥有一个reducer调用action(ADD_USER)并添加一个新的用户到我们到应用状态中。
### 创建Redux应用
现在,当你了解的基础知识以后,让我们继续创建我们第一个基于Redux的应用程序。<br/>
为了让事情变得简单,我们将要创建一个todo应用程序,这样我们可以玩转很多Redux的重要概念,而不用过多的关注应用本身。<br/>
我们考虑一下一个todo应用程序,需要些什么基本的东西。首先一个todo程序,由一个列表组成。其实这个列表包含一些我们可以改变的项目。<br/>
从应用的状态来看,我们可以这样定义我们的模型(model):
```javascript
{
todo: {
items: [
{
message: "Finish Redux blog post...",
completed: false
}
]
}
}
```
### 添加 Actions
我们要怎样处理我们应用的状态呢?首先,我们添加一个新待办项目到我们状态中去,让我们创建一个action来做这件事:
```javascript
function addTodo(message) {
return {
type: 'ADD_TODO',
message: message,
completed: false
};
}
```
注意```type```这个字段,这个必须是唯一的,用于表明action的意图。
type字段的约定格式为大写字母,并且每个单词以下划线作为分隔,接下来你将使用这个名字/标示符在你的reducers中来处理具体的actions,并把它们变成可变的状态。<br/>
一旦我们增加了我们的待办事项,我们肯定希望能够将其标记为已完成状态,我们也可以删除它,可以清空所有的待办项目。<br/>
因此让我们创建actions来做这些事情:
```javascript
function completeTodo(index) {
return {
type: 'COMPLETE_TODO',
index: index
};
}
function deleteTodo(index) {
return {
type: 'DELETE_TODO',
index: index
};
}
function clearTodo() {
return {
type: 'CLEAR_TODO'
};
}
```
到目前为止,我们已经定义好我们的actions,让我们继续定义我们的store,如前所述,store是Redux应用的核心,所有的状态(state)、调度器(dispatched actions)、reducers都依赖于它。
```javascript
import { createStore } from 'redux';
var defaultState = {
todo: {
items: []
}
};
function todoApp(state, action) {
}
var store = redux.createStore(todoApp, defaultState);
```
### 添加Reducers
现在,我们已经拥有一些actions和一个store。让我们创建我们的第一个reducer,如前所述,reducer仅仅是一个action处理器,拥有处理actions和改变应用的状态(state)。
让我们先处理我们的```ADD_TODO``` action,如下所示:
```javascript
function todoApp(state, action) {
switch (action.type) {
case 'ADD_TODO':
var newState = Object.assign({}, state);
newState.todo.items.push({
message: action.message,
completed: false
});
return newState;
default:
return state;
}
}
```
注意,当我们说一个reducer“改变”了应用的状态,如果一个状态需要改变,我们真正要做的是创建一个状态(state)的副本,并修改这个状态的副本。如果状态没有改变,那我们就返回相同的状态。任何情况下,如果你直接修改原始的状态(state),这意味着你将改变状态的历史。<br/>
现在我们有了第一个我们的action处理器,让我们添加其它的:<br/>
```javascript
function todoApp(state, action) {
switch (action.type) {
case 'ADD_TODO':
var newState = Object.assign({}, state);
newState.todo.items.push({
message: action.message,
completed: false
});
return newState;
case 'COMPLETE_TODO':
var newState = Object.assign({}, state);
newState.todo.items[action.index].completed = true;
return newState;
case 'DELETE_TODO':
var items = [].concat(state.todo.items);
items.splice(action.index, 1);
return Object.assign({}, state, {
todo: {
items: items
}
});
case 'CLEAR_TODO':
return Object.assign({}, state, {
todo: {
items: []
}
});
default:
return state;
}
}
```
###结合React UI
现在,我们已经制定了业务逻辑,让我们写一些UI代码,由于大部分React的知识都跟构建Flux应用类似,我们就不再深入讲解。一下是我们的代码:
```js
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
var defaultState = {
todo: {
items: []
}
};
// Add the actions here that we created in the previous steps...
function todoApp(state, action) {
// Add the reducer logic that we added in the previous steps...
}
var store = createStore(todoApp, defaultState);
class AddTodoForm extends React.Component {
state = {
message: ''
};
onFormSubmit(e) {
e.preventDefault();
store.dispatch(addTodo(this.state.message));
this.setState({ message: '' });
}
onMessageChanged(e) {
var message = e.target.value;
this.setState({ message: message });
}
render() {
return (
<form onSubmit={this.onFormSubmit.bind(this)}>
<input type="text" placeholder="Todo..." onChange={this.onMessageChanged.bind(this)} value={this.state.message} />
<input type="submit" value="Add" />
</form>
);
}
}
class TodoItem extends React.Component {
onDeleteClick() {
store.dispatch(deleteTodo(this.props.index));
}
onCompletedClick() {
store.dispatch(completeTodo(this.props.index));
}
render() {
return (
<li>
<a href="#" onClick={this.onCompletedClick.bind(this)} style=>{this.props.message.trim()}</a>
<a href="#" onClick={this.onDeleteClick.bind(this)} style=>[x]</a>
</li>
);
}
}
class TodoList extends React.Component {
state = {
items: []
};
componentWillMount() {
store.subscribe(() => {
var state = store.getState();
this.setState({
items: state.todo.items
});
});
}
render() {
var items = [];
this.state.items.forEach((item, index) => {
items.push(<TodoItem
key={index}
index={index}
message={item.message}
completed={item.completed}
/>);
});
if (!items.length) {
return (
<p>
<i>Please add something to do.</i>
</p>
);
}
return (
<ol>{ items }</ol>
);
}
}
ReactDOM.render(
<div>
<h1>Todo</h1>
<AddTodoForm />
<TodoList />
</div>,
document.getElementById('container')
);
```
如你所见,为Redux应用构建我们的UI并不难,唯一不同的是使用```store.subscribe(listener)```来监听状态(state)的改变,然后通过```store.getState()```获取状态。但除此之外,它非常像构建Flux应用。
### 在Stormpath React SDK中支持Redux
因为有不少请求为Stormpath React SDK添加Redux支持,因此我们实现了这个功能,如果你想配置SDK来使用Redux,简单配置dispatcher选项并设置几个type和redux指向store,具体如下:
```javascript
function myApp(state, action) {
return state;
}
ReactStormpath.init({
dispatcher: {
type: 'redux',
store: createStore(myApp)
}
});
```
一旦做到这一点,我们就可以通过Stormpath React SDK拦截和处理我们的actions调度,例如,如果你希望通过用户数据来丰富你的状态,那么简单地处理```USER_SET```action来添加用户数据到你的状态中。
```javascript
function myApp(state, action) {
switch (action.type) {
case 'USER_SET':
return Object.assign({}, state, {
user: action.data
});
default:
return state;
}
}
```
###总结
正如你在文章中所看到的一样,构建一个Redux应用是非常简单和直接的。这就像是构建Flux应用一样,仅仅是概念上的差异,并且手动写的代码变得更少。希望你们喜欢这个教程,并且发现未来你可以使用它。如果有任何问题,请参考github上的<a href="https://github.com/typerandom/stormpath-react-redux-todo-example-application" target="_blank">项目</a>。<br/>
###扩展阅读
想要学习更多关于给React应用添加用户认证,请看以下教程:
* <a href="https://stormpath.com/blog/build-a-react-app-with-user-authentication/">Tutorial: Build a React.js Application With User Authentication</a>
* <a href="https://stormpath.com/blog/react-sdk-custom-forms/">Custom Login and Registration Forms</a>
注:本文翻译自<a href="https://stormpath.com/blog/build-a-redux-powered-react-application/" target="_blank">Let's Build a Redux Powered React Application</a>,如有翻译不对的地方请指正。谢谢!
|
Python
|
UTF-8
| 5,844
| 3.140625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
******************************************************************************************************************************
Project: Network Intrusion Detection using Artificial Neural Network(ANN) Discovery
Program Name: PYTHON_NID_ANN_12052019.01.00
Author: Richard Kessler
Date Created: 12.05.2019
Purpose: ANN analysis of Network Intrusion data to identify feature selection and model parameters.
Data Scope: Network Intrusion training data which contain network logs and traffic features used to detect anomalies.
******************************************************************************************************************************
"""
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
# Importing the dataset
dataset = pd.read_csv('Train_data.csv')
X = dataset.iloc[:, 1:42].values
y = dataset.iloc[:, 0].values
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
#Encode Categorical Variable 1
labelencoder_X_1 = LabelEncoder()
X[:, 0] = labelencoder_X_1.fit_transform(X[:, 0])
#Encode Categorical Variable 2
labelencoder_X_2 = LabelEncoder()
X[:, 1] = labelencoder_X_2.fit_transform(X[:, 1])
#Encode Categorical Variable 3
labelencoder_X_3 = LabelEncoder()
X[:, 2] = labelencoder_X_3.fit_transform(X[:, 2])
#Create Dummy Variables
onehotencoder = OneHotEncoder(categorical_features = [0])
X = onehotencoder.fit_transform(X).toarray()
#Removing the first dummy variable as 3 were created and we need to reduce to 2
X = X[:, 1:]
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
#Initializing the ANN
classifier = Sequential()
#Adding the input layer and the first hidden layer with Dropout
classifier.add(Dense(activation = 'relu', units = 22, kernel_initializer = 'uniform', input_dim = 42))
classifier.add(Dropout(rate = 0.1))
#Adding a second hidden layer
classifier.add(Dense(activation = 'relu', units = 22, kernel_initializer = 'uniform'))
classifier.add(Dropout(rate = 0.1))
#Adding an output layer (binary outcome)
classifier.add(Dense(activation = 'sigmoid', units = 1, kernel_initializer = 'uniform'))
#Compiling the ANN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
#Fitting the ANN to the Training Set
classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)
# Predicting the Test set results
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)
# Confusion Matrix Accuracy (99% Accurate)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
#Evaluate the ANN using Kfold - Pre-Eval Accuracy: 99.4%, Post-Eval Accuracy: 99.63
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
def build_classifier():
classifier = Sequential()
classifier.add(Dense(activation = 'relu', units = 22, kernel_initializer = 'uniform', input_dim = 42))
classifier.add(Dense(activation = 'relu', units = 22, kernel_initializer = 'uniform'))
classifier.add(Dense(activation = 'sigmoid', units = 1, kernel_initializer = 'uniform'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
return classifier
classifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs = 100)
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = 1)
mean = accuracies.mean()
variace = accuracies.std()
#Tuning the ANN to discover the best parameters for Keras optimization
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
from keras.models import Sequential
from keras.layers import Dense
def build_classifier(optimizer):
classifier = Sequential()
classifier.add(Dense(activation = 'relu', units = 22, kernel_initializer = 'uniform', input_dim = 42))
classifier.add(Dense(activation = 'relu', units = 22, kernel_initializer = 'uniform'))
classifier.add(Dense(activation = 'sigmoid', units = 1, kernel_initializer = 'uniform'))
classifier.compile(optimizer = optimizer, loss = 'binary_crossentropy', metrics = ['accuracy'])
return classifier
classifier = KerasClassifier(build_fn = build_classifier)
#GridSearch Dictionary
parameters = {'batch_size': [25, 32],
'epochs': [100, 500],
'optimizer': ['adam', 'rmsprop']}
grid_search = GridSearchCV(estimator = classifier,
param_grid = parameters,
scoring = 'accuracy',
cv = 10)
grid_search = grid_search.fit(X_train, y_train)
best_parameters = grid_search.best_params_
best_accuracy = grid_search.best_score_
"""
********************************************************************************************************************************
Analysis Outcome: Overall, the ANN model performed extremely well with predictions coming in over 99% using the initial training
data without feature modification. Although this model resulted in high accuracy...it shows preliminary expectations of overfitting.
Recommended Actions: Significantly reduce feature scope and re-validate which I believe will result in <99% accuracy but a less
biased model.
********************************************************************************************************************************
|
Python
|
UTF-8
| 3,213
| 2.71875
| 3
|
[] |
no_license
|
import logging
from urlparse import urljoin
from urllib import urlencode
from Cookie import SimpleCookie
import tornado.httpclient
import json
from simple_notification import notify
class HTTPClient(object):
def __init__(self, http_client=None):
self.http_client = http_client if http_client else \
tornado.httpclient.HTTPClient()
self.cookies = SimpleCookie()
def get(self, url, data=None, headers={}):
if data is not None:
if isinstance(data, dict):
data = urlencode(data)
if '?' in url:
url += '&%s' % data
else:
url += '?%s' % data
return self.__fetch(url, 'GET', headers=headers)
def post(self, url, data, headers={}):
if data is not None:
if isinstance(data, dict):
data = urlencode(data)
return self.__fetch(url, 'POST', data, headers)
def __fetch(self, url, method, data=None, headers={}):
#Send the cookies that have been previously set
if len(self.cookies) > 0:
headers["Cookie"] = self.cookies.output(attrs=[],
header="",sep=";").strip()
response = self.http_client.fetch(url, method=method,
body=data, headers=headers)
try:
#Record any new cookies set
self.cookies.update(SimpleCookie(response.headers["Set-Cookie"]))
except KeyError:
pass
return response
class NotificationClient(HTTPClient):
def __init__(self,url):
HTTPClient.__init__(self)
self.url = url
def post(self, url, data, headers={}):
if self.xsrf_token:
data["_xsrf"] = self.xsrf_token
return super(NotificationClient, self).post(url, data, headers)
def login(self, username, password):
if not self.xsrf_token:
self.get(urljoin(self.url, "/auth/login"))
return self.post(urljoin(self.url,"/auth/login"), {"name":username})
def get_notifications(self):
while True:
try:
#TODO: pass in a cursor of the last update seen
#Otherwise, we might miss notifications
resp = self.post(urljoin(self.url, "/api/notification/updates"), {})
print resp.body
notes = json.loads(resp.body)
for note in notes["notifications"]:
notify.Message(note["summary"],note["message"],note["category"])
except tornado.httpclient.HTTPError, e:
if e.code != 599:
logging.error("Bad response from server",exc_info=True)
def new_notification(self, notification):
resp = self.post(urljoin(self.url, "/api/notification/new"), {"body":notification})
return resp
@property
def xsrf_token(self):
try:
return self.cookies["_xsrf"].value
except KeyError:
return None
def main():
client = NotificationClient("http://localhost:8889")
client.login("asdf","asdf")
client.get_notifications()
if __name__ == "__main__":
main()
|
Markdown
|
UTF-8
| 13,474
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
Kurl.sh
====================================
Kurl is a Kubernetes installer for airgapped and online clusters.
Kurl relies on `kubeadm` to bring up the Kubernetes control plane, but there are a variety of tasks a system administrator must perform both before and after running kubeadm init in order to have a production-ready Kubernetes cluster, such as installing Docker, configuring Pod networking, or installing kubeadm itself.
The purpose of this installer is to automate those tasks so that any user can deploy a Kubernetes cluster with a single script.
## Online Usage
To run the latest version of the install script:
```
curl https://kurl.sh/latest | sudo bash
```
HA
```
curl https://kurl.sh/latest | sudo bash -s ha
```
## Airgapped Usage
To install Kubernetes in an airgapped environment, first fetch the installer archive:
```
curl -LO https://kurl.sh/bundle/latest.tar.gz
```
After copying the archive to your host, untar it and run the install script:
```
tar xvf latest.tar.gz
cat install.sh | sudo bash
```
## Supported Operating Systems
* Ubuntu 16.04
* Ubuntu 18.04 (Recommended)
* CentOS 7.4, 7.5, 7.6
* RHEL 7.4, 7.5, 7.6
## Minimum System Requirements
* 2 CPUs or more
* 4 GB or more of RAM per machine
* TCP ports 6443 and 6783 open
* UDP ports 6783 and 6784 open
## Options
The install scripts are idempotent. Re-run the scripts with different flags to change the behavior of the installer.
| Flag | Usage |
| -------------------------------- | -------------------------------------------------------------------------------------------------- |
| airgap | Do not attempt outbound Internet connections while installing |
| bypass-storagedriver-warnings | Bypass all Docker storagedriver warnings |
| bootstrap-token | Authentication token used by kubernetes when adding additional nodes |
| bootstrap-token-ttl | TTL of the `bootstrap-token` |
| ceph-pool-replicas | Replication factor of ceph pools. Default is based on number of ready nodes if unset. |
| disable-contour | If present, disables the deployment of the Contour ingress controller |
| disable-prometheus | If present, disables the deployment of Prometheus monitoring components |
| disable-rook | Do not deploy the Rook add-on |
| encrypt-network | Disable network encryption with `encrypt-network=0` |
| ha | Install in multi-master mode |
| hard-fail-on-loopback | If present, aborts the installation if devicemapper on loopback mode is detected |
| http-proxy | If present, then use proxy |
| ip-alloc-range | Customize the range of IPs assigned to pods |
| load-balancer-address | IP:port of a load balancer for the K8s API servers in ha mode |
| service-cidr | Customize the range of virtual IPs assigned to services |
| nodeless | Create a nodeless setup (see [section below](#Nodeless)) |
| no-docker | Skip docker installation |
| no-proxy | If present, do not use a proxy |
| public-address | The public IP address |
| private-address | The private IP address |
| no-ce-on-ee | Disable installation of Docker CE onto platforms it does not support - RHEL, SLES and Oracle Linux |
| reset | Uninstall Kubernetes |
| storage-class | The name of an alternative StorageClass that will provision storage for PVCs |
## Joining Nodes
The install script will print the command that can be run on worker nodes to join them to your new cluster.
This command will be valid for 2 hours.
To get a new command to join worker nodes, re-run the install script on the master node.
For HA clusters, the install script will print out separate commands for joining workers and joining masters.
## Connecting Remotely
You can generate a kubeconfig to use from your local machine with:
```
sudo bash install.sh task=generate-admin-user
```
This will use the load balancer or public address for the Kubernetes API server and generate a new user with full admin privileges.
Be sure to open TCP port 6443 to allow traffic from your local machine.
## What It Does
### Kubeadm Pre-Init
Kurl will perform the following steps on the host prior to delegating to `kubeadm init`.
* Check OS compatibility
* Check Docker compatiblity if pre-installed
* Disable swap
* Check SELinux
* Install Docker
* Install Kubeadm, Kubelet, Kubectl and CNI packages
* Generate Kubeadm config files from flags passed to the script
* Load kernel modules required for running Kube-proxy in IPVS mode
* Configure Docker and Kubernetes to work behind a proxy if detected
### Add-Ons
After `kubeadm init` has brought up the Kubernetes control plane, Kurl will install addons into the cluster.
The available addons are:
* [Weave](https://www.weave.works/oss/net/)
* [Rook](https://rook.io/)
* [Contour](https://projectcontour.io/)
* [Docker Registry](https://docs.docker.com/registry/)
* [Prometheus](https://prometheus.io/)
* [Nodeless](https://www.elotl.co/)
* [Calico](https://www.projectcalico.org/)
* AWS (enables the AWS cloud provider in Kubernetes)
## Nodeless
When a nodeless setup is created, pods annotated with "kubernetes.io/target-runtime":"kiyot" will be scheduled to run on EC2 instances, started and terminated on demand. For example, to run nginx:
kubectl run nginx --image=nginx --replicas=5 --overrides='{"apiVersion":"apps/v1", "spec": {"template": {"metadata": {"annotations": {"kubernetes.io/target-runtime":"kiyot"}}}}}'
To create a nodeless cluster, use:
sudo bash install.sh nodeless
Nodeless currently only works on AWS. When you create an EC2 instance for running the install script, it needs to be tagged with:
"kubernetes.io/cluster/<cluster-name>" = "owned"
The IAM policy for the instance:
```
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"autoscaling:DescribeAutoScalingGroups",
"autoscaling:DescribeLaunchConfigurations",
"autoscaling:DescribeTags",
"ec2:AttachVolume",
"ec2:AuthorizeSecurityGroupIngress",
"ec2:CreateRoute",
"ec2:CreateSecurityGroup",
"ec2:CreateTags",
"ec2:CreateVolume",
"ec2:DeleteRoute",
"ec2:DeleteSecurityGroup",
"ec2:DeleteVolume",
"ec2:DescribeAddresses",
"ec2:DescribeElasticGpus",
"ec2:DescribeImages",
"ec2:DescribeInstances",
"ec2:DescribeRegions",
"ec2:DescribeRouteTables",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSpotPriceHistory",
"ec2:DescribeSubnets",
"ec2:DescribeTags",
"ec2:DescribeVolumes",
"ec2:DescribeVpcAttribute",
"ec2:DescribeVpcs",
"ec2:DetachVolume",
"ec2:ModifyInstanceAttribute",
"ec2:ModifyInstanceCreditSpecification",
"ec2:ModifyVolume",
"ec2:ModifyVpcAttribute",
"ec2:RequestSpotInstances",
"ec2:RevokeSecurityGroupIngress",
"ec2:RunInstances",
"ec2:TerminateInstances",
"ecr:BatchGetImage",
"ecr:GetAuthorizationToken",
"ecr:GetDownloadUrlForLayer",
"elasticloadbalancing:AddTags",
"elasticloadbalancing:AttachLoadBalancerToSubnets",
"elasticloadbalancing:ApplySecurityGroupsToLoadBalancer",
"elasticloadbalancing:CreateLoadBalancer",
"elasticloadbalancing:CreateLoadBalancerPolicy",
"elasticloadbalancing:CreateLoadBalancerListeners",
"elasticloadbalancing:ConfigureHealthCheck",
"elasticloadbalancing:DeleteLoadBalancer",
"elasticloadbalancing:DeleteLoadBalancerListeners",
"elasticloadbalancing:DescribeLoadBalancers",
"elasticloadbalancing:DescribeLoadBalancerAttributes",
"elasticloadbalancing:DetachLoadBalancerFromSubnets",
"elasticloadbalancing:DeregisterInstancesFromLoadBalancer",
"elasticloadbalancing:ModifyLoadBalancerAttributes",
"elasticloadbalancing:RegisterInstancesWithLoadBalancer",
"elasticloadbalancing:SetLoadBalancerPoliciesForBackendServer",
"elasticloadbalancing:AddTags",
"elasticloadbalancing:CreateListener",
"elasticloadbalancing:CreateTargetGroup",
"elasticloadbalancing:DeleteListener",
"elasticloadbalancing:DeleteTargetGroup",
"elasticloadbalancing:DescribeListeners",
"elasticloadbalancing:DescribeLoadBalancerPolicies",
"elasticloadbalancing:DescribeTargetGroups",
"elasticloadbalancing:DescribeTargetHealth",
"elasticloadbalancing:ModifyListener",
"elasticloadbalancing:ModifyTargetGroup",
"elasticloadbalancing:RegisterTargets",
"elasticloadbalancing:SetLoadBalancerPoliciesOfListener",
"iam:CreateServiceLinkedRole",
"kms:DescribeKey"
],
"Resource": [
"*"
]
}
]
}
```
If nodeless is chosen, the kubenet network plugin will be used instead of Weave, and EBS for persistent volumes instead of Rook.
HA works with nodeless, but currently only one nodeless worker instance per cluster is supported.
More information: https://www.elotl.co/
## How It Works
The `bundles` directory holds Dockerfiles used to download the Kubernetes and Docker host packages required for each supported OS.
Make tasks use these Dockerfiles to run an image for the target OS and download .dep or .rpm files and all required dependencies.
The `scripts` directory contains the top-level `install.sh` and `join.sh` scripts along with helper scripts.
The `web` directory holds an Express app for serving the install scripts.
## Setting up a nodeless Kubernetes cluster
Enable the aws, nodeless and calico plugins, and disable prometheus, weave, rook, kotsadm and contour:
diff --git a/scripts/Manifest b/scripts/Manifest
index 04d4f74..a467744 100644
--- a/scripts/Manifest
+++ b/scripts/Manifest
@@ -1,12 +1,15 @@
KUBERNETES_VERSION=1.15.3
DOCKER_VERSION=18.09.8
-WEAVE_VERSION=2.5.2
-ROOK_VERSION=1.0.4
-CONTOUR_VERSION=0.14.0
+#WEAVE_VERSION=2.5.2
+#ROOK_VERSION=1.0.4
+#CONTOUR_VERSION=0.14.0
REGISTRY_VERSION=2.7.1
-PROMETHEUS_VERSION=0.33.0
-KOTSADM_VERSION=1.1.0
+#PROMETHEUS_VERSION=0.33.0
+#KOTSADM_VERSION=1.1.0
KOTSADM_APPLICATION_SLUG=sentry-enterprise
+AWS_VERSION=0.0.1
+NODELESS_VERSION=0.0.1
+CALICO_VERSION=3.9.1
KURL_URL=
The AWS cloud provider in Kubernetes needs cloud resources to be tagged with the cluster name, otherwise it won't use them. For an example on how to create a VPC, subnet, route table, instance, IAM profile and security groups, everything tagged correctly, please see the file `addons/aws/0.0.1/create-vpc.tf`.
## Contributing
1. Spin up an instance for the target OS, e.g. Ubuntu 18.04.
1. Build the Kubernetes host packages for your desired version of Kubernetes. For K8s 1.15.2 on Ubuntu 18.04 you'd use `make build/packages/kubernetes/1.15.2/ubuntu-18.04`. (For packages that have already been released, you can save time by running `curl -L https://kurl.sh/dist/kubernetes-1.15.2.tar.gz | tar xzvf -` on your server.)
1. Airgap only - build the Docker package: `make build/packages/docker/18.09.8/ubuntu-18.04`
1. OPTIONAL - when developing the kurl-util image `export SYNC_KURL_UTIL_IMAGE=1`
1. Run the task to watch for code changes and copy them to your server: `REMOTES=<user>@<hostname>,<user>@<hostname2> make watchrsync`
1. Edit scripts/Manifest to configure Kubernetes and addons.
That will place the installer in your HOME's kurl directory and sync any changes you make locally to the scripts/ directory.
If you rebuild the OS packages, you'll need to manually run `rsync -r build/ ${USER}@${HOST}:kurl` to push those changes.
The `make watchrsync` command requires Node with the `gaze-run-interrupt` package available globally.
On the remote instance run `cd ~/kurl && sudo bash install.sh` to test your changes.
|
C++
|
UTF-8
| 691
| 3.0625
| 3
|
[] |
no_license
|
/*
* Copyright (c) 2018
* Carick Wienke <carick dot wienke at gmail dot com>
*/
#pragma once
#include "Direction.hpp"
enum class Orientation : bool
{
Horizontal,
Vertical
};
Orientation perpendicular( Orientation orientation );
class Edge
{
public:
static Edge fromDirection( Direction side );
static const Edge Right;
static const Edge Left;
static const Edge Top;
static const Edge Bottom;
public:
int index() const;
Orientation parallel() const;
Orientation perpendicular() const;
Edge( const Edge& other ) = default;
private:
Edge( Orientation orientation, bool topOrLeft );
Orientation _orientation;
bool _topOrLeft;
};
|
C
|
UTF-8
| 146
| 2.78125
| 3
|
[] |
no_license
|
#include<stdio.h>
void main()
{
int a[3][3]={1,2,3,4,5,6,7,8,9};
int b[6]={1,2,3,4,5,6};
printf("%d\n",*(b+1));
printf("%d\n",*(*(a+2)+1));
}
|
C#
|
UTF-8
| 842
| 2.75
| 3
|
[] |
no_license
|
public static IQueryable<TResult> Select<TSource, TResult>(this IQueryable<TSource> source, IEnumerable<string> columns)
{
// the x in x => ...
var par = Expression.Parameter(typeof(TSource), "x");
// "Bindings" (the Col1 = x.Col1 inside the x => new { Col1 = x.Col1 })
var binds = columns.Select(x => Expression.Bind((MemberInfo)typeof(TResult).GetProperty(x) ?? typeof(TResult).GetField(x), Expression.PropertyOrField(par, x)));
// new TResult
var new1 = Expression.New(typeof(TResult));
// new TResult { Bindings }
var mi = Expression.MemberInit(new1, binds);
// x => new TResult { Bindings }
var lambda = Expression.Lambda<Func<TSource, TResult>>(mi, par);
// Select(x => new TResult { Bindings })
return source.Select(lambda);
}
|
Markdown
|
UTF-8
| 2,485
| 3.484375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
**Elementary**
Simple tab control.
```jsx
const { Tabs, TabPage } = require('precise-ui');
<Tabs>
<TabPage header="First">
First content.
</TabPage>
<TabPage header="Second">
Second content.
</TabPage>
<TabPage header="Third">
Third content.
</TabPage>
<TabPage header="Last">
Final content.
</TabPage>
</Tabs>
```
Simple tab control starting at a different tab.
```jsx
const { Tabs, TabPage } = require('precise-ui');
<Tabs defaultIndex={2}>
<TabPage header="First">
First content.
</TabPage>
<TabPage header="Second">
Second content.
</TabPage>
<TabPage header="Third">
Third content.
</TabPage>
<TabPage header="Last">
Final content.
</TabPage>
</Tabs>
```
Using the tab control to not present the last tab. This is possible since the Tabs component has two states:
* controlled
* managed (not controlled)
The latter is automatically active if no value for `selectedIndex` was (initially) passed. It cannot be changed during the lifetime. If we want to start with a different tab than the first one, we should then use the `defaultIndex` prop. In controlled mode we are therefore required to use the `onTabChange` callback. This way we can react to data changes and apply them to the underlying model.
**Controlled Mode**
Let's see the controlled mode in action.
```jsx
const { Tabs, TabPage } = require('precise-ui');
class MyTabComponent extends React.Component {
constructor() {
this.state = {
index: 0
};
this.changeTab = (e) => {
if (e.selectedIndex < 3) {
this.setState({
index: e.selectedIndex
});
}
};
}
render() {
return (
<Tabs
selectedIndex={this.state.index}
onTabChange={this.changeTab}>
<TabPage header="First">
First content.
</TabPage>
<TabPage header="Second">
Second content.
</TabPage>
<TabPage header="Third">
Third content.
</TabPage>
<TabPage header="Last">
Final content.
</TabPage>
</Tabs>
);
}
}
<MyTabComponent />
```
The previous example always updates the model with exception of changing the selected index to the last tab. As this is not performed we won't be able to look into the last tab. This could be used to disable a tab or do other things which are necessary from the perspective of some business logic. Don't forget to add the visual hint in the header.
|
C++
|
UTF-8
| 1,594
| 3.03125
| 3
|
[] |
no_license
|
// C++ traditional way
#include <cassert>
#include <cstddef>
//include boost thread
#include <boost/thread/thread.hpp>
int shared_i = 0;
void do_inc() {
for (std::size_t i = 0; i < 30000; ++i) {
// do some work
// ......
const int i_snapshot = ++ shared_i;
// do some work with i_snapshot
// ......
}
}
void do_dec() {
for (std::size_t i = 0; i < 30000; ++i) {
// do some work
// ......
const int i_snapshot = --shared_i;
// do some work with i_snapshot
// ......
}
}
void run() {
boost::thread t1(&do_inc);
boost::thread t2(&do_dec);
t1.join();
t2.join();
// assert(shared_i == 0); // Ooops
std::cout << "shared_i == " << shared_i << std::endl;
}
int main() {
run();
return 0;
}
//##############################################################################
// we need to change the code so that only one thread modify the shared_i
// variable at a single moment of time
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
int shared_i = 0;
boost::mutex i_mutex;
void do_inc() {
for (std::size_t i = 0; i < 30000; ++i) {
// do some work
// ......
int i_snapshot;
{ // critical section begins
boost::lock_guard<boost::mutex> lock(i_mutex);
i_snapshot = ++ shared_i;
} // critical section ends
}
}
void do_dec() {
for (std::size_t i = 0; i < 30000; ++i) {
// do some work
// ......
int i_snapshot;
{
boost::lock_guard<boost::mutex> lock(i_mutex);
i_snapshot = -- shared_i;
}
// do some work with i_snapshot
// ......
}
}
|
JavaScript
|
UTF-8
| 3,550
| 2.625
| 3
|
[] |
no_license
|
let request = require('request');
let fs = require('fs');
module.exports = {
pwd: function(done) {
// if(cmd === 'pwd'){
// cmd = process.cwd();
// }
done(process.cwd())
//process.stdout.write(process.cwd());
// process.stdout.write('\nprompt > ');
},
date: function(done){
done(Date());
// process.stdout.write(Date());
// process.stdout.write('\nprompt > ');
},
ls: function(done){
fs.readdir('.', function(err, files) {
let fileArr = [];
if (err) throw err;
files.forEach(function(file) {
fileArr.push(file);
//process.stdout.write(file.toString() + "\n");
});
done(fileArr.join('\n'));
//process.stdout.write("prompt > ");
});
},
echo: function(done, strArr){
//console.log(strArr);
done(strArr.slice(1).join(' '))
// process.stdout.write(strArr.slice(1).join(' '));
// process.stdout.write('\nprompt > ');
},
cat: function(done, fileArr){
//console.log(fileArr[1])
fs.readFile(process.cwd() + '/' + fileArr[1], (err,data)=> {
if(err) throw err;
done(data);
// process.stdout.write(data);
// process.stdout.write('prompt > ');
});
},
head: function(done, fileArr){
fs.readFile(process.cwd() + '/' + fileArr[1],'utf8', (err,data)=> {
if(err) throw err;
done(data.split('\n').slice(0,5).join('\n'))
// process.stdout.write(data.split('\n').slice(0,5).join('\n'));
// process.stdout.write('prompt > ');
});
},
tail: function(done, fileArr){
fs.readFile(process.cwd() + '/' + fileArr[1],'utf8', (err,data)=> {
if(err) throw err;
done(data.split('\n').slice(-6).join('\n'));
// process.stdout.write(data.split('\n').slice(-6).join('\n'));
// process.stdout.write('prompt > ');
});
},
sort: function(done, fileArr){
fs.readFile(process.cwd() + '/' + fileArr[1],'utf8', (err,data)=> {
if(err) throw err;
process.stdout.write(data.split('\n').sort().join('\n')+'\n');
process.stdout.write('prompt > ');
});
},
wc: function(done, fileArr){
fs.readFile(process.cwd() + '/' + fileArr[1],'utf8', (err,data)=> {
if(err) throw err;
done(data.split('\n').length + '\n')
// process.stdout.write(data.split('\n').length + '\n');
// process.stdout.write('prompt > ');
});
},
uniq: function(done, fileArr){
fs.readFile(process.cwd() + '/' + fileArr[1],'utf8', (err,data)=> {
if(err) throw err;
let split = data.split('\n');
let newArr = [split[0]];
for(let i = 1; i<split.length; i++){
if(split[i] !== newArr[i-1]){
newArr.push(split[i]);
}
}
done(newArr.join('\n')+'\n');
// process.stdout.write(newArr.join('\n')+'\n');
// process.stdout.write('prompt > ');
});
},
curl: function(done, fileArr){
let url = fileArr[1];
request(url,function(error, response, body){
if(error) throw error;
done(body+'\n');
// process.stdout.write(body+'\n');
// process.stdout.write('prompt > ');
})
}
}
|
C
|
UTF-8
| 2,744
| 3.34375
| 3
|
[] |
no_license
|
#include "library2.h"
int main(int argc, char **argv){
int pkt_numero, i;
float tiempo_primera_llegada, tiempo_corriendo, tiempo, tiemposistema;
FILE*t_entre_llegadas; // fichero para almacenar el Tiempo entre llegadas.
FILE*t_en_sistema; // fichero para almacenar el Tiempo en el sistema.
t_entre_llegadas = fopen("tllegadas.txt","w"); // Fichero de escritura
t_en_sistema = fopen("tsistema.txt","w");
pkt_numero = 0; // Se inicializa el numero de pkts.
tiempo_corriendo = TIEMPO_INICIAL;// Se inicializa el tiempo, se actualiza tras cada pkt nuevo.
// Generacion e insercion del evento genesis:
tiempo_primera_llegada = random_poisson(LAMBDA);
tiempo_corriendo += tiempo_primera_llegada;
InsertarEvento(&lista_eventos,CrearEvento(tiempo_corriendo,PKT_IN)); // Creacion e insercion del evento en la lista.
// Generacion en insercion del evento final:
InsertarEvento(&lista_eventos,CrearEvento(TIEMPO_FINAL, PKT_END)); // el tiempo en el que llega este pkt es 30, marcando el fin de la simulacion.
// La lista debe contenter el primer y ultimo evento:
PintarLista(&lista_eventos);
// Se muestra al usuario que ha llegado un pkt (sin tener en cuenta el final):
printf("llega 1 pkt.\n");
// se pausa el programa esperando interaccion del usuario.
getchar();
// Bucle infinito usando i como contador del numero de iteraciones que se realizan.
for (i=1; i>=1; i++){
// Dependiendo del tipo de pkt se realiza una u otra accion.
switch ( lista_eventos->tipo) {
case PKT_IN:
// Se escribe el tiempo en el que llega el pkt para conseguir el tiempo entre llegadas:
fprintf(t_entre_llegadas,"%f \n",lista_eventos -> tiempo);
//Creacion e insercion de un evento nuevo de llegada:
tiempo = (lista_eventos->tiempo) + random_poisson(LAMBDA);
InsertarEvento(&lista_eventos,CrearEvento(tiempo, PKT_IN));
tiemposistema = random_poisson(MU); // tiempo que va a permanecer en el sistema.
fprintf(t_en_sistema,"%f \n",tiemposistema); //Se escribe el tiempo que va a permanencia del pkt en el sistema.
// Creacion e insercion de un evento nuevo de salida:
tiempo = (lista_eventos->tiempo) + tiemposistema;
InsertarEvento(&lista_eventos,CrearEvento(tiempo,PKT_OUT));
break;
case PKT_OUT:
puts("Paquete Transmitido.");
tiemposistema = lista_eventos->tiempo;
fprintf(t_en_sistema,"%f \n",tiemposistema); // se escribe en fichero el tiempo.
break;
case PKT_END:
puts("Programa Finalizado");
exit(1);
break;
}
printf("iteracion %i \n",(i));
PintarLista(&lista_eventos);
// se elimina de la lista el evento puesto que ya ha sido procesado.
BorrarEvento(&lista_eventos,lista_eventos->tiempo);
}
}
|
Python
|
UTF-8
| 471
| 2.875
| 3
|
[] |
no_license
|
import sys
from progressbar import AnimatedMarker, Bar, BouncingBar, Counter, ETA, Percentage, ProgressBar, ReverseBar, RotatingMarker, SimpleProgress, Timer
class Progress:
def __init__(self, max):
self.max = max;
self.widgets = ['Queueing', Percentage(), Bar()]
self.index = 0
def start(self):
self.pbar = ProgressBar(widgets=self.widgets, maxval=self.max).start()
def next(self):
self.pbar.update( self.index + 1 )
def finish(self):
self.pbar.finish()
|
JavaScript
|
UTF-8
| 824
| 3.21875
| 3
|
[] |
no_license
|
const Snub = require('../snub.js');
// create multiple snub instances, and listen on each.
const snub1 = new Snub();
snub1.on('hello', (payload) => {
console.log('Recieved Instance 1 => ', payload);
});
const snub2 = new Snub();
snub2.on('hello', (payload) => {
console.log('Recieved Instance 2 => ', payload);
});
const snub3 = new Snub();
snub3.on('hello', (payload) => {
console.log('Recieved Instance 3 => ', payload);
});
// timeout is not required, just needed for example when running multiple snub instances in single app
setTimeout(() => {
// at this point we have three listeners we can test this buy doing the following.
snub1.poly('hello', 'You can see me per listener').send();
// send 'hello' to a single listener 1 time.
snub3.mono('hello', 'Im delivered only once').send();
}, 500);
|
TypeScript
|
UTF-8
| 829
| 2.78125
| 3
|
[] |
no_license
|
export interface FieldUiState {
id: string;
expand: boolean;
}
export interface Size {
width: number;
height: number;
}
export interface Template {
name: string;
image: string | null;
size: Size;
fontName: 'NotoSansCJKjp';
fields: Field[];
}
interface BaseField {
id: string;
name: string;
sampleData: string;
position: {
x: number;
y: number;
};
size: Size;
}
export interface TextField extends BaseField {
type: 'text';
style: {
alignment: 'left' | 'center' | 'right';
fontSize: number;
characterSpacing: number;
lineHeight: number;
};
}
export interface ImageField extends BaseField {
type: 'image';
style: {};
}
export type Field = TextField | ImageField;
export function isTextField(field: Field): field is TextField {
return field.type === 'text';
}
|
JavaScript
|
UTF-8
| 3,594
| 2.546875
| 3
|
[] |
no_license
|
//функция обновления при загрузке страницы
$(document).ready(function () {
update_content();
})
//функция добавления курса для отслеживания
function LoadVal(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}
catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Ваш браузер не поддерживает Ajax");
}
}
}
var id_code=document.getElementById('my_select').value;
ajaxRequest.onreadystatechange=function () {
if (ajaxRequest.readyState==4){
var arr=JSON.parse(ajaxRequest.responseText);
for(var i=0; i<arr.length; i++){
var s="<tr>";
s+="<td>"+arr[i].Name+"</td>";
s+="<td>"+arr[i].EngName+"</td>";
s+="<td>"+arr[i].Nominal+"</td>";
s+="<td>"+arr[i].ISO_Char_Code+"</td>";
s+="<td>"+arr[i].curs+"</td>";
s+="</tr>";
}
s+="</table>";
var ajaxDisplay=document.getElementById('ajaxDiv');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
contentType: false,
cache: false,
processData: false,
success: function (result) {
update_content();
},
});
ajaxDisplay.innerHTML=s;
}
}
ajaxRequest.open("GET","insert_ajax.php?id_code="+id_code ,true);
ajaxRequest.send(null);
}
//функция удаления
function DelVal(id_code){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}
catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Ваш браузер не поддерживает Ajax");
}
}
}
ajaxRequest.onreadystatechange=function () {
if (ajaxRequest.readyState==4){
var ajaxDisplay=document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML=ajaxRequest.responseText;
}
}
ajaxRequest.open("GET","delete_ajax.php?id_code="+id_code,true);
$.ajax({
//type: $(this).attr('method'),
url: $(this).attr('action'),
contentType: false,
cache: false,
processData: false,
success: function (result) {
update_content();
},
});
ajaxRequest.send(null);
}
//функция обновления
function update_content() {
$.ajax({
type: 'post',
url: 'select_form.php',
contentType: false,
cache: false,
processData: false,
success: function (result) {
document.getElementById('cont').innerHTML = result;
},
});
}
|
C#
|
UTF-8
| 801
| 3.265625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassObjectsStep223
{
public class Program
{
static void Main(string[] args)
{
Math math = new Math();
Console.WriteLine(" What number you want to do the math operations.?\n ");
int mathOperations = Convert.ToInt32(Console.ReadLine());
int firstMath = math.mathstuff1(mathOperations);
int secondtMath = math.mathstuff2(mathOperations);
int ThirdMath = math.mathstuff3(mathOperations);
Console.WriteLine("First math: " + firstMath + "\nSecond math : " + secondtMath + "\nThird Math : " + ThirdMath);
Console.ReadLine();
}
}
}
|
Java
|
UTF-8
| 8,100
| 2.03125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2016 SPeCS.
*
* 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. under the License.
*/
package pt.up.fe.specs.clava.ast.decl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.suikasoft.jOptions.Datakey.DataKey;
import org.suikasoft.jOptions.Datakey.KeyFactory;
import org.suikasoft.jOptions.Interfaces.DataStore;
import pt.up.fe.specs.clava.ClavaNode;
import pt.up.fe.specs.clava.ast.decl.enums.Linkage;
import pt.up.fe.specs.clava.ast.decl.enums.NameKind;
import pt.up.fe.specs.clava.ast.decl.enums.Visibility;
import pt.up.fe.specs.clava.ast.type.Type;
import pt.up.fe.specs.util.SpecsCheck;
import pt.up.fe.specs.util.SpecsCollections;
import pt.up.fe.specs.util.collections.SpecsList;
/**
* Represents a decl with a name.
*
* TODO: getDeclName() should be made abstract.
*
* @author JoaoBispo
*
*/
public abstract class NamedDecl extends Decl {
/// DATAKEYS BEGIN
public final static DataKey<String> QUALIFIED_PREFIX = KeyFactory.string("qualifiedPrefix");
public final static DataKey<String> DECL_NAME = KeyFactory.string("declName");
public final static DataKey<NameKind> NAME_KIND = KeyFactory.enumeration("nameKind", NameKind.class)
.setDefault(() -> NameKind.IDENTIFIER);
/**
* True if this declaration is a C++ class member.
*/
public final static DataKey<Boolean> IS_CXX_CLASS_MEMBER = KeyFactory.bool("isCXXClassMember");
/**
* True if this declaration is an instance member of a C++ class.
*/
public final static DataKey<Boolean> IS_CXX_INSTANCE_MEMBER = KeyFactory.bool("isCXXInstanceMember");
/**
* The linkage of the declaration from a semantic point of view.
* <p>
* Entities in anonymous namespaces are external (in c++98).
*/
public final static DataKey<Linkage> LINKAGE = KeyFactory.enumeration("linkage", Linkage.class);
/**
* The visibility of this entity.
*/
public final static DataKey<Visibility> VISIBILITY = KeyFactory.enumeration("visibility", Visibility.class);
/// DATAKEYS END
public NamedDecl(DataStore data, Collection<? extends ClavaNode> children) {
super(data, children);
}
protected String processDeclName(String declName) {
// return declName == null ? "" : declName;
return declName != null && declName.isEmpty() ? null : declName;
}
protected Type processType(Type type) {
return type == null ? getFactory().nullType() : type.copy();
}
public String getDeclName() {
return get(DECL_NAME);
}
public void setDeclName(String declName) {
set(DECL_NAME, declName);
}
public boolean hasDeclName() {
String declName = getDeclName();
if (declName.isEmpty()) {
return false;
}
return true;
}
/**
* The code of this decl, without the type declaration.
*
* @return
*/
public String getTypelessCode() {
return getDeclName();
}
/**
* The qualified prefix that should be used for this record in the scope it currently is.
*
* <p>
* For instance, if Decl has the qualified prefix a::b, and is inside the namespace a, returns b.
*/
public Optional<String> getCurrentQualifiedPrefix() {
// Get namespace
String namespace = getNamespace().orElse(null);
if (namespace == null) {
return Optional.empty();
}
// Split namespace
List<String> namespaceElements = new ArrayList<>(Arrays.asList(namespace.split("::")));
// Get namespace chain for this node
List<ClavaNode> ancestors = this.getAncestors(Arrays.asList(NamespaceDecl.class, TagDecl.class));
int prefixElementsToRemove = 0;
var numToCheck = Math.min(ancestors.size(), namespaceElements.size());
// SpecsCheck.checkArgument(ancestors.size() <= namespaceElements.size(),
// () -> "Expected number of qualifier ancestors ("
// + ancestors.stream().map(node -> ((NamedDecl) node).getDeclName()).collect(Collectors.toList())
// + ") to be less or equal than the number of namespace elements (" + namespaceElements
// + ")");
// Remove elements that correspond to the same prefix in current node namespace
// for (int i = 0; i < ancestors.size(); i++) {
for (int i = 0; i < numToCheck; i++) {
var ancestor = ancestors.get(i);
SpecsCheck.checkArgument(ancestor instanceof NamedDecl, () -> "Expected a NamedDecl, got " + ancestor);
var namedDecl = (NamedDecl) ancestor;
// System.out.println("NAMESPACE " + i + ": " + namespaceElements.get(i));
// System.out.println("NAMED DECL " + i + ": " + namedDecl.getDeclName());
if (namespaceElements.get(i).equals(namedDecl.getDeclName())) {
prefixElementsToRemove++;
} else {
break;
}
}
// Remove prefix elements
var currentNamespaceElements = SpecsCollections.subList(namespaceElements, prefixElementsToRemove);
// No more namespaces, return current namespace elements
if (currentNamespaceElements.isEmpty()) {
return Optional.empty();
}
return Optional.of(currentNamespaceElements.stream().collect(Collectors.joining("::")));
}
public Optional<String> getNamespace() {
// Qualified name has full name
String qualifiedName = get(QUALIFIED_PREFIX);
if (qualifiedName.isEmpty()) {
return Optional.empty();
}
String currentString = qualifiedName;
// Remove template parameters
int templateParamStart = currentString.indexOf('<');
if (templateParamStart != -1) {
currentString = currentString.substring(0, templateParamStart);
}
String namespace = currentString;
// Remove ::, if present
// TODO: Unnecessary now?
if (namespace.endsWith("::")) {
namespace = namespace.substring(0, namespace.length() - "::".length());
}
return !namespace.isEmpty() ? Optional.of(namespace) : Optional.empty();
}
public String getCurrentQualifiedName() {
var declName = getDeclName();
String qualifiedPrefix = getCurrentQualifiedPrefix().orElse("");
if (qualifiedPrefix.isEmpty()) {
return declName;
}
return qualifiedPrefix + "::" + declName;
}
public String getFullyQualifiedName() {
var declName = getDeclName();
return getNamespace()
.map(namespace -> namespace + "::" + declName)
.orElse(declName);
}
@Override
public SpecsList<DataKey<?>> getSignatureKeys() {
return super.getSignatureKeys().andAdd(DECL_NAME).andAdd(QUALIFIED_PREFIX);
}
public void setQualifiedName(String qualifiedName) {
// Split the qualified name into qualified prefix and name
String name = qualifiedName;
String qualifiedPrefix = "";
int lastIndexOfColon = qualifiedName.lastIndexOf("::");
if (lastIndexOfColon != -1) {
qualifiedPrefix = qualifiedName.substring(0, lastIndexOfColon);
name = qualifiedName.substring(lastIndexOfColon + "::".length(), qualifiedName.length());
}
set(QUALIFIED_PREFIX, qualifiedPrefix);
set(DECL_NAME, name);
}
}
|
JavaScript
|
UTF-8
| 1,858
| 3.109375
| 3
|
[] |
no_license
|
import { invariant } from "../../../lib/unit";
const SPACE = " ";
const ENTER = `
`;
export const LEFT_BRACKET = "{";
const RIGHT_BARCKET = "}";
const END = ";";
class Grammar {
constructor() {
this._index = 0;
this._stack = [];
}
parse(input) {
this._input = input;
}
_parseSentence() {
let token = "";
while (this._index < this._input.length) {
const _character = this._input[this._index++];
if (_character === LEFT_BRACKET) {
this._stack.push(LEFT_BRACKET);
token += _character;
} else if (_character === RIGHT_BARCKET) {
const _popCharacter = this._stack.pop();
invariant(_popCharacter === LEFT_BRACKET, "wrong stack instance");
if (this._stack.length === 0) {
return LEFT_BRACKET + token + RIGHT_BARCKET;
} else {
token += _character;
}
} else {
token += _character;
}
}
invariant(false, "no close barcket found");
}
nextToken() {
let token = "";
while (this._index < this._input.length) {
const _character = this._input[this._index++];
if (_character === SPACE || _character === ENTER) {
if (token === "") {
continue;
} else {
return token;
}
} else if (_character === END) {
if (token === "") {
return END;
} else {
this._index--;
return token;
}
} else if (_character === LEFT_BRACKET) {
if (token === "") {
invariant(this._stack.length === 0, "the stack should be empty");
this._stack.push(_character);
return this._parseSentence();
} else {
invariant(false, "do not use { in the name");
}
} else {
token += _character;
}
}
return token;
}
}
export { Grammar };
|
C++
|
UTF-8
| 1,055
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
#include "LightSensor.hpp"
const unsigned int LightSensor::CONNECTION_ATTEMPT_DELAY = 500;
const unsigned int LightSensor::CONNECTION_TIMEOUT = 5000;
LightSensor::LightSensor(uint8_t sdaPin, uint8_t sclPin) {
Serial.print("\nConnecting to BH1750FVI");
lightSensor = new BH1750FVI(BH1750_DEFAULT_I2CADDR, BH1750_CONTINUOUS_HIGH_RES_MODE_2, BH1750_SENSITIVITY_DEFAULT,
BH1750_ACCURACY_DEFAULT);
unsigned int elapsedTime = 0;
while (!lightSensor->begin(sdaPin, sclPin) && elapsedTime < CONNECTION_TIMEOUT) {
delay(CONNECTION_ATTEMPT_DELAY);
elapsedTime += CONNECTION_ATTEMPT_DELAY;
Serial.print(".");
}
isConnected = elapsedTime < CONNECTION_TIMEOUT;
if (isConnected) {
Serial.println("\nBH1750FVI connected");
} else {
Serial.println("\nUnable to connect to BH1750FVI");
}
}
float LightSensor::measureLightLevel() {
return isConnected ? lightSensor->readLightLevel() : 0.0f;
}
bool LightSensor::isAvailable() {
return isConnected;
}
|
SQL
|
UTF-8
| 562
| 4.125
| 4
|
[] |
no_license
|
-- Write your MySQL query statement below
-- First Solution
SELECT
DISTINCT
A.num ConsecutiveNums
FROM
Logs A
JOIN
Logs B
ON
A.id+1 = B.id
JOIN
Logs C
ON
B.id+1 = C.id
AND
A.num = B.num
AND
B.num = C.num
-- Second Solution
SELECT
DISTINCT
A.num ConsecutiveNums
FROM
Logs A,
Logs B,
Logs C
WHERE
A.id <> B.id and B.id <> C.id
AND
A.num = B.num
AND
B.num = C.num
AND
((A.id+1 = B.id and A.id+2 = C.id)
OR
(A.id-1 = B.id and A.id+1 = C.id)
OR
(A.id-2 = B.id and A.id-1 = C.id))
|
Java
|
UTF-8
| 552
| 2.171875
| 2
|
[] |
no_license
|
package com.dobybros.chat.services;
import com.dobybros.chat.data.Authorization;
public interface AuthorizationService {
/**
* 从登陆服务器保存一个Authorization对象
*
* @param session
*/
public void saveAuthorization(Authorization session);
/**
* 通过authorizationCode验证并消费Authorization对象。
*
* @param userId
* @param authorizationCode
* @return
*/
public Authorization consumeAuthorizationByCode(String userId,
String authorizationCode);
}
|
Java
|
UTF-8
| 3,158
| 2.8125
| 3
|
[] |
no_license
|
package com.project.tutorial.abstractdemo.coffemachine;
public class Maxim extends CoffeeDispensor{
public Maxim() {
super();
}
public void getHotAmericano(){
setMilk(0);
setCoffeeBean(10);
setWater(100);
setTemp(80);
setTeaPowder(0);
setSugar(0);
waterQty = waterQty - 100;
coffeeBeanQty = coffeeBeanQty - 10;
}
public void getHotExpresso(){
setMilk(100);
setCoffeeBean(10);
setWater(100);
setTemp(90);
setTeaPowder(0);
setSugar(30);
waterQty = waterQty - 100;
coffeeBeanQty = coffeeBeanQty - 10;
milkQty = milkQty - 100;
sugarQty = sugarQty - 30;
}
public void getHotTea(){
setMilk(80);
setCoffeeBean(0);
setWater(80);
setTemp(90);
setTeaPowder(20);
setSugar(30);
waterQty = waterQty - 80;
teaQty = teaQty - 20;
sugarQty = sugarQty - 30;
milkQty = milkQty - 80;
}
public void getHotWater(){
setMilk(0);
setCoffeeBean(0);
setWater(80);
setTemp(90);
setTeaPowder(0);
setSugar(0);
waterQty = waterQty - 80;
}
public void getHotMilk(){
setMilk(100);
setCoffeeBean(0);
setWater(0);
setTemp(90);
setTeaPowder(0);
setSugar(0);
milkQty = milkQty - 100;
}
public void getSteam(){
System.out.println("Dispensing Steam from Maxim");
}
public void cleanMachine(){
System.out.println("Cleaned Maxim machine");
}
public void getColdAmericano(){
setMilk(0);
setCoffeeBean(10);
setWater(100);
setTemp(0);
setTeaPowder(0);
setSugar(0);
waterQty = waterQty - 100;
coffeeBeanQty = coffeeBeanQty - 10;
}
public void getColdExpresso(){
setMilk(100);
setCoffeeBean(10);
setWater(100);
setTemp(0);
setTeaPowder(0);
setSugar(30);
waterQty = waterQty - 100;
coffeeBeanQty = coffeeBeanQty - 10;
milkQty = milkQty - 100;
sugarQty = sugarQty - 30;
}
public void getColdTea(){
setMilk(100);
setCoffeeBean(0);
setWater(100);
setTemp(0);
setTeaPowder(30);
setSugar(60);
waterQty = waterQty - 100;
teaQty = teaQty - 30;
milkQty = milkQty - 100;
sugarQty = sugarQty - 60;
}
public void getColdWater(){
setMilk(0);
setCoffeeBean(0);
setWater(100);
setTemp(0);
setTeaPowder(0);
setSugar(0);
waterQty = waterQty -100;
}
public void getColdMilk(){
setMilk(100);
setCoffeeBean(0);
setWater(0);
setTemp(0);
setTeaPowder(0);
setSugar(0);
milkQty = milkQty - 100;
}
}
|
Shell
|
UTF-8
| 2,361
| 3.59375
| 4
|
[] |
no_license
|
#!/bin/bash
echo -e "\033[1;94m🔧 Setting up MacPorts"
curl -LO https://raw.githubusercontent.com/GiovanniBussi/macports-ci/master/macports-ci
source ./macports-ci install
echo -e "\033[1;94m⬇️ Installing GitHub CLI"
sudo port install gh
echo -e "\033[1;94m😀 Authenticating GitHub CLI"
echo $TOKEN >> token.txt
gh auth login --with-token < token.txt
gh auth status
echo -e "\033[1;94m🔍 Determining current outdated version"
CURRENT=$(port info --version $NAME | sed 's/[A-Za-z: ]*//g') # Remove letters, colon and space
echo "Current version number is $CURRENT!"
echo -e "\033[1;94m🏷️ Determining new version from tag"
# We want to keep the dots, but remove all letters
TAG=$(echo $TAG | sed 's/[A-Za-z]*//g')
echo "New version number is $TAG!"
echo -e "\033[1;94m📒 Determining Category"
CATEGORY=$(port info --category $NAME)
CATEGORY_LIST=($CATEGORY)
CATEGORY=${CATEGORY_LIST[1]} # Only take the first category
CATEGORY=$(echo "$CATEGORY" | tr "," "\n") # Replace commas with line breaks
echo "Category is $CATEGORY!"
echo -e "\033[1;94m⬇️ Cloning MacPorts Repo"
gh repo fork $REPO --clone=true --remote=true
# Name of the cloned folder
CLONE=$(echo $REPO | awk -F'/' '{print $2}')
echo -e "\033[1;94m📁 Creating local Portfile Repo"
mkdir -p ports/$CATEGORY/$NAME
# Copy Portfile to the local repo
cp $CLONE/$CATEGORY/$NAME/Portfile ports/$CATEGORY/$NAME/Portfile
source macports-ci localports ports
echo -e "\033[1;94m⏫ Bumping Version"
# Replaces first instance of old version with new version
sed -i '' "1,/$CURRENT/ s/$CURRENT/$TAG/" ports/$CATEGORY/$NAME/Portfile
sudo port bump $NAME
echo -e "\033[1;94m📨 Sending PR"
# Finds public emails and takes the first one
EMAIL=$(gh api /user/public_emails | jq --raw-output '.[0] | .email')
# Git credentials
# echo "https://$USER:$TOKEN@github.com" > ~/.git-credentials
git config user.email $EMAIL
git config user.name $USER
git config user.password $TOKEN
cd $CLONE
git checkout -b $NAME
# Copy changes back to main repo
cp ../ports/$CATEGORY/$NAME/Portfile $CATEGORY/$NAME/Portfile
git add $CATEGORY/$NAME/Portfile
git commit -m "$NAME: update to $TAG"
# git push --set-upstream origin $NAME
gh pr create --title "$NAME: update to $TAG" --body "Created with [`action-macports-bump`](https://github.com/harens/action-macports-bump)" --base=master --head=$NAME
|
Java
|
UTF-8
| 4,623
| 1.59375
| 2
|
[] |
no_license
|
package com.tencent.mm.plugin.sns.ui;
import android.annotation.TargetApi;
import android.content.Context;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView.BufferType;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.plugin.sns.ui.item.BaseTimeLineItem.BaseViewHolder;
import com.tencent.mm.pluginsdk.ui.e.j;
import com.tencent.mm.sdk.platformtools.bo;
public class AsyncNormalTextView extends CollapsibleTextView {
private String content;
private Context context;
private au qPr;
private BaseViewHolder rgW;
private int rgX = 0;
public AsyncNormalTextView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.context = context;
}
public final void a(String str, au auVar, int i, av avVar) {
AppMethodBeat.i(38136);
this.rgX = i;
this.content = str;
this.qPr = auVar;
this.rhX = avVar;
if (bo.isNullOrNil(str)) {
setVisibility(8);
}
AppMethodBeat.o(38136);
}
public void setShow(BaseViewHolder baseViewHolder) {
AppMethodBeat.i(38137);
this.rgW = baseViewHolder;
crz();
AppMethodBeat.o(38137);
}
public final void crz() {
AppMethodBeat.i(38138);
if (!bo.isNullOrNil(this.content)) {
System.currentTimeMillis();
setVisibility(0);
if (this.rgX == 1) {
this.content = this.content.length() > 100 ? this.content.substring(0, 100) + "..." : this.content;
a(this.rgX, new SpannableStringBuilder(j.b(this.context, this.content, this.rhR.getTextSize())), BufferType.NORMAL, this.qPr.rhW, this.rhX.riA, this.rhX.rAs, this.qPr, this.content, this.rhX.rgZ);
} else if (this.content.length() < 400 || this.rhX.rgZ) {
CharSequence charSequence = null;
if (this.rhX != null) {
charSequence = this.rhX.rAq;
}
if (charSequence == null) {
charSequence = new SpannableStringBuilder(j.b(this.context, this.content, this.rhR.getTextSize()));
}
if (this.rhX != null) {
a(this.rgX, charSequence, BufferType.SPANNABLE, this.qPr.rhW, this.rhX.riA, this.rhX.rAs, this.qPr, this.content, this.rhX.rgZ);
}
} else {
a(this.rgX, this.content, BufferType.NORMAL, this.qPr.rhW, this.rhX.riA, this.rhX.rAs, this.qPr, this.content, this.rhX.rgZ);
}
ar arVar = new ar(this.rhX.rAs, this.rhX.riA, false, false, 1);
arVar.userName = this.rhX.igi;
this.rhR.setTag(arVar);
if (this.rhS != null) {
this.rhS.setTag(arVar);
}
this.rhT.setTag(this.rgW);
}
AppMethodBeat.o(38138);
}
/* Access modifiers changed, original: protected */
public void onLayout(boolean z, int i, int i2, int i3, int i4) {
AppMethodBeat.i(38139);
super.onLayout(z, i, i2, i3, i4);
AppMethodBeat.o(38139);
}
/* Access modifiers changed, original: protected */
public void onMeasure(int i, int i2) {
AppMethodBeat.i(38140);
super.onMeasure(i, i2);
AppMethodBeat.o(38140);
}
public void onPopulateAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
AppMethodBeat.i(38141);
super.onPopulateAccessibilityEvent(accessibilityEvent);
accessibilityEvent.getText().add(this.content);
AppMethodBeat.o(38141);
}
@TargetApi(14)
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo accessibilityNodeInfo) {
AppMethodBeat.i(38142);
super.onInitializeAccessibilityNodeInfo(accessibilityNodeInfo);
accessibilityNodeInfo.setText(this.content);
AppMethodBeat.o(38142);
}
public String getContent() {
return this.content;
}
public void setContentWidth(int i) {
AppMethodBeat.i(38143);
if (this.rhS != null) {
this.rhR.setSpecialWidth(i);
LayoutParams layoutParams = new LayoutParams(i, -2);
this.rhS.setLayoutParams(layoutParams);
this.rhR.setLayoutParams(layoutParams);
this.rhT.setLayoutParams(layoutParams);
}
AppMethodBeat.o(38143);
}
}
|
Java
|
UTF-8
| 1,637
| 1.921875
| 2
|
[] |
no_license
|
/*
* Copyright (c)
* 2019. THE BODY SHOP INTERNATIONAL LIMITED.
* All rights reserved.
*/
package uk.co.thebodyshop.core.search.solrfacetsearch.provider.impl;
import java.util.Objects;
import de.hybris.platform.core.model.product.ProductModel;
import de.hybris.platform.solrfacetsearch.config.IndexedProperty;
import de.hybris.platform.solrfacetsearch.config.exceptions.FieldValueProviderException;
import de.hybris.platform.solrfacetsearch.indexer.IndexerBatchContext;
import de.hybris.platform.solrfacetsearch.indexer.spi.InputDocument;
import de.hybris.platform.solrfacetsearch.provider.impl.AbstractValueResolver;
import uk.co.thebodyshop.core.enums.TbsBaseType;
import uk.co.thebodyshop.core.model.TbsBaseProductModel;
import uk.co.thebodyshop.core.model.TbsVariantProductModel;
/**
* @author Jagadeesh
*/
public class ProductColourValueResolver extends AbstractValueResolver<ProductModel, Object, Object>
{
@Override
protected void addFieldValues(final InputDocument inputDocument, final IndexerBatchContext indexerBatchContext, final IndexedProperty indexedProperty, final ProductModel productModel, final ValueResolverContext<Object, Object> valueResolverContext)
throws FieldValueProviderException
{
if (productModel instanceof TbsVariantProductModel)
{
final TbsVariantProductModel tbsVariantProduct = (TbsVariantProductModel) productModel;
if (TbsBaseType.COLOUR.equals(((TbsBaseProductModel)tbsVariantProduct.getBaseProduct()).getType()) && Objects.nonNull(tbsVariantProduct.getColour()))
{
inputDocument.addField(indexedProperty, tbsVariantProduct.getColour().getHexCode());
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.