language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 2,928
| 2.90625
| 3
|
[] |
no_license
|
package visualization;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import org.graphstream.graph.*;
import org.graphstream.graph.implementations.*;
import org.graphstream.ui.view.Viewer;
import simulation.Main;
public class Plotter {
static Graph g;
static MyNode[] myNodes;
public static void plotOld(){
Graph g = new SingleGraph("tree1");
Viewer v = g.display();
int n = 20;
int c = 1; //numOfNeighbors
MyNode[] myNodes = new MyNode[n];
for(int i=0; i<n; i++){
myNodes[i] = new MyNode(c,g,i);
}
for(int i=1;i<n;i++){
myNodes[i-1].AddNeighbor(myNodes[i]);
}
v.disableAutoLayout();
myNodes[0].RemoveNeighbor(myNodes[1],true);
myNodes[1].AddNeighbor(myNodes[0]);
}
public static void plotFromLogFile(String filename){
LinkedList<String> logLst = new LinkedList<String>();
try {
filename = Main.logdir + filename + ".log";
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
String firstLine = br.readLine();
int n = Integer.parseInt(firstLine.substring(firstLine.indexOf("N=")+2, firstLine.indexOf("C=")-1));
int c = Integer.parseInt(firstLine.substring(firstLine.indexOf("C=")+2, firstLine.indexOf("ChunkSize")-1));
String s = br.readLine();
while(s!=null){
logLst.add(s);
s = br.readLine();
}
br.close();
fr.close();
plot(logLst,n,c);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void plot(LinkedList<String> logList, int n, int c){
g = new SingleGraph("tree1");
Viewer v = g.display();
myNodes = new MyNode[n];
for(int i=0; i<n; i++){
myNodes[i] = new MyNode(c,g,i);
}
String currLog = logList.remove();
while(!logList.isEmpty() && !currLog.startsWith("=")){
currLog = logList.remove();
}
initGraph(currLog);
v.disableAutoLayout();
while(!logList.isEmpty()){
currLog = logList.remove();
if(currLog.contains("(")){
int[] tuple = getFirstTuple(currLog);
if(currLog.startsWith("+")){
myNodes[tuple[0]].AddNeighbor(myNodes[tuple[1]]);
}
else if(currLog.startsWith("-")){
myNodes[tuple[0]].RemoveNeighbor(myNodes[tuple[1]],true);
}
}
}
}
private static int[] getFirstTuple(String s) {
int[] ans = new int[2];
int start = s.indexOf('(');
int sep = s.indexOf(',');
int end = s.indexOf(')');
ans[0] = Integer.parseInt(s.substring(start+1, sep));
ans[1] = Integer.parseInt(s.substring(sep+1,end));
return ans;
}
private static void initGraph(String s) {
System.out.println("\n\ninitializing display:");
while(s.length()>5){
int[] tuple = getFirstTuple(s);
System.out.print("(" + tuple[0] + "," + tuple[1] + ")");
myNodes[tuple[0]].AddNeighbor(myNodes[tuple[1]]);
s = s.substring(s.indexOf(')')+1);
}
System.out.println();
}
}
|
Java
|
UTF-8
| 1,086
| 2.796875
| 3
|
[] |
no_license
|
package com.softserve.BookLibrary.validator;
import com.softserve.BookLibrary.entity.Book;
import com.softserve.BookLibrary.manager.BookManager;
import javax.ejb.EJB;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class UniqueIsbnValidator implements ConstraintValidator<UniqueIsbn, String> {
private Long bookId;
@EJB
private BookManager bookManager;
@Override
public void initialize(UniqueIsbn constraintAnnotation) {
bookId = constraintAnnotation.bookId();
/**
* Initializes the validator in preparation for isValid(Object, ConstraintValidatorContext) calls.
* This method is guaranteed to be called before any use of this instance for validation.
* @param constraintAnnotation
*/
}
@Override
public boolean isValid(String isbn, ConstraintValidatorContext context) {
boolean valid;
Book book = bookManager.findByIsbn(isbn);
valid = (book == null) || (book.getId().equals(bookId));
return valid;
}
}
|
C++
|
UTF-8
| 502
| 3.28125
| 3
|
[] |
no_license
|
//1108. Defanging an IP Address
class Solution {
public:
string defangIPaddr(string address) {
string add;
int n=address.size();
for(int i=0;i<n;i++)
{
if(!(address[i]=='.'))
{
add.push_back(address[i]);
}
else{
add.push_back('[');
add.push_back('.');
add.push_back(']');
}
}
return add;
}
};
|
Shell
|
UTF-8
| 2,560
| 3.40625
| 3
|
[] |
no_license
|
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
UNAME=`uname -s`
# Source all files in the ~/.bash/ directory
source ~/.bash/*
# --------------------------------------
# ALIASES
# --------------------------------------
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
alias fn='find . -name'
alias ..='cd ..'
alias gg='cd .. && ls'
# I prefer grep colors to boring pgrep
alias pgrep='ps -efM | grep'
# --------------------------------------
# LS AND GREP COLORS
# --------------------------------------
if [ -x /usr/bin/dircolors ]; then
alias ls='ls --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
fi
# --------------------------------------
# MAN PAGE COLORS
# --------------------------------------
export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;31m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;32m'
# --------------------------------------
# GIT SHORTCUTS & COLORS
# --------------------------------------
git config alias.co checkout
git config alias.st status
git config alias.ci commit
git config alias.br branch
git config color.ui true
# --------------------------------------
# MAC OSX SPECIFIC
# --------------------------------------
if [ "$UNAME" = Darwin ]; then
# add color to ls
alias ls='ls -G'
# add color to grep
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
# Quicklook from terminal
function ql ()
{
(qlmanage -p "$@" > /dev/null 2>&1 &
local ql_pid=$!
read -sn 1
kill ${ql_pid}) > /dev/null 2>&1
}
fi
# --------------------------------------
# SET PS1
# --------------------------------------
PS1='(\u@\h:\W)\$ '
case "$TERM" in xterm-*color)
PS1='\[\e[31m\](\[\e[m\]\u\[\e[31m\]@\h\[\e[m\]:\[\e[36m\]\W\[\e[31m\])\[\e[36m\]\$ \[\e[m\]'
esac
# --------------------------------------
# HISTORY
# --------------------------------------
# don't put duplicate lines in the history.
HISTCONTROL=ignoredups:ignorespace
# append to the history file, don't overwrite it
shopt -s histappend
HISTSIZE=1000
HISTFILESIZE=2000
# --------------------------------------
# ETC
# --------------------------------------
# check the window size after each command
shopt -s checkwinsize
# Add ~/.bin to path
export PATH=~/.bin:$PATH
function g(){
cd $* && ls
}
set -o vi
|
C++
|
UTF-8
| 467
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
#ifndef SNAKEBLOCK_H
#define SNAKEBLOCK_H
// Snake body RGB values:
const int red = 240;
const int green = 150;
const int blue = 50;
class SnakeBody {
public:
SnakeBody(float sbX, float sbY, float sbZ);
void draw();
// getters and setters (RGB & XYZ)
void setColour(float sbR, float sbG, float sbB);
void setX(float sbX);
void setY(float sbY);
void setZ(float sbZ);
float getX();
float getY();
float getZ();
private:
float x, y, z, r, g, b;
};
#endif
|
Java
|
UTF-8
| 261
| 1.96875
| 2
|
[] |
no_license
|
package stepDefinitions;
import cucumber.api.java.en.And;
import pages.SignUpPage;
public class SignUpSteps {
private SignUpPage page = new SignUpPage();
@And("I intrude my email")
public void iIntrudeMyEmail() {
page.setEmail();
}
}
|
PHP
|
UTF-8
| 184
| 2.5625
| 3
|
[] |
no_license
|
<?php
declare(strict_types = 1);
namespace App\Errors;
class FloatError extends Error
{
public function getTypeName(): string
{
return 'Float';
}
}
|
TypeScript
|
UTF-8
| 4,988
| 3.09375
| 3
|
[] |
no_license
|
import { MGPMap } from '../MGPMap';
import { MGPOptional } from '../MGPOptional';
describe('MGPMap', () => {
it('Set should bug if key value was already present', () => {
const map: MGPMap<string, string> = new MGPMap();
map.set('oui', 'yes');
expect(() => map.set('oui', 'si')).toThrow();
});
it('Put should replace value if key value was already present', () => {
const map: MGPMap<string, string> = new MGPMap();
map.put('oui', 'yes');
expect(() => map.put('oui', 'DA')).not.toThrow();
expect(map.get('oui')).toEqual(MGPOptional.of('DA'));
});
it('ListKey should work', () => {
const map: MGPMap<string, number> = new MGPMap();
map.set('first', 1);
map.set('second', 2);
expect(map.listKeys()).toEqual(['first', 'second']);
});
describe('replace', () => {
it('Replace should work', () => {
const map: MGPMap<string, number> = new MGPMap();
map.set('first', 1);
map.replace('first', 0);
expect(map.get('first')).toEqual(MGPOptional.of(0));
});
it('Replace should throw when value not found', () => {
const map: MGPMap<string, number> = new MGPMap();
map.set('first', 1);
expect(() => map.replace('firstZUUU', 0))
.toThrowError('No Value to replace for key firstZUUU!');
});
});
describe('delete', () => {
it('Should delete element', () => {
const map: MGPMap<string, number> = new MGPMap();
map.set('first', 0);
map.set('second', 1);
map.set('third', 2);
map.delete('first');
expect(map.get('first')).toEqual(MGPOptional.empty());
});
it('Should throw when unexisting key passed', () => {
const map: MGPMap<string, number> = new MGPMap();
map.set('first', 0);
expect(() => map.delete('second')).toThrowError('No Value to delete for key "second"!');
});
});
it('GetByIndex should give them by order of input', () => {
const map: MGPMap<string, number> = new MGPMap();
map.set('first', 0);
map.set('second', 1);
map.set('third', 2);
expect(map.getByIndex(1).value).toBe(1);
});
it('Should throw when calling set after making immutable', () => {
const map: MGPMap<string, number> = new MGPMap();
map.set('first', 0);
map.set('second', 1);
map.makeImmutable();
expect(() => map.set('third', 2)).toThrowError('Cannot call set on immutable map!');
});
it('PutAll should concantenate two maps, erasing the overlapping content on the receiver', () => {
const receiver: MGPMap<string, number> = new MGPMap();
receiver.set('first', 0);
receiver.set('second', 1);
const giver: MGPMap<string, number> = new MGPMap();
giver.set('first', 1);
giver.set('third', 3);
receiver.putAll(giver);
const expectedSum: MGPMap<string, number> = new MGPMap();
expectedSum.set('first', 1);
expectedSum.set('second', 1);
expectedSum.set('third', 3);
expect(receiver).toEqual(expectedSum);
});
it('Size should work', () => {
const map: MGPMap<string, number> = new MGPMap();
expect(map.size()).toBe(0);
});
describe('copy', () => {
it('Copy should be identical when no immutable', () => {
const map: MGPMap<string, number> = new MGPMap();
map.set('first', 0);
map.set('second', 1);
const copy: MGPMap<string, number> = map.getCopy();
expect(copy).toEqual(map);
map.set('third', 2);
expect(copy).not.toEqual(map);
});
it('Copy should bethe same but mutable when immutable', () => {
const map: MGPMap<string, number> = new MGPMap();
map.set('first', 0);
map.set('second', 1);
const copy: MGPMap<string, number> = map.getCopy();
map.makeImmutable();
expect(copy).not.toEqual(map);
copy.makeImmutable();
expect(copy).toEqual(map);
});
});
describe('equals', () => {
it('should detect maps with distinct keys as different', () => {
const map1: MGPMap<string, number> = new MGPMap();
map1.set('first', 0);
const map2: MGPMap<string, number> = new MGPMap();
map2.set('second', 1);
expect(map1.equals(map2)).toBeFalse();
});
it('should detect map with same keys but distinct values as different', () => {
const map1: MGPMap<string, number> = new MGPMap();
map1.set('first', 0);
const map2: MGPMap<string, number> = new MGPMap();
map2.set('first', 1);
expect(map1.equals(map2)).toBeFalse();
});
});
});
|
Python
|
UTF-8
| 412
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
import unittest
import encoder.xml
class XmlTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.encode = encoder.xml.Encoder().encode
def test_sample_doc(self):
class SampleDoc:
def __xml__(self, tag):
with tag.body():
yield 'Hello world!'
self.assertEqual(self.encode(SampleDoc()), '<body>Hello world!</body>')
|
Java
|
UTF-8
| 365
| 1.757813
| 2
|
[] |
no_license
|
package com.adnanali.foodish.Interface;
import com.adnanali.foodish.Model.CustomDictionary;
public interface ConnectorInterface {
void changeFragment(boolean isAddToBackStack, android.support.v4.app.Fragment fragment, CustomDictionary... dictionary);
void removeFragment(android.support.v4.app.Fragment fragment);
void changeTitle(String title);
}
|
Markdown
|
UTF-8
| 728
| 3.5
| 4
|
[] |
no_license
|
# 题目分析
## 三次遍历思想
### 将输入的字符串转成数组<br>将输入的第二个和第三个值push到一个数组里面<br>遍历第一个数组,如果这个数组的第i项和第二个数组的第0项相等,并且这个数组的第i+1项和第二个数组的第1项相等,则判断一下第i+2有没有值,如果有就push到一个新数组中。<br>最后,返回这个数组
```
var findOcurrences = function(text, first, second) {
let arr=text.split(' ')
let input=[]
let output=[]
input.push(first,second)
for(let i=0;i<arr.length;i++){
if(arr[i]==input[0]&&arr[i+1]==input[1]&&Boolean(arr[i+2])!=false){
output.push(arr[i+2])
}
}
return output
};
|
Rust
|
UTF-8
| 1,969
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
use ndarray::{Array1, Array2, ArrayView1};
#[derive(Debug, Clone)]
pub struct Iris {
iris_vec: Vec<f64>,
pub iris: Array2<f64>,
class_vec: Vec<f64>,
pub class: Array2<f64>,
}
impl Iris {
pub fn new(
sepal_length: f64,
sepal_width: f64,
petal_length: f64,
petal_width: f64,
class: Vec<f64>,
) -> Self {
let iris_vec: Vec<f64> = vec![sepal_length, sepal_width, petal_length, petal_width];
let iris: Array2<f64> = match Array2::from_shape_vec((1, iris_vec.len()), iris_vec.to_vec())
{
Ok(result) => result,
Err(error) => panic!(
"Shape does not correspond to the number of elements in vector v {}!",
error
),
};
let class_vec: Vec<f64> = class;
let class: Array2<f64> =
match Array2::from_shape_vec((1, class_vec.len()), class_vec.to_vec()) {
Ok(result) => result,
Err(error) => panic!(
"Shape does not correspond to the number of elements in vector v {}!",
error
),
};
Self {
iris_vec,
iris,
class_vec,
class,
}
}
fn l2_norm(&mut self, x: ArrayView1<f64>) -> f64 {
x.dot(&x).sqrt()
}
fn normalize_vec(&mut self, mut x: Array1<f64>) -> Vec<f64> {
let norm = self.l2_norm(x.view());
x.mapv_inplace(|e| e / norm);
x.to_vec()
}
pub fn normalize(&mut self) {
self.iris_vec = self.normalize_vec(Array1::from_vec(self.iris_vec.clone()));
self.iris = match Array2::from_shape_vec((1, self.iris_vec.len()), self.iris_vec.to_vec()) {
Ok(result) => result,
Err(error) => panic!(
"Shape does not correspond to the number of elements in vector v {}!",
error
),
};
}
}
|
Java
|
UTF-8
| 6,099
| 2.015625
| 2
|
[] |
no_license
|
package com.leckan.popularmoviestwo.UI;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import com.facebook.stetho.Stetho;
import com.facebook.stetho.okhttp.StethoInterceptor;
import com.leckan.popularmoviestwo.Adapter.MovieAdapter;
import com.leckan.popularmoviestwo.BuildConfig;
import com.leckan.popularmoviestwo.Model.DummyMovies;
import com.leckan.popularmoviestwo.Model.Movie;
import com.leckan.popularmoviestwo.R;
import com.leckan.popularmoviestwo.Utilities.DownloadMoviesTask;
import com.leckan.popularmoviestwo.Utilities.FavoriteMoviesTask;
import com.leckan.popularmoviestwo.Utilities.Utility;
import com.squareup.okhttp.OkHttpClient;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements MovieAdapter.ListItemClickListener {
ConnectivityManager mConMgr;
@BindView(R.id.recycler_view) RecyclerView moviesList;
MovieAdapter adapter;
private String sPreferredType;
private final String MOVIES_SAVED_STATE = "movies";
boolean isRestoredState;
private final String IS_RESTORED_SAVED_STATE = "detailrestored";
private final String CURRENT_SCROLL_POSITION = "currentScrollPosition";
private GridLayoutManager layoutManager;
List<Movie> Movies;
int currentScrollPosition = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
if (BuildConfig.DEBUG_MODE) {
Stetho.initialize(
Stetho.newInitializerBuilder(this)
.enableDumpapp(
Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this)).build());
OkHttpClient client = new OkHttpClient();
client.networkInterceptors().add(new StethoInterceptor());
}
int mNoOfColumns = Utility.calculateNoOfColumns(getApplicationContext());
mConMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
isRestoredState = false;
Movies = DummyMovies.getMovieList();
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(MOVIES_SAVED_STATE)) {
Movies = savedInstanceState.getParcelableArrayList(MOVIES_SAVED_STATE);
}
if(savedInstanceState.containsKey(IS_RESTORED_SAVED_STATE))
{
isRestoredState = true;
}
if (savedInstanceState.containsKey(CURRENT_SCROLL_POSITION)) {
currentScrollPosition = savedInstanceState.getInt(CURRENT_SCROLL_POSITION, 0);
}
}
layoutManager = new GridLayoutManager(this, mNoOfColumns);
moviesList.setLayoutManager(layoutManager);
adapter = new MovieAdapter(Movies, this);
moviesList.setAdapter(adapter);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(CURRENT_SCROLL_POSITION, layoutManager.findFirstVisibleItemPosition());
outState.putParcelableArrayList(MOVIES_SAVED_STATE, (ArrayList<? extends Parcelable>) Movies);// adapter.movieList.toArray());
outState.putBoolean(IS_RESTORED_SAVED_STATE,isRestoredState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(MOVIES_SAVED_STATE)) {
Movies = savedInstanceState.getParcelableArrayList(MOVIES_SAVED_STATE);
}
if (savedInstanceState.containsKey(CURRENT_SCROLL_POSITION)) {
currentScrollPosition = savedInstanceState.getInt(CURRENT_SCROLL_POSITION,0);
layoutManager.scrollToPosition(currentScrollPosition);
}
}
}
@Override
protected void onStart() {
super.onStart();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
sPreferredType = preferences.getString("chosenSortType1", "popular");
if(Movies.get(0).getId()== 0) {
NetworkInfo networkInfo = mConMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected() && !sPreferredType.equalsIgnoreCase("favorites")) {
LoadMoviesPage(sPreferredType);
} else {
LoadDefaultPage();
}
}
}
private void LoadDefaultPage() {
new FavoriteMoviesTask(MainActivity.this, moviesList).execute();
}
public void LoadMoviesPage(String prefType) {
new DownloadMoviesTask(MainActivity.this, prefType, moviesList,currentScrollPosition).execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemThatWasClickedId = item.getItemId();
if (itemThatWasClickedId == R.id.action_settings) {
Intent settingsIntent = new Intent(getBaseContext(), SettingsActivity.class);
startActivity(settingsIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onListItemClick(int clickedItemIndex) {
onSaveInstanceState(null);
}
}
|
C#
|
UTF-8
| 594
| 2.796875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommonCode
{
public class ProgramDescription
{
public string Name { get; set; }
public System.Type Type { get; set; }
public ProgramDescription()
{
}
public ProgramDescription(System.Type type)
{
Name = type.Name;
Type = type;
}
public IProgram CreateNewInstance()
{
return Activator.CreateInstance(Type) as IProgram;
}
}
}
|
PHP
|
UTF-8
| 588
| 2.671875
| 3
|
[] |
no_license
|
<?php
declare(strict_types=1);
namespace BS\SchoolBoard\FactoryMethod\Strategy\Response;
use BS\SchoolBoard\Entity\SchoolBoard\SchoolBoardInterface;
/**
* Interface GeneratorInterface
*
* @package BS\SchoolBoard\FactoryMethod\Strategy\Response
*/
interface GeneratorInterface
{
/**
* @param \BS\SchoolBoard\Entity\SchoolBoard\SchoolBoardInterface $schoolBoard schoolBoard
*
* @return \BS\SchoolBoard\Strategy\Response\GeneratorInterface
*/
public function make(SchoolBoardInterface $schoolBoard): \BS\SchoolBoard\Strategy\Response\GeneratorInterface;
}
|
Java
|
UTF-8
| 1,105
| 1.835938
| 2
|
[] |
no_license
|
package ir.sharif.math.ap99_2.tinsta_shared.profile.event;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import ir.sharif.math.ap99_2.tinsta_shared.event.Event;
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = SetToNotShowBirthdayEvent.class, name = "SetToNotShowBirthdayEvent"),
@JsonSubTypes.Type(value = SetToNotShowEmailEvent.class, name = "SetToNotShowEmailEvent"),
@JsonSubTypes.Type(value = SetToNotShowPhoneNumberEvent.class, name = "SetToNotShowPhoneNumberEvent"),
@JsonSubTypes.Type(value = SetToShowBirthdayEvent.class, name = "SetToShowBirthdayEvent"),
@JsonSubTypes.Type(value = SetToShowEmailEvent.class, name = "SetToShowEmailEvent"),
@JsonSubTypes.Type(value = SetToShowPhoneNumberEvent.class, name = "SetToShowPhoneNumberEvent"),
})
public abstract class InfoPrivacyEvent extends Event {
public InfoPrivacyEvent() {
}
public InfoPrivacyEvent(Object source) {
super(source);
}
}
|
Java
|
UTF-8
| 16,753
| 1.734375
| 2
|
[] |
no_license
|
package org.xtext.urdf.generator;
import java.io.File;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.xtext.EcoreUtil2;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xtext.urdf.myURDF.AssignNewValue;
import org.xtext.urdf.myURDF.Collision;
import org.xtext.urdf.myURDF.DotExpression;
import org.xtext.urdf.myURDF.Inertial;
import org.xtext.urdf.myURDF.Link;
import org.xtext.urdf.myURDF.MyURDFPackage;
import org.xtext.urdf.myURDF.NamedElement;
import org.xtext.urdf.myURDF.ReUseAble;
import org.xtext.urdf.myURDF.Reuse;
import org.xtext.urdf.myURDF.Robot;
import org.xtext.urdf.myURDF.Topology;
import org.xtext.urdf.myURDF.URDFAttrFloat;
import org.xtext.urdf.myURDF.URDFAttrINT;
import org.xtext.urdf.myURDF.URDFAttrNumeric;
import org.xtext.urdf.myURDF.URDFAttrSTRING;
import org.xtext.urdf.myURDF.URDFAttrSignedNumeric;
import org.xtext.urdf.myURDF.Visual;
import org.xtext.urdf.validation.CyclesValidator;
import org.xtext.urdf.validation.GenericTree;
import org.xtext.urdf.validation.GenericTreeNode;
public class UrdfGenerator
{
List<String> originList = Arrays.asList("x","y","z","roll","pitch","yaw");
HashMap<String,String> originKeyValues = new HashMap<String,String>();;
public Robot getRobot(Resource res)
{
return (Robot)EcoreUtil2.getObjectByType(res.getContents(),MyURDFPackage.eINSTANCE.getRobot());
}
public String generateURDF(Resource res)
{
String urdf = "";
try {
urdf = generate(getRobot(res));
} catch (Exception e) {
e.printStackTrace();
}
return urdf;
}
public String generate(Robot robot) throws Exception {
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = docBuilder.newDocument();
String type = robot.eClass().getName();
Element rootElement = doc.createElement(type);
rootElement.setAttribute("name", robot.getName());
doc.appendChild(rootElement);
EList<EObject> totalList = new BasicEList<EObject>();
totalList.addAll(robot.getLinks());
totalList.addAll(robot.getJoint());
Iterator<EObject> it = totalList.iterator();
while (it.hasNext()) {
EObject entry = (EObject) it.next();
try {
generateTag(doc, rootElement ,entry);
} catch (Exception e) {
e.printStackTrace();
}
// destination.appendChild(doc.createTextNode(entry.eContainingFeature().toString()));
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("c:\\temp\\" + robot.getName() + ".xml"));
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(source, result);
//This requires a Graphviz installation on the OS.
generateGraphViz(robot.getTopologies());
return source.toString();
}
private void generateGraphViz(EList<Topology> topologies) {
if(topologies == null || topologies.isEmpty()) {
return;
}
GraphViz gv = new GraphViz();
gv.addln(gv.start_graph());
//gv.addln("rankdir=LR"); this gives a horizontal graph. Display is better top-down.
GenericTree<String> tree = getTree(topologies);
for (GenericTreeNode<String> node : tree.getAllNodes()) {
if(tree.getRoot().equals(node)) {
continue;
} else {
gv.addln(node.getParent() + " [shape=box, color=black]");
gv.addln(node.getParent() + "_" + node.getData() + " [shape=ellipse, color=blue]");
gv.addln(node.getParent() + " -> " + node.getParent()+"_"+node.getData() + ";");
if(tree.isLeafNode(node)) {
gv.addln(node.getData() + " [shape=box, color=black]");
}
gv.addln(node.getParent()+"_"+node.getData() + " -> " + node.getData() + ";");
}
}
gv.addln(gv.end_graph());
System.out.println(gv.getDotSource());
String type = "png";
File out = new File(GraphViz.TEMP_DIR + "\\urdfGraph." + type);
gv.writeGraphToFile( gv.getGraph( gv.getDotSource(), type ), out );
}
public EObject checkType(Field f, EObject entry) {
EObject temp = null;
if (entry.getClass().getPackage().getName().equals("org.xtext.urdf.myURDF.impl")) {
try {
temp = (EObject)f.get(entry);
} catch (Exception e) {
// ignore
}
}
return temp;
}
@SuppressWarnings("unchecked")
public Element generateTag(Document doc, Element destination, EObject entry) throws Exception {
String type = entry.eClass().getName();
String superType = entry.getClass().getSuperclass().getSimpleName();
Field[] fields = entry.getClass().getDeclaredFields();
Field[] superfields = entry.getClass().getSuperclass().getDeclaredFields();
Field[] total = Stream.concat(Arrays.stream(fields), Arrays.stream(superfields)).toArray(Field[]::new);
Element tag = null;
tag = doc.createElement(type);
entry = revertToOriginalName(entry);
if(superType != null && superType.equalsIgnoreCase("reuseableimpl") && hasFeature(entry,"isReuseOf")) {
EStructuralFeature ft = entry.eClass().getEStructuralFeature("isReuseOf");
EObject aReuseAble = (EObject)entry.eGet(ft);
if(aReuseAble != null) {
EObject merged = mergeURDFObject(entry,aReuseAble);
generateTag(doc, destination, merged);
return null;
}
}
manageInterfaceTypes(doc,superType,destination,tag);
for(Field f : total){
if (f.getName().contains("_EDEFAULT") ||
f.getName().equals(null) ||
f.getName().equals("fromTopo")) {
// ignore
} else {
f.setAccessible(true);
if(checkType(f, entry)!=null) {
//A link does not know whether it is a parent or child link - therefore parent/child
// tags has to be handled while traversing the joint
if(type.equalsIgnoreCase("joint") && f.getType().isAssignableFrom(Link.class)) {
Element e = null;
if(f.getName().equalsIgnoreCase("childof")) {
e = doc.createElement("child");
} else if(f.getName().equalsIgnoreCase("parentof")) {
e = doc.createElement("parent");
}
Link cLink = (Link)f.get(entry);
e.setAttribute("link", cLink.getName());
tag.appendChild(e);
} else if(isAttr(f)) {
if(f.getName().equalsIgnoreCase("pathToFile")) {
tag.setAttribute("filename", getAttributeValue(f,entry).replace("\t", "\\t"));
} else if(f.getName().equalsIgnoreCase("massKilogram")) {
tag.setAttribute("value", getAttributeValue(f,entry));
} else {
if(type.equalsIgnoreCase("origin")) {
manageOriginFields(tag,f,entry);
} else {
tag.setAttribute(f.getName(), getAttributeValue(f,entry));
}
}
} else {
generateTag(doc, tag, (EObject)f.get(entry));
}
} else if (f.getType().isAssignableFrom(EList.class)) {
EList<EObject> list = (EList<EObject>)f.get(entry);
if(list != null) {
for (int i = 0; i < list.size(); i++) {
if(list.get(i) != null) {
generateTag(doc,tag ,list.get(i));
}
}
}
} else {
if((""+f.get(entry)).equalsIgnoreCase("null")) {
//ignore null attributes
} else {
tag.setAttribute(f.getName(),""+f.get(entry));
}
}
}
}
return destination;
}
private EObject revertToOriginalName(EObject entry) {
if(entry instanceof NamedElement && ((NamedElement)entry).getName() != null && ((NamedElement)entry).getName().startsWith("_")) {
//revert to original name after renaming in derived state
((NamedElement)entry).setName(((NamedElement)entry).getName().substring(1));
}
return entry;
}
private void manageInterfaceTypes(Document doc, String superType, Element destination, Element tag) {
String pureName = superType.toLowerCase().replace("impl", "");
List<String> interfaceList = Arrays.asList("geometry","material");
if(interfaceList.contains(pureName)) {
pureName = Character.toString(pureName.charAt(0)).toUpperCase()+pureName.substring(1);
Element supertag = doc.createElement(pureName);
destination.appendChild(supertag).appendChild(tag);
} else {
destination.appendChild(tag);
}
}
@SuppressWarnings("unchecked")
private EObject mergeURDFObject(EObject entry, EObject aReuseAble) {
//aReuseAble = the object to be reused from
//entry = the object that reuses
Link reuseCopy = null;
if(aReuseAble instanceof Link) {
reuseCopy = (Link)EcoreUtil2.copy(aReuseAble);
}
//Avoid going into reuse mode in 'generateTag' with the new copy object - by setting null in isreuseof
reuseCopy.setIsReuseOf(null);
((NamedElement)reuseCopy).setName(((NamedElement)entry).getName());
EStructuralFeature ft = entry.eClass().getEStructuralFeature("reuse");
//Now add or edit the properties/features from the entry object to the reuseCopy object
EObjectContainmentEList<Reuse> reuseList = (EObjectContainmentEList<Reuse>)entry.eGet(ft);
if(reuseList == null || reuseList.isEmpty()) {
//nothing to add or edit
return reuseCopy;
} else {
for (Reuse reuse : reuseList) {
//Add:
ReUseAble reUseAbleAdd = reuse.getAdd();
if(reUseAbleAdd != null) {
EObject merged = addProperties(reUseAbleAdd,reuseCopy);
return merged;
}
//Edit:
AssignNewValue newValue = reuse.getEdit();
//For debugging
//String value = ((URDFAttrSignedNumericImpl)newValue.getNewReuseable()).getValue();
DotExpression expr = (DotExpression)newValue.getGetRef();
//For debugging: MassInKiloGrams
//String name = expr.getTail().eContainingFeature().getName();
//Now we compare the object id for the container object/parent object of entry (which holds the new value that we want to assign) with the container object of in the Object we reuse from
EObject parent = expr.getTail().eContainer();
//We have to use the container object to compare with - as URDFAttr objects has different id in entry and aReUseable
List<EObject> list = (List<EObject>)EcoreUtil2.getAllContentsOfType(aReuseAble, expr.getTail().eContainer().getClass());
for (EObject obj : list) {
//Parent holds the new value
//obj holds the old value
if(obj == parent) {
//temp hold old value
EStructuralFeature aFeature = expr.getTail().eContainingFeature();
EObject oldValue = (EObject)obj.eGet(aFeature);
//Set new value
obj.eSet(aFeature, newValue.getNewReuseable());
reuseCopy = (Link)EcoreUtil2.copy(aReuseAble);
reuseCopy.setIsReuseOf(null);
((NamedElement)reuseCopy).setName(((NamedElement)entry).getName());
//Put the old value back
obj.eSet(aFeature, oldValue);
return reuseCopy;
}
}
}
}
return null;
}
private EObject addProperties(ReUseAble addProperties, Link baseObject) {
if(addProperties instanceof Inertial) {
baseObject.setInertial((Inertial)addProperties);
} else if(addProperties instanceof Visual) {
baseObject.getVisual().add((Visual)addProperties);
} else if(addProperties instanceof Collision) {
baseObject.getCollision().add((Collision)addProperties);
}
return baseObject;
}
private void manageOriginFields(Element tag, Field f, EObject entry) {
// consider using entry.hashCode() to make sure we work on the same origin object.
// it should not be a problem since this method only is called from generateTag which deals with one EObject at a time
if(originList.contains(f.getName())) {
originKeyValues.put(f.getName(), getAttributeValue(f,entry));
}
if(originKeyValues.containsKey("x") && originKeyValues.containsKey("y") && originKeyValues.containsKey("z")) {
tag.setAttribute("xyz",originKeyValues.get("x") + " " + originKeyValues.get("y") + " " + originKeyValues.get("z"));
originKeyValues.remove("x"); originKeyValues.remove("y"); originKeyValues.remove("z");
}
if(originKeyValues.containsKey("roll") && originKeyValues.containsKey("pitch") && originKeyValues.containsKey("yaw")) {
tag.setAttribute("rpy",originKeyValues.get("roll") + " " + originKeyValues.get("pitch") + " " + originKeyValues.get("yaw"));
originKeyValues.remove("roll"); originKeyValues.remove("pitch"); originKeyValues.remove("yaw");
}
}
private boolean isAttr(Field f) {
if(f.getType().isAssignableFrom(URDFAttrSignedNumeric.class) ||
f.getType().isAssignableFrom(URDFAttrNumeric.class) ||
f.getType().isAssignableFrom(URDFAttrSTRING.class) ||
f.getType().isAssignableFrom(URDFAttrFloat.class) ||
f.getType().isAssignableFrom(URDFAttrINT.class)) {
return true;
} else {
return false;
}
}
private String getAttributeValue(Field field, EObject eo) {
String temp = null;
try {
if(field.getType().isAssignableFrom(URDFAttrSignedNumeric.class)) {
URDFAttrSignedNumeric aNum = (URDFAttrSignedNumeric)field.get(eo);
temp = aNum.getValue();
} else if(field.getType().isAssignableFrom(URDFAttrNumeric.class)) {
URDFAttrNumeric aNum = (URDFAttrNumeric)field.get(eo);
temp = aNum.getValue();
}else if(field.getType().isAssignableFrom(URDFAttrSTRING.class)) {
URDFAttrSTRING aStr = (URDFAttrSTRING)field.get(eo);
temp = aStr.getValue();
}else if(field.getType().isAssignableFrom(URDFAttrFloat.class)) {
URDFAttrFloat aFloat = (URDFAttrFloat)field.get(eo);
temp = ""+aFloat.getValue();
}else if(field.getType().isAssignableFrom(URDFAttrINT.class)) {
URDFAttrINT aInt = (URDFAttrINT)field.get(eo);
temp = ""+aInt.getValue();
}
} catch (Exception e) {
e.printStackTrace();
}
return temp;
}
private boolean hasFeature(EObject obj, String featureName) {
for(EStructuralFeature feature : obj.eClass().getEAllStructuralFeatures()) {
if(feature.getName().equalsIgnoreCase(featureName)) {
return true;
}
}
return false;
}
public GenericTree<String> getTree(EList<Topology> topoList) {
GenericTree<String> tree = new GenericTree<String>();
CyclesValidator validator = new CyclesValidator();
//Start to get the root topologies
EList<Topology> rootList = validator.getRootTopologies(topoList, false);
if(rootList == null) {
return null;
}
for (Topology topo : rootList) {
GenericTreeNode<String> node = validator.buildNodeChainFromTopology(topo, null);
if(tree.getRoot() == null) {
tree.setRoot(node.getTopNode());;
} else if(tree.getRoot().equals(node.getTopNode())) {
if(!node.getTopNode().getChildren().isEmpty()) {
tree.getRoot().addChild(node.getTopNode().getChildAt(0));
}
} else {
System.out.println("It should not be possible to end here");
}
System.out.println(tree.toStringWithDepth());
}
topoList.removeAll(rootList);
//build rest of the tree
for (Topology topo : topoList) {
GenericTreeNode<String> parentNode = tree.find(topo.getParent().getName());
validator.buildNodeChainFromTopology(topo.getChild(), parentNode);
System.out.println(tree.toStringWithDepth());
}
return tree;
}
}
|
Java
|
UTF-8
| 1,257
| 2.03125
| 2
|
[] |
no_license
|
package org.comroid.auth.repo;
import org.comroid.auth.entity.UserAccount;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
public interface AccountRepository extends CrudRepository<UserAccount, String> {
@Query("select u from UserAccount u where u.sessionId = ?1")
Optional<UserAccount> findBySessionId(String sessionId);
@Query("select u from UserAccount u where u.username = ?1")
Optional<UserAccount> findByUsername(String username);
@Query("select u from UserAccount u where u.email = ?1")
Optional<UserAccount> findByEmail(String email);
@Query("select u from UserAccount u where u.emailVerifyCode = ?1")
Optional<UserAccount> findByEmailVerificationCode(String code);
@Query("select u from UserAccount u where u.changePasswordCode = ?1")
Optional<UserAccount> findByPasswordUpdateCode(String code);
@Modifying(clearAutomatically = true)
@Transactional
@Query("update UserAccount u set u.sessionId = ?2 where u.uuid = ?1")
void setSessionId(String id, String sessionId);
}
|
C++
|
UTF-8
| 246
| 2.734375
| 3
|
[] |
no_license
|
#ifndef DOG_HPP
#define DOG_HPP
#include "Animal.hpp"
class Dog: public Animal
{
public:
virtual void makeSound(void) const;
Dog &operator=(Dog const &rhs);
Dog(Dog const &rhs);
Dog(std::string type);
Dog();
virtual ~Dog();
};
#endif
|
PHP
|
UTF-8
| 174
| 2.78125
| 3
|
[] |
no_license
|
<?php
$a = 'abc';
var_dump($a);
// null
var_dump($b);
// null
unset($a);
var_dump($a);
// check if variable exist
$d = '';
var_dump(isset($d));
var_dump(isset($zzzzzz));
|
C++
|
UTF-8
| 5,481
| 3.40625
| 3
|
[] |
no_license
|
Multithreading
До многоядерных процессоров
ускорение выполнения программ
out-of-order execution
SIMD
Многопоточность была и раньше и реализовалась с помощью прерываний
Можно также несколько компьютеров использовать с одной расшареной памятью,
или без шареной памяти (concurrent и distributed соответственно)
Программа может не выигрывать от распараллелирования, так как у процессор,
диск и оперативная память в одном экземпляре и все может упираться в их ресурс
Привет Скакову
std::thread th([]()
{
...
});
th.join() -- дождаться выполнения потока
th.detach() -- какая-то функция, до конца не понял. Функция нужна очень редко, в очень паталогических случаях
поток начинает выполнение сразу после объявления, если в него передана функция
Также можно создать с помощью пустого конструктора, а потом запустить уже на функции
Это легковесная обертка, у нее небольшой интерфейс
Проблемы многопоточности:
std::array<int, 10000> accounts;
void transfer(size_t from, size_t to, int account)
{
if (accounts[from] < amount)
thrwo insufficient_fund();
accounts[from] -= amount;
accounts[to] += amount;
}
// проблемы в том, что можем списать одновременно x денег с одного аккаунта и у нас может стать меньше 0 денег.
// В разных потоках проерка прошла без проблем. Также если две операции на одном аккаунте, мы можем перекрыть
// запись в accounts[to] так как там три атомарные операции.
Mutexes
std::mutex m;
void transfer(size_t from, size_t to, int account)
{
std::lock_guard<std::mutex> lg(m); // lock_guard -- умная оболочка для мьютекса. Работает с разными мьютексами (их есть несколько)
if (accounts[from] < amount)
throw insufficient_fund();
accounts[from] -= amount;
accounts[to] += amount;
}
Закон Амдала
Пусть у нас есть alpha кода - должна выполняться последовательно,
а 1 - alpha может выполняться параллельно
и N - количество исполнителей (потоков)
alpha = s
p = 1 - alpha
N == 1 | s | p |
N == 2 | s | p/2|
N == 3 | s |p/3|
1/(alpha + (1 - alpha) / N)
struct account {
int money;
std::mutex m;
}
void transfer(size_t from, size_t to, int account)
{
std::lock_guard<std::mutex> lg(accounts[from].m);
std::lock<std::mutex> lg2(accounts[to].m);
if (accounts[from].money < amount)
throw insufficient_fund();
accounts[from].money -= amount;
accounts[to].money += amount;
}
Теперь при переводе со счета x на y и с a на b то мьютекса не будет, так как теперь на каждый аккаунт свой мьютекс
Либо если переводим со счета a на a, undef
Но теперь при переводе с a на b и b на a одновременно в первой строчке оба потока залочат мьютексы обратного перевода
И оба будут ждать бесконечно пока во второй строке не разлочится мьютекс
Это как-то связано с состоянием гонки.
Пример -- запустили два раза одновременно transfer и непонятно какой из них выполнится первым. Второй может и не выполниться
состояние гонки -- ситуация, когда результат выполнения зависит от того, в каком порядке выполнятся потоки.
Проблема, описанная выше -- deadlock
Чтобы ее решить можно сначала лочить минимум, потом максимум.
void transfer(size_t from, size_t to, int account)
{
if (from != to)
std::lock_guard<std::mutex> lg(accounts[min(from, to)].m);
std::lock<std::mutex> lg2(accounts[max(from, to)].m);
if (accounts[from].money < amount)
throw insufficient_fund();
accounts[from].money -= amount;
accounts[to].money += amount;
}
Можно нарисовать граф мьютексов, где вершины это мьютексы, а ребро из a в b есть если какой-то поток, удерживая мьютекс
a может просить мьютекс b.
Если есть цикл в этом графе, то есть вероятность дедлока. Для возникновения дедлока требуется столько потоков, сколько ребер в цикле
|
Markdown
|
UTF-8
| 3,254
| 2.6875
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
---
id: jwt-blacklisting
title: JWT Blacklisting
sidebar_label: JWT Blacklisting
---
[JWT](https://jwt.io/) Blacklisting is one of the RIG's core features. Imagine a use case where someone does a malicious action using specific JWT. By blacklisting this JWT, you can prevent any other malicious actions. Once it's blacklisted, user is not able to do any action within the RIG (unless it's an unsecured action -- e.g. unsecured reverse proxy endpoint).
You can blacklist a JWT via REST API call to `POST :4010/v3/session-blacklist` and in body specify the `sessionId` and `validityInSeconds`. `sessionId` is by default expecting [JWT ID - JTI](https://tools.ietf.org/html/rfc7519#page-10), but you can change it via `JWT_SESSION_FIELD` env var.
Blacklist is using so called [ETS](http://erlang.org/doc/man/ets.html) tables to store JTIs and their expiration time. These information are automatically synchronized across RIG cluster. That means you can blacklist a JWT via whatever RIG node and it will apply to all RIG nodes. Blacklisted JTIs in ETS tables are cleaned up based on the `validityInSeconds` property provided in a request.
> `validityInSeconds` should be ideally set to at least _**JWT expiration time - current time**_.
## API
There are 2 APIs that are easily accessible via built-in Swagger UI (`your_host:4010/swagger-ui`).
- `POST :4010/v3/session-blacklist` - to blacklist a JWT
- `GET :4010/v3/session-blacklist/{sessionId}` - to check whether JWT is blacklisted at the moment
## Example
JWT used below has the following payload:
```json
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022,
"jti": "johndoe",
"exp": 4516239022
}
```
Run in terminal:
```bash
# run RIG - note the "secured" field in the PROXY_CONFIG_FILE
docker run -d --name rig \
-e PROXY_CONFIG_FILE='[{"id":"service","name":"service","auth_type":"jwt","auth":{"use_header":true,"header_name":"Authorization","use_query":false,"query_name":""},"versioned":false,"version_data":{"default":{"endpoints":[{"id":"secured","path_regex":"todos/1","method":"GET","secured":true}]}},"proxy":{"target_url":"http://jsonplaceholder.typicode.com","port":80}}]' \
-e JWT_SECRET_KEY='rigsecret' \
-p 4000:4000 \
-p 4010:4010 \
accenture/reactive-interaction-gateway
# check if JWT is blacklisted - should return "Not found.", that means it's not blacklisted
curl "http://localhost:4010/v3/session-blacklist/johndoe" \
-H "accept: application/json"
# call an API - should return some data
curl http://localhost:4000/todos/1 \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJqdGkiOiJqb2huZG9lIiwiZXhwIjo0NTE2MjM5MDIyfQ.gPP_Ya_QphNAas3NXqqlfwvyzy_TSN5sh_eMqX0Xnf4"
# blacklist the JWT for 60 seconds
curl -X POST "http://localhost:4010/v3/session-blacklist" -H "accept: application/json" -H "content-type: application/json" -d "{ \"validityInSeconds\": 60,\"sessionId\": \"johndoe\"}"
# check if JWT is blacklisted - should return empty response, that means it's blacklisted
curl "http://localhost:4010/v3/session-blacklist/johndoe" \
-H "accept: application/json"
# call an API - should return "Authentication failed."
curl http://localhost:4000/todos/1 \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJqdGkiOiJqb2huZG9lIiwiZXhwIjo0NTE2MjM5MDIyfQ.gPP_Ya_QphNAas3NXqqlfwvyzy_TSN5sh_eMqX0Xnf4"
```
You can restrict access also to your WS/SSE/Longpolling connections/subscriptions via `SUBSCRIPTION_CHECK` env var, check the [ops guide](./rig-ops-guide.md).
|
Markdown
|
UTF-8
| 1,694
| 3.9375
| 4
|
[
"MIT"
] |
permissive
|
# Programming Assignment 2: Deques and Randomized Queues
> Please navigate to the official [assignment URL](http://coursera.cs.princeton.edu/algs4/assignments/queues.html) for complete details.
Write a generic data type for a deque and a randomized queue. The goal of this assignment is to implement elementary data structures using arrays and linked lists, and to introduce you to generics and iterators.
**Dequeue.**
A double-ended queue or deque (pronounced “deck”) is a generalization of a stack and a queue that supports adding and removing items from either the front or the back of the data structure.
**Randomized queue.**
A randomized queue is similar to a stack or queue, except that the item removed is chosen uniformly at random from items in the data structure.
Performance requirements. Your randomized queue implementation must support each randomized queue operation (besides creating an iterator) in constant amortized time. That is, any sequence of m randomized queue operations (starting from an empty queue) must take at most cm steps in the worst case, for some constant c. A randomized queue containing n items must use at most 48n + 192 bytes of memory. Additionally, your iterator implementation must support operations next() and hasNext() in constant worst-case time; and construction in linear time; you may (and will need to) use a linear amount of extra memory per iterator.
**Client.** Write a client program Permutation.java that takes an integer k as a command-line argument; reads in a sequence of strings from standard input using StdIn.readString(); and prints exactly k of them, uniformly at random. Print each item from the sequence at most once.
|
Java
|
UTF-8
| 554
| 2.1875
| 2
|
[] |
no_license
|
package com.zugara.atproj.lampsplus.utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import java.lang.reflect.Method;
import java.util.HashMap;
/**
* Created by andre on 15-Dec-18.
*/
public class ApplicationUtil {
public static void startActivity(Activity srcActivity, Class dstActivity) {
Context context = srcActivity.getApplicationContext();
Intent intent = new Intent(context, dstActivity);
srcActivity.startActivity(intent);
srcActivity.finish();
}
}
|
Markdown
|
UTF-8
| 3,009
| 2.671875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
+++
# Experience widget.
widget = "experience" # See https://sourcethemes.com/academic/docs/page-builder/
headless = true # This file represents a page section.
active = true # Activate this widget? true/false
weight = 40 # Order that this section will appear.
title = "Experience"
subtitle = ""
# Date format for experience
# Refer to https://sourcethemes.com/academic/docs/customization/#date-format
date_format = "Jan 2006"
# Experiences.
# Add/remove as many `[[experience]]` blocks below as you like.
# Required fields are `title`, `company`, and `date_start`.
# Leave `date_end` empty if it's your current employer.
# Begin/end multi-line descriptions with 3 quotes `"""`.
[[experience]]
title = "Machine learning engineer"
company = "Innova SpA"
company_url = "https://www.innovatrieste.it/home.htm"
location = "Trieste, Italia"
date_start = "2019-12-01"
date_end = ""
description = """
Main activities:
* Computational Modelling
* Backend development
"""
[[experience]]
title = "Postdoctoral researcher"
company = "SISSA"
company_url = "https://www.sissa.it"
location = "Trieste, Italia"
date_start = "2017-03-08"
date_end = "2019-11-30"
description = """
Research in cognitive neuroscience. Main activities:
* Data analysis
* Data processing
* Computational Modelling
"""
[[experience]]
title = "Web developer"
company = "Physics department, Universidad de Buenos Aires"
company_url = ""
location = "Buenos Aires, Argentina"
date_start = "2016-04-01"
date_end = "2016-08-31"
description = """
Developed front and backend of a Joomla component to organize the
research done in the physics department. Technical knowledge used:
* Joomla
* PHP
* MySql
* Javascript
* JQuery
"""
[[experience]]
title = "Teaching Assistant"
company = "Universidad de Buenos Aires"
company_url = ""
location = "Buenos Aires, Argentina"
date_start = "2014-03-01"
date_end = "2016-06-30"
description = """
Taught university admission and graduate level physics. Topics included:
* Mechanics
* Thermodynamics
* Basic electrodynamics
* Basic quantum mechanics
"""
[[experience]]
title = "Undergraduate Teaching Assistant"
company = "Universidad de Buenos Aires"
company_url = ""
location = "Buenos Aires, Argentina"
date_start = "2010-04-01"
date_end = "2012-03-31"
description = """
Taught first year graduate level physics.
"""
[[experience]]
title = "PhD student"
company = """
Integrative Neuroscience Lab, Physics department, Universidad de Buenos Aires
(currently Neuroscience Lab, Universidad Torcuato di Tella)
"""
company_url = "https://www.utdt.edu/ver_contenido.php?id_contenido=10518&id_item_menu=20132"
location = "Buenos Aires, Argentina"
date_start = "2011-04-01"
date_end = "2016-03-31"
description = """
Research in cognitive neuroscience. Main activities:
* Data analysis
* Data processing
* Computational Modelling
"""
+++
|
Python
|
UTF-8
| 2,135
| 2.5625
| 3
|
[] |
no_license
|
import collections
import datetime
import gzip
import io
import json
import logging
import operator
import os
import sys
START = int(sys.argv[1]);
DELTA = int(sys.argv[2]) * 60
SUFFIX = '.json.gz'
def xy(a, b):
return {'x': a - b,
'y': b - a}
os.chdir('stations2')
paths = sorted(p for p in os.listdir() if p.endswith(SUFFIX))
latest = START - DELTA
stations = []
matrix = []
for path in paths:
t = int(path[:-len(SUFFIX)])
if t - latest >= DELTA:
assert t - latest < 2 * DELTA, '{path} follows a gap of more than {delta} seconds'.format(path=path, delta=DELTA)
latest += DELTA
with io.TextIOWrapper(gzip.open(path)) as f:
doc = json.load(f)
logging.info('{t} / {x} seconds old / {n}'.format(t=datetime.datetime.fromtimestamp(t), x=t - doc['lastUpdate'], n=len(matrix)))
row = []
i = 0
for station in sorted(doc['results'], key=operator.itemgetter('id')):
while i < len(stations) and stations[i] != station['id']:
if stations[i] > station['id']:
# a new station that's not at the end, so we have to fix all previous rows
logging.warning('{path} contains a different set of stations: {x} vs {y}'.format(path=path, **xy({x['id'] for x in doc['results']}, set(stations))))
stations.insert(i, station['id'])
for old_row in matrix:
old_row.insert(i, [0, 0])
continue
logging.warning('{path} is missing station {id}'.format(path=path, id=station['id']))
row.append([0, 0])
i += 1
if i >= len(stations): stations.append(station['id'])
row.append([station['availableBikes'], station['availableDocks']])
i += 1
assert len(row) == len(stations)
matrix.append(row)
sys.stdout.write('var DATA = ')
json.dump({'start': START,
'delta': DELTA,
'stations': stations,
'data': matrix},
sys.stdout,
separators=(',', ':'))
sys.stdout.write(';\n')
|
Java
|
UTF-8
| 809
| 2.09375
| 2
|
[] |
no_license
|
package com.example.demo.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@SuppressWarnings("serial")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="product")
public class Product implements Serializable{
@Id
private String id;
private String name;
private boolean enable;
private Double price=0.0;
private int quantity =0;
private String image;
@ManyToOne
@JoinColumn(name = "id_category")
private Category category;
@Override
public String toString() {
return "";
}
}
|
JavaScript
|
UTF-8
| 1,935
| 2.75
| 3
|
[] |
no_license
|
const express = require('express');
const expressAsyncHandler = require('express-async-handler');
const Employee = require('../models/Employee');
const authMiddleware = require('../middlewares/authMiddleware');
const employeeRouter = express.Router();
//Create Employee
employeeRouter.post('/',
authMiddleware,
expressAsyncHandler(async (req, res) => {
//Grab the user from the req.user
const userId = req.user._id
const employee = await Employee.create({
name: req.body.name,
designation: req.body.designation,
experience: req.body.experience,
reporting: userId,
});
if (employee) {
res.status(200);
res.json(employee);
} else {
res.status(500);
throw new Error('employee created failed');
}
}
));
//fetch
employeeRouter.get(
'/',
expressAsyncHandler(async (req, res) => {
const employees = await Employee.find({})
//Compare password
if (employees) {
res.status(201);
res.send(employees);
} else {
res.status(401);
throw new Error('there are no employees');
}
})
);
//update
employeeRouter.put('/:id', authMiddleware,
expressAsyncHandler(async (req, res) => {
const employee = await Employee.findById(req.params.id);
if (employee) {
const updatedEmployee = await Employee.findByIdAndUpdate(
req.params.id,
req.body,
{
new: true,
runValidators: true,
}
);
res.status(200);
res.json(updatedEmployee);
} else {
res.status(500);
throw new Error('Update failed');
}
})
);
//delete
employeeRouter.delete(
'/:id',
expressAsyncHandler(async (req, res) => {
try {
const employee = await Employee.findByIdAndDelete(req.params.id);
res.status(200);
res.send(employee);
} catch (error) {
res.json(error);
}
})
);
module.exports = employeeRouter;
|
Java
|
UTF-8
| 318
| 1.914063
| 2
|
[] |
no_license
|
package com.lms.service;
import org.springframework.web.multipart.MultipartFile;
import com.lms.model.dict.FileType;
import com.lms.model.entity.File;
public interface FileService {
public Long saveFile(MultipartFile file, FileType type);
public void deleteFile(Long id);
public File get(Long id);
}
|
Ruby
|
UTF-8
| 126
| 3.109375
| 3
|
[] |
no_license
|
def f1 x, a
x == 0 ? a : f1(x - 1, x * a)
end
def f x
f1 x, 1
end
p f 0
p f 1
p f 2
p f 3
p f 100
p f 1000
# p f 100000
|
Python
|
UTF-8
| 288
| 2.9375
| 3
|
[] |
no_license
|
from tkinter import *
root = Tk()
widget = Label(root, text="Eat at Joe's") # setting label text
# setting the background, foreqround, cursor, and font
widget.config(bg='black', fg='red', cursor='cross', font=('Times', 24, 'italic'))
widget.pack(expand=YES, fill=BOTH)
root.mainloop()
|
C
|
UTF-8
| 1,566
| 2.875
| 3
|
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main_pushswap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mtaylor <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/03 15:22:54 by mtaylor #+# #+# */
/* Updated: 2019/03/03 15:23:00 by mtaylor ### ########.fr */
/* */
/* ************************************************************************** */
#include "pushswap.h"
static void do_sort(t_stack *a, t_stack *b, int len)
{
if (len == 1 || sorted(a))
return ;
if (len == 2)
sort_two(a, 'a');
else if (len == 3)
sort_stack_of_three(a, 'a');
else if (len < QUICKSORT_BATCH + 3)
selection_sort(a, b, len);
else
quick_sort(a, b, len);
}
int main(int ac, char **av)
{
t_stack *a;
t_stack *b;
int stack_len;
int flag;
if (ac < 2)
return (0);
flag = 0;
a = create_stack();
b = create_stack();
if (ft_strequ(av[1], "-v"))
{
flag = 1;
av++;
}
stack_len = fill_stack(a, ac, av);
if (a->top)
do_sort(a, b, stack_len);
if (flag)
print_stack(a);
free_stack(a);
free_stack(b);
return (0);
}
|
Python
|
UTF-8
| 3,116
| 2.75
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
import sys
import cv2
import numpy as np
from .utils.transformer import imageTransformer
from .polygones import translate_poly, transform_M_poly
from .utils.util import getBbox
def rotate_layer(layers, dictRotation):
"""Rotate Layers.
Args:
layers (list[ndarray]): list with the input images.
dictRotation (dict): keys & values:
'theta' : int # rotation around the x axis.
'phi' : int # rotation around the y axis.
'gamma' : int # rotation around the z axis.
Return:
list[ndarray] : list of image rotated
"""
global imgBiggerSize, imgOriginalSize, M, imageCroped, hTr, wTr, p
theta = dictRotation['theta'] # rotation around the x axis
phi = dictRotation['phi'] # rotation around the y axis
gamma = dictRotation['gamma'] # rotation around the z axis
if len(layers) > 1:
result = all(elem.shape == layers[0].shape for elem in layers)
if not result:
print("All images must have the same shape")
sys.exit()
transformedImages = []
for n, img in enumerate(layers):
# Rotate Image
image, imgPerspLargeBorder, M = imageTransformer(img, theta, phi, gamma)
if n == 0:
# Get Image perfect size
imgBiggerSize = image.shape[:2]
imgOriginalSize = img.shape[:2]
hTr, wTr = getBbox(imgPerspLargeBorder)
hSt, wSt = getBbox(np.flip(imgPerspLargeBorder))
p = 2
# Crop Image
imageCroped = image[hTr-p: imgBiggerSize[0] - hSt+p, wTr-p: imgBiggerSize[1] - wSt+p]
imageCroped = cv2.copyMakeBorder(imageCroped.copy(), 1,1,1,1, cv2.BORDER_CONSTANT, value=(0,0,0))
transformedImages.append(imageCroped)
return transformedImages
def rotate_poly(polygone):
"""Rotate Polygone.
Args:
polygone (list): The input polygone [x1,y1,x2,y2,x3,y3,x4,y4].
Return:
list: polygone [x1,y1,x2,y2,x3,y3,x4,y4]
"""
# Rotate
transf_points = transform_M_poly(polygone, M)
# Translate Bigger
hh = round(imgBiggerSize[0]/4)
ww = round(imgBiggerSize[1]/4)
transf_points = translate_poly(transf_points, hh, ww)
# Crop
transf_points = translate_poly(transf_points, -hTr+p, -wTr+p)
return transf_points
def get_mask():
"""Create a mask of rotate layer.
Return:
ndarray: Image mask
"""
# Get Image Rectangle
height, width = imgOriginalSize
pointsMask = np.array([0,0,width,0,width,height,0,height])
pointsMask = rotate_poly(pointsMask)
# Create empty image
mask = np.zeros_like(imageCroped)
# Create Mask
pointsMask = np.array(pointsMask).reshape((-1,1,2))
mask = cv2.fillPoly(mask, pts=[pointsMask], color=(255,255,255))
return mask
|
Markdown
|
UTF-8
| 1,196
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
---
layout: post
title: Terraform Basics
date: 2017-09-19
summary: Defines all your infrastructure as code. I learned this through a lot of trial and error over the course of a week.
categories: terraform iac
---
#### Files and Folders
* `.tfstate` Stores the current configuration of your infrastructure. This can be local and remote (see: [terraform backend](https://www.terraform.io/docs/backends)).
* `.tf` Terraform configuration file which defines the parameters of your infrastructure.
* `.terraform` This is a folder which stores your state.
* `.tfstate.backup` Stores the result of a terraform plan? Not entirely sure of the purpose.
#### Commands
```
terraform init
```
Initialises a `.terraform` working directory and a blank `.tfstate`.
```
terraform import [parameters] ID
```
Imports state into your `.tfstate` from your existing infrastructure. Check the correct syntax at [the docs](https://www.terraform.io/docs/commands/import.html).
```
terraform plan
```
Checks your `.tfstate` against what you've configured in your `.tf` files.
```
terraform apply
```
Applies the changes (if any) specified in `terraform plan`. Be very careful with this command!
|
C++
|
UTF-8
| 1,167
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
#include "thread_pool.h"
thread_pool::~thread_pool()
{
stop();
}
void thread_pool::init_thread_size(int size)
{
for (int i = 0; i < size; ++i)
{
auto t = std::make_shared<std::thread>(std::bind(&thread_pool::run_task, this));
threads_.emplace_back(t);
}
}
void thread_pool::stop()
{
std::call_once(call_flag_, [this]{ stop_impl(); });
}
std::size_t thread_pool::size()
{
std::unique_lock<std::mutex> lock(mutex_);
return task_queue_.size();
}
void thread_pool::run_task()
{
while (true)
{
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mutex_);
cond_.wait(lock, [this]{ return threadpool_stoped_ || !task_queue_.empty(); });
if (threadpool_stoped_ && task_queue_.empty())
{
return;
}
task = std::move(task_queue_.front());
task_queue_.pop();
}
task();
}
}
void thread_pool::stop_impl()
{
threadpool_stoped_ = true;
cond_.notify_all();
for(auto& t: threads_)
{
if (t->joinable())
{
t->join();
}
}
}
|
Java
|
UTF-8
| 386
| 2.234375
| 2
|
[] |
no_license
|
package come.wry.dragger;
import come.wry.dragger.MVP.MainActivity;
import dagger.Component;
/**
* 作者:wry
* 时间:2017/3/20:11:43
* 说明:
*/
@Component(modules = MainModule.class) // 作为桥梁,沟通调用者 和 依赖对象库
public interface MainComponent {
//定义注入的方法 (指定注入到哪个类中)
void inject(MainActivity activity);
}
|
C#
|
UTF-8
| 1,566
| 2.53125
| 3
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SeeThroughSprite : MonoBehaviour
{
public SpriteRenderer sprite;
public Color transpartentColour;
public float speed = 1;
bool fadeInBool;
bool fadeOutBool;
void Start()
{
if(!sprite)
{
sprite = GetComponentInParent<SpriteRenderer>();
}
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.tag == "Player")
{
fadeOutBool = false;
fadeInBool = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
fadeInBool = false;
fadeOutBool = true;
}
}
void FixedUpdate()
{
sprite.color = transpartentColour;
if(fadeInBool && fadeOutBool == false)
{
if(transpartentColour.a >= .54f)
{
transpartentColour.a -= (Time.fixedDeltaTime * speed) / 100;
}
else
{
transpartentColour.a = .54f;
fadeInBool = false;
}
}
if(fadeOutBool && fadeInBool == false)
{
if (transpartentColour.a <= 1)
{
transpartentColour.a += (Time.fixedDeltaTime * speed)/100;
}
else
{
transpartentColour.a = 1;
fadeOutBool = false;
}
}
}
}
|
C++
|
UTF-8
| 3,975
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
/*
* PipelineReg.cpp
*
* Created on: 3 Jul 2012
* Author: db434
*/
#include "PipelineReg.h"
#include "../../Exceptions/InvalidOptionException.h"
// Toggle whether pipeline registers are heavily clock gated.
// 0 = either whole register is read/written, or none of it is.
// 1 = sections of each register can be used individually.
#define CLOCK_GATE 0
using namespace Instrumentation;
CounterMap<size_t> PipelineReg::active;
CounterMap<size_t> PipelineReg::hammingDist;
void PipelineReg::activity(const DecodedInst& oldVal,
const DecodedInst& newVal,
PipelineRegister::PipelinePosition stage) {
if (!Instrumentation::collectingStats()) return;
size_t width;
int hamming = 0;
switch (stage) {
// Information sent from fetch to decode:
// * encoded instruction (32 bits)
case PipelineRegister::FETCH_DECODE:
width = 32;
hamming += __builtin_popcount(oldVal.toInstruction().toInt() ^ newVal.toInstruction().toInt());
break;
// Information sent from decode to execute:
// * Up to two operands (2x32 bits)
// * Opcode and function (11 bits)
// * Channel map entry (4 bits)
// * Various other flags (5 bits?)
case PipelineRegister::DECODE_EXECUTE:
width = 12;
hamming += __builtin_popcount(oldVal.opcode() ^ newVal.opcode() );
hamming += __builtin_popcount(oldVal.predicate() ^ newVal.predicate());
if (!CLOCK_GATE || newVal.hasOperand1()) {
hamming += __builtin_popcount(oldVal.operand1() ^ newVal.operand1() );
width += 32;
}
if (!CLOCK_GATE || newVal.hasOperand2()) {
hamming += __builtin_popcount(oldVal.operand2() ^ newVal.operand2() );
width += 32;
}
if (!CLOCK_GATE || newVal.isExecuteStageOperation()) {
hamming += __builtin_popcount(oldVal.function() ^ newVal.function() );
width += 4;
}
if (!CLOCK_GATE || newVal.sendsOnNetwork()) {
hamming += __builtin_popcount(oldVal.channelMapEntry() ^ newVal.channelMapEntry());
width += 4;
}
break;
// Information sent from execute to write:
// * Result (32 bits)
// * Destination register (5 bits)
// * Destination channel (20 bits?)
// * Various other flags (3 bits?)
case PipelineRegister::EXECUTE_WRITE:
width = 3;
if (!CLOCK_GATE || newVal.hasDestReg() || newVal.sendsOnNetwork()) {
hamming += __builtin_popcount(oldVal.result() ^ newVal.result());
width += 32;
}
if (!CLOCK_GATE || newVal.hasDestReg()) {
hamming += __builtin_popcount(oldVal.destination() ^ newVal.destination());
width += 5;
}
if (!CLOCK_GATE || newVal.sendsOnNetwork()) {
hamming += __builtin_popcount(oldVal.networkDestination().flatten(Encoding::hardwareChannelID) ^ newVal.networkDestination().flatten(Encoding::hardwareChannelID));
width += 20;
}
break;
default:
throw InvalidOptionException("pipeline register index", stage);
break;
}
active.increment(width);
hammingDist.setCount(width, hammingDist[width] + hamming);
}
void PipelineReg::dumpEventCounts(std::ostream& os, const chip_parameters_t& params) {
CounterMap<size_t>::iterator it;
for (it = active.begin(); it != active.end(); it++) {
size_t width = it->first;
count_t activeCycles = it->second;
count_t hamming = hammingDist[width];
os << "<pipeline_register width=\"" << width << "\">\n";
// Only registers of these widths actually exist. All other widths are the
// result of clock gating portions of the registers.
if (width==32 || width==60 || width==84)
os << xmlNode("instances", params.totalCores()) << "\n";
os << xmlNode("active", activeCycles) << "\n"
<< xmlNode("write", activeCycles) << "\n"
<< xmlNode("hd", hamming) << "\n"
<< xmlEnd("pipeline_register") << "\n";
}
}
|
C++
|
UTF-8
| 1,065
| 2.84375
| 3
|
[] |
no_license
|
/*--------------------------------------------------------------
Copyright (C) 2021 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the prior
written consent of DigiPen Institute of Technology is prohibited.
File Name: Input.h
Project: CS230
Author: Kevin Wright
Creation date: 2/10/2021
-----------------------------------------------------------------*/
#pragma once
#include <vector>
namespace CS230 {
class InputKey {
public:
enum class Keyboard {
None, Enter, Escape, Space, Left, Up, Right, Down,
A, B, C, D, E, F, G, H, I, J,
K, L, M, N, O, P, Q, R, S, T,
U, V, W, X, Y, Z, Tilde,
Count
};
InputKey(Keyboard button);
bool IsKeyDown() const;
bool IsKeyReleased() const;
private:
Keyboard button;
};
class Input {
public:
Input();
bool IsKeyDown(InputKey::Keyboard key) const;
bool IsKeyReleased(InputKey::Keyboard key) const;
void SetKeyDown(InputKey::Keyboard key, bool value);
void Update();
private:
std::vector<bool> keyDown;
std::vector<bool> wasKeyDown;
};
}
|
Java
|
UTF-8
| 469
| 2.15625
| 2
|
[
"IJG"
] |
permissive
|
package org.apache.http.conn.scheme;
import java.io.IOException;
import java.net.InetAddress;
@Deprecated
public abstract interface HostNameResolver
{
public abstract InetAddress resolve(String paramString)
throws IOException;
}
/* Location: C:\Games\SteamLibrary\steamapps\common\Wurm Unlimited Dedicated Server\server.jar!\org\apache\http\conn\scheme\HostNameResolver.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 0.7.1
*/
|
C
|
UTF-8
| 766
| 3.703125
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
void read_word(int counts[26]);
bool equal_array(int counts1[26],int counts2[26]);
int main()
{
int a[26] = {0}, b[26] = {0};
printf("Enter first word: ");
read_word(a);
printf("Enter second word: ");
read_word(b);
bool flag = equal_array(a,b);
printf("The words are ");
if(flag)
printf("anagrams");
else
printf("not anagrams");
return 0;
}
void read_word(int counts[26])
{
int ch;
while((ch = getchar()) != '\n')
if(ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
counts[toupper(ch) - 'A']++;
}
bool equal_array(int counts1[26],int counts2[26])
{
int i = 0;
while(i < 26)
{
if(counts1[i] == counts2[i])
i++;
else
break;
}
return i == 26 ? true : false;
}
|
Python
|
UTF-8
| 12,428
| 2.546875
| 3
|
[] |
no_license
|
import pandas as pd
# read the csv file
raw_csv_data = pd.read_csv('Absenteeism_data.csv')
#expand the columns and rows display
pd.set_option('display.max_rows', 700)
pd.set_option('display.max_columns', 12)
pd.set_option('display.width', 1000)
#print(raw_csv_data)
#hena howa 3ayz y3ml copy ll csv file da w y4t3'l 3ala el copy dy 34an mybwz4 el nos5a el aslya ....
# fa 3mlna copy ll raw_csv_data w 7tenaha f el data_frame
data_frame = raw_csv_data.copy()
#print(data_frame)
# get info of the data frame
#data_frame.info()
#.............................................................................................
# a7na 3ayzen n-predict eih ? el absenteeism from work .......
# fe el columns howa mdeek column asmo absenteeism in hours fa howa mdek kol employee bl ID bta3o w howa 3'ab kam sa3a youm kam...
# example : employee ID 26 3'aab 4 hours on data 7/7/2015...
# fa el absenteeism in hours dy to3tbr "dependant variable" el howa el variable el leh 3laka bl 7aga el 3ayz a3mlha predict
# ba2y el columns asmohom "independent variables" dol mlhom4 3laka bl 7aga el 3ayz a3mlha predict bs hys3dony
#...........................................................................................
#fe columns m4 h7tagha f el analytics el h3mlo dlw2ty ... da homa hy2llo el precision aslun...zay eih ?
# el ID column da .... da ah by3rfny kol employee 3'aab kam sa3a aw b m3na asa7 men el employee el 3'ab 3adad sa3at mo3yna f youm mo3yn
# bs hal el ID da hyfedny f el analytics ???? la2 mlho4 lazma .. la2n ana 3ayz a7dd el absenteeism from work fa el ID mlho4 ay 3laka..
# fa h3mlo drop..
data_frame = data_frame.drop(['ID'],axis=1) # axis = 1 ...m3naha enk btms7 el column el asmo ID .... lw axis = 0 kda htms7 el row
# mmkn t3ml bardo del data_frame['ID'] ...hya hya
# bs lw ht3ml drop mtnsa4 t3ml assign "=" ....
#print(data_frame)
#......................................................................................
#feh el column bta3 el reason for absence b numeric values...
# ana msln lw 3ayz a3raf as3'ar w akbar value h3ml kda
#print(data_frame['Reason for Absence'].min())
#print(data_frame['Reason for Absence'].max())
#lw 3ayz a3raf el unique values el fe el column da h3ml kda
#print(data_frame['Reason for Absence'].unique())
# lw 3ayz a3ml sort ll unique values dy h3ml kda
#print(sorted(data_frame['Reason for Absence'].unique())) #hla2y en rakam 20 m4 mwgod msln..
# Note mohma awe ... el values f el column da numeric la2n el numeric values ashal b kter f el t3amol m3aha mn el text plus enha a7san
# fe el data storage la2nha bta5od memory a2l .....
# dlw2ty 34an a3ml quantitative analysis m7tag eny afsel el reason of absence column da l dummy values ( statistics ) ..h3ml kda
reason_columns = pd.get_dummies(data_frame['Reason for Absence']) # keda ana 3mlt data frame ll reason of absence lw7do
#print(reason_columns)
# ( statistics bardo ) 34an atgnb 7dos potenial multi collinearity issues.. dy 7aga kda statistics m4 fahmha bsra7a..lazm a4el el first column
# mn el reasons for absence data frame....
reason_columns = pd.get_dummies(data_frame['Reason for Absence'], drop_first = True)
#print(reason_columns)
# tb3an kda h4el el column bta3 el reason of absence mn el data frame la2n already fasaltha w 3mltha data frame lw7dha
data_frame = data_frame.drop(['Reason for Absence'], axis= 1)
#print(data_frame)
#.................................................................................
# h3ml 7aga asmha grouping ... da hysahel 3lya el analytics ... w howa eny h2sm el reasons for absence l groups ...
# kol group 3obara 3an data frame lw7do
# ana 2asemt el reason for absence l groups ... 4 groups ... kol group feh reasons mot4abha m3 b3d ....
# fa 3mlt data frame l kol group mn el 4 groups ...
#badal ma yekon 3andy 28 reason ... la2 ana 2asemthom l groups ... 4 groups ..... fa hykon sabab el absence howa wa7ed mn el groups dol bs..
# h3ml el 7war da ezay ??
#bst3ml functions asmha loc ... dy btgbly aw bt5leny a3ml access 3ala columns mo7dda...
reason_type1 = reason_columns.loc[:,1:14] # awl group hyb2a feh columns mn 1 l 14
reason_type2 = reason_columns.loc[:,15:17] # tany group feh columns mn 15 l 17 .. and so on....
reason_type3 = reason_columns.loc[:,18:21]
reason_type4 = reason_columns.loc[:,22:28]
#print(reason_type1)
#print(reason_type2)
# tab ana 3ayz yb2a kol group represented by "one column" bs w "700 rows" .. el one column da b "1" lw awl group msln el 14 columns bto3o fehom 1
# w el one column da yb2a b "0" lw mfy4 wala column mn el 14 columns el fe awl group mfhom4 zero .. tab leh b3ml kda ??
# gm3t kol group f one column w 700 rows ... 34an a4of hal feh 7ad mn el employees 3'ab mn el sho3'l bsbb ay disease mn el group da ...
# badal ma yekon 3andy 28 reason ... la2 ana 2asemthom l groups ... 4 groups ..... fa hykon sabab el absence howa wa7ed mn el groups dol bs..
# h3ml el 7war da ezay ?? bl max(axis =1)
# shof el video latef ..............
reason_type1 = reason_columns.loc[:,1:14].max(axis = 1) # kda da ydeny 1 column .. w value at each row mn el 700 ... lw el 14 columns el fe awl group da kan fehom 1 .. fa el value b 1 .. lw mfho4 1 fa yb2a b zero....
reason_type2 = reason_columns.loc[:,15:17].max(axis=1)
reason_type3 = reason_columns.loc[:,18:21].max(axis=1)
reason_type4 = reason_columns.loc[:,22:28].max(axis=1)
#print(reason_type1)
#print(reason_type2)
#................................................................................................
#dlw2ty b2a 3ayz a3ml concatenate ll data_frame w el reason_type1 w type2 w type3 w type4
data_frame = pd.concat([data_frame,reason_type1,reason_type2,reason_type3,reason_type4],axis=1)
#print(data_frame)
# fhmt b2a shwia kda ana b3ml eih ????
# ana el awl 2asemt el reason for absence l groups ... 4 groups ... kol group feh reasons mot4abha m3 b3d ....
# fa 3mlt data frame l kol group mn el 4 groups ...
# b3dha gm3t kol group f one column w 700 rows ... 34an a4of hal feh 7ad mn el employees 3'ab mn el sho3'l bsbb ay disease mn el group da ...
# badal ma yekon 3andy 28 reason ... la2 ana 2asemthom l groups ... 4 groups ..... fa hykon sabab el absence howa wa7ed mn el groups dol..
# w damagt el results bta3t el groups dy f el data_frame el aslya .........kda hysahel 3lya el analytics...
# 7aga baseta kda.............
# el columns bta3t el types esmha 0,1,2,3 .......fa 3ayz a3'yr asamehom...
# el data_frame.columns.values dy htgblk el names bta3t el columns kolha..5odhom copy paste w 7othom fe variable esmo column_names w 3'ayar
# b2a el names bta3t el columns el 3ayz t3'yrha..
#print(data_frame.columns.values)
column_names = ['Date','Transportation Expense','Distance to Work','Age',
'Daily Work Load Average', 'Body Mass Index', 'Education', 'Children' ,'Pets',
'Absenteeism Time in Hours','Reason_1', 'Reason_2','Reason_3','Reason_4'] #3'yrt asamehom ....
# b3dha 7ot asamy el columns b3d el ta3del fe el data frame bta3tk el aslya...............
data_frame.columns = column_names
#print(data_frame)
#...................................................................................
# Note 3ala ganb .... b nafs el technique el fo2 da bardo a2dr a3ml reordering ll colums
# print(data_frame.columns.values) w ha5od el values copy w paste w a7othom fe variable gded..w a3'yr fe el order bta3hom....
columns_reordered = ['Reason_1', 'Reason_2', 'Reason_3' ,'Reason_4','Date', 'Transportation Expense','Distance to Work' ,'Age',
'Daily Work Load Average', 'Body Mass Index', 'Education', 'Children', 'Pets',
'Absenteeism Time in Hours'] # reordered columns ...7othm fe el dataframe el aslya b2a
data_frame = data_frame[columns_reordered]
#print(data_frame)
#...................................................................................
# Note 3ala ganb ..... el .head() da bygblk awl 5 rows f el data frame bat3tk...
#print(data_frame.head())
#..................................................................................................................
# bl nsba ll date column h3ml 3leh shwia operations htfham ana leh 3mlt kda f el a5er .....................
# bs el awl h3ml 7aga asmha check point .. eih dy ??? h3ml copy ll data frame bta3ty el aslya w a7otha f data frame gdeda asmha df_reason_mod
# leh b3ml kda ??? enta 3mtn lazm t3ml kda kol fatra f el code ...34an lw feh mo4kla aw logical error f el code sho3'lak kolo myboz4...
# zay ma enta bt3ml save kol shwia f el code b3d ma btktb kaza satr .... 34an lw 7slt mo4kla aw el kahraba at3t el code myro74...
# fa ana kol shwia b3ml copy ll data frame el wsltlha w a7otha fe data frame gdeda............
# el data frame el gdeda asmha df_reason_mod..
# awl 7aga el date shaklo kda 07/07/2015 msln ana 3ayzo kda 07-07-2015 ( el howa shakl el timestamp)
# h3ml kda ezay ?? ..
df_reason_mod = data_frame.copy() # awl 7aga a5dt copy mn el data frame el aslya 34an m4 teboz bs aho .............
df_reason_mod['Date'] = pd.to_datetime(df_reason_mod['Date']) # ast5dmt el to_datetime dy function bt7wly l timestamp....
#print(df_reason_mod['Date']) # atb3 el date kda ... htla2eh timestamp....lw 3mlt print kda hydek date bs mn 3'er time...tab fen el time ??
# el time howa m4 byktbo ... tab lw 3ayz a3mlo access ??.....a3ml kda ... da hygblk awl row el date w el time....
#print(df_reason_mod['Date'][0])
#......................dlw2ty 3ayz afsel el days w el months ....................
# awl 7aga el months..................
# h3ml for loop telef 3ala el date column ... a7na 3arfen el date column feh date w time fa ana 3ayz el date mle4 da3wa bl time
# fa h-access element element fe el for loop dy w kol element h-access el month bta3o bs .......w h7ot el months dy f el list
months_list = []
for i in range(700):
months_list.append(df_reason_mod['Date'][i].month)
#print(months_list) # dy el list el feha el months ...7ot el months b2a f el data frame bt3tk...
df_reason_mod['months_value'] = months_list
#print(df_reason_mod)
# nafs el klam h3mlo 3ala el days......................
# h3ml function esmha get_day ...dy bta5od el date kamel w trg3lo el day
def get_day(date_value): # one parameter el howa el date
return date_value.weekday() # .weekday() dy function btrg3 el day of the date ...
df_reason_mod['day of the week'] = df_reason_mod['Date'].apply(get_day) #kol element mwgod f el date column f el data frame bta3ty h-apply 3leh function asmha get_day el ana m3rfha fo2 w b3d ma apply h7ot el day da f el list esmha "day of the week" h7otha gowa el data frame bta3ty y3ny htb2a column gowaha.....
#print(df_reason_mod)
# eih b2a el ana 3mlto kol da f el date column ??
# ana aslun kont 3ayz afara2 el date column l days w months lw7dohom ...........
# 34an da hydeny accuracy w precision a7san b kter.....
# fa 34an a3ml kda lazm a7wl el date l timestamp b3dha afsel el date da l days w months..........
#...................................................................................................
#a5er column h3mlo pre-processing howa el education.......................
# lw 3mlna count ll education column y3ny shofna el values el feh w kol value mtkrr kam mara....
# hla2y en value 1 mtkrr 583 ..... w ba2y el values el hya 2,3,4 mtkrren 2olyl awl ....
#print(df_reason_mod['Education'].value_counts())
# fa m3na kda en a3'lab el employees el 3ndy fe educational state b 1 ...ayan kanet el 1 dy b2a ana m3rf4 ....
# fa 2alk 5las ana hfsel el education l 2 columns ...wa7d el value bta3to howa el 583 w el tany feh el count bta3 ba2y el values(2,,3,4) la2n kda kda homa 3ddhom 2olyl...
# tab h3ml kda ezay????
# h3mlhom f shakl map .... el nas el 3ndhom key = 1 el value bta3thom b 583
# w el nas ely el key bta3hom b 2,3,4 lehom value lw7dhom el howa 3ddhom kolhm m3 b3d
df_reason_mod['Education'] = df_reason_mod['Education'].map({1:0,2:1,3:1,4:1})
# garab b2a a3ml counts ll education kda b2a ...........htla2y howa el keys el mwgoda 0,1 bs... w el values bta3t el 0 hya 583 w el values bta3t el 1 hya mgmo3 el counts bta3(2,3,4)..........
#print(df_reason_mod['Education'].value_counts())
#................................................................................................
#a3ml checkpoint a5era b2a
df_preprocessed = df_reason_mod.copy()
#print(df_preprocessed)
|
SQL
|
UTF-8
| 641
| 3.28125
| 3
|
[] |
no_license
|
-- This script Will only run if you are using Oracle Database 10g
-- or higher
-- This script does the following:
-- Connects as the store user and creates items for the
-- Oracle Database 10g examples featured in Chapter 1
CONNECT store/store_password;
-- BINARY_FLOAT and BINARY_DOUBLE example
CREATE TABLE binary_test (
bin_float BINARY_FLOAT,
bin_double BINARY_DOUBLE
);
INSERT INTO binary_test (
bin_float, bin_double
) VALUES (
39.5f, 15.7d
);
INSERT INTO binary_test (
bin_float, bin_double
) VALUES (
BINARY_FLOAT_INFINITY, BINARY_DOUBLE_INFINITY
);
-- commit the transaction
COMMIT;
|
C++
|
UTF-8
| 1,470
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
#define mp make_pair
#define pb push_back
typedef pair <int, int> pairs;
typedef set<pairs> spll;
typedef list<pair <int, int> > lpii;
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& people)
{
vector<vector<int>> ans;
if(people.size() == 0)
return ans;
spll s;
lpii l;
set <int> d[people.size() + 1];
for(int i = 0; i != people.size(); i++)
s.insert(mp(people[i][0], people[i][1]));
spll :: reverse_iterator it = s.rbegin();
int last = s.rbegin() -> first;
int x = 0;
while(1)
{
if(it != s.rend() && it->first == last)
{
d[x].insert(it->second);
it++;
continue;
}
for(set <int> :: iterator i = d[x].begin(); i != d[x].end(); i++)
{
lpii :: iterator j = l.begin();
int temp = *i;
while(temp--)
j++;
l.insert(j, mp(last, *i));
}
x++;
if(it != s.rend())
last = it->first;
else
break;
}
for(lpii :: iterator it = l.begin(); it != l.end(); it++)
{
vector <int> temp;
temp.pb(it->first);
temp.pb(it->second);
ans.pb(temp);
}
return ans;
}
};
|
C#
|
UTF-8
| 18,111
| 2.546875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Net.Mail;
using Entidades;
using MySql.Data.MySqlClient;
namespace Persistencia
{
public class User_CAD
{
public ArrayList lista = new ArrayList();
/**
* Se encarga de introducir un usuario en la base de datos
*
*/
public void InsertarUser(User_EN u)
{
Conexion nueva_conexion = new Conexion();
try
{
string parametro1 = "@fechaRegistro";
string parametro2 = "@password";
string insert = "insert into Usuario(Email,NombreCompleto,UserName,Password,IdPerfil,Verificado,IdEmpresa,FechaRegistro) VALUES ('"
+ u.Correo + "','" + u.Nombre + "','" + u.NombreUsu + "'," + parametro2 + "," +
u.IdPerfil + "," + 0 + "," + u.IdEmpresa + "," + parametro1 + ")";
//POR DEFECTO, VISIBILIDAD Y VERIFICACION SON FALSAS
nueva_conexion.SetQuery(insert);
nueva_conexion.addParameter(parametro1, u.FechaRegistro);
nueva_conexion.addParameter(parametro2, u.Contraseña);
nueva_conexion.EjecutarQuery();
}
catch (Exception ex) { ex.Message.ToString(); }
finally { nueva_conexion.Cerrar_Conexion(); }
}
/**
* Se encarga de mostrar el usuario que se quiere mostrar a través de su ID
*/
public ArrayList MostrarUser(User_EN u)
{
Conexion nueva_conexion = new Conexion();
nueva_conexion.SetQuery("Select * from Usuario where IdUsuario=" + u.ID);
DataTable dt = nueva_conexion.QuerySeleccion();
if (dt != null)
{
User_EN usuario = new User_EN();
usuario.ID = Convert.ToInt16(dt.Rows[0]["IdUsuario"]);
usuario.Correo = dt.Rows[0]["Email"].ToString();
usuario.Nombre = dt.Rows[0]["NombreCompleto"].ToString();
usuario.NombreUsu = dt.Rows[0]["UserName"].ToString();
usuario.Contraseña = (byte[])dt.Rows[0]["Password"];
usuario.IdPerfil = Convert.ToInt16(dt.Rows[0]["IdPerfil"].ToString());
if (Convert.ToBoolean(dt.Rows[0]["Verificado"]))
{
usuario.Verified = "Verificado";
}
else
{
usuario.Verified = "No Verificado";
}
lista.Add(usuario);
}
return lista;
}
/**
* Se encarga de mostrar todos los usuarios del sistema.
*/
public ArrayList MostrarUsuarios()
{
Conexion nueva_conexion = new Conexion();
nueva_conexion.SetQuery("Select u.UserName, u.NombreCompleto, u.Email, u.Verificado, u.FechaRegistro, u.FechaUltimoIngreso "+
"from Usuario u, Perfil p "+
"where u.IdPerfil = p.IdPerfil and p.NombrePerfil = 'Usuario' ");
DataTable dt = nueva_conexion.QuerySeleccion();
for (int i = 0; i < dt.Rows.Count; i++)
{
User_EN usuario = new User_EN();
usuario.Correo = dt.Rows[i]["Email"].ToString();
usuario.Nombre = dt.Rows[i]["NombreCompleto"].ToString();
usuario.NombreUsu = dt.Rows[i]["UserName"].ToString();
if (Convert.ToBoolean(dt.Rows[i]["Verificado"]))
{
usuario.Verified = "Verificado";
}
else
{
usuario.Verified = "No Verificado";
}
usuario.FechaRegistro = DateTime.Parse(dt.Rows[i]["FechaRegistro"].ToString());
usuario.UltimoIngreso = DateTime.Parse(dt.Rows[i]["FechaUltimoIngreso"].ToString());
lista.Add(usuario);
}
return lista;
}
/**
* Se encarga de borrar el usuario, si existe en la base de datos, a través de su ID
**/
public bool BorrarUser(string userName)
{
Conexion nueva_conexion = new Conexion();
try
{
string delete = "";
delete = "Delete from Usuario where Usuario.UserName = '" + userName +"'";
nueva_conexion.SetQuery(delete);
nueva_conexion.EjecutarQuery();
return true;
}
catch (Exception ex) { ex.Message.ToString(); return false; }
finally { nueva_conexion.Cerrar_Conexion(); }
}
/**
* Recibe un nombre de usuario o un correo electrónico y devuelve los datos del usuario al que pertenecen.
* En caso de que no exista tal usuario/correo, devuelve NULL
*/
public User_EN BuscarUser(string busqueda, string tabla)
{
User_EN usuario = null;
Conexion nueva_conexion = new Conexion();
try
{
string empresa = "";
string condicion = "";
usuario = new User_EN();
if (tabla != "Administrador")
{
empresa = ", Empresa,Perfil ";
condicion = "and Empresa.IdEmpresa = Usuario.IdEmpresa AND Usuario.IdPerfil = Perfil.IdPerfil";
}
string select = "Select * from " + tabla + empresa + " where (UserName ='" + busqueda + "' or Email = '" + busqueda +
"') "+condicion;
nueva_conexion.SetQuery(select);
DataTable dt = nueva_conexion.QuerySeleccion();
if (dt != null && dt.Rows.Count > 0) //Teóricamente solo debe de devolver una sola fila debido a que tanto el usuario como el email son claves alternativas (no nulos y no repetidos)
{
usuario.ID = Convert.ToInt16(dt.Rows[0]["IdUsuario"]);
usuario.Correo = dt.Rows[0]["Email"].ToString();
usuario.NombreUsu = dt.Rows[0]["UserName"].ToString();
usuario.Contraseña = (byte[])dt.Rows[0]["Password"];
usuario.IdPerfil = Convert.ToInt16(dt.Rows[0]["IdPerfil"].ToString());
if (Convert.ToBoolean(dt.Rows[0]["Verificado"]))
{
usuario.Verified = "Verificado";
}
else
{
usuario.Verified = "No Verificado";
}
if (tabla != "Administrador")
{
usuario.Nombre = dt.Rows[0]["NombreCompleto"].ToString();
usuario.Intentos = Convert.ToInt16(dt.Rows[0]["Intentos"]);
usuario.NombreEmp = dt.Rows[0]["NombreEmpresa"].ToString();
usuario.NombrePerfil = dt.Rows[0]["NombrePerfil"].ToString();
}
}
}
catch (Exception ex) { ex.Message.ToString(); }
finally { nueva_conexion.Cerrar_Conexion(); }
return usuario;
}
/**
* Recibe un nombre de usuario o un correo electrónico y devuelve los datos del usuario al que pertenecen.
* En caso de que no exista tal usuario/correo, devuelve NULL
*/
public User_EN BuscarUserAdmin(string busqueda)
{
User_EN usuario = null;
Conexion nueva_conexion = new Conexion();
try
{
string select = "Select * from Usuario where UserName ='" + busqueda + "'";
nueva_conexion.SetQuery(select);
DataTable dt = nueva_conexion.QuerySeleccion();
if (dt != null) //Teóricamente solo debe de devolver una sola fila debido a que tanto el usuario como el email son claves alternativas (no nulos y no repetidos)
{
usuario = new User_EN();
usuario.ID = Convert.ToInt16(dt.Rows[0]["IdUsuario"]);
usuario.Correo = dt.Rows[0]["Email"].ToString();
usuario.Nombre = dt.Rows[0]["NombreCompleto"].ToString();
usuario.NombreUsu = dt.Rows[0]["UserName"].ToString();
usuario.IdPerfil = Convert.ToInt16(dt.Rows[0]["IdPerfil"].ToString());
if (Convert.ToBoolean(dt.Rows[0]["Verificado"]))
{
usuario.Verified = "Verificado";
}
else
{
usuario.Verified = "No Verificado";
}
usuario.FechaRegistro = DateTime.Parse(dt.Rows[0]["FechaRegistro"].ToString());
usuario.UltimoIngreso = DateTime.Parse(dt.Rows[0]["FechaUltimoIngreso"].ToString());
}
}
catch (Exception ex) { ex.Message.ToString(); }
finally { nueva_conexion.Cerrar_Conexion(); }
return usuario;
}
/**
* Se encarga de listar todos los amigos que tiene un usuario
**/
public ArrayList ListarAmigos()
{
Conexion nueva_conexion = new Conexion();
nueva_conexion.SetQuery("Select * from Friends where Friends.User1 = ");
DataTable dt = nueva_conexion.QuerySeleccion();
while (dt != null)
{
lista.Add(dt.Rows[0]["Users2"].ToString());
}
return lista;
}
/**
* Se encarga de mostrarnos todos los datos del usuario y contraseña que le pasamos
**/
public User_EN LeerUser(User_EN u)
{
Conexion nueva_conexion = new Conexion();
User_EN usuario = new User_EN();
try
{
string select = "";
select = "Select * from Usuario where UserName ='" + u.NombreUsu + "' and Password = '" + u.Contraseña + "'";
nueva_conexion.SetQuery(select);
DataTable dt = nueva_conexion.QuerySeleccion();
if (dt != null)
{
usuario.ID = Convert.ToInt16(dt.Rows[0]["IdUsuario"]);
usuario.Correo = dt.Rows[0]["Email"].ToString();
usuario.Nombre = dt.Rows[0]["NombreCompleto"].ToString();
usuario.NombreUsu = dt.Rows[0]["UserName"].ToString();
usuario.Contraseña = (byte[])dt.Rows[0]["Password"];
usuario.IdPerfil = Convert.ToInt16(dt.Rows[0]["IdPerfil"].ToString());
if (Convert.ToBoolean(dt.Rows[0]["Verificado"]))
{
usuario.Verified = "Verificado";
}
else
{
usuario.Verified = "No Verificado";
}
}
}
catch (Exception ex) { ex.Message.ToString(); }
finally { nueva_conexion.Cerrar_Conexion(); }
return usuario;
}
/**
* Se encarga de una vez recibido el email y darle al link, poner al que le perteneza ese usuario el verified a 1
**/
public void confirmacionUser(User_EN u)
{
Conexion nueva_conexion = new Conexion();
try
{
string update = "";
update = "Update Usuario set Verificado = '1' where Usuario.Email = '" + u.Correo + "'";
nueva_conexion.SetQuery(update);
nueva_conexion.EjecutarQuery();
}
catch (Exception ex) { ex.Message.ToString(); }
finally { nueva_conexion.Cerrar_Conexion(); }
}
/**
* Se encarga de actualizar el usuario si sufre alguna modificacion en alguno de sus campos
**/
public void actualizarUser(User_EN u)
{
Conexion nueva_conexion = new Conexion();
try
{
string update = "";
string parametro2 = "@password";
update = "Update Usuario set Email = '" + u.Correo + "',NombreCompleto = '" + u.Nombre +
"',UserName = '" + u.NombreUsu + "', Password = " + parametro2 + " where Usuario.IdUsuario ="+u.ID;
nueva_conexion.SetQuery(update);
nueva_conexion.addParameter(parametro2, u.Contraseña);
nueva_conexion.EjecutarQuery();
}
catch (Exception ex) { ex.Message.ToString(); }
finally { nueva_conexion.Cerrar_Conexion(); }
}
/**
* Se encarga de actualizar el usuario si sufre alguna modificacion en alguno de sus campos
**/
public void actualizarUserAdmin(User_EN u)
{
Conexion nueva_conexion = new Conexion();
try
{
string update = "";
bool verifid = false;
if (u.Verified == "Verificado")
{
verifid = true;
}
update = "Update Usuario set Email = '" + u.Correo + "',NombreCompleto = '" + u.Nombre +
"',UserName = '" + u.NombreUsu + "' ,Verificado = " + verifid + " where Usuario.IdUsuario =" + u.ID;
nueva_conexion.SetQuery(update);
nueva_conexion.EjecutarQuery();
}
catch (Exception ex) { ex.Message.ToString(); }
finally { nueva_conexion.Cerrar_Conexion(); }
}
/**
* Se encarga de actualizar el usuario si sufre algun intento fallido de iniciar sesion
**/
public void establecerIntentos(User_EN u)
{
Conexion nueva_conexion = new Conexion();
try
{
string update = "";
update = "Update Usuario set Intentos = " + u.Intentos + " where Usuario.IdUsuario =" + u.ID;
nueva_conexion.SetQuery(update);
nueva_conexion.EjecutarQuery();
}
catch (Exception ex) { ex.Message.ToString(); }
finally { nueva_conexion.Cerrar_Conexion(); }
}
/**
* Se encarga de actualizar el usuario con el fin de bloquer a este.
**/
public void bloquearUsuario(User_EN u)
{
Conexion nueva_conexion = new Conexion();
try
{
string update = "";
string nombreParam = "@fechaBloqueo";
update = "Update Usuario set Verificado = " + false + ",FechaIntentoIngreso = "+ nombreParam +" where Usuario.IdUsuario =" + u.ID;
nueva_conexion.SetQuery(update);
nueva_conexion.addParameter(nombreParam, u.FechaBloqueo);
nueva_conexion.EjecutarQuery();
}
catch (Exception ex) { ex.Message.ToString(); }
finally { nueva_conexion.Cerrar_Conexion(); }
}
/**
* Se encarga de actualizar el usuario con el fin de bloquer a este.
**/
public void RestablecerContraseña(User_EN u)
{
Conexion nueva_conexion = new Conexion();
try
{
string update = "";
string parametro2 = "@password";
update = "Update Usuario set Password = " + parametro2 + " where Usuario.IdUsuario =" + u.ID;
nueva_conexion.SetQuery(update);
nueva_conexion.addParameter(parametro2, u.Contraseña);
nueva_conexion.EjecutarQuery();
}
catch (Exception ex) { ex.Message.ToString(); }
finally { nueva_conexion.Cerrar_Conexion(); }
}
/**
* Se encarga de mostrar el usuario que se quiere mostrar a través de su ID
*/
public string miPerfil(User_EN u)
{
Conexion nueva_conexion = new Conexion();
nueva_conexion.SetQuery("Select NombrePerfil from Perfil where IdPerfil=" + u.IdPerfil);
DataTable dt = nueva_conexion.QuerySeleccion();
string nomPerfil = "";
if (dt != null)
{
nomPerfil = dt.Rows[0]["NombrePerfil"].ToString();
}
return nomPerfil;
}
/**
* Se encarga de mostrar el usuario que se quiere mostrar a través de su ID
*/
public ArrayList MostrarPerfiles()
{
Conexion nueva_conexion = new Conexion();
nueva_conexion.SetQuery("Select * from Perfil WHERE NOT(NombrePerfil = 'Super Administrador')");
DataTable dt = nueva_conexion.QuerySeleccion();
string nomPerfil = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
nomPerfil = dt.Rows[i]["NombrePerfil"].ToString();
lista.Add(nomPerfil);
}
return lista;
}
/**
* Se encarga de mostrar el usuario que se quiere mostrar a través de su ID
*/
public int getIdPerfil(string u)
{
Conexion nueva_conexion = new Conexion();
nueva_conexion.SetQuery("Select IdPerfil from Perfil where NombrePerfil='" + u + "'");
DataTable dt = nueva_conexion.QuerySeleccion();
int idPerfil = 0;
if (dt != null)
{
idPerfil = Convert.ToInt32(dt.Rows[0]["IdPerfil"].ToString());
}
return idPerfil;
}
}
}
|
JavaScript
|
UTF-8
| 1,396
| 2.65625
| 3
|
[] |
no_license
|
// eslint-disable-next-line import/no-extraneous-dependencies
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
const target = path.resolve(__dirname, '../../src/public/images');
const destination = path.resolve(__dirname, '../../dist/images');
if (!fs.existsSync(destination)) {
fs.mkdirSync(destination);
}
const processImage = (image) => {
if (image.indexOf('.') > -1) {
let file;
if (image.indexOf('/') > -1) {
file = `${destination}/${image.substr(0, image.lastIndexOf('/'))}/${image.substr(image.lastIndexOf('/') + 1).split('.').slice(0, -1).join('.')}`;
} else {
file = `${destination}/${image.split('.')
.slice(0, -1)
.join('.')}`;
}
// mengubah ukuran gambar dengan lebar 800px, dengan prefix -large.jpg
sharp(`${target}/${image}`)
.resize(800)
.toFile(path.resolve(__dirname, `${file}-large.jpg`));
// mengubah ukuran gambar dengan lebar 480px, dengan prefix -small.jpg
sharp(`${target}/${image}`)
.resize(480)
.toFile(path.resolve(__dirname, `${file}-small.jpg`));
} else {
try {
fs.readdirSync(`${target}/${image}`)
.forEach((image2) => {
processImage(`${image}/${image2}`);
});
} catch (e) {
// Not a directory
}
}
};
fs.readdirSync(target)
.forEach((image) => {
processImage(image);
});
|
PHP
|
UTF-8
| 3,956
| 2.578125
| 3
|
[] |
no_license
|
<?php
class EntryDB
{
public $conn = "";
public $query = "";
function OpenConnection()
{
$this->conn =mysql_connect("localhost", "bietthuleh_dba", "zxcVBN123") or die("can't connect server");
mysql_query("set names 'utf8'");
mysql_select_db("bietthuleh_db",$this->conn) or die("can't connect database");
}
function CloseConnection()
{
mysql_close($this->conn);
}
function Search()
{
mysql_select_db("bietthuleh_db",$this->conn);
$sql="select * from tbl_entry";
$this->query =mysql_query($sql);
}
function SearchEntryEvent()
{
mysql_select_db("bietthuleh_db",$this->conn);
$sql="select * from tbl_entry where menu_id='6'";
$this->query =mysql_query($sql);
}
function SearchEntryPromotion()
{
mysql_select_db("bietthuleh_db",$this->conn);
$sql="select * from tbl_entry where menu_id='7'";
$this->query =mysql_query($sql);
}
function SearchEntryNews()
{
mysql_select_db("bietthuleh_db",$this->conn);
$sql="select * from tbl_entry where menu_id='8' ORDER BY entry_id DESC";
$this->query =mysql_query($sql);
}
function SearchEntryById($IdSearch)
{
mysql_select_db("bietthuleh_db",$this->conn);
$sql="select * from tbl_entry where entry_id=".$IdSearch;
$this->query =mysql_query($sql);
}
function InsertEntryEvent($EntryName, $EntryContent, $EntryNameEn, $EntryContentEn, $EntryImg, $EntryStatus)
{
mysql_select_db("bietthuleh_db",$this->conn);
$date = date("Y-m-d h:i:sa");
$sql1="INSERT INTO tbl_entry (entry_name, entry_content, entry_name_en, entry_content_en, entry_img, entry_datetime, menu_id, entry_status)VALUES ('".$EntryName."', '".$EntryContent."','".$EntryNameEn."','".$EntryContentEn."','".$EntryImg."','".$date."', '6', '".$EntryStatus."')";
$this->query =mysql_query($sql1);
}
function InsertEntryPromotion($EntryName, $EntryContent, $EntryNameEn, $EntryContentEn, $EntryImg, $EntryStatus)
{
mysql_select_db("bietthuleh_db",$this->conn);
$date = date("Y-m-d h:i:sa");
$sql1="INSERT INTO tbl_entry (entry_name, entry_content, entry_name_en, entry_content_en, entry_img, entry_datetime, menu_id, entry_status)VALUES ('".$EntryName."', '".$EntryContent."','".$EntryNameEn."','".$EntryContentEn."','".$EntryImg."','".$date."', '7', '".$EntryStatus."')";
$this->query =mysql_query($sql1);
}
function InsertEntryNews($EntryName, $EntryContent, $EntryNameEn, $EntryContentEn, $EntryImg, $EntryStatus)
{
mysql_select_db("bietthuleh_db",$this->conn);
$date = date("Y-m-d h:i:sa");
$sql1="INSERT INTO tbl_entry (entry_name, entry_content, entry_name_en, entry_content_en, entry_img, entry_datetime, menu_id, entry_status)VALUES ('".$EntryName."', '".$EntryContent."','".$EntryNameEn."','".$EntryContentEn."','".$EntryImg."','".$date."', '7', '".$EntryStatus."')";
$this->query =mysql_query($sql1);
}
function UpdateEntry($IdEdit, $NameEdit, $ContentEdit, $NameEnEdit, $ContentEnEdit, $EntryImg, $EntryStatus )
{
mysql_select_db("bietthuleh_db",$this->conn);
$sql2="UPDATE tbl_entry SET entry_name ='".$NameEdit."', entry_content='".$ContentEdit."', entry_name_en ='".$NameEnEdit."', entry_content_en='".$ContentEnEdit."', entry_img='".$EntryImg."', entry_status='".$EntryStatus."' WHERE entry_id=".$IdEdit;
$this->query =mysql_query($sql2);
}
function DeleteEntry($IdDelete)
{
mysql_select_db("bietthuleh_db",$this->conn);
$sql3="DELETE FROM tbl_entry WHERE entry_id=".$IdDelete;
$this->query =mysql_query($sql3);
}
function SearchForComment()
{
$sql="select entry_id, entry_name from tbl_entry";
$this->query =mysql_query($sql);
}
}
?>
|
Shell
|
UTF-8
| 1,015
| 3.171875
| 3
|
[
"Apache-2.0"
] |
permissive
|
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
WD=/tmp/mkdeb
USR_SHARE_DOCS=$WD"/usr/share/doc/qtcreator-plugin-wizard-opaque-class"
CHANGE_LOG_FILE=$WD"/usr/share/doc/qtcreator-plugin-wizard-opaque-class/changelog.Debian.gz"
rm -rf $WD
mkdir -p $WD/usr/share/qtcreator/templates/wizards/opaque-class
mkdir -p $USR_SHARE_DOCS
cp $DIR/../../src/* $WD/usr/share/qtcreator/templates/wizards/opaque-class/
cp -rf $DIR/DEBIAN $WD
cp $DIR/../../copyright.txt $USR_SHARE_DOCS/copyright
find $WD -type d | xargs chmod 755
#gzip -c changelog.txt > $CHANGE_LOG_FILE
gzip --best -c $DIR/../../changelog.txt > changelog.Debian.gz
mv changelog.Debian.gz $USR_SHARE_DOCS
chmod 0644 $USR_SHARE_DOCS/*
fakeroot dpkg-deb --build $WD
VERSION=`cat $DIR/DEBIAN/control | grep Version | awk '{print $2}'`
PACKAGENAME=`cat $DIR/DEBIAN/control | grep Package | awk '{print $2}'`
ARCH=`cat $DIR/DEBIAN/control | grep Architecture | awk '{print $2}'`
FILENAME=$PACKAGENAME"_"$VERSION"_"$ARCH".deb"
mv $WD/../mkdeb.deb $FILENAME
|
Swift
|
UTF-8
| 2,579
| 3.203125
| 3
|
[] |
no_license
|
//
// StringUtils.swift
// CardRequisition
//
// Created by Raphael Carletti on 9/18/18.
// Copyright © 2018 Raphael Carletti. All rights reserved.
//
import Foundation
class StringUtils {
static func formatCreditCardNumber(text: String) -> String {
let textReplaced = text.replacingOccurrences(of: " ", with: "")
var newText = ""
textReplaced.enumerated().forEach { (index, character) in
if index % 4 == 0 && index > 0 {
newText += " "
}
newText.append(character)
}
return newText
}
static func formatCreditCardNumberWithEncryption(cardNumber: String) -> String {
let textReplaced = cardNumber.replacingOccurrences(of: " ", with: "")
var newText = ""
var numberOfSpaces = 0
textReplaced.enumerated().forEach { (index, character) in
if index % 4 == 0 && index > 0 {
numberOfSpaces += 1
newText += " "
}
if numberOfSpaces == 3 {
newText.append(character)
} else {
newText.append("*")
}
}
return newText
}
}
extension String {
func currencyInputFormatting() -> String? {
var number: NSNumber?
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
formatter.currencySymbol = ""
var amountWithPrefix = self
if let regex = try? NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive) {
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double / 100))
if let number = number, let string = formatter.string(from: number) {
return string
}
}
return nil
}
func getDouble() -> Double? {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
if let number = formatter.number(from: self)?.doubleValue {
return number
}
return nil
}
}
|
Python
|
UTF-8
| 1,302
| 4.21875
| 4
|
[] |
no_license
|
"""
You are given the lengths AB and BC.
Your task is to find (angle , as shown in the figure) in degrees.
Input Format
The first line contains the length of side .
The second line contains the length of side .
Constraints
Lengths and are natural numbers.
Output Format
Output in degrees.
Note: Round the angle to the nearest integer.
Examples:
If angle is 56.5000001°, then output 57°.
If angle is 56.5000000°, then output 57°.
If angle is 56.4999999°, then output 56°.
Sample Input
10
10
Sample Output
45°
"""
#Import math Library
from math import atan, degrees
#unicode for degree sign
degree_sign = u"\N{DEGREE SIGN}"
#input the opposite side length and cast as an int
opposite_side = int(input())
#input the adjacent side length and cast as an int
adjacent_side = int(input())
"""
atan(opposite_side/adjacent_side) returns the angle in radians
degrees(atan(opposite_side/adjacent_side)) converts angle in degrees
round(degrees(atan(opposite_side/adjacent_side))) removes the numbers after the decimal since the default is 0 decimal places
We cast to a string using str since we need to concatenate with the unicode degree symbol
"""
print(str(round(degrees(atan(opposite_side/adjacent_side)))) + degree_sign)
|
PHP
|
UTF-8
| 890
| 3.203125
| 3
|
[] |
no_license
|
<?php
namespace Models\Output;
/**
* @author Mike Pearce <mike@mikepearce.net>
* @package cardReader
* @since 20/09/10
*/
class Text extends AbstractOutput
{
/**
* Output the data as a sting
* @todo Make this a bit cleverer
**/
public function out()
{
print "This is your travel itinerary: \n";
foreach ($this->_data AS $card)
{
echo 'Leg: '. $card->journeyLeg ." ";
echo 'take the '. $card->type .' '. $card->number ." ";
echo 'from '. $card->startDest .' ';
if ($card->start_info) {
echo '('.$card->start_info .") ";
}
echo 'to '. $card->endDest ." ";
if ($card->end_info) {
echo '('.$card->end_info .")";
}
echo "\n";
}
}
}
|
Java
|
UTF-8
| 763
| 2.421875
| 2
|
[] |
no_license
|
package test.lky.zkclient;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import java.util.List;
/**
* Created by kylong on 2016/9/3.
*/
public class Get_Children_Sample {
public static void main(String[] args) throws InterruptedException {
String path = "/test";
ZkClient zkClient = new ZkClient("10.3.8.88:2181,10.3.8.89:2181,10.2.5.54:2181",5000);
zkClient.subscribeChildChanges(path, new IZkChildListener() {
public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
System.out.println(parentPath+"'s child changed, currentChilds:" + currentChilds);
}
});
Thread.sleep(Integer.MAX_VALUE);
}
}
|
JavaScript
|
UTF-8
| 1,584
| 2.53125
| 3
|
[] |
no_license
|
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
todoList: [],
isEditing: false,
selectedTodo: {}
}
const todoSlice = createSlice({
name: 'todos',
initialState,
reducers: {
fetchTodo: (state, action) => {
state.todoList = action.payload
},
saveTodo: (state, action) => {
state.todoList.push(action.payload)
},
setCheck: (state, action) => {
state.todoList.forEach(item => {
if (action.payload === item.id) {
item.done = !item.done
}
})
},
removeTodo: (state, action) => {
state.todoList = state.todoList.filter(item => action.payload !== item.id)
},
setIsEditing: (state, action) => {
state.isEditing = true
state.selectedTodo = action.payload
},
setCancelEditing: (state) => {
state.isEditing = false
state.selectedTodo = {}
},
updateTodoAction: (state, action) => {
state.todoList = state.todoList.map(todo => todo.id === state.selectedTodo.id ? { ...todo, item: action.payload } : todo)
}
}
});
export const { saveTodo, setCheck, removeTodo,
setIsEditing, setCancelEditing, updateTodoAction, fetchTodo } = todoSlice.actions
export const selectTodoList = state => state.todos.todoList
export const isEditing = state => state.todos.isEditing
export const selectedVal = state => state.todos.selectedTodo
export default todoSlice.reducer
|
Go
|
UTF-8
| 515
| 3.015625
| 3
|
[] |
no_license
|
package request
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
)
// Simple is the most simple request structure
type Simple struct {
DriverID int
}
// NewSimple is constructor of request.Simple which converts request body to equest.Simple
func NewSimple(requestBody io.Reader) *Simple {
s, _ := ioutil.ReadAll(requestBody)
requestBody = ioutil.NopCloser(bytes.NewBuffer(s))
decoder := json.NewDecoder(requestBody)
var t Simple
err := decoder.Decode(&t)
if err != nil {
panic(err)
}
return &t
}
|
C++
|
UTF-8
| 2,027
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
#include "cppgomoku/game_server.h"
namespace gomoku
{
GameServer::GameServer(Board *b, Player *p1, Player *p2, bool silent) {
board = b;
player1 = p1;
player2 = p2;
this->silent = silent;
}
void GameServer::showGameInfo() {
if (player1) {
printf("[--Player 1--]:\n------\n");
printf("%s", player1->PlayerInfo().c_str());
printf("\n");
}
if (player2) {
printf("[--Player 2--]:\n------\n");
printf("%s", player2->PlayerInfo().c_str());
printf("\n");
}
board->printBoard();
}
int GameServer::startGame() {
board->initBoard(player1->getColor());
Player * color_to_player[2];
color_to_player[player1->getColor()] = player1;
color_to_player[player2->getColor()] = player2;
if (!silent) showGameInfo();
int next_move, winner_color;
while (true) {
Player *current_player = color_to_player[board->currentPlayerColor()];
printf("Before get action\n");
next_move = current_player->getAction(*board);
printf("After get action\n");
if (!board->isValidMove(next_move)) {
printf("Invalid move %d\n", next_move);
throw std::runtime_error("Invalid move!");
}
board->play(next_move);
if (!silent) showGameInfo();
bool is_end = board->gameEnd(winner_color);
if (is_end) {
if (!silent) {
if (winner_color != Board::kPlayerEmpty)
printf("Game end with winner %s(color %c)\n",
color_to_player[winner_color]->getName().c_str(),
Board::stone(winner_color));
else
printf("Game end with no winner.\n");
}
return winner_color;
}
}
}
} // gomoku
|
PHP
|
UTF-8
| 7,430
| 2.609375
| 3
|
[] |
no_license
|
<?php
class Test extends Activity
{
private $testId;
public function setTestId($value)
{
$this->testId = $value;
}
public function getTestId()
{
return $this->testId;
}
private $question;
public function setQuestion($value)
{
$this->Util()->ValidateString($value, 5000, 1, 'Pregunta');
$this->question = $value;
}
public function getQuestion()
{
return $this->question;
}
private $opcionA;
public function setOpcionA($value)
{
$this->Util()->ValidateString($value, 1000, 1, 'Opcion A');
$this->opcionA = $value;
}
public function getOpcionA()
{
return $this->opcionA;
}
private $opcionB;
public function setOpcionB($value)
{
$this->Util()->ValidateString($value, 1000, 1, 'Opcion B');
$this->opcionB = $value;
}
public function getOpcionB()
{
return $this->opcionB;
}
private $opcionC;
public function setOpcionC($value)
{
$this->Util()->ValidateString($value, 1000, 0, 'Opcion C');
$this->opcionC = $value;
}
public function getOpcionC()
{
return $this->opcionC;
}
private $opcionD;
public function setOpcionD($value)
{
$this->Util()->ValidateString($value, 1000, 0, 'Opcion D');
$this->opcionD = $value;
}
public function getOpcionD()
{
return $this->opcionD;
}
private $opcionE;
public function setOpcionE($value)
{
$this->Util()->ValidateString($value, 1000, 0, 'Opcion E');
$this->opcionE = $value;
}
public function getOpcionE()
{
return $this->opcionE;
}
private $answer;
public function setAnswer($value)
{
$this->Util()->ValidateString($value, 1000, 0, 'Respuesta');
$this->answer = $value;
}
public function getAnswer()
{
return $this->answer;
}
public function Enumerate($tipo = null)
{
$sql = "
SELECT * FROM activity_test
WHERE activityId = '".$this->getActivityId()."'
ORDER BY testId ASC";
$this->Util()->DB()->setQuery($sql);
$result = $this->Util()->DB()->GetResult();
foreach($result as $key => $res)
{
$result[$key]["opcionAShort"] = substr($res["opcionA"], 0, 20);
$result[$key]["opcionBShort"] = substr($res["opcionB"], 0, 20);
$result[$key]["opcionCShort"] = substr($res["opcionC"], 0, 20);
$result[$key]["opcionDShort"] = substr($res["opcionD"], 0, 20);
$result[$key]["opcionEShort"] = substr($res["opcionE"], 0, 20);
$result[$key]["ponderation"] = $this->PonderationPerQuestion();
}
//print_r($result);
return $result;
}
function Randomize($questions, $max)
{
$keys = array_rand($questions, $max);
foreach($keys as $key)
{
$returnArray[] = $questions[$key];
}
return $returnArray;
}
public function Access($maxTries)
{
$sql = "
SELECT try FROM activity_score
WHERE activityId = '".$this->getActivityId()."'
AND userId = '".$this->getUserId()."'";
// exit;
$this->Util()->DB()->setQuery($sql);
$try = $this->Util()->DB()->GetSingle();
if($try < $maxTries)
{
return 1;
}
return 0;
}
public function TestScore()
{
$this->Util()->DB()->setQuery("
SELECT ponderation FROM activity_score
WHERE activityId = '".$this->getActivityId()."'
AND userId = '".$this->getUserId()."'");
$score = $this->Util()->DB()->GetSingle();
return $score;
}
public function Info($id = null)
{
//creamos la cadena de seleccion
$sql = "SELECT
*
FROM
activity_test
WHERE
testId='" . $this->getTestId() . "'";
//configuramos la consulta con la cadena de actualizacion
$this->Util()->DB()->setQuery($sql);
//ejecutamos la consulta y obtenemos el resultado
$result = $this->Util()->DB()->GetRow();
if($result)
$result = $this->Util->EncodeRow($result);
return $result;
}
public function PonderationPerQuestion()
{
//creamos la cadena de seleccion
$sql = "SELECT
noQuestions
FROM
activity
WHERE
activityId='" . $this->getActivityId() . "'";
//configuramos la consulta con la cadena de actualizacion
$this->Util()->DB()->setQuery($sql);
//ejecutamos la consulta y obtenemos el resultado
$result = $this->Util()->DB()->GetSingle();
if($result == 0)
{
$result = 1;
}
$ponderation = 100/$result;
return $ponderation;
}
public function Edit()
{
//creamos la cadena de seleccion
$sql = "UPDATE
activity_test
SET
question = '".$this->question."',
opcionA = '".$this->opcionA."',
opcionB = '".$this->opcionB."',
opcionC = '".$this->opcionC."',
opcionD = '".$this->opcionD."',
opcionE = '".$this->opcionE."',
answer = '".$this->answer."'
WHERE
testId='" . $this->getTestId() . "'";
//configuramos la consulta con la cadena de actualizacion
$this->Util()->DB()->setQuery($sql);
//ejecutamos la consulta y obtenemos el resultado
$result = $this->Util()->DB()->UpdateData();
$this->Util()->setError(90010, 'complete', "Se ha actualizado la pregunta.");
$this->Util()->PrintErrors();
return $result;
}
function SendTest($answers)
{
//print_r($this);
$questionScore = $this->PonderationPerQuestion();
$score = 0;
if(is_array($answers))
{
foreach($answers as $key => $option)
{
$sql = "SELECT answer FROM
activity_test
WHERE
testId='" .$key. "'";
$this->Util()->DB()->setQuery($sql);
$result = $this->Util()->DB()->GetSingle();
if(!$result)
{
$result = "opcionA";
}
if($option == $result)
{
$score += $questionScore;
}
}
}
$this->Util()->DB()->setQuery("
SELECT COUNT(*)
FROM activity_score
WHERE activityId = '".$this->getActivityId()."' AND userId = '".$this->getUserId()."'");
$count = $this->Util()->DB()->GetSingle();
if($count == 0)
{
$this->Util()->DB()->setQuery("
INSERT INTO `activity_score` (
`userId` ,
`activityId` ,
`try` ,
`ponderation`
)
VALUES (
'".$this->getUserId()."',
'".$this->getActivityId()."',
'1',
'".$score."');");
$result = $this->Util()->DB()->InsertData();
}
else
{
$this->Util()->DB()->setQuery("
UPDATE `activity_score` SET
`ponderation` = '".$score."',
try = try + 1
WHERE
`userId` = '".$this->getUserId()."' AND activityId = '".$this->getActivityId()."' LIMIT 1");
$result = $this->Util()->DB()->UpdateData();
}
$timeLimitName = 'timeLimit'.$this->getActivityId();
unset($_SESSION[$timeLimitName]);
$student=new Student;
$student->setUserId($this->getUserId);
$infoStudent=$student->GetInfo();
$mail = new PHPMailer(); // defaults to using php "mail()"
//contenido del correo
$body = "Has hecho realizado examen correctament <br/> Calificacion obtenida: ".$score;
//asunto o tema
$subject ="Examen finalizado Correctamente";
//("quienloenvia@hotmail.com", "nombre de quien lo envia");
$mail->SetFrom(EMAIL_USERNAME, "Administrador del Sistema");
//correo y nombre del destinatario
$mail->AddAddress($infoStudent['email'], $infoStudent['names']);
$mail->Subject = $subject;
$mail->MsgHTML($body);
$mail->Send();
$this->Util()->setError(90000, 'complete', "Has respondido el examen Satisfactoriamente. Tu resultado esta abajo.");
$this->Util()->PrintErrors();
}
}
?>
|
Ruby
|
UTF-8
| 294
| 2.6875
| 3
|
[] |
no_license
|
module IssuesHelper
def printTags(issue)
tags = Tag.where("issue_id = ?", issue.id)
allTags = ""
tags.each do |tag|
allTags = allTags + ", #" +tag.label
end
if allTags.length == 0
allTags = "None"
else
allTags = allTags[2..allTags.length]
end
return allTags
end
end
|
Markdown
|
UTF-8
| 2,155
| 2.9375
| 3
|
[] |
no_license
|
## AWS Certificate Manager

#### Managed certificate renewal
ACM creates free HTTPS certificates that are continuously renewed by Amazon. These managed renewals are more reliable than the common alternative certificates from "Let's Encrypt" which require cron jobs for certificate renewal. Cron jobs can unexpectedly fail when rare events aren't fully covered in the timing configuration.
#### More secure site traffic, better SEO
TLS is "[Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security)" and the older SSL protocol is "Secure Sockets Layer". A TLS-enabled site will encrypt all network traffic in a HTTPS connection, preventing attackers from inspecting the traffic or modifying it while in transit. All browsers will show a prominent "Not Secure" label next to the website if no TLS certificate is installed. TLS-enabled sites also score higher in Google's search rankings.
## Route 53 DNS management
In these guides, we will assume a more complex situation where you have multiple business clients that have bought their own domains at different registries.
#### Mixed ownership: client controls domain, we control the DNS records
A client may have primary control of a domain name. To manage that domain on AWS, we need the domain's nameserver records pointing to Route 53. This configuration gives us the ability to customize all DNS records for that domain, including the CNAME records needed for certificate creation.
#### Requesting nameserver configuration
When a Record Set is made for a new Hosted Zone in Route 53, 4 NS records will be shown. When the client owns the domain through a third-party registrar, you can ask the client's IT team to change the domain's nameservers in the registrar's DNS configuration to point towards the 4 AWS nameservers listed in the Record Set.
When the domain's nameservers are set to Route 53's nameservers, we can then create the certificate and succesfully validate the domain in Route 53.
Continue to the [certificate creation guide](./Creating-a-SSL-TLS-Certificate-for-a-Custom-Domain.md).
|
Markdown
|
UTF-8
| 502
| 2.703125
| 3
|
[] |
no_license
|
# SparseArray & ArrayMap
## SparseArray
内部通过两个数组来进行数据存储的
一个存储key (Key 只能是 int ) ,另外一个存储value
存取都通过二分搜索来查找
对 HashMap 优化了装箱拆箱的步骤
## ArrayMap
内部通过两个数组来进行数据存储的
一个存储key的hashcode ,另外一个存储key,value
[数据结构HashMap(Android SparseArray 和ArrayMap)](https://juejin.im/post/5b2a24dd51882574bc55b974)
|
TypeScript
|
UTF-8
| 3,667
| 3.03125
| 3
|
[] |
no_license
|
import { Component, Input} from '@angular/core';
@Component({
selector: 'calendar',
templateUrl: 'calendar.html'
})
export class CalendarComponent {
month: Array<number>;
@Input() today: Date;
@Input() displaytype: string = 'week';
wHead: string[] = ['日', '一', '二', '三', '四', '五', '六'];
selectedDay: Date; //被选择的日期
reallyToday: Date; //真正的Today
constructor() {
this.today = new Date();
this.reallyToday = new Date();
this.selectedDay = new Date(this.today);
this.createMonth(this.today.toISOString());
}
createMonth(date: string) {
var month = new Array();
var firstday = new Date(date);
firstday.setDate(1);
var firstdayNextMonth = new Date(date);
if (firstday.getMonth() < 11) {
firstdayNextMonth.setDate(1);
firstdayNextMonth.setMonth(firstday.getMonth()+1);
} else {
firstdayNextMonth.setDate(31);
firstdayNextMonth.setMonth(firstdayNextMonth.getTime()+24*3600000);
}
var lastday = new Date(date);
lastday.setTime(firstdayNextMonth.getTime() - 24 * 3600000);
//开始写月份数据
var month = [];
var daynum = 0;
var day = new Date();
var ok = false;
for (var i = 0; i <= 5; i++) {
var weekday = new Array();
for (var j = 0; j <= 6; j++) {
//多种情况一起考虑
if (i === 0 && j < firstday.getDay()) {
//属于前月的
var day = new Date();
day.setTime(firstday.getTime() - ((firstday.getDay() - j) * 24 * 3600000));
weekday.push({day:day});
} else {
//属于这个月的
if (daynum < lastday.getDate()) {
var day = new Date();
day.setTime(firstday.getTime() + daynum * 24 * 3600000);
weekday.push({ day: day, selected: true });
if (daynum === lastday.getDate() && lastday.getDay() === 6) {
ok = true;
}
daynum++;
} else {
//属于后月
var day = new Date();
day.setTime(lastday.getTime() + ((j - lastday.getDay()) * 24 * 3600000));
weekday.push({ day: day });
if (j === 6) {
ok = true;
}
daynum++;
}
}
}
month.push(weekday);
if (ok) {
break;
}
}
this.month = month;
console.log(this.month);
}
ismonthtoday(index) {
if (this.reallyToday.getDate() === index.day.getDate()) {
return true;
} else {
return false;
}
}
isSelectedmonthDay(index) {
if (index.day.getDate() === this.selectedDay.getDate()&& this.selectedDay.getMonth() === index.day.getMonth()) {
return true;
} else {
return false;
}
}
selectmonthDay(index) {
this.today = this.selectedDay = index.day;
this.createMonth(this.today.toISOString());
}
toMonthDay(index) {
return index.day.getDate();
}
}
|
Markdown
|
UTF-8
| 2,659
| 3.078125
| 3
|
[] |
no_license
|
---
date: 2023-01-15
tags:
- java
- clean code
- gradle
title: Spotless - an alternative to Checkstyle that applies the formatting
type: Essay
pinned: true
---
[Checkstyle][4] is a wonderful tool when we want to enforce the style guidelines in
the project. But it has 2 major problems:
1. It can't apply the formatting, it can only check whether the code is
compatable. You need to rely on alternatives like suggested in this [Stack
Overflow thread][1]. But there is
no programattic way to do it.
2. It can't work only on the changes that you have made. For you to only check
with the files that you have modified, you need a workaround suggested in
[this article][2]. (I don't speak the language but the code snippet is quite
evident)
## Enter [Spotless][3]
Spotless is more or less similar to Checkstyle but with few more features that
we need. We will only discuss the differences. The rest is same.
### Apply the fixes
While Checkstyle only supports finding out the problems, Spotless can even fix
them for you. With Gradle you would end up running
```bash
./gradlew spotlessApply
```
and ta-da!
The regular `./gradlew spotlessCheck` will just generate a report for you like
Checkstyle does.
### Working with only the diff
A very neat feature with Spotless is that it can only work with the diff. So
if you are integrating a code formatter for the first time on a legacy project
it would become very simple. The spotless configuration looks something like
this:
```groovy
spotless {
ratchetFrom 'origin/main'
// more configuration omitted
```
This will only check and apply against the diff with `main` branch. Works fine
with tags, branches or any other commit for that matter.
### Working with an existing code formatter
Onboarding a legacy project to these changes is always challenging because
you end up either too many changes or it doesn't comply with the exact code
style that your organization is following. If your project already uses Eclipse
code formatter, you can simply re-use that with spotless. No new files or
anything is required.
```groovy
spotless {
java {
eclipse().configFile('./.settings/eclipse-formatter.xml')
// more configurations emitted
}
}
```
Well, these are the 3 features I loved about Spotless, which made it easy to
integrate with my existing projects.
---
[1]: https://stackoverflow.com/questions/8409074
[2]: https://ealebed.github.io/posts/2020/gradle-checkstyle-on-changed-files-only/
[3]: https://github.com/diffplug/spotless
[4]: https://checkstyle.org/
This is my 10th of 100 post in [#100daysToOffload](https://100daystooffload.com/).
|
C++
|
UTF-8
| 2,105
| 2.703125
| 3
|
[] |
no_license
|
#include "player.h"
Player::Player( ScenePrimitive * obj)
:obj(obj), cam(NULL), spotlight(NULL), coins(0)
{
zoffset = 0;
homeSlice = 0;
vel = Vector3(0,0,0);
accl = Vector3(0,0,-1);
levelPos = -1;
maxSpeed = 40;
}
void Player::Load(Scene* scene)
{
cam = scene->getDefaultCamera();
cam -> setPosition(Vector3(1,2,17));
//cam -> setPosition(Vector3(15,15,15));
//cam -> setPosition(Vector3(-70,0,0));
cam -> lookAt(obj->getPosition());
spotlight = new SceneLight(SceneLight::SPOT_LIGHT, scene, 33, .2, .5, .05);
spotlight->setSpotlightProperties(20,6);
scene->addLight(spotlight);
}
void Player::translate(const Number& x, const Number& y, const Number& z)
{
obj->Translate(x,y,z);
}
void Player::rotate(const Quaternion& q)
{
Quaternion rotated =q+ obj->getRotationQuat() ;
rotated.Normalize();
obj->setRotationQuat(rotated.w, rotated.x, rotated.y, rotated.z);
}
void Player::Update(Number elapsed, const Keyboard & keyboard)
{
if(keyboard.isKeyDown(KEY_UP))
{
vel.y = 4;
}
if(keyboard.isKeyDown(KEY_DOWN))
{
vel.y = -4;
}
if(keyboard.isKeyDown(KEY_LEFT))
{
vel.x = -4;
}
if(keyboard.isKeyDown(KEY_RIGHT))
{
vel.x = 4;
}
if(keyboard.isKeyDown(304))
{
zoffset -= 0.5;
if (zoffset < -4) zoffset = -4;
}
if(keyboard.isKeyDown(306))
{
zoffset += 0.5;
if (zoffset > 4) zoffset = 4;
}
vel += accl*elapsed;
if( !keyboard.isKeyDown(304) && !keyboard.isKeyDown(306) )
{
zoffset *= 0.7;
}
accl.z = (vel.z-maxSpeed);
if(vel.length() > maxSpeed)
{
vel.Normalize();
vel = vel * maxSpeed;
}
obj->Translate(vel*elapsed);
obj->Yaw(vel.x*200*elapsed);
obj->Pitch(vel.y*-200*elapsed);
homeSlice += vel.z*elapsed;
if( dirtyCam)
{
dirtyCam =false;
cam->lookAt(Vector3( 0,0,homeSlice));
}
obj->setPositionZ(homeSlice + zoffset);
//cam-> Translate(0,0, vel.z*elapsed);
cam->setPositionZ(homeSlice + 15);
spotlight->setPosition( cam -> getPosition() );
spotlight->lookAt( obj->getPosition() );
}
const Vector3& Player::getPosition()
{
return obj->getPosition();
}
void Player::setMaxSpeed(double speed)
{
maxSpeed = speed;
}
|
Swift
|
UTF-8
| 2,971
| 3
| 3
|
[
"MIT"
] |
permissive
|
//
// NewsDetailView.swift
// News
//
// Created by Ravi Theja on 20/03/20.
// Copyright © 2020 Idlebrains. All rights reserved.
//
import SwiftUI
import URLImage
let exampleArticle = ListItem(articleUrl: "https://www.theverge.com/2020/3/19/21187161/microsoft-directx-12-ultimate-api-release-xbox-series-x-pc-gaming",
name: "Microsoft’s DirectX 12 Ultimate unifies graphics tech for PC gaming and Xbox Series X",
description: "Bringing a suite of software advancements in gaming graphics onto a single platform",
date: Date(),
source: "The Verge",
body: "Bringing a suite of software advancements in gaming graphics onto a single platform")
struct NewsDetailView: View {
let article: ListItem
var body: some View {
HStack(alignment: .top) {
VStack(alignment: .leading, spacing: 20) {
Text(article.name).font(.largeTitle).lineLimit(nil)
VStack(alignment: .leading, spacing: 5) {
HStack(alignment: .center) {
if (article.imageUrl != nil) {
URLImage(article.imageUrl!, placeholder: {_ in
Image("placeholder-image").resizable().aspectRatio(contentMode: .fit)
}, content: {
$0.image.resizable().aspectRatio(contentMode: .fit)
})
} else {
Image("placeholder-image").resizable().aspectRatio(contentMode: .fit)
}
}
HStack {
Text(article.sourceWebsite ?? "Unknown").font(.footnote).foregroundColor(.gray)
Spacer()
Text(Utils.getFormattedDateString(someDate: article.date)).font(.footnote).foregroundColor(.gray)
}
}
Text(article.body ?? article.description).lineLimit(nil).font(.body)
HStack(alignment: .center) {
Button(action: {
print("Request to open article \(self.article.articleUrl)")
let url: URL? = URL(string: self.article.articleUrl)!
guard url != nil else {
return
}
UIApplication.shared.open(url!)
}, label: {
Text("Read full article")
}).disabled(article.articleUrl.isEmpty).padding().frame(maxWidth: .infinity).border(Color.blue).padding()
}
}.padding()
Spacer()
}
}
}
struct NewsDetailView_Previews: PreviewProvider {
static var previews: some View {
NewsDetailView(article: exampleArticle)
}
}
|
TypeScript
|
UTF-8
| 2,515
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
import { Post, Command } from "../types"
import { MessageEmbed } from "discord.js";
import getErrString from '../getErrString'
const paginationEmbed = require("discord.js-pagination");
import axios from 'axios';
//Formats an Array of Posts into a String that can be sent as an embedded message
const postsToString = (pArray: Post[]) => {
return pArray.map(post => {
return `**${post.company_name}${post.municipality_name != null ? ' --- ' + post.municipality_name : ''}**
[${post.heading}](https://duunitori.fi/tyopaikat/tyo/${post.slug})`
}).join("\n\n");
}
const posts: Command = {
name: 'posts',
description: 'Get the original developer job postings',
usage: 'dev posts <all>',
arguments: ['all'],
cooldown: 5,
async execute(message, args) {
if (args[0] == 'all') {
//GET ALL DEVELOPER JOB POSTINGS
//Send a placeholder message
let msg = await message.channel.send("Getting the latest developer job postings from Duunitori.")
//Asynchronous http get request from dev-job-api
axios.get("http://dev-job-api.herokuapp.com/api/posts").then(async response => {
let allPosts: Array<Post> = response.data.posts;
const pages: Array<MessageEmbed> = [];
const chunk: number = 10;
for (let i: number = 0; i < allPosts.length; i += chunk) {
//Get the next 10 posts
let postsArr: Array<Post> = allPosts.slice(i, i + chunk);
//Combine info about the post objects into a string
let strPosts = postsToString(postsArr);
//Append the results into an embed
let embed = new MessageEmbed()
.setTitle(`*Duunitori developer job postings*`)
.setDescription(strPosts);
//Add the next embed page to the array
pages.push(embed);
}
msg.edit("Here they are:");
paginationEmbed(message, pages);
return;
}).catch((err) => {
console.log(err);
return msg.channel.send("Sorry, an error occurred while getting the job postings.");
})
} else {
//If the user supplies the command with invalid arguments
return message.channel.send(getErrString(this, args))
}
}
}
module.exports = posts;
|
Python
|
UTF-8
| 5,731
| 2.953125
| 3
|
[] |
no_license
|
import streamlit as st
import pydeck as pdk
from requests import get
from json import loads
from agente import Buscador
from lista_cidades import lista_cidades
class RotasCidades:
def __init__(self):
self.limite = False
self.cidades = lista_cidades
self.cidade_final = ""
self.metodos_opcoes = ["AMPLITUDE", "PROFUNDIDADE", "PROFUNDIDADE LIMITADA",
"APROFUNDAMENTO ITERATIVO", "BIDIRECIONAL", "A_ESTRELA",
"GREEDY", "CUSTO_UNIFORME"]
#metodo que ira iniciar quando a pagina carregar
def inicial(self):
"""Inicia a pagina com esses elementos"""
st.set_page_config(page_title="Rotas Cidades")
st.title("Rotas Cidades")
texto1 = "Cidade para receber Ajuda Humanitária:"
self.cidade_final = st.sidebar.selectbox(texto1, self.cidades)
texto2 = "Método para gerar a rota:"
self.metodo = st.sidebar.selectbox(texto2, self.metodos_opcoes)
if self.metodo == self.metodos_opcoes[2]:
buscar_rota = False
texto = "Informe o limite da rota:"
self.limite = st.sidebar.number_input(texto, min_value=1, step=1, max_value=10)
buscar_rota = st.sidebar.checkbox("Buscar rota")
if buscar_rota:
self.gerar_rota()
#metodo para gerar a rota de Ajuda Humanitaria e Atendimento
def gerar_rota(self):
agente = Buscador()
if self.metodos_opcoes.index(self.metodo) >= 5:
rota_AH = agente.encontrar_caminho_ponderado(self.cidade_final, self.metodo, 1)
rota_AT = agente.encontrar_caminho_ponderado(self.cidade_final, self.metodo, 2)
#rota_AT = agente.encontrar_atendimento(self.cidade_final, "AMPLITUDE")
else:
rota_AH = agente.encontrar_ajuda_humanitaria(self.cidade_final, self.metodo, self.limite)
rota_AT = agente.encontrar_atendimento(self.cidade_final, self.metodo, self.limite)
rota_final = agente.unifica_caminho(rota_AH, rota_AT)
st.info("Ajuda Humanitária sai de: {}.".format(rota_final[0]))
st.info("O Atendimento mais próximo é: {}.".format(rota_final[len(rota_final)-1]))
if len(rota_final)>=3:
desc = self.descrever_rota(rota_final)
st.success(desc)
self.busca_coordenadas(rota_final)
#metodo para fazer as coordenadas
def busca_coordenadas(self, rota):
coord_da_rota = []
for i in rota:
requisicao = get("https://api-valeparaiba.herokuapp.com/valedoparaiba/coordenadas/{}/".format(i))
lat_lon = loads(requisicao.content)
coord_da_rota.append(lat_lon)
for i in range(len(coord_da_rota)):
if i == len(coord_da_rota)-1:
coord_da_rota[i]['lat2'] = coord_da_rota[i]['lat']
coord_da_rota[i]['lon2'] = coord_da_rota[i]['lon']
else:
coord_da_rota[i]['lat2'] = coord_da_rota[i+1]['lat']
coord_da_rota[i]['lon2'] = coord_da_rota[i+1]['lon']
self.plotar_mapa(coord_da_rota)
self.apresentar_pontos()
#metodo para desenhar e exibir mapa
def plotar_mapa(self, coord_rota):
try:
ALL_LAYERS = {
"Pontos": pdk.Layer(
"ScatterplotLayer",
data=coord_rota,
get_position=["lon", "lat"],
get_color=[210, 50, 192, 50],
get_radius=30000,
radius_scale=0.05,
),
"Ligações": pdk.Layer(
"ArcLayer",
data=coord_rota,
get_source_position=["lon", "lat"],
get_target_position=["lon2", "lat2"],
get_source_color=[200, 30, 0, 160],
get_target_color=[200, 30, 0, 160],
auto_highlight=True,
width_scale=0.1,
get_width="outbound",
width_min_pixels=3,
width_max_pixels=30,
)
}
st.sidebar.markdown('### Opções')
selected_layers = [
layer for layer_name, layer in ALL_LAYERS.items()
if st.sidebar.checkbox(layer_name, True)
]
if selected_layers:
estilo = "mapbox://styles/mapbox/streets-v11"
st.pydeck_chart(pdk.Deck(
map_style=estilo,
initial_view_state={"latitude": coord_rota[0]["lat"], #37.76
"longitude": coord_rota[0]["lon"], "pitch": 50},
layers=selected_layers,
))
else:
st.error("Please choose at least one layer above.")
except:
st.error("Algum erro aconteceu.")
#Funcao para descrever a rota
def descrever_rota(self, rota):
desc = "Saindo de {}, você deverá passar por ".format(rota[0])
for i in range(1, len(rota)):
if i == len(rota)-1:
desc = desc+" e por fim {}.".format(rota[i])
else:
desc = desc+" {},".format(rota[i])
return desc
#Funcao para apresentar os pontos de AH e Atendimento
def apresentar_pontos(self):
agente = Buscador()
AH, AT = agente.mostrar_pontos()
st.info("Os pontos de Ajuda Humanitária no Vale do Paraíba são:{}".format(AH))
st.info("Os pontos de Atendimento Hospitalar são:{}".format(AT))
if __name__ == "__main__":
rc = RotasCidades()
rc.inicial()
|
C++
|
UTF-8
| 788
| 2.6875
| 3
|
[] |
no_license
|
#pragma once
#include "Piloto.h"
#include "Consola.h"
#include <vector>
#include <iostream>
using namespace std;
class Pista {
int maxCar;
int metros;
vector <Piloto*> pilotosPista;
public:
Pista(int maxCar, int metros);
~Pista();
int returnTamPista() const {
return metros;
}
int returnMaxCarros() const {
return maxCar;
}
size_t returnNumPilotosPista() const {
return pilotosPista.size();
}
string returnNomePiloto(int i)const {
return pilotosPista[i]->getNome();
}
char returnIDCarro(int i)const {
return pilotosPista[i]->getIDCar();
}
Piloto* returnPilotoPista(int pos){
return pilotosPista[pos];
}
void inserePilotoNaPista(Piloto* aux);
Piloto* retiraPiloto(char id);
// Se ligar sinal de emergencia, sai da pista, move to garagem
};
|
Python
|
UTF-8
| 1,767
| 2.9375
| 3
|
[
"CC-BY-3.0"
] |
permissive
|
import unicodedata
import codecs
import sys
import scipy as sp
import hmm
tbl = dict.fromkeys(i for i in xrange(sys.maxunicode)
if unicodedata.category(unichr(i)).startswith('P'))
def uniq(listinput):
""" This finds the unique elements of the list listinput. """
""" This will be provided for the student. """
output = []
for x in listinput:
if x not in output:
output.append(x)
return output
def remove_punctuation(text):
return text.translate(tbl)
def fileParse(filename):
infile = codecs.open(filename,'r','utf-8')
data = []
for line in infile:
data.append(line)
characters = []
for i in xrange(len(data)):
characters += list(remove_punctuation(data[i].rstrip() + ' ').lower())
return(characters)
def alphabet(characters):
return(sp.sort(uniq(characters)).tolist())
def printLetters(alphabet):
for i in xrange(len(alphabet)):
print alphabet[i].encode('utf-8')
return
def russianHMM(n_trials,characters,alphabet):
model = hmm.hmmTrain(characters,2,tol=.1,maxiter=100)
obs = hmm.transformObservations(alphabet,characters)
logProb = hmm.score(model,obs)
for i in xrange(n_trials-1):
print(i)
temp_model = hmm.hmmTrain(characters,2,tol=.1,maxiter=100)
temp_logProb = hmm.score(temp_model,obs)
if temp_logProb > logProb:
model = temp_model
logProb = temp_logProb
return model
def separateVowels(model,characters,alphabet):
alpha,beta,logProb = hmm.betaPass(model,hmm.transformObservations(alphabet,characters))
gam = hmm.gamma(alpha,beta)
stateProbs = sp.sum(gam,0)/gam.shape[0]
bools = model[1][0,:]*stateProbs[0] > model[1][1,:]*stateProbs[1]
state_1_chars = sp.array(alphabet)[bools].tolist()
state_2_chars = sp.array(alphabet)[-bools].tolist()
return state_1_chars, state_2_chars
|
C++
|
UTF-8
| 421
| 2.625
| 3
|
[
"Unlicense"
] |
permissive
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
// https://www.hackerrank.com/contests/30-days-of-code/challenges/day-0-print-hello-world/submissions/code/4670326
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
cout << "Hello World." << endl << "Welcome to 30 Days of Code.";
return 0;
}
|
Java
|
UTF-8
| 7,079
| 2.15625
| 2
|
[] |
no_license
|
package com.deals.sine90.dealsinstreet;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.PorterDuff;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Home extends AppCompatActivity {
ImageView homeimage,mapimage,wishlistimage,storeimage,expireimage;
LinearLayout home,map,wishlist,store,expire;
TextView hometext,maptext,wishlisttext,storetext,expiretext;
Resources res;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//getting resources
res = getApplicationContext().getResources();
final int newColor = res.getColor(R.color.colorPrimary);
//getting ids
home=(LinearLayout)findViewById(R.id.home);
homeimage=(ImageView)findViewById(R.id.homeimage);
hometext=(TextView)findViewById(R.id.hometext);
map=(LinearLayout)findViewById(R.id.maps);
mapimage=(ImageView)findViewById(R.id.mapimage);
maptext=(TextView)findViewById(R.id.maptext);
wishlist=(LinearLayout)findViewById(R.id.wishlist);
wishlistimage=(ImageView)findViewById(R.id.wishlistimage);
wishlisttext=(TextView)findViewById(R.id.wishlisttext);
store=(LinearLayout)findViewById(R.id.mystore);
storeimage=(ImageView)findViewById(R.id.mystoreimage);
storetext=(TextView)findViewById(R.id.mystoretext);
expire=(LinearLayout)findViewById(R.id.expiring);
expireimage=(ImageView)findViewById(R.id.expiringimage);
expiretext=(TextView)findViewById(R.id.expiringtext);
//default set color for home icon and text
homeimage.setColorFilter(newColor, PorterDuff.Mode.SRC_ATOP);
hometext.setTextColor(newColor);
//map on clicklistener
map.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mapimage.setColorFilter(newColor, PorterDuff.Mode.SRC_ATOP);
maptext.setTextColor(newColor);
hometext.setTextColor(getResources().getColor(R.color.light_blacck));
homeimage.setColorFilter(null);
wishlisttext.setTextColor(getResources().getColor(R.color.light_blacck));
wishlistimage.setColorFilter(null);
storeimage.setColorFilter(null);
storetext.setTextColor(getResources().getColor(R.color.light_blacck));
expireimage.setColorFilter(null);
expiretext.setTextColor(getResources().getColor(R.color.light_blacck));
Intent intent=new Intent(Home.this,MapsActivity.class);
startActivity(intent);
}
});
wishlist.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
wishlistimage.setColorFilter(newColor,PorterDuff.Mode.SRC_ATOP);
wishlisttext.setTextColor(newColor);
hometext.setTextColor(getResources().getColor(R.color.light_blacck));
homeimage.setColorFilter(null);
maptext.setTextColor(getResources().getColor(R.color.light_blacck));
mapimage.setColorFilter(null);
storeimage.setColorFilter(null);
storetext.setTextColor(getResources().getColor(R.color.light_blacck));
expireimage.setColorFilter(null);
expiretext.setTextColor(getResources().getColor(R.color.light_blacck));
Intent intent=new Intent(Home.this,WishList.class);
startActivity(intent);
}
});
store.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
storetext.setTextColor(newColor);
storeimage.setColorFilter(newColor,PorterDuff.Mode.SRC_ATOP);
hometext.setTextColor(getResources().getColor(R.color.light_blacck));
homeimage.setColorFilter(null);
maptext.setTextColor(getResources().getColor(R.color.light_blacck));
mapimage.setColorFilter(null);
wishlisttext.setTextColor(getResources().getColor(R.color.light_blacck));
wishlistimage.setColorFilter(null);
expireimage.setColorFilter(null);
expiretext.setTextColor(getResources().getColor(R.color.light_blacck));
Intent intent=new Intent(Home.this,Mystore.class);
startActivity(intent);
}
});
expire.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
expiretext.setTextColor(newColor);
expireimage.setColorFilter(newColor,PorterDuff.Mode.SRC_ATOP);
hometext.setTextColor(getResources().getColor(R.color.light_blacck));
homeimage.setColorFilter(null);
maptext.setTextColor(getResources().getColor(R.color.light_blacck));
mapimage.setColorFilter(null);
wishlisttext.setTextColor(getResources().getColor(R.color.light_blacck));
wishlistimage.setColorFilter(null);
storeimage.setColorFilter(null);
storetext.setTextColor(getResources().getColor(R.color.light_blacck));
Intent intent=new Intent(Home.this,Expiring.class);
startActivity(intent);
}
});
//home onclicklistener
home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
homeimage.setColorFilter(newColor, PorterDuff.Mode.SRC_ATOP);
hometext.setTextColor(newColor);
maptext.setTextColor(getResources().getColor(R.color.light_blacck));
mapimage.setColorFilter(null);
wishlisttext.setTextColor(getResources().getColor(R.color.light_blacck));
wishlistimage.setColorFilter(null);
storeimage.setColorFilter(null);
storetext.setTextColor(getResources().getColor(R.color.light_blacck));
expireimage.setColorFilter(null);
expiretext.setTextColor(getResources().getColor(R.color.light_blacck));
}
});
}
@Override
public void onBackPressed() {
//Execute your code here
finish();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//finish();
onBackPressed();
break;
}
return true;
}
}
|
PHP
|
UTF-8
| 837
| 3.15625
| 3
|
[] |
no_license
|
<?php
class Pedido{
private $cliente = NULL;
private $productos = NULL;
public function __construct(Cliente $cliente=NULL,Productos $productos=NULL){
if($cliente!==NULL){
$this->setCliente($cliente);
}
}
public function setCliente(Cliente $cliente){
return $this->cliente = $cliente;
}
public function getCliente(){
return $this->cliente;
}
public function setProductos(Productos $productos){
$this->productos = $productos;
}
public function getProductos(){
return $this->productos;
}
public function guardar(){
}
}
|
TypeScript
|
UTF-8
| 543
| 3.921875
| 4
|
[] |
no_license
|
abstract class Animal {
private name: string;
constructor(theName: string){
this.name = theName;
}
walk(distance: number){
console.log(`Hi, my name is ${this.name} and I'm walking ${distance} meters`);
}
}
// abstract can not instancete let aAnimal = new Animal("Test");
// aAnimal.walk(10);
class Snake extends Animal{
constructor(theName: string) {
super(theName);
}
// overwrite walk function
walk(distance: number){
console.log("Snakes don't really walk")
}
}
|
C
|
UTF-8
| 5,752
| 3.28125
| 3
|
[] |
no_license
|
/***********************************************************************
*
* OBJECT.C
* Object File Routines for 68000 Assembler
*
* Function: initObj()
* Opens the specified object code file for writing. If the file cannot
* be opened, then the routine prints a message and exits.
*
* outputObj()
* Places the data whose size, value, and address are specified in the
* object code file. If the new data would cause the current S-record to
* exceed a certain length, or if the address of the current item doesn't
* follow immediately after the address of the previous item, then the
* current S-record is written to the file (using writeObj) and a new
* S-record is started, beginning with the specified data.
*
* writeObj()
* Writes the current S-record to the object code file. The record length
* and checksum fields are filled in before the S-record is written. If
* an error occurs during the writing, the routine prints a message and
* exits.
*
* finishObj()
* Flushes the S-record buffer by writing out the data in it (using
* writeObj), if any, then writes a termination S-record and closes the
* object code file. If an error occurs during this write, the routine
* prints a messge and exits.
*
* Usage: initObj(char *name)
*
* int outputObj(long newAddr, int data, int size)
*
* int writeObj(void)
*
* finishint Obj(void)
*
* Author: Paul McKee
* ECE492 North Carolina State University, 12/13/86
* Modified A.E. Romer 17 March 1991
* Version 1.0
************************************************************************/
#include <stdio.h>
#include <ctype.h>
#include "asm.h"
/* Define the maximum number of bytes (address, data,
and checksum) that can be in one S-record */
#define SRECSIZE 36
extern char line[256];
extern FILE *objFile;
static char sRecord[80], *objPtr;
static char byteCount, checksum, lineFlag;
static long objAddr;
static char objErrorMsg[] = "Error writing to object file\n";
int initObj(char *name)
{
objFile = fopen(name, "w");
if (!objFile)
{
puts("Can't open object file");
exit(0);
}
/* Output S-record file header */
/* fputs("Here comes an S-record...\n", objFile); */
fputs("S004000020DB\n", objFile);
lineFlag = FALSE;
return NORMAL;
}
int outputObj(long newAddr, long data, int size)
{
/* If the new data doesn't follow the previous data, or if the S-record
would be too long, then write out this S-record and start a new one */
if ((lineFlag && (newAddr != objAddr)) || (byteCount + size > SRECSIZE))
{
writeObj();
lineFlag = FALSE;
}
/* If no S-record is already being assembled, then start making one */
if (!lineFlag)
{
if ((newAddr & 0xFFFF) == newAddr)
{
sprintf(sRecord, "S1 %04X", newAddr);
byteCount = 2;
}
else if ((newAddr & 0xFFFFFF) == newAddr)
{
sprintf(sRecord, "S2 %06X", newAddr);
byteCount = 3;
}
else
{
sprintf(sRecord, "S3 %08lX", newAddr);
byteCount = 4;
}
objPtr = sRecord + 4 + byteCount*2;
checksum = (char) (checkValue(newAddr) & 0xff);
objAddr = newAddr;
lineFlag = TRUE;
}
/* Add the new data to the S-record */
switch (size)
{
case BYTE : data &= 0xFF;
sprintf(objPtr, "%02X", data);
byteCount++;
checksum += (char) (data & 0xff);
break;
case WORD : data &= 0xFFFF;
sprintf(objPtr, "%04X", data);
byteCount += 2;
checksum += (char) (checkValue(data) & 0xff);
break;
case LONG : sprintf(objPtr, "%08lX", data);
byteCount += 4;
checksum += (char) (checkValue(data) & 0xff);
break;
default : printf("outputObj: INVALID SIZE CODE!\n");
exit(0);
}
objPtr += size*2;
objAddr += (long) size;
return NORMAL;
}
long checkValue(long data)
{
return (data + (data >> 8) + (data >> 16) + (data >> 24)) & 0xFF;
}
int writeObj(void)
{
char recLen[3];
/* Fill in the record length
* (including the checksum in the record length */
sprintf(recLen, "%02X", ++byteCount);
strncpy(sRecord+2, recLen, 2);
/* Add the checksum
* (including in the checksum the record length) */
checksum += byteCount;
sprintf(objPtr, "%02X\n", (~checksum & 0xFF));
/* Output the S-record to the object file */
/* fputs("Here comes an S-record...\n", objFile); */
fputs(sRecord, objFile);
if ferror(objFile)
{
fputs(objErrorMsg, stderr);
exit(0);
}
return NORMAL;
}
int finishObj(void)
{
/* Write out the last real S-record, if present */
if (lineFlag)
writeObj();
/* Write out a termination S-record and close the file*/
fputs("S9030000FC\n", objFile);
if ferror(objFile)
{
fputs(objErrorMsg, stderr);
exit(0);
}
fclose(objFile);
return NORMAL;
}
|
Java
|
UTF-8
| 163
| 1.84375
| 2
|
[] |
no_license
|
package com.exalto.UI.grid;
import javax.swing.JButton;
public class Corner extends JButton
{
public Corner() {
super("");
setBorderPainted(false);
}
}
|
Java
|
UTF-8
| 2,240
| 1.9375
| 2
|
[] |
no_license
|
package cn.appsys.service;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.appsys.dao.AppInfoMapper;
import cn.appsys.pojo.AppCategory;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.DataDictionary;
@Service("AppInfoServiceImpl")
public class AppInfoServiceImpl implements AppInfoService {
@Autowired
AppInfoMapper appInfoMapper;
@Override
public List<AppInfo> getAppInfosByPage(Map<String, Object> map) {
return appInfoMapper.getAppInfosByPage(map);
}
@Override
public int getAppInfoTotalCount(AppInfo appInfo) {
return appInfoMapper.getAppInfoTotalCount(appInfo);
}
@Override
public List<AppCategory> getFirstLevelList() {
return appInfoMapper.getFirstLevelList();
}
@Override
public List<AppCategory> getSecondLevelList(
int firstLevelId) {
return appInfoMapper.getSecondLevelList(firstLevelId);
}
@Override
public List<AppCategory> getThridLevelList(
int secondLevelId) {
return appInfoMapper.getThridLevelList(secondLevelId);
}
@Override
public List<DataDictionary> getAppStatusList() {
return appInfoMapper.getAppStatusList();
}
@Override
public List<DataDictionary> getAppFlatFormList() {
return appInfoMapper.getAppFlatFormList();
}
@Override
public List<DataDictionary> getAppFlatFormList(String typeCode) {
// TODO Auto-generated method stub
return appInfoMapper.getAppFlatFormList(typeCode);
}
@Override
public int checkApkNameUnique(@Param("APKName") String APKName) {
// TODO Auto-generated method stub
return appInfoMapper.checkApkNameUnique(APKName);
}
@Override
public int addAppInfo(AppInfo appInfo) {
// TODO Auto-generated method stub
return appInfoMapper.addAppInfo(appInfo);
}
@Override
public AppInfo getAppInfoById(int id) {
return appInfoMapper.getAppInfoById(id);
}
@Override
public AppInfo getAppByAidVid(AppInfo appInfo) {
return appInfoMapper.getAppByAidVid(appInfo);
}
@Override
public boolean checkApp(AppInfo appInfo) {
int row = appInfoMapper.checkApp(appInfo);
if (row != 0) {
return true;
}else{
return false;
}
}
}
|
C++
|
UTF-8
| 2,349
| 3.40625
| 3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"ISC"
] |
permissive
|
#include "nb/NBMatrixMath.h"
using namespace NBMath;
/**
Invert a two by two matrix easily
given:
[a b
c d]
return:
(1/(ad - bc)) [ d -b
-c a]
@param m the 2 by 2 matrix to invert.
@return the inversion of m
*/
const boost::numeric::ublas::matrix<double>
NBMath::invert2by2(boost::numeric::ublas::matrix<double> m) {
double det = 1.0 / (m(0, 0) * m(1, 1) - m(0, 1) * m(1, 0));
double tmp = m(0, 0);
m(0, 0) = m(1, 1);
m(1, 1) = tmp;
tmp = -m(0, 1);
m(0, 1) = -m(1, 0);
m(1, 0) = tmp;
return det * m;
}
const boost::numeric::ublas::vector<double>
NBMath::solve(boost::numeric::ublas::matrix<double> A,
const boost::numeric::ublas::vector<double>& b) {
boost::numeric::ublas::permutation_matrix<double> P(A.size1());
int singularRow = lu_factorize(A, P);
if (singularRow != 0) {
// TODO: This case needs to be dealt with
throw "the system had no solution";
}
boost::numeric::ublas::vector<double> result(A.size2());
result.assign(b);
lu_substitute(A, P, result);
return result;
}
const boost::numeric::ublas::matrix<double>
NBMath::solve(boost::numeric::ublas::matrix<double> A,
const boost::numeric::ublas::matrix<double>& B) {
boost::numeric::ublas::permutation_matrix<double> P(A.size1());
int singularRow = lu_factorize(A, P);
if (singularRow != 0) {
// TODO: This case needs to be dealt with
throw "the system had no solution";
}
boost::numeric::ublas::matrix<double> result(A.size2(), B.size1());
result.assign(B);
lu_substitute(A, P, result);
return result;
}
// Solve the linear system Ax=b for the vector x.
// NOTE: This method is hard coded to work for 3x3 matrices and 3-vectors.
// We can get superior performance this way.
const ufvector3 NBMath::solve(ufmatrix3& A,
const ufvector3& b) {
boost::numeric::ublas::permutation_matrix
<double, boost::numeric::ublas::bounded_array<double, 9> >
P(A.size1());
int singularRow = lu_factorize(A, P);
if (singularRow != 0) {
// TODO: This case needs to be dealt with
throw "the system had no solution";
}
ufvector3 result(A.size2());
result.assign(b);
lu_substitute(A, P, result);
return result;
}
|
C++
|
UTF-8
| 999
| 2.515625
| 3
|
[] |
no_license
|
const uint16_t timer_start = 0;
const uint16_t timer_threshold = 8000;
const int LED = 4;
const int ledPin = 13;
ISR (PCINT0_vect) // handle pin change interrupt for D8 to D13 here
{
digitalWrite(LED, !digitalRead(BlueLED));
Serial.println("Pin D8-D13 Triggerd");
}
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(LED, OUTPUT);
// initialize timer1
//Commence serial communication
Serial.begin(9600);
//Reset timer register
TCCR1A = 0;
//Set prescaler to 1024
TCCR1B |= (1 << CS12);
TCCR1B &= ~(1 << CS11);
TCCR1B |= (1 << CS10);
//Reset timer and set timer compare bit
TCNT1 = timer_start;
OCR1A = timer_threshold;
//Enable Timer1 interrupt
TIMSK1 = (1 << OCIE1A);
//Enabling pin interrupt
PCICR |= 0b00000111;
PCMSK0 |=0b00000111;
//Setting input and outputs
pinMode(ledPin, OUTPUT);
pinMode(LED, OUTPUT);
pinMode(8, INPUT);
}
ISR(TIMER1_COMPA_vect) {
digitalWrite(ledPin, !digitalRead(ledPin));
TCNT1 = timer_start;
}
void loop()
{
}
|
Python
|
UTF-8
| 1,379
| 3.5625
| 4
|
[] |
no_license
|
# --STAR-- --Link--
# https://evelynn.gitbooks.io/google-interview/strobogrammatic_number_iii.html
class Solution:
"""
@param n: the length of strobogrammatic number
@return: All strobogrammatic numbers
"""
def findStrobogrammatic(self, lo, hi):
# write your code here
self.nums = ['0', '1', '6', '8', '9']
self.rnums = ['0', '1', '9', '8', '6']
n_hi, _hi = 0, int(hi)
while _hi > 0:
_hi //= 10
n_hi += 1
n_lo, _lo = 0, int(lo)
while _lo > 0:
_lo //= 10
n_lo += 1
for n in range(n_lo, n_hi + 1):
k = self.generate(n, n & 1, ['0', '1', '8'] if n & 1 == 1 else [''], int(lo), int(hi))
if n == n_lo or n == n_hi:
k = list(filter(lambda v: int(lo) <= int(v) <= int(hi), k))
print(k)
"""
@param n: max number of digits
@param l: current number of digits
"""
def generate(self, n, l, ret, lo, hi):
if l >= n:
return ret
newRet = []
startIndex = 0 if l < n - 2 else 1
for s in ret:
for i in range(startIndex, len(self.nums)):
new_s = self.nums[i] + s + self.rnums[i]
newRet += [ new_s ]
return self.generate(n, l + 2, newRet, lo, hi)
Solution().findStrobogrammatic("123", "1234")
|
Markdown
|
UTF-8
| 1,032
| 2.828125
| 3
|
[] |
no_license
|
# [MediaShout Script to Text](http://DouglasMeyer.github.com/MediaShoutScriptToText)
This is a helper HTML page to convert a MediaShout script (.ssc) to a format that is ready to print.
## How to use it
Go to [this](http://DouglasMeyer.github.com/MediaShoutScriptToText) page and drag your .scc file into the dashed box. Your script should be ready to print. If you would like to make some changes before printing, do so; the page should be editable.
I hope this is able to help you out. If there is some way this tool could help you out better, [let me know](mailto:DouglasMeyer@mail.com?subject=MediaShout script to text.).
## Why did I make this
This project was created because I needed to print all the songs from a .scc along with scripture references (to help the translator for my church's Spanish ministry). Unfortunately, MediaShout V4 doesn't provide an easy way to do this.
## What this will do
* Make it easy to print what you want from a .ssc file.
## What this won't do
* Edit or create files to be used in MediaShout
|
C++
|
UTF-8
| 439
| 3.171875
| 3
|
[] |
no_license
|
#include "copy_constructor.hpp"
Pencil::Pencil() : color(""),
cost(0) {}
Pencil::Pencil(std::string c, int initial_cost) : color(c),
cost(initial_cost) {}
Pencil::Pencil(const Pencil &old) : color(old.color),
cost(old.cost) {}
std::string Pencil::getColor() {
return color;
}
int Pencil::getCost() {
return cost;
}
|
JavaScript
|
UTF-8
| 1,526
| 2.59375
| 3
|
[] |
no_license
|
import React, { Component } from "react";
import PlayListTrack from "../../components/PlayListTrack";
export default class PlayList extends Component {
state = {
loading: true,
error: null,
playList: null
};
constructor() {
super();
}
componentDidMount() {
this.loadPlayList();
}
loadPlayList = () => {
console.log("loading play list");
const URL = "https://react-api-lab.herokuapp.com/playlists/@miikEe12";
this.setState({
loading: true,
error: null
});
fetch(URL)
.then(response => response.json())
.then(data => {
this.setState({
loading: false,
playList: data.data
});
})
.catch(error => {
this.setState({
loading: false,
error: error
});
});
};
//return <TrackListItem key={track.id} data={track} />;
renderList(playList) {
const list = playList.map(item => {
return <PlayListTrack key={item.id} data={item.track} />;
});
return list;
}
render() {
const { loading, playList, error } = this.state;
console.log(playList);
return (
<main className="container">
{!loading &&
playList && (
<React.Fragment>
<div className="container-trakcs">
<h2>Tracks:</h2>
<div>
<ul>{this.renderList(playList)}</ul>
</div>
</div>
</React.Fragment>
)}
</main>
);
}
}
|
Markdown
|
UTF-8
| 1,933
| 4.03125
| 4
|
[] |
no_license
|
Comparison and logical operators
You may be familiar with comparison operators from math class. Let’s make sure there aren’t any gaps in your knowledge.
Comparison Operators
Less than (<) — returns true if the value on the left is less than the value on the right, otherwise it returns false.
Greater than (>) — returns true if the value on the left is greater than the value on the right, otherwise it returns false.
Less than or equal to (<=) — returns true if the value on the left is less than or equal to the value on the right, otherwise it returns false.
Greater than or equal to (>=) — returns true if the value on the left is greater than or equal to the value on the right, otherwise it returns false.
Equal to (===) — returns true if the value on the left is equal to the value on the right, otherwise it returns false.
Not equal to (!==) — returns true if the value on the left is not equal to the value on the right, otherwise it returns false.
Logical Operators
Comparison operators allow us to assert the equality of a statement with JavaScript. For example, we can assert whether two values or expressions are equal with ===, or, whether one value is greater than another with >.
There are scenarios, however, in which we must assert whether multiple values or expressions are true. In JavaScript, we can use logical operators to make these assertions.
&& (and) — This operator will be truthy (act like true) if and only if the expressions on both sides of it are true. || (or) — This operator will be truthy if the expression on either side of it is true. Otherwise, it will be falsy (act like false).
While loop
The while loop loops through a block of code as long as a specified condition is true.
while (condition) {
// code block to be executed
}
For loop
The for loop has the following syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Thank you
|
C#
|
UTF-8
| 9,147
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
using System.Collections.Generic;
using System.Linq;
using System;
using System.Text.RegularExpressions;
using Plivo.Exception;
namespace Plivo.Utilities
{
public class MpcUtils
{
public static void ValidSubAccount(string accountId)
{
if (accountId.Length != 20)
{
throw new PlivoValidationException("Subaccount Id should be of length 20");
}
if (accountId.Substring(0, 2) != "SA")
{
Console.WriteLine(accountId.Substring(0, 3));
throw new PlivoValidationException("Subaccount Id should start with 'SA' ");
}
}
public static bool ValidMultipleDestinationNos(string paramName, string paramValue, string role, char delimiter, int limit)
{
if (paramValue.Split(delimiter).Count() > 1 && role.ToLower() != "agent")
{
throw new PlivoValidationException("Multiple " + paramName + " values given for role " + role);
}
else if (paramValue.Split(delimiter).Count() >= limit)
{
throw new PlivoValidationException("No of " + paramName + " values provided should be lesser than " +
Convert.ToString(limit));
}
else
{
return true;
}
}
public static bool ValidMultipleDestinationIntegers(string paramName, string paramValue)
{
string[] values = paramValue.Split('<');
int n;
for (int i=0;i<values.Length;i++)
{
if (!(int.TryParse(values[i], out n)))
{
throw new PlivoValidationException(paramName + "Destination Values must be of type int");
}
}
return true;
}
public static bool ValidParamString(string paramName, string paramValue = null, bool mandatory = false, List<string> expectedValues = null)
{
if (mandatory && paramValue == null)
{
throw new PlivoValidationException(paramName + " is a required parameter");
}
if (paramValue == null)
{
return true;
}
if (expectedValues == null)
{
return true;
}
if (!expectedValues.Contains(paramValue))
{
throw new PlivoValidationException(paramName + ": Expected one of " + string.Join(" ", expectedValues) + " but received " + paramValue + " instead");
}
return true;
}
public static bool ValidParamInt(string paramName, uint? paramValue = null, bool mandatory = false, List<uint?> expectedValues = null)
{
if (mandatory && paramValue == null)
{
throw new PlivoValidationException(paramName + " is a required parameter");
}
if (paramValue == null)
{
return true;
}
if (expectedValues == null)
{
return true;
}
if (!expectedValues.Contains(paramValue))
{
throw new PlivoValidationException(paramName + ": Expected one of " + string.Join(" ", expectedValues) + " but received " + paramValue + " instead");
}
return true;
}
public static bool MultiValidParam(string paramName, string paramValue,bool mandatory = false, bool makeLowerCase = false, List<string> expectedValues = null, char separator = ',')
{
if (mandatory && paramValue == null)
{
throw new PlivoValidationException(paramName + " is a required parameter");
}
if (paramValue == null)
{
return true;
}
if (makeLowerCase)
{
paramValue = paramValue.ToLower();
}
else
{
paramValue = paramValue.ToUpper();
}
string[] values = paramValue.Split(separator);
foreach (string value in values)
{
if (!expectedValues.Contains(value.Trim()))
{
throw new PlivoValidationException(paramName + ": Expected one of " + string.Join(" ", expectedValues) + " but received " + value + " instead");
}
}
return true;
}
public static bool ValidUrl(string paramName, string paramValue, bool mandatory = false)
{
if (mandatory && paramValue == null)
{
throw new PlivoValidationException(paramName + " is a required parameter");
}
if (paramValue == null)
{
return true;
}
string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
Regex rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (!rgx.IsMatch(paramValue))
{
throw new PlivoValidationException("Invalid URL : Doesn't satisfy the URL format");
}
else
{
return true;
}
}
public static bool IsOneAmongStringUrl(string paramName, string paramValue, bool mandatory = false,
List<string> expectedValues = null)
{
if (mandatory && paramValue == null)
{
throw new PlivoValidationException(paramName + " is a required parameter");
}
if (paramValue == null)
{
return true;
}
if (expectedValues.Contains(paramValue.ToLower()) || expectedValues.Contains(paramValue.ToUpper()))
{
return true;
}
else if(ValidUrl(paramName, paramValue))
{
return true;
}
else
{
throw new PlivoValidationException(paramName + " neither a valid URL nor in the expected values");
}
}
public static bool ValidDateFormat(string paramName, string paramValue, bool mandatory = false)
{
if (mandatory && paramValue == null)
{
throw new PlivoValidationException(paramName + " is a required parameter");
}
if (paramValue == null)
{
return true;
}
string Pattern = @"^(\d{4}\-\d{2}\-\d{2}\ \d{2}\:\d{2}(\:\d{2}(\.\d{1,6})?)?)$";
Regex rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (!rgx.IsMatch(paramValue))
{
throw new PlivoValidationException("Invalid Datetime : Doesn't satisfy the datetime format");
}
else
{
return true;
}
}
public static bool ValidRange(string paramName, uint? paramValue, bool mandatory = false, uint? lowerBound = null, uint? upperBound = null)
{
if (mandatory && paramValue == null)
{
throw new PlivoValidationException(paramName + " is a required parameter");
}
if (paramValue == null)
{
return true;
}
if (lowerBound != null && upperBound != null)
{
if (paramValue < lowerBound || paramValue > upperBound)
{
throw new PlivoValidationException(paramName + " ranges between " + Convert.ToString(lowerBound) + " and " + Convert.ToString(upperBound));
}
if (paramValue >= lowerBound && paramValue <= upperBound)
{
return true;
}
}
else if(lowerBound != null)
{
if (paramValue < lowerBound)
{
throw new PlivoValidationException(paramName + " should be greater than " +
Convert.ToString(lowerBound));
}
if (paramValue >= lowerBound)
{
return true;
}
}
else if(upperBound != null)
{
if (paramValue > upperBound)
{
throw new PlivoValidationException(paramName + " should be lesser than " +
Convert.ToString(upperBound));
}
if (paramValue <= upperBound)
{
return true;
}
}
else
{
throw new PlivoValidationException("Any one or both of lower and upper bound should be provided");
}
return true;
}
}
}
|
Shell
|
UTF-8
| 455
| 2.828125
| 3
|
[] |
no_license
|
echo Site Name:
read SITE_HUMAN_NAME
echo "Site Macince Name (dash sepereated words):"
read SITE
export PANTHEON_SITE_NAME=$SITE
PATH_TO_TERMINUS/terminus site:create --org ORG_ID $PANTHEON_SITE_NAME "$SITE_HUMAN_NAME" empty
export PANTHEON_SITE_GIT_URL="$(PATH_TO_TERMINUS/terminus connection:info $PANTHEON_SITE_NAME.dev --field=git_url)"
git remote add origin $PANTHEON_SITE_GIT_URL
PATH_TO_TERMINUS/terminus connection:set $PANTHEON_SITE_NAME.dev git
|
Rust
|
UTF-8
| 2,739
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
use Error;
use Year;
use CourseId;
use Degree;
use Studygroup;
use reqwest;
const BASE_URL: &'static str = "https://www2.htw-dresden.de/~app/API/GetExams.php";
/// An exam, something to study for!
#[derive(Deserialize, Debug)]
pub struct Exam {
#[serde(rename = "Title")]
pub title: String,
#[serde(rename = "ExamType")]
pub exam_type: String,
#[serde(rename = "StudyBranch")]
pub study_branch: String,
#[serde(rename = "Day")]
pub day: String,
#[serde(rename = "StartTime")]
pub start_time: String,
#[serde(rename = "EndTime")]
pub end_time: String,
#[serde(rename = "Examiner")]
pub examiner: String,
#[serde(rename = "NextChance")]
pub next_chance: String,
#[serde(rename = "Rooms")]
pub rooms: Vec<String>,
}
impl Exam {
/// Returns a list of `Exam`s for a given study group.
///
/// # Arguments
///
/// * `group` - Studygroup
///
/// # Example
///
/// ```
/// use htwdresden::{Degree, Studygroup, Exam};
///
/// let group = Studygroup { year: 2016, course: 121, group: 61, degree: Degree::Bachelor };
/// let exams = Exam::for_studygroup(&group);
/// ```
pub fn for_studygroup(group: &Studygroup) -> Result<Vec<Exam>, Error> {
Exam::for_student(group.year, group.course, group.degree)
}
/// Returns a list of `Exam`s for a given student.
///
/// # Arguments
///
/// * `year` - Year
/// * `course` - Course identifier
/// * `degree` - Degree
///
/// # Example
///
/// ```
/// use htwdresden::{Degree, Exam};
///
/// let exams = Exam::for_student(2016, 121, Degree::Bachelor);
/// ```
pub fn for_student(year: Year, course: CourseId, degree: Degree) -> Result<Vec<Exam>, Error> {
let url = format!("{base}?StgJhr={year}&Stg={course}&AbSc={degree}",
base = BASE_URL,
year = year,
course = course,
degree = degree.short());
let exams = reqwest::get(&url)?
.json()
.map(|response: Vec<Exam>| response)?;
Ok(exams)
}
/// Returns a list of `Exam`s for a given professor.
///
/// # Arguments
///
/// * `prof` - Professor name
///
/// # Example
///
/// ```
/// use htwdresden::Exam;
///
/// let exams = Exam::for_prof("Rennekamp");
/// ```
pub fn for_prof(prof: &str) -> Result<Vec<Exam>, Error> {
let url = format!("{base}?Prof={prof}", base = BASE_URL, prof = prof);
let exams = reqwest::get(&url)?
.json()
.map(|response: Vec<Exam>| response)?;
Ok(exams)
}
}
|
Go
|
UTF-8
| 703
| 4.34375
| 4
|
[] |
no_license
|
package main
import "fmt"
//输入一个字符串,判断是否是回文
//思路:从中间截断,第一个字符和最后一个比较,依次类推。符合条件,返回true
func Process(str string ) bool {
//Rune 是int32 的别名。用UTF-8 进行编码.rune表示的是字符,byte表示的是字节。(中文字符就3字节)
result := []rune(str)
length := len(result)
for i,_ := range result {
if i == length/2 {
break
}
last := length -i -1
if result[i] != result[last] {
return false
}
}
return true
}
func main() {
var str string
fmt.Scanf("%s",&str)
if Process(str) {
fmt.Printf("%s 是回文",str)
}else {
fmt.Printf("%s 不是回文",str)
}
}
|
Python
|
UTF-8
| 5,425
| 3.328125
| 3
|
[] |
no_license
|
import pygame
import itertools
import random
import tracer
class Board:
def __init__(self, cols, rows, size):
self._cols = cols
self._rows = rows
self._size = size
self._surface = pygame.Surface([self.get_width(), self.get_height()])
self._board = [[(0, 0, 0) for i in range(cols)] for i in range(rows)]
self._colored = [[(0, 0, 0) for i in range(cols)] for i in range(rows)]
self._guessed = [[False for i in range(cols)] for i in range(rows)]
self._queue = []
self._selected = []
self._tracer = tracer.Tracer(self._board)
self._active = False
self._colors = [
(255, 0, 0),
(0, 255, 0),
(0, 0, 255),
(255, 255, 0)
]
for i in range(len(self._colored)):
for j in range(len(self._colored[i])):
self._colored[i][j] = self._colors[random.randint(0, 3)]
self._ticks = 0
def guess(self):
row = random.randint(0, 9)
cell = random.randint(0, 9)
self._guessed[row][cell] = True
self._queue.append((row, cell))
print(self._queue)
def show_combination(self):
for cell in self._queue:
if self._guessed[cell[0]][cell[1]]:
self._board[cell[0]][cell[1]] = self._colored[cell[0]][cell[1]]
self._ticks = 2000
def handle_timer(self, ticks):
if self._ticks > 0:
self._ticks -= ticks
if self._ticks <= 0:
self._ticks = 0
for cell in self._queue:
if self._guessed[cell[0]][cell[1]]:
self._board[cell[0]][cell[1]] = (0, 0, 0)
def get_surface(self):
return self._surface
def render(self):
self._surface.fill((0, 0, 0))
pygame.draw.rect(self._surface, (255, 255, 255),
(0, 0, self.get_width(), self.get_height()), 1)
for i in range(self._cols):
for j in range(self._rows):
self.render_cell((i, j))
return self.get_surface()
def render_cell(self, cell):
my_top = cell[1] * self._size
my_left = cell[0] * self._size
if self.get_item(cell):
color = self.get_item(cell)
pygame.draw.rect(self._surface, (255, 255, 255), (my_left, my_top, self._size, self._size), 1)
if cell == self._active:
pygame.draw.rect(self._surface, color, (my_left + 3, my_top + 3, self._size - 6, self._size - 6))
else:
pygame.draw.rect(self._surface, color, (my_left + 1, my_top + 1, self._size - 2, self._size - 2))
else:
pygame.draw.rect(self._surface, (255, 255, 255), (my_left, my_top, self._size, self._size), 1)
def get_cell(self, x, y):
return x // self._size, y // self._size
def get_item(self, cell):
return self._board[cell[0]][cell[1]]
def click(self, pos):
self._selected.append(self.get_cell(pos[0], pos[1]))
print('Selected: ',self._selected)
if self._selected == self._queue:
self.guess()
self.show_combination()
self._selected.clear()
elif len(self._selected) == len(self._queue):
pygame.quit()
def step(self):
if self._active:
self.step_with_active()
else:
self.step_without_active()
def collapse(self, new_cells):
cells_to_delete = dict()
for cell in new_cells:
series_cells = self.get_series_cells(cell)
for s_cell in series_cells:
cells_to_delete[s_cell] = True
for cell in cells_to_delete:
self.set_item(cell, False)
return len(cells_to_delete)
def get_series_cells(self, cell):
return self.get_horizontal_series_cells(cell) + self.get_vertical_series_cells(cell)
def get_horizontal_series_cells(self, cell):
horizontal_cells = [cell]
i = cell[0] + 1
while i < len(self._board):
next_cell = (i, cell[1])
horizontal_cells.append(next_cell)
i += 1
i = cell[0] - 1
while i >= 0:
next_cell = (i, cell[1])
horizontal_cells.append(next_cell)
i -= 1
return horizontal_cells
def get_vertical_series_cells(self, cell):
vertical_cells = [cell]
i = cell[1] + 1
while i < len(self._board[cell[0]]):
next_cell = (cell[0], i)
vertical_cells.append(next_cell)
i += 1
i = cell[1] - 1
while i >= 0:
next_cell = (cell[0], i)
vertical_cells.append(next_cell)
i -= 1
return vertical_cells
def step_without_active(self):
if self.get_item(self.clicked_cell):
self._active = self.clicked_cell
def get_height(self):
return self._rows * self._size
def get_width(self):
return self._cols * self._size
def in_board(self, pos):
if self._left > pos[0]:
return False
if self._left + self.get_height() < pos[0]:
return False
if self._top > pos[1]:
return False
if self._top + self.get_width() < pos[1]:
return False
return True
def clear_active(self):
self._active = False
|
C++
|
UTF-8
| 844
| 2.78125
| 3
|
[] |
no_license
|
#pragma once
#include <string.h>
#include "fooking.h"
NS_BEGIN
#define BUFF_SIZE 1024
class Buffer
{
public:
Buffer();
Buffer(size_t n);
Buffer(const char *buffer, size_t size);
Buffer(Buffer &buf);
~Buffer();
public:
size_t append(const char *buf, size_t len);
size_t append(const char *buf){ return append(buf, strlen(buf)); }
size_t append(const Buffer &buf){ return append(buf.data(), buf.size()); }
size_t append(const Buffer *buf){ return append(buf->data(), buf->size()); }
size_t size() const{ return nLength; }
bool empty() const{ return nLength == 0; }
char *data() const{ return pBuffer + nOffset;}
void clear(){ nLength = nOffset = 0;}
size_t seek(size_t n);
private:
void resize(size_t n);
private:
char* pBuffer;
size_t nTotal;//总长度
size_t nLength;//数据长度
size_t nOffset;//偏移位置
};
NS_END
|
Python
|
UTF-8
| 1,917
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
import time
from threading import Timer
from logzero import logger
class RemainingTimer(Timer):
_time_until_call = None
_started_at = None
def __init__(self, time_until_call, func_to_be_called):
self._time_until_call = time_until_call
super().__init__(time_until_call, func_to_be_called)
def start_timer(self):
self._started_at = time.time()
self.start()
def elapsed(self):
return time.time() - self._started_at
def remaining(self):
return self._time_until_call - self.elapsed()
class ResettableTimer:
def __init__(self, interval, function, timeout, *args, **kwargs):
self._interval = interval
self._function = function
self._timeout = timeout
self._args = args
self._kwargs = kwargs
self._count = 1
self._timer = Timer(self._interval, self._function, self._args, self._kwargs)
def start(self):
self._timer.start()
def is_alive(self):
return self._timer.is_alive()
def cancel(self):
self._timer.cancel()
def reset(self):
if self._count * self._interval < self._timeout:
logger.info("wildlife-cam: Resetting timer, count: {}, interval: {}, timeout: {}".format(self._count,
self._interval,
self._timeout))
self._timer.cancel()
self._count += 1
self._timer = Timer(self._interval, self._function, self._args, self._kwargs)
self._timer.start()
else:
logger.info("wildlife-cam: Not resetting timer, timeout reached")
def trigger(self):
logger.info("wildlife-cam: timer triggered")
self._timer.cancel()
self._function()
|
Java
|
UTF-8
| 1,753
| 3.359375
| 3
|
[] |
no_license
|
import java.util.*;
public class Main {
public static String bfs (HashMap<String, ArrayList<String>> list, String s, String d) {
Queue<String> queue = new ArrayDeque<>();
HashMap<String,String> prev = new HashMap<>();
queue.offer(s);
prev.put(s, null); //for tracing back
while (!queue.isEmpty()) {
String curr = queue.poll();
if (curr.equals(d))
break;
else if (list.containsKey(curr)) { //find path from s to next
for (String nei : list.get(curr)) {
if (!prev.containsKey(nei)) {
queue.offer(nei);
prev.put(nei, curr); //d, s
}
}
}
}
if (!prev.containsKey(d)) //never arrive
return "";
else {
String ss = "";
while (d != null) {
ss = d.charAt(0) + ss;
d = prev.getOrDefault(d, null); //trace
}
StringBuilder sb = new StringBuilder();
return ss;
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int N = Integer.parseInt(sc.nextLine());
for (int k = 0; k < N; k++) {
sc.nextLine();
String[] st = sc.nextLine().split(" ");
int m = Integer.parseInt(st[0]);
int n = Integer.parseInt(st[1]);
HashMap<String, ArrayList<String>>list = new HashMap<>();
for (int i = 0; i < m; i++) {
st = sc.nextLine().split(" ");
String d1 = st[0];
String d2 = st[1];
//Build path
if (!list.containsKey(d1))
list.put(d1, new ArrayList<>());
if (!list.containsKey(d2))
list.put(d2, new ArrayList<>());
list.get(d1).add(d2);
list.get(d2).add(d1);
}
if (k > 0)
System.out.println();
for (int i = 0; i < n; i++) {
st = sc.nextLine().split(" ");
System.out.println(bfs(list, st[0], st[1]));
}
}
}
}
|
Ruby
|
UTF-8
| 1,598
| 2.921875
| 3
|
[] |
no_license
|
require 'yaml'
require_relative '../classes/book.rb'
module OopLibrary
def self.generateBooksData
books = [
Book.new("Don Quixote", "Miguel de Cervantes"),
Book.new("In Search of Lost Time", "Marcel Proust"),
Book.new("Ulysses", "James Joyce"),
Book.new("The Odyssey", "Homer"),
Book.new("War and Peace", "Leo Tolstoy"),
Book.new("Moby Dick", "Herman Melville"),
Book.new("The Divine Comedy", "Dante Alighieri"),
Book.new("Hamlet", "William Shakespeare"),
Book.new("The Adventures of Huckleberry Finn", "Mark Twain"),
Book.new("The Great Gatsby", "F. Scott Fitzgerald"),
Book.new("The Iliad", "Homer"),
Book.new("One Hundred Years of Solitude", "Gabriel Garcia Marquez"),
Book.new("Madame Bovary", "Gustave Flaubert"),
Book.new("Crime and Punishment", "Fyodor Dostoyevsky"),
Book.new("The Brothers Karamazov", "Fyodor Dostoyevsky"),
Book.new("Pride and Prejudice", "Jane Austen"),
Book.new("The Sound and the Fury", "William Faulkner"),
Book.new("Lolita", "Vladimir Nabokov"),
Book.new("Nineteen Eighty Four", "George Orwell"),
Book.new("Alice's Adventures in Wonderland", "Lewis Carroll"),
Book.new("Harry Potter and the Philosopher’s Stone", "J. K. Rowling"),
Book.new("Harry Potter and the Chamber of Secrets", "J. K. Rowling"),
Book.new("Harry Potter and the Prisoner of Azkaban", "J. K. Rowling"),
Book.new("Harry Potter and the Goblet of Fire", "J. K. Rowling"),
Book.new("Harry Potter and the Order of the Phoenix", "J. K. Rowling"),
Book.new("Harry Potter and the Half-Blood Prince", "J. K. Rowling"),
Book.new("Harry Potter and the Deathly Hallows", "J. K. Rowling"),
Book.new("The Giver", "Lois Lowry")
]
File.new("./data_store/books.yml", "w")
File.open("./data_store/books.yml", "w") {|f| f.write(books.to_yaml) }
end
end
|
C#
|
UTF-8
| 1,977
| 3.34375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Weboo.Prueba
{
public class Anagramas
{
public static int CantidadEnCadena (string cadena)
{
if (cadena.Length <= 1)
return 0;
int c = 0;
for (int i = 0; i < cadena.Length - 1; i++)
{
for (int j = 1; j < cadena.Length - i; j++)
{
for (int k = 1; k < cadena.Length - i; k++)
{
if (i + k > cadena.Length - j)
break;
string a = cadena.Substring(i, j);
string b = cadena.Substring(i + k, j);
if (EsAnagrama(a, b))
c++;
}
}
}
return c;
}
public static bool EsAnagrama(string a, string b)
{
if (a.Length != b.Length)
return false;
bool ToF = false;
bool[] Ra = new bool[a.Length];
bool[] Rb = new bool[b.Length];
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < b.Length; j++)
{
if (Rb[j] == true)
continue;
if (a[i] == b[j])
{
Ra[i] = true;
Rb[j] = true;
break;
}
}
}
for (int k = 0; k < Ra.Length; k++)
{
if (Ra[k] == true)
ToF = true;
else
{
ToF = false;
break;
}
}
return ToF;
}
}
}
|
Rust
|
UTF-8
| 779
| 3.109375
| 3
|
[
"Apache-2.0"
] |
permissive
|
use std::time::Instant;
use std::net::SocketAddr;
/// `Agent` objects represent registered clients connecting to this server instance. Each registered
/// `Agent` must have a unique `agent_id` (generated by the server) and an `app` type associated with it.
pub struct Agent {
/// The unique id of this agent
pub agent_id: String,
/// The remote address of this agent
pub address: SocketAddr,
pub app: String,
/// The time this agent was registered
pub registration_time: Instant
}
impl Agent {
pub fn new(address: SocketAddr, agent_id: String) -> Self {
Agent {
address,
agent_id,
app: String::from("test_app"),
registration_time: Instant::now()
}
}
}
|
Python
|
UTF-8
| 889
| 3.078125
| 3
|
[] |
no_license
|
import sys
TC = int(sys.stdin.readline())
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
for _ in range(TC):
dist = list(map(str, sys.stdin.readline().rstrip()))
go = 0 # 0북1동2남3서
start_x, start_y = 0, 0
trace = [(start_x, start_y)]
for i in dist:
if i == 'F':
start_x += dx[go]
start_y += dy[go]
elif i == 'B':
start_x -= dx[go]
start_y -= dy[go]
elif i == 'L':
if go == 0:
go = 3
else:
go -= 1
elif i == 'R':
if go == 3:
go = 0
else:
go += 1
trace.append((start_x, start_y))
width = max(trace, key=lambda x: x[0])[0] - min(trace, key=lambda x: x[0])[0]
height = max(trace, key=lambda x: x[1])[1] - min(trace, key=lambda x: x[1])[1]
print(width * height)
|
C
|
UTF-8
| 566
| 2.546875
| 3
|
[] |
no_license
|
// The main loop
#include "datastructure.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "readinput.h"
#include "writeoutput.h"
#include "freeKeys.h"
int main()
{
printf("chatbot:Hi! (type \"exit\" to exit)\n>>");
char input[100];
char output[100][20];
Key *header = malloc(sizeof(Key));
loadLibrary(header);
fgets(input,100,stdin);
while(strcmp(input,"exit\n"))
{
int count = modifyInput(output,input);
printf("%s\n",returnReply(output,header,count));
printf(">>");
fgets(input,100,stdin);
}
freeKeys(header);
return 0;
}
|
Python
|
UTF-8
| 9,016
| 3.03125
| 3
|
[] |
no_license
|
import random
import pytest
import inspect
import re
import closures
import os
from closures import *
README_CONTENT_CHECK_FOR = [
'doc_string_validator',
'gen_next_fib_num',
'fn_run_counter',
'add',
'mul',
'div',
'fn_run_counter_1',
'fn_run_counter_2'
]
def function_name_has_cap_letter(module_name):
functions = inspect.getmembers(module_name, inspect.isfunction)
for function in functions:
t = re.findall('([A-Z])', function[0])
if t:
return True
return False
def test_function_names():
assert not function_name_has_cap_letter(closures), "One of your function has a capitalized alphabet!"
def test_readme_exists():
assert os.path.isfile("README.md"), "README.md file missing!"
def test_readme_proper_description():
readme_looks_good = True
f = open("README.md", "r")
content = f.read()
f.close()
for c in README_CONTENT_CHECK_FOR:
if c not in content:
readme_looks_good = False
pass
assert readme_looks_good, "You have not described all the functions/class well in your README.md file"
def test_readme_file_for_formatting():
f = open("README.md", "r")
content = f.read()
f.close()
assert content.count("#") >= 40
def test_indentations():
lines = inspect.getsource(closures)
spaces = re.findall('\n +.', lines)
for space in spaces:
assert len(space) % 4 == 2, "Your script contains misplaced indentations"
assert len(re.sub(r'[^ ]', '', space)) % 4 == 0, "Your code indentation does not follow PEP8 guidelines"
def function_with_less_no_string():
pass
def function_with_less_doc_string():
"""
pass
:return:
"""
pass
def function_with_more_doc_string():
"""
This is a sample function which contains more than fifty characters in its docstring
:return: does not return anything
"""
pass
def test_doc_string_validator_positive():
validator = closures.doc_string_validator(function_with_more_doc_string)
assert validator()
def test_doc_string_validator_negative():
validator = closures.doc_string_validator(function_with_less_doc_string)
assert not validator()
def test_doc_string_validator_none():
validator = closures.doc_string_validator(function_with_less_doc_string)
assert not validator()
def test_doc_string_validator_non_function():
with pytest.raises(TypeError):
var = 5
validator = closures.doc_string_validator(var)
validator()
def test_doc_string_validator_is_closure():
validator = closures.doc_string_validator(function_with_less_doc_string)
assert validator.__closure__
def test_gen_next_fib():
fib = gen_next_fib_num()
val = 0
gen_fib = []
for i in range(5):
val = fib()
gen_fib.append(val)
assert val == 8
assert gen_fib == [1, 2, 3, 5, 8]
def test_gen_next_fib_1():
fib1 = gen_next_fib_num()
fib2 = gen_next_fib_num()
val1 = 0
val2 = 0
for i in range(5):
val1 = fib1()
val2 = fib2()
assert val1 == val2
def test_gen_next_fib_is_closure():
fib = gen_next_fib_num()
assert fib.__closure__
def test_fn_run_counter_1_is_closure():
fn = fn_run_counter_1(add)
assert fn.__closure__
def test_fn_run_counter_1_add_count_pos():
# clear dict as it would have been modified in above test cases
fn_count_dict.clear()
count_add = fn_run_counter_1(add)
r = random.randint(1, 10)
for i in range(r):
count_add(random.random(), random.random())
assert fn_count_dict['add'] == r
def test_fn_run_counter_1_mul_count_pos():
# clear dict as it would have been modified in above test cases
fn_count_dict.clear()
count_mul = fn_run_counter_1(mul)
r = random.randint(1, 10)
for i in range(r):
count_mul(random.random(), random.random())
assert fn_count_dict['mul'] == r
def test_fn_run_counter_1_div_count_pos():
# clear dict as it would have been modified in above test cases
fn_count_dict.clear()
count_div = fn_run_counter_1(div)
r = random.randint(1, 10)
for i in range(r):
count_div(random.randint(1, 10), random.randint(1, 10))
assert fn_count_dict['div'] == r
def test_fn_run_counter_1_add_count_neg():
# clear dict as it would have been modified in above test cases
fn_count_dict.clear()
count_add = fn_run_counter_1(add)
r = random.randint(1, 10)
for i in range(r):
count_add(random.random(), random.random())
assert not fn_count_dict.get('mul') and not fn_count_dict.get('div')
def test_fn_run_counter_1_count_all():
count_add = fn_run_counter_1(add)
count_mul = fn_run_counter_1(mul)
count_div = fn_run_counter_1(div)
# clear dict as it would have been modified in above test cases
fn_count_dict.clear()
r1 = random.randint(1, 10)
for i in range(r1):
count_add(random.random(), random.random())
assert fn_count_dict['add'] == r1
r2 = random.randint(1, 10)
for i in range(r2):
count_mul(random.random(), random.random())
assert fn_count_dict['mul'] == r2
r3 = random.randint(1, 10)
for i in range(r3):
count_div(random.randint(1, 10), random.randint(1, 10))
assert fn_count_dict['div'] == r3
assert fn_count_dict == {'div': r3, 'mul': r2, 'add': r1}
def test_fn_run_counter_1_functionality():
count_add = fn_run_counter_1(add)
count_mul = fn_run_counter_1(mul)
count_div = fn_run_counter_1(div)
random_int = random.randint(1, 10)
assert random_int + random_int == count_add(random_int, random_int)
assert random_int * random_int == count_mul(random_int, random_int)
assert random_int / random_int == count_div(random_int, random_int)
def test_fn_run_counter_1_inputs():
with pytest.raises(TypeError):
count_add = fn_run_counter_1('abc')
count_add(1, 3)
with pytest.raises(TypeError):
count_add = fn_run_counter_1(add)
count_add(1, 'r')
with pytest.raises(ZeroDivisionError):
count_div = fn_run_counter_1(div)
count_div(1, 0)
def test_fn_run_counter_2_is_closure():
fn = fn_run_counter_2(add, {})
assert fn.__closure__
def test_fn_run_counter_2_add_count_pos():
d = {}
count_add = fn_run_counter_2(add, d)
r = random.randint(1, 10)
for i in range(r):
count_add(random.random(), random.random())
assert d['add'] == r
def test_fn_run_counter_2_mul_count_pos():
d = {'mul': 2}
count_mul = fn_run_counter_2(mul, d)
r = random.randint(1, 10)
for i in range(r):
count_mul(random.random(), random.random())
print(d)
assert d['mul'] == r + 2
def test_fn_run_counter_2_div_count_pos():
d = {'add': 3}
count_div = fn_run_counter_2(div, d)
r = random.randint(1, 10)
for i in range(r):
count_div(random.randint(1, 10), random.randint(1, 10))
assert d['div'] == r and d['add'] == 3
def test_fn_run_counter_2_add_count_neg():
d = {}
count_add = fn_run_counter_2(add, d)
r = random.randint(1, 10)
for i in range(r):
count_add(random.random(), random.random())
assert not d.get('mul') and not d.get('div')
def test_fn_run_counter_2_count_all():
d1 = {}
count_add = fn_run_counter_2(add, d1)
count_mul = fn_run_counter_2(mul, d1)
count_div = fn_run_counter_2(div, d1)
r1 = random.randint(1, 10)
for i in range(r1):
count_add(random.random(), random.random())
assert d1['add'] == r1
r2 = random.randint(1, 10)
for i in range(r2):
count_mul(random.random(), random.random())
assert d1['mul'] == r2
r3 = random.randint(1, 10)
for i in range(r3):
count_div(random.randint(1, 10), random.randint(1, 10))
assert d1['div'] == r3
assert d1 == {'div': r3, 'mul': r2, 'add': r1}
d2 = {}
count_add = fn_run_counter_2(add, d2)
count_mul = fn_run_counter_2(mul, d2)
count_div = fn_run_counter_2(div, d2)
r1 = random.randint(11, 20)
for i in range(r1):
count_add(random.random(), random.random())
assert d2['add'] == r1
r2 = random.randint(11, 20)
for i in range(r2):
count_mul(random.random(), random.random())
assert d2['mul'] == r2
r3 = random.randint(11, 20)
for i in range(r3):
count_div(random.randint(1, 10), random.randint(1, 10))
assert d2['div'] == r3
assert d2 == {'div': r3, 'mul': r2, 'add': r1}
assert d1 != d2
def test_fn_run_counter_2_inputs():
with pytest.raises(TypeError):
count_add = fn_run_counter_2('abc', {})
count_add(1, 3)
with pytest.raises(TypeError):
count_add = fn_run_counter_2('abc', 'd')
count_add(1, 3)
with pytest.raises(TypeError):
count_add = fn_run_counter_2(add, {})
count_add(1, 'r')
with pytest.raises(ZeroDivisionError):
count_div = fn_run_counter_2(div, {})
count_div(1, 0)
|
Python
|
UTF-8
| 13,084
| 4.03125
| 4
|
[] |
no_license
|
from time import time
from random import randint
# Сортування за зростанням(яке в кожній функції є першим) та спаданням знаходяться в 1 функції з поверненням змінних до початкових значень
def bubbleSort(arr):
new_arr = arr[:]
compare_count = 0
exchange_сount = 0
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
compare_count += 1
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
exchange_сount += 2
print("Сортування за зростанням: ", arr)
print('Кількість порівнянь послідовності зростання: ', compare_count)
print('Кількість перестановок послідовності зростання: ', exchange_сount)
compare_count = 0
exchange_сount = 0
for i in range(n):
for j in range(0, n - i - 1):
compare_count += 1
if new_arr[j] < new_arr[j + 1]:
new_arr[j], new_arr[j + 1] = new_arr[j + 1], new_arr[j]
exchange_сount += 2
print("Сортування за спаданням: ", new_arr)
print('Кількість порівнянь послідовності спадання:', compare_count)
print('Кількість перестановок послідовності спадання: ', exchange_сount)
def selectionSort(arr):
new_arr = arr[:]
compare_count = 0
exchange_сount = 0
for i in range(len(arr)):
min_idx = i
for j in range(i + 1, len(arr)):
compare_count += 1
if arr[min_idx] > arr[j]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
exchange_сount += 2
print("Сортування за зростанням: ", arr)
print('Кількість порівнянь послідовності зростання: ', compare_count)
print('Кількість перестановок послідовності зростання: ', exchange_сount)
compare_count = 0
exchange_сount = 0
for i in range(len(new_arr)):
min_idx = i
for j in range(i + 1, len(new_arr)):
compare_count += 1
if new_arr[min_idx] < new_arr[j]:
min_idx = j
new_arr[i], new_arr[min_idx] = new_arr[min_idx], new_arr[i]
exchange_сount += 2
print("Сортування за спаданням: ", new_arr)
print('Кількість порівнянь послідовності спадання: ', compare_count)
print('Кількість перестановок послідовності спадання: ', exchange_сount)
def insertionSort(arr):
new_arr = arr[:]
compare_count = 0
exchange_count = 0
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
compare_count += 2
arr[j + 1] = arr[j]
exchange_count += 1
j -= 1
compare_count += 2
arr[j + 1] = key
exchange_count += 2
print("Сортування за зростанням: ", arr)
print('Кількість порівнянь послідовності зростання: ', compare_count)
print('Кількість перестановок послідовності зростання: ', exchange_count)
compare_count = 0
exchange_count = 0
for i in range(1, len(new_arr)):
key = new_arr[i]
j = i - 1
while j >= 0 and key > new_arr[j]:
compare_count += 2
new_arr[j + 1] = new_arr[j]
exchange_count += 1
j -= 1
compare_count += 2
new_arr[j + 1] = key
exchange_count += 2
print("Сортування за спаданням: ", arr)
print('Кількість порівнянь послідовності зростання: ', compare_count)
print('Кількість перестановок послідовності зростання: ', exchange_count)
def cocktailSort(arr):
new_arr = arr[:]
compare_count = 0
exchange_count = 0
n = len(arr)
swapped = True
start = 0
end = n - 1
while swapped:
swapped = False
for i in range(start, end):
compare_count += 1
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
exchange_count += 2
swapped = True
if not swapped:
break
swapped = False
end = end - 1
for i in range(end - 1, start - 1, -1):
compare_count += 1
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
exchange_count += 2
swapped = True
start = start + 1
print("Сортування за зростанням: ", arr)
print('Кількість порівнянь послідовності зростання: ', compare_count)
print('Кількість перестановок послідовності зростання: ', exchange_count)
compare_count = 0
exchange_count = 0
n = len(new_arr)
swapped = True
start = 0
end = n - 1
while swapped:
swapped = False
for i in range(start, end):
compare_count += 1
if new_arr[i] < new_arr[i + 1]:
new_arr[i], new_arr[i + 1] = new_arr[i + 1], arr[i]
exchange_count += 2
swapped = True
if not swapped:
break
swapped = False
end = end - 1
for i in range(end - 1, start - 1, -1):
compare_count += 1
if new_arr[i] < new_arr[i + 1]:
new_arr[i], new_arr[i + 1] = new_arr[i + 1], new_arr[i]
exchange_count += 2
swapped = True
start = start + 1
print("Сортування за спаданням: ", new_arr)
print('Кількість порівнянь послідовності спадання: ', compare_count)
print('Кількість перестановок послідовності спадання: ', exchange_count)
def shellSort(arr):
new_arr = arr[:]
compare_count = 0
exchange_count = 0
n = len(arr)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
compare_count += 2
arr[j] = arr[j - gap]
exchange_count += 1
j -= gap
arr[j] = temp
exchange_count += 2
gap //= 2
print("Сортування за зростанням: ", arr)
print('Кількість порівнянь послідовності зростання: ', compare_count)
print('Кількість перестановок послідовності зростання: ', exchange_count)
compare_count = 0
exchange_count = 0
n = len(arr)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and new_arr[j - gap] < temp:
compare_count += 2
new_arr[j] = new_arr[j - gap]
exchange_count += 1
j -= gap
new_arr[j] = temp
exchange_count += 2
gap //= 2
print("Сортування за спаданням: ", new_arr)
print('Кількість порівнянь послідовності спадання: ', compare_count)
print('Кількість перестановок послідовності спадання: ', exchange_count)
def heapify_growth(arr, n, i, exchange_count, compare_count):
largest = i
l = 2 * i + 1
r = 2 * i + 2
compare_count += 2
if l < n and arr[i] < arr[l]:
largest = l
exchange_count += 1
compare_count += 2
if r < n and arr[largest] < arr[r]:
largest = r
exchange_count += 1
compare_count += 1
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
exchange_count += 2
exchange_count, compare_count = heapify_growth(arr, n, largest, compare_count, exchange_count)
return compare_count, exchange_count
def heapify_decrease(arr, n, i, compare_count, exchange_count):
largest = i
l = 2 * i + 1
r = 2 * i + 2
compare_count += 2
if l < n and arr[i] > arr[l]:
largest = l
exchange_count += 1
compare_count += 2
if r < n and arr[largest] > arr[r]:
largest = r
exchange_count += 1
compare_count += 1
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
exchange_count += 2
exchange_count, compare_count = heapify_decrease(arr, n, largest, compare_count, exchange_count)
return compare_count, exchange_count
def heapSort(arr):
new_arr = arr[:]
n = len(arr)
compare_count = 0
exchange_count = 0
heapify_growth(arr, n, 0, compare_count, exchange_count)
for i in range(n, -1, -1):
exchange_count, compare_count = heapify_growth(arr, n, i, compare_count, exchange_count)
compare_count += 1
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
exchange_count += 2
heapify_growth(arr, i, 0, compare_count, exchange_count)
print("Сортування за зростанням: ", arr)
print('Кількість порівнянь послідовності зростання: ', compare_count)
print('Кількість перестановок послідовності зростання: ', exchange_count)
n = len(new_arr)
compare_count = 0
exchange_count = 0
heapify_decrease(new_arr, n, 0, compare_count, exchange_count)
for i in range(n, -1, -1):
exchange_count, compare_count = heapify_decrease(new_arr, n, i, compare_count, exchange_count)
for i in range(n - 1, 0, -1):
new_arr[i], new_arr[0] = new_arr[0], new_arr[i]
heapify_decrease(new_arr, i, 0, compare_count, exchange_count)
print("Сортування за спаданням: ", new_arr)
print('Кількість порівнянь послідовності спадання: ', compare_count)
print('Кількість перестановок послідовності спадання: ', exchange_count)
# Введення послідовності
# При довжині послідовності у 100 000 значень програма видає лише вихідну послідовність і припиняє роботу,
# тому зменшено до 10000
arr = []
if len(input(
"Чи хочете Ви ввести до 30 значень самостійно?(Інші будуть введені рандомом)"
"\nНатисніть *Enter* для рандомної генерації та введіть що-небудь"
" для введення власних значень: ")) > 0:
while True:
elements_count = int(input("Скільки значень ви хочете ввести: "))
if elements_count <= 30:
arr += ([int(input("Введіть значення: ")) for i in range(elements_count)])
arr += ([randint(0, 10000) for i in range(10000 - elements_count)])
break
else:
print("Кількість має бути до 30!")
else:
arr += ([randint(0, 10000) for i in range(10000)])
print("Вихідна послідовність: \n", arr)
print()
print("***БУЛЬБАШКОВЕ СОРТУВАННЯ***")
print()
tic = time()
bubbleSort(arr[:])
toc = time()
print("Час виконання сортування бульбашкою: ", (toc - tic))
print()
print("***СОРТУВАННЯ ВИБОРОМ***")
print()
tic = time()
selectionSort(arr[:])
toc = time()
print("Час виконання сортування вибором: ", (toc - tic))
print()
print("***СОРТУВАННЯ ВСТАВКАМИ***")
print()
tic = time()
insertionSort(arr[:])
toc = time()
print("Час виконання сортування вставкою: ", (toc - tic))
print()
print("***СОРТУВАННЯ КОКТЕЙЛЕМ***")
print()
tic = time()
cocktailSort(arr[:])
toc = time()
print("Час виконання сортування коктейлем: ", (toc - tic))
print()
print("***СОРТУВАННЯ ШЕЛЛА***")
print()
tic = time()
shellSort(arr[:])
toc = time()
print("Час виконання сортування Шелла: ", (toc - tic))
print()
print("***СОРТУВАННЯ ПІРАМІДОЮ***")
print()
tic = time()
heapSort(arr[:])
toc = time()
print("Час виконання сортування пірамідою: ", (toc - tic))
|
Python
|
UTF-8
| 2,976
| 3.71875
| 4
|
[] |
no_license
|
'''
--- Day 5: Hydrothermal Venture ---
You come across a field of hydrothermal vents on the ocean floor! These vents constantly produce large, opaque clouds, so it would be best to avoid them if possible.
They tend to form in lines; the submarine helpfully produces a list of nearby lines of vents (your puzzle input) for you to review. For example:
0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2
Each line of vents is given as a line segment in the format x1,y1 -> x2,y2 where x1,y1 are the coordinates of one end the line segment and x2,y2 are the coordinates of the other end. These line segments include the points at both ends. In other words:
An entry like 1,1 -> 1,3 covers points 1,1, 1,2, and 1,3.
An entry like 9,7 -> 7,7 covers points 9,7, 8,7, and 7,7.
For now, only consider horizontal and vertical lines: lines where either x1 = x2 or y1 = y2.
So, the horizontal and vertical lines from the above list would produce the following diagram:
.......1..
..1....1..
..1....1..
.......1..
.112111211
..........
..........
..........
..........
222111....
In this diagram, the top left corner is 0,0 and the bottom right corner is 9,9. Each position is shown as the number of lines which cover that point or . if no line covers that point. The top-left pair of 1s, for example, comes from 2,2 -> 2,1; the very bottom row is formed by the overlapping lines 0,9 -> 5,9 and 0,9 -> 2,9.
To avoid the most dangerous areas, you need to determine the number of points where at least two lines overlap. In the above example, this is anywhere in the diagram with a 2 or larger - a total of 5 points.
Consider only horizontal and vertical lines. At how many points do at least two lines overlap?
R: 5698
'''
import time
import tracemalloc
start_time = time.time()
tracemalloc.start()
#####################################################################
import numpy as np
winds = np.zeros(shape=(1000,1000))
def defineWinds(x0, y0, x1, y1):
global winds
if x0 == x1:
for i in range(min(y0, y1), max(y0,y1) + 1):
winds[x0][i] += 1
elif y0 == y1:
for i in range(min(x0, x1), max(x0,x1) + 1):
winds[i][y0] += 1
def getOverlaps():
global winds
values = 0
for i in range(1000):
for j in range(1000):
values += 1 if winds[i][j] > 1 else 0
return values
f = open("winds.txt", "r")
for line in f:
line = line.replace("\n","")
if not line:
continue
parts = line.split(" -> ")
part0 = parts[0].split(",")
part1 = parts[1].split(",")
defineWinds(int(part0[0]), int(part0[1]), int(part1[0]), int(part1[1]))
else:
print(getOverlaps())
#####################################################################
print("--- %s miliseconds ---" % ((time.time() - start_time)*1000))
print("--- %s MB used ---" % (tracemalloc.get_traced_memory()[1]/1000000))
tracemalloc.stop()
|
Python
|
UTF-8
| 1,572
| 3.0625
| 3
|
[] |
no_license
|
import unittest
from fibservice import fibs
import test_const
class FibTestCase(unittest.TestCase):
"""
Unit test cases for fibs function
"""
def setUp(self):
"""
Pass
"""
pass
def tearDown(self):
"""
Pass
"""
pass
def test_normal_number_input(self):
"""
U1-1
"""
self.assertEqual([], fibs(0))
self.assertEqual(test_const.FIB_1, fibs(1))
self.assertEqual(test_const.FIB_2, fibs(2))
self.assertEqual(test_const.FIB_5, fibs(5))
self.assertEqual(test_const.FIB_100, fibs(100))
def test_negative_input(self):
"""
U1-2 to U1-5
"""
self.assertEqual([], fibs(-1))
self.assertEqual([], fibs(1.1))
self.assertEqual([], fibs("1"))
# Upper Boundary
self.assertEqual([], fibs(10001))
self.assertEqual(test_const.FIB_10000_LAST, fibs(10000)[-1])
def test_fib_with_base(self):
"""
U1-6 to U1-7
"""
self.assertEqual(test_const.FIB_2, fibs(2, test_const.FIB_1[:]))
self.assertEqual(test_const.FIB_3, fibs(3, test_const.FIB_1[:]))
self.assertEqual(test_const.FIB_3, fibs(3, test_const.FIB_2[:]))
self.assertEqual(test_const.FIB_5, fibs(5, test_const.FIB_2[:]))
self.assertEqual(test_const.FIB_100, fibs(100, test_const.FIB_5[:]))
# negative input
self.assertEqual(test_const.FIB_5, fibs(5, 5))
self.assertEqual(test_const.FIB_5, fibs(5, "hello"))
|
Java
|
UTF-8
| 457
| 2.296875
| 2
|
[] |
no_license
|
package arc.ecs.injection;
import arc.ecs.*;
import java.lang.reflect.*;
/**
* API used by {@link FieldHandler} to resolve field values in classes eligible for injection.
* @author Snorre E. Brekke
*/
public interface FieldResolver{
/**
* Called after Wo
*/
void initialize(Base base);
/**
* @param target object which should have dependencies injected.
*/
Object resolve(Object target, Class<?> fieldType, Field field);
}
|
Markdown
|
UTF-8
| 2,779
| 2.53125
| 3
|
[] |
no_license
|
---
title: "Tipps und Tricks"
---
# Das kreative schwarze Loch
Kennst du das, wenn du einfach gar keine Ahnung hast was du machen sollst, aber irgendwie Lust hast etwas zu tun?
Im kreativen schwarzen Loch verschwinden alle Ideen und nichts hat so wirklich die Möglichkeit dich zu begeistern um es auch in die Tat umzusetzten. Das kennt fast jeder, würde ich sagen und das ist absolut nichts schlimmes, mir geht es oft genauso. In diesen Fällen kann man sich entweder stundenlang Anregungen suchen oder akzeptieren, dass Langeweile auch mal zum kreativ sein dazu gehört. Das ist dann die beste Gelegenheit etwas mit Freunden zu machen und auf andere Gedanken zu kommen. Oft kommt genau dann die zündende Idee, wenn du nicht damit rechnest und dann macht es umso mehr Spaß sich auch der Umsetzung des Geistesblitzes zu widmen. Gut Ding will Weile haben und manchmal braucht dein Kopf eine Nacht zum Drüberschlafen um dich vollends für etwas überzeugen zu können.
<br></br>
# Ufo's
Als Ufo's oder "UnFertige Objekte" bezeichnet man die lustigen kleinen Projekte, die man voller Begeisterung anfängt und sie dann mangels Durchhaltevermögen, Zeit oder Lust liegen lässt. Man mag sie nicht wegwerfen oder in wiederverwetbare Einzelteile zerlegen, weil die Idee ja eigentlich ganz gut war und wenn es fertig ist, bestimmt auch sehr toll ist. Diese kleinen Dinger sind perfekt um schwarze Löcher zu stopfen. Ich selbst habe eine UFO-Kiste in der sich zum Beispiel angefangene Pullis, Tücher oder Experimente befinden, alles in Tütchen mitsamt Anleitung oder der Ideenskizze versehen, damit ich auch jeder Zeit weiter arbeiten kann. wenn man sich angewöhnt Dinge so wegzupacken, dann kann man sie in Phasen der schwarzen Kreativlöcher hervorholen und einfach weitermachen. Es muss dabei nicht fertig werden, aber irgendwann kommt die Genugtuung, und man beendet doch mal ein UFO. Mein ältestes Ufo ist ein Kreuzstichbild ich bekam es von meiner Mutter als ich noch in der Grundschule war, inzwischen ist das auch schon 20 Jahre alt aber immer Mal wieder hole ich es hervor und irgendwann in den nächsten 30 Jahren werde ich vermutlich auch dieses Projekt beenden.
<br></br>
# Good-2-Know
Hier findest du Links zu Beiträgen in denen ich Tipps gebe und Tricks zeige zu ganz bestimmten Problemstellungen.
- Wie man Plüschstoff mit der Nähmaschine näht: [Kuschelkissen](/monstermassiges-kuschelkissen/)
- Wie man Wolle zum Spinnen vorbereitet: [Spinnvorbereitung](/vlies-kammzug-rolag-fauxlag-punis/)
- Wie man große Mengen Stifte sortiert aufbewahrt: [Stifteaufbewahrung](/stifteaufbewahrung/)
- Wie man eine Spindel abwickelt: [Spindel abwickeln](/spindel-abwickeln/)
- Wie man fertig Gestricktes spannt: [Strickwaren spannen](/fertiggestricktes-spannen/)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.