language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
C# | UTF-8 | 820 | 2.609375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Computer_Era.Game.Objects
{
public class OperatingSystemProperties
{
public string Description { get; set; }
public string Author { get; set; }
public int[] Programms { get; set; }
public int Size { get; set; } //В килобайтах
public Collection<FileSystem> FileSystems { get; set; } = new Collection<FileSystem>();
}
public class OperatingSystem : Item<OperatingSystemProperties>
{
public OperatingSystem(int uid, string name, string type, int price, DateTime man_date, OperatingSystemProperties properties) : base(uid, name, type, price, man_date, properties) { }
}
}
|
Python | UTF-8 | 3,091 | 2.609375 | 3 | [] | no_license | import os
import os, sys
from shutil import rmtree
from os import makedirs
from os import remove
import shutil
# intérprete para operaciones de entrada y salida basadas en archivos
from io import open
# Hostname
import socket
# Json
import json
# Date Time
import time
from datetime import date
from datetime import datetime, timedelta
import datetime
# DB
import pymysql
# GUID
import uuid
def AnalysisLogError (TestID, GuidTest, CountTest, Hostname, Version):
print ("********************************************")
print ("******************************************************")
print (" Inicio de Analisis del Log (Error)")
print ("******************************************************")
print ("********************************************")
# Verificar la cantidad de archivos Log que se generaron
from Setting import PathLogs
print ("Ruta Folder: ", PathLogs)
# variable dirs contiene la lista de archivos generados
dirs = os.listdir(PathLogs)
# variable (i) define el nuemro de identificaciones detectadas (item)
LineaLog = 0
print (dirs)
print (LineaLog)
# segun la cantidad de archivos generados (dirs) se recorre uno a uno
for file in dirs:
# Creamos la ruta y el archivo que vamos a trabajar
PathFileLog = PathLogs + file
print("File open")
print ("/////////////////////////////////////////////////////////////////////////////////////////////////////////////")
print ("/////////////////////////////////////////////////////////////////////////////////////////////////////////////")
print ("File: ",PathFileLog)
print ("/////////////////////////////////////////////////////////////////////////////////////////////////////////////")
print ("/////////////////////////////////////////////////////////////////////////////////////////////////////////////")
# La aplicaicon lee y guarada en la variable "archivo_texto" toda la informacion
archivo_texto=open (PathFileLog, "r")
# Se lee Linea por linea
lineas_texto=archivo_texto.readlines()
#///////////////////////////////////////////
# Por cada linea del archivo log, buscamos el parametro
#///////////////////////////////////////////
from Setting import ParametroBusqueda
LineaLog = 0
TotalError = 0
for ClientLine in lineas_texto:
Timeline = ""
LineaLog +=1
InfoLogerror = ""
# Get parametro de busqueda para los Erorres en log file
parametro = ParametroBusqueda[2]
# Call funcion BusquedaEdgeiden analizar linea por linea
if parametro in ClientLine:
Timeline = ClientLine[0:19]
InfoLogerror = ClientLine
TotalError += 1
from AddLogError import AddLogError
AddLogError (TestID, GuidTest, CountTest, Hostname, Version, file, Timeline, LineaLog, InfoLogerror)
return TotalError
|
PHP | UTF-8 | 213 | 2.578125 | 3 | [] | no_license | <?php
function generateCookie($user,$password,$checkbox){
if($checkbox == true)
{
setcookie("cuser",$user,time()+60*60*24*30);
setcookie("cpass",$password,time()+60*60*24*30);
}
}
?> |
Shell | UTF-8 | 238 | 2.703125 | 3 | [] | no_license | #!/bin/bash
# Set Flatfish's home path here
FLATFISH_PATH="$HOME/workspace/flatfish"
# Don't change these unless you know what you are doing
USER="$(id -nu)"
UUID="$(id -u)"
UGID="$(id -g)"
export FLATFISH_PATH
export UUID
export UGID
|
C++ | UTF-8 | 348 | 2.8125 | 3 | [] | no_license | #include<bits/stdc++.h>
#define lld long long int
using namespace std;
int mobius(int n){
int p= 0;
if(n%2==0){
n = n/2;p++;
if(n%2==0)return 0;
}
for(int i=3;i<=sqrt(n);i+=2){
if(n%i==0){
n=n/i;p++;
if(n%i==0)return 0;
}
}
return (p%2==0)?-1:1;
}
int main(){
cout<<mobius(17)<<" "<<mobius(25)<<endl;
}
|
C# | UTF-8 | 7,422 | 2.78125 | 3 | [
"MIT"
] | permissive | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Xunit;
namespace System.Numerics.Matrices.Tests
{
/// <summary>
/// Tests for the Matrix1x3 structure.
/// </summary>
public class Test1x3
{
const int Epsilon = 10;
[Fact]
public void ConstructorValuesAreAccessibleByIndexer()
{
Matrix1x3 matrix1x3;
matrix1x3 = new Matrix1x3();
for (int x = 0; x < matrix1x3.Columns; x++)
{
for (int y = 0; y < matrix1x3.Rows; y++)
{
Assert.Equal(0, matrix1x3[x, y], Epsilon);
}
}
double value = 33.33;
matrix1x3 = new Matrix1x3(value);
for (int x = 0; x < matrix1x3.Columns; x++)
{
for (int y = 0; y < matrix1x3.Rows; y++)
{
Assert.Equal(value, matrix1x3[x, y], Epsilon);
}
}
GenerateFilledMatrixWithValues(out matrix1x3);
for (int y = 0; y < matrix1x3.Rows; y++)
{
for (int x = 0; x < matrix1x3.Columns; x++)
{
Assert.Equal(y * matrix1x3.Columns + x, matrix1x3[x, y], Epsilon);
}
}
}
[Fact]
public void IndexerGetAndSetValuesCorrectly()
{
Matrix1x3 matrix1x3 = new Matrix1x3();
for (int x = 0; x < matrix1x3.Columns; x++)
{
for (int y = 0; y < matrix1x3.Rows; y++)
{
matrix1x3[x, y] = y * matrix1x3.Columns + x;
}
}
for (int y = 0; y < matrix1x3.Rows; y++)
{
for (int x = 0; x < matrix1x3.Columns; x++)
{
Assert.Equal(y * matrix1x3.Columns + x, matrix1x3[x, y], Epsilon);
}
}
}
[Fact]
public void ConstantValuesAreCorrect()
{
Matrix1x3 matrix1x3 = new Matrix1x3();
Assert.Equal(1, matrix1x3.Columns);
Assert.Equal(3, matrix1x3.Rows);
Assert.Equal(Matrix1x3.ColumnCount, matrix1x3.Columns);
Assert.Equal(Matrix1x3.RowCount, matrix1x3.Rows);
}
[Fact]
public void ScalarMultiplicationIsCorrect()
{
GenerateFilledMatrixWithValues(out Matrix1x3 matrix1x3);
for (double c = -10; c <= 10; c += 0.5)
{
Matrix1x3 result = matrix1x3 * c;
for (int y = 0; y < matrix1x3.Rows; y++)
{
for (int x = 0; x < matrix1x3.Columns; x++)
{
Assert.Equal(matrix1x3[x, y] * c, result[x, y], Epsilon);
}
}
}
}
[Fact]
public void MemberGetAndSetValuesCorrectly()
{
Matrix1x3 matrix1x3 = new Matrix1x3();
matrix1x3.M11 = 0;
matrix1x3.M12 = 1;
matrix1x3.M13 = 2;
Assert.Equal(0, matrix1x3.M11, Epsilon);
Assert.Equal(1, matrix1x3.M12, Epsilon);
Assert.Equal(2, matrix1x3.M13, Epsilon);
Assert.Equal(matrix1x3[0, 0], matrix1x3.M11, Epsilon);
Assert.Equal(matrix1x3[0, 1], matrix1x3.M12, Epsilon);
Assert.Equal(matrix1x3[0, 2], matrix1x3.M13, Epsilon);
}
[Fact]
public void HashCodeGenerationWorksCorrectly()
{
HashSet<int> hashCodes = new HashSet<int>();
Matrix1x3 value = new Matrix1x3(1);
for (int i = 2; i <= 100; i++)
{
Assert.True(hashCodes.Add(value.GetHashCode()), "Unique hash code generation failure.");
value *= i;
}
}
[Fact]
public void SimpleAdditionGeneratesCorrectValues()
{
Matrix1x3 value1 = new Matrix1x3(1);
Matrix1x3 value2 = new Matrix1x3(99);
Matrix1x3 result = value1 + value2;
for (int y = 0; y < Matrix1x3.RowCount; y++)
{
for (int x = 0; x < Matrix1x3.ColumnCount; x++)
{
Assert.Equal(1 + 99, result[x, y], Epsilon);
}
}
}
[Fact]
public void SimpleSubtractionGeneratesCorrectValues()
{
Matrix1x3 value1 = new Matrix1x3(100);
Matrix1x3 value2 = new Matrix1x3(1);
Matrix1x3 result = value1 - value2;
for (int y = 0; y < Matrix1x3.RowCount; y++)
{
for (int x = 0; x < Matrix1x3.ColumnCount; x++)
{
Assert.Equal(100 - 1, result[x, y], Epsilon);
}
}
}
[Fact]
public void EqualityOperatorWorksCorrectly()
{
Matrix1x3 value1 = new Matrix1x3(100);
Matrix1x3 value2 = new Matrix1x3(50) * 2;
Assert.Equal(value1, value2);
Assert.True(value1 == value2, "Equality operator failed.");
}
[Fact]
public void AccessorThrowsWhenOutOfBounds()
{
Matrix1x3 matrix1x3 = new Matrix1x3();
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix1x3[-1, 0] = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix1x3[0, -1] = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix1x3[1, 0] = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix1x3[0, 3] = 0; });
}
[Fact]
public void MuliplyByMatrix2x1ProducesMatrix2x3()
{
Matrix1x3 matrix1 = new Matrix1x3(3);
Matrix2x1 matrix2 = new Matrix2x1(2);
Matrix2x3 result = matrix1 * matrix2;
Matrix2x3 expected = new Matrix2x3(6, 6,
6, 6,
6, 6);
Assert.Equal(expected, result);
}
[Fact]
public void MuliplyByMatrix3x1ProducesMatrix3x3()
{
Matrix1x3 matrix1 = new Matrix1x3(3);
Matrix3x1 matrix2 = new Matrix3x1(2);
Matrix3x3 result = matrix1 * matrix2;
Matrix3x3 expected = new Matrix3x3(6, 6, 6,
6, 6, 6,
6, 6, 6);
Assert.Equal(expected, result);
}
[Fact]
public void MuliplyByMatrix4x1ProducesMatrix4x3()
{
Matrix1x3 matrix1 = new Matrix1x3(3);
Matrix4x1 matrix2 = new Matrix4x1(2);
Matrix4x3 result = matrix1 * matrix2;
Matrix4x3 expected = new Matrix4x3(6, 6, 6, 6,
6, 6, 6, 6,
6, 6, 6, 6);
Assert.Equal(expected, result);
}
private void GenerateFilledMatrixWithValues(out Matrix1x3 matrix)
{
matrix = new Matrix1x3(0,
1,
2);
}
}
}
|
Java | UTF-8 | 853 | 3.578125 | 4 | [] | no_license | package com.cei37.arrays_strings;
import java.util.HashMap;
import java.util.Map;
public class ReplaceString {
/**
*
*/
public static void main(String[] args) {
String original = "This is a String to test some options that I saw before.";
String remove = "aeiou";
System.out.println(removeCharacters(original,remove));
}
public static String removeCharacters(String str, String remove) {
StringBuffer sb = new StringBuffer();
HashMap<Character,Boolean> hash = new HashMap<Character, Boolean>();
for (int i=0; i<str.length(); i++) {
hash.put(str.charAt(i), false);
}
for (int i=0; i<remove.length(); i++) {
hash.put(remove.charAt(i), true);
}
for (int i=0; i<str.length(); i++) {
if (!hash.get(str.charAt(i))) {
sb.append(str.charAt(i));
}
}
return sb.toString();
}
} |
C++ | UTF-8 | 21,167 | 2.703125 | 3 | [] | no_license | //
// Created by jhwangbo on 07/09/17.
//
#ifndef BENCHMARK_MATH_HPP
#define BENCHMARK_MATH_HPP
#include <Eigen/Core>
#include <vector>
#include <memory>
#include <numeric>
#include "math.h"
#include <iostream>
#include <stdlib.h>
#include "float.h"
#include "raiCommon/rai_utils.hpp"
#include "immintrin.h"
namespace benchmark {
class VecDyn;
class MatDyn;
class DynamicArray{
public:
friend class benchmark::VecDyn;
friend class benchmark::MatDyn;
double *v = nullptr;
double* ptr() {return v;}
const double* ptr() const {return v;}
private:
void allocate(int size) {
free(v);
v = static_cast<double*>(aligned_alloc(32, size*sizeof(double)));
}
};
template<int n>
class Vec {
public:
union {
double v[n];
std::aligned_storage<n, 32> alignment_only;
};
typedef Eigen::Map<Eigen::Matrix<double, n, 1> > EigenVecn;
EigenVecn e() {
return EigenVecn(v, n, 1);
}
inline void operator/=(double val) {
for (int i = 0; i < n; i++)
v[i] /= val;
}
inline void operator*=(double val) {
for (int i = 0; i < n; i++)
v[i] *= val;
}
inline void setZero() {
memset(ptr(), 0, n* sizeof(double));
}
inline double norm() {
double sum=0.0;
for (int i = 0; i < n; i++)
sum += v[i]*v[i];
return sqrt(sum);
}
inline double squaredNorm() {
double sum=0.0;
for (int i = 0; i < n; i++)
sum += v[i]*v[i];
return sum;
}
double operator [](int i) const {return v[i];}
double & operator [](int i) {return v[i];}
double* ptr() {return &(v[0]);}
const double* ptr() const {return &(v[0]);}
inline Vec<n>& operator=(const DynamicArray &rhs) {
memcpy(ptr(), rhs.ptr(), n * sizeof(double));
return *this;
}
inline void operator-=(const Vec<n> &rhs) {
for (int i = 0; i < n; i++)
v[i] -= rhs[i];
}
inline void operator+=(const Vec<n> &rhs) {
for (int i = 0; i < n; i++)
v[i] += rhs[i];
}
inline Vec<n>& operator=(const Vec<n> &rhs) {
memcpy(ptr(), rhs.ptr(), n * sizeof(double));
return *this;
}
template<int rows, int cols>
inline Vec<n>& operator=(const Eigen::Matrix<double, rows, cols> &rhs) {
memcpy(ptr(), rhs.data(), n * sizeof(double));
return *this;
}
};
template<int n, int m>
class Mat {
public:
union {
double v[n * m];
std::aligned_storage<n * m, 32> alignment_only;
};
Mat() {};
double operator [](int i) const {return v[i];}
double & operator [](int i) {return v[i];}
double* ptr() {return &(v[0]);}
const double* ptr() const {return &(v[0]);}
Eigen::Map<Eigen::Matrix<double, n, m> > e() {
return Eigen::Map<Eigen::Matrix<double, n, m> >(v, n, m);
}
template<int j, int k>
void fillSub(int startRow, int startColumn, Mat<j, k> &in) {
for (int i = 0; i < j; i++) /// column index
for (int o = 0; o < k; o++) /// row index
v[n * (startColumn + i) + (o + startRow)] = in[i * j + o];
}
void fillSub(int startRow, int startColumn, Mat<3, 3> &in) {
for (int i = 0; i < 3; i++) /// column index
for (int o = 0; o < 3; o++) /// row index
v[n * (startColumn + i) + (o + startRow)] = in[i * 3 + o];
}
void setIdentity() {
static_assert(n == m, "setIdentity: the matrix must be a square matrix");
memset(ptr(), 0, n * n * sizeof(double));
for (int i = 0; i < n; i++)
v[i * n + i] = 1.0;
}
inline void setZero() {
memset(ptr(), 0, n*m* sizeof(double));
}
inline double sum() const {
double sum = 0;
for(int i=0; i< n; i++)
for(int j=0; j<m; j++)
sum += v[i+j*n];
return sum;
}
inline Mat<n,m>& operator=(const Mat<n,m> &rhs) {
memcpy(ptr(), rhs.ptr(), n*m * sizeof(double));
return *this;
}
inline void operator*=(const double val) {
for(int i=0; i< n; i++)
for(int j=0; j<m; j++)
v[i+j*n] *= val;
}
template<int rows, int cols>
inline Mat<n,m>& operator=(const Eigen::Matrix<double, rows, cols> &rhs) {
memcpy(ptr(), rhs.data(), n *m* sizeof(double));
return *this;
}
inline Mat<n,m>& operator=(const DynamicArray &rhs) {
memcpy(ptr(), rhs.ptr(), n * m * sizeof(double));
return *this;
}
};
class VecDyn: public DynamicArray {
public:
int n;
typedef Eigen::Map<Eigen::Matrix<double, -1, 1> > EigenVecn;
VecDyn(){}
VecDyn(int size){
resize(size);
}
VecDyn(const VecDyn& vec){
resize(vec.n);
memcpy(ptr(), vec.ptr(), n* sizeof(double));
}
double operator [](int i) const {return v[i];}
double & operator [](int i) {return v[i];}
~VecDyn(){
free(v);
}
inline double sum() const {
double sum = 0;
for(int i=0; i< n; i++)
sum += v[i];
return sum;
}
void resize(int size) {
n = size;
allocate(size);
}
inline double squaredNorm() {
double sum=0.0;
for (int i = 0; i < n; i++)
sum += v[i]*v[i];
return sum;
}
inline double norm() {
double sum=0.0;
for (int i = 0; i < n; i++)
sum += v[i]*v[i];
return sqrt(sum);
}
EigenVecn e() {
return EigenVecn(v, n, 1);
}
inline void operator/=(double val) {
for (int i = 0; i < n; i++)
v[i] /= val;
}
inline void operator*=(double val) {
for (int i = 0; i < n; i++)
v[i] *= val;
}
inline VecDyn& operator=(const VecDyn &rhs) {
memcpy(ptr(), rhs.ptr(), n * sizeof(double));
return *this;
}
template<int rows, int cols>
inline VecDyn& operator=(const Eigen::Matrix<double, rows, cols> &rhs) {
memcpy(ptr(), rhs.data(), n * sizeof(double));
return *this;
}
template<int size>
inline VecDyn& operator=(const Vec<size> &rhs) {
memcpy(ptr(), rhs.ptr(), n * sizeof(double));
return *this;
}
inline void setZero() {
memset(ptr(), 0, n* sizeof(double));
}
inline void setZero(int n) {
resize(n);
memset(ptr(), 0, n* sizeof(double));
}
};
class MatDyn: public DynamicArray {
public:
int n, m;
MatDyn(){}
MatDyn(int rows, int cols){
resize(rows, cols);
}
MatDyn(const MatDyn& vec){
resize(vec.n, vec.m);
memcpy(ptr(), vec.ptr(), n*m* sizeof(double));
}
~MatDyn() {
free(v);
}
Eigen::Map<Eigen::Matrix<double, -1, -1> > e() {
return Eigen::Map<Eigen::Matrix<double, -1, -1> >(v, n, m);
}
double operator [](int i) const {return v[i];}
double & operator [](int i) {return v[i];}
void resize(int rows, int cols) {
n = rows;
m = cols;
allocate(rows * cols);
}
template<int j, int k>
void fillSub(int startRow, int startColumn, Mat<j, k> &in) {
for (int i = 0; i < j; i++) /// column index
for (int o = 0; o < k; o++) /// row index
v[n * (startColumn + i) + (o + startRow)] = in[i * j + o];
}
void fillSub(int startRow, int startColumn, Mat<3, 3> &in) {
for (int i = 0; i < 3; i++) /// column index
for (int o = 0; o < 3; o++) /// row index
v[n * (startColumn + i) + (o + startRow)] = in[i * 3 + o];
}
void setIdentity() {
memset(ptr(), 0, n * n * sizeof(double));
for (int i = 0; i < n; i++)
v[i * n + i] = 1.0;
}
inline void setZero() {
memset(v, 0, n*m* sizeof(double));
}
inline void setZero(int rows, int cols) {
resize(rows,cols);
memset(ptr(), 0, n*m* sizeof(double));
}
template<int rows, int cols>
inline MatDyn& operator=(const Mat<rows,cols> &rhs) {
memcpy(ptr(), rhs.ptr(), n*m * sizeof(double));
return *this;
}
template<int rows, int cols>
inline MatDyn& operator=(const Eigen::Matrix<double, rows, cols> &rhs) {
memcpy(ptr(), rhs.data(), n *m* sizeof(double));
return *this;
}
inline MatDyn& operator=(const MatDyn &rhs) {
memcpy(ptr(), rhs.ptr(), n * m * sizeof(double));
return *this;
}
};
struct Transformation {
Mat<3,3> rot;
Vec<3> pos;
};
inline void quatToRotMat(const Vec<4> &q, Mat<3, 3> &R) {
R[0] = q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3];
R[1] = 2 * q[0] * q[3] + 2 * q[1] * q[2];
R[2] = 2 * q[1] * q[3] - 2 * q[0] * q[2];
R[3] = 2 * q[1] * q[2] - 2 * q[0] * q[3];
R[4] = q[0] * q[0] - q[1] * q[1] + q[2] * q[2] - q[3] * q[3];
R[5] = 2 * q[0] * q[1] + 2 * q[2] * q[3];
R[6] = 2 * q[0] * q[2] + 2 * q[1] * q[3];
R[7] = 2 * q[2] * q[3] - 2 * q[0] * q[1];
R[8] = q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3];
}
inline void rotMatToQuat(const Mat<3, 3> &R, Vec<4> &q) {
double tr = R[0] + R[4] + R[8];
if (tr > 0.0) {
double S = sqrt(tr + 1.0) * 2.0; // S=4*qw
q[0] = 0.25 * S;
q[1] = (R[5] - R[7]) / S;
q[2] = (R[6] - R[2]) / S;
q[3] = (R[1] - R[3]) / S;
} else if ((R[0] > R[4]) & (R[0] > R[8])) {
double S = sqrt(1.0 + R[0] - R[4] - R[8]) * 2.0; // S=4*qx
q[0] = (R[5] - R[7]) / S;
q[1] = 0.25 * S;
q[2] = (R[3] + R[1]) / S;
q[3] = (R[6] + R[2]) / S;
} else if (R[4] > R[8]) {
double S = sqrt(1.0 + R[4] - R[0] - R[8]) * 2.0; // S=4*qy
q[0] = (R[6] - R[2]) / S;
q[1] = (R[3] + R[1]) / S;
q[2] = 0.25 * S;
q[3] = (R[7] + R[5]) / S;
} else {
double S = sqrt(1.0 + R[8] - R[0] - R[4]) * 2.0; // S=4*qz
q[0] = (R[1] - R[3]) / S;
q[1] = (R[6] + R[2]) / S;
q[2] = (R[7] + R[5]) / S;
q[3] = 0.25 * S;
}
}
template<int n, int m, int l>
inline void matmul(const Mat<n, m> &mat1, const Mat<m, l> &mat2, Mat<n, l> &mat) {
for (int j = 0; j < 3; j++) // col
for (int k = 0; k < 3; k++) // row
mat[j * 3 + k] =
mat1[k] * mat2[j * 3] + mat1[k + 3] * mat2[j * 3 + 1] + mat1[k + 6] * mat2[j * 3 + 2];
}
/// first matrix is transposed
template<int n, int m, int l>
inline void transposedMatMul(const Mat<m, n> &mat1, const Mat<m, l> &mat2, Mat<n, l> &mat) {
for (int j = 0; j < 3; j++) // col
for (int k = 0; k < 3; k++) // row
mat[j * 3 + k] =
mat1[k * 3] * mat2[j * 3] + mat1[k * 3 + 1] * mat2[j * 3 + 1] + mat1[k * 3 + 2] * mat2[j * 3 + 2];
}
/// second matrix is transposed
template<int n, int m, int l>
inline void transposed2MatMul(const Mat<n, m> &mat1, const Mat<l, m> &mat2, Mat<n, l> &mat) {
for (int j = 0; j < 3; j++) // col
for (int k = 0; k < 3; k++) // row
mat[j * 3 + k] =
mat1[k] * mat2[j] + mat1[k + 3 * 1] * mat2[j + 3 * 1] + mat1[k + 3 * 2] * mat2[j + 3 * 2];
}
template<int n, int l>
inline void matScalarMul(double scalar, Mat<n, l> &mat) {
for (int j = 0; j < n*l; j++)
mat[j] *= scalar;
};
template<int n, int m>
inline void transpose(const Mat<n, m> &mat1, Mat<m, n> &mat) {
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
mat[j + i * m] = mat1[i + j * n];
}
template<int n, int m>
inline void matvecmul(const Mat<n, m> &mat1, const Vec<m> &vec1, Vec<n> &vec) {
for (int j = 0; j < n; j++) {
vec[j] = 0;
for (int i = 0; i < m; i++) // col
vec[j] += mat1[i * n + j] * vec1[i];
}
}
template<int n, int m>
inline void matTransposevecmul(const Mat<n, m> &mat1, const Vec<m> &vec1, Vec<n> &vec) {
for (int j = 0; j < n; j++) {
vec[j] = 0;
for (int i = 0; i < m; i++) // col
vec[j] += mat1[i + j* n] * vec1[i];
}
}
inline void matvecmul(const MatDyn &mat1, const VecDyn &vec1, VecDyn &vec) {
for (int j = 0; j < mat1.n; j++) {
vec[j] = 0;
for (int i = 0; i < mat1.m; i++) // col
vec[j] += mat1[i * mat1.n + j] * vec1[i];
}
}
inline void matvecmul(const Mat<3, 3> &mat1, const Vec<3> &vec1, double *vec) {
for (int j = 0; j < 3; j++) // col
vec[j] = mat1[j] * vec1[0] + mat1[j + 3] * vec1[1] + mat1[j + 6] * vec1[2];
}
inline void matvecmulThenAdd(const Mat<3,3> &mat1, const Vec<3> &vec1, Vec<3> &vec) {
for (int j = 0; j < 3; j++) // col
vec[j] += mat1[j] * vec1[0] + mat1[j + 3] * vec1[1] + mat1[j + 6] * vec1[2];
}
template<int size>
inline void vecsub(const Vec<size> &vec1, const Vec<size> &vec2, Vec<size> &vec) {
for (int j = 0; j < size; j++) // col
vec[j] = vec1[j] - vec2[j];
}
inline void vecsub(const VecDyn &vec1, const VecDyn &vec2, VecDyn &vec) {
for (int j = 0; j < vec1.n; j++) // col
vec[j] = vec1[j] - vec2[j];
}
inline void vecadd(const VecDyn &vec1, const VecDyn &vec2, VecDyn &vec) {
for (int j = 0; j < vec1.n; j++) // col
vec[j] = vec1[j] + vec2[j];
}
template<int size>
inline void vecsub(const Vec<size> &vec1, Vec<size> &vec) {
for (int j = 0; j < size; j++) // col
vec[j] -= vec1[j];
}
template<int n, int m>
inline void matadd(const Mat<n, m> &mat1, Mat<n, m> &mat) {
for (int i = 0; i < n; i++) // col
for (int j = 0; j < m; j++) // col
mat[i + n * j] += mat1[i + n * j];
}
inline void matadd(const MatDyn &mat1, MatDyn &mat) {
for (int i = 0; i < mat1.n; i++) // col
for (int j = 0; j < mat1.m; j++) // col
mat[i + mat1.n * j] += mat1[i + mat1.n * j];
}
template<int n, int m>
inline void matadd(const Mat<n, m> &mat1, const Mat<n, m> &mat2, Mat<n, m> &mat) {
for (int i = 0; i < n; i++) // col
for (int j = 0; j < m; j++) // col
mat[i + n * j] = mat1[i + n * j] + mat2[i + n * j];
}
template<int n, int m>
inline void matsub(const Mat<n, m> &mat1, Mat<n, m> &mat) {
for (int i = 0; i < n; i++) // col
for (int j = 0; j < m; j++) // col
mat[i + n * j] -= mat1[i + n * j];
}
template<int n, int m>
inline void matsub(const Mat<n, m> &mat1, const Mat<n, m> &mat2, Mat<n, m> &mat) {
for (int i = 0; i < n; i++) // col
for (int j = 0; j < m; j++) // col
mat[i + n * j] = mat1[i + n * j] - mat2[i + n * j];
}
template<int n>
inline void mataddIdentity(Mat<n, n> &mat) {
for (int i = 0; i < n; i++)
mat[i + n * i] += 1;
}
template<int size>
inline void vecadd(const Vec<size> &vec1, Vec<size> &vec) {
for (int j = 0; j < size; j++) // col
vec[j] += vec1[j];
}
inline void vecadd(const VecDyn &vec1, VecDyn &vec) {
for (int j = 0; j < vec1.n; j++) // col
vec[j] += vec1[j];
}
template<int size>
inline void vecadd(const Vec<size> &vec1, const Vec<size> &vec2, Vec<size> &vec) {
for (int j = 0; j < size; j++) // col
vec[j] = vec1[j] + vec2[j];
}
// vec = a*vec1
template<int size>
inline void add_aX(double a, const Vec<size> &vec1, Vec<size> &vec) {
for (int j = 0; j < size; j++) // col
vec[j] += a * vec1[j];
}
// vec = vec2+a*vec1
template<int size>
inline void add_b_p_aX(double a, const Vec<size> &vec1, const Vec<size> &vec2, Vec<size> &vec) {
for (int j = 0; j < 3; j++) // col
vec[j] = vec2[j] + a * vec1[j];
}
template<int size>
inline void vecDot(const Vec<size> &vec1, const Vec<size> &vec2, double &scalar) {
scalar = std::inner_product(vec1.ptr(), vec1.ptr() + size, vec2.ptr(), 0.0);
}
template<int size>
inline void vecDot(const double* vec1, const Vec<size> &vec2, double &scalar) {
scalar = std::inner_product(vec1, vec1 + size, vec2.ptr(), 0.0);
}
template<int size>
inline double vecDot(const Vec<size> vec1, const Vec<size> &vec2) {
return std::inner_product(vec1.ptr(), vec1.ptr() + size, vec2.ptr(), 0.0);
}
template<int size>
inline void vecDivide(const Vec<size> &vec1, const double scalar, Vec<size> &vec) {
for (int j = 0; j < size; j++) // col
vec[j] = vec1[j] / scalar;
}
template<int n, int m>
inline void matDivide(const Mat<n,m> &mat1, const double scalar, Mat<n,m> &mat) {
for (int j = 0; j < n*m; j++) // col
mat[j] = mat1[j] / scalar;
}
inline void cross(const Vec<3> &vec1, const Vec<3> &vec2, Vec<3> &vec) {
vec[0] = vec1[1] * vec2[2] - vec1[2] * vec2[1];
vec[1] = vec1[2] * vec2[0] - vec1[0] * vec2[2];
vec[2] = vec1[0] * vec2[1] - vec1[1] * vec2[0];
}
inline void cross(const double* vec1, const Vec<3> &vec2, Vec<3> &vec) {
vec[0] = vec1[1] * vec2[2] - vec1[2] * vec2[1];
vec[1] = vec1[2] * vec2[0] - vec1[0] * vec2[2];
vec[2] = vec1[0] * vec2[1] - vec1[1] * vec2[0];
}
inline void cross(const Vec<3> &vec1, const Vec<3> &vec2, double *vec) {
vec[0] = vec1[1] * vec2[2] - vec1[2] * vec2[1];
vec[1] = vec1[2] * vec2[0] - vec1[0] * vec2[2];
vec[2] = vec1[0] * vec2[1] - vec1[1] * vec2[0];
}
inline void crossThenAdd(const Vec<3> &vec1, const Vec<3> &vec2, Vec<3> &vec) {
vec[0] += vec1[1] * vec2[2] - vec1[2] * vec2[1];
vec[1] += vec1[2] * vec2[0] - vec1[0] * vec2[2];
vec[2] += vec1[0] * vec2[1] - vec1[1] * vec2[0];
}
inline void crossThenSub(const Vec<3> &vec1, const Vec<3> &vec2, Vec<3> &vec) {
vec[0] -= vec1[1] * vec2[2] - vec1[2] * vec2[1];
vec[1] -= vec1[2] * vec2[0] - vec1[0] * vec2[2];
vec[2] -= vec1[0] * vec2[1] - vec1[1] * vec2[0];
}
inline void vecScalarMul(const double scalar, Vec<3> &product) {
for (int i = 0; i < 3; i++)
product[i] *= scalar;
}
inline void vecScalarMul(const double scalar, const Vec<3> &vec, Vec<3> &product) {
for (int i = 0; i < 3; i++)
product[i] = scalar * vec[i];
}
template<int size>
inline void vecScalarMul(const double scalar, const Vec<size> &vec, Vec<size> &product) {
for (int i = 0; i < size; i++)
product[i] = scalar * vec[i];
}
inline void vecScalarMul(const double scalar, const VecDyn &vec, VecDyn &product) {
for (int i = 0; i < vec.n; i++)
product[i] = scalar * vec[i];
}
template<int size>
inline void vecScalarMulThenAdd(const double scalar, const double *vec, Vec<size> &sum) {
for (int i = 0; i < size; i++)
sum[i] += scalar * vec[i];
}
template<int size>
inline void vecScalarMulThenAdd(const double scalar, const Vec<size> &vec, Vec<size> &sum) {
for (int i = 0; i < size; i++)
sum[i] += scalar * vec[i];
}
inline void skewSymMat(const Vec<3> &vec, Mat<3,3> &mat) {
mat[0] = 0;
mat[4] = 0;
mat[8] = 0;
mat[1] = vec[2];
mat[2] = -vec[1];
mat[3] = -vec[2];
mat[5] = vec[0];
mat[6] = vec[1];
mat[7] = vec[0];
}
template<int size>
inline double squaredNormOfDiff(const Vec<size>& vec1, const Vec<size>& vec2){
double sum=0;
for(int i=0; i<size; i++) {
const double diff = vec1[i] - vec2[i];
sum += diff * diff;
}
return sum;
}
inline void matReverse(Mat<3, 3> &mat) {
mat[0] = mat[0];
mat[1] = mat[1];
mat[2] = mat[2];
mat[3] = - mat[3];
mat[4] = - mat[4];
mat[5] = - mat[5];
mat[6] = - mat[6];
mat[7] = - mat[7];
mat[8] = - mat[8];
}
inline void rpyToRotMat_intrinsic(const Vec<3> &rpy, Mat<3, 3> &R) {
const double su = std::sin(rpy[0]), cu = std::cos(rpy[0]);
const double sv = std::sin(rpy[1]), cv = std::cos(rpy[1]);
const double sw = std::sin(rpy[2]), cw = std::cos(rpy[2]);
R[0] = cv * cw;
R[1] = cv * sw;
R[2] = -sv;
R[3] = su * sv * cw - cu * sw;
R[4] = cu * cw + su * sv * sw;
R[5] = su * cv;
R[6] = su * sw + cu * sv * cw;
R[7] = cu * sv * sw - su * cw;
R[8] = cu * cv;
}
inline void rpyToRotMat_extrinsic(const Vec<3> &rpy, Mat<3, 3> &R) {
const double su = std::sin(rpy[0]), cu = std::cos(rpy[0]);
const double sv = std::sin(rpy[1]), cv = std::cos(rpy[1]);
const double sw = std::sin(rpy[2]), cw = std::cos(rpy[2]);
R[0] = cv * cw;
R[1] = cu * sw + su * cw * sv;
R[2] = su * sw - cu * cw * sv;
R[3] = -cv * sw;
R[4] = cu * cw - su * sv * sw;
R[5] = su * cw + cu * sv * sw;
R[6] = sv;
R[7] = -su * cv;
R[8] = cu * cv;
}
/// computes RIR^T
inline void similarityTransform(const Mat<3, 3> &R, const Mat<3, 3> &I, Mat<3, 3> &mat) {
// Mat<3, 3> temp;
// transposed2MatMul(I, R, temp);
// matmul(R, temp, mat);
const double t00 = R[0]*I[0]+R[3]*I[3]+R[6]*I[6];
const double t10 = R[0]*I[1]+R[3]*I[4]+R[6]*I[7];
const double t20 = R[0]*I[2]+R[3]*I[5]+R[6]*I[8];
const double t01 = R[1]*I[0]+R[4]*I[1]+R[7]*I[2];
const double t11 = R[1]*I[1]+R[4]*I[4]+R[7]*I[5];
const double t21 = R[1]*I[2]+R[4]*I[5]+R[7]*I[8];
const double t02 = R[2]*I[0]+R[5]*I[1]+R[8]*I[2];
const double t12 = R[2]*I[1]+R[5]*I[4]+R[8]*I[5];
const double t22 = R[2]*I[2]+R[5]*I[5]+R[8]*I[8];
mat[0] = R[0]*t00 + R[3]*t10 + R[6]*t20;
mat[1] = R[1]*t00 + R[4]*t10 + R[7]*t20;
mat[2] = R[2]*t00 + R[5]*t10 + R[8]*t20;
mat[3] = mat[1];
mat[4] = R[1]*t01 + R[4]*t11 + R[7]*t21;
mat[5] = R[2]*t01 + R[5]*t11 + R[8]*t21;
mat[6] = mat[2];
mat[7] = mat[5];
mat[8] = R[2]*t02 + R[5]*t12 + R[8]*t22;
// std::cout<<test.e()<<"\n";
// std::cout<<mat.e()<<"\n\n";
}
inline void angleAxisToRotMat(const Vec<3> &a1, const double theta, Mat<3, 3> &rotMat) {
double s, c;
sincos(theta, &s, &c);
const double t = 1.0 - c;
const double tmp1 = a1[0] * a1[1] * t;
const double tmp2 = a1[2] * s;
const double tmp3 = a1[0] * a1[2] * t;
const double tmp4 = a1[1] * s;
const double tmp5 = a1[1] * a1[2] * t;
const double tmp6 = a1[0] * s;
const double tmp7 = a1[0] * a1[0] * t + c;
const double tmp8 = a1[1] * a1[1] * t + c;
const double tmp9 = a1[2] * a1[2] * t + c;
rotMat[0] = tmp7;
rotMat[1] = tmp1 + tmp2;
rotMat[2] = tmp3 - tmp4;
rotMat[3] = tmp1 - tmp2;
rotMat[4] = tmp8;
rotMat[5] = tmp5 + tmp6;
rotMat[6] = tmp3 + tmp4;
rotMat[7] = tmp5 - tmp6;
rotMat[8] = tmp9;
}
inline void vecTransposeMatVecMul(const Vec<3> &vec, const Mat<3, 3> &mat, double &scalar) {
/// x^T M x
scalar = vec[0] * (mat[0] * vec[0] + mat[1] * vec[1] + mat[2] * vec[2])
+ vec[1] * (mat[3] * vec[0] + mat[4] * vec[1] + mat[5] * vec[2])
+ vec[2] * (mat[6] * vec[0] + mat[7] * vec[1] + mat[8] * vec[2]);
}
} // benchmark
#endif //BENCHMARK_MATH_HPP
|
Python | UTF-8 | 337 | 3.296875 | 3 | [] | no_license | '''
Sem erros
Poderia acrescentar comentarios
exemplo:#essse programa calcula o valor de pi usando numeros aleatorio, #importando variaveis, #calculando valorda funcao, #calculando o somantorio, etc
Sandra: 3.5
'''
from math import sqrt, pi, exp
m = 0
s = 2.
x = 1.
gaussiana = 1/(s*sqrt(2*pi))*exp(-1/2.*((x-m)/s)**2)
print(gaussiana)
|
C++ | UTF-8 | 1,438 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <openctm.h>
#include <jtflib/mesh/io.h>
using namespace std;
using namespace zjucad::matrix;
int main(int argc, char *argv[])
{
if ( argc != 3 ) {
cerr << "#usage: ./test_ctm model.obj model.ctm\n";
return __LINE__;
}
matrix<size_t> tris;
matrix<double> nods;
jtf::mesh::load_obj(argv[1], tris, nods);
CTMcontext context;
CTMuint vertCount, triCount, * indices;
CTMfloat *vertices;
// Create our mesh in memory
vertCount = nods.size(2);
triCount = tris.size(2);
vertices = (CTMfloat *)malloc(3*sizeof(CTMfloat)*vertCount);
indices = (CTMuint *)malloc(3*sizeof(CTMuint)*triCount);
std::copy(tris.begin(), tris.end(), indices);
std::copy(nods.begin(), nods.end(), vertices);
cout << "[Info] total memory cost: " << 3*sizeof(CTMfloat)*vertCount+3*sizeof(CTMuint)*triCount << endl;
// Create a new context
context = ctmNewContext(CTM_EXPORT);
// Config compression method
ctmCompressionMethod(context, CTM_METHOD_MG2);
ctmCompressionLevel(context, 9);
ctmVertexPrecision(context, 0.1);
// Define our mesh representation to OpenCTM (store references to it in
// the context)
ctmDefineMesh(context, vertices, vertCount, indices, triCount, NULL);
// Save the OpenCTM file
ctmSave(context, argv[2]);
// Free the context
ctmFreeContext(context);
// Free our mesh
free(indices);
free(vertices);
cout << "[Info] done\n";
return 0;
}
|
Java | UTF-8 | 2,971 | 3.3125 | 3 | [] | no_license | //This file creates the opening screen of the program.
package starter;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.*;
import acm.program.*;
import acm.graphics.*;
public class MenuPane extends GraphicsPane {
private MainApplication program; // you will use program to get access to
// all of the GraphicsProgram calls
private GButton playButton;
private GLabel playLabel;
private GLabel welcomeLabel;
private GImage card1;
private GImage card2;
private GImage card3;
private GImage card4;
private GImage card5;
public static final int cardSizeX = 400;
public static final int cardSizeY = 570;
public static final int cardPosY = 210;
private GButton dirButton;
private GLabel dirLabel;
public MenuPane(MainApplication app) {
super();
program = app;
//play button
playButton = new GButton("", 815, 600, 170, 75);
playButton.setFillColor(Color.ORANGE);
//play label on top of play button
playLabel = new GLabel("PLAY", 830, 655);
playLabel.setFont("TimesRoman-Bold-52");
playLabel.setColor(Color.WHITE);
//welcome label
welcomeLabel = new GLabel("WELCOME TO VIRTUAL UNO", 170, 150);
welcomeLabel.setFont("TimesRoman-Bold-100");
welcomeLabel.setColor(Color.RED);
//Direction button and label
dirButton = new GButton("", 740, 800, 315, 75);
dirButton.setFillColor(Color.ORANGE);
dirLabel = new GLabel("DIRECTIONS", 750, 855);
dirLabel.setFont("TimesRoman-Bold-48");
dirLabel.setColor(Color.WHITE);
//cards
card1 = new GImage("Wild/+4.png", 350, cardPosY);
card1.setSize(cardSizeX, cardSizeY + 2);
card2 = new GImage("Blue/+2.png", 525, cardPosY - 5);
card2.setSize(cardSizeX, cardSizeY + 12);
card3 = new GImage("Green/1.png", 700, cardPosY);
card3.setSize(cardSizeX, cardSizeY);
card4 = new GImage("Yellow/3.png", 875, cardPosY);
card4.setSize(cardSizeX, cardSizeY);
card5 = new GImage("Red/reverse.png", 1050, cardPosY);
card5.setSize(cardSizeX, cardSizeY);
}
@Override
public void showContents() {
program.add(card1);
program.add(card2);
program.add(card3);
program.add(card4);
program.add(card5);
program.add(playButton);
program.add(playLabel);
program.add(welcomeLabel);
program.add(dirButton);
program.add(dirLabel);
}
@Override
public void hideContents() {
program.remove(playButton);
program.remove(playLabel);
program.remove(welcomeLabel);
program.remove(card1);
program.remove(card2);
program.remove(card3);
program.remove(card4);
program.remove(card5);
program.remove(dirButton);
program.remove(dirLabel);
}
@Override
public void mousePressed(MouseEvent e) {
GObject obj = program.getElementAt(e.getX(), e.getY());
if (obj == playButton) {
program.switchToFirstUser();
}
if (obj == playLabel) {
program.switchToFirstUser();
}
if (obj == dirButton) {
program.switchToDirections();
}
if (obj == dirLabel) {
program.switchToDirections();
}
}
}
|
PHP | UTF-8 | 659 | 3 | 3 | [] | no_license | <?php
namespace Battleship\Ship;
class ShipFactory
{
public static function build($id)
{
switch ($id) {
case Carrier::ID:
return new Carrier();
break;
case Battleship::ID:
return new Battleship();
break;
case Cruiser::ID:
return new Cruiser();
break;
case Submarine::ID:
return new Submarine();
break;
case Destroyer::ID:
return new Destroyer();
break;
}
throw new \Exception('Invalid Ship id');
}
}
|
Java | UTF-8 | 486 | 1.96875 | 2 | [] | no_license | package com.ssm.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ssm.dao.ShopMapper;
import com.ssm.pojo.Shop;
import com.ssm.service.ShopService;
@Service
public class ShopServiceImpl implements ShopService{
@Autowired
private ShopMapper shopMappper;
@Override
public List<Shop> findShop(Shop shop) {
return shopMappper.findShop(shop);
}
}
|
Python | UTF-8 | 303 | 3.34375 | 3 | [
"MIT"
] | permissive | """
"""
import subprocess
import time
start = time.time()
sleep_procs = []
for _ in range(10):
proc = subprocess.Popen(["sleep", "1"])
sleep_procs.append(proc)
for proc in sleep_procs:
proc.communicate()
end = time.time()
delta = end - start
print(f"Finished in {delta:.3} seconds")
|
C++ | UTF-8 | 584 | 3.3125 | 3 | [] | no_license | #include "PriorityQueue.h"
#include <iostream>
using namespace std;
int main()
{
priorityQueue myqueue;
if (myqueue.empty())
cout << "My priority Queue is empty\n" << endl;
myqueue.insert(59);
myqueue.insert(41);
myqueue.insert(25);
myqueue.insert(12);
myqueue.insert(91);
myqueue.min();
myqueue.extractMin();
myqueue.insert(34);
myqueue.insert(63);
myqueue.extractMin();
myqueue.insert(75);
myqueue.insert(85);
myqueue.extractMin();
cout << "Minimum value is ";
cout << myqueue.min() << endl;
system("pause");
return 0;
} |
PHP | UTF-8 | 1,392 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
use app\components\core\Selector;
use app\components\form\Form;
use app\models\Book;
$model = $body['book'] ?? new Book();
$form = new Form('/library/book/add', Form::POST, $model, $errors ?? []);
$isnbField = $form->field('ISBN', 'isbn');
$titleField = $form->field('Title', 'title');
$authorField = $form->field('Author', 'author');
$publisherField = $form->field('Publisher', 'publisher_name');
$quantityField = $form->field('Quantity', 'quantity');
$yearField = $form->field('Year', 'year');
// Making categories selector
$cats = [];
foreach ($body['categories'] as $cat) {
$cats[$cat->name] = $cat->id;
}
$selector = new Selector('Category', 'category_id', $cats);
?>
<h1 class="my-5">Add new book</h1>
<?php $form->begin(); ?>
<div class="row">
<div class="col-md mb-3">
<?php $isnbField->render() ?>
</div>
<div class="col-md mb-3">
<?php $selector->render(); ?>
</div>
<div class="col-md mb-3">
<?php $quantityField->render() ?>
</div>
</div>
<div class="col-md mb-3">
<?php $titleField->render() ?>
</div>
<div class="row">
<div class="col-md mb-3">
<?php $authorField->render() ?>
</div>
<div class="col-md mb-3">
<?php $publisherField->render() ?>
</div>
<div class="col-md mb-3">
<?php $yearField->render() ?>
</div>
</div>
<button type="submit" class="my-2 btn btn-primary">Add</button>
<?php $form->end(); ?> |
Ruby | UTF-8 | 906 | 3.953125 | 4 | [] | no_license |
def create_array_of_bottles
array_of_bottles = []
bottle_with_p = rand(1000)
1000.times do |i|
temp_bottle = Bottle.new
if i == bottle_with_p
temp_bottle.is_poison = true;
end
array_of_bottles << temp_bottle
end
array_of_bottles
end
def find_poison(array_of_bottles)
array_of_bottles.each_with_index do |b,i|
if b.is_poison
p i
end
end
return -1
end
def find_poison_using_b_search(array_of_bottles)
mid = find_length_in_log_n(array_of_bottles,1) / 2
end
def find_length_in_log_n(array_of_bottles, test_number)
if array_of_bottles[test_number] != nil
find_length_in_log_n(array_of_bottles, test_number * 2)
else
p "length_in_log_n : #{test_number}"
return test_number
end
return test_number
end
class Bottle
attr_accessor :is_poison
def initialize
@is_poison = false;
end
end
find_poison(create_array_of_bottles())
|
Markdown | UTF-8 | 3,961 | 3.046875 | 3 | [] | no_license | ---
title: Capitalism has its flaws
tags:
- history
- creating-art
- blog
- climate change
date: "2019-03-18"
---

<b>Again.. stress alert.. do not read this if you have significant depressive states.. you have been warned</b>
Don't get me wrong. I love capitalism. I enjoy the benefits of a society built by talents, education, tech and progress coming from enterepreneural pursuits. Never in our lifetime have existed 7.7 billion people that can enjoy the resources of this planet and harness it to improve our living standards without the threat of war. It is truly amazing to live in this moment. Even a guy like me can learn about anything, use rectangular boxes called computers to code and communicate information through websites and publish it through servers and making it accessible through smart devices within a few clicks.
But yet I have fears that capitalism is the way forward into the future. Eventhough our civilization's best attributes are built on this concept, I still see its flaws now revealing itself. It is truly scary but enlightening at the same time.
My firsthand experience with capitalism in Africa is not my best performance as a human being. I'm not proud of helping a governmnent official steal oil from his country's public resources and transfer it to his personal business. I would not specifically name who is the people involved to promote safety of others still working with them. Capitalism became a way wherein corruption got out of hand all over the world. Even in the Philippines, the main source of all evil and poor progress is - yes, corruption.
Capitalism enabled tax evasion strategies. Transfering wealth in various tax havens all around the world became a mechanism for rich heads of states to filter out significant funds that they have earned or stole from their countries. This money could have been used to improve third world economies but instead pooled out of their countries for personal gain.
Capitalism also have introduced social media wherein everyone created a web of information that seems to be reality. Most people get their knowledge from Facebook, Twitter & Instagram and what is scary is that data in these platforms are largely unverified.
Capitalism also hides the layers of history. It is so easy to believe for the younger generations that the world is a static ball of happiness and abundance. The age of our specie is around 250,000 years and the age of stability that we currently have is just 50 years!!!
Lastly, capitalism paved way for these particular events wherein Exxon Mobil and Shell executives hid the [devastating effects of fossil fuel use](https://www.theguardian.com/environment/climate-consensus-97-per-cent/2018/sep/19/shell-and-exxons-secret-1980s-climate-change-warnings) and thus increasing human caused global warming and climate changes. The effects of [one single memo](https://www.scientificamerican.com/article/exxon-knew-about-climate-change-almost-40-years-ago/) produced by the executives of this company is so catasthropic that it will change the path of history forever. This is a [video](https://www.youtube.com/watch?v=TbW_1MtC2So) on how we got in these mess we are in.
I overused the word capitalism here because I'm trying to paint a picture that this is so far the best that our society have produced to harness our human capabilities and solve our daily struggles - but its not even perfect at all. Capitalism goes deep, because of the freedom it allows people to create virtually anything. But the downside of it is it doesn't factor nature - resources and negative impact and also it shows how exposed we are from insidious desires of the few to manipulate the future for personal gain.
Civilization is continously transforming itself and we might be in a time that we need to improve the way we operate virtually everything..
|
Markdown | UTF-8 | 5,197 | 2.984375 | 3 | [] | no_license | ---
id: 640
title: 'Twitter via IM. It isn't just about the track.'
date: 2009-03-13T08:40:14+00:00
author: Tyler (Chacha)
layout: post
guid: http://chacha102.com/?p=640
permalink: /twitter-via-im-it-isnt-just-about-the-track-2/
jd_tweet_this:
- yes
wp_jd_clig:
- http://cli.gs/MRRMdD
categories:
- Misc
---
It is an understatement to say that Twitter is used by a lot of people. With that large amount of people, there are many ways to get Twitter. Some people perfer the web client. Most people, actually, perfer the web client. But sometimes you need something different than the web client. Something that will alert you when certain things happen. This is why I believe that Twitter desktop clients are so popular. Unlike the web site, they run in the background and alert you when something special happens, like getting a reply, a direct message, or something else that requires you attention. It beats all heck for refreshing the page, looking through your Home and Reply tabs trying to figure out what happened recently.
People who do large [surveys](http://blog.hubspot.com/blog/tabid/6307/bid/4584/New-Data-on-Top-Twitter-Applications-and-Usage.aspx) on what other people like to use while Twittering have figured out that more than 50% of Twitter users use clients other than the website. Most people use Tweetdeck, it having 7.3% of the application market. (Twitterfeed is first, but doesn’t count sine it is automated tweeting) Tweetdeck probably provides the most unique experience for Twitter because it allows you to get updates on specific keywords, similar to track. It does this using the TwitterSearch available at search.twitter.com.
In all, there are over 600 different Twitter applications. Most of which are using direct API calls to the website in order to get Tweets. But what happens when you need to get to Twitter when the website is blocked. In many cases, companies will block websites like Twitter in order to get people to be more productive. This breaks all the Twitter API calls, resulting in, yep, no Tweets on your desktop client. The entire debate on whether Twitter can be useful to your job is up for grabs, but I don’t have a job. I’m trying to Twitter while government paid teachers, sit on their butts during the 4 years I am in highschool, and proceed to waste my time. So, I’m not going to argue whether or not it is beneficial for your job to Twitter. That is up to you.
In order to solve this problem, you first need to understand a little about what Jabber is. Jabber is an open isntant messaging platform that is used by Google Talk and is supported by many clients. PSI, Pidign, etc, all support Jabber. Unlike AIM, MSN, and other networks, Jabber is open so anyone can create an application using it fairly easily. To find more, google ‘Jabber’ and you’ll find more information than you need to know about it/
Let’s examine the problem. Twitter + Unfilter Internet = Happy. Twitter – Unfiltered Internet = Sad.This is, once again, because in order for desktop applications to work, you must have the desktop application go to Twitter.com/api/blah. If that is blocked, you are out of luck. But what if you had a different computer, on an unfiltered connection, go and grab your updates. And then, after it grabbed your updates, it could send you the tweets afterwards, using this new protocol we just learned called Jabber. You would, well, have Twitter via IM!
Originally, when Twitter was first made, Twitter had a IM version, very similar to the one we just described. The unique thing about Twitter’s IM was that it allowed for ‘track’ or the ability to search all of Twitter for certain keywords. This was extremely useful for companies, because if Comcast wanted to bring customer service to Twitter, they just tracked ‘comcast’ and they would find any Tweets about Comcast. But Twitter soon removed this, saying that it the feature was disabled to keep the main service stable. They promised it would return sometime, but, we know that it won’t be coming back anytime soon.
Many believe that Twitter got rid of IM, and would later lease it to specific companies that paid them, as a way of making money. Comcast would now have to pay Twitter so that they could provide customer service on Twitter. Sounds fair enough.
But why did they have to get rid of the IM feature completely? They could have disabled track, and then given the rest of us our real time updates. This, is finally, where this post is headed. I would much rather have Twitter on my Google Talk, with or without track. I think that using IM is a powerful method of recieving updates, one far better than any current desktop client. Because if you enabled IM, you would enable people to get Tweets ANYWHERE, in real time. Instead of having to have a mobile browser on a cell phone, I could just open up my IM client. Instead of having a 3rd party application getting my updates, why couldn’t I just go right to the source and get my Twitter updates from Twitter?
How do you get your Twitter fix everyday? Do you have problems with internet access? |
Python | UTF-8 | 1,426 | 2.65625 | 3 | [] | no_license | #-*- coding:utf-8 -*-
import logging
import logging.config
'''
#1
logging.warning('watch out')
logging.info('i told u')
# 输出 loggin 只会打印输出比 warning 更高级别的日志
WARNING:root:watch out
'''
'''
# 配置 logging # 存入文件名 # 存入的类型
logging.basicConfig(filename='example.log',level=logging.INFO)
logging.debug('the message should go to the log file')
logging.info('so should this')
logging.warning('and this')
'''
'''
logging.basicConfig(format='%(asctime)s %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this envent was logged')
'''
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
# logger.debug('debug message')
# logger.info('info message')
# logger.warning('warning message')
# logger.error('error message')
# logger.critical('critical message')
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('simple_example')
logger.debug('debug message')
logger.info('info message')
logger.warning('warning message')
logger.error('error message')
logger.critical('critical message')
#################################
|
C++ | UTF-8 | 586 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | #include<iostream>
#include<string>
using namespace std;
int t;
int x,y,l;
string s;
int c;
bool map[101][101];
int main()
{
//freopen("in1656.txt","r",stdin);
while(cin>>t)
{
memset(map,false,sizeof(map));
while(t--)
{
cin>>s>>x>>y>>l;
c=0;
for(int i=x;i<=x+l-1;++i)
{
for(int j=y;j<=y+l-1;++j)
{
if(s=="TEST"&&map[i][j])
{
c++;
}
else if(s=="WHITE")
{
map[i][j]=false;
}
else if(s=="BLACK")
{
map[i][j]=true;
}
}
}
if(s=="TEST")
{
cout<<c<<endl;
}
}
}
return 0;
}
|
Python | UTF-8 | 3,863 | 3.25 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# # Watttime Interview Assessment
# In[22]:
import pandas as pd
# In[23]:
data_gppd = pd.read_csv("gppd.csv")
# In[24]:
data_entso = pd.read_csv("entso.csv")
# In[25]:
data_platts = pd.read_csv("platts.csv")
# In[ ]:
# #### Function to clen the country names
# In[26]:
def clean(x):
x = x[:x.find("(")]
return x
# In[27]:
data_entso["country"] = data_entso["country"].apply(clean)
# #### Function to remove special characters from plants and unit names
# In[28]:
import re
def special_character(k):
k = re.sub(r"[^a-zA-Z0-9]+", ' ', k)
return k
# In[29]:
data_platts["UNIT"] = data_platts["UNIT"].apply(special_character)
# In[30]:
data_entso["unit_name"] = data_entso["unit_name"].apply(special_character)
# In[31]:
data_gppd["plant_name"] = data_gppd["plant_name"].apply(special_character)
# In[32]:
data_entso["plant_name"] = data_entso["plant_name"].apply(special_character)
# #### Read the fuel_thesaurus.csv file
# In[33]:
import csv
rows = []
with open("fuel_thesaurus.csv") as fuel_file:
csvreader = csv.reader(fuel_file)
for row in csvreader:
rows.append(row)
u_fuel = []
p_fuel = []
for z in range(1,len(rows)):
u_fuel.append(rows[z][0])
p_fuel.append(rows[z][1])
# #### Function to convert unit fuel to primary fuel
# In[34]:
def primary_fuel(y):
if y.lower() in u_fuel:
index = u_fuel.index(y.lower())
y = p_fuel[index]
return y
# In[35]:
data_entso["unit_fuel"] = data_entso["unit_fuel"].apply(primary_fuel)
# #### Maping Function
# ##### plant_name , plant primary fuel , country are the three conditions to map gppd.csv and entso.csv file ---> It gives 9 records of gpp_plant_id and entso_unit_id
# ##### wipp_id[plant_id] and unit names are the two conditions to map gppd.csv, entso.csv to platts.csv --> Final common rows for all the three files are two records
# In[36]:
def mapping(data_gppd,data_entso,data_platts):
gppd_plant_id = []
entso_unit_id = []
platts_unit_id =[]
for p in range(len(data_gppd["plant_id"])):
for x in range(len(data_entso["plant_name"])):
if data_gppd["plant_name"][p].lower() == data_entso["plant_name"][x].lower():
if data_gppd["plant_primary_fuel"][p] == data_entso["unit_fuel"][x]:
if data_gppd["country_long"][p] == data_entso["country"][x].strip():
if type(data_gppd["wepp_id"][p]) == float:
continue
else:
for k in range(len(data_platts["unit_id"].tolist())):
if int(data_gppd["wepp_id"][p]) == data_platts["plant_id"][k]:
if data_entso["unit_name"][x].lower() == data_platts["UNIT"][k].lower():
platts_unit_id.append(data_platts["unit_id"][k])
gppd_plant_id.append(data_gppd["plant_id"][p])
entso_unit_id.append(data_entso["unit_id"][x])
return platts_unit_id,gppd_plant_id,entso_unit_id
# In[37]:
platts_unit_id,gppd_plant_id,entso_unit_id = mapping(data_gppd,data_entso,data_platts)
# In[38]:
print(platts_unit_id)
print(entso_unit_id)
print(gppd_plant_id)
# #### Writing output into the mapping.csv file
# In[39]:
dict = {'gppd_plant_id':gppd_plant_id,'entso_unit_id':entso_unit_id,'platts_unit_id':platts_unit_id}
df = pd.DataFrame(dict)
df.to_csv('mapping.csv')
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
|
TypeScript | UTF-8 | 1,012 | 2.625 | 3 | [] | no_license | import {CoursesService} from './courses.service';
import {Course} from "../interfaces/course.inteface";
describe('CoursesService', () => {
let coursesService: CoursesService;
beforeEach(() => {
coursesService = new CoursesService();
});
it('should create an instance', () => {
expect(coursesService).toBeTruthy();
});
it('should get the courses list = 5 ', () => {
coursesService.getCoursesList();
const mockedCountLength: number = 5;
expect(coursesService.coursesItems.length).toEqual(mockedCountLength);
});
it('should find desired course object using getCourseItemById method ', () => {
const mockedId: string = '3he3hj3hj3hj34j3h4j34h';
const mockedObject: Course = {
id: '3he3hj3hj3hj34j3h4j34h',
title: 'ANGULAR 6',
creation: '15/02/1990',
duration: 60,
description: 'FFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFF',
topRated: true
};
expect(coursesService.getCourseItemById(mockedId)).toEqual(mockedObject);
});
});
|
C# | UTF-8 | 1,475 | 3.5 | 4 | [] | no_license | public class Solution {
public int LadderLength(string beginWord, string endWord, IList<string> wordList) {
if (wordList == null || !wordList.Contains(endWord)) {
return 0;
}
var result = 1;
var wordSet = new HashSet<string>(wordList);
var queue = new Queue<string>();
queue.Enqueue(beginWord);
while (queue.Count > 0) {
var size = queue.Count;
for (var i = 0; i < size; i++) {
var curWord = queue.Dequeue();
for (var j = 0; j < curWord.Length; j++) {
for (var k = 'a'; k <= 'z'; k++) {
var str = ReplaceAt(curWord, j, k);
if (str == curWord) {
continue;
}
if (str == endWord) {
return result + 1;
}
if (wordSet.Contains(str)) {
wordSet.Remove(str);
queue.Enqueue(str);
}
}
}
}
result++;
}
return 0;
}
private static string ReplaceAt(string str, int index, char newChar)
{
var chars = str.ToCharArray();
chars[index] = newChar;
return new string(chars);
}
}
|
Java | UTF-8 | 203 | 1.625 | 2 | [] | no_license | package repository;
import main.AdressClient;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AdressClientRepository extends JpaRepository<AdressClient, Long> {
}
|
Java | UTF-8 | 629 | 2.0625 | 2 | [] | no_license | package com.example.olympia.implementations.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.olympia.abstractions.dao.ClientDAO;
import com.example.olympia.abstractions.service.ClientService;
import com.example.olympia.entity.Client;
@Service
public class ClientServiceStandard implements ClientService{
@Autowired
private ClientDAO clientDao;
@Override
@Transactional
public Client findById(int id) {
return clientDao.findById(id);
}
}
|
Python | UTF-8 | 1,155 | 3.53125 | 4 | [] | no_license | # """
# This is BinaryMatrix's API interface.
# You should not implement it, or speculate about its implementation
# """
#class BinaryMatrix(object):
# def get(self, row: int, col: int) -> int:
# def dimensions(self) -> list[]:
class Solution:
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
height, width = binaryMatrix.dimensions()
min_seen = float('inf')
eligible_rows = set([i for i in range(height)])
left = 0
right = width-1
while left <= right:
midpoint = left + ((right-left) // 2)
found_one = False
still_good_rows = set()
for row in eligible_rows:
if binaryMatrix.get(row, midpoint) == 1:
found_one = True
still_good_rows.add(row)
min_seen = min(min_seen, midpoint)
if not found_one:
left = midpoint + 1
else:
eligible_rows = still_good_rows
right = midpoint - 1
if min_seen != float('inf'):
return min_seen
else:
return -1
|
Java | UTF-8 | 436 | 2.203125 | 2 | [] | no_license | package com.technicalsand.user;
import org.hibernate.EmptyInterceptor;
import org.springframework.stereotype.Service;
@Service
public class CustomInterceptor extends EmptyInterceptor {
@Override
public String onPrepareStatement(String sql) {
System.err.println("Before Modifying SQL =" + sql);
sql = sql.replace("ATTENDANCE_1_2019 ", "ATTENDANCE_2_2019 ");
System.err.println("After Modifying SQL =" + sql);
return sql;
}
} |
PHP | UTF-8 | 3,167 | 2.53125 | 3 | [] | no_license | <?php
if (!isset($_COOKIE['name']) || !isset($_COOKIE['pass']) || $_COOKIE['name'] == "" || $_COOKIE['pass'] == "") {
echo "notexist";
exit();
}
$db = mysqli_connect("localhost", "risk_game", "", "riskdb");
$name = $_POST["name"];
$pass = $_POST["pass"];
$stmt = $db->prepare("SELECT `user_id` FROM players WHERE `user_name`=? AND `user_password`=?;");
$stmt->bind_param('ss', $_COOKIE['name'], $_COOKIE['pass']);
$stmt->execute();
$uid = mysqli_fetch_row($stmt->get_result())[0];
$stmt = $db->prepare("SELECT `player_ids`,`wanted_players`,`game_id`,`game_ready`,`auto_start` FROM games WHERE `game_name`=? AND `game_password`=?;");
$stmt->bind_param('ss', $name, $pass);
$stmt->execute();
$out = $stmt->get_result();
if (mysqli_num_rows($out) == 0) {
echo "notexist";
} else {
$result = mysqli_fetch_row($out);
$players = $result[0];
$player_a = explode(",", $players);
if ($result[3] == "1") {
echo "notexist";
} else if (in_array($uid, $player_a)) {
echo "already";
} else {
$player_count = sizeof($player_a) - 1;
$max_players = intval($result[1]);
$game_id = $result[2];
$auto_start = $result[4] == "1";
if ($player_count < $max_players) {
$players = $players . $uid . ",";
$stmt = $db->prepare("UPDATE games SET `player_ids`=? WHERE `game_id`=?;");
$stmt->bind_param('ss', $players, $game_id);
$stmt->execute();
$stmt = $db->prepare("SELECT `user_games` FROM players WHERE `user_id`=?;");
$stmt->bind_param('s', $uid);
$stmt->execute();
$current_games = mysqli_fetch_row($stmt->get_result())[0];
$current_games = $current_games . $game_id . ",";
$stmt = $db->prepare("UPDATE players SET `user_games`=? WHERE `user_id`=?;");
$stmt->bind_param('ss', $current_games, $uid);
$stmt->execute();
if ($player_count == ($max_players - 1) && $auto_start) {
echo "STARTING";
$p_ids = explode(",", $players);
$order = array();
for ($i = 0; $i < count($p_ids)-1; $i++) {
$order[] = $p_ids[$i];
}
shuffle($order);
$game_data = "0||" . implode(",", $order) . "||";
for ($i = 0; $i < 41; $i++) {
$game_data .= "-1,";
}
$game_data .= "-1||";
for ($i = 0; $i < 41; $i++) {
$game_data .= "0,";
}
$game_data .= "0||0||";
$troopsPer = 0;
$n_players = count($p_ids)-1;
if ($n_players < 3) {
exit();
} else if ($n_players == 3) {
$troopsPer = 35;
} else if ($n_players == 4) {
$troopsPer = 30;
} else if ($n_players == 5) {
$troopsPer = 25;
} else if ($n_players == 6) {
$troopsPer = 20;
} else {
exit();
}
for ($i = 0; $i < $n_players-1; $i++) {
$game_data .= $troopsPer . ",";
}
$game_data .= $troopsPer . "||";
for ($i = 0; $i < 41; $i++) {
$game_data .= "-1,";
}
$game_data .= "-1";
$stmt = $db->prepare("UPDATE games SET `game_data`=? WHERE `game_id`=?;");
$stmt->bind_param('ss', $game_data, $game_id);
$stmt->execute();
$stmt = $db->prepare("UPDATE games SET `game_ready`=true WHERE `game_id`=?;");
$stmt->bind_param('s', $game_id);
$stmt->execute();
}
} else {
echo "filled";
}
}
}
?> |
Python | UTF-8 | 394 | 2.984375 | 3 | [] | no_license | #
# @lc app=leetcode.cn id=69 lang=python3
#
# [69] x 的平方根
#
class Solution:
def mySqrt(self, x: int) -> int:
if x<=1:
return x
left=0
right=x
while left<right:
mid=left+(right-left)//2
s=mid*mid
if s<=x:
left=mid+1
else:
right=mid
return right-1
|
Java | UTF-8 | 1,421 | 2.734375 | 3 | [] | no_license | package vn.edu.techkids.controllers.enemyplanes;
import vn.edu.techkids.controllers.ControllerManager;
import vn.edu.techkids.models.GameConfig;
/**
* Created by qhuydtvt on 5/6/2016.
*/
public class EnemyPlaneControllerManager extends ControllerManager {
private int count = 0;
private int planeType = 0;
private EnemyPlaneControllerManager() {
super();
}
@Override
public void run() {
super.run();
count++;
if(GameConfig.getInst().durationInSeconds(count) > 2) {
count = 0;
planeType++;
for (int x = 40; x < GameConfig.getInst().
getScreenWidth() - 40; x += 100) {
if(planeType % 2 == 0) {
this.singleControllerVector.add(
EnemyPlaneController.create(EnemyPlaneType.BLACK, x, 0)
);
}
else {
this.singleControllerVector.add(
EnemyPlaneController.create(EnemyPlaneType.WHITE, x, 0)
);
}
}
}
}
private static EnemyPlaneControllerManager inst;
public static EnemyPlaneControllerManager getInst() {
if(inst == null) {
inst = new EnemyPlaneControllerManager();
}
return inst;
}
}
|
SQL | UTF-8 | 6,718 | 3.21875 | 3 | [] | no_license | DROP TABLE transacao_empresa;
DROP TABLE transacao;
DROP TABLE funcao_func;
DROP TABLE funcionario;
DROP TABLE tipo_funcao;
DROP TABLE tipo_setor;
DROP TABLE socio;
DROP TABLE aluno;
DROP TABLE telefone_empresa;
DROP TABLE endereco_empresa;
DROP TABLE empresa;
DROP TABLE telefone;
DROP TABLE endereco;
DROP TABLE usuario;
DROP TABLE historico_transacao_empresa;
DROP TABLE historico_tipo_funcao;
DROP TABLE HISTORICO_SENHA;
CREATE TABLE usuario
(
usu_id NUMBER NOT NULL PRIMARY KEY,
usu_cpf VARCHAR2(15) NOT NULL,
usu_rg VARCHAR2(15) NOT NULL,
usu_email VARCHAR2(200) NOT NULL,
usu_nome VARCHAR2(200) NOT NULL,
usu_senha VARCHAR2(20) NOT NULL
);
CREATE TABLE endereco
(
end_id NUMBER NOT NULL PRIMARY KEY,
usu_id NUMBER NOT NULL,
end_cep VARCHAR2(10) NOT NULL,
end_logradouro VARCHAR2(150) NOT NULL,
end_numero NUMBER,
end_complemento VARCHAR2(50),
end_cidade VARCHAR2(150) NOT NULL,
end_estado VARCHAR2(100) NOT NULL,
end_bairro VARCHAR2(100) NOT NULL
);
ALTER TABLE endereco
ADD FOREIGN KEY(usu_id)REFERENCES usuario(usu_id);
CREATE TABLE telefone
(
tel_id NUMBER NOT NULL PRIMARY KEY,
usu_id NUMBER NOT NULL,
tel_ddd NUMBER NOT NULL,
tel_numero VARCHAR2(10) NOT NULL
);
ALTER TABLE telefone
ADD FOREIGN KEY(usu_id)REFERENCES usuario(usu_id);
CREATE TABLE empresa
(
emp_id NUMBER NOT NULL PRIMARY KEY,
emp_cnpj VARCHAR2(20) NOT NULL,
emp_incricao_municipal VARCHAR2(25) NOT NULL,
emp_incricao_estadual VARCHAR2(25) NOT NULL,
emp_nome_fantasia VARCHAR2(150) NOT NULL,
emp_razao_social VARCHAR2(200) NOT NULL
);
CREATE TABLE endereco_empresa
(
empend_id NUMBER NOT NULL PRIMARY KEY,
emp_id NUMBER NOT NULL,
empend_cep VARCHAR2(10) NOT NULL,
empend_logradouro VARCHAR2(150) NOT NULL,
empend_numero NUMBER,
empend_complemento VARCHAR2(50),
empend_cidade VARCHAR2(150) NOT NULL,
empend_estado VARCHAR2(100) NOT NULL,
empend_bairro VARCHAR2(100) NOT NULL,
empend_email VARCHAR2(200),
empend_site VARCHAR2(200)
);
ALTER TABLE endereco_empresa
ADD FOREIGN KEY(emp_id)REFERENCES empresa(emp_id);
CREATE TABLE telefone_empresa
(
emptel_id NUMBER NOT NULL PRIMARY KEY,
emp_id NUMBER NOT NULL,
emptel_ddd NUMBER NOT NULL,
emptel_numero VARCHAR2(20) NOT NULL
);
ALTER TABLE telefone_empresa
ADD FOREIGN KEY(emp_id)REFERENCES empresa(emp_id);
CREATE TABLE aluno
(
alu_ra NUMBER NOT NULL PRIMARY KEY,
usu_id NUMBER NOT NULL,
emp_id NUMBER NOT NULL
);
ALTER TABLE aluno
ADD FOREIGN KEY(usu_id)REFERENCES usuario(usu_id);
ALTER TABLE aluno
ADD FOREIGN KEY(emp_id)REFERENCES empresa(emp_id);
CREATE TABLE socio
(
soc_id NUMBER NOT NULL PRIMARY KEY,
usu_id NUMBER NOT NULL,
emp_id NUMBER NOT NULL
);
ALTER TABLE socio
ADD FOREIGN KEY(emp_id)REFERENCES empresa(emp_id);
ALTER TABLE socio
ADD FOREIGN KEY(usu_id)REFERENCES usuario(usu_id);
CREATE TABLE tipo_setor
(
tip_setorid NUMBER NOT NULL PRIMARY KEY,
tip_descricao VARCHAR2(100) NOT NULL,
emp_id NUMBER NOT NULL
);
ALTER TABLE tipo_setor
ADD FOREIGN KEY(emp_id)REFERENCES empresa(emp_id);
CREATE TABLE tipo_funcao
(
funcao_id NUMBER NOT NULL PRIMARY KEY,
funcao_descricao VARCHAR2(100) NOT NULL,
funcao_salario NUMBER(10, 2) NOT NULL,
emp_id NUMBER NOT NULL,
tip_setorid NUMBER NOT NULL
);
ALTER TABLE tipo_funcao
ADD FOREIGN KEY(emp_id)REFERENCES empresa(emp_id);
ALTER TABLE tipo_funcao
ADD FOREIGN KEY(tip_setorid)REFERENCES tipo_setor(tip_setorid);
CREATE TABLE funcionario
(
fun_id NUMBER NOT NULL PRIMARY KEY,
fun_ctps VARCHAR2(20) NOT NULL,
usu_id NUMBER NOT NULL,
emp_id NUMBER NOT NULL
);
ALTER TABLE funcionario
ADD FOREIGN KEY(emp_id)REFERENCES empresa(emp_id);
ALTER TABLE funcionario
ADD FOREIGN KEY(usu_id)REFERENCES usuario(usu_id);
CREATE TABLE funcao_func
(
fun_id NUMBER NOT NULL,
funcao_id NUMBER NOT NULL,
emp_id NUMBER NOT NULL
);
ALTER TABLE funcao_func
ADD FOREIGN KEY(emp_id)REFERENCES empresa(emp_id);
ALTER TABLE funcao_func
ADD FOREIGN KEY(fun_id)REFERENCES funcionario(fun_id);
ALTER TABLE funcao_func
ADD FOREIGN KEY(funcao_id)REFERENCES tipo_funcao(funcao_id);
CREATE TABLE transacao
(
trans_id NUMBER NOT NULL PRIMARY KEY,
trans_descricao VARCHAR2(100) NOT NULL,
trans_data DATE,
emp_id NUMBER NOT NULL
);
ALTER TABLE transacao
ADD FOREIGN KEY(emp_id)REFERENCES empresa(emp_id);
CREATE TABLE transacao_empresa
(
traemp_id NUMBER NOT NULL PRIMARY KEY,
traemp_descricao VARCHAR2(100) NOT NULL,
traemp_tipotransacao VARCHAR2(100) NOT NULL,
traemp_valorbruto NUMBER(8, 2) NOT NULL,
traemp_valorliquido NUMBER(8, 2) NOT NULL,
traemp_datatransacao DATE,
trans_id NUMBER NOT NULL,
emp_id NUMBER NOT NULL,
usu_id NUMBER NOT NULL
);
ALTER TABLE transacao_empresa
ADD FOREIGN KEY(emp_id)REFERENCES empresa(emp_id);
ALTER TABLE transacao_empresa
ADD FOREIGN KEY(trans_id)REFERENCES transacao(trans_id);
ALTER TABLE transacao_empresa
ADD FOREIGN KEY(usu_id)REFERENCES usuario(usu_id);
CREATE TABLE historico_transacao_empresa
(
data DATE,
user_log VARCHAR2(30),
traemp_id NUMBER NOT NULL,
traemp_descricao VARCHAR2(100) NOT NULL,
traemp_tipotransacao VARCHAR2(100) NOT NULL,
traemp_valorbruto NUMBER(8, 2) NOT NULL,
traemp_valorliquido NUMBER(8, 2) NOT NULL,
traemp_datatransacao DATE,
trans_id NUMBER NOT NULL,
emp_id NUMBER NOT NULL,
usu_id NUMBER NOT NULL
);
CREATE TABLE historico_tipo_funcao
(
data DATE,
user_log VARCHAR2(30),
funcao_id NUMBER NOT NULL,
funcao_descricao VARCHAR2(100) NOT NULL,
funcao_salario NUMBER(10, 2) NOT NULL,
emp_id NUMBER NOT NULL,
tip_setorid NUMBER NOT NULL
);
CREATE TABLE HISTORICO_SENHA(USU_ID NUMBER NOT NULL, TIMESTAMP DATETIME NOT NULL, SENHA VARCHAR(20)NOT NULL); |
Ruby | UTF-8 | 820 | 2.71875 | 3 | [
"MIT"
] | permissive | class LeTitle < ActiveRecord::Base
validates_length_of :name, :within => 0..20
validates_uniqueness_of :name, :message => :already_exists
validates_length_of :description, :maximum => 80
#-----------------------------------------------------------------------------
# Base methods:
#-----------------------------------------------------------------------------
#++
# Computes a shorter description for the name associated with this data
def get_full_name
self.name.to_s
end
# Computes a verbose or formal description for the name associated with this data
def get_verbose_name
[
(name.empty? ? nil : name),
(description.empty? ? nil : description)
].compact.join(": ")
end
#-----------------------------------------------------------------------------
#++
end
|
Python | UTF-8 | 1,523 | 3.984375 | 4 | [] | no_license | # Reorder LinkedLists in Python
# Author: Pavan kumar Paluri
# LeetCode-Medium
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
# 3 stage algorithm:
# stage -1 : Find the mid-point in the linkedlist
# Stage-2: Reverse the second half of the linkedlist
# Stage-3: Merge the first half and the reversed second half such that the odd elements are occupied by the first half and even elements are occupied by the second half
# base condition:
if head is None:
return
# Stage-1:
fast, slow = head, head
while fast.next is not None:
fast = fast.next
if fast.next is not None:
slow = slow.next
fast = fast.next
# If here: slow exactly at mid-pt and fast is at end of list
# Stage-2:
current = slow.next
prev = None
slow.next = None
while current is not None:
tmp = current.next
current.next = prev
prev = current
current = tmp
# Stage-3:
head1, head2 = head, prev
while head2 is not None:
tmpp = head1.next
head1.next = head2
head1 = head2
head2 = tmpp
|
Python | UTF-8 | 3,755 | 2.734375 | 3 | [] | no_license | #! /usr/bin/env python3
import sys
import unittest
# from wherever
import deco
class Tests(unittest.TestCase):
def assert2ring(self, seed, tape, reps, pats, out):
result = deco.run([str(seed), tape, str(reps), *pats])
output = '\n'.join(out) + '\n'
self.assertEqual(result.returncode, 0)
self.assertEqual(result.stderr, '')
self.assertEqual(result.stdout, output)
def test_usage(self):
result = deco.run([])
self.assertEqual(result.returncode, 1)
self.assertEqual(result.stdout, 'USAGE: ' + deco.PATH + ' [seed] [tape] [iters] [src:dst ...]\n')
self.assertEqual(result.stderr, '')
def test_bad_seed(self):
result = deco.run(['blue', '[...]', '3', '.:..'])
self.assertEqual(result.returncode, 101)
self.assertEqual(result.stdout, '')
self.assertIn(
'Seed must be a number.',
result.stderr
)
def test_bad_reps(self):
result = deco.run(['7', '[...]', 'cats', '.:..'])
self.assertEqual(result.returncode, 101)
self.assertEqual(result.stdout, '')
self.assertIn(
'Iters must be a number.',
result.stderr
)
def test_bad_pat1(self):
result = deco.run(['2', '[...]', '4', 'blah'])
self.assertEqual(result.returncode, 1)
self.assertEqual(result.stderr, '')
self.assertIn(
'Invalid pair: blah',
result.stdout
)
def test_bad_pat2(self):
result = deco.run(['9', '[...]', '5', 'a:b:c'])
self.assertEqual(result.returncode, 1)
self.assertEqual(result.stderr, '')
self.assertIn(
'Invalid pair: a:b:c',
result.stdout
)
def test_2ring0(self):
self.assert2ring(1, 'B', 7, ['A:B'], [
'B'
])
def test_2ring1(self):
self.assert2ring(19, 'A', 4, ['A:AA'], [
'A',
'AA',
'AAA',
'AAAA',
'AAAAA'
])
def test_2ring2(self):
self.assert2ring(57, 'QQQQQ', 4, ['QQ:Q'], [
'QQQQQ',
'QQQQ',
'QQQ',
'QQ',
'Q'
])
def test_2ring3(self):
self.assert2ring(12, 'AAABBB', 50, ['AB:BA'], [
'AAABBB',
'AABABB',
'ABAABB',
'BAAABB',
'BAABAB',
'BAABBA',
'BABABA',
'BABBAA',
'BBABAA',
'BBBAAA'
])
def test_2ring4(self):
self.assert2ring(19, 'XXXXX', 50, ['X:O', 'X:+'], [
'XXXXX',
'+XXXX',
'+XXOX',
'+XXO+',
'++XO+',
'++OO+'
])
def test_2ring5(self):
pats = ['=<:<=', '-<:>=', '>=:=>', '>-:=<']
self.assert2ring(88, '[-----<-----]', 25, pats, [
'[-----<-----]',
'[---->=-----]',
'[----=>-----]',
'[----==<----]',
'[----=<=----]',
'[----<==----]',
'[--->===----]',
'[---=>==----]',
'[---==>=----]',
'[---===>----]',
'[---====<---]',
'[---===<=---]',
'[---==<==---]',
'[---=<===---]',
'[---<====---]',
'[-->=====---]',
'[--=>====---]',
'[--==>===---]',
'[--===>==---]',
'[--====>=---]',
'[--=====>---]',
'[--======<--]',
'[--=====<=--]',
'[--====<==--]',
'[--===<===--]',
'[--==<====--]'
])
if __name__ == '__main__':
deco.main(sys.argv)
|
C++ | UTF-8 | 1,197 | 2.9375 | 3 | [] | no_license | class Solution {
public:
void merge(int A[], int m, int B[], int n) {
if (m == 0){
for(int i = 0; i < n; i++)
A[i] = B[i];
return;
}
int indexA = m - 1;
int indexB = n - 1;
int indexNew = m + n - 1;
while (indexA >= 0 && indexB >= 0){
while(A[indexA] < B[indexB] && indexB >= 0){
A[indexNew] = B[indexB];
indexNew--;
indexB--;
}
if (indexB < 0)
break;
while(A[indexA] >= B[indexB] && indexA >= 0){
A[indexNew] = A[indexA];
indexNew--;
indexA--;
}
}
if (indexA >= 0){
while(indexA >= 0){
A[indexNew] = A[indexA];
indexNew--;
indexA--;
}
}
if (indexB >= 0){
while(indexB >= 0){
A[indexNew] = B[indexB];
indexNew--;
indexB--;
}
}
}
};
|
Markdown | UTF-8 | 1,644 | 3.109375 | 3 | [] | no_license | CS370-Project
Term project for Operating Systems course (CS 370, Spring 2020) consisting of a group of 4.
Overview:
Our project’s objective is to develop an intelligent music player that recognizes human emotions. It will take an image from a camera when a sensor is triggered. Then, a song will play corresponding to the person's emotion/mood. An example of this would be if a person is smiling then the song Happy by Will Farrell will be played. We plan on using PyTorch to create an image classifier that recognizes different human emotions.
Emotion detecting:
We’ll be using Amazon SageMaker (Amazon’s machine learning service) using AWS Python SDK (API that will give us access to AWS services) with our PyTorch model to do all the training with so that we’ll be able to detect the emotion of a person and then play the song that they’re in the mood for.
Music:
We’ll be using Volumio, a software dedicated to be a music player that will play any file type, can be connected to spotify & downloaded onto a raspberry pi. It will require a SD Card & we’ll be attaching a speaker to the raspberry pi to output the music once emotion is detected.
We want to start off by utilizing spotify’s web API which allows us to get audio analysis of a track and we can use the tempo of a song to determine if it’s happy or sad. We’ll be parsing through the user’s playlists on spotify so that it doesn’t play a random song the user hasn’t heard before.
Autonomous Camera:
We’ll be using a sensor to detect when an individual is at a certain proximity from it and take a picture.The picture will then be uploaded and processed.
|
C++ | UTF-8 | 2,422 | 3.515625 | 4 | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
] | permissive | // RUN: %clang_cc1 -std=c++20 -verify %s
// RUN: %clang_cc1 -std=c++17 -verify %s
namespace One {
char (&b(int(&&)[1]))[1]; // #1 expected-note{{too many initializers}}
char (&b(int(&&)[2]))[2]; // #2 expected-note{{too many initializers}}
void f() {
static_assert(sizeof(b({1})) == 1); // #1
static_assert(sizeof(b({1, 2})) == 2); // #2
b({1, 2, 3}); // expected-error{{no matching function}}
}
} // namespace One
namespace Two {
struct Bob {
Bob(int = 1);
};
char (&b(Bob(&&)[1]))[1]; // #1
char (&b(Bob(&&)[2]))[2]; // #2
void f() {
static_assert(sizeof(b({})) == 1); // #1
static_assert(sizeof(b({Bob()})) == 1); // #1
static_assert(sizeof(b({2, Bob()})) == 2); // #2
}
} // namespace Two
namespace Three {
struct Kevin {
Kevin(int);
};
char (&b(Kevin(&&)[2]))[2]; // #2 expected-note{{too few initializers}}
void f() {
b({2}); // #1 expected-error{{no matching function}}
}
} // namespace Three
namespace Four {
char (&b(int(&&)[1], float))[1]; // #1 expected-note{{candidate}}
char (&b(int(&&)[1], double))[2]; // #2 expected-note{{candidate}}
char (&c(float, int(&&)[1]))[1]; // #1 expected-note{{candidate}}
char (&c(double, int(&&)[1]))[2]; // #2 expected-note{{candidate}}
void f() {
b({1}, 0); // expected-error{{is ambiguous}}
c(0, {1}); // expected-error{{is ambiguous}}
}
} // namespace Four
typedef decltype(sizeof(char)) size_t;
namespace std {
// sufficient initializer list
template <class _E>
class initializer_list {
const _E *__begin_;
size_t __size_;
constexpr initializer_list(const _E *__b, size_t __s)
: __begin_(__b),
__size_(__s) {}
public:
typedef _E value_type;
typedef const _E &reference;
typedef const _E &const_reference;
typedef size_t size_type;
typedef const _E *iterator;
typedef const _E *const_iterator;
constexpr initializer_list() : __begin_(nullptr), __size_(0) {}
constexpr size_t size() const { return __size_; }
constexpr const _E *begin() const { return __begin_; }
constexpr const _E *end() const { return __begin_ + __size_; }
};
} // namespace std
namespace Five {
struct ugly {
ugly(char *);
ugly(int);
};
char (&f(std::initializer_list<char *>))[1]; // #1
char (&f(std::initializer_list<ugly>))[2]; // #2
void g() {
// Pick #2 as #1 not viable (3->char * fails).
static_assert(sizeof(f({"hello", 3})) == 2); // expected-warning{{not allow}}
}
} // namespace Five
|
C++ | UTF-8 | 1,376 | 3.53125 | 4 | [] | no_license | // Implement the Calculator class
#include "calculator.h"
#include <math.h>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
Calculator::Calculator(std::string input) {
std::regex decimalRegex("([-0-9\\.]+)");
std::smatch match;
while (std::regex_search(input, match, decimalRegex)) {
std::string decimalString = match.str();
double decimal = std::stod(decimalString);
data.push_back(decimal);
input = match.suffix();
}
}
int Calculator::getDataCount() { return data.size(); }
std::string Calculator::getDataString() {
std::string dataString;
for (int i = 0; i < data.size(); i++) {
dataString.append(std::to_string(data[i]));
if (i < data.size() - 1) {
dataString.append(" ");
}
}
return dataString;
}
double Calculator::getStandardDeviation() {
if (data.size() < 2) {
return 0;
}
double mean = getMean();
double sumOfSquares = 0;
for (int i = 0; i < data.size(); i++) {
double deviation = (data[i] - mean);
double squaredDeviation = pow(deviation, 2);
sumOfSquares += squaredDeviation;
}
double variance = sumOfSquares / (data.size() - 1);
return sqrt(variance);
}
double Calculator::getMean() {
if (data.empty()) {
return 0;
}
double mean = 0;
for (int i = 0; i < data.size(); i++) {
mean += data[i];
}
return mean / data.size();
}
|
JavaScript | UTF-8 | 1,799 | 2.84375 | 3 | [] | no_license | import React, { useState } from 'react'
import {TextField, Button} from '@material-ui/core'
import './form.css'
const Form = () => {
const addLocationHandler = () => {
setFormInputs([...formInputs, `Location ${count}`])
setCount(count + 1)
}
const deleteLocationHandler = () => {
if (count <= 3) {
alert("Minimum of 2 locations is required!")
return;
}
setFormInputs([...formInputs].slice(0, formInputs.length - 1))
setCount(count - 1)
}
const [count, setCount] = useState(3)
const [formInputs, setFormInputs] = useState(["Location 1","Location 2"])
const resultInputs = formInputs.map(i => {
return (
<div key = {i} className="input-container">
<TextField id={i} label={i} variant="outlined" fullWidth required />
</div>
)
})
return (
<div className="form">
<div className="information">
<h2>Set the locations of everyone here!</h2>
<div className="button-container">
<Button variant="contained" color="default">Find Your Eatery!</Button>
</div>
</div>
<div className="form-container">
<form noValidate autoComplete="off">
{resultInputs}
<div className="button-container">
<Button variant="outlined" color="primary" onClick={() => addLocationHandler()}>Add More Locations</Button>
</div>
<div className="button-container">
<Button variant="outlined" color="default" onClick={() => deleteLocationHandler()}>Delete Last Location</Button>
</div>
</form>
</div>
</div>
)}
export default Form
|
Markdown | UTF-8 | 2,366 | 3.125 | 3 | [] | no_license | # thrift 使用手册
## thrift介绍
RPC框架:简单的说,RPC就是从一台机器(客户端)上通过参数传递的方式调用另一台机器(服务器)上的一个函数或方法(可以统称为服务)并得到返回的结果。
用户通过Thrift的IDL(接口定义语言)来描述接口函数及数据类型,然后通过Thrift的编译环境生成各种语言类型的接口文件,用户可以根据自己的需要采用不同的语言开发客户端代码和服务器端代码。
使用thrift框架,可以屏蔽传输等一大堆中间事务,我们只需要:
1. 定义(约定)一个接口(.thrift)文件,然后用thrift生成Java类。这个类由客户端和服务端共同拥有并使用。
2. 服务端根据文件中定义的接口,做出具体的业务实现。
3. 客户端连接服务端,调用文件中的客户端的方法,拿到结果。
## 安装方法
我们统一在Java环境下进行编写。
各种环境下安装方法见[thrift官网](https://thrift.apache.org/docs/install/)。
例如在Mac下只需要:
```shell
brew install thrift
```
就可以了。
之后在Maven环境中添加thrift对应依赖,并且在工程中添加thrift生成工具即可。
## 数据类型
### 基本类型:
- bool:布尔值,true 或 false,对应 Java 的 boolean
- byte:8 位有符号整数,对应 Java 的 byte
- i16:16 位有符号整数,对应 Java 的 short
- i32:32 位有符号整数,对应 Java 的 int
- i64:64 位有符号整数,对应 Java 的 long
- double:64 位浮点数,对应 Java 的 double
- string:utf-8编码的字符串,对应 Java 的 String
### 结构体类型:
- struct:定义公共的对象,类似于 C 语言中的结构体定义,在 Java 中是一个JavaBean
### 集合类型:
- list:对应 Java 的 ArrayList
- set:对应 Java 的 HashSet
- map:对应 Java 的 HashMap
### 异常类型(基本用不到):
- exception:对应 Java 的 Exception
### 服务类型:
- service:对应服务的类
### 命名空间:
- thrift的命名空间相当于Java中的package,主要目的是组织代码。
```thrift
namespace java com.xxx.thrift
```
### 文件包含
- 文件包含
Thrift也支持文件包含,相当于C/C++中的include,Java中的import。
```thrift
include "xxx.thrift"
```
|
Java | UTF-8 | 300 | 2.046875 | 2 | [] | no_license | package es.uam.eps.ads.p4.Exceptions;
public class UsuarioNoRelevante extends Exception {
private static final long serialVersionUID = 919937515513416439L;
public UsuarioNoRelevante() {
}
@Override
public String toString() {
return "Relevant items cannot be empty";
}
}
|
Python | UTF-8 | 466 | 3.234375 | 3 | [] | no_license | from Crypto.Cipher import AES
pad = b" "
print(pad)
obj = AES.new("This is a key123", AES.MODE_CBC, "This is an IV456")
message = input("Enter a message to encrypt: ")
plaintext = message.encode("utf-8")
print(plaintext)
length = 16 - (len(plaintext)%16)
print(length)
plaintext += length*pad
print(plaintext)
ciphertext = obj.encrypt(plaintext)
print(ciphertext)
obj2 = AES.new("This is a key123", AES.MODE_CBC, "This is an IV456")
print(obj2.decrypt(ciphertext))
|
Java | UTF-8 | 831 | 2.0625 | 2 | [] | no_license | package com.praksa.musicexplorer.model;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Table(name="tbl_like_album")
@NoArgsConstructor
public class LikeAlbum {
@EmbeddedId
@Getter @Setter private LikeAlbumId id;
@ManyToOne(fetch = FetchType.EAGER)
@MapsId("user_id")
@JoinColumn(name = "user_id")
@Getter @Setter private User user;
@ManyToOne(fetch = FetchType.EAGER)
@MapsId("album_id")
@JoinColumn(name = "album_id")
@Getter @Setter private Album album;
public LikeAlbum(LikeAlbumId id) {
super();
this.id = id;
}
}
|
PHP | UTF-8 | 4,245 | 2.71875 | 3 | [] | no_license | <!DOCTYPE html>
<?php
session_start();
function swap(&$x,&$y) {
$tmp=$x;
$x=$y;
$y=$tmp;
}
if(!isset($_SESSION['loadCounter'])){
$_SESSION['loadCounter'] = 1;
}
if(isset($_POST['checkoff'])){
if(count($_SESSION['actions']) == 1)
{
array_pop($_SESSION['actions']);
}
else{
unset($_SESSION['actions'][$_POST['checkoff']]);
$_SESSION['actions'] = array_values($_SESSION['actions']);
// swap($_SESSION['actions'][$_POST['checkoff']], $_SESSION['actions'][count($_SESSION['actions'])-1]);
// array_pop($_SESSION['actions']);
}
// unset($_SESSION['actions'][(int)$_POST['checkoff']]);
}
if(!isset($_SESSION['actions'])){
$_SESSION['actions'] = array();
// array_pop($_SESSION['actions']);
}
if(isset($_POST['item']) && isset($_POST['priority'])){
if($_POST['item']!= ""){
// array_push($_SESSION['actions'], $_POST['item']);
$temp = array('action' => $_POST['item'], 'priority' => $_POST['priority']);
array_push($_SESSION['actions'], $temp);
// print_r($_SESSION['actions']);
}
unset($_POST['item']);
}
else{
if(!isset($_POST['up']) && !isset($_POST['checkoff'])){
// print($_SESSION['loadCounter']);
if($_SESSION['loadCounter'] != 1){
echo "<h1 id='errormsg'>ERROR! both the action and priority must be set</h1>";
$_SESSION['loadCounter']++;
}
else{
$_SESSION['loadCounter']++;
}
}
}
if(isset($_POST['up'])){
shuffle($_SESSION['actions']);
}
?>
<html>
<head>
<title>to-do list</title>
<style type="text/css">
@import url("./styles.css");
</style>
<link href="https://fonts.googleapis.com/css?family=Slabo+27px" rel="stylesheet">
</head>
<body>
<header>TO-DO LIST</header>
<hr width="50%">
<br><br>
<form id="addAction" method="post">
<label for="item" style="font-size: 26px;">Add Action to List</label><br>
<input type="text" name="item" placeholder="action">
<input type="submit" value="add">
<br><br>
<label for="priority">Priority:</label>
<select name="priority">
<option value="" selected disabled hidden>select priority</option>
<option value="Max (!!!!)">Max (!!!!)</option>
<option value="High (!!!)">High (!!!)</option>
<option value="Medium (!!)">Medium (!!)</option>
<option value="Low (!)">Low (!)</option>
</select>
</form>
<h4>List</h4>
<div id="listContest">
<table id="listTable">
<tbody>
<tr>
<td id="head1">check off action</td>
<td id="head2">to-do action</td>
<td id="head3">Priority</td>
</tr>
<?php
if(isset($_SESSION['actions']) && !empty($_SESSION['actions'])){
for($i = 0; $i < sizeof($_SESSION['actions']); $i++){ ?>
<tr>
<td>
<form method="post">
<?php echo "<input type='hidden' id = 'checked' name='checkoff' value = $i />";
echo "<button>check</button>";?>
</form>
</td>
<?php echo "<td>".$_SESSION['actions'][$i]['action']."</td>"; ?>
<?php echo "<td>".$_SESSION['actions'][$i]['priority']."</td>"; ?>
</tr>
<?php }
} ?>
</tbody>
</table>
<!--<input type="radio" id = "checked" name="do" value = "check"/>-->
<br><br>
<form id="update" method="post">
<input type="submit" name="up" value="suffle list"/>
</form>
</div>
</body>
</html> |
Markdown | UTF-8 | 3,133 | 3.25 | 3 | [
"MIT"
] | permissive | # Pimple IoC
Class resolver for the [Pimple](http://pimple.sensiolabs.org/) container.
This project is heavily inspired by how [Laravel](http://laravel.com/) resolve it's classes out of their IoC container. In fact most of the code is taken directly from their ```Container``` class.
## Installation
Add the IoC container to your ```composer.json``` using the command line.
```
composer require jonsa/pimple-ioc
```
## Usage
The class resolver is registered in Pimple as a ```ServiceProvider```
```php
use Jonsa\PimpleResolver\ServiceProvider;
use Pimple\Container;
$container = new Container();
$container->register(new ServiceProvider());
```
This will register the ```make``` key on the Container which resolves the requested class.
```php
$instance = $container['make']('Acme\MyClass');
```
and the ```bind``` key to bind a definition to a concrete implementation
```php
$container['bind']('Acme\MyInterface', 'Acme\MyClass');
```
### Resolved recursively
Class dependencies are resolved recursively.
```php
interface FooContract {}
class Foo implements FooContract {};
class Bar {
public function __construct(FooContract $foo) {}
}
class Baz {
public function __construct(Bar $bar) {}
}
$container['bind']('FooContract', 'FooClass');
$baz = $container['make']('Baz');
```
### Define constructor parameters
To override a class parameter use the parameter array on the resolver method.
```php
class Log {
public function __construct(Psr\Log\LoggerInterface $logger, $level = Psr\Log\LogLevel::WARNING)
{
...
}
}
$container['make']('Log', array(
'level' => Psr\Log\LogLevel::DEBUG
));
```
### Inject into the resolver workflow
To customize a resolved class before it is returned from the resolver, simply listen to the ```CLASS_RESOLVED``` event.
```php
use Jonsa\PimpleResolver\ServiceProvider;
use Jonsa\PimpleResolver\Events;
use Symfony\Component\EventDispatcher\EventDispatcher;
$dispatcher = new EventDispatcher;
$container[ServiceProvider::EVENT_DISPATCHER] = function () use ($dispatcher) {
return $dispatcher;
});
$dispatcher->addListener(Events::CLASS_RESOLVED, function (ClassResolvedEvent $event) {
$object = $event->getResolvedObject();
...
});
```
Alternatively the ```EVENT_DISPATCHER``` key can be populated with a string which in turn returns an event dispatcher from the container
```php
$container[ServiceProvider::EVENT_DISPATCHER] = 'my dispatcher key';
```
## Configuration
The ServiceProvider has three configuration parameters.
```php
class ServiceProvider implements ServiceProviderInterface {
public function __construct($bindContainerInstance = true, $makeMethod = 'make', $bindMethod = 'bind')
{
...
}
}
```
```$bindContainerInstance``` tells the ServiceProvider whether to bind the container instance to the ```'Pimple\Container'``` key. If the container is extended, that class name will also be bound to the container instance.
```$makeMethod``` is used to define which key on the container to be used as the make method.
```$bindMethod``` is used to define which key on the container to be used as the bind method.
|
Java | UTF-8 | 164 | 1.882813 | 2 | [] | no_license | package com.cg.eis.service;
import com.cg.eis.beans.Employee;
public interface EmployeeServiceInterface {
abstract String schemeGenerator(int salary);
}
|
TypeScript | UTF-8 | 1,389 | 2.75 | 3 | [] | no_license | import { Component, OnInit } from '@angular/core';
import { ValidatorFn, FormControl } from 'reactive-forms-module2-proposal';
// regex from https://www.regextester.com/96683
const dateRegex = /^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))$/;
const dateValidatorFn: ValidatorFn = control => {
if (!dateRegex.test(control.value)) {
return {
invalidDate: 'Invalid date format! Try YYYY-MM-DD',
};
}
return null;
};
function dateToString(date: Date | null) {
if (!date) return '';
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${padString(month)}-${padString(day)}`;
}
function padString(int: number) {
return int < 10 ? `0${int}` : `${int}`;
}
function stringToDate(text: string) {
if (!dateRegex.test(text)) return null;
const parts = text.split('-');
const date = new Date(2010, 0, 1);
date.setFullYear(parseInt(parts[0], 10));
date.setMonth(parseInt(parts[1], 10) - 1);
date.setDate(parseInt(parts[2], 10));
return date;
}
@Component({
selector: 'app-example-three',
templateUrl: './example-three.component.html',
styleUrls: ['./example-three.component.scss'],
})
export class ExampleThreeComponent {
controlA = new FormControl<Date | null>(null);
stringToDate = stringToDate;
dateToString = dateToString;
dateValidatorFn = dateValidatorFn;
}
|
Swift | UTF-8 | 1,123 | 2.6875 | 3 | [] | no_license | //
// ViewController.swift
// DemoTelCall
//
// Created by zj-db0465 on 15/10/10.
// Copyright © 2015年 icetime17. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.call10086()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// self.call10086()
}
func call10086() {
let number: String = "10086"
// let url: NSURL = NSURL(string: "tel://\(number)")! // 直接拨打。
let url: NSURL = NSURL(string: "telprompt://\(number)")! // 有呼叫提示
if (UIApplication.sharedApplication().canOpenURL(url)) {
UIApplication.sharedApplication().openURL(url)
}
}
}
|
Java | UTF-8 | 6,720 | 2.859375 | 3 | [] | no_license | package abd;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Workload {
/** Instance variables **/
private final Random rand;
private static final int populate_size = 5000;
private final Connection c;
/**
* Parametrized constructor
* @param rand Random
* @param c Connection
* @throws Exception Connection exception
*/
public Workload(Random rand, Connection c) throws Exception {
this.rand = rand;
this.c = c;
//---- DEMO WORKLOAD ----
// initialize connection, e.g. c.setAutoCommit(false);
// or create prepared statements...
//-----------------------
}
/* ------------------------------------------------------------------------------------------------------------- */
/**
* Create database tables
* @param c Connection
*/
private static void tables(Connection c) throws SQLException {
Statement s = c.createStatement();
/* sql statements */
String client = "CREATE TABLE Client (" +
"id SERIAL , " +
"name VARCHAR(255), " +
"address VARCHAR(255), " +
"PRIMARY KEY(id)" +
")";
String product = "CREATE TABLE Product (" +
"id SERIAL , " +
"description VARCHAR(255), " +
"stock INT not NULL, " +
"min INT not NULL, " +
"max INT not NULL, " +
"PRIMARY KEY(id) " +
")";
String invoice = "CREATE TABLE Invoice (" +
"id SERIAL , " +
"clientID INTEGER , " +
"PRIMARY KEY(id), " +
"FOREIGN KEY(clientID) REFERENCES Client(id)" +
")";
String invoice_line = "CREATE TABLE InvoiceLine (" +
"id SERIAL, " +
"invoiceID INT , " +
"productID INT, " +
"PRIMARY KEY(id), " +
"FOREIGN KEY(invoiceID) REFERENCES Invoice(id), " +
"FOREIGN KEY(productID) REFERENCES Product(id) " +
")";
String order = "CREATE TABLE Orders(" +
"id SERIAL , " +
"productID INT , " +
"supplier VARCHAR(256), " +
"items INT not NULL, " +
"PRIMARY KEY(id), " +
"FOREIGN KEY(productID) REFERENCES Product(id) " +
")";
s.executeUpdate( client );
s.executeUpdate( product );
s.executeUpdate( invoice );
s.executeUpdate( invoice_line );
s.executeUpdate( order );
s.close();
}
/**
* Insert values in database tables
* @param c Connection
* @throws SQLException SQL Query Exception
*/
private static void insert(Connection c) throws SQLException {
Random r = new Random();
String clients = "INSERT INTO Client(name, address) VALUES (?,?)";
String products = "INSERT INTO Product(description, stock, min, max) VALUES (?,?,?,?)";
PreparedStatement client_record = c.prepareStatement(clients);
PreparedStatement product_record = c.prepareStatement(products);
for(int i = 0 ; i < populate_size ; i++){
/* insert clients */
client_record.setString(1,"Name " + i);
client_record.setString(2,"Address " + i);
client_record.addBatch();
/* insert products */
int max = r.nextInt(20);
int min = r.nextInt(max > 1 ? max - 1 : 1);
int stock = r.nextInt(max > 0 ? max : 1);
product_record.setString(1,"Product " + i);
product_record.setInt( 2, stock );
product_record.setInt( 3, min );
product_record.setInt( 4, max );
product_record.addBatch();
}
/* execute batches */
client_record.executeBatch();
product_record.executeBatch();
/* close connections */
client_record.close();
product_record.close();
}
/**
* Drops database schema
* @param c Connection
* @throws SQLException
*/
public static void dropSchema(Connection c) throws SQLException {
try{
Statement s = c.createStatement();
String dropSchema = "DROP SCHEMA IF EXISTS public CASCADE;";
String setSchema = "CREATE SCHEMA public; " +
"GRANT ALL ON SCHEMA public TO public;";
s.executeUpdate(dropSchema);
s.executeUpdate(setSchema);
s.close();
}catch (SQLException sql){
sql.printStackTrace();
}
}
public static void populate(Random rand, Connection c) throws Exception {
Statement s = c.createStatement();
//---- DEMO WORKLOAD ----
tables( c );
insert( c );
//-----------------------
s.close();
}
public void transaction() throws Exception {
Statement s = c.createStatement();
String account = "SELECT DISTINCT P.name FROM Product as P " +
"JOIN Invoice AS I ON P.id=I.productID " +
"JOIN Client AS C ON I.clientID = ?";
String top10 = "SELECT P.name, count(P.id) FROM Product as P " +
"JOIN Invoice AS I ON I.productID=P.id " +
"GROUP BY P.name " +
"ORDER BY COUNT(P.id) DESC LIMIT 10";
switch(rand.nextInt(2)) {
// sell
case 0:
List<Integer> prods;
int r = rand.nextInt(30);
int n = r > 0 ? r : 1;
prods = IntStream.range( 0, n )
.mapToObj( i -> rand.nextInt( populate_size ) )
.collect( Collectors.toList() );
int cli = rand.nextInt(populate_size);
cli = cli > 0 ? cli : 1;
// insert into invoice : cli -> inv
break;
case 1:
ResultSet rs = s.executeQuery("select * from demo");
while(rs.next())
;
break;
}
//-----------------------
s.close();
}
} |
Markdown | UTF-8 | 650 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | [leakcanary-android-core](../index.md) / [leakcanary](index.md) / [<no name provided>](./-no name provided-.md)
# <no name provided>
`fun <no name provided>(): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html)
Listener set in [LeakCanary.Config](-leak-canary/-config/index.md) and called by LeakCanary on a background thread when the
heap analysis is complete.
This is a functional interface with which you can create a [OnHeapAnalyzedListener](-on-heap-analyzed-listener/index.md) from a lambda.
Usage:
``` kotlin
val listener = OnHeapAnalyzedListener { heapAnalysis ->
process(heapAnalysis)
}
```
|
C | UTF-8 | 243 | 3.40625 | 3 | [] | no_license | #include<stdio.h>
void swap(int *, int *);
void swap(int *x,int *y)
{
*x=*x^*y;
*y=*x^*y;
*x=*x^*y;
}
int main()
{
int x=10,y=20;
printf("\nbefore swap x=%d,y=%d",x,y);
swap(&x,&y);
printf("\nafter swap x=%d,y=%d",x,y);
return 0;
}
|
C++ | UTF-8 | 1,649 | 3.359375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void dfs(vector<vector<int> > &adj_list, int node, vector<bool> &visited,unordered_set<int>* single_component)
{
if(visited[node]) return;
visited[node] = true;
single_component->insert(node);
vector<int> adj_nodes = adj_list[node];
for (int neighbour : adj_nodes)
{
dfs(adj_list, neighbour, visited, single_component);
}
}
unordered_set<unordered_set<int> * > get_connected_components(vector<vector<int> > &adj_list, int num_nodes)
{
vector<bool> visited(num_nodes + 1, false);
unordered_set<unordered_set<int> *> all_components;
for ( int node = 1 ; node <= num_nodes ; node += 1)
{
unordered_set<int> *single_component = new unordered_set<int>();
dfs(adj_list,node, visited , single_component);
if (single_component->size() > 0)
{
all_components.insert(single_component);
}
}
return all_components;
}
int main(int argc, char const *argv[])
{
int num_nodes;
cin >> num_nodes;
vector<vector<int> > adj_list(num_nodes + 1);
int egde_count;
cin >> egde_count;
for (int edge = 1; edge <= egde_count ; edge += 1)
{
int v1, v2;
cin >> v1 >> v2;
adj_list[v1].push_back(v2);
adj_list[v2].push_back(v1);
}
unordered_set<unordered_set<int> * > connected_components = get_connected_components(adj_list, num_nodes);
unordered_set<unordered_set<int>*>::iterator it = connected_components.begin();
while(it != connected_components.end())
{
unordered_set<int>* component = *it;
unordered_set<int>::iterator it2 = component->begin();
while (it2 != component->end())
{
cout << *(it2) << " ";
it2++;
}
cout << endl;
it++;
}
return 0;
} |
Ruby | UTF-8 | 605 | 3.59375 | 4 | [] | no_license | class Rotor
# initialiser les rotor avec un row
def initialize(row)
@row = row
end
ALPHABET = ('a'..'z').to_a
def rotor_combination
Hash[ ALPHABET.zip(permutator)]
end
def permutator
generated_alphabet = []
ALPHABET.each do |letter|
if (letter.ord + @row) < 123 && (letter.ord + @row) > 96
generated_alphabet << (letter.ord + @row).chr
else
generated_alphabet << (letter.ord + @row - 123 + 97 ).chr
end
end
generated_alphabet
end
end
rotor = Rotor.new(2)
#
# p Rotor::ALPHABET
# p rotor.permutator
# p rotor.rotor_combination
|
C++ | UTF-8 | 415 | 2.796875 | 3 | [] | no_license | #define LEXER_H
#include <stdio.h>
#include <iostream>
#include <vector>
#include <stdlib.h>
#include "Token.h"
class Lexer {
char c;
// Wrapper that checks sigle character tokens
// ( '+', '-', '('... etc )
Token checkToken(char tok);
public:
// Initialize c as NULL
Lexer () : c('\0') { };
// Returns the next token, error token
// if token was invalid
Token nextToken();
};
|
C++ | UTF-8 | 1,509 | 2.671875 | 3 | [] | permissive | // This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
#include "caf/detail/comparable.hpp"
#include <string>
namespace caf {
/// Unit is analogous to `void`, but can be safely returned, stored, etc.
/// to enable higher-order abstraction without cluttering code with
/// exceptions for `void` (which can't be stored, for example).
struct unit_t : detail::comparable<unit_t> {
constexpr unit_t() noexcept = default;
constexpr unit_t(const unit_t&) noexcept = default;
constexpr unit_t& operator=(const unit_t&) noexcept = default;
template <class T>
explicit constexpr unit_t(T&&) noexcept {
// nop
}
static constexpr int compare(const unit_t&) noexcept {
return 0;
}
template <class... Ts>
constexpr unit_t operator()(Ts&&...) const noexcept {
return {};
}
};
static constexpr unit_t unit = unit_t{};
/// @relates unit_t
template <class Processor>
void serialize(Processor&, const unit_t&, unsigned int) {
// nop
}
/// @relates unit_t
inline std::string to_string(const unit_t&) {
return "unit";
}
template <class T>
struct lift_void {
using type = T;
};
template <>
struct lift_void<void> {
using type = unit_t;
};
template <class T>
struct unlift_void {
using type = T;
};
template <>
struct unlift_void<unit_t> {
using type = void;
};
} // namespace caf
|
Markdown | UTF-8 | 642 | 2.625 | 3 | [] | no_license | # finalportfolio2021spring
This is the final for my visual argument which I turned into a series. Attached in this file is the feedback from people from that workshop day in class. I have also provided screenshots of the work that was made before for the website. I have also linked the sources in here for the visual argument, and the website. Although the website now has a sources page. I had a lot of fun finishing up these projects and I hope that you enjoy the works as well.
Here is the link to the live website! <a href="https://reaial.github.io/finalportfolio2021spring/">https://reaial.github.io/finalportfolio2021spring/</a>
|
PHP | UTF-8 | 1,202 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php require('../includes/header.inc.php'); ?>
<?php $this->renderBegin(); ?>
<div id="instructions">
<h1>The Four-Function Calculator: Our First Simple Application</h1>
<p>We can combine this understanding of statefulness and events to make our first simple
QCubed Forms application.</p>
<p>This calculator is just a collection of two <strong>TextBox</strong> objects (one for each operand), a
<strong>ListBox</strong> object containing the four arithmetic functions, a <strong>Button</strong> object to execute
the operation, and a <strong>Label</strong> to view the result.</p>
<p>Note that there is no validation, checking, etc. currently in this Form. Any string data
will be parsed by PHP to see if there is any numeric data, and if not, it will be parsed as 0. Dividing
by zero will throw a PHP error.</p>
</div>
<div id="demoZone">
<p>Value 1: <?php $this->txtValue1->render(); ?></p>
<p>Value 2: <?php $this->txtValue2->render(); ?></p>
<p>Operation: <?php $this->lstOperation->render(); ?></p>
<?php $this->btnCalculate->render(); ?>
<hr/>
<?php $this->lblResult->render(); ?>
</div>
<?php $this->renderEnd(); ?>
<?php require('../includes/footer.inc.php'); ?> |
Python | UTF-8 | 10,413 | 2.8125 | 3 | [] | no_license | from ..methods import BaseMethod
class sendSticker(BaseMethod):
"""Use this method to send static .WEBP or animated .TGS stickers. On success, the sent Message is returned.
Parameters
----------
chat_id : Integer or String
Unique identifier for the target chat or username of the target channel (in the format @channelusername)
sticker : InputFile or String
Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files �
disable_notification : Boolean, optional
Sends the message silently. Users will receive a notification with no sound.
reply_to_message_id : Integer, optional
If the message is a reply, ID of the original message
reply_markup : InlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReply, optional
Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user.
"""
def __init__(self,
chat_id,
sticker,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None,
propagate_values: bool = False,
propagate_fields: dict = None):
super().__init__(propagate_values=propagate_values, propagate_fields=propagate_fields)
self.chat_id = chat_id
self.sticker = sticker
self.disable_notification = disable_notification
self.reply_to_message_id = reply_to_message_id
self.reply_markup = reply_markup
class getStickerSet(BaseMethod):
"""Use this method to get a sticker set. On success, a StickerSet object is returned.
Parameters
----------
name : String
Name of the sticker set
"""
def __init__(self,
name,
propagate_values: bool = False,
propagate_fields: dict = None):
super().__init__(propagate_values=propagate_values, propagate_fields=propagate_fields)
self.name = name
class uploadStickerFile(BaseMethod):
"""Use this method to upload a .PNG file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
Parameters
----------
user_id : Integer
User identifier of sticker file owner
png_sticker : InputFile
PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. More info on Sending Files �
"""
def __init__(self,
user_id,
png_sticker,
propagate_values: bool = False,
propagate_fields: dict = None):
super().__init__(propagate_values=propagate_values, propagate_fields=propagate_fields)
self.user_id = user_id
self.png_sticker = png_sticker
class createNewStickerSet(BaseMethod):
"""Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. You must use exactly one of the fields png_sticker or tgs_sticker. Returns True on success.
Parameters
----------
user_id : Integer
User identifier of created sticker set owner
name : String
Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in �_by_<bot username>�. <bot_username> is case insensitive. 1-64 characters.
title : String
Sticker set title, 1-64 characters
png_sticker : InputFile or String, optional
PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files �
tgs_sticker : InputFile, optional
TGS animation with the sticker, uploaded using multipart/form-data. See https://core.telegram.org/animated_stickers#technical-requirements for technical requirements
emojis : String
One or more emoji corresponding to the sticker
contains_masks : Boolean, optional
Pass True, if a set of mask stickers should be created
mask_position : MaskPosition, optional
A JSON-serialized object for position where the mask should be placed on faces
"""
def __init__(self,
user_id,
name,
title,
emojis,
png_sticker=None,
tgs_sticker=None,
contains_masks=None,
mask_position=None,
propagate_values: bool = False,
propagate_fields: dict = None):
super().__init__(propagate_values=propagate_values, propagate_fields=propagate_fields)
self.user_id = user_id
self.name = name
self.title = title
self.png_sticker = png_sticker
self.tgs_sticker = tgs_sticker
self.emojis = emojis
self.contains_masks = contains_masks
self.mask_position = mask_position
class addStickerToSet(BaseMethod):
"""Use this method to add a new sticker to a set created by the bot. You must use exactly one of the fields png_sticker or tgs_sticker. Animated stickers can be added to animated sticker sets and only to them. Animated sticker sets can have up to 50 stickers. Static sticker sets can have up to 120 stickers. Returns True on success.
Parameters
----------
user_id : Integer
User identifier of sticker set owner
name : String
Sticker set name
png_sticker : InputFile or String, optional
PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files �
tgs_sticker : InputFile, optional
TGS animation with the sticker, uploaded using multipart/form-data. See https://core.telegram.org/animated_stickers#technical-requirements for technical requirements
emojis : String
One or more emoji corresponding to the sticker
mask_position : MaskPosition, optional
A JSON-serialized object for position where the mask should be placed on faces
"""
def __init__(self, user_id,
name,
emojis,
png_sticker=None,
tgs_sticker=None,
mask_position=None,
propagate_values: bool = False,
propagate_fields: dict = None):
super().__init__(propagate_values=propagate_values, propagate_fields=propagate_fields)
self.user_id = user_id
self.name = name
self.png_sticker = png_sticker
self.tgs_sticker = tgs_sticker
self.emojis = emojis
self.mask_position = mask_position
class setStickerPositionInSet(BaseMethod):
"""Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.
Parameters
----------
sticker : String
File identifier of the sticker
position : Integer
New sticker position in the set, zero-based
"""
def __init__(self,
sticker,
position,
propagate_values: bool = False,
propagate_fields: dict = None):
super().__init__(propagate_values=propagate_values, propagate_fields=propagate_fields)
self.sticker = sticker
self.position = position
class deleteStickerFromSet(BaseMethod):
"""Use this method to delete a sticker from a set created by the bot. Returns True on success.
Parameters
----------
sticker : String
File identifier of the sticker
"""
def __init__(self,
sticker,
propagate_values: bool = False,
propagate_fields: dict = None):
super().__init__(propagate_values=propagate_values, propagate_fields=propagate_fields)
self.sticker = sticker
class setStickerSetThumb(BaseMethod):
"""Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success.
Parameters
----------
name : String
Sticker set name
user_id : Integer
User identifier of the sticker set owner
thumb : InputFile or String, optional
A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size; see https://core.telegram.org/animated_stickers#technical-requirements for animated sticker technical requirements. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files �. Animated sticker set thumbnail can't be uploaded via HTTP URL.
"""
def __init__(self,
name,
user_id,
thumb=None,
propagate_values: bool = False,
propagate_fields: dict = None):
super().__init__(propagate_values=propagate_values, propagate_fields=propagate_fields)
self.name = name
self.user_id = user_id
self.thumb = thumb |
Java | UTF-8 | 869 | 2.234375 | 2 | [] | no_license | import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class JUnit extends User{
private String testname;
@Test
public void testSetname() {
User test=new User();
test.userName="abc";
assertEquals("abc",test.getUserName());
test.userName="aaa";
assertEquals("aaa",test.getUserName());
}
@Test
public void setPassword(){
User test1=new User();
assertEquals("",test1.passWord);
}
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingFolder()throws IOException{
File createdFolder = folder.newFolder("rw");
File createdFile = folder.newFile("UserData.txt");
asserTure(createdFile.exists());
}
private void asserTure(boolean exists) {
// TODO Auto-generated method stub
}
}
|
Java | UTF-8 | 576 | 3.890625 | 4 | [] | no_license | public class Main {
public static void main(String[] args) {
int result = 10 + 20;
// ' // ' is a single line comment
// ' = ' is a assignment operator
System.out.println("The result of 10 + 20 :"+result);
result *= 10;
System.out.println("result of ( 10+20 )*10 :"+result);
result /= 10;
System.out.println("result of ( 10+20 )/10 :"+result);
int resultRemainder = result % 10; // this will give us the remainder
System.out.println("remainder of ( 10+20 )/10 :"+resultRemainder);
}
}
|
C | UTF-8 | 356 | 3.390625 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int n,y = 0,m = 0,d = 0;
scanf("%d",&n);
if(n >= 365)
{
y = y + n /365;
n = n % 365;
}
if(n >= 30)
{
m = m+ n/30;
n = n % 30;
}
if(n >= 0)
{
d = d +n;
}
printf("%d years\n%d months\n%d days",y,m,d);
return 0;
}
|
PHP | UTF-8 | 2,051 | 2.9375 | 3 | [] | no_license | <?php
class Ampersand_BinPack_Output
{
protected $_bins;
/**
* @param Ampersand_BinPack_State $state
* @return Ampersand_BinPack_Output
* @author Josh Di Fabio <josh.difabio@ampersandcommerce.com>
*/
public static function factory(Ampersand_BinPack_State $state)
{
$output = new Ampersand_BinPack_Output();
$output->_setBins($state->getBins());
return $output;
}
/**
* @param array $bins
* @return void
* @author Josh Di Fabio <josh.difabio@ampersandcommerce.com>
*/
protected function _setBins(array $bins)
{
$this->_bins = array();
foreach ($bins as $_bin) {
if ($_bin->getItems()) {
$this->_bins[] = $_bin;
}
}
}
/**
* @return int
* @author Josh Di Fabio <josh.difabio@ampersandcommerce.com>
*/
public function getNrOfBins()
{
return count($this->_bins);
}
/**
* @param bool $withQuantities OPTIONAL
* @return array
* @author Josh Di Fabio <josh.difabio@ampersandcommerce.com>
*/
public function getAssignments($withQuantities = false)
{
$assignments = array();
$methodName = $withQuantities ? 'getItemQuantities' : 'getItemIdentifiers';
foreach ($this->_bins as $_bin) {
$assignments[] = $_bin->$methodName();
}
return $assignments;
}
/**
* @return array
* @author Josh Di Fabio <josh.difabio@ampersandcommerce.com>
*/
public function getAssignmentStats()
{
$stats = array(
'nr_of_bins' => count($this->_bins),
'volume_used_pct_normalised' => 0,
'bins' => array(),
);
foreach ($this->_bins as $_bin) {
$_stats = $_bin->getStats();
$stats['bins'][] = $_bin->getStats();
$stats['volume_used_pct_normalised'] += $_stats['volume_used_pct_normalised'];
}
$stats['volume_used_pct_normalised'] /= count($this->_bins);
return $stats;
}
} |
C++ | UTF-8 | 1,211 | 2.734375 | 3 | [] | no_license | #include "Methods.h"
#include <iostream>
#include <jni.h>
#include <string.h>
JNIEXPORT void JNICALL
Java_Methods_accessConstructor(JNIEnv* env, jobject obj)
{
jmethodID mid;
jclass cls = env->GetObjectClass(obj);
mid = env->GetMethodID(cls, "<init>", "(Ljava/lang/String;)V");
if (mid ==NULL){
return;
}
jstring s = env->NewStringUTF("C++");
env->CallVoidMethod(obj, mid, s);
}
JNIEXPORT void JNICALL
Java_Methods_accessStaticMethod(JNIEnv* env, jobject obj)
{
jmethodID mid;
jclass cls = env->GetObjectClass(obj);
mid = env->GetStaticMethodID(cls, "intSumStatic", "(II)I");
if (mid ==NULL){
return;
}
int s = env->CallStaticIntMethod(cls, mid, 5, 7);
}
JNIEXPORT void JNICALL
Java_Methods_accessInstanceMethod(JNIEnv* env, jobject obj)
{
jmethodID mid;
jclass cls = env->GetObjectClass(obj);
mid = env->GetMethodID(cls, "recSendString",
"(Ljava/lang/String;)Ljava/lang/String;");
if (mid ==NULL){
return;
}
jstring s = env->NewStringUTF("Hello from C++");
jstring str = (jstring) env->CallObjectMethod(obj, mid, s);
const char* cstr = env->GetStringUTFChars(str, NULL);
}
|
Java | UTF-8 | 2,134 | 2.21875 | 2 | [] | no_license | package com.ndrmf.complaint.model;
import java.time.LocalDateTime;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.ndrmf.user.model.User;
@Entity
@Table(name="complaint_review")
public class ComplaintReview {
private UUID id;
private Complaint complaintRef;
private User userRef;
private LocalDateTime dateTime;
private String comments;
private boolean isSatisfied;
public ComplaintReview() {}
public ComplaintReview(UUID id, Complaint complaintRef, User userRef, LocalDateTime dateTime, String remarks,boolean isSatisfied) {
super();
this.id = id;
this.complaintRef = complaintRef;
this.userRef = userRef;
this.dateTime = dateTime;
this.comments = remarks;
this.isSatisfied=isSatisfied;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(columnDefinition = "uuid", updatable = false)
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
@ManyToOne
@JoinColumn(name="complaint_id",columnDefinition = "uuid")
public Complaint getComplaintRef() {
return complaintRef;
}
public void setComplaintRef(Complaint complaintRef) {
this.complaintRef = complaintRef;
}
@ManyToOne
@JoinColumn(name="user_id",columnDefinition = "uuid")
public User getUserRef() {
return userRef;
}
public void setUserRef(User userRef) {
this.userRef = userRef;
}
public LocalDateTime getDateTime() {
return dateTime;
}
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
public String getComments() {
return comments;
}
public void setComments(String remarks) {
this.comments = remarks;
}
public boolean isSatisfied() {
return isSatisfied;
}
public void setSatisfied(boolean isSatisfied) {
this.isSatisfied = isSatisfied;
}
}
|
Java | GB18030 | 1,324 | 2.453125 | 2 | [] | no_license | package taobao;
import java.util.Date;
import com.yueqian.cn.dao.IUserDao;
import com.yueqian.cn.dao.entity.User;
import com.yueqian.cn.dao.impl.StudentDao;
import com.yueqian.cn.dao.impl.StudentDaoImpl;
import com.yueqian.cn.dao.impl.UserDaoImpl;
public class TsetStudenDaoImpl {
public static void main(String[] args) {
/*StudentDao userDao = new StudentDaoImpl();
User user = new User(null, 23, "С", "Ů", "ˮ", new Date(), 321D);
int rows = userDao.save(user);
if (rows>0) {
System.out.println("ɹ");
}else {
System.out.println("ʧܣ");
}*/
/*StudentDao userDao = new StudentDaoImpl();
User user = new User();
user.setId(1);
int rows = userDao.delete(user);
if (rows>0) {
System.out.println("ɾɹ");
} else {
System.out.println("ɾʧܣ");
}*/
/*StudentDao userDao = new StudentDaoImpl();
User user = new User(5, 12, "С", "Ů", "", new Date(), 7561D);
int rows = userDao.update(user);
if (rows>0) {
System.out.println("ijɹ");
} else {
System.out.println("ʧܣ");
}*/
StudentDao userDao = new StudentDaoImpl();
User user = userDao.getById(2);
System.out.println(user);
}
}
|
C# | UTF-8 | 1,945 | 3.765625 | 4 | [] | no_license | namespace Exam_Maslan
{
using System;
using System.Numerics;
using System.Text;
public class Maslan
{
private const int MaxTransformationsCount = 10;
private const int DesiredSumLength = 1;
public static void Main()
{
StringBuilder input = new StringBuilder(Console.ReadLine());
Console.WriteLine(GetTransformationResult(input));
}
private static string GetTransformationResult(StringBuilder input)
{
int transformations = 0;
while (true)
{
++transformations;
string sum = GetSecretSum(input);
if (sum.Length == DesiredSumLength)
{
return string.Format("{0}{1}{2}", transformations, Environment.NewLine, sum);
}
else if (transformations == MaxTransformationsCount)
{
return sum.ToString();
}
else
{
input = new StringBuilder(sum);
}
}
}
private static string GetSecretSum(StringBuilder input)
{
BigInteger currentSum = 1;
while (input.Length > 0)
{
input = input.Remove(input.Length - 1, 1);
BigInteger tempSum = 0;
for (int index = 1; index < input.Length; index += 2)
{
// Char.GetNumericValue() returns double, which is not compatible
// with BigInteger, so we need to explicitly convert the value to int
tempSum += (int)char.GetNumericValue(input[index]);
}
if (tempSum > 0)
{
currentSum *= tempSum;
}
}
return currentSum.ToString();
}
}
} |
Java | UTF-8 | 3,215 | 2.03125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2014 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.apiman.gateway.platforms.war;
import io.apiman.gateway.engine.GatewayConfigProperties;
import io.apiman.gateway.engine.IEngine;
import io.apiman.gateway.engine.IPolicyErrorWriter;
import io.apiman.gateway.engine.IPolicyFailureWriter;
import io.apiman.gateway.engine.impl.ConfigDrivenEngineFactory;
import io.apiman.gateway.engine.impl.DefaultPolicyErrorWriter;
import io.apiman.gateway.engine.impl.DefaultPolicyFailureWriter;
import java.util.Map;
/**
* Top level gateway. Used when the API Management Runtime Engine is being used
* in a standard Web Application gateway scenario.
*
* @author eric.wittmann@redhat.com
*/
public class WarGateway {
public static WarEngineConfig config;
public static IEngine engine;
public static IPolicyFailureWriter failureFormatter;
public static IPolicyErrorWriter errorFormatter;
/**
* Initialize the gateway.
*/
public static void init() {
config = new WarEngineConfig();
// Surface the max-payload-buffer-size property as a system property, if it exists in the apiman.properties file
if (System.getProperty(GatewayConfigProperties.MAX_PAYLOAD_BUFFER_SIZE) == null) {
String propVal = config.getConfigProperty(GatewayConfigProperties.MAX_PAYLOAD_BUFFER_SIZE, null);
if (propVal != null) {
System.setProperty(GatewayConfigProperties.MAX_PAYLOAD_BUFFER_SIZE, propVal);
}
}
ConfigDrivenEngineFactory factory = new ConfigDrivenEngineFactory(config);
engine = factory.createEngine();
failureFormatter = loadFailureFormatter();
errorFormatter = loadErrorFormatter();
}
private static IPolicyErrorWriter loadErrorFormatter() {
Class<? extends IPolicyErrorWriter> clazz = config.getPolicyErrorWriterClass(engine.getPluginRegistry());
if (clazz == null) {
clazz = DefaultPolicyErrorWriter.class;
}
Map<String, String> conf = config.getPolicyErrorWriterConfig();
return ConfigDrivenEngineFactory.instantiate(clazz, conf);
}
private static IPolicyFailureWriter loadFailureFormatter() {
Class<? extends IPolicyFailureWriter> clazz = config.getPolicyFailureWriterClass(engine.getPluginRegistry());
if (clazz == null) {
clazz = DefaultPolicyFailureWriter.class;
}
Map<String, String> conf = config.getPolicyFailureWriterConfig();
return ConfigDrivenEngineFactory.instantiate(clazz, conf);
}
/**
* Shuts down the gateway.
*/
public static void shutdown() {
engine = null;
}
}
|
Python | UTF-8 | 368 | 3.09375 | 3 | [] | no_license | #!/usr/bin/env python3
"""
converts a label vector into a one-hot matrix.
"""
import tensorflow.keras as K
def one_hot(labels, classes=None):
"""
- Converts a label vector into a one-hot matrix.
- last dimension of the one-hot matrix must
be the number of classes.
"""
cat = K.utils.to_categorical(labels, num_classes=classes)
return cat
|
Java | UTF-8 | 1,057 | 3.09375 | 3 | [] | no_license | import java.io.*;
class Main{
static long shl(long x,int n){
int i=0;
for(;i!=n;i++)x*=2;
return x;
}
static long shr(long x,int n){
int i=0;
for(;i!=n;i++)x/=2;
return x;
}
public static void main(String[]args){
String t=String.valueOf(new char[]{
65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 50, 51, 52, 53,
54, 55,
});
try{
InputStreamReader reader=new InputStreamReader(System.in);
OutputStreamWriter writer=new OutputStreamWriter(System.out);
int b=0,c;
long x=0;
int p;
for(;(c=reader.read())!=-1;){
if(c==61){
break;
}
if(Boolean.compare(c/97!=0,false)*Boolean.compare(c/123==0,false)==1)c-=0x20;
if((p=t.indexOf(c))!=-1){
x=shl(x,5)+p;
b+=5;
if(b/8!=0){
b-=8;
long r=shr(x,b);
writer.write((int)(r%256));
x-=shl(r,b);
}
}
}
while(b/8!=0){
b-=8;
writer.write((int)(shr(x,b)%256));
}
writer.flush();
}catch(Exception e){e.printStackTrace();}
}
} |
C++ | UTF-8 | 647 | 2.90625 | 3 | [] | no_license | //3406726 2013-08-19 00:58:38 Accepted 1016 C++ 0 188 花花的表世界
#include<iostream>
#include<vector>
using namespace std;
int main(){
int t,n,p;
cin>>t;
while(t--){
int l = 0;
vector<char> v;
cin>>n;
for(int i=0;i<n;i++){
cin>>p;
for(int j=l;j<p;j++)
v.push_back('(');
v.push_back(')');
l = p;
}
int rc = 0;
for(size_t i=0;i<v.size();i++)
{
if(v[i] == ')') {
int w = 1;
for(int j=i-1;j>=0;j--)
{
if(v[j] == '(') {
v[j] = '[';
break;
}
if(v[j] != ')')
w++;
}
if(rc != 0) cout<<" ";
cout<<w;
rc ++;
}
}
cout<<endl;
}
return 0;
}
|
PHP | UTF-8 | 246 | 2.5625 | 3 | [] | no_license | <?php
namespace Gini\ORM\Bank;
use \Gini\ORM\Object;
class Company extends Object
{
public $name = 'string:40';
public $code = 'string:40';
protected static $db_index = [
'unique:name',
'unique:code',
];
}
|
Python | UTF-8 | 4,448 | 2.546875 | 3 | [] | no_license | from django import forms
class Work01Form(forms.Form) :
name = forms.CharField(label = "名前")
mail = forms.EmailField(label = "メール")
age = forms.IntegerField(label = "年齢")
class Work02Form (forms.Form):
name = forms.CharField(
label = "名前",
initial = "",
widget=forms.TextInput(attrs={"class" : "form-control"}))
mail = forms.EmailField(
label = "メール",
initial = "",
widget=forms.EmailInput(attrs={"class" : "form-control"}))
age = forms.IntegerField(
label = "年齢",
initial = "",
widget=forms.NumberInput(attrs={"class" : "form-control"}))
class Work03Form (forms.Form):
name = forms.CharField(
label = "名前",
initial = "",
widget=forms.TextInput(attrs={"class" : "form-control"}))
city = forms.ChoiceField(
label = "行ってみたい都市",
initial = "",
choices = (
('Tokyo', '東京'),
('NewYork', 'ニューヨーク'),
('London', 'ロンドン'),
('Paris', 'パリ'),
('Madrid', 'マドリード')
),
widget=forms.Select(attrs={"class" : "form-control"}))
class Work04Form (forms.Form):
name = forms.CharField(
label = "名前",
initial = "",
widget=forms.TextInput(attrs={"class" : "form-control"}))
music = forms.ChoiceField(
label="好きな音楽",
initial = "",
choices = (
('pop', 'ポップ'),
('rock', 'ロック'),
('anime', 'アニソン'),
('idol', 'アイドル'),
),
widget=forms.RadioSelect(attrs={"class" : "form-control-custom"}))
class Work05Form (forms.Form):
name = forms.CharField(
label = "名前",
initial = "",
widget=forms.TextInput(attrs={"class" : "form-control"}))
movie = forms.MultipleChoiceField(
label = "好きな映画",
initial = "",
choices = (
('sf', 'SF'),
('action', 'アクション'),
('comedy', 'コメディ'),
('suspence', 'サスペンス'),
),
widget=forms.CheckboxSelectMultiple(attrs={"class" : "form-control-custom"}))
class Work06Form (forms.Form):
name = forms.CharField(
label = "名前",
initial = "",
widget=forms.TextInput(attrs={"class" : "form-control"}))
message = forms.CharField(
label="メッセージ",
initial = "",
widget=forms.Textarea(attrs={"class" : "form-control"}))
class Work07Form (forms.Form):
name = forms.CharField(
label = "名前",
initial = "",
widget=forms.TextInput(attrs={"class" : "form-control"}))
secret = forms.CharField(
initial = "this is secret",
widget=forms.HiddenInput())
class Work08Form (forms.Form):
school = forms.CharField(
label = "学校名",
initial = "",
widget=forms.TextInput(attrs={"class" : "form-control"}))
grade = forms.ChoiceField(
label = "学年",
initial = "",
choices = (
('1st', '1年'),
('2nd', '2年'),
('3rd', '3年'),
),
widget=forms.Select(attrs={"class" : "form-control"}))
subject = forms.ChoiceField(
label="好きな科目",
initial = "",
choices = (
('Japanese', '国語'),
('Math', '数学'),
('English', '英語'),
('Science', '理科'),
('SocialStudies', '社会'),
),
widget=forms.RadioSelect(attrs={"class" : "form-control-custom"}))
class Work09Form (forms.Form):
movie = forms.CharField(
label = "好きな映画",
initial = "",
widget=forms.TextInput(attrs={"class" : "form-control"}))
genre = forms.MultipleChoiceField(
label = "好きな映画ジャンル",
initial = "",
choices = (
('SF', 'SF'),
('Action', 'アクション'),
('Love', '恋愛'),
('Comedy', 'コメディ'),
('Horror', 'ホラー'),
),
widget=forms.CheckboxSelectMultiple(attrs={"class" : "form-control-custom"}))
comment = forms.CharField(
label="映画のコメント",
initial = "",
widget=forms.Textarea(attrs={"class" : "form-control"}))
|
Java | UTF-8 | 3,058 | 2.59375 | 3 | [] | no_license |
package domain;
import javax.persistence.*;
import static javax.persistence.GenerationType.IDENTITY;
/**
* Tested: True
*
* @author Tiron Andreea-Ecaterina & Alexandru Stoica
* @version 1.0
*/
@Entity
@Table(name = "SESSION_MEMBER")
@SuppressWarnings("unused")
public class SessionMemberEntity implements Idable<Integer> {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "ID_SESSION_MEMBER")
private Integer id;
@ManyToOne(targetEntity = SessionEntity.class)
@JoinColumn(name = "ID_SESSION", updatable = false)
private SessionEntity session;
@ManyToOne(targetEntity = UserEntity.class)
@JoinColumn(name = "ID_USER", updatable = false)
private UserEntity user;
@ManyToOne(targetEntity = ConfigurationSessionMemberEntity.class)
@JoinColumn(name = "ID_CONFIGURATION_SESSION_MEMBER", updatable = false)
private ConfigurationSessionMemberEntity configuration;
private static final Integer DEFAULT_ID = 0;
/**
* @apiNote Don't user this constructor [it's for testing only]
*/
@Deprecated
public SessionMemberEntity() {
this(DEFAULT_ID, null, null, null);
}
public SessionMemberEntity(SessionEntity session, UserEntity user,
ConfigurationSessionMemberEntity configuration) {
this(DEFAULT_ID, session, user, configuration);
}
public SessionMemberEntity(Integer id, SessionEntity session, UserEntity user,
ConfigurationSessionMemberEntity configuration) {
this.id = id;
this.session = session;
this.user = user;
this.configuration = configuration;
}
/**
* Effect: Return the id of a section member.
*
* @return [Integer] : returns the id of a section member.
*/
public Integer getId() {
return id;
}
/**
* Effect: Sets the id of a section member.
*
* @param id: new value for id.
*/
public void setId(Integer id) {
this.id = id;
}
/**
* Effect: Return the id of a section configuration.
*
* @return [ConfigurationSessionMemberEntity] : returns the id of a section configuration.
*/
public ConfigurationSessionMemberEntity getConfiguration() {
return configuration;
}
/**
* Effect: Returns the session of a SessionMember.
*
* @return [SessionEntity]: returns the session of a session member.
*/
public SessionEntity getSession() {
return session;
}
/**
* Effect: Returns the user of a SessionMemberEntity.
*
* @return [UserEntity]: returns the user of a session member.
*/
public UserEntity getUser() {
return user;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SessionMemberEntity that = (SessionMemberEntity) o;
return id.equals(that.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}
|
Java | UTF-8 | 4,224 | 2.296875 | 2 | [] | no_license | package ie.cognate.sng;
import ie.cognate.Stitcher;
import java.awt.Frame;
import java.awt.Insets;
import java.util.ArrayList;
import processing.core.PShape;
import processing.core.PApplet;
import processing.data.JSONArray;
import processing.data.JSONObject;
public class Loader implements Runnable {
Sng3 p5;
boolean loaded;
public Loader(Sng3 p5){
this.p5 = p5;
//p5.loaded = false;
}
@Override
public void run() {
p5.symbol_cols = new int[4][5][2];
int white = p5.color(255);
int black = p5.color(0);
int red = p5.color(242, 55, 55);
int green = p5.color(59, 177, 74);
int yellow = p5.color(238, 232, 16);
int orange = p5.color(245, 120, 52);
int blue = p5.color(51, 160, 217);
int purple = p5.color(184, 86, 160);
int light_purple = p5.color(182, 110, 189);
int red_orange = p5.color(245, 88, 52);
int [][]second = {{white, black}, {red, white}, {green, red}, {black, yellow}, {white, orange}};
int [][]third = {{white, black}, {blue, orange}, {purple, white}, {black, yellow}, {white, red}};
int [][]forth = {{white, black}, {white, red_orange}, {white, green}, {white, yellow}, {white, light_purple}};
int [][]first = {{white, black}, {blue, orange}, {red, green}, {yellow, purple}, {black, white}};
p5.symbol_cols[0] = first;
p5.symbol_cols[1] = second;
p5.symbol_cols[2] = third;
p5.symbol_cols[3] = forth;
Insets in = p5.frame.getInsets();
p5.frameTop = in.top;
p5.frameSides = in.left + in.right;
p5.frameBottom = in.bottom;
p5.border = p5.width/20;
p5.smallborder = p5.width/30;
p5.simage_w = (p5.width/2)-(int)(p5.smallborder*1.5);
p5.simage_h = ((p5.height-p5.frameTop)/2)-(int)(p5.smallborder*1.5);
p5.half_w = p5.width/2;
p5.half_h = (p5.height- p5.frameTop)/2;
p5.smooth();
p5.noStroke();
p5.stitch = new Stitcher(p5);
JSONArray categories = p5.loadJSONArray("actual.json");
int count = 0;
for(int i=0; i<categories.size(); i++){
JSONObject category = categories.getJSONObject(i);
JSONArray pals = category.getJSONArray("palettes");
count += pals.size();
}
p5.palettes = new ArrayList<Palette>(count);
count = 0;
for(int i=0; i<categories.size(); i++ ){
JSONObject category = categories.getJSONObject(i);
JSONArray pals = category.getJSONArray("palettes");
for(int j=0; j<pals.size(); j++){
JSONObject pal = pals.getJSONObject(j);
JSONArray cols = pal.getJSONArray("flosses");
int [] thisPal = new int [cols.size()];
for(int k=0; k<thisPal.length; k++){
thisPal[k] = PApplet.unhex(cols.getString(k));
}
String name = pal.getString("name");
Palette palette = new Palette(p5, thisPal, name, p5.loadImage(pal.getString("url")));
p5.palettes.add(palette);
count++;
}
}
//add previously saved palettes
p5.allusers = p5.loadJSONArray("NO_EDIT/user.json");
int number = Math.min(6, p5.allusers.size());
for(int i=p5.allusers.size()-number; i< p5.allusers.size(); i++, count++){
JSONObject pal = p5.allusers.getJSONObject(i);
JSONArray cols = pal.getJSONArray("flosses");
Floss [] flosses = new Floss[cols.size()];
for(int k=0; k<cols.size(); k++){
String str = cols.getString(k);
Floss f;
if(str.contains(":")){
//f = new RestrictedFloss(this, str);
f = new Floss(p5, str);
}else{
f = new Floss(p5, new Integer( PApplet.unhex(str) ));
}
flosses[k] = f;
}
String name = pal.getString("name");
p5.palettes.add(new Palette(p5, flosses, name, p5.loadImage(pal.getString("url"))));
}
p5.gui = new GUI(p5, 600, 400 + p5.frameTop);
Frame f = new Frame("control window");
f.add(p5.gui);
p5.gui.init();
f.setTitle("S'n'G controls");
f.setSize(p5.gui.w, p5.gui.h);
f.setLocation(100, 100);
f.setResizable(false);
f.setVisible(true);
p5.symbols = new PShape[200];
//load 200 symbols
for(int i=0; i<200; i++){
p5.symbols[i] = p5.loadShape("complex/symbol"+i+".svg");
}
p5.thankyou = p5.loadShape("assets/thankyou.svg");
p5.pfont = p5.createFont("Arial",18,true);
p5.brokenImg = p5.loadShape("assets/broken.svg");
loaded = true;
}
}
|
JavaScript | UTF-8 | 16,115 | 3.140625 | 3 | [] | no_license | // Function for finding index of a character from an array.
Array.prototype.reIndexOf = function (character) {
if (this.length !== 0) {
for (let i in this) {
if (this[i].toString().match(character)) {
return parseInt(i);
}
}
}
return -1;
};
/**
* when everything is loaded then the calculator
* animate class is added to the calculator
* which starts the calculator creation animation.
*/
window.addEventListener("load", function () {
$("#calculator").addClass("animate");
});
// Main function.
$(document).ready(function () {
let gridGap = parseInt($("#calculator").css("grid-gap"), 10);
let heightGridGaps = 5;
let widthGridGaps = 3;
let calculatorHeight = 6.5;
let calculatorWidth = 4;
let width = window.innerWidth;
let height = window.innerHeight;
let keyLength;
// Dynamically setting the calculator dimensions relative to viewport dimensions.
if (width / calculatorWidth > height / calculatorHeight) {
keyLength = Math.floor((Math.floor(height * 0.8) - heightGridGaps * gridGap) / calculatorHeight);
} else {
keyLength = Math.floor((Math.floor(width * 0.8) - widthGridGaps * gridGap) / calculatorWidth);
}
$("#calculator").css({"height": Math.ceil(keyLength * calculatorHeight + heightGridGaps * gridGap), "width": Math.ceil(keyLength * calculatorWidth + widthGridGaps * gridGap), "font-size": keyLength * 0.5 + "px"});
$("#backspace span:first-of-type").css({"width": keyLength * 0.5 + "px", "height": keyLength * 0.5 + "px"});
$("#screen span").css("font-size", keyLength + "px");
setCalculatorEventsUp(keyLength);
});
function setCalculatorEventsUp(keyLength) {
/**
* When the calculator creation animation is ended,
* then the click and keyboard event handlers are attached
* and use of the calculator becomes available.
*/
$("#screen span:nth-of-type(1)")[0].addEventListener('transitionend', function () {
$(".button").bind("click", function () {
keyPressed($(this).attr("id"), keyLength);
});
$(document).on("keydown", function(event) {
let key = event.which || event.keyCode;
switch(key) {
case 48:
keyPressed("zero", keyLength);
break;
case 49:
keyPressed("one", keyLength);
break;
case 50:
keyPressed("two", keyLength);
break;
case 51:
keyPressed("three", keyLength);
break;
case 52:
keyPressed("four", keyLength);
break;
case 53:
keyPressed("five", keyLength);
break;
case 54:
keyPressed("six", keyLength);
break;
case 55:
keyPressed("seven", keyLength);
break;
case 56:
keyPressed("eight", keyLength);
break;
case 57:
keyPressed("nine", keyLength);
break;
case 8:
keyPressed("backspace", keyLength);
break;
}
}).on("keypress", function(event) {
let key = event.which || event.keyCode;
switch(key) {
case 99:
keyPressed("clear", keyLength);
break;
case 47:
keyPressed("divide", keyLength);
break;
case 42:
keyPressed("multiply", keyLength);
break;
case 45:
keyPressed("minus", keyLength);
break;
case 43:
keyPressed("plus", keyLength);
break;
case 13:
keyPressed("equal", keyLength);
break;
case 46:
keyPressed("comma", keyLength);
break;
case 37:
keyPressed("percent", keyLength);
break;
}
});
});
};
/**
* Global variables for the calculator and its memory.
*/
const numberCodes = {"zero": "0", "one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9"};
const operatorCodes = {"divide": "/", "multiply": "*", "minus": "-", "plus": "+", "equal": "="};
let operator = null;
let numberArray = [];
let operatorArray = [];
/**
* This is the brain of the calculator, when a key is clicked on
* or pressed on the keyboard a signal comes here and it's decided,
* what will be done relative to calculator current state.
*/
function keyPressed(keyId, keyLength) {
let currentlyOnScreen = $("#screen span:first-of-type")[0].innerHTML;
if (numberCodes[keyId] !== undefined && (currentlyOnScreen.length < 16 || operator !== null)) {
if ((parseFloat(currentlyOnScreen) !== 0 || /[.]/.test(currentlyOnScreen)) && operator !== "=") {
if (operator !== null) {
currentlyOnScreen = numberCodes[keyId];
arrangeScreenFontSize(currentlyOnScreen, keyLength);
$("#screen span:first-of-type")[0].innerHTML = numberCodes[keyId];
operator = null;
} else {
currentlyOnScreen += numberCodes[keyId];
arrangeScreenFontSize(currentlyOnScreen, keyLength);
$("#screen span:first-of-type")[0].innerHTML += numberCodes[keyId];
}
} else if (operator !== "=") {
if (/[.]/.test(currentlyOnScreen)) {
currentlyOnScreen += numberCodes[keyId];
} else {
currentlyOnScreen = numberCodes[keyId];
}
arrangeScreenFontSize(currentlyOnScreen, keyLength);
$("#screen span:first-of-type")[0].innerHTML = numberCodes[keyId];
}
} else if (operatorCodes[keyId] !== undefined) {
if (operatorCodes[keyId] !== "=") {
if (operator === "=") {
operatorArray.push(operatorCodes[keyId]);
operator = operatorCodes[keyId];
} else if (numberArray.length === 0 && operatorCodes[keyId] === "-" && currentlyOnScreen === "0") {
currentlyOnScreen = operatorCodes[keyId];
arrangeScreenFontSize(currentlyOnScreen, keyLength);
$("#screen span:first-of-type")[0].innerHTML = currentlyOnScreen;
} else if (currentlyOnScreen[0] !== "-" || currentlyOnScreen.length > 1) {
if (operator === null) {
numberArray.push(currentlyOnScreen);
operatorArray.push(operatorCodes[keyId]);
operator = operatorCodes[keyId];
} else {
operatorArray[operatorArray.length - 1] = operatorCodes[keyId];
operator = operatorCodes[keyId];
}
}
} else {
numberArray.push(currentlyOnScreen);
currentlyOnScreen = operate();
if (/[e]/.test(currentlyOnScreen)) {
numberArray = [scientificToDecimal(currentlyOnScreen)];
} else {
numberArray = [currentlyOnScreen];
}
operatorArray = [];
operator = operatorCodes[keyId];
arrangeScreenFontSize(currentlyOnScreen, keyLength);
$("#screen span:first-of-type")[0].innerHTML = currentlyOnScreen;
}
} else if (keyId === "comma") {
if (!/[.]/.test(currentlyOnScreen)) {
if (parseInt(currentlyOnScreen) !== 0) {
if (operator === null) {
currentlyOnScreen += ".";
arrangeScreenFontSize(currentlyOnScreen, keyLength);
} else if (operator !== "=") {
currentlyOnScreen = "0.";
operator = null;
arrangeScreenFontSize(currentlyOnScreen, keyLength);
}
$("#screen span:first-of-type")[0].innerHTML = currentlyOnScreen;
} else {
currentlyOnScreen += ".";
arrangeScreenFontSize(currentlyOnScreen, keyLength);
$("#screen span:first-of-type")[0].innerHTML = currentlyOnScreen;
}
} else if (/[.]/.test(currentlyOnScreen) && operator !== null && operator !== "=") {
currentlyOnScreen = "0.";
arrangeScreenFontSize(currentlyOnScreen, keyLength);
$("#screen span:first-of-type")[0].innerHTML = currentlyOnScreen;
operator = null;
}
} else if (keyId === "clear") {
numberArray = [];
operatorArray = [];
currentlyOnScreen = "0";
operator = null;
arrangeScreenFontSize(currentlyOnScreen, keyLength);
$("#screen span:first-of-type")[0].innerHTML = currentlyOnScreen;
currentlyOnScreen = "0";
operator = null;
arrangeScreenFontSize(currentlyOnScreen, keyLength);
$("#screen span:first-of-type")[0].innerHTML = currentlyOnScreen;
} else if (keyId === "negate" && parseFloat(currentlyOnScreen) !== 0 && (operator === null || operator === "=")) {
let currentlyOnScreenBuffer = currentlyOnScreen;
if (currentlyOnScreen[0] === "-") {
currentlyOnScreen = currentlyOnScreen.substr(1);
} else {
currentlyOnScreen = "-" + currentlyOnScreen;
}
console.log((numberArray.length === 1) + " hola " + typeof(currentlyOnScreenBuffer) + " -- " + typeof(numberArray[0]));
if (numberArray.length === 1 && parseFloat(currentlyOnScreenBuffer) === parseFloat(numberArray[0])) {
numberArray[0] = currentlyOnScreen;
}
arrangeScreenFontSize(currentlyOnScreen, keyLength);
$("#screen span:first-of-type")[0].innerHTML = currentlyOnScreen;
} else if (keyId === "percent" && parseFloat(currentlyOnScreen) !== 0) {
currentlyOnScreen = parseFloat(currentlyOnScreen) / 100;
if (operator === "=") {
numberArray[numberArray.length - 1] = currentlyOnScreen;
}
arrangeScreenFontSize(currentlyOnScreen, keyLength);
$("#screen span:first-of-type")[0].innerHTML = currentlyOnScreen;
} else if (keyId === "backspace") {
if ((currentlyOnScreen.length > 0 || parseFloat(currentlyOnScreen) > 0) && operator === null) {
if (currentlyOnScreen.length > 1) {
currentlyOnScreen = currentlyOnScreen.substr(0, currentlyOnScreen.length - 1);
} else {
if (operatorArray.length > 0) {
operatorArray.pop();
operator = "=";
currentlyOnScreen = numberArray[numberArray.length - 1];
} else {
currentlyOnScreen = "0";
}
}
arrangeScreenFontSize(currentlyOnScreen, keyLength);
$("#screen span:first-of-type")[0].innerHTML = currentlyOnScreen;
}
}
console.log(numberArray);
console.log(operatorArray);
};
/**
* When the equal sign is pressed or clicked then the operation value gets calculated.
* The numbers are stored in a number array and operation operators in a separate array.
* First the multiply and divide operations are done and after that plus and minus operations.
* The function iterates through operator array and whenever it finds a multiply or divide sign
* it takes from the number array two variables, one from the same index as itself and second
* one from its index + 1 spot. Then does the operation and inserts it to the number array in
* the spot with index as itself and deletes spot from the number array its index + 1 and then
* deletes itself from the operator array. And this goes on till the end when operator array
* is empty and number array is left only one value which is the value of the full operation.
*/
function operate() {
numberArray = numberArray.map(Number);
let index = operatorArray.reIndexOf(/[*\/]/);
while (index !== -1) {
if (operatorArray[index] === "*") {
numberArray[index] = multiply(numberArray[index], numberArray[index + 1]);
numberArray.splice(index + 1, 1);
} else {
numberArray[index] = divide(numberArray[index], numberArray[index + 1]);
numberArray.splice(index + 1, 1);
}
operatorArray.splice(index, 1);
index = operatorArray.reIndexOf(/[*\/]/);
}
index = operatorArray.reIndexOf(/[+\-]/);
while (index !== -1) {
if (operatorArray[index] === "+") {
numberArray[index] = add(numberArray[index], numberArray[index + 1]);
numberArray.splice(index + 1, 1);
} else {
numberArray[index] = subtract(numberArray[index], numberArray[index + 1]);
numberArray.splice(index + 1, 1);
}
operatorArray.splice(index, 1);
index = operatorArray.reIndexOf(/[+\-]/);
}
return numberArray[0].toString();
};
function add(a, b) {
return a + b;
};
function subtract(a, b) {
return a - b;
};
function multiply(a, b) {
return a * b;
};
function divide(a, b) {
return a / b;
};
/**
* When last equation result became big enough or small for JavaScript to
* display it as exponential and user decides to continue with that number
* as a first number of the next calculation, then this function is used
* to convert it to decimal again.
*/
function scientificToDecimal(number) {
let numberHasSign = number.startsWith("-") || number.startsWith("+");
let sign = numberHasSign ? number[0] : "";
number = numberHasSign ? number.replace(sign, "") : number;
//if the number is in scientific notation remove it
if (/\d+\.?\d*e[\+\-]*\d+/i.test(number)) {
let zero = '0';
let parts = String(number).toLowerCase().split('e'); //split into coefficient and exponent
let e = parts.pop();//store the exponential part
let l = Math.abs(e); //get the number of zeros
let sign = e / l;
let coefficient_array = parts[0].split('.');
if (sign === -1) {
coefficient_array[0] = Math.abs(coefficient_array[0]);
number = zero + '.' + new Array(l).join(zero) + coefficient_array.join('');
} else {
let dec = coefficient_array[1];
if (dec) l = l - dec.length;
number = coefficient_array.join('') + new Array(l + 1).join(zero);
}
}
return sign + number;
};
// This function is used for changing the font size of the screen relative to its content change.
function arrangeScreenFontSize(currentlyOnScreen, keyLength) {
$("#ruler")[0].innerHTML = currentlyOnScreen;
let screenWidth = $("#screen")[0].offsetWidth;
let fontSize = parseInt($("#screen span:first-of-type").css("font-size"));
if ($("#ruler")[0].offsetWidth > screenWidth) {
fontSize -= 0.1;
$("#ruler").css("fontSize", fontSize + "px");
while ($("#ruler")[0].offsetWidth > screenWidth) {
fontSize -= 0.1;
$("#ruler").css("fontSize", fontSize + "px");
}
$("#screen span:first-of-type").css("fontSize", fontSize + "px");
} else if (fontSize < keyLength) {
while ($("#ruler")[0].offsetWidth < screenWidth && fontSize < keyLength) {
fontSize += 0.1;
$("#ruler").css("fontSize", fontSize + "px");
}
if (fontSize === keyLength) {
$("#screen span:first-of-type").css("fontSize", fontSize + "px");
} else {
fontSize -= 0.1;
$("#screen span:first-of-type").css("fontSize", fontSize + "px");
}
}
}; |
C | UTF-8 | 3,086 | 3.984375 | 4 | [] | no_license | #include <errno.h> // errno
#include <math.h> // HUGE_VAL
#include <stdio.h> // printf
#include <stdlib.h> // strtod
#include <string.h> // strerror
#define MINARGS 2
// Helper functions
int convert_argument(const char* arg, double* convertedArg);
int swap(double* numbers, int length);
int main(int argc, char* argv[]) {
int result;
if(argc < MINARGS) {
printf("Must include numbers to sort\n");
result = 1;
} else if(argc == MINARGS) {
// Verify input is valid number
double convertedArg;
if(convert_argument(argv[1], &convertedArg) == 0) {
// If valid, print
printf("%.2f\n", convertedArg);
result = 0;
} else {
result = 1;
}
} else {
int sortedLength = argc - 1; // Ignore first element, typically executable path
double sortedArguments[sortedLength];
// Convert string arguments to double array
int argIndex;
int sortedIndex = 0;
for(argIndex = 1; argIndex < argc; argIndex++) {
if(convert_argument(argv[argIndex], &sortedArguments[sortedIndex++]) == 1) {
printf("Argument %d %s invalid, aborting\n", argIndex + 1, argv[argIndex]);
return 1;
}
}
// Keep swapping until sorted
while(swap(sortedArguments, sortedLength) != 0) {}
// Print results
for(sortedIndex = 0; sortedIndex < sortedLength; sortedIndex++) {
printf("%.2f ", sortedArguments[sortedIndex]);
}
printf("\n");
result = 0;
}
return result;
}
int convert_argument(const char* arg, double* convertedArg) {
int result;
char* endPtr;
// Error check
if(arg == NULL || convertedArg == NULL) {
return 1;
}
errno = 0; // Set to 0 to determine if strtod converted to 0 or there was an error
*convertedArg = strtod(arg, &endPtr);
// Check for errors
if((*convertedArg == 0.0 || *convertedArg == HUGE_VAL) && errno != 0) {
printf("Error converting number: %s\n", strerror(errno));
result = 1;
}
// All characters not converted
else if(endPtr != arg + strlen(arg)) { // End pointer does not point to end of string
printf("Unable to convert full string to number\n");
result = 1;
}
// Conversion success
else {
result = 0;
}
return result;
}
int swap(double* numbers, int length) {
int numSwapped = 0;
int index;
double tmp;
// Error check
if(numbers == NULL || length <= 0) {
return -1;
}
// Loop through array and swap as necessary
for(index = 0; index < length - 1; index++) {
// Compare current number to the next one
if(numbers[index] > numbers[index + 1]) {
// Swap
tmp = numbers[index];
numbers[index] = numbers[index + 1];
numbers[index + 1] = tmp;
// Update counter
numSwapped++;
}
}
return numSwapped;
} |
Markdown | UTF-8 | 1,632 | 2.515625 | 3 | [] | no_license | # smApps-G2
ECC3303 Embedded Systems Designs Project Group 2
Unplanned and unsecure parking become the main issues that require a parking management system for several places such as shopping mall, resident area, educational area and many more. Even though there are some place that has been installed with this more advance parking management system with payment, there are still some issue such as complex payment procedure, contact method payment, unknown parking availability, hard to find the location of payment machine and the loss of ticket. Thus, this project is to design a smart parking payment system applying the smartphone application (also known as smApps) which is the QR code scanner and e-wallet to enhance efficiency of parking system and the payment process, also, at the same time, indicate the parking availability to assist the parking planning. For user, the e-wallet will be able to play the role as an electronic wallet and as an application to scan the QR code to perform any parking payment. In prototyping of this project, a scale model built to shows when the user’s car is come to the parking barrier, the user needs to scan the QR code to entering and leaving from the parking area. All the database and communication are done by adapting Google Firebase platform to smApps system. In addition, the prototype implemented the software application and hardware component which are Android studio,
raspberry pi, servo motor, LCD screen, and IR sensor. smApps system designed can help to reduce the complexity in parking payment process and manage the parking availability in saving cost and time.
|
Python | UTF-8 | 320 | 3.140625 | 3 | [] | no_license | import matplotlib.pyplot as plt
languages = ["Python", "Java", "C++", "Dart", "JavaScript"]
jobs = [70, 80, 88, 12, 90]
plt.pie(jobs, labels=languages)
plt.legend()
plt.show()
chinese = ["Noddels", "Burger", "Manchurian", "Chilly Potato"]
persons = [60, 10, 20, 10]
plt.pie(persons, labels=chinese)
plt.legend()
plt.show()
|
Markdown | UTF-8 | 3,724 | 3.265625 | 3 | [
"BSD-3-Clause",
"CC0-1.0"
] | permissive | # fhirpatch
## What's this?
This is a Javascript implementation of the FHIRPatch specification as
described at https://www.hl7.org/fhir/fhirpatch.html. For FHIR Path
parsing, it uses the excellent fhirpath.js library.
## Usage
Please refer to `test/fhirpatch.test.js` for more examples.
```
const {FhirPatch} = require('fhirpatch');
# Create a new patch, to fix Fred Flintstone's birthdate from CE to BCE
const patch = {
resourceType: 'Parameters',
parameter: [{
name: 'operation',
part: [
{ name: 'path', valueString: 'Patient.birthDate' },
{ name: 'value', valueString: '-2020-01-01'},
{ name: 'type', valueString: 'replace' },
],
}],
};
const resource = {
resourceType: 'Patient',
name: [{
given: ['Fred'],
family: 'Flintstone'
}],
birthDate: '2020-01-01',
}
# Apply the patch in one step
let result = FhirPatch.apply(resource, patch); // returns a *copy* of resource with the patch applied.
# Prepare a patch which can be applied to many resources
let patcher = new FhirPatch(patch);
let result = patcher.apply(resource);
```
Apply operations will always return the resource in the format in which they received it. The following
formats are supported:
* Javascript objects
* JSON
* XML
The patcher will throw an exception whenever any of the following conditions obtains:
1. The provided patch is not a valid FHIR parameters object.
2. The provided patch isn't a valid FHIR patch.
3. The path to be patched doesn't exist (except for delete operations).
4. The required arguments for a given operation type are not present.
5. The resource is invalid **before** patching.
6. The resource is invalid **after** patching.
## Authoring support
This library has support to help you create FHIR patches.
```
patch = new FhirPatch();
patch.operations.push(
new Operation({
type: 'delete',
path: 'Practitioner.telecom.where(value="6564664444")',
}),
new Operation({
type: 'insert',
value: {
system: 'phone',
value: '75774767896',
},
valueType: 'valueContactPoint',
path: 'Practitioner.telecom',
index: 0,
});
)
patch.toString('json'); // generate json of patch
patch.describe(); // gernerate array of strings describing the patch operations in english
```
## Known Limitations
1. It could definitely be faster and probably more robust by doing our own
fhirpath implementation.
2. Two of HL7's test cases don't pass. In one case (@apply.27) I'm pretty
sure the test case is at fault. In the other, it's an issue of the
code that autogenerates the test case and it'ss just not worth the time to
fix right now.
3. This library has not been tested on a browser, since we need it for use in node.
4. There may be a limitation inherent to using an external FHIRPath implementation,
but it's not covered by the test cases and is not worth the time right now. See
comment on Operation#tail for discussion.
5. FHIR object validation is not what it should be, and may well miss some cases
that the official FHIR validator would catch.
## Examples
### Patch with a complex value
```json
{
"resourceType": "Parameters",
"parameter": [
{
"name": "operation",
"parameter": [
{
"name": "type",
"valueCode": "add"
},
{
"name": "path",
"valueString": "Patient"
},
{
"name": "name",
"valueString": "contact"
},
{
"name": "value",
"parameter": [
{
"name": "name",
"valueHumanName": {
"text": "a name"
}
}
]
}
]
}
]
}
```
|
C# | UTF-8 | 3,647 | 2.59375 | 3 | [
"MIT"
] | permissive | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Xml;
namespace CoreWCF.IdentityModel
{
internal struct XmlAttributeHolder
{
public static XmlAttributeHolder[] emptyArray = Array.Empty<XmlAttributeHolder>();
public XmlAttributeHolder(string prefix, string localName, string ns, string value)
{
Prefix = prefix;
LocalName = localName;
NamespaceUri = ns;
Value = value;
}
public string Prefix { get; }
public string NamespaceUri { get; }
public string LocalName { get; }
public string Value { get; }
public void WriteTo(XmlWriter writer)
{
writer.WriteStartAttribute(Prefix, LocalName, NamespaceUri);
writer.WriteString(Value);
writer.WriteEndAttribute();
}
public static void WriteAttributes(XmlAttributeHolder[] attributes, XmlWriter writer)
{
for (int i = 0; i < attributes.Length; i++)
{
attributes[i].WriteTo(writer);
}
}
public static XmlAttributeHolder[] ReadAttributes(XmlDictionaryReader reader)
{
int maxSizeOfHeaders = int.MaxValue;
return ReadAttributes(reader, ref maxSizeOfHeaders);
}
public static XmlAttributeHolder[] ReadAttributes(XmlDictionaryReader reader, ref int maxSizeOfHeaders)
{
if (reader.AttributeCount == 0)
{
return emptyArray;
}
XmlAttributeHolder[] attributes = new XmlAttributeHolder[reader.AttributeCount];
reader.MoveToFirstAttribute();
for (int i = 0; i < attributes.Length; i++)
{
string ns = reader.NamespaceURI;
string localName = reader.LocalName;
string prefix = reader.Prefix;
string value = string.Empty;
while (reader.ReadAttributeValue())
{
if (value.Length == 0)
{
value = reader.Value;
}
else
{
value += reader.Value;
}
}
Deduct(prefix, ref maxSizeOfHeaders);
Deduct(localName, ref maxSizeOfHeaders);
Deduct(ns, ref maxSizeOfHeaders);
Deduct(value, ref maxSizeOfHeaders);
attributes[i] = new XmlAttributeHolder(prefix, localName, ns, value);
reader.MoveToNextAttribute();
}
reader.MoveToElement();
return attributes;
}
private static void Deduct(string s, ref int maxSizeOfHeaders)
{
int byteCount = s.Length * sizeof(char);
if (byteCount > maxSizeOfHeaders)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlBufferQuotaExceeded));
}
maxSizeOfHeaders -= byteCount;
}
public static string GetAttribute(XmlAttributeHolder[] attributes, string localName, string ns)
{
for (int i = 0; i < attributes.Length; i++)
{
if (attributes[i].LocalName == localName && attributes[i].NamespaceUri == ns)
{
return attributes[i].Value;
}
}
return null;
}
}
}
|
Java | UTF-8 | 431 | 1.65625 | 2 | [] | no_license | package atm;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class AtmApplication {
public static void main(String[] args) {
SpringApplication.run(AtmApplication.class, args);
}
@Bean
public StartupRunner startupRunner() {
return new StartupRunner();
}
}
|
Go | UTF-8 | 352 | 2.53125 | 3 | [] | no_license | package main
import (
"github.com/gorilla/mux"
"net/http"
"os"
"io"
"github.com/NYTimes/gziphandler"
)
func main() {
m := mux.NewRouter()
m.HandleFunc("/", func(w http.ResponseWriter,r *http.Request) {
file, _ := os.Open("/tmp/dataBasic.jpg")
io.Copy(w, file)
file.Close()
})
http.ListenAndServe(":3000", gziphandler.GzipHandler(m))
}
|
Markdown | UTF-8 | 982 | 3.765625 | 4 | [] | no_license | # 342. Power of Four
[Link to Question](https://leetcode.com/problems/power-of-four/)
## Description
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
**Example 1:**
```
Input: 16
Output: true
```
**Example 2:**
```
Input: 5
Output: false
```
**Follow up**: Could you solve it without loops/recursion?
## Thoughts
Bitwise operation
## Solution
Languages:
- [C](#C)
- [Python](#python)
- [Java](#java)
<div id="C"></div>C Code:
```C
```
<div id="python"></div>Python Code:
```python
class Solution:
def isPowerOfFour(self, num: int) -> bool:
# condition 1: the binary representation of num must only contains one bit of 1
# condition 2: the only bit of 1 must be on an even index from the rightmost digit
# starting from 0
return num and not (num & (num-1)) and not (num & 0xaaaaaaaa)
```
<div id="java"></div>Java Code:
```java
```
[Return to README](./../README.md)
|
Python | UTF-8 | 814 | 3.578125 | 4 | [] | no_license | # sys is a module. It lets us access command line arguments, which are
# stored in sys.argv.
import sys
import random
if len(sys.argv) < 2:
print("Please supply a flash card file.")
exit(1)
flashcard_filename = sys.argv[1]
f = open(flashcard_filename, "r")
que_ans = {}
for line in f:
entry = line.strip().split(",")
question = entry[0]
answer = entry[1]
que_ans[question] = answer
f.close()
questions = list(que_ans.keys())
print("Welcome to the flash card quiz!")
print("You can enter 'quit' at anytime to exit the game")
while True:
ques = random.choice(questions)
answ = que_ans[ques]
choice = input(ques + "?")
if choice == "quit":
break
elif choice == answ:
print("you are correct!")
else:
print("oops! the answer is " + answ)
|
Markdown | UTF-8 | 3,655 | 2.625 | 3 | [] | no_license | ---
layout: post
status: publish
published: true
title: Open Source Documentation
author: Colin Ramsay
author_login: colinramsay
author_email: colinramsay@gmail.com
author_url: http://colinramsay.co.uk
wordpress_id: 465
wordpress_url: http://colinramsay.co.uk/?p=465
date: !binary |-
MjAwOC0xMS0yNCAwMDoyMTowNyArMDAwMA==
date_gmt: !binary |-
MjAwOC0xMS0yMyAyMzoyMTowNyArMDAwMA==
categories:
- Castle
- Documentation
tags: []
comments: []
---
<p>Recently I've set up a network attached storage computer on my home network. As well as providing RAID storage for all the devices in the house, it acts as a central download server for everyone to use. Key to this strategy is <a href="http://www.sabnzbd.org/">SABnzbd</a>, a Python application which downloads binaries from newsgroups, and which sits on the server as a daemon, grabbing files on a schedule or when we ask it to. The functionality of this software is incredible, but more than that, there is a great deal of documentation for each feature directly linked from the web interface. This enabled me to set up advanced features such as RSS feeds, categorisation, and post-download scripts, in order to shift SABnzbd from being handy to indispensible.</p>
<p>This post is not about SABnzbd though - it's about documentation. My latest project has been a very quick CMS solution using Monorail, and I've been taking advantage of the new features available in Castle's trunk. The new routing in Monorail, the fluent API for component registration in Microkernel, and more new features, have all been making my life easier... once I've figured them out. I'm in awe of the people who have produced these features and I'm not adverse to digging round test cases where I can, in order to find out how to use them. </p>
<p>However, it would unarguably be better if the Castle documentation reflected these new changes. It's understandable that the documention lags behind these features, and since I don't have the intimate Castle knowledge needed to contribute to fixing bugs or adding new code, I figured it'd be good to try and work on this documentation. Castle uses an <a href="http://castleproject.org/community/getinvolved.html#documentation">XML based documentation format</a> which is just fine for final docs, but not that great for scrabbling down notes and filling out information. For that, I've decided to use the using.castleproject.org wiki, a site designed to hold tips and tricks for the Castle Project.</p>
<p>I've set up a <a href="http://using.castleproject.org/display/CASTLE/Helping+With+Documentation">simple system of tagging</a> which allows people to search out stuff in need of documentation and then tag it when it's complete. At that point, I plan on converting it into a patch for the official Castle documentation. In this way we can get the rapid prototyping of a wiki combined with an easy route to formal documentation. I think barrier for entry is a definite problem for contributing on many projects, and documentation can be a good place to start. For Castle, I'm trying to make even the barrier for entry for even that documentation very low. So if you can help out with the <a href="http://using.castleproject.org/display/MR/Routing+Overview">routing documentation</a> or the <a href="http://using.castleproject.org/display/MR/Monorail+Validation">validation documentation</a> or anything else that's missing or incomplete in the <a href="http://castleproject.org/">main Castle docs</a>, please pitch in and try and help! </p>
<p>(Also published on <a href="http://www.lostechies.com/blogs/colin_ramsay/archive/2008/11/23/open-source-documentation.aspx">my LosTechies blog</a>)</p>
|
JavaScript | UTF-8 | 1,886 | 2.53125 | 3 | [] | no_license | class Menu extends React.Component{
constructor (props){
super(props);
this.buttonClick = this.buttonClick.bind(this);
this.state = {
counter: 0,
}
}
buttonClick(){
this.setState({counter: ++this.state.counter})
};
render (){
let x =
<div id="LayoutGrid1">
<div className="row">
<div className="col-1">
<div id="site_ResponsiveMenu1">
<label className="toggle" htmlFor="ResponsiveMenu1-submenu" id="ResponsiveMenu1-title"><Text counter={this.state.counter}/><span id="ResponsiveMenu1-icon"><span> </span><span> </span><span> </span></span></label>
<input type="checkbox" id="ResponsiveMenu1-submenu"/>
<ul className="ResponsiveMenu1" id="ResponsiveMenu1">
<li><a href="#">Главная</a></li>
<li><a href="#">О нас</a></li>
<li><a href="#">Контакты</a></li>
</ul>
</div>
</div>
</div>
</div>;
return <div id="site_LayoutGrid1">{x}<Button
counter={this.state.counter}
handler ={this.buttonClick}
/><Text
counter={this.state.counter}
/></div>;
}
}
class Button extends React.Component{
render(){
return <button
onClick={this.props.handler}
>НАЖАТЬ {this.props.counter}</button>
}
}
class Text extends React.Component{
render(){
return <div
>НАЖАТО {this.props.counter}</div>
}
}
ReactDOM.render(
<Menu/>,
document.getElementById("menu")
); |
Markdown | UTF-8 | 2,939 | 2.9375 | 3 | [] | no_license | # USNX Boilerplate
This is some boilerplate for developing web apps. It makes use of modern
developments tools such as [Bower](http://bower.io/)
and [Grunt](http://gruntjs.com/), which in turn make use of the
[NodeJS](http://nodejs.org) engine.
## Dependencies
* [Git](http://git-scm.com/downloads)
* [Node JS](http://nodejs.org/download/)
* [Bower](https://github.com/twitter/bower)
* [Grunt](http://gruntjs.com/getting-started)
## Installation
1. If you have not done so already, install [Git](http://git-scm.com/downloads)
and [Node JS](http://nodejs.org/download/).
2. Use the Node Package Manager (NPM) to install Bower and Grunt (You will need
administration privligaes).
npm install -g bower grunt-cli
3. Clone the git repository to a directory on your development machine.
git clone git://github.com/USNX/usnx-boilerplate.git [target-directory]
cd usnx-boilerplate
4. Install your project dependencies using the Node Package Manager (NPM) and
Bower.
npm install && bower install
5. Run `grunt build` to build your project.
6. Run `grunt server` to start the server on port 8000
7. Open your browser and navigate to `http://localhost:8000`. You should see
the home page.
## Installing Packages with Bower
You can install packages from any git repo using Twitter's
[Bower](https://github.com/twitter/bower). This places that package under the
directory specified in your `.bowerrc` file (defaults to `components`), and
adds an entry to the dependencies section of the `bower.json` file. Help with
Bower is available via `bower help` or the [Bower web site](http://bower.io/).
### Example
There are several ways to install the jQuery UI plugin:
1. If the following entry is in your directory's bower.json
// bower.json
"dependiencies": {
"jquery-ui": "~1.10.2"
}
then simply typing:
bower install
will install jQuery UI ver. 1.10.*.
2. You can quickly install the newest version of jQuery UI by typing:
bower install jquery-ui
3. You can specify a specific version of jQuery UI and make an entry in the
depencencies section of your `bower.json` by entering:
bower install jquery-ui#1.10.2 --save
## Grunt
[Grunt](http://gruntjs.com) is a task runner that can be configured to automate
certain tasks. It is compatable with many modern web technologies such as
Compass, Less, and CoffeeScript.
This software comes with Grunt packages for [Compass](http://compass-style.org/),
[jsHint](http://www.jshint.com/), and has a stand-alone webserver that will
automatically push detected changes in your files to the browser.
### Using Grunt
You can start the server and start watching for changes in *.html, *.scss, and
*.js files by using:
grunt server
This will start a local development server at `localhost:8000`. Any changes you
make to `public/*.html`, `public/js/*.js`, and `public\css\sass\*.scss` will be
automatically pushed to the browser every time you save them. |
Markdown | UTF-8 | 11,068 | 3.390625 | 3 | [] | no_license | # Class
## const メンバ関数とmutable
**`const` メンバ関数** ... インスタンスが `const` でも呼び出し可能なメンバ関数のこと。
```cpp
class ClassName {
public:
ReturnType member_func(params, ...) const;
};
ReturnType member_func(params, ...) const {
body...
}
```
### const/非constメンバ関数のオーバーロード
`const` がついているかどうかでも、**オーバーロード** ができる。
```cpp
class Foo {
int a;
public:
int get_a();
int get_a() const;
};
int Foo::get_a() {
std::cout << "Not const" << std::endl;
return a;
}
int Foo::get_a() const {
std::cout << "const" << std::endl;
return a;
}
```
上の場合、インスタンス自体が `const` か、`非const` かで評価される。
### constメンバ関数でも書き込む場合
キャッシュを作成するよう場合有効。
メンバ変数を `mutable` 指定することで、 `const` メンバ関数からでも書き換える操作ができるようになる。
## コンストラクタ・デストラクター
### コンストラクタ
Pythonでいう `__init__()` 。
```cpp
class ClassName {
public:
ClassName(); // コンストラクタの宣言
};
ClassName::ClassName() : member(init-value), member(init-value), ... {
body
}
```
上の `: member(value), member(value), ...` の ` : ` は、**メンバ初期化リスト**
### デストラクター
コンストラクタは、正常に動作するために、メンバ変数位がにも必要であれば、追加でメモリ領域を確保する。
プログラム内で適切にメモリ領域を解放しないと、やがてメモリ不足(メモリリーク)に陥る。
これを解決するには、デストラクタを用いる。デストラクタはインスタンスが破棄されるときに呼ばれる。
インスタンスが破棄されるタイミングは、関数本体などの `{` が閉じるタイミング。
```cpp
class ClassName {
public:
~ClassName(); // デストラクタの宣言
};
ClassName::~ClassName() {
body
}
```
#### RAII
コンストラクタでメモリ確保して、デストラクタで解放することを **RAII** (Resource Acquisition Is Initialization) という。
## 初期値を受け取るコンストラクタ
```cpp
class ClassName {
public:
ClassName(params, ...);
};
ClassName variable(args, ...);
```
この形を取ると、コンパイラが自動生成する **デフォルトコンストラクタ** がなくなってしまう。
**デフォルトコンストラクタ**は、引数がないコンストラクタ、通常はコンパイラが自動的に定義する。
プログラマがこれを定義すると、そちらが使われる。
### 移譲コンストラクタ
コンストラクタの内部のみで使える、他のコンストラクタを呼び出す為の専用方法。
1. 移譲先コンストラクタが呼ばれる
2. 処理が行われた後、移譲元のコンストラクタの処理が行われる。
移譲コンストラクタの場合、メンバ変数の初期化は移譲先でしかできない
```cpp
class ClassName {
public:
ClassName(params, ...); // 移譲元コンストラクタの宣言
};
ClassName::ClassName(params, ...) : ClassName(args, ...) { // 移譲先コンストラクタの呼び出し
body;
}
```
### コピーインストラクタ
コンストラクタには、
1. ユーザ定義コンストラクタ
2. コンパイラ生成コンストラクタ
がある。コンパイラ生成コンストラクタの中には、クラスをコピーする際に使われる**コピーコンストラクタ** が存在する。
```cpp
class ClassName {
public:
ClassName(const ClassName& variable); // コピーコンストラクタ
};
```
メモリ領域やリソースを扱うクラスの場合、コピーコンストラクタをプログラマが定義する必要がある。
メンバ変数がポインタ変数の場合、コンパイラが生成するコピーでは、ポインタ変数の値(アドレス) のみコピーを行い、
ポインタ変数が指し示す先の実際のオブジェクトはコピーしない。
これは、ポインタ変数の値のみコピーすると、オブジェクトは1つしかないのに、複数のクラスが同じアドレス値をもっていることになり、
それらオブジェクトが破棄されるたびに、それぞれ同じオブジェクトを解放しようとする、**二重解放** が起きる。
### explicit 指定子
**暗黙のコンストラクタ呼び出し** が発生することを防ぐために、`explicit` 演算子 を追加する.
```cpp
class A {
int m_v;
public:
explicit A(int); // 暗黙のコンストラクタ呼び出しを禁止できる
int v() const;
};
A::A(int v) : m_v(v) {
}
int A::v() const {
return m_v;
}
int main() {
A x = 0; // ERROR
A y(42); // OK
};
```
## デフォルトの初期値
Pythonでいう
```python
class A:
def __init__(self):
self.a = 0
```
ってやってるだけ。
### メンバ変数の初期値
メンバ変数のデフォルト値を指定するには次の方法がある。
この構文は、**非静的メンバ変数の初期化子** (Non Static Data Member Initializer: NSDMI) という名称が付いている。
```cpp
class ClassName {
TypeName variable = default;
TypeName variable = { default };
TypeName variable(default);
TypeName variable{default};
};
```
### メンバ初期化リストと初期値
NSDMIとコンストラクタのメンバ初期化リストの両方がある場合、コンストラクタで指定した初期値の方を使って初期化される。
## 継承
Pythonでいう
```python
class DerivedClass(BaseClass):
...
```
は、
```cpp
class DerivedClass : AccessSpecifier BaseClass {
...
};
```
`AccessSpecifier` は、継承クラスが `public` で公開しているメンバを派生クラスでも `public` で公開する意味。
### オーバライド
存在する機能の「処理内容」を変えるには、 **オーバライド**する。しかし、なんでもオーバライド できるわけではなく、
基底クラス定義時に、「派生クラスで変更可能」という宣言をしておく必要がある。この宣言がなされたメンバ関数のことを**仮想関数**
と呼ぶ。
なお、**オーバライド** するには、 `override` 指定子をつける。な、**オーバライド** はあくまで処理だけを書き換えられる。引数は変更できない。
```cpp
class BaseClass {
public:
virtual ReturnType function(params, ...);
};
ReturnType BaseClass::function(params, ...) {
// virtualは書かない
}
class DerivedClass : public BaseClass {
public:
ReturnType function(params, ...) override {
// 仮想関数のオーバライド
}
};
ReturnType DerivedClass::function(params, ...) {
body;
}
```
なお、基底クラスで `virtual` 指定しておけば、派生クラスで`override`指定子を省略してもオーバライドできる。
しかし、開発しているうちに基底クラスのメンバ関数の仕様が変更された場合、メンバ関数が仮想関数で無くなったりすることも考えられる。
このような、ミスを回避するために、オーバライドするつもりのメンバ関数に `override` と指定することで、もし規定クラスから無くなっていた場合でも、
エラーを出してくれる。意識的にこの`override` 指定子をつけた方が良い。
### 名前の隠蔽
基底クラスが持っているメンバ関数と同じ名前のメンバ関数を派生クラスに追加すると、発生する。
これが起こると、基底クラスのメンバ関数を呼ぶことができなくなる。
名前の隠蔽は、派生クラスでオーバライドを追加しようとした時に起こる。
こういった場合、 `using` 宣言を使うと、基底クラスのメンバ関数をオーバロードとして追加できる。
```cpp
class ClassName : AccessSpecifier BaseClass {
public:
using BaseClass::member_func;
};
```
型名に別名をつける際に利用した `using` 宣言とは別物。
### 純粋仮想関数と抽象クラス
規定クラスでは宣言のみで、処理内容がなく、派生クラスが必ずオーバライドして処理を書くように強制させる **純粋仮想関数** がある。
PyTorch の `torch.nn.Module` (?)
```cpp
class ClassName {
public:
virtual ReturnType function(params, ...) = 0; // 純粋仮想関数
};
```
#### 純粋クラス
純粋仮想関数が宣言されたクラスは **抽象クラス** と呼ばれる。
```cpp
class AbstractClass {
public:
virtual void foo() = 0;
};
```
Javaの `Interface` や Swiftの `Protocol` の真似するためにこの抽象クラスを使うのは、
パフォーマンスの面からみてあまり好ましくない。
## オブジェクトポインタ
ポインタを経由して、メンバにアクセスする際は、`struct` と同じく`->` を使う。
### this ポインタ
メンバ関数で、ある変数を参照するために使う。Pythonでいう `self.` にあたるのが、 `this` ポインタ
`this` ポインタには、そのメンバ関数呼び出しに使われたオブジェクトを指し示すポインタが格納されている。
`const` メンバ関数の中では、`this` ポインタは `cosnt` ポインタとなる。
`const` メンバ関数の中では、非 `const` メンバ関数を呼び出すことも、メンバ変数に変更を加えることもできない。
## クラス、構造体、共同体
基本的に `struct` も `class` も違いはない。
ある違いは、以下の表の通り
| | Class | Struct |
| ------------------------------------ | ------- | ------ |
| メンバに対するアクセス指定 | private | public |
| 規定クラスからの派生時のアクセス指定 | private | public |
| | | |
一応、データを纏めるのに `struct` 、オブジェクト作るなら、`class` がよい。
## friend関数
非公開メンバはクラスの外側からアクセスできない。しかし、**フレンド関数** を使うことで、
特別に非公開メンバにアクセスるることができる。
非メンバ関数をフレンド関数として宣言するには、その非メンバ関数のプロトタイプ宣言に `friend` をつけたものをクラス内に記述する。
引数は、クラスのポインタや、参照を取るのが一般的。
## static クラスメンバ
|
Python | UTF-8 | 234 | 2.734375 | 3 | [] | no_license | import os
import time
flag = ""
for i in range(0,30):
os.system("git reset --hard HEAD~1")
time.sleep(0.3)
f = open("./flag.txt")
time.sleep(0.3)
flag = f.read().strip() + flag
time.sleep(0.3)
print(flag)
|
Python | UTF-8 | 3,504 | 3 | 3 | [] | no_license | import asyncio
import curses
import itertools
import random
import time
from curses_tools import draw_frame, get_frame_size, read_controls
def read_frame(path):
with open(path, 'r') as frame_file:
frame = frame_file.read()
return frame
async def blink(canvas, row, column, symbol, offset_tics):
while True:
for _ in range(offset_tics):
await asyncio.sleep(0)
canvas.addstr(row, column, symbol, curses.A_DIM)
for _ in range(20):
await asyncio.sleep(0)
canvas.addstr(row, column, symbol)
for _ in range(3):
await asyncio.sleep(0)
canvas.addstr(row, column, symbol, curses.A_BOLD)
for _ in range(5):
await asyncio.sleep(0)
canvas.addstr(row, column, symbol)
for _ in range(3):
await asyncio.sleep(0)
async def fire(canvas, start_row, start_column, rows_speed=-0.3, columns_speed=0):
"""Display animation of gun shot. Direction and speed can be specified."""
row, column = start_row, start_column
canvas.addstr(round(row), round(column), '*')
await asyncio.sleep(0)
canvas.addstr(round(row), round(column), 'O')
await asyncio.sleep(0)
canvas.addstr(round(row), round(column), ' ')
row += rows_speed
column += columns_speed
symbol = '-' if columns_speed else '|'
rows, columns = canvas.getmaxyx()
max_row, max_column = rows - 1, columns - 1
curses.beep()
while 0 < row < max_row and 0 < column < max_column:
canvas.addstr(round(row), round(column), symbol)
await asyncio.sleep(0)
canvas.addstr(round(row), round(column), ' ')
row += rows_speed
column += columns_speed
async def animate_spaceship(canvas, row, column, frames):
frame_rows, frame_columns = get_frame_size(frames[0])
canvas_size_y, canvas_size_x = canvas.getmaxyx()
for frame in itertools.cycle(frames):
rows_direction, columns_direction, space_pressed = read_controls(canvas)
if (0 < row + rows_direction < canvas_size_y - frame_rows):
row += rows_direction
if (0 < column + columns_direction < canvas_size_x - frame_columns):
column += columns_direction
draw_frame(canvas, row, column, frame)
await asyncio.sleep(0)
draw_frame(canvas, row, column, frame, negative=True)
def draw(canvas):
canvas.border()
canvas.nodelay(True)
curses.curs_set(False)
canvas_size_y, canvas_size_x = canvas.getmaxyx()
frames = (read_frame('frames/rocket_frame_1.txt'), read_frame('frames/rocket_frame_2.txt'))
coroutines = []
stars_count = 100
for _ in range(stars_count):
coroutines.append(blink(
canvas,
random.randint(2, canvas_size_y - 2),
random.randint(2, canvas_size_x - 2),
symbol=random.choice('+*.:'),
offset_tics=random.randint(1, 30)
))
gun_shot = fire(canvas, canvas_size_y//2-1, canvas_size_x//2+2)
coroutines.append(gun_shot)
spaceship = animate_spaceship(canvas, canvas_size_y//2, canvas_size_x//2, frames)
coroutines.append(spaceship)
while True:
for coroutine in coroutines:
try:
coroutine.send(None)
except StopIteration:
coroutines.remove(coroutine)
canvas.refresh()
time.sleep(0.1)
if __name__ == '__main__':
curses.update_lines_cols()
curses.wrapper(draw)
|
JavaScript | UTF-8 | 3,596 | 2.796875 | 3 | [] | no_license | /**
* [launchFunction description]
* @param {[type]} mExec [description]
* @param {[type]} currentObj [description]
* @param {[type]} oScope [description]
* @return {[type]} [description]
*/
function launchFunction( mExec, currentObj, oScope){
var result = null, sActionName, mArgs = [];
[ sActionName, mArgs] = ( mExec instanceof Array)? mExec : [ mExec, []];
return oScope[sActionName].apply( currentObj, ( mArgs instanceof Array)? mArgs : [ mArgs]);
}
/**
* [_analyseObject description]
* @param {[type]} promiseResolve [description]
* @param {[type]} promiseReject [description]
* @param {[type]} oStep [description]
* @param {[type]} oData [description]
* @param {[type]} oScope [description]
* @constructor
* @return {[type]} [description]
*/
function _analyseObject( promiseResolve, promiseReject, oStep, oData, oScope){
var sResult = 'default',
oNextStep, bNext = true,
arg = [].slice.call( arguments);
fTick.call( oData);
if( 'action' in oStep){
launchFunction( oStep.action, oData, oScope);
}
if( 'test' in oStep){
sResult = launchFunction( oStep.test, oData, oScope).toString();
bNext = ( 'force' in oStep && sResult != oStep.force)? false : bNext;
if( bNext){
oNextStep = oStep.if[ sResult] || { action : ()=>{ promiseReject( oData)}};
arg[ arg.indexOf( oStep) ] = oNextStep;
}
_analyseObject.apply( this, arg);
}else{
promiseResolve( oData);
}
};
/**
* [_analyseArray description]
* @param {[type]} promiseResolve [description]
* @param {[type]} promiseReject [description]
* @param {[type]} oStep [description]
* @param {[type]} oData [description]
* @param {[type]} oScope [description]
* @constructor
* @return {[type]} [description]
*/
function _analyseArray( promiseResolve, promiseReject, aStep, oData, oScope){
var oStep, bResult = false,
iLen = aStep.length,
aClone = [...aStep].reverse();
for(;iLen--;){
oStep = aClone[iLen];
fTick.call( oData);
if( 'action' in oStep){
launchFunction( oStep.action, oData, oScope);
}
if( 'test' in oStep){
bResult = launchFunction( oStep.test, oData, oScope);
}
if( 'force' in oStep){
if( !bResult){
iLen++;
continue;
}
}
if( !bResult){
break;
}
}
// fin du script;
if( bResult){
promiseResolve( oData);
}else{
promiseReject( oData);
}
};
var fTick = function(){};
/**
* [oScope description]
* @type {[type]}
*/
class DecisionTree{
/**
* [addTick description]
* @param {[type]} _fTick [description]
*/
static addTick( _fTick){
fTick = _fTick;
}
/**
* [decide description]
* @param {[type]} mStep [description]
* @param {[type]} mData [description]
* @param {[type]} [oScope=window] [description]
* @return {[type]} [description]
*/
static decide( mStep, mData, oScope = window){
var execute = ( mStep instanceof Array)? _analyseArray : _analyseObject ;
return new Promise( (promiseResolve, promiseReject) => {
if( mData instanceof Array){
mData.map((oData)=>{
execute.apply( this, [ promiseResolve, promiseReject, mStep, oData, oScope]);
});
}else{
execute.apply( this, [ promiseResolve, promiseReject, mStep, mData, oScope]);
}
});
}
}
|
Java | UTF-8 | 622 | 3.046875 | 3 | [] | no_license | class Solution {
public boolean isAnagram(String s, String t) {
int[] s_count = new int[26];
int[] t_count = new int[26];
if(s.length() != t.length()){
return false;
}
for(char c : s.toCharArray()){
s_count[c-'a'] = s_count[c-'a'] + 1;
}
for(char c : t.toCharArray()){
t_count[c-'a'] = t_count[c-'a'] + 1;
}
for(int i=0;i<s_count.length;i++){
if(s_count[i] != t_count[i]){
return false;
}
}
return true;
}
} |
Python | UTF-8 | 2,091 | 2.953125 | 3 | [] | no_license | from datetime import datetime
from DataModule.Data import Data
from Backtest.Action import Action
from DataModule.DataManager import DataManager
from Backtest.Strategies.Strategy import Strategy
from Backtest.Signals.MovingAverage import MovingAverage
from Backtest.Signals.RecentHigh import RecentHigh
from Backtest.Signals.RecentLow import RecentLow
from Backtest.Signals.Price import Price
from Backtest.Position import Position
class MovingAverageCrossover(Strategy):
trade_open = False
position = None
entry_price = None
def enter(self, signals):
if signals['short_ma'] > signals['long_ma']:
if signals['price'] >= signals['recent_high']:
self.trade_open = True
self.position = Position.LONG
self.entry_price = signals['price']
return Action('AAPL', Action.Operation.BUY, 1)
elif signals['short_ma'] < signals['long_ma']:
if signals['price'] <= signals['recent_low']:
self.trade_open = True
self.position = Position.SHORT
self.entry_price = signals['price']
return Action('AAPL', Action.Operation.SELL, 1)
return None
def exit(self, signals):
if not self.trade_open:
return False
# Calculate draw down
draw_down = self.position * (signals['price'] - self.entry_price) / self.entry_price
if self.position == Position.SHORT:
draw_down *= -1
# Stop loss
if draw_down < -0.05:
return True
return False
def get_data(self):
data_manger = DataManager()
start = datetime(2017, 10, 31)
end = datetime(2018, 10, 31)
return data_manger.get('AAPL', Data.Interval.THIRTY_MIN, start, end)
def get_signals(self):
signals = {
'short_ma': MovingAverage(3),
'long_ma': MovingAverage(20),
'recent_high': RecentHigh(3),
'recent_low': RecentLow(3),
'price': Price()
}
return signals
|
C++ | UTF-8 | 173 | 2.578125 | 3 | [
"MIT"
] | permissive | #include <thread>
void new_thread()
{
while (true)
{
std::thread *th = new std::thread(new_thread);
}
}
int main()
{
new_thread();
return 0;
}
|
Java | UTF-8 | 486 | 3.8125 | 4 | [] | no_license | package Day3;
public class Multiple_Conditions_Statement {
public static void main(String[] args) {
int a = 1;
int b = 3;
int c = 5;
if (a+b > c) {
System.out.println("a & b is greater than c");
} else if(a+b < c) {
System.out.println("a & b is less than c");
} else {
System.out.println("a & b is equal to c");
}//eEnd of multiple condition
}//end of main method
}//end of java class
|
Java | UTF-8 | 219 | 2.734375 | 3 | [] | no_license | package com.app.fruits;
public class Orange extends Fruits{
public Orange(String nm) {
super(nm);
}
@Override
public void taste()
{
System.out.println( super.getName() + "is Sweet n Sour in taste");
}
}
|
Python | UTF-8 | 4,531 | 2.625 | 3 | [
"Apache-2.0",
"CC0-1.0",
"LicenseRef-scancode-public-domain",
"CC-BY-4.0"
] | permissive | # -*- coding: utf-8 -*-
# Copyright (C) 2016-2023 PyThaiNLP Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import List
import numpy as np
THAI_CHARACTERS_WITHOUT_SHIFT = [
"ผปแอิืทมใฝ",
"ฟหกดเ้่าสวง",
"ๆไำพะัีรนยบลฃ",
"ๅ/_ภถุึคตจขช",
]
THAI_CHARACTERS_WITH_SHIFT = [
"()ฉฮฺ์?ฒฬฦ",
"ฤฆฏโฌ็๋ษศซ.",
'๐"ฎฑธํ๊ณฯญฐ,',
"+๑๒๓๔ู฿๕๖๗๘๙",
]
ENGLISH_CHARACTERS_WITHOUT_SHIFT = [
"1234567890-=",
"qwertyuiop[]\\",
"asdfghjkl;'",
"zxcvbnm,./",
]
ENGLISH_CHARACTERS_WITH_SHIFT = [
"!@#$%^&*()_+",
"QWERTYUIOP{}|",
'ASDFGHJKL:"',
"ZXCVBNM<>?",
]
ALL_CHARACTERS = [
THAI_CHARACTERS_WITHOUT_SHIFT + THAI_CHARACTERS_WITH_SHIFT,
ENGLISH_CHARACTERS_WITHOUT_SHIFT + ENGLISH_CHARACTERS_WITH_SHIFT,
]
def search_location_of_character(char: str):
for language_ix in [0, 1]:
for ix, row in enumerate(ALL_CHARACTERS[language_ix]):
if char in row:
return (language_ix, ix // 4, ix % 4, row.index(char))
def find_neighbour_locations(
loc: tuple,
char: str,
kernel: List = [(-1, -1), (-1, 0), (1, 1), (0, 1), (0, -1), (1, 0)],
):
language_ix, is_shift, row, pos = loc
valid_neighbours = []
for kr, ks in kernel:
_row, _pos = row + kr, pos + ks
if 0 <= _row <= 3 and 0 <= _pos <= len(
ALL_CHARACTERS[language_ix][is_shift * 4 + _row]
):
valid_neighbours.append((language_ix, is_shift, _row, _pos, char))
return valid_neighbours
def find_misspell_candidates(char: str, verbose: bool = False):
loc = search_location_of_character(char)
if loc is None:
return None
valid_neighbours = find_neighbour_locations(loc, char)
chars = []
printing_locations = ["▐"] * 3 + [char] + ["▐"] * 3
for language_ix, is_shift, row, pos, char in valid_neighbours:
try:
char = ALL_CHARACTERS[language_ix][is_shift * 4 + row][pos]
chars.append(char)
kernel = (row - loc[1], pos - loc[2])
if kernel == (-1, -1):
ix = 5
elif kernel == (-1, 0):
ix = 6
elif kernel[0] == 0:
ix = 3 + kernel[1]
elif kernel == (1, 0):
ix = 0
elif kernel == (1, 1):
ix = 1
else:
continue
printing_locations[ix] = char
except IndexError as e:
continue
except Exception as e:
print("Something wrong with: ", char)
raise e
return chars
def misspell(sentence: str, ratio: float = 0.05):
"""
Simulate some mispellings for the input sentence.
The number of mispelled locations is governed by ratio.
:params str sentence: sentence to be mispelled
:params float ratio: number of misspells per 100 chars. Defaults to 0.5.
:return: sentence containing some misspelled
:rtype: str
:Example:
::
from pythainlp.tools.misspell import misspell
sentence = "ภาษาไทยปรากฏครั้งแรกในพุทธศักราช 1826"
misspell(sent, ratio=0.1)
# output:
ภาษาไทยปรากฏครั้งแรกในกุทธศักราช 1727
"""
num_misspells = np.floor(len(sentence) * ratio).astype(int)
positions = np.random.choice(
len(sentence), size=num_misspells, replace=False
)
# convert strings to array of characters
misspelled = list(sentence)
for pos in positions:
potential_candidates = find_misspell_candidates(sentence[pos])
if potential_candidates is None:
continue
candidate = np.random.choice(potential_candidates)
misspelled[pos] = candidate
return "".join(misspelled)
|
Go | UTF-8 | 3,273 | 2.6875 | 3 | [
"MIT"
] | permissive | package config
import (
"fmt"
"regexp"
"strings"
"github.com/go-kratos/kratos/v2/encoding"
"github.com/go-kratos/kratos/v2/log"
)
// Decoder is config decoder.
type Decoder func(*KeyValue, map[string]interface{}) error
// Resolver resolve placeholder in config.
type Resolver func(map[string]interface{}) error
// Option is config option.
type Option func(*options)
type options struct {
sources []Source
decoder Decoder
resolver Resolver
}
// WithSource with config source.
func WithSource(s ...Source) Option {
return func(o *options) {
o.sources = s
}
}
// WithDecoder with config decoder.
// DefaultDecoder behavior:
// If KeyValue.Format is non-empty, then KeyValue.Value will be deserialized into map[string]interface{}
// and stored in the config cache(map[string]interface{})
// if KeyValue.Format is empty,{KeyValue.Key : KeyValue.Value} will be stored in config cache(map[string]interface{})
func WithDecoder(d Decoder) Option {
return func(o *options) {
o.decoder = d
}
}
// WithResolver with config resolver.
func WithResolver(r Resolver) Option {
return func(o *options) {
o.resolver = r
}
}
// WithLogger with config logger.
// Deprecated: use global logger instead.
func WithLogger(_ log.Logger) Option {
return func(o *options) {}
}
// defaultDecoder decode config from source KeyValue
// to target map[string]interface{} using src.Format codec.
func defaultDecoder(src *KeyValue, target map[string]interface{}) error {
if src.Format == "" {
// expand key "aaa.bbb" into map[aaa]map[bbb]interface{}
keys := strings.Split(src.Key, ".")
for i, k := range keys {
if i == len(keys)-1 {
target[k] = src.Value
} else {
sub := make(map[string]interface{})
target[k] = sub
target = sub
}
}
return nil
}
if codec := encoding.GetCodec(src.Format); codec != nil {
return codec.Unmarshal(src.Value, &target)
}
return fmt.Errorf("unsupported key: %s format: %s", src.Key, src.Format)
}
// defaultResolver resolve placeholder in map value,
// placeholder format in ${key:default}.
func defaultResolver(input map[string]interface{}) error {
mapper := func(name string) string {
args := strings.SplitN(strings.TrimSpace(name), ":", 2) //nolint:gomnd
if v, has := readValue(input, args[0]); has {
s, _ := v.String()
return s
} else if len(args) > 1 { // default value
return args[1]
}
return ""
}
var resolve func(map[string]interface{}) error
resolve = func(sub map[string]interface{}) error {
for k, v := range sub {
switch vt := v.(type) {
case string:
sub[k] = expand(vt, mapper)
case map[string]interface{}:
if err := resolve(vt); err != nil {
return err
}
case []interface{}:
for i, iface := range vt {
switch it := iface.(type) {
case string:
vt[i] = expand(it, mapper)
case map[string]interface{}:
if err := resolve(it); err != nil {
return err
}
}
}
sub[k] = vt
}
}
return nil
}
return resolve(input)
}
func expand(s string, mapping func(string) string) string {
r := regexp.MustCompile(`\${(.*?)}`)
re := r.FindAllStringSubmatch(s, -1)
for _, i := range re {
if len(i) == 2 { //nolint:gomnd
s = strings.ReplaceAll(s, i[0], mapping(i[1]))
}
}
return s
}
|
Markdown | UTF-8 | 1,812 | 2.984375 | 3 | [
"CC-BY-4.0",
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | ---
title: "Disconnecting from a Data Source or Driver"
description: "Disconnecting from a Data Source or Driver"
author: David-Engel
ms.author: v-davidengel
ms.date: "01/19/2017"
ms.service: sql
ms.subservice: connectivity
ms.topic: conceptual
helpviewer_keywords:
- "disconnecting from driver [ODBC]"
- "data sources [ODBC], disconnecting"
- "disconnecting from data source [ODBC]"
- "connecting to data source [ODBC], disconnecting"
- "connecting to driver [ODBC], disconnecting"
- "ODBC drivers [ODBC], disconnecting"
---
# Disconnecting from a Data Source or Driver
When an application has finished using a data source, it calls **SQLDisconnect**. **SQLDisconnect** frees any statements that are allocated on the connection and disconnects the driver from the data source. It returns an error if a transaction is in process.
After disconnecting, the application can call **SQLFreeHandle** to free the connection. After freeing the connection, it is an application programming error to use the connection's handle in a call to an ODBC function; doing so has undefined but probably fatal consequences. When **SQLFreeHandle** is called, the driver releases the structure used to store information about the connection.
The application also can reuse the connection, either to connect to a different data source or reconnect to the same data source. The decision to remain connected, as opposed to disconnecting and reconnecting later, requires that the application writer consider the relative costs of each option; both connecting to a data source and remaining connected can be relatively costly depending on the connection medium. In making a correct tradeoff, the application must also make assumptions about the likelihood and timing of further operations on the same data source.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.