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
|
---|---|---|---|---|---|---|---|
PHP
|
UTF-8
| 1,459 | 2.625 | 3 |
[] |
no_license
|
<?php
require_once('Inventory.php');
require_once('Order.php');
require_once('OrderQueue.php');
$inventoryObj = new Inventory();
$orderQueue = OrderQueue::loadQueue();
$allOrdersStatus = array();
$allOrdersStatusHumanReadable = '';
foreach($orderQueue as $internalSerializeOrder){
echo "Processing order: ". $internalSerializeOrder . "\n";
$orderObj = Order::createOrderObjFromInternailSerializedOrder($internalSerializeOrder);
$orderStatus['internalOrderID'] = $orderObj->getInternalOrderID();
$orderStatus['sourceID'] = $orderObj->getSourceID();
$orderStatus['sourceOrderID'] = $orderObj->getSourceOrderID();
$orderDetails = $orderObj->getOrderDetails();
$orderStatus['Fulfilled'] = array();
$orderStatus['Backordered'] = array();
foreach($orderDetails as $line){
if ($inventoryObj->isEmptyInventory()){
//echo json_encode($allOrdersStatus);
echo $allOrdersStatusHumanReadable;
exit;
}
$product = $line["Product"];
$quantity = $line["Quantity"];
if ($inventoryObj->fulfill($product, $quantity)){
array_push($orderStatus['Fulfilled'], $line);
}else{
array_push($orderStatus['Backordered'], $line);
}
}
array_push($allOrdersStatus, $orderStatus);
$allOrdersStatusHumanReadable .= json_encode($orderStatus) . "\n";
}
//echo json_encode($allOrdersStatus);
echo $allOrdersStatusHumanReadable;
|
Markdown
|
UTF-8
| 1,030 | 3.125 | 3 |
[] |
no_license
|
# BloomShaderEffect
The bloom filter operates as follows:
firstly for each pixel calculate its luminance based on RGB intensities;
second, extract the highest luminance values from the resulting luminance surface based on a given threshold;
finally, apply Gaussian blur onto thresholded luminance surface and add the resulting image with the original one.
See how brightly the sun starts to shine!
To implement this method the CUDA Toolkit of version 9.1 was used together with Python 3.6 interpreter and PyCUDA 2017.1.1 library.
This implementation is a single Python script that contains both CPU and GPU variants of the bloom algorithm. The script accepts one obligatory argument — the filename of the image to bloom, and six optional arguments: luminance threshold, Gaussian blur standard deviation, number of standard deviation taken for blurring, desired mode (GPU, CPU or both) to run, filename to save resulting image, and an option to show or not the results in a figure.
To view help run: python bloom.py --help
|
C#
|
UTF-8
| 2,611 | 2.515625 | 3 |
[] |
no_license
|
using System;
using System.Linq;
using ControlePonto.DataObject.DTO;
using ControlePonto.DataObject.Entities;
using ControlePonto.Repository.Base;
namespace ControlePonto.Business
{
public class FuncionarioBusiness
{
IRepository<FuncionarioMapping> _repository;
public FuncionarioBusiness(IRepository<FuncionarioMapping> repository)
{
_repository = repository;
}
public Funcionario GetFuncionario(int id)
{
try
{
return _repository.Get(id);
}
catch (Exception ex)
{
throw new Exception("Erro ao Pesquisar Funcionario");
}
}
public IQueryable<Funcionario> ListFuncionarios(long[] setores, long[] departamentos)
{
try
{
return _repository.ListAll().Where(x => (setores.Contains(x.IDSetor))
&& (!x.IDDepartamento.HasValue
|| departamentos.Contains(x.IDDepartamento.Value)))
.Select(x => (Funcionario)x);
}
catch (Exception ex)
{
throw new Exception("Erro ao Pesquisar Funcionario");
}
}
public IQueryable<Funcionario> ListFuncionarios()
{
try
{
return _repository.ListAll().Select(x => (Funcionario)x);
}
catch (Exception ex)
{
throw new Exception("Erro ao Pesquisar Funcionario");
}
}
public void Insert(Funcionario obj)
{
try
{
_repository.InsertCommit(obj);
}
catch (Exception ex)
{
throw new Exception("Erro ao Inserir Funcionario");
}
}
public void Update(Funcionario obj)
{
try
{
_repository.UpdateCommit(obj);
}
catch (Exception ex)
{
throw new Exception("Erro ao Atualizar Funcionario");
}
}
public void Delete(int id)
{
try
{
_repository.DeleteCommit(id);
}
catch (Exception ex)
{
throw new Exception("Erro ao Deletar Funcionario");
}
}
}
}
|
Java
|
UTF-8
| 3,434 | 2.65625 | 3 |
[] |
no_license
|
package TickTackToe;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class OnePcGameController {
private final Replica replica = new Replica();
@FXML
private Label turnLabel;
@FXML
private Button replayBtn;
@FXML
private Button backBtn;
@FXML
private Button cellBtn1;
@FXML
private Button cellBtn2;
@FXML
private Button cellBtn3;
@FXML
private Button cellBtn4;
@FXML
private Button cellBtn5;
@FXML
private Button cellBtn6;
@FXML
private Button cellBtn7;
@FXML
private Button cellBtn8;
@FXML
private Button cellBtn9;
@FXML
public void initialize() {
replayBtn.setText(replica.replay);
backBtn.setText(replica.back);
clickReplay();
}
@FXML
public void updateField() {
if (Game.turn) turnLabel.setText(replica.crossTurn);
else turnLabel.setText(replica.zeroTurn);
cellBtn1.setText(String.valueOf(Game.getCell(1, 1)));
cellBtn2.setText(String.valueOf(Game.getCell(1, 2)));
cellBtn3.setText(String.valueOf(Game.getCell(1, 3)));
cellBtn4.setText(String.valueOf(Game.getCell(2, 1)));
cellBtn5.setText(String.valueOf(Game.getCell(2, 2)));
cellBtn6.setText(String.valueOf(Game.getCell(2, 3)));
cellBtn7.setText(String.valueOf(Game.getCell(3, 1)));
cellBtn8.setText(String.valueOf(Game.getCell(3, 2)));
cellBtn9.setText(String.valueOf(Game.getCell(3, 3)));
if (Game.checkWin('x')) {
turnLabel.setText(replica.crossWin);
Game.lockField = true;
} else if (Game.checkWin('o')) {
turnLabel.setText(replica.zeroWin);
Game.lockField = true;
} else if (Game.checkDraw()) {
turnLabel.setText(replica.draw);
Game.lockField = true;
}
}
public void handleCellBtnAction(int x, int y) {
x -= 1;
y -= 1;
if (Game.lockField) return;
if (Game.field[x][y] != 0) return;
if (Game.turn) Game.field[x][y] = 'x';
else Game.field[x][y] = 'o';
Game.turn = !Game.turn;
}
@FXML
public void clickReplay() {
Game.field = new char[3][3];
Game.lockField = false;
Game.turn = true;
updateField();
}
@FXML
public void handleBackBtnAction(ActionEvent event) throws Exception {
Stage stage;
Parent root;
stage = (Stage) backBtn.getScene().getWindow();
root = FXMLLoader.load(getClass().getResource("menuUI.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
@FXML
public void clickCellBtn1(ActionEvent event) {
handleCellBtnAction(1, 1);
updateField();
}
@FXML
public void clickCellBtn2(ActionEvent event) {
handleCellBtnAction(1, 2);
updateField();
}
@FXML
public void clickCellBtn3(ActionEvent event) {
handleCellBtnAction(1, 3);
updateField();
}
@FXML
public void clickCellBtn4(ActionEvent event) {
handleCellBtnAction(2, 1);
updateField();
}
@FXML
public void clickCellBtn5(ActionEvent event) {
handleCellBtnAction(2, 2);
updateField();
}
@FXML
public void clickCellBtn6(ActionEvent event) {
handleCellBtnAction(2, 3);
updateField();
}
@FXML
public void clickCellBtn7(ActionEvent event) {
handleCellBtnAction(3, 1);
updateField();
}
@FXML
public void clickCellBtn8(ActionEvent event) {
handleCellBtnAction(3, 2);
updateField();
}
@FXML
public void clickCellBtn9(ActionEvent event) {
handleCellBtnAction(3, 3);
updateField();
}
}
|
Java
|
UTF-8
| 7,083 | 2.78125 | 3 |
[] |
no_license
|
package net.nextlogic.airsim.visualizer;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class RelativeField extends JPanel implements KeyListener {
private int panelWidth;
private int panelHeight;
private double boundary;
private double captureL;
public final static double headerAngle = Math.PI/18;
public final static double headerLength = 1;
// current positions and poses
private Point2D pPos = null;
private double pTheta;
private Point2D ePos = null;
private double eTheta;
private List<Line2D> evaderPath = new ArrayList<Line2D>();
private JFrame frame;
private char keyPressed = 0;
/**
* Constructor
*/
public RelativeField(int panelSize, double b, double l) {
panelWidth = panelSize;
panelHeight = panelSize;
boundary = b;
captureL = l;
frame = new JFrame("Playing Field relative to Pursuer state");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(panelWidth, panelHeight);
frame.add(this);
frame.addKeyListener(this);
frame.setVisible(true);
}
public void saveImage(String filename) {
BufferedImage image = new BufferedImage(panelWidth, panelHeight, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
paint(g);
try {
ImageIO.write(image, "png", new File(filename));
} catch (IOException ex) {
System.out.println("Error saving image '" + filename + ".png'");
}
}
public int scaleWorldToPanelWidth(double value) {
return (int) ((panelWidth*(value+boundary))/(2*boundary));
}
public int scaleWorldToPanelHeight(double value) {
return (int) ((panelHeight*(value+boundary))/(2*boundary));
}
public void resetBoundaryForMax() {
double maxBoundary = boundary;
double x, y;
Point2D endpoint;
for (Line2D evaderSegment : evaderPath) {
endpoint = evaderSegment.getP2();
x = Math.abs(endpoint.getX());
y = Math.abs(endpoint.getY());
if (x > maxBoundary) {
maxBoundary = x;
}
if (y > maxBoundary) {
maxBoundary = y;
}
}
boundary = maxBoundary;
}
/**
* Sets evader segments to draw
* @param input List of Point2D
*/
public void setEvaderPath(List<Point2D> input) {
clearEvader();
for (int i = 0; i < input.size() - 1; i++) {
evaderPath.add(new Line2D.Float(input.get(i), input.get(i + 1)));
}
}
public void setPursuerState(Point2D pos, double d) {
pPos = pos;
pTheta = d;
}
public void setEvaderState(Point2D pos, double theta) {
ePos = pos;
eTheta = theta;
}
public void clearAll() {
clearEvader();
}
public void clearEvader() {
evaderPath.clear();
}
/**
* Call this to refresh the window
*/
public void repaint() {
if (frame != null) {
frame.repaint();
}
}
/**
* Overloaded JPanel method
*/
public void paint(Graphics g) {
// Update size in case user has resized window
panelHeight = this.getHeight();
panelWidth = this.getWidth();
// White background
g.setColor(Color.gray);
g.fillRect(0, 0, panelWidth, panelHeight);
int x1, y1, x2, y2;
// Draw evader path
for (Line2D l : evaderPath) {
x1 = scaleWorldToPanelWidth(l.getY1());
y1 = scaleWorldToPanelHeight(l.getX1());
x2 = scaleWorldToPanelWidth(l.getY2());
y2 = scaleWorldToPanelHeight(l.getX2());
g.setColor(Color.blue);
g.drawLine(x1, panelHeight - y1, x2, panelHeight - y2);
}
if (pPos != null) {
g.setColor(Color.red);
drawStateTriangle(pPos, pTheta, g);
// Draw pursuer capture radius
x2 = scaleWorldToPanelWidth(pPos.getY());
y2 = scaleWorldToPanelHeight(pPos.getX());
int rx = (int) ((captureL/(2*boundary)) * panelWidth);
int ry = (int) ((captureL/(2*boundary)) * panelHeight);
g.setColor(Color.orange);
g.drawOval(x2 - rx, panelHeight - (y2 + ry), 2*rx, 2*ry);
}
if (ePos != null) {
g.setColor(Color.blue);
drawStateTriangle(ePos, eTheta, g);
}
}
private void drawStateTriangle(Point2D pos, double pTheta2, Graphics g) {
double x = pos.getY();
double y = pos.getX();
double[] xCoords = {x, x + headerLength*Math.sin(pTheta2 + Math.PI + headerAngle),
x + headerLength*Math.sin(pTheta2 + Math.PI - headerAngle)};
double[] yCoords = {y, y + headerLength*Math.cos(pTheta2 + Math.PI + headerAngle),
y + headerLength*Math.cos(pTheta2 + Math.PI - headerAngle)};
int[] xCoordsPixels = new int[3];
int[] yCoordsPixels = new int[3];
for (int i = 0; i < 3; i++) {
xCoordsPixels[i] = scaleWorldToPanelWidth(xCoords[i]);
yCoordsPixels[i] = panelHeight - scaleWorldToPanelHeight(yCoords[i]);
}
g.drawPolygon(xCoordsPixels, yCoordsPixels, 3);
}
/**
* Waits until user presses a key, then returns the key pressed
* @return key pressed as char
*/
public char waitKey() {
keyPressed = 0;
while (keyPressed == 0) {
// Wait
try {
Thread.sleep(25);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return keyPressed;
}
/**
* Waits until user presses a key, then returns the key pressed
* Will return 0 if timeout occurs
* @param timeout Max time to wait in milliseconds
* @return key pressed as char
*/
public char waitKey(long timeout) {
long currentTime = System.currentTimeMillis();
long startTime = System.currentTimeMillis();
keyPressed = 0;
while (currentTime - startTime < timeout && keyPressed == 0) {
// Wait
try {
Thread.sleep(25);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentTime = System.currentTimeMillis();
}
return keyPressed;
}
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e) {
keyPressed = e.getKeyChar();
}
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
|
Markdown
|
UTF-8
| 617 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
## Hashdot - cozy hash accessors.
Hashdot provides a nicer way to access stuff in your hashes, if you've ever done JavaScript, Lua or countless others you'll be familiar with it.
Note: This is a terrible monkeypatch of the Hash class, I would advise against using it in large production systems, I wrote it because I find it comfortable to write in this style smaller scripts. Consider yourself warned. ¯\_(ツ)_/¯
```ruby
require 'hashdot'
hash = {
:symbol_key => 1,
"string_key" => 2
}
hash.symbol_key #=> 1
hash.string_key #=> 2
```
That's pretty much it.
## Running tests
```bash
$ make test
```
|
Python
|
UTF-8
| 5,489 | 2.953125 | 3 |
[] |
no_license
|
class Token:
def __init__(self, ty, value, line=0, pos=0):
self.type = ty
self.value = value
self.line = line
self.pos = pos
def __str__(self):
return f"Token(type: {self.type}, value: {self.value})"
def __repr__(self):
return f"Token(type: {self.type}, value: {self.value}, line: {self.line}, pos: {self.pos})"
class IntegerToken(Token):
def __init__(self, ty, value, line, pos):
super().__init__(ty, value, line, pos)
def __str__(self):
return f"IntegerToken(type: {self.type}, value: {self.value})"
def __repr__(self):
return f"IntegerToken(type: {self.type}, value: {self.value}, line: {self.line}, pos: {self.pos})"
class OperatorToken(Token):
pass
class PrecedenceToken(OperatorToken):
pass
class FirstPrecedenceToken(PrecedenceToken):
pass
class SecondPrecedenceToken(PrecedenceToken):
pass
class ThirdPrecedenceToken(PrecedenceToken):
pass
class MultiplyToken(FirstPrecedenceToken):
def __init__(self, ty, value, ident, line, pos):
self.ident = ident
super().__init__(ty, value, line, pos)
def __str__(self):
return f"MultiplyToken(type: {self.type}, id: {self.ident})"
def __repr__(self):
return f"MultiplyToken(type: {self.type}, id: {self.ident}, line: {self.line}, pos: {self.pos})"
class DivideToken(FirstPrecedenceToken):
def __init__(self, ty, value, ident, line, pos):
self.ident = ident
super().__init__(ty, value, line, pos)
def __str__(self):
return f"DivideToken(type: {self.type}, id: {self.ident})"
def __repr__(self):
return f"DivideToken(type: {self.type}, id: {self.ident}, line: {self.line}, pos: {self.pos})"
class LParenToken(FirstPrecedenceToken):
def __init__(self, ty, value, ident, line, pos):
self.ident = ident
super().__init__(ty, value, line, pos)
def __str__(self):
return f"LParenToken(type: {self.type}, id: {self.ident})"
def __repr__(self):
return f"LParenToken(type: {self.type}, id: {self.ident}, line: {self.line}, pos: {self.pos})"
class RParenToken(FirstPrecedenceToken):
def __init__(self, ty, value, ident, line, pos):
self.ident = ident
super().__init__(ty, value, line, pos)
def __str__(self):
return f"RParenToken(type: {self.type}, id: {self.ident})"
def __repr__(self):
return f"RParenToken(type: {self.type}, id: {self.ident}, line: {self.line}, pos: {self.pos})"
class AdditionToken(SecondPrecedenceToken):
def __init__(self, ty, value, ident, line, pos):
self.ident = ident
super().__init__(ty, value, line, pos)
def __str__(self):
return f"AdditionToken(type: {self.type}, id: {self.ident})"
def __repr__(self):
return f"AdditionToken(type: {self.type}, id: {self.ident}, line: {self.line}, pos: {self.pos})"
class SubtractToken(SecondPrecedenceToken):
def __init__(self, ty, value, ident, line, pos):
self.ident = ident
super().__init__(ty, value, line, pos)
def __str__(self):
return f"SubtractToken(type: {self.type}, id: {self.ident})"
def __repr__(self):
return f"SubtractToken(type: {self.type}, id: {self.ident}, line: {self.line}, pos: {self.pos})"
class VariableToken(Token):
def __init__(self, ty, value, line=0, pos=0, ident=None):
self.ident = ident
super().__init__(ty, value, line, pos)
def __str__(self):
return f"VariableToken(type: {self.type}, value: {self.value}, id: {self.ident})"
def __repr__(self):
return f"VariableToken(type: {self.type}, value: {self.value}, id: {self.ident} line: {self.line}, pos: {self.pos})"
class AssignmentToken(OperatorToken):
def __init__(self, ty, value, line, pos, ident=None,):
self.ident = ident
super().__init__(ty, value, line, pos)
def __str__(self):
return f"AssignmentToken(type: '{self.type}', operator: {self.ident} )"
def __repr__(self):
return f"AssignmentToken(type: '{self.type}', operator: {self.ident}, line: {self.line}, pos: {self.pos})"
class RelationalToken(ThirdPrecedenceToken):
def __init__(self, ty, value, ident, line, pos):
self.ident = ident
super().__init__(ty, value, line, pos)
def __str__(self):
return f"RelationalToken(type: {self.type}, id: {self.ident})"
def __repr__(self):
return f"RelationalToken(type: {self.type}, id: {self.ident}, line: {self.line}, pos: {self.pos})"
class ConditionalToken(ThirdPrecedenceToken):
pass
class ConditionStatementToken(ConditionalToken):
def __init__(self, ty, value, ident, line, pos):
self.ident = ident
super().__init__(ty, value, line, pos)
def __str__(self):
return f"ConditionStatementToken(type: {self.type}, id: {self.ident})"
def __repr__(self):
return f"ConditionStatementToken(type: {self.type}, id: {self.ident}, line: {self.line}, pos: {self.pos})"
class ConditionalExpressionToken(ConditionalToken):
def __init__(self, ty, value, ident, line, pos):
self.ident = ident
super().__init__(ty, value, line, pos)
def __str__(self):
return f"ConditionalExpressionToken(type: {self.type}, id: {self.ident})"
def __repr__(self):
return f"ConditionalExpressionToken(type: {self.type}, id: {self.ident}, line: {self.line}, pos: {self.pos})"
|
Markdown
|
UTF-8
| 7,536 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
<div align="center">
<img width="200" height="200"
src="https://s3.amazonaws.com/pix.iemoji.com/images/emoji/apple/ios-11/256/notebook.png">
<h1>next-mdx-blog</h1>
<p>Easy blog for next.js</p>
</div
[](https://github.com/prettier/prettier) [](https://circleci.com/gh/hipstersmoothie/next-mdx-blog) [](https://www.npmjs.com/package/next-mdx-blog) [](https://www.npmjs.com/package/next-mdx-blog)
`next-mdx-blog` enables you to easily add a blog to any `next.js` based project.
EXAMPLE: http://hipstersmoothie.com/blog/
CODE: https://github.com/hipstersmoothie/hipstersmoothie
Features:
- MDX Blog
- RSS Feed
- Simple Setup
- Customizable Rendering
## Install
```sh
yarn add next-mdx-blog
```
## Usage
You can store your blog posts anywhere in the `pages` directory. But to keep things tidy I like to keep all blog posts in `pages/blog`.
### Blog Post Format
A post has a `meta` header. The rest of the blog post is MDX. Anything in the `meta` header will be stored.
```mdx
export const meta = {
author: 'Andrew Lisowski',
authorLink: 'https://github.intuit.com/alisowski',
avatar: 'https://avatars2.githubusercontent.com/u/1192452?s=400&v=4'
publishDate: '2018-05-10T12:00:00Z',
title: 'First Post',
}
# Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC
```
### Next Plugin
To get your blog index to build you must use the `next-mdx-blog` plugin in your `next.config.js`. You must also add `@zeit/next-mdx` to parse your blog posts.
Make sure to include `mdx` in your `pageExtensions`.
```js
const withPlugins = require('next-compose-plugins');
// Generates Blog Index
const withBlog = require('next-mdx-blog');
const withMDX = require('@zeit/next-mdx')();
module.exports = withPlugins([withMDX, withBlog], {
pageExtensions: ['js', 'mdx']
});
```
Now you `next` website will generate a `posts.js` with all the metadata about the posts in your project. You can use to build your blog. Anything stored in the `meta` header can be found here.
#### Configuration
You can add a global author by passing a configuration objecting into `next-mdx-blog`.
```js
const withBlog = require('next-mdx-blog');
const withMDX = require('@zeit/next-mdx')();
module.exports = withPlugins([withMDX, withBlog], {
author: 'Andrew Lisowski',
authorLink: 'https://github.intuit.com/alisowski',
avatar: 'https://avatars2.githubusercontent.com/u/1192452?s=400&v=4',
pageExtensions: ['js', 'mdx']
});
```
##### Asset Prefix
If you website is being served out of something other than the root domain you might need to add a prefix to your urls. Such as is the case with github pages.
```js
const withBlog = require('next-mdx-blog');
const withMDX = require('@zeit/next-mdx')();
module.exports = withPlugins([withMDX, withBlog], {
assetPrefix: 'my-github-project',
pageExtensions: ['js', 'mdx']
});
```
### Components
`next-mdx-blog` comes with default `list` and `post` components to build your blog with. You do not need to use these components, they are sensible defaults.
To get these to work you should also include `bulma` in your head somehow
```html
<link
rel="stylesheet"
href="https://jenil.github.io/bulmaswatch/default/bulmaswatch.min.css"
/>
```
#### Usage with next.js
To use the components with next.js you have to flush the styles. This is a bug in styled-jsx component package + next.js. To remedy this manually flush the styles:
```js
import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import flush from 'styled-jsx/server';
import flushBlog from 'next-mdx-blog/dist/components/flush';
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
const { html, head, errorHtml, chunks } = renderPage();
return { html, head, errorHtml, chunks, styles: [flush(), flushBlog()] };
}
render() {}
}
```
#### List
A list of blog posts. Each post displays a small preview of it's content. You must dynamically require the blog posts to get the previews working. This component should be used to display the blog index.
`pages/blog.js`:
```js
import React from 'react';
import Head from 'next/head';
import BlogIndex from 'next-mdx-blog/dist/components/list';
import postsData from '../posts';
// Dynamically import the blog posts
postsData.forEach(post => {
post.file = import('../pages' + post.filePath.replace('pages', ''));
});
const blogPage = ({ posts = postsData }) => (
<div className="blog-index">
<Head>
<title>Blog Posts</title>
</Head>
<BlogIndex posts={posts} stubClassName="content" />
</div>
);
// Before page loads await the dynamic components. prevents blog preview page flash.
blogPage.getInitialProps = async () => {
await Promise.all(
postsData.map(async post => {
post.BlogPost = (await post.file).default;
return post;
})
);
return { posts: [...postsData] };
};
export default blogPage;
```
##### List Props
###### posts
The post index generated by the next plugin.
###### perPage
How many posts to display per page.
###### className
Classname for the root div.
###### stubClassName
Classname for the post stubs.
###### foldHeight
How much of the post should be displayed before the fold.
#### Post
A full blog post. To get your blog content to render inside the blog posts component your must either
1. Modify `_app.js` to render blog content inside appropriate wrapper
```js
import React from 'react';
import App, { Container } from 'next/app';
import Layout from '../components/layout';
import BlogPost from 'next-mdx-blog/dist/components/post';
import posts from '../posts';
// Override the App class to put layout component around the page contents
// https://github.com/zeit/next.js#custom-app
export default class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
const { pathname } = this.props.router;
return (
<Container>
<Layout pathname={pathname} active={active}>
{pathname.includes('blog/') ? (
<BlogPost
post={posts.find(post => post.urlPath === pathname)}
className="content"
>
<Component {...pageProps} />
</BlogPost>
) : (
<Component {...pageProps} />
)}
</Layout>
</Container>
);
}
}
```
2. Wrap blog content inside each `mdx` file. This is more work but you can customize each blog post.
```mdx
export const meta = {
publishDate: '2018-05-10T12:00:00Z',
title: 'First Post',
}
import Post from 'next-mdx-blog/dist/components/post'
<Post post={meta}>
# Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC
</Post>
```
##### Post Props
###### children
Post body.
###### className
Classname to wrap the post in.
###### post
The post meta data to display.
##### \_app.js - Asset Prefix
If you are prefixing your URLS you will need to identify posts by prefixing the pathname.
```js
const prefixUrl = (p) => path.join(assetPrefix, p)
<BlogPost post={posts.find(post => post.urlPath === prefixUrl(pathname))}>
<Component {...pageProps} />
</BlogPost>
```
|
SQL
|
UTF-8
| 843 | 2.953125 | 3 |
[] |
no_license
|
CREATE DATABASE Locadora;
CREATE TABLE Empresas
(
idEmpresa INT PRIMARY KEY IDENTITY
,Nome VARCHAR(200) NOT NULL
);
CREATE TABLE Marcas
(
idMarca INT PRIMARY KEY IDENTITY
,Nome VARCHAR(200) NOT NULL
);
CREATE TABLE Modelos
(
idModelo INT PRIMARY KEY IDENTITY
,idMarca INT FOREIGN KEY REFERENCES Marcas
,Descricao VARCHAR(300)
);
CREATE TABLE Clientes
(
idCliente INT PRIMARY KEY IDENTITY
,Nome VARCHAR(150) NOT NULL
,Cpf VARCHAR(20) NOT NULL
);
CREATE TABLE Veiculos
(
idVeiculo INT PRIMARY KEY IDENTITY
,idEmpresa INT FOREIGN KEY REFERENCES Empresas
,idMarca INT FOREIGN KEY REFERENCES Marcas
,Placa VARCHAR(10)
);
CREATE TABLE Alugueis
(
idAluguel INT PRIMARY KEY IDENTITY
,idVeiculo INT FOREIGN KEY REFERENCES Veiculos
,idCliente INT FOREIGN KEY REFERENCES Clientes
,DataInicio DATETIME
,DataFim DATETIME
);
|
Java
|
UTF-8
| 593 | 1.8125 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sessionbeans;
import entities.Product;
import entities.StoredBasket;
import entities.User;
import javax.ejb.Local;
/**
*
* @author oligavin
*/
@Local
public interface UserBasketBeanLocal {
public void addProduct(User user, Product product);
public void addProduct(User user, Product product, int qty);
public void removeStoredBasket(StoredBasket storedBasket);
}
|
PHP
|
UTF-8
| 1,936 | 2.625 | 3 |
[] |
no_license
|
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "bank".
*
* @property int $id
* @property string $client_id
* @property string $secret_id
* @property string $code
* @property string $response_type
* @property string $authorization_code
* @property string $refresh_token
* @property string $access_token
* @property int $sandbox
*/
class Bank extends \yii\db\ActiveRecord
{
const STATUS_BLOCKED = 'api';
const STATUS_ACTIVE = 'sandbox';
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'bank';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['client_id', 'secret_id', 'code', 'response_type', 'authorization_code', 'refresh_token', 'access_token'], 'string', 'max' => 255],
['sandbox', 'string'],
['sandbox', 'default', 'value' => self::STATUS_ACTIVE],
['sandbox', 'in', 'range' => array_keys(self::getStatusesArray())],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'client_id' => 'Client ID',
'secret_id' => 'Secret ID',
'code' => 'Code',
'response_type' => 'Response Type',
'authorization_code' => 'Authorization Code',
'refresh_token' => 'Refresh Token',
'access_token' => 'Access Token',
'sandbox' => 'Sandbox'
];
}
/**
* {@inheritdoc}
*/
public function getStatusName()
{
return ArrayHelper::getValue(self::getStatusesArray(), $this->status);
}
public static function getStatusesArray()
{
return [
self::STATUS_BLOCKED => Yii::t('app', 'STATUS_REAL_API'),
self::STATUS_ACTIVE => Yii::t('app', 'STATUS_SANDBOX'),
];
}
}
|
Java
|
UTF-8
| 389 | 2.1875 | 2 |
[] |
no_license
|
package com.stress.sub1.sub3;
import com.jtransc.annotation.JTranscKeep;
@JTranscKeep
public class Class3657 {
public static final String static_const_3657_0 = "Hi, my num is 3657 0";
static int static_field_3657_0;
int member_3657_0;
public void method3657()
{
System.out.println(static_const_3657_0);
}
public void method3657_1(int p0, String p1)
{
System.out.println(p1);
}
}
|
Python
|
UTF-8
| 1,229 | 2.71875 | 3 |
[] |
no_license
|
import praw
from credentials import AWS_ACCESS_KEY, AWS_BUCKET_NAME, AWS_SECRET_KEY, CLIENT_ID, CLIENT_SECRET, USER_AGENT
import time
import io
import json
#gain authorization to scan reddit through praw
reddit = praw.Reddit(client_id= CLIENT_ID,
client_secret=CLIENT_SECRET,
user_agent= USER_AGENT)
counter = 0
texts = []
urls = []
for submission in reddit.subreddit('nottheonion').top('day'):
if counter == 3:
break
else:
texts.append(submission.title)
urls.append(submission.url)
counter += 1
titlelist = []
counter = 0
for title in texts:
date = time.strftime("%Y-%m-%dT%H:%M:%S.0Z")
titlelist.append({'uid':counter,'updateDate':date,'titleText':title,'mainText':title, 'redirectionURL': urls[counter]})
counter += 1
#checks for version control
try:
to_unicode = unicode
except NameError:
to_unicode = str
with io.open('data.json', 'w', encoding='utf8') as outfile:
print("Writing to JSON file...")
str_ = json.dumps(titlelist,
indent=4, sort_keys=True,
separators=(',', ': '), ensure_ascii=False)
outfile.write(to_unicode(str_))
print("Write successful. \n")
|
Java
|
UTF-8
| 5,001 | 2 | 2 |
[
"BSD-2-Clause-Views"
] |
permissive
|
/*
* Copyright (c) 2014, Thoughtworks Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
*/
package org.clintonhealthaccess.lmis.app.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import org.clintonhealthaccess.lmis.app.R;
import org.clintonhealthaccess.lmis.app.models.Commodity;
import java.util.ArrayList;
import java.util.List;
public class SearchCommodityAdapter extends ArrayAdapter<Commodity> {
private final int resource;
private final ArrayList<Commodity> suggestions;
private final List<Commodity> items;
private final ArrayList<Commodity> itemsAll;
public SearchCommodityAdapter(Context context, int resource, ArrayList<Commodity> objects) {
super(context, resource, objects);
this.resource = resource;
this.suggestions = new ArrayList<Commodity>();
this.items = objects;
this.itemsAll = (ArrayList<Commodity>) objects.clone();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(resource, parent, false);
TextView textViewCommodityName = (TextView) rowView.findViewById(R.id.textViewCommodityName);
Commodity commodity = getItem(position);
textViewCommodityName.setText(commodity.getName());
return rowView;
}
public List<Commodity> getItemsAll(){
return itemsAll;
}
@Override
public Filter getFilter() {
return nameFilter;
}
Filter nameFilter = new Filter() {
@Override
public String convertResultToString(Object resultValue) {
String str = ((Commodity) (resultValue)).getName();
return str;
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
suggestions.clear();
for (Commodity commodity : itemsAll) {
if (commodity.getName().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
suggestions.add(commodity);
}
}
for (Commodity commodity : itemsAll){
if(commodity.getName().toLowerCase().contains(constraint.toString().toLowerCase())
&& !suggestions.contains(commodity)){
suggestions.add(commodity);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<Commodity> filteredList = (ArrayList<Commodity>) results.values;
if (results != null && results.count > 0) {
clear();
for (Commodity c : filteredList) {
add(c);
}
notifyDataSetChanged();
}
}
};
}
|
Java
|
UTF-8
| 6,943 | 2.359375 | 2 |
[] |
no_license
|
package com.oneside.ui.story;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.oneside.base.adapter.XSimpleAdapter;
import com.oneside.base.view.XRoundImageView;
import com.oneside.R;
import com.oneside.model.beans.CoachPersonalCard;
import com.oneside.utils.LangUtils;
import java.util.List;
/**
* Created by pingfu on 16-9-12.
*/
public class CourseCardAdapter extends XSimpleAdapter<CoachPersonalCard> {
//卡牌未激活状态
private static final int UNACTIVE_STATUE = 0;
//卡牌已激活状态
private static final int ACTIVE_STATUS = 1;
//卡牌未已使用状态
private static final int USED_STATUS = 2;
//卡牌已过期状态
private static final int EXPIRED_STATUS = 3;
private static final int REFUND_STATUS = 9;
public CourseCardAdapter(Context context, List<CoachPersonalCard> items) {
super(context, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = createItemView(R.layout.adapter_course_card);
if (convertView != null) {
holder = new ViewHolder();
holder.llDate = findViewById(convertView, R.id.ll_date);
holder.tvBeginDate = findViewById(convertView, R.id.tv_begin_time);
holder.ivHeader = findViewById(convertView, R.id.iv_header);
holder.tvName = findViewById(convertView, R.id.tv_name);
holder.tvDescription = findViewById(convertView, R.id.tv_desc);
holder.tvPrice = findViewById(convertView, R.id.tv_price);
holder.tvRemainCourses = findViewById(convertView, R.id.tv_remain_times);
holder.llBottom = findViewById(convertView, R.id.ll_bottom);
holder.tvPriceMark = findViewById(convertView, R.id.tv_price_mark);
convertView.setTag(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
setData(holder, getItem(position));
return convertView;
}
private void setData(ViewHolder holder, CoachPersonalCard item) {
if(holder == null || item == null) {
return;
}
holder.llDate.setVisibility(item.isShowDate ? View.VISIBLE : View.GONE);
holder.tvBeginDate.setText(item.date);
if(item.coach != null) {
holder.tvName.setText(item.coach.name);
holder.ivHeader.setImageUri(item.coach.avatar);
} else {
holder.ivHeader.setImageUri("");
holder.tvName.setText("");
}
holder.tvDescription.setText(item.name);
holder.tvPrice.setText(LangUtils.formatPrice(item.price));
holder.tvRemainCourses.setText("剩余课程: " + String.format("%s节", item.remainCourses));
switch (item.status) {
case USED_STATUS:
case EXPIRED_STATUS:
holder.tvName.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.llBottom.setBackgroundColor(mContext.getResources().getColor(R.color.hint_gray));
holder.tvPrice.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.tvBeginDate.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.tvDescription.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.tvPriceMark.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.ivHeader.setGray(true);
holder.tvRemainCourses.setText("课程已终止");
break;
case REFUND_STATUS:
holder.tvName.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.llBottom.setBackgroundColor(mContext.getResources().getColor(R.color.hint_gray));
holder.tvPrice.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.tvBeginDate.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.tvDescription.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.tvPriceMark.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.ivHeader.setGray(true);
break;
case UNACTIVE_STATUE:
holder.tvName.setTextColor(mContext.getResources().getColor(R.color.text_color_gray_black));
holder.llBottom.setBackgroundColor(Color.parseColor("#bd86ef"));
holder.tvPrice.setTextColor(mContext.getResources().getColor(R.color.title_red_color));
holder.tvBeginDate.setTextColor(mContext.getResources().getColor(R.color.text_color_gray_66));
holder.tvDescription.setTextColor(mContext.getResources().getColor(R.color.text_color_gray_66));
holder.tvPriceMark.setTextColor(mContext.getResources().getColor(R.color.title_red_color));
holder.ivHeader.setGray(false);
break;
default:
holder.tvName.setTextColor(mContext.getResources().getColor(R.color.text_color_gray_black));
holder.llBottom.setBackgroundColor(Color.parseColor("#bd86ef"));
holder.tvPrice.setTextColor(mContext.getResources().getColor(R.color.title_red_color));
holder.tvBeginDate.setTextColor(mContext.getResources().getColor(R.color.text_color_gray_66));
holder.tvDescription.setTextColor(mContext.getResources().getColor(R.color.text_color_gray_66));
holder.ivHeader.setGray(false);
break;
}
if(item.remainCourses == 0) {
holder.tvName.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.llBottom.setBackgroundColor(mContext.getResources().getColor(R.color.hint_gray));
holder.tvPrice.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.tvBeginDate.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.tvDescription.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.tvPriceMark.setTextColor(mContext.getResources().getColor(R.color.hint_gray));
holder.ivHeader.setGray(true);
}
}
private static class ViewHolder {
LinearLayout llDate;
TextView tvBeginDate;
XRoundImageView ivHeader;
TextView tvName;
TextView tvDescription;
TextView tvPrice;
TextView tvRemainCourses;
TextView tvPriceMark;
LinearLayout llBottom;
}
}
|
C++
|
UTF-8
| 526 | 3.09375 | 3 |
[] |
no_license
|
#ifndef OBSERVER_H
#define OBSERVER_H
#include <iostream>
using namespace std;
class Observer
{
private:
string observerName;
public:
Observer(string name): observerName(name){}
void update(const string &subject)
{
cout <<"observer: " << observerName << " get new subject: " << subject << endl;
}
};
class WBObserver:public Observer
{
public:
WBObserver(const string& name):Observer(name){}
};
class LJYObserver:public Observer
{
public:
LJYObserver(const string& name):Observer(name){}
};
#endif
|
Java
|
GB18030
| 2,039 | 4.34375 | 4 |
[] |
no_license
|
/*
* Objectеequals
*
* equals:
*
* public boolean equals(Object obj) {
return (this == obj);
}
o1.equals(o2):o1thiso2obj
== ͣȽϵڴַͬtrue֮false
ObjectеequalsȽϵõڴַ
javaequalsƵĿģжĶǷһ
*/
package rObject;
public class Test02 {
public static void main(String[] args){
Object o1 = new Object();
Object o2 = new Object();
//o1.equals()˵ǰַo1˵this==o1
//o1.equals(o2)ʱobj==o2
System.out.println(o1.equals(o2));//false
System.out.println(o1==o2);
Star s1 = new Star(250,"");
Star s2 = new Star(250,"");
System.out.println(s1.equals(s2));//false
System.out.println(s1==s2);
}
}
class Star{
//֤
int id;
//
String name;
Star(int id,String name){
this.id=id;
this.name=name;
}
//ObjectеequalsȽϵڴַ
//ʾҵӦȽ
//ObjectеequalsҲҪд
//涨д
//˴涨֤һ£һ£ͬһ
//s1.equals(s2)
//s1൱thiss2൱objobjObject͵ģObject
//ûidԣobj.idʲˣҪobjǿתΪStar͵
public boolean equals(Object obj){
if (this==obj){
return true;
}
if(obj instanceof Star){//Ƕ̬Ϳǿת
Star s = (Star)obj;
if(this.id==s.id && s.name.equals(name)){
//Ϊs.name.equals()õStringдequals,ʲô͵.õľǸеķ
//ϵ͵ָ͵Ķ̬
return true;
}
}
return false;
}
}
|
Markdown
|
UTF-8
| 2,867 | 2.609375 | 3 |
[] |
no_license
|
---
title: Best Bath Items For Your New-Born Baby
date: 2019-01-04 12:35:00
category: baby shampoo & soap
thumbnail: /img/5.jpg
---

You’ve had the infant and brought him (or her) house in the super cute heading home outfit, now begins the entire year of ‘the firsts’. Initial smile, first coo, first-time sleeping during the night, initial big diaper blowout and initial bath. You wish to ensure that everything with baby’s initial bath is really as easy and exciting as possible.
The ultimate way to do is to be sure you have everything baby needs because of their first bath in fact it is accessible when it's needed. We’ve put jointly a number of the very best bath time items which will make baby and momma content. You can include these products to your child registry or grab anything you’re lacking today.
<!-- more -->

#### Blossoming baby bath mat
This extremely adorable flower fits correct in your sink. It could be tossed in the washer and is certainly easy to maintain shop. This bath mat is a favorite of brand-new moms for several years.
#### Bath kneeler mat
Not merely does baby have to be comfortable during bath period, so does mother! This plush kneeler mat continues on the ground by the tub to create seated with baby more fun. It could be wiped down and dried.
#### Aden and Anais washcloths
These washcloths are created away of cotton muslin and very soft. They endure well and are ideal for washing small baby bottoms and toes.
#### Aden and Anais hooded towel
There is nothing at all cuter a fresh from the tub baby in a hooded towel! Aden and Anais includes a smooth cotton muslin towel that's durable and oh therefore precious.
#### Gentle baby soap
You wish to ensure that you have a soap readily available this soft enough for your lovely babe’s eyes and in addition is free from any harsh chemical substances. California Baby includes a selection of different shampoo and body washes that not merely smell great but are ideal for infants. Aden and Anais is certainly another great soft baby wash substitute for have for bath period.
#### Waterfall rinser
In order to avoid getting water in babies eyes or over their noses, make sure to have this Skip Hop waterfall rinser in your bathroom. The water falls back over baby’s neck instead of right into their face like a traditional cup.
#### Water toys
As baby gets bigger you may want to add in some toys to your bath time routine. Some of my favorites are this light up koi goldfish, mix and match foam pals, and COGS building bath toys. Be sure to also have this Oball toy scoop to easily hold all of babies toys in the tub.
Now that you have all of the best bath time products in tow you are on the right track to making bath time more fun and enjoyable for mom and baby!
|
C++
|
UTF-8
| 1,133 | 2.625 | 3 |
[] |
no_license
|
/********************************************************************************
CodeForces 100030L Make Your Donation Now (二分)
********************************************************************************/
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int INF = 0x7f7f7f7f;
const int N = 1e5 + 10;
int a[N], b[N], n;
ll sum[N];
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d%d", a + i, b + i);
sort(a + 1, a + n + 1);
sort(b + 1, b + n + 1);
sum[n] = a[n];
for (int i = n - 1; i >= 1; i--) sum[i] = sum[i + 1] + a[i];
int ans;
ll ans_sum = 0;
for (int i = 1; i <= 2 * n; i++)
{
int p = i <= n ? a[i] : b[i - n];
int k1 = lower_bound(b + 1, b + n + 1, p) - b - 1;
int k2 = upper_bound(a + 1, a + n + 1, p) - a;
int middle = n - k1 - (n + 1 - k2);
ll s = (ll)middle * p + sum[k2];
if (s > ans_sum)
{
ans_sum = s;
ans = p;
}
else if (s == ans_sum && p < ans)
{
ans = p;
}
}
printf("%d %I64d\n", ans, ans_sum);
return 0;
}
|
Markdown
|
UTF-8
| 1,367 | 2.828125 | 3 |
[] |
no_license
|
+++
title = "茶葉蛋做法"
date = 2019-04-21T23:58:18+08:00
draft = false
summary = ""
# Tags and categories
# For example, use `tags = []` for no tags, or the form `tags = ["A Tag", "Another Tag"]` for one or more tags.
tags = ["recipe","食譜","食"]
categories = ["life"]
# Featured image
# To use, add an image named `featured.jpg/png` to your page's folder.
[image]
# Caption (optional)
caption = ""
# Focal point (optional)
# Options: Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight
focal_point = ""
+++
1. 將雞蛋用清水刷洗乾淨!大家都知道雞蛋是從雞的哪裡生出來的吧,
不刷乾淨,那滷汁就會被污染喔!
2. 準備一個鍋子,將洗淨的雞蛋放入,加水蓋過雞蛋,再加一匙鹽於水中。
開中小火,用常溫水開始煮雞蛋。
3. 水滾後,再煮約5分鐘後,即可用湯匙敲裂雞蛋蛋殼。
加入紅茶包、黑糖、八角、花椒和醬油於鍋中,攪拌均勻。
4. 將鍋子移入電鍋中,外鍋放2杯水,開啟電源。電源跳起後,悶約30分鐘後,
再倒2杯水於外鍋,再煮一次。
(家中有悶燒鍋的,就可以直接放進悶鍋鍋裡,悶約4個小時!)
5. 放涼後,即可連湯汁放入密封的保鮮盒內,放冰箱冷藏保存!
冰冰涼涼的吃,風味也很棒喔!
|
Markdown
|
UTF-8
| 4,367 | 2.890625 | 3 |
[] |
no_license
|
# dcinside-python3api
##### dcinside python3 전용 비공식 API 입니다.
# 사용법
###### 사용전 requests, beautifulsoup4, lxml 꼭 설치해주세요
###### 프로젝트에 dcapi 폴더를 포함해준후 선언해줍니다.
```python
import dcapi
```
#### dcapi.write.post(gall_name,usid,password,title,content)
```python
#비로그인(유동) 상태에서 글을 작성할수있습니다.
post_num = dcapi.write.post("programming","nick","password","subject","content")
print(post_num)
# -> 12345
#성공할시 작성된 글의 글번호가 리턴됩니다.
```
#### dcapi.write.reply(gall_name,usid,password,title,content)
```python
#비로그인(유동) 상태에서 댓글을 달을수있습니다.
result = dcapi.write.reply("programming","938896","nick","pass1234","test")
print(result)
# -> true
#성공할시 true값이 리턴됩니다.
```
#### dcapi.delete.post(gall_name,post_num,password)
```python
#비로그인(유동) 글을 삭제할수있습니다.
result = dcapi.delete.post("programming","99999","1234a")
print(result)
# -> true
#글삭제를 성공할시 true값이 리턴됩니다.
```
#### dcapi.delete.reply(gall_name,post_num,reply_num,password)
```python
#비로그인(유동) 댓글을 삭제할수있습니다.
result = dcapi.delete.reply("programming","993951","3809972","1234")
print(result)
# -> true
# 글삭제 성공시 true 실패시 false값이 리턴됩니다.
```
#### dcapi.read.post(gall_name,post_num)
```python
# 게시글의 고유번호를 이용해 게시글의 정보를 가져옵니다.
data = dcapi.read.post("programming","930329")
print(data)
# -> {'post_num': '930329', 'title': '제목입니다', 'writer': '닉네임', 'time': '2018-11-16 21:28:46', 'ip': '(218.153)', 'view_num': '44', 'comment_num': '0', 'up': '1', 'down': '2', 'gonic_up': '0', 'content': '내용이고요 '}
print(data['post_num'],data['title'],data['content']) # 게시글의 원하는 정보만 사용할수도 있습니다.
# -> 930329 제목입니다 내용이고요
```
#### dcapi.read.reply(gall_name,post_num)
```python
# 해당글의 댓글들을 가져옵니다. (인덱스는 0번부터 시작합니다.)
#data = dcapi.read.reply("programming","931271")
print(data)
# => {0: ['ㅇㅇ(121.134)', 'for문 두개로 해결하고 싶은거야?'], 1: ['ㅇㅇ(121.134)', 'list에 들어가는 순서는 어떻게 하고싶은거야?'], 2: ['ㅇㅇ(121.134)', 'm = len(mat)if m == 0:코드끝n = len(mat[0])if k > min(m,n):코드 끝우선 인풋 정합성 확인'], 3: ['ㅇㅇ(175.211)', 'list에 들어가는 순서 상관 없음. for문
# while문 몇개를 쓰던 상관없음'], 4: ['ㅇㅇ(175.211)', '아니 저렇게 간단하게 끝난다고?!']}
print(data[0])
# 0번째 댓글의 정보들을 가져옵니다.
# =>['ㅇㅇ(121.134)', 'for문 두개로 해결하고 싶은거야?']
print(data[0][0])
# => ㅇㅇ(121.134) 0번째의 작성자 정보만 가져옵니다.
```
#### dcapi.vote.up(gall_name,post_num)
```python
# 해당글을 추천합니다.
res = dcapi.vote.up("programming","12345")
print(res)
# -> true
# 성공시 true값을 반환합니다.
```
#### dcapi.vote.down(gall_name,post_num)
```python
# 해당글을 비추천합니다.
res = dcapi.vote.up("programming","12345")
print(res)
# -> true
# 성공시 true값을 반환합니다.
```
#### dcapi.vote.hit(gall_name,post_num)
```python
# 해당글을 힛추(힛갤추천)합니다.
res = dcapi.vote.up("programming","12345")
print(res)
# -> true
# 성공시 true값을 반환합니다.
```
#### dcapi.read.title(gall_name,start_page,end_page)
```python
# 해당 갤러리 글들의 제목들을 가져옵니다.
data = dcapi.read.title("programming")
print(data)
# -> {1: ['첫번째글제목'],['두번째글제목'], ... }
# 페이지 구간을 적어줄수있습니다.
data = dcapi.read.title("programming",1,5) # 1페이지부터 5페이지까지 제목들을 가져오기
print(data)
# -> {1: ['첫번째글제목'],['두번째글제목'], ... ,2 : ['첫번째글제목'],['두번째글제목'], ... }
print(data[2]) # 다수의 페이지를 가져와 원하는 페이지들의 제목만 볼수도있습니다.
# -> {2 : ['첫번째글제목'],['두번째글제목'], ... }
print(data[2][10]) # 원하는 페이지에 원하는 인덱스의 제목만도 가져올수있습니다.
# -> 10번째글의 제목입니다.
```
|
Python
|
UTF-8
| 307 | 3.015625 | 3 |
[] |
no_license
|
N, M = map(int, input().split())
AB = []
for _ in range(M):
a, b = map(int, input().split())
AB.append((a, b))
AB.sort(key=lambda x: x[1])
# print(AB)
base = AB[0][1]
ans = 1
for ab in AB[1:]:
if ab[0] < base <= ab[1]:
continue
else:
ans += 1
base = ab[1]
print(ans)
|
C++
|
UTF-8
| 2,724 | 2.546875 | 3 |
[] |
no_license
|
/*
* Created by Kuang Peng on 2018/4/8
*/
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <iostream>
#include "tuple.h"
#include "ns3/key-hash.h"
#include "net-device.h"
namespace ns3 {
/*
static int
tuple_lookup(tuple_t* tp, tuple_key_t* key) {
int idx = hash_crc32(key, TP_KEY_SIZE, CRC32) % TP_KEY_CONTAINER_SIZE;
tuple_key_container_t * tc = &tp->key_container[idx];
while (tc->next != NULL) {
tc = tc->next;
if (key_compare((uint8_t*)&tc->key, (uint8_t*)key, TP_KEY_SIZE) == 0) {
return 1;
}
}
return 0;
}
*/
static void
tuple_insert(tuple_t* tp, tuple_key_t* key, tuple_key_container_t* key_pool, int& pool_ptr) {
int idx = hash_crc32(key, TP_KEY_SIZE, CRC32) % TP_KEY_CONTAINER_SIZE;
tuple_key_container_t * tc = &tp->key_container[idx];
while (tc->next != NULL) {
tc = tc->next;
if (key_compare((uint8_t*)&tc->key, (uint8_t*)key, TP_KEY_SIZE) == 0) {
tc->packet_count++;
return;
}
}
if (tc->next == NULL) {
tc->next = &key_pool[pool_ptr++];
tc = tc->next;
tc->key = *key;
tc->packet_count=1;
tc->next = NULL;
tp->distinct_flow_count++;
}
}
static tuple_key_t
tuple_extract_key(Ptr<const Packet> packet, uint16_t protocol, const Address &from, const Address &to) {
tuple_key_t key = {};
memset(key.src_port, 0, 2);
memset(key.dst_port, 0, 2);
uint32_t pkt_size = packet->GetSize();
uint8_t* pkt = new uint8_t[pkt_size];
packet->CopyData(pkt, pkt_size);
memcpy(key.proto, &pkt[9], 1);
memcpy(key.src_addr, &pkt[12], 4);
memcpy(key.dst_addr, &pkt[16], 4);
if (key.proto[0] == 0x06) {//tcp
memcpy(key.src_port, &pkt[20], 2);
memcpy(key.dst_port, &pkt[22], 2);
}
else if (key.proto[0] == 0x11) {//udp
memcpy(key.src_port, &pkt[20], 2);
memcpy(key.dst_port, &pkt[22], 2);
}
delete pkt;
return key;
}
void tuple_count(tuple_t* tp, tuple_key_container_t* key_pool, int& pool_ptr, Ptr<const Packet> packet, uint16_t protocol, const Address &from, const Address &to)
{
tuple_key_t key = tuple_extract_key(packet, protocol, from, to);
tp->packet_count++;
tuple_insert(tp, &key, key_pool, pool_ptr);
}
static uint32_t get_key_value(const uint8_t* key, int size)
{
uint32_t res = 0;
for (int i = 0; i < size; i++)
{
res = (res << 8) + key[i];
}
return res;
}
std::ostream & operator<< (std::ostream&os, const tuple_key_t& tk)
{
os << "src_addr:" << get_key_value(tk.src_addr, 4) << " dst_addr:" << get_key_value(tk.dst_addr, 4);
os << " src_port:" << get_key_value(tk.src_port, 2) << " dst_port:" << get_key_value(tk.dst_port, 2);
os << " protocol:" << get_key_value(tk.proto, 1);
return os;
}
}
|
TypeScript
|
UTF-8
| 1,021 | 2.78125 | 3 |
[] |
no_license
|
export default class User {
public id: number = 0;
public firstname: string = "";
public lastname: string = "";
public email: string = "";
public city: string = "";
public age: number = 0;
public token: string = "";
public tokenExpired: Date = new Date();
public privilegeId: number = 0;
public User() {
this.id = 0;
this.firstname = "";
this.lastname = "";
this.email = "";
this.city = "";
this.age = 0;
this.token = "";
this.tokenExpired = new Date();
this.privilegeId = 0;
}
public setUser(user: User) {
this.id = user.id;
this.firstname = user.firstname;
this.lastname = user.lastname;
this.email = user.email;
this.city = user.city;
this.age = user.age;
this.token = user.token;
this.tokenExpired = user.tokenExpired;
this.privilegeId = user.privilegeId;
}
public clear() {
this.setUser(new User());
}
}
|
JavaScript
|
UTF-8
| 1,107 | 3.421875 | 3 |
[] |
no_license
|
/**
* @author EmmanuelOlaojo
* @since 4/25/16
*/
angular.module("Validator", [])
.factory("validator", [function(){
var validator = {};
validator.hasSpace = function(value){
return value.indexOf(' ') > -1;
};
validator.illegalChars = function(value){
return /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(value);
};
validator.isLength = function(value, min, max){
if(max)
return value.length >= min && value.length <= max;
else
return value.length >= min;
};
validator.validPassword = function(value){
//Checks that there is an uppercase letter, a
//lowercase letter and a number in value
var upper = false;
var lower = false;
var num = false;
for(var i = 0; i < value.length; i++){
if(!isNaN(value[i])) num = true;//if it's a number
else if(value[i] == value[i].toUpperCase()) upper = true;//if it's uppercase
else if(value[i]== value[i].toLowerCase()) lower = true;//if it's lowercase
}
return upper&&lower&#
};
return validator;
}]);
|
Java
|
UTF-8
| 111 | 2.109375 | 2 |
[] |
no_license
|
public class Teacher extends Human {
public void teacher(){
System.out.println("shangke");
}
}
|
Shell
|
UTF-8
| 1,126 | 4.03125 | 4 |
[] |
no_license
|
#!/bin/bash
# Change hostname if needed
current_hostname="$(cat /etc/hostname)"
rasp='raspberrypi'
if [ "$current_hostname" == "$rasp" ]; then
echo '>>>Hostname must be changed for node network'
echo 'Enter Node name, followed by [ENTER]:'
read node_name
while true; do
read -p "To confirm, node_name is ${node_name}? [y/n]" yn
case $yn in
[Yy]* ) break;;
[Nn]* ) echo 'Please re-run the script with the correct input'; exit;;
* ) echo 'Please answer y/n.';;
esac
done
echo ">>>Changing hostname to ${node_name}"
sudo sed -i "s%$current_hostname%$node_name%g" /etc/hostname
sudo sed -i 's%$current_hostname%$node_name%g' /etc/hosts
echo ">>>Committing name to ${node_name} system"
sudo /etc/init.d/hostname.sh
echo ">>>Rebooting system to apply hostname"
sudo reboot
fi
echo ">>>Hostname is ${current_hostname}"
echo '>>>Running system config'
sudo /bin/sh /home/pi/tribes-pi-config/setup/00-system-config.sh
echo '>>>Running bluetooth config'
sudo /bin/sh /home/pi/tribes-pi-config/setup/01-bluetooth-config.sh
|
Markdown
|
UTF-8
| 746 | 3.890625 | 4 |
[] |
no_license
|
## C++ 空类
C++ 空类中包含 6 个默认函数
```c++
class Empty
{
};
```
一个空的 class 在 C++ 编译器处理过后就不再为空,编译器会自动地为我们声明一些 member function。
```c++
class Empty
{
public:
Empty(); // 缺省构造函数
Empty(const Empty&); // 拷贝构造函数
~Empty(); // 析构函数
Empty& operator=(const Empty&); // 赋值运算符
Empty* operator&(); // 取址运算符
const Empty* operator&() const; // 取址运算符 const
};
```
如果只是声明一个空类,不做任何事情的话,编译器会自动为你生成一个默认构造函数、一个拷贝默认构造函数、一个默认拷贝赋值操作符和一个默认析构函数。
|
Swift
|
UTF-8
| 1,003 | 2.625 | 3 |
[] |
no_license
|
//
// IntroViewController.swift
// triviaApp
//
// Created by Michael Berend on 15/03/2018.
// Copyright © 2018 Michael Berend. All rights reserved.
//
import UIKit
class IntroViewController: UIViewController {
// create outlets for the name field and the button
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var startButton: UIButton!
/// hide start button
override func viewDidLoad() {
startButton.isHidden = true
super.viewDidLoad()
}
/// let result screen unwind to start screen (in its original state)
@IBAction func unwindToIntro(unwindSegue: UIStoryboardSegue) {
startButton.isHidden = true
nameField.isHidden = false
nameField.text = ""
}
/// save submitted name, hide field and show start button
@IBAction func nameFieldSumbitted(_ sender: UITextField) {
NameScore.shared.name = nameField.text
nameField.isHidden = true
startButton.isHidden = false
}
}
|
Java
|
UTF-8
| 128 | 1.984375 | 2 |
[] |
no_license
|
package UpCasting;
public class Music {
public static void tune(Instrument i)
{
i.play(Note.MIDLLE_C);
}
}
|
Python
|
UTF-8
| 599 | 4.21875 | 4 |
[] |
no_license
|
import random
randomInt=random.randrange(1,10)
chancecount=0
print("\n\nGUESS A NUMBER BETWEEN 1 TO 9")
print("\nYOU HAVE 5 CHANCES")
while chancecount < 5:
guess=int(input("ENTER YOU GUESS HERE : "))
chancecount=chancecount+1
if guess < randomInt:
print("\nTOO LOW!!! GUESS A NUMBER HIGHER THAN ",guess)
if guess > randomInt:
print("\nTOO HIGH!!! GUESS A NUMBER LOWER THAN ", guess)
if guess == randomInt:
print("\nYOU WIN!!!")
break
if not chancecount < 5:
print("\nYOU LOSE!!! THE NUMBER IS", randomInt)
|
Java
|
UTF-8
| 889 | 1.875 | 2 |
[] |
no_license
|
package com.example.kioteacher.home;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
import com.example.kioteacher.R;
import com.example.kioteacher.qr.ScannerActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton Button_add = (ImageButton)findViewById(R.id.qrImageButton);
Button_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ScannerActivity.class);
startActivity(intent);
}
});
}
}
|
Ruby
|
UTF-8
| 2,354 | 2.609375 | 3 |
[] |
no_license
|
require 'csv'
require 'date'
require 'json'
CONTRIBUTOR_ACTIVE_MONTHS = 3
PROJECT_IDLE_MONTHS = 6
author_last_seen = {}
author_commits = {}
period_commits = 0
period_authors = {}
period_author_first_seen = {}
tag_authors = {}
csv = []
last_date = nil
File.readlines( ARGV[0] || "commits.log" ).each do |line|
date_string, email, name, decorator = line.split( "|" )
date = Date.parse( date_string )
csv << [date, 'project', 'project_started', ''] if last_date.nil?
if last_date && Date.parse(last_date) >> PROJECT_IDLE_MONTHS < date
csv << [Date.parse(last_date) >> PROJECT_IDLE_MONTHS, 'project', 'project_idle', period_authors.to_json, period_commits]
csv << [date, 'project', 'project_active', '']
period_commits = 0
period_authors = {}
end
csv << [date, 'committer', 'started_contributing', name] if !author_last_seen[name]
author_last_seen[name] = date
author_commits[name] ||= 0
author_commits[name] += 1
period_authors[name] ||=0
period_authors[name] += 1
period_author_first_seen[name] ||= date
tag_authors[name] ||= 0
tag_authors[name] += 1
left_authors = []
author_last_seen.each do |author,last_seen|
if last_seen >> CONTRIBUTOR_ACTIVE_MONTHS < date
left_authors << author
csv << [last_seen >> CONTRIBUTOR_ACTIVE_MONTHS, 'committer', 'left_project', author, author_commits[author]]
csv << [period_author_first_seen[author], 'committer', 'activity_between', author, author_last_seen[author], author_commits[author]]
author_commits.delete author
period_author_first_seen.delete author
end
end
left_authors.each { |author| author_last_seen.delete( author ) }
# Add tagging event
if decorator =~ /tag: (.*)/
csv << [date, 'project', 'tag', $1, name, tag_authors.to_json]
tag_authors = {}
end
last_date = date_string
period_commits += 1
end
# Dump out remaining active people
period_author_first_seen.each do |author,first_seen|
csv << [first_seen, 'committer', 'activity_between', author, author_last_seen[author], author_commits[author]]
end
csv << [Date.parse(last_date), 'project', 'last_data', author_commits.to_json, period_commits]
CSV.open( ARGV[1] || "project_timeline.csv", "w" ) do |out|
out << ['date','actor', 'action', 'data', 'commits']
csv.sort { |a,b| a[0] <=> b[0] }.each { |x| out << x }
end
|
C#
|
UTF-8
| 1,898 | 2.984375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Messages;
using Events;
using NServiceBus;
namespace NSBServer
{
public class AddBookCommandHandler : IHandleMessages<AddBookCommand>
{
public IBus Bus { get; set; }
public void Handle(AddBookCommand message)
{
// Write the message to the console to show it has been received.
Console.WriteLine("=============================================");
Console.WriteLine("AddBookCommand received");
Console.WriteLine("\tTitle:\t{0}", message.Title);
Console.WriteLine("\tAuthor:\t{0}", message.Author);
Console.WriteLine("\tCopies:\t{0}", message.Copies);
// Update the data model
// 1. create instance of Book.
Book newBook = new Book()
{
Title=message.Title,
Author=message.Author,
Copies = new List<Copy>()
};
// 2. Add the number of copies specified
for (int i = 1; i <= message.Copies; i++)
{
newBook.Copies.Add(new Copy());
}
// 3. Add the book to the Fake database
FakeDb db = FakeDb.GetInstance();
int newId = db.AddBook(newBook);
// Raise the BookAddedEvent
BookAddedEvent e = new BookAddedEvent()
{
BookId = newId, // the returned Id
Title = message.Title,
Author = message.Author,
Copies = message.Copies
};
Bus.Publish(e);
// Return a success message for the moment.
CommandSatus response = CommandSatus.Successful;
Bus.Return<CommandSatus>(response);
}
}
}
|
Go
|
UTF-8
| 497 | 2.96875 | 3 |
[] |
no_license
|
package main
import (
"fmt"
"testing"
)
func Test_tree2str(t *testing.T) {
tests := []struct {
t *TreeNode
want string
}{
{treeFromLevelOrder(1, 2, 3, 4), "1(2(4))(3)"},
{treeFromLevelOrder(1, 2, 3, NA, 4), "1(2()(4))(3)"},
}
for _, tc := range tests {
tt := tc
testName := fmt.Sprintf(
"%v",
tt.t,
)
t.Run(testName, func(t *testing.T) {
got := tree2str(tt.t)
if got != tt.want {
t.Errorf("tree2str(%v) = %v, want %v", tt.t, got, tt.want)
}
})
}
}
|
Java
|
UTF-8
| 8,491 | 2.265625 | 2 |
[] |
no_license
|
package java.util.stream;
/* JADX ERROR: NullPointerException in pass: ExtractFieldInit
java.lang.NullPointerException
at jadx.core.utils.BlockUtils.isAllBlocksEmpty(BlockUtils.java:546)
at jadx.core.dex.visitors.ExtractFieldInit.getConstructorsList(ExtractFieldInit.java:221)
at jadx.core.dex.visitors.ExtractFieldInit.moveCommonFieldsInit(ExtractFieldInit.java:121)
at jadx.core.dex.visitors.ExtractFieldInit.visit(ExtractFieldInit.java:46)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:12)
at jadx.core.ProcessClass.process(ProcessClass.java:32)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200)
*/
abstract class AbstractSpinedBuffer {
public static final int MAX_CHUNK_POWER = 30;
public static final int MIN_CHUNK_POWER = 4;
public static final int MIN_CHUNK_SIZE = 16;
public static final int MIN_SPINE_SIZE = 8;
protected int elementIndex;
protected final int initialChunkPower;
protected long[] priorElementCount;
protected int spineIndex;
/* JADX ERROR: Method load error
jadx.core.utils.exceptions.DecodeException: Load method exception: bogus opcode: 00e6 in method: java.util.stream.AbstractSpinedBuffer.<init>():void, dex:
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:118)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:248)
at jadx.core.ProcessClass.process(ProcessClass.java:29)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200)
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e6
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1227)
at com.android.dx.io.OpcodeInfo.getName(OpcodeInfo.java:1234)
at jadx.core.dex.instructions.InsnDecoder.decode(InsnDecoder.java:581)
at jadx.core.dex.instructions.InsnDecoder.process(InsnDecoder.java:74)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:104)
... 5 more
*/
protected AbstractSpinedBuffer() {
/*
// Can't load method instructions: Load method exception: bogus opcode: 00e6 in method: java.util.stream.AbstractSpinedBuffer.<init>():void, dex:
*/
throw new UnsupportedOperationException("Method not decompiled: java.util.stream.AbstractSpinedBuffer.<init>():void");
}
/* JADX ERROR: Method load error
jadx.core.utils.exceptions.DecodeException: Load method exception: bogus opcode: 00e9 in method: java.util.stream.AbstractSpinedBuffer.<init>(int):void, dex:
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:118)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:248)
at jadx.core.ProcessClass.process(ProcessClass.java:29)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200)
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e9
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1227)
at com.android.dx.io.OpcodeInfo.getName(OpcodeInfo.java:1234)
at jadx.core.dex.instructions.InsnDecoder.decode(InsnDecoder.java:581)
at jadx.core.dex.instructions.InsnDecoder.process(InsnDecoder.java:74)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:104)
... 5 more
*/
protected AbstractSpinedBuffer(int r1) {
/*
// Can't load method instructions: Load method exception: bogus opcode: 00e9 in method: java.util.stream.AbstractSpinedBuffer.<init>(int):void, dex:
*/
throw new UnsupportedOperationException("Method not decompiled: java.util.stream.AbstractSpinedBuffer.<init>(int):void");
}
/* JADX ERROR: Method load error
jadx.core.utils.exceptions.DecodeException: Load method exception: bogus opcode: 00e3 in method: java.util.stream.AbstractSpinedBuffer.chunkSize(int):int, dex:
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:118)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:248)
at jadx.core.ProcessClass.process(ProcessClass.java:29)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200)
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e3
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1227)
at com.android.dx.io.OpcodeInfo.getName(OpcodeInfo.java:1234)
at jadx.core.dex.instructions.InsnDecoder.decode(InsnDecoder.java:581)
at jadx.core.dex.instructions.InsnDecoder.process(InsnDecoder.java:74)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:104)
... 5 more
*/
protected int chunkSize(int r1) {
/*
// Can't load method instructions: Load method exception: bogus opcode: 00e3 in method: java.util.stream.AbstractSpinedBuffer.chunkSize(int):int, dex:
*/
throw new UnsupportedOperationException("Method not decompiled: java.util.stream.AbstractSpinedBuffer.chunkSize(int):int");
}
public abstract void clear();
/* JADX ERROR: Method load error
jadx.core.utils.exceptions.DecodeException: Load method exception: bogus opcode: 00e3 in method: java.util.stream.AbstractSpinedBuffer.count():long, dex:
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:118)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:248)
at jadx.core.ProcessClass.process(ProcessClass.java:29)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200)
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e3
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1227)
at com.android.dx.io.OpcodeInfo.getName(OpcodeInfo.java:1234)
at jadx.core.dex.instructions.InsnDecoder.decode(InsnDecoder.java:581)
at jadx.core.dex.instructions.InsnDecoder.process(InsnDecoder.java:74)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:104)
... 5 more
*/
public long count() {
/*
// Can't load method instructions: Load method exception: bogus opcode: 00e3 in method: java.util.stream.AbstractSpinedBuffer.count():long, dex:
*/
throw new UnsupportedOperationException("Method not decompiled: java.util.stream.AbstractSpinedBuffer.count():long");
}
/* JADX ERROR: Method load error
jadx.core.utils.exceptions.DecodeException: Load method exception: bogus opcode: 00e3 in method: java.util.stream.AbstractSpinedBuffer.isEmpty():boolean, dex:
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:118)
at jadx.core.dex.nodes.ClassNode.load(ClassNode.java:248)
at jadx.core.ProcessClass.process(ProcessClass.java:29)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:292)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:200)
Caused by: java.lang.IllegalArgumentException: bogus opcode: 00e3
at com.android.dx.io.OpcodeInfo.get(OpcodeInfo.java:1227)
at com.android.dx.io.OpcodeInfo.getName(OpcodeInfo.java:1234)
at jadx.core.dex.instructions.InsnDecoder.decode(InsnDecoder.java:581)
at jadx.core.dex.instructions.InsnDecoder.process(InsnDecoder.java:74)
at jadx.core.dex.nodes.MethodNode.load(MethodNode.java:104)
... 5 more
*/
public boolean isEmpty() {
/*
// Can't load method instructions: Load method exception: bogus opcode: 00e3 in method: java.util.stream.AbstractSpinedBuffer.isEmpty():boolean, dex:
*/
throw new UnsupportedOperationException("Method not decompiled: java.util.stream.AbstractSpinedBuffer.isEmpty():boolean");
}
}
|
Markdown
|
UTF-8
| 1,881 | 3.03125 | 3 |
[] |
no_license
|
---
slug: frankie-and-bennys-pay-for-your-meal-via-the-web
date: 2019-10-20T17:17:06.747Z
title: "Frankie and Bennys: Pay for your meal via the web"
link: ''
tags: [payments]
---
Bất cứ khi nào tôi thấy một nhà hàng nói rằng bạn có thể thanh toán trên điện thoại di động, tôi luôn kiểm tra nó, chủ yếu để tôi có thể nhận ra sự thật rằng bạn cần sử dụng một ứng dụng. Hãy tưởng tượng sự ngạc nhiên của tôi khi mã QR dẫn đến một luồng thanh toán dựa trên web ..... và nó đã hoạt động.
Công việc tuyệt vời Frankie và Benny's!
<figure><img src="/images/2019-10-20-frankie-and-bennys-pay-for-your-meal-via-the-web-0.jpeg" alt="A QR code to a mobile app?"></figure>
<figure><img src="/images/2019-10-20-frankie-and-bennys-pay-for-your-meal-via-the-web-1.jpeg" alt="Pay on mobile QR Code"></figure>
<figure><img src="/images/2019-10-20-frankie-and-bennys-pay-for-your-meal-via-the-web-2.jpeg" alt="Select your restaurant"></figure>
<figure><img src="/images/2019-10-20-frankie-and-bennys-pay-for-your-meal-via-the-web-3.jpeg" alt="Check your bill"></figure>
<figure><img src="/images/2019-10-20-frankie-and-bennys-pay-for-your-meal-via-the-web-4.jpeg" alt="Select your payment"></figure>
Tại thời điểm này, tôi đã chọn Google Pay, nhưng nó không hoạt động (gửi email nội bộ!)
<figure><img src="/images/2019-10-20-frankie-and-bennys-pay-for-your-meal-via-the-web-5.jpeg" alt="Processing"></figure>
<figure><img src="/images/2019-10-20-frankie-and-bennys-pay-for-your-meal-via-the-web-6.jpeg" alt="Payment selected"></figure>
<figure><img src="/images/2019-10-20-frankie-and-bennys-pay-for-your-meal-via-the-web-7.jpeg" alt="Payment processed"></figure>
Công cụ khá tuyệt vời, và đó là khoảng một phút kết thúc.
|
Python
|
UTF-8
| 2,366 | 2.84375 | 3 |
[] |
no_license
|
#!/usr/bin/env python2
import numpy as np
from math import *
import arm_model
import os
import yaml
import logging
def clip(x, minval, maxval):
if x > maxval:
return maxval
elif x < minval:
return minval
else:
return x
CALIBRATION_FILE = 'calibration.yml'
if os.path.exists(CALIBRATION_FILE):
SERVO_LIMITS = yaml.load(open(CALIBRATION_FILE, 'r'))['limits']
logging.info("Loaded servo limits from '%s'" % CALIBRATION_FILE)
else:
logging.warning("No calibration file found at '%s', using (0, 180) for all"
% CALIBRATION_FILE)
SERVO_LIMITS = [{'min': 0, 'max': 180}] * arm_model.NUM_SERVOS
def limit_servos(servos):
for i in range(arm_model.NUM_SERVOS):
l = SERVO_LIMITS[i]
servos[i] = clip(servos[i], l['min'], l['max'])
return servos
# note: this completely ignores the rotational servo in the base
cmd1 = np.array([110.0, 100.0])
Y0 = np.array([-.108, 0])
cmd2 = np.array([150.0, 180.0])
Y1 = np.array([-.21, -0.01])
# hack in a differnt point2
cmd3 = np.array([105, 170])
Y2 = np.array([-0.16, 0.09])
cmd2, Y1 = cmd3, Y2
# each X is an array of two theta values
state0 = arm_model.inverse_2d(Y0)
state1 = arm_model.inverse_2d(Y1)
# TODO: unify this with the arm servo calibration
def calc_base_servo_cmd(theta):
# 60 -> 0
# 155 -> pi/4
m = (155 - 60) / (pi / 4 - 0)
return 60 + m * (theta - 0)
# servo1 of 110 corresponds to theta1 of state0[0]
# servo2 of 100 corresponds to theta2 of state0[1]
# calculate servo values from angle values
def calc_arm_servos(thetas):
m = (cmd2 - cmd1) / (state1 - state0)
# print(m)
cmd = cmd1 + m * (thetas - state0)
return cmd
def draw_calibration_curve():
import matplotlib.pyplot as plt
plt.ylabel('Servo cmd')
plt.xlabel('Angle')
t0 = np.linspace(0, 2 * pi, num=20)
t1 = np.linspace(0, 2 * pi, num=20)
plt.plot(
t0, [calc_arm_servos([t, 0])[0] for t in t0],
color='b',
label='Servo 1')
plt.plot(
t1, [calc_arm_servos([0, t])[1] for t in t1],
color='g',
label='Servo 2')
plt.legend()
plt.title('Arm angle -> servo mapping')
# plt.plot(t1)
plt.show()
if __name__ == '__main__':
print('state0: %s' % str(state0))
print('state1: %s' % str(state1))
draw_calibration_curve()
|
PHP
|
UTF-8
| 472 | 2.953125 | 3 |
[] |
no_license
|
<?php
namespace AppBundle\Entity;
/**
* Dummytext
*
*/
class Dummytext
{
/**
* @var string
*
*/
private $text;
/**
* Set text
*
* @param string $text
*
* @return Dummytext
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
/**
* Get text
*
* @return string
*/
public function getText()
{
return $this->text;
}
}
|
PHP
|
UTF-8
| 6,623 | 2.578125 | 3 |
[] |
no_license
|
<?php
class generar_control {
function generar($factura, $nit_cli, $fecha, $monto, $dosificacion, $autorizacion) {//
$monto= round($monto);
$fecha=str_replace('/', '', $fecha);
$digitos = $this->paso1($factura, $nit_cli, $fecha, $monto);
$cad_concat = $this->paso2($factura, $nit_cli, $fecha, $monto, $dosificacion, $autorizacion, $digitos);
$arc4 = $this->paso3($digitos, $cad_concat, $dosificacion);
$total = $this->paso4($arc4, $digitos);
$mensaje = $this->big_base_convert($total);
$cc=$this->allegedrc4($mensaje, $dosificacion . $digitos);
$i=0;
$codigo="";
while ($i< strlen($cc)){
if($i!=0){
$codigo.='-';
}
$codigo.=$cc[$i].$cc[$i+1];
$i+=2;
}
return $codigo;
}
function paso1(&$factura, &$nit_cli, &$fecha, &$monto) {
$vhf = new algverhoeff();
$factura = $vhf->verhoeff_add_recursive($factura, 2);
$nit_cli = $vhf->verhoeff_add_recursive($nit_cli, 2);
$fecha = $vhf->verhoeff_add_recursive($fecha, 2);
$monto = $vhf->verhoeff_add_recursive($monto, 2);
// $suma = bcadd(bcadd(bcadd($factura, $nit_cli), $fecha), $monto);
$suma = $factura + $nit_cli + $fecha + $monto;
$suma = $vhf->verhoeff_add_recursive($suma, 5);
$digitos = "" . substr($suma, -5);
return $digitos;
}
function paso2($factura, $nit_cli, $fecha, $monto, $dosificacion, $autorizacion, $digitos) {
$nd = array($digitos[0] + 1, $digitos[1] + 1, $digitos[2] + 1, $digitos[3] + 1, $digitos[4] + 1);
$cad = array(
'1' => substr($dosificacion, 0, $nd[0]),
'2' => substr($dosificacion, $nd[0], $nd[1]),
'3' => substr($dosificacion, $nd[0] + $nd[1], $nd[2]),
'4' => substr($dosificacion, $nd[0] + $nd[1] + $nd[2], $nd[3]),
'5' => substr($dosificacion, $nd[0] + $nd[1] + $nd[2] + $nd[3], $nd[4]),
);
$objeto = array(
'autorizacion' => $autorizacion . $cad[1],
'factura' => $factura . $cad[2],
'nit_cli' => $nit_cli . $cad[3],
'fecha' => $fecha . $cad[4],
'monto' => $monto . $cad[5]
);
return implode('', $objeto);
}
function paso3($digitos, $cad_concat, $dosificacion) {
$allegedrc4= $this->allegedrc4($cad_concat, $dosificacion.$digitos);
return $allegedrc4;
}
function paso4($arc4,$digitos){
$suma_total = 0;
$sumas = array_fill(0, 5, 0);
$strlen_arc4 = strlen($arc4);
for ($i = 0; $i < $strlen_arc4; $i++) {
$x = ord($arc4[$i]);
$sumas[$i % 5] += $x;
$suma_total += $x;
}
$total = "0";
foreach ($sumas as $i => $sp) {
$total += (int)(($suma_total*$sp)/($digitos[$i]+1));
}
return $total;
}
function allegedrc4($mensaje, $llaverc4) {
$state = array();
$x = 0;
$y = 0;
$index1 = 0;
$index2 = 0;
$nmen = 0;
$i = 0;
$cifrado = "";
$state = range(0, 255);
$strlen_llave = strlen($llaverc4);
$strlen_mensaje = strlen($mensaje);
for ($i = 0; $i < 256; $i++) {
$index2 = ( ord($llaverc4[$index1]) + $state[$i] + $index2 ) % 256;
list($state[$i], $state[$index2]) = array($state[$index2], $state[$i]);
$index1 = ($index1 + 1) % $strlen_llave;
}
for ($i = 0; $i < $strlen_mensaje; $i++) {
$x = ($x + 1) % 256;
$y = ($state[$x] + $y) % 256;
list($state[$x], $state[$y]) = array($state[$y], $state[$x]);
// ^ = XOR function
$nmen = ord($mensaje[$i]) ^ $state[( $state[$x] + $state[$y] ) % 256];
$cifrado .= substr("0" . $this->big_base_convert($nmen, "16"), -2);
}
return $cifrado;
}
private function big_base_convert($numero, $base = "64") {
$dic = array(
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'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', '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', '+', '/');
$cociente = "1";
$resto = "";
$palabra = "";
$c = 0;
while ($cociente > 0) {
$cociente = intval($numero / $base);
$resto = $numero % $base;
$palabra = $dic[0 + $resto] . $palabra;
$numero = "" . $cociente;
}
// while (bccomp($cociente, "0")) {
// $cociente = bcdiv($numero, $base);
// $resto = bcmod($numero, $base);
// $palabra = $dic[0 + $resto] . $palabra;
// $numero = "" . $cociente;
// }
return $palabra;
}
}
class algverhoeff {
var $table_d = array(
array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
array(1, 2, 3, 4, 0, 6, 7, 8, 9, 5),
array(2, 3, 4, 0, 1, 7, 8, 9, 5, 6),
array(3, 4, 0, 1, 2, 8, 9, 5, 6, 7),
array(4, 0, 1, 2, 3, 9, 5, 6, 7, 8),
array(5, 9, 8, 7, 6, 0, 4, 3, 2, 1),
array(6, 5, 9, 8, 7, 1, 0, 4, 3, 2),
array(7, 6, 5, 9, 8, 2, 1, 0, 4, 3),
array(8, 7, 6, 5, 9, 3, 2, 1, 0, 4),
array(9, 8, 7, 6, 5, 4, 3, 2, 1, 0),
);
var $table_p = array(
array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
array(1, 5, 7, 6, 2, 8, 3, 0, 9, 4),
array(5, 8, 0, 3, 7, 9, 6, 1, 4, 2),
array(8, 9, 1, 6, 0, 4, 3, 5, 2, 7),
array(9, 4, 5, 3, 1, 2, 6, 8, 7, 0),
array(4, 2, 8, 6, 5, 7, 3, 9, 0, 1),
array(2, 7, 9, 3, 8, 0, 6, 4, 1, 5),
array(7, 0, 4, 6, 9, 1, 3, 2, 5, 8),
);
var $table_inv = array(0, 4, 3, 2, 1, 5, 6, 7, 8, 9);
function calcsum($number) {
$c = 0;
$n = strrev($number);
$len = strlen($n);
for ($i = 0; $i < $len; $i++) {
$c = $this->table_d[$c][$this->table_p[($i + 1) % 8][$n[$i]]];
}
return $this->table_inv[$c];
}
function verhoeff_add_recursive($number, $digits) {
$temp = $number;
while ($digits > 0) {
$temp .= $this->calcsum($temp);
$digits--;
}
return $temp;
}
}
class algbase64 {
}
?>
|
Java
|
UTF-8
| 2,259 | 1.875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* SETTE - Symbolic Execution based Test Tool Evaluator
*
* SETTE is a tool to help the evaluation and comparison of symbolic execution based test input
* generator tools.
*
* Budapest University of Technology and Economics (BME)
*
* Authors: Lajos Cseppentő <lajos.cseppento@inf.mit.bme.hu>, Zoltán Micskei <micskeiz@mit.bme.hu>
*
* Copyright 2014-2016
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package hu.bme.mit.sette.application;
/**
* Tasks (commands) for the SETTE.
*/
public enum ApplicationTask {
EXIT(false, false, false),
GENERATOR(true, true, true),
RUNNER(true, true, true),
PARSER(true, true, true),
TEST_GENERATOR(true, true, true),
TEST_RUNNER(true, true, true),
SNIPPET_BROWSER(true, false, false),
EXPORT_CSV(true, true, true),
EXPORT_CSV_BATCH(true, false, true), // tag is a comma-separated list for this task
RUNNER_PROJECT_BROWSER(false, false, false),
PARSER_EVOSUITE_MUTATION(true, true, true);
private final boolean requiresSnippetProject;
private final boolean requiresTool;
private final boolean requiresRunnerProjectTag;
private ApplicationTask(boolean requiresSnippetProject, boolean requiresTool,
boolean requiresRunnerProjectTag) {
this.requiresSnippetProject = requiresSnippetProject;
this.requiresTool = requiresTool;
this.requiresRunnerProjectTag = requiresRunnerProjectTag;
}
public boolean requiresSnippetProject() {
return requiresSnippetProject;
}
public boolean requiresTool() {
return requiresTool;
}
public boolean requiresRunnerProjectTag() {
return requiresRunnerProjectTag;
}
@Override
public String toString() {
return name().replace('_', '-').toLowerCase();
}
}
|
Rust
|
UTF-8
| 2,450 | 2.578125 | 3 |
[] |
no_license
|
extern crate rustmojo as this;
use std::fs::File;
use this::acqua::acquamodel::Comparison;
use this::acqua::acquamodel::Node;
use this::acqua::acquamodel::NoNumberHandling;
use this::mojoreader::MojoInformation;
use this::mojoreader::MojoReader;
fn treeprint(node: &Node) {
println!("Tree:");
treeprint_level(0, node);
}
fn print_indent(i: usize) {
for _ in 0..i {
print!(" ");
}
}
fn treeprint_level(indent: usize, node: &Node) {
print_indent(indent);
match node {
Node::ValueNode(value) => {
println!("{}", value)
},
Node::DecisionNode(decision) => {
let col_name = format!("Col{}", decision.column.get_column_no());
let mut ifline = String::new();
match decision.condition.nan {
NoNumberHandling::None => {},
NoNumberHandling::AsTrue => ifline.push_str(&format!("{}.isNAN() || ", col_name)),
NoNumberHandling::AsFalse => ifline.push_str(&format!("!{}.isNAN() && ", col_name)),
}
match decision.condition.comparison {
Comparison::None => {},
Comparison::Numeric(f) => {
ifline.push_str(&col_name);
if decision.condition.invert {
ifline.push_str(&format!(" >= {}", f));
} else {
ifline.push_str(&format!(" < {}", f));
}
},
Comparison::Bitset(_) => {
if decision.condition.invert {
ifline.push('!');
}
ifline.push_str(&format!("set(...).contains({})", col_name));
},
};
println!("if {}", ifline);
print_indent(indent);
println!("then");
treeprint_level(indent + 1, &decision.do_then);
print_indent(indent);
println!("else");
treeprint_level(indent + 1, &decision.do_else);
},
}
}
fn main() {
let mut file= File::open("data/gbm_v1.00_names.mojo/trees/t00_000.bin").unwrap();
let size = file.metadata().unwrap().len();
println!("file size is {}", size);
let mojo_reader = MojoReader::new(MojoInformation::new());
let root = mojo_reader.read_tree_from_file(&mut file).expect("ERROR");
println!("byte count is {}", size);
treeprint(&root);
}
|
Java
|
UTF-8
| 5,712 | 2.015625 | 2 |
[] |
no_license
|
package com.miracas.espresso.fragments.expresso;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.miracas.R;
import com.miracas.espresso.adapters.ExpressoBrewingAdapter;
import com.miracas.espresso.client.base.ClientCodes;
import com.miracas.espresso.client.espresso.GetBrewingProductsClient;
import com.miracas.espresso.client.responses.BrewedItem;
import com.miracas.espresso.client.responses.Product;
import com.miracas.espresso.design.IOnRequestCompleted;
import com.miracas.espresso.layouts.CustomLinearLayoutManager;
import com.miracas.espresso.utils.SharedStorage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
public class MyExpressoTabBrewing extends Fragment implements IOnRequestCompleted {
private ExpressoBrewingAdapter adapter;
private RecyclerView listView;
private List<BrewedItem> items;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_layout_my_expresso_brewing, container, false);
items = new ArrayList<>();
adapter = new ExpressoBrewingAdapter(getContext(), items);
listView = view.findViewById(R.id.products_list);
CustomLinearLayoutManager customLinearLayoutManager = new CustomLinearLayoutManager(getContext());
listView.setLayoutManager(customLinearLayoutManager);
listView.setAdapter(adapter);
SharedStorage storage = new SharedStorage(getActivity());
String userID = storage.getValue(getActivity().getString(R.string.shared_storage_user_id));
GetBrewingProductsClient client = new GetBrewingProductsClient(this, userID);
client.execute();
Handler timer = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
int firstPosition = customLinearLayoutManager.findFirstVisibleItemPosition();
int lastPosition = customLinearLayoutManager.findLastVisibleItemPosition();
if (items != null && !items.isEmpty() && firstPosition >= 0) {
long now = System.currentTimeMillis();
for (int i = 0; i <= lastPosition - firstPosition; ++i) {
View child = listView.getChildAt(i);
BrewedItem item = items.get(i + firstPosition);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH);
long difference = 10000;
try {
Calendar calendar = Calendar.getInstance();
calendar.setTime(format.parse(item.created_at));
calendar.add(Calendar.DATE, 3);
long end = calendar.getTime().getTime();
difference = end - now;
} catch (ParseException ignored) {
}
try {
TextView timerHours = child.findViewById(R.id.timerHours);
TextView timerMinutes = child.findViewById(R.id.timerMinutes);
TextView timerSeconds = child.findViewById(R.id.timerSeconds);
if (difference > 0) {
long seconds = difference / 1000;
long minutes = (seconds / 60) % 60;
long hours = (seconds / 60) / 60;
timerSeconds.setText(String.valueOf(seconds % 60));
timerMinutes.setText(String.valueOf(minutes));
timerHours.setText(String.valueOf(hours));
} else {
timerSeconds.setText("0");
timerMinutes.setText("0");
timerHours.setText("0");
}
} catch (Exception ignored) {
}
}
}
timer.postDelayed(this, 1000);
}
};
timer.postDelayed(runnable, 1000);
return view;
}
@Override
public void onRequestComplete(int clientCode, Object response) {
View view = getView();
if (clientCode == ClientCodes.GET_BREWING_ITEMS && view != null) {
List<BrewedItem> itemsResponse = (List<BrewedItem>) response;
if (itemsResponse != null) {
for (Iterator<BrewedItem> iterator = itemsResponse.iterator(); iterator.hasNext();) {
BrewedItem item = iterator.next();
if (item.product.img_url == null || item.product.img_url.isEmpty())
iterator.remove();
}
if (itemsResponse.isEmpty()) {
view.findViewById(R.id.emptyMessage).setVisibility(View.VISIBLE);
} else {
items.addAll(itemsResponse);
adapter.notifyDataSetChanged();
}
}
view.findViewById(R.id.loading).setVisibility(View.GONE);
}
}
}
|
JavaScript
|
UTF-8
| 309 | 2.5625 | 3 |
[] |
no_license
|
import { useTips } from "./TipDataProvider.js";
import Tip from "./Tip.js";
const TipList = () => {
const contentElement = document.querySelector(".tipList")
const tips = useTips()
for (const tipString of tips) {
contentElement.innerHTML += Tip(tipString)
}
}
export default TipList
|
Python
|
UTF-8
| 1,061 | 2.796875 | 3 |
[] |
no_license
|
import csv
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def main():
return render_template('main.html', data={})
@app.route('/data')
def data():
data = {"timestamps": [], "hr": [], "br": [], "temp": [], "valence": [], "stress": [], "incident": []}
with open('csv/data.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for row in spamreader:
try:
int(row[0])
except:
continue
data["timestamps"].append(row[0])
data["hr"].append(row[1])
data["br"].append(row[2])
data["temp"].append(row[3])
data["valence"].append(row[4])
data["stress"].append(row[5])
data["incident"].append(row[6])
data["max_hr"] = max(data["hr"])
data["min_hr"] = min(data["hr"])
data["max_br"] = max(data["br"])
data["min_br"] = min(data["br"])
data["max_temp"] = max(data["temp"])
data["min_temp"] = min(data["temp"])
return data
|
Markdown
|
UTF-8
| 1,268 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
---
layout: page
title: About
permalink: /about/
---
### Hello world!
My name is Cristian Gutu and I am a **Software Engineer** on **Prudential’s Messaging Team**.
Primarily I work on designing and implementing data pipelines supporting the flow of millions of events between producer and consumer systems across the organization. By leveraging a micro-services based pub-sub architecture, each pipeline is designed to move away from traditional monolithic point-to-point integrations to a more resilient microservices based event streaming pattern enabling real-time analytics, event based notifications, and data feed subscriptions.
I have experience with **Java**, **Python**, **Apache Kafka**, **Angular 13**, **Docker**, **Jenkins** and **Amazon Web Services** (AWS).
### Skills & Certifications
**Back-end:** Java, Python
**Front-end:** Angular 13, TypeScript, JavaScript, HTML, CSS
**Big Data and Stream Processing:** Apache Kafka, Kafka Streams, Apache Avro
**Data:** SQL, NoSQL (MySQL, DynamoDB)
**Technologies:** AWS, Spring Boot, Docker
**Certifications:** AWS Certified Developer (DVA-CO1)
### More Information
See my [LinkedIn](https://www.linkedin.com/in/gutucristian/) profile to learn more about me.
### Contact me
[gutucristian27@gmail.com](mailto:gutucristian27@gmail.com)
|
JavaScript
|
UTF-8
| 1,087 | 2.65625 | 3 |
[] |
no_license
|
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var mysql = require('mysql');
//start server
app.listen(port);
console.log('Server started, at http://localhost'+ port);
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '13748abc',
database: 'characters'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
app.get('/cast', function(req, res) {
connection.query('SELECT * FROM seinfeld', function(err, result) {
if(err){ console.log(err);}
else{
var html = '<h1> Characters <h1>'
for(var i = 0; i < result.length; i++)
{
html += '<div style="background-color:blue; color:red; margin-left:30px;">';
html += '<ul>';
html += '<li> ' + result[i].id + '</li>';
html += '<li> ' + result[i].name + '</li>';
html += '</ul>';
html += '<br />';
html += '</div>';
}
res.send(html);
}
});
});
|
Python
|
UTF-8
| 5,777 | 2.640625 | 3 |
[] |
no_license
|
import smtplib
import html2text
import os
import pyodbc
import __main__ as main
from simple_salesforce import Salesforce
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
config = {}
execfile('/etc/py.conf', config) # contains all the passwords, etc
def testconfig():
print config['sqluser_qas']
def alert(toAddr, subject, body, fromAddr = 'KNG Automation <automation@kng.com>', showOriginProgram = True):
"""Quick send email method.
In a lot of programs, if something goes bad, I just want to fire off a quick email. It's hard to remember all of the function arguments
The downside is I forget which program is send which email, so I add the program's name at the bottom
"""
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = fromAddr
msg['To'] = toAddr
if showOriginProgram:
body += '<p><small>Sent from <b>' + main.__file__ + '</b></small></p>'
part1 = MIMEText(html2text.html2text(body), 'plain')
part2 = MIMEText(body, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('10.0.0.16')
s.sendmail(fromAddr, [toAddr], msg.as_string())
s.quit()
return True
class MSSQL:
"""Helper class to do queries in MSSQL.
Python default methods were tedious to type every time
"""
def __init__(self, system='qas'):
self.system = system
dsn = ''
if system == 'qas':
self.conn = pyodbc.connect("DSN=sapdev;UID=" + config["sqluser_qas"] + ";PWD=" + config["sqlpass_qas"] + ";DATABASE=QAS")
elif system == 'prd':
self.conn = pyodbc.connect("DSN=sapprd;UID=" + config["sqluser_prd"] + ";PWD=" + config["sqlpass_prd"] + ";DATABASE=PRD")
else :
print "System not recognized"
exit(1)
self.cursor = self.conn.cursor()
def do_query(self, query_str):
self.cursor.execute(query_str)
data = self.cursor.fetchall()
headerArr = [x[0] for x in self.cursor.description]
ret_list = list()
for x in data:
ret_list.append({headerArr[i]:str(j).strip() for (i,j) in enumerate(list(x))})
return ret_list
class SF:
"""Helper class to grab/manipulate SF data from Python. Mostly using simple_salesforce module
Mostly used for query, but could be expanded
"""
def __init__(self, system='qas'):
if system == 'qas':
self.sf = Salesforce(username=config["sf_user_qas"], password=config["sf_pass_qas"], security_token=config["sf_token_qas"], sandbox=True)
elif system == 'prd':
self.sf = Salesforce(username=config["sf_user_prd"], password=config["sf_pass_prd"], security_token=config["sf_token_prd"], sandbox=False)
else :
self.sf = Salesforce(username=config["sf_user_qas"], password=config["sf_pass_qas"], security_token=config["sf_token_qas"], sandbox=True)
def do_query(self, query_str):
"""Take a standard SOQL query and return a list of dictionary results
It should nest any subqueries
"""
recs = self.sf.query_all(query_str)
retlist = []
for rec in recs['records']:
cur_ret_dict = {}
for field in rec:
if type(rec[field]) != unicode and rec[field] != None:
curfield = rec[field]
if 'records' in rec[field]:
#subdict = {}
sublist = []
for subrec in rec[field]['records']:
curtmpdict = {}
for subfield in subrec:
cursubfield = subrec[subfield]
if type(subrec[subfield]) == unicode:
curtmpdict[subfield] = subrec[subfield]
sublist.append(curtmpdict)
cur_ret_dict[field] = sublist
elif type(rec[field]) == unicode:
cur_ret_dict[field] = rec[field]
else:
pass
cur_ret_dict['Id'] = rec['attributes']['url'][-18:]
retlist.append(cur_ret_dict)
return retlist
def unstack_query(self, stacked_list):
"""Function to put a nested SF query result into a "flatter" table that's easier to use in an easier use in Pandas
"""
retlist = []
for head_rec in stacked_list:
subrec_list = []
main_currec_dict = {}
for field in head_rec:
if type(head_rec[field]) == list:
for cur_subrec in head_rec[field]:
prefixed_names_dict = {}
for regular_field_name in cur_subrec:
prefixed_field_name = field + u'_' + regular_field_name
prefixed_names_dict[prefixed_field_name] = cur_subrec[regular_field_name]
subrec_list.append(prefixed_names_dict)
else:
main_currec_dict[field] = head_rec[field]
for cur_subrec in subrec_list:
for cur_main_field in main_currec_dict:
cur_subrec[cur_main_field] = main_currec_dict[cur_main_field]
retlist.append(cur_subrec)
return retlist
|
TypeScript
|
UTF-8
| 4,713 | 2.640625 | 3 |
[
"MIT",
"BSD-2-Clause"
] |
permissive
|
// AngularIO libraries.
import { Component, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
@Component({
selector: 'app-dialog-box',
templateUrl: './dialog-box.component.html',
styleUrls: ['./dialog-box.component.css']
})
/*
*
* The DialogBoxComponent that displays a dynamic
* dialog box based on the string given.
*
*/
export class DialogBoxComponent {
// The username the user has chosen
user_name: string;
// Callback function in order to trigger application to start
callback: Function;
/*
*
* DialogBoxComponent that takes in a MatDialog in order to display it
* to the user.
*
* @param {dialog:MatDialog} The MatDialog used to display to the user.
*
*/
constructor(private dialog: MatDialog) { }
/*
*
* Opens the MatDialog and adds the string given to display to the user.
*
* @param {message:String} The string to display on the dialog box.
*
*/
open_dialog(dialog_title: string, dialog_text: string, submit_input: boolean, confirm_input: boolean): void{
setTimeout(() => {
let dialogRef = this.dialog.open(DialogBox,{
data: { init: true, title: dialog_title, text: dialog_text, submit_input: submit_input, confirm_input: confirm_input },
height: '50%',
width: '50%',
disableClose: true
});
if(confirm_input == false){
dialogRef.afterClosed().subscribe(result => {
this.user_name = result.data.user_name;
this.callback.apply(this);
});
}
}, 0);
}
/*
*
* Saves the function to call back to after the user has agreed to the
* contents of the dialog box.
*
* @param {callBack:Function} The function that gets called after the
* user has agreed to the dialog box.
*
*/
set_callback(callback:Function): void{
this.callback = callback;
}
/*
*
* Returns the user name the user set.
*
* @return {String} The user name.
*
*/
get_user_name(): string{
return this.user_name;
}
}
@Component({
selector: 'dialog-box',
templateUrl: 'dialog-box.html',
styleUrls: ['./dialog-box.component.css']
})
/*
*
* A custom DialogBox that the DialogBoxComponent uses in order to display dynmic text.
*
*/
export class DialogBox {
// Init boolean value.
init: boolean;
error: boolean = false;
// The DialogBox title and text.
dialog_title: string;
dialog_text: string;
// Boolean values to display the proper buttons.
submit_input: boolean = true;
confirm_input: boolean = false;
/*
*
* Custom DialogBox that is configured to use any data that is given.
*
* @param {dialogRef:MatDialogRef<DialogBox>} The current MatDialogBoxRef
* that is used to update text.
* @param {data:any} Information that is passed
* to the DialogBox to display.
*
*/
constructor(
public dialog_ref: MatDialogRef<DialogBox>,
@Inject(MAT_DIALOG_DATA) public data: any) {
this.init = this.data.init;
this.dialog_title = data.title;
this.dialog_text = data.text;
this.submit_input = data.submit_input;
this.confirm_input = data.confirm_input;
}
/*
*
* Function sets the username the user has typed in the input box and confirms it is
* an email.
*
* @param {matInput:any} The input string value the user set as their username.
*
*/
set_user_name(matInput: any): void {
var user_name = matInput.value;
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var emailTest = user_name != null && user_name != '' && re.test(String(user_name).toLowerCase());
if(emailTest){
this.data.user_name = matInput.value;
this.dialog_ref.close({data:this.data});
}
}
/*
*
* Calls submit_btn method when a user has typed their name and clicked enter.
*
* @param {event:any} The event being triggered by all buttons being typed.
*
*/
enter_click(event: any): void {
if(event.keyCode == 13) {
let submit_btn: HTMLElement = document.getElementById('submit_btn') as HTMLElement;
submit_btn.click();
}
}
/*
*
* Function that closes the second dialog box.
*
*/
close(): void {
this.dialog_ref.close();
}
}
|
Ruby
|
UTF-8
| 326 | 3.109375 | 3 |
[] |
no_license
|
class ConstantNode < Node
attr_reader :id, :val
def initialize(id, val)
super()
@id, @val = id, val
end
# no need to recurse here because
# constants only contain terminal values
def accept visitor
visitor.visit_constant_node self
end
def to_s
"Constant -> #{@id} = #{@val}"
end
end
|
SQL
|
UTF-8
| 248 | 3.734375 | 4 |
[
"MIT"
] |
permissive
|
CREATE PROC usp_GetEmployeesFromTown (@currentTown VARCHAR(50))
AS
SELECT e.[FirstName], e.[LastName]
FROM Employees AS e
JOIN Addresses AS a ON a.AddressID = e.AddressID
JOIN Towns AS t ON a.TownID = t.TownID
WHERE t.[Name] LIKE @currentTown
|
PHP
|
UTF-8
| 363 | 2.515625 | 3 |
[] |
no_license
|
<?php
function getwebcontent($url){
$ch = curl_init();
$timeout = 10;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
$contents = trim(curl_exec($ch));
curl_close($ch);
return $contents;
}
?>
|
Java
|
UTF-8
| 4,725 | 2.71875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
/*
* #%L
* SPIM Data: registered, multi-angle, multi-channel etc. image sequences.
* %%
* Copyright (C) 2013 - 2022 BigDataViewer developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package mpicbg.spim.data.sequence;
import java.text.ParseException;
import java.util.ArrayList;
/**
* Class with static methods to deal with integer patterns defining ranges of numbers and create String instances based
* on simple expressions like {aaa} or {t}.
*
* @author Stephan Preibisch (stephan.preibisch@gmx.de)
*/
public class IntegerPattern
{
/**
* Analyzes a file pattern and returns the number of digits as well as the replace pattern
* for a certain type,
* e.g. analyze spim_TL{t}_Angle{aaa}.tif for how many 'a' need to be replaced. It would
* return {aaa}, so you know it is with leading zeros up to a length of 3.
*
* @param inputFilePattern - e.g. spim_TL{t}_Angle{aaa}.tif
* @param type - e.g. 't' or 'a'
* @return the replace pattern "{t}" or "{aaa}", null if {type} does not exist in the String
*/
public static String getReplaceString( final String inputFilePattern, final char type )
{
String replacePattern = null;
int numDigitsTL = 0;
final int i1 = inputFilePattern.indexOf( "{" + type );
final int i2 = inputFilePattern.indexOf( type + "}" );
if ( i1 >= 0 && i2 > 0 )
{
replacePattern = "{";
numDigitsTL = i2 - i1;
for ( int i = 0; i < numDigitsTL; ++i )
replacePattern += type;
replacePattern += "}";
}
return replacePattern;
}
/**
* Parse a pattern provided by the user defining a range of integers. Allowed are enumerations seperated by
* commas, each entry can be a single number, a range e.g. 4-100 or a range in intervals e.g. 0-30:10 - which
* is equivalent to 0,10,20,30
*
* @param integers - the input
* @return a list of integers that were described, an empty list with the entry 0 if the String is "" or null
* @throws ParseException if the input string was illegal
*/
public static ArrayList< Integer > parseIntegerString( final String integers ) throws ParseException
{
ArrayList< Integer > tmp = null;
if ( integers == null || integers.trim().length() == 0 )
{
tmp = new ArrayList<Integer>();
tmp.add( 0 );
return tmp;
}
try
{
tmp = new ArrayList<Integer>();
final String[] entries = integers.split( "," );
for ( String s : entries )
{
s = s.trim();
s = s.replaceAll( " ", "" );
if ( s.contains( "-" ) )
{
int start = 0, end = 0, step;
start = Integer.parseInt( s.substring( 0, s.indexOf("-") ) );
if ( s.indexOf( ":" ) < 0 )
{
end = Integer.parseInt( s.substring( s.indexOf("-") + 1, s.length() ) );
step = 1;
}
else
{
end = Integer.parseInt( s.substring( s.indexOf("-") + 1, s.indexOf(":") ) );
step = Integer.parseInt( s.substring( s.indexOf(":") + 1, s.length() ) );
}
if ( end > start )
for ( int i = start; i <= end; i += step )
tmp.add( i );
else
for ( int i = start; i >= end; i -= step )
tmp.add( i );
}
else
{
tmp.add( Integer.parseInt( s ) );
}
}
}
catch ( final Exception e )
{
e.printStackTrace();
throw new ParseException( "Cannot parse: '" + integers + "'", 0 );
}
return tmp;
}
}
|
C#
|
UTF-8
| 387 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
using System.Collections.Generic;
using ValueTypes;
namespace ValueTypesTests.Cards
{
public class Hand : Value
{
public Card[] Cards { get; }
public Hand(params Card[] cards) => Cards = cards;
protected override IEnumerable<ValueBase> GetValues() => Group(Cards);
public override string ToString() => string.Join<Card>(", ", Cards);
}
}
|
Python
|
UTF-8
| 527 | 3.078125 | 3 |
[] |
no_license
|
# procesar_csv.py
import pylab as pl
import csv
#
entrada = open('uma_02.csv')
tabla = []
for fila in csv.reader(entrada):
tabla.append(fila)
entrada.close()
x=[0]
y=[0]
z=[0]
for fila in range(1, len(tabla)):
x.append(float(tabla[fila][13]))
y.append(float(tabla[fila][2]))
z.append(float(tabla[fila][3]))
print(ltln)
#print(x)
pl.plot(x,y,z)
pl.xlabel('velocidad')
pl.ylabel('latlong')
pl.title('Ejemplo de grafica de un archivo csv')
pl.show()
|
Java
|
UTF-8
| 3,733 | 2.84375 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hive.main;
import hive.model.GameProgress;
import hive.model.game.DefaultGame;
import hive.model.game.Game;
import hive.model.game.rules.GameStatus;
import hive.model.game.rules.HiveUtil;
import hive.model.players.Player;
import hive.model.players.decisions.IADecision;
import hive.model.players.decisions.IA.Level;
import java.util.Scanner;
/**
*
* @author Coralie
*/
public class HiveConsoleIABoucle {
/**
* @param args the command line arguments
*/
static void printWhich(int i){
switch (i) {
case 0:
System.out.println("Hard vs Medium");
break;
case 20:
System.out.println("Medium vs Hard");
break;
case 40:
System.out.println("Easy vs Hard");
break;
case 60:
System.out.println("Hard vs Easy");
break;
case 80:
System.out.println("Medium vs Easy");
break;
case 100:
System.out.println("Easy vs Medium");
break;
default:
break;
}
}
public static void main(String[] args) {
// choisir les décisions qu'il faut ICI
// si il y a un humain, s'inspirer du shéma de HiveConsoleHuman dans le corps du while
// (il faut setAction avant de doAction() quand c'est à un humain de jouer)
int i = 0;
Game game;
while (i < 120) {
if (i < 20) {
game = DefaultGame.get(new IADecision(Level.HARD)/*white*/, new IADecision(Level.MEDIUM)/*black*/);
} else if (i < 40) {
game = DefaultGame.get(new IADecision(Level.MEDIUM)/*white*/, new IADecision(Level.HARD)/*black*/);
} else if (i < 60) {
game = DefaultGame.get(new IADecision(Level.EASY)/*white*/, new IADecision(Level.HARD)/*black*/);
} else if (i < 80) {
game = DefaultGame.get(new IADecision(Level.HARD)/*white*/, new IADecision(Level.EASY)/*black*/);
} else if (i < 100) {
game = DefaultGame.get(new IADecision(Level.MEDIUM)/*white*/, new IADecision(Level.EASY)/*black*/);
} else {
game = DefaultGame.get(new IADecision(Level.EASY)/*white*/, new IADecision(Level.MEDIUM)/*black*/);
}
printWhich(i);
GameProgress progress = new GameProgress(game);
Player player = null;
while (game.rules.getStatus(game.state) == GameStatus.CONTINUES && HiveUtil.nbTurns(game.state)<50) {
player = game.state.turn.getCurrent();
progress.doAction();
// mettre un sleep ici ?
}
System.out.println("Turn : " + HiveUtil.nbTurns(game.state));
switch(game.rules.getStatus(game.state))
{
case DRAW:
System.out.println("Match nul");
break;
case CURRENT_WINS:
System.out.println(game.state.turn.getCurrent().color);
break;
case OPPONENT_WINS:
System.out.println(game.state.turn.getOpponent().color);
break;
}
//System.out.println(game.state.board);
i++;
}
}
}
|
Python
|
UTF-8
| 393 | 3 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
import nltk
from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag
ex = 'European authorities fined Google a record $5.1 billion on Wednesday for abusing its power in the mobile phone market and ordered the company to alter its practices'
def preprocess(sent):
sent = nltk.word_tokenize(sent)
sent = nltk.pos_tag(sent)
return sent
sent = preprocess(ex)
print(sent)
|
C++
|
UTF-8
| 1,965 | 2.953125 | 3 |
[] |
no_license
|
#ifndef __MATCH_H__
#define __MATCH_H__
#include "config.h"
#include <functional>
#include <arx/Collections.h>
namespace prec {
// -------------------------------------------------------------------------- //
// Match
// -------------------------------------------------------------------------- //
class Match {
private:
arx::array<SIFT, 2> keys;
int distSqr; /**< Distance between 2 keypoints. TODO: remove. */
public:
Match() {}
Match(SIFT key0, SIFT key1, int distSqr): distSqr(distSqr) {
/* Match class must store KeyPoints in some fixed order on the basis of keypoint owner.
* I.e. in case we have several matches between two images, calls to getKey method of these
* matches with the same parameters must never return keypoints from different images.
*
* Here we use tag field of keypoint. Unique PanoImage identifier is stored in tag, and
* therefore it provides exactly what we need. */
if(key0.getTag() > key1.getTag()) {
this->keys[0] = key0;
this->keys[1] = key1;
} else {
this->keys[0] = key1;
this->keys[1] = key0;
}
}
arx::UnorderedPair<SIFT, KeyPointPtrComparer> getKeys() const { return arx::make_upair(this->keys[0], this->keys[1], KeyPointPtrComparer()); }
SIFT getKey(std::size_t n) const { return this->keys[n]; }
int getDistSqr() const { return this->distSqr; }
bool isNull() const { return this->keys[0].isNull(); }
};
// -------------------------------------------------------------------------- //
// MatchDistComparer
// -------------------------------------------------------------------------- //
class MatchDistComparer: public std::binary_function<Match, Match, bool> {
public:
bool operator()(const Match& l, const Match& r) const {
return l.getDistSqr() < r.getDistSqr();
}
};
} // namespace prec
#endif
|
Python
|
UTF-8
| 1,612 | 4.34375 | 4 |
[] |
no_license
|
def example_one(i):
if i == 10:
return
print(i)
i = i + 1
example_one(i)
# example_one(0)
def fibonacci(x, y, max, counter=0):
if counter == max:
return
print(counter)
counter += 1
next_num = x + y
print(x)
fibonacci(y, next_num, max, counter)
# fibonacci(1, 1, 10) #calls fib function
#prints a star pyramid
def stars(max, counter=0):
if counter == max:
return
counter += 1
print(counter * "*")
stars(max, counter)
# stars(20)
#the below function returns the factorial of all numbers up until the number(n) that is passed...
def factorial(n):
if n == 1 or n == 0: #there is no factorial of 1 or 0, so we have to account for this base case here...
return 1
fact_num = n * factorial(n-1) #define a new variable that is equal to the number passed(n) times factorial of n minus 1 (ex: n=5, n-1=4)...
print(str(n) + '! = ' + str(fact_num)) #print n! = new variable (fact_num)
return fact_num #return new variable...
factorial(10) #Dont forget to call the function!!!
#How to reverse and array with a for loop:
array = [1, 2, 3, 4, 5]
for i in range(len(array) / 2)
j = len(array) - i - 1
array[i], array[len(array) - 1 - i] = array[len(array) - 1 - i], array[i]
#How to reverse an array with recursion:
def rev_array(array, i):
if i >= len(array) / 2 or len(array) == none:
return array
j = len(array) - i - 1
array[i], array[j] = array[j], array[i]
return reverse_array(array, i + 1)
|
Markdown
|
UTF-8
| 1,487 | 2.765625 | 3 |
[] |
no_license
|
+-- {: .rightHandSide}
+-- {: .toc .clickDown tabindex="0"}
###Context###
#### Differential geometry
+--{: .hide}
[[!include synthetic differential geometry - contents]]
=--
=--
=--
> This entry is about the concept in [[differential geometry]] and [[Lie theory]]. For the concept in functional analysis see at _[[distribution]]_.
#Contents#
* table of contents
{:toc}
## Definition
A __real distribution__ on a real [[smooth manifold]] $M$ is a [[real vector bundle|real vector subbundle]] of the [[tangent bundle]] $T M$.
A __complex distribution__ is a [[complex vector bundle|complex vector subbundle]] of the [[complexification|complexified]] tangent bundle $T_{\mathbb{C}}M$ of $M$.
A __distribution of [[hyperplanes]]__ is a distribution of [[codimension]] $1$ in $T M$; a __distribution of complex hyperplanes__ is a distribution of complex codimension $1$ in $T_{\mathbb{C}} M$.
## Examples
One class of examples comes from smooth [[foliations]] by [[submanifolds]] of constant dimension $m\lt n$. Then the [[tangent vectors]] at all points to the submanifolds forming the foliation form a distribution of subspaces of dimension $m$. The distributions of that form are said to be __[[integrable distribution|integrable]]__.
... _say something about the Frobenius theorem_ ...
## References
Discussion in the context of [[geometric quantization]]:
* N. M. J. Woodhouse, _Geometric quantization_
[[!redirects distributions of subspaces]]
|
Java
|
UTF-8
| 1,813 | 3.453125 | 3 |
[] |
no_license
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.rmi.server.ExportException;
import java.util.Random;
import java.util.Scanner;
public class Main {
private final static int MAX_NUMBER = 100;
private static Random rnd = new Random();
private static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
while (true) { //Generating randInt
newint();
System.out.println("Съиграем еще раз? (y/N)");
String line = input.readLine();
if( !line.equalsIgnoreCase("Y") )
break;
}
}
private static void newint() {
int rand = rnd.nextInt(MAX_NUMBER);//generate random number
System.out.println("Загадано число от 0 до 100, угадаешь?\nВводи:");
while(true) {
try {
String line = input.readLine();
if (line.isEmpty()) {
continue;
}
int number = Integer.parseInt(line);
if (number > rand) {
System.out.println("Меньше!");
} else if (number < rand) {
System.out.println("Больше!");
} else if (number == rand) {
System.out.println("Угадал!");
break;
} else {
System.out.println("Число не попало в диапазон от 0 до " + MAX_NUMBER);
}
} catch (Exception e){
System.out.println("Это не число, попробуй еще раз");
}
}
}
}
|
Java
|
UTF-8
| 4,769 | 2.328125 | 2 |
[] |
no_license
|
package com.spring.core;
import com.spring.core.config.BasketInitializer;
import com.spring.core.dao.ListOfGoodsDao;
import com.spring.core.dao.impl.InFileBasketDao;
import com.spring.core.model.Basket;
import com.spring.core.model.Product;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class InFileBasketTest {
@Mock
private Basket basketList;
@Mock
private ListOfGoodsDao listOfGoods;
@Mock
private BasketInitializer basketInitializer;
private InFileBasketDao basket;
private static List<Product> productsList;
private static List<Product> productsFromBasket;
@Before
public void initialBasket() {
productsList = new ArrayList<>() {{
add(new Product("phone", new BigDecimal(790.22), 340));
add(new Product("pan", new BigDecimal(9.12), 15));
add(new Product("computer", new BigDecimal(3200.00), 2100));
}};
productsFromBasket = new ArrayList<>() {{
add(new Product("phone", new BigDecimal(790.22), 340));
add(new Product("pan", new BigDecimal(9.12), 15));
add(new Product("computer", new BigDecimal(3200.00), 2100));
}};
basket = new InFileBasketDao(listOfGoods, basketInitializer, basketList);
when(basketList.getBasket()).thenReturn(productsFromBasket);
}
@Test
public void testGetProductsFromBasket() {
assertEquals(productsList.get(1).getPrice(), basket.getProductsFromBasket().get(1).getPrice());
assertEquals(productsList.get(1).getWeight(), basket.getProductsFromBasket().get(1).getWeight());
}
@Test
public void testGetAllProducts() {
when(listOfGoods.getProducts()).thenReturn(productsList);
assertEquals(productsList.get(1).getName(), basket.getAllProducts().get(1).getName());
assertEquals(productsList.get(1).getWeight(), basket.getAllProducts().get(1).getWeight());
}
@Test
public void testGetProduct() {
assertEquals(productsList.get(1).getName(), basket.getProduct(1).getName());
assertEquals(productsList.get(2).getPrice(), basket.getProduct(2).getPrice());
assertEquals(productsList.get(0).getWeight(), basket.getProduct(0).getWeight());
}
@Test(expected = Exception.class)
public void testGetNonexistentProduct() {
int size = basket.getProductsFromBasket().size();
basket.getProduct(size);
}
@Test
public void testUpdateProduct() throws Exception {
when(listOfGoods.getProduct(1)).thenReturn(productsList.get(1));
basket.updateProduct(2, 1);
assertEquals(productsList.get(1), basket.getProduct(2));
verify(basketInitializer, times(1)).updateBasket(basketList);
}
@Test(expected = Exception.class)
public void testUpdateNonexistentProduct() throws Exception {
when(listOfGoods.getProduct(1)).thenReturn(productsList.get(1));
int size = basket.getProductsFromBasket().size();
basket.updateProduct(size, 1);
}
@Test(expected = Exception.class)
public void testUpdateOnNonexistentProduct() throws Exception {
when(listOfGoods.getProduct(10)).thenThrow(Exception.class);
basket.updateProduct(1, 10);
}
@Test
public void testAddProduct() throws Exception {
int sizeBefore = basket.getProductsFromBasket().size();
when(listOfGoods.getProduct(2)).thenReturn(productsList.get(2));
basket.addProduct(2);
int sizeAfter = basket.getProductsFromBasket().size();
assertEquals(sizeBefore + 1, sizeAfter);
verify(basketInitializer, times(1)).updateBasket(basketList);
}
@Test(expected = Exception.class)
public void testAddNonexistentProduct() throws Exception {
when(listOfGoods.getProduct(10)).thenThrow(Exception.class);
basket.addProduct(10);
}
@Test
public void testDeleteProduct() throws Exception {
int sizeBefore = basket.getProductsFromBasket().size();
basket.deleteProduct(2);
int sizeAfter = basket.getProductsFromBasket().size();
assertFalse(sizeBefore == sizeAfter);
verify(basketInitializer, times(1)).updateBasket(basketList);
}
@Test(expected = Exception.class)
public void testDeleteNonexistentProduct() throws Exception {
int size = basket.getProductsFromBasket().size();
basket.deleteProduct(size);
}
}
|
Markdown
|
UTF-8
| 4,334 | 3.734375 | 4 |
[
"MIT"
] |
permissive
|
# SetImmutable [](https://travis-ci.org/JonDotsoy/setImmutable.js)
An alternative to [lodash.set][] when your object necessary working with immutable objects.
## Installation
Using npm:
npm install --save setimmutable
In Node.js:
```javascript
const set = require('setimmutable');
```
## Mutable Vs. Immutable
In a simple object when do you use `_.set` the data is updated if it is frozen nothing happens. The **SetImmutable** update the object tree until the final element to be replaced.
```javascript
// const setLodash = require('lodash.set')
// const setImmutable = require('setimmutable')
// With mutable object
const nextObjMutable = setLodash(originalObj, path, 3) // Update the element and return the original object.
nextObjMutable === originalObj // true
// With immutable object
const nextObjImmutable = setImmutable(originalObj, path, 3) // Update the tree element and return a new object.
nextObjImmutable === originalObj // false
```
## SetImmutable with complex constructors
To update the object tree is used the reference constructor. This makes a new object and assigns all old properties to the new object. But there are times when the constructor is complex and requires special properties to be declared.
```javascript
// Simple Constructor
class SimpleConstructor {
constructor() { /* ... */ }
}
// Complex Constructor
class ComplexConstructor {
constructor(requiredArg, especialArg) { /* ... */ }
}
```
**SetImmutable** load the custom Clone to make a new object.
**Example:**
```javascript
// const clone = require('setimmutable/clone')
function customClone (objValue, srcValue) {
switch (objValue.constructor) {
// My custom class
case MyClass: return MyClass.parse(objValue) // Return new object instance of MyClass
// My second custom class
case MySecondClass: return new MySecondClass(...myArgs) // Return new object instance of MySecondClass
// Set default clone
default: return clone(objValue)
}
}
setImmutable(originalObject, path, newValue, customClone)
```
## API
### `set(object, path, value, [customClone])`
Sets the value at path of object. If a portion of path doesn't exist, it's created.
**Note:** This not method mutates object. It re-create the object defined on the path.
**Arguments**
- **object (*Object*)**: The object to modify.
- **path (*Array*|*string*)**: The path of the property to set.
- **value (*)**: The value to set.
- **[customClone] (*Function*)**: The function to customize clone object.
**Returns**
- ***(Object)***: Return object.
**Example 1 (on [RunKit](https://runkit.com/jondotsoy/setimmutable-example-1))**
```javascript
const object = {}
set(object, '[0][1][2]', 'a')
// => { '0': { '1': {'2': 'a' } } }
```
**Example 2 (on [RunKit](https://runkit.com/jondotsoy/setimmutable-example-2))**
```javascript
const object = []
function customClone (objValue, srcValue) {
switch (objValue.constructor) {
case Person: return Person.clone(objValue)
/* ... */
/* default: return require('setimmutable/clone')(objValue) */
}
}
set(object, '[0].people.[1].firstName', 'Lucky', customClone)
// => [ { 'people': [..., Person { 'firstName': 'Lucky' } ] } ]
```
## SetImmutable with [Redux][redux]
**With SetImmutable:**
```javascript
const set = require('setimmutable')
function Reducer (state = initialState, action) {
switch (action.type) {
case 'UPDATE_PERSON': {
return set(state, ['people', action.id, 'firstName'], action.firstName)
}
/* ... */
}
}
```
**Without SetImmutable:**
```javascript
function Reducer (state = initialState, action) {
switch (action.type) {
case 'UPDATE_PERSON': {
return {
...state,
people: state.people.map((person, index) => {
if (person.id === action.id) {
return {
...state.people[index],
firstName: action.firstName
}
} else {
return person
}
})
}
}
/* ... */
}
}
```
[lodash.set]: https://lodash.com/docs#set "_.set(object, path, value)"
[redux]: http://redux.js.org/ "Redux is a predictable state container for JavaScript apps."
|
Markdown
|
UTF-8
| 935 | 4.03125 | 4 |
[] |
no_license
|
## Problem
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
```
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
```
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
## Solution
- Find lengths of the two lists - l1 and l2.
- find which list is bigger. Move l1-l2 nodes if A is longer list otherwise l2-l1 for list B.
- At this point, you are at two nodes, that are equidistant from the end node c3.
- go node by node on both lists and compare pointer.
|
Java
|
UTF-8
| 3,776 | 2.125 | 2 |
[] |
no_license
|
package com.example.mp5;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.lib.LocationData;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapFragment extends Fragment implements OnMapReadyCallback {
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
private float currentLocation = 210.0f;
private float notFull = 120.0f;
private float halfFull = 60.0f;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_map, container, false);
return mView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView) mView.findViewById(R.id.map);
if (mMapView != null) {
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mGoogleMap = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
for (LocationItem locationItem : DataManager.getLocationItems()) {
float color = 0.0f;
if (locationItem.getFill() == -1) {
color = notFull;
} else if (locationItem.getFill() == 0) {
color = halfFull;
}
googleMap.addMarker(new MarkerOptions().position(new LatLng(locationItem.getLatitude(),
locationItem.getLongitude())).title(locationItem.getName()).icon(BitmapDescriptorFactory.defaultMarker(color)).snippet("Time: " + locationItem.getTime()).visible(true));
}
googleMap.addMarker(new MarkerOptions().position(new LatLng(DataManager.getCurLatitude(), DataManager.getCurLongitude())).title("You :)").icon(BitmapDescriptorFactory.defaultMarker(currentLocation)).visible(true));
CameraPosition bardeenQuad = CameraPosition.builder().target(new LatLng(40.111691, -88.227062)).zoom(17).bearing(0).tilt(45).build();
CameraPosition currentLoc = CameraPosition.builder().target(new LatLng(DataManager.getCurLatitude(), DataManager.getCurLongitude())).zoom(17).bearing(0).tilt(45).build();
if (DataManager.getCurLatitude() == 0 || DataManager.getCurLongitude() == 0) {
//set camera position on the Bardeen quad if current location is invalid
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(bardeenQuad));
} else {
//set camera position on current location
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(currentLoc));
}
}
}
|
PHP
|
UTF-8
| 5,956 | 2.796875 | 3 |
[] |
no_license
|
<?php
/**
* Use an HTML form to edit an entry in the
* users table.
*
*/
require "session.php";
require "common.php";
require "checkstaff.php";
if(isset($_POST['addsec'])){
if(isset($_POST['newsec_id']) and isset($_POST['newyear']) and isset($_POST['newsem']) and isset($_POST['newtid'])){
$newsec_id = $_POST['newsec_id'];
$newyear = $_POST['newyear'];
$newsem = $_POST['newsem'];
$newtid = $_POST['newtid'];
$cid = $_GET['cid'];
$sql = "INSERT INTO section (cid,sec_id,yearr,sem,tid)
VALUES ('".$cid."', ".$newsec_id.", ".$newyear.", ".$newsem.", '".$newtid."');";
$res = mysqli_query($db, $sql);
if(!$res){
echo "Cannot insert section. It might already exist! Try Editing instead. ";
}
}
}
if (isset($_POST['submit'])) {
try {
$cid = $_GET['cid'];
$invalidtid = array();
for ($i=0; $i < count($_POST['sec_id']); $i++ ) {
$sec_id = $_POST['sec_id'][$i];
$year = $_POST['year'][$i];
$sem = $_POST['sem'][$i];
$tid= $_POST['tid'][$i];
//check if teacher is valid
$sql2 = "SELECT count(*) as count
FROM teacher
WHERE tid = ". $tid ." ;";
$result2 = mysqli_query($db,$sql2);
if(!$result2){
echo "cannot fetch at sql2";
echo $sql2;
exit();
}
//teacher doesn't exist
if(mysqli_fetch_array($result2)['count'] == 0){
array_push($invalidtid,$sec_id) ; //add to array
}
//the actual update query
$sql = "UPDATE section
SET yearr=".$year.", sem=".$sem.", tid= '".$tid."'
WHERE sec_id = '".$sec_id."' AND cid = '".$cid."' ";
$result = mysqli_query($db,$sql);
if(!$result){
echo "cannot update";
}
}
if(sizeof($invalidtid) != 0){
echo '<script language="javascript">';
echo 'alert("invalid teacher id for section : ';
foreach($invalidtid as $itid) {
//print array for check
echo $itid.' ';
}
echo '");';
echo '</script>';
}
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<?php
if (isset($_GET['cid'])) {
$cid = $_GET['cid'];
//////////////////// sections ///////////////
$sql = "SELECT S.sec_id, S.yearr, S.sem, S.tid, C.cname,T.tid, T.tname
FROM section S, course C, teacher T
WHERE S.cid = ".$cid." AND S.cid=C.cid AND T.tid=S.tid ORDER BY CAST(S.sec_id AS UNSIGNED);";
// echo $sql;
$result = mysqli_query($db,$sql);
if(!$result){
echo "cannot fetch";
exit();
}
/////////////////////about course///////////////////////
$sql2 = "SELECT * FROM course C WHERE C.cid = ".$cid.";";
// echo $sql;
$result2 = mysqli_query($db,$sql2);
if(!$result2){
echo "cannot fetch2";
exit();
}
$row2= mysqli_fetch_array($result2);
require "templates/header.php";
include "splitleft-staff.html";
?>
<div class="splitright">
<?php
include "backbuttonstaff.html"; ?>
<!--
<?php if (isset($_POST['submit']) && $statement) : ?>
<blockquote><?php echo escape($_POST['cname']); ?> successfully updated.</blockquote>
<?php endif; ?>
-->
<div style="padding-left: 10px;">
<h1>Course Info : Manage Section</h1>
<p>
<pre>
Course ID: <?= $row2['cid'] ?> 	
Course Name : <?= $row2['cname'] ?> 	
Credits: <?=$row2['credits']?> </pre></p>
<form method="post" action="">
<table class="data-table" style="display: block; overflow-y: auto; width:1000px; max-height: 500px;">
<caption style="background: none"> sections of course <?= $cid ?> : </caption>
<thead>
<th> section id</th>
<th> year</th>
<th> semester</th>
<th> teacher id</th>
<th> teacher name</th>
<th> </th>
</thead>
<tbody>
<tr>
<td> <input type="text" name="newsec_id"> </td>
<td> <input type="text" name="newyear"> </td>
<td> <input type="text" name="newsem"> </td>
<td> <input type="text" name="newtid"> </td>
<td> </td>
<td> <input class="addbutton" type="submit" name="addsec" value = "+"> </td>
</tr>
<?php foreach ($result as $row) :
$sec = $row['sec_id'];
$year = $row['yearr'];
$sem = $row['sem'];
$tid = $row['tid'];
$tname = $row['tname'];
?>
<tr>
<td><?php echo escape($row["sec_id"]); ?>
<input type="hidden" name="sec_id[]" value=<?php echo escape($row["sec_id"]); ?> class="field left" readonly>
</td>
<td><?php echo escape($year); ?>
<input type="hidden" name="year[]" value=<?php echo escape($year); ?> class="field left" readonly>
</td>
<td><?php echo escape($sem); ?>
<input type="hidden" name="sem[]" value=<?php echo escape($sem); ?> class="field left" readonly>
</td>
<td>
<input type="text" name="tid[]" maxlength="45" value=<?php echo escape($tid); ?> class="formtextboxsmall" >
</td>
<td><?php echo escape($row["tname"]);?> </td>
<td><a href="delete-section.php?cid=<?= $cid?>&sec_id=<?= $sec ?>&year=<?= $year ?>&sem=<?= $sem?>"><i class="fas fa-trash-alt"></i></a></td>
<!-- <td><a href="delete-section.php?cid=<?= $row["cid"] ?>?sec_id=<?php echo escape($row["sec_id"]); ?>?year=<?php echo escape($row["year"]); ?>?sem=<?php echo escape($row["sem"]); ?>">Delete</a></td> -->
</tr>
<?php endforeach; ?>
</tbody>
</table>
<br>
<a class="gobacklink" style="display: inline-block; background-color:salmon;" href="managecourse.php">Back to manage course</a>
<input style="display: inline-block;" type="submit" name="submit" class="submitbutton" value="Submit">
</form>
</div>
<?php require "templates/footer.php";
} else {
echo "Something went wrong!";
exit;
}
?>
|
Java
|
UTF-8
| 3,301 | 1.8125 | 2 |
[] |
no_license
|
package com.ianarbuckle.fitnow.activities.running.gallery;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.ianarbuckle.fitnow.BaseFragment;
import com.ianarbuckle.fitnow.FitNowApplication;
import com.ianarbuckle.fitnow.R;
import com.ianarbuckle.fitnow.utils.Constants;
import com.ianarbuckle.fitnow.utils.GalleryDialogFragment;
import com.ianarbuckle.fitnow.utils.RecyclerItemClickListener;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Ian Arbuckle on 16/03/2017.
*
*/
public class RunGalleryFragment extends BaseFragment implements RunGalleryView {
GridLayoutManager gridLayoutManager;
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@BindView(R.id.rlEmptyMessage)
RelativeLayout rlEmptyMessage;
RunGalleryAdapter adapter;
RunGalleryPresenterImpl presenter;
public static Fragment newInstance() {
return new RunGalleryFragment();
}
@Override
protected void initPresenter() {
presenter = new RunGalleryPresenterImpl(this, FitNowApplication.getAppInstance().getDatabaseHelper());
}
@Override
public void onStart() {
super.onStart();
presenter.getUploads();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
ButterKnife.bind(this, view);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Bundle bundle = presenter.getBundle();
bundle.putInt(Constants.POSITION_KEY, position);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
GalleryDialogFragment runGalleryDialogFragment = GalleryDialogFragment.newInstance();
runGalleryDialogFragment.setArguments(bundle);
runGalleryDialogFragment.show(fragmentTransaction, Constants.TAG_GALLERY_FULLSCREEN_FRAGMENT);
}
@Override
public void onLongItemClick(View view, int position) {
}
}));
return view;
}
@Override
public void showProgress() {
showProgressDialog();
}
@Override
public void hideProgress() {
hideProgressDialog();
}
@Override
public void setAdapter(RunGalleryAdapter adapter) {
recyclerView.setVisibility(View.VISIBLE);
rlEmptyMessage.setVisibility(View.GONE);
recyclerView.setAdapter(adapter);
}
@Override
public void showErrorMessage() {
}
@Override
public boolean onBackPressed() {
getActivity().finish();
return super.onBackPressed();
}
}
|
JavaScript
|
UTF-8
| 2,800 | 2.5625 | 3 |
[] |
no_license
|
function insertDepartamentos() {
var nombre = $("#dNb").val();
var descripcion = $("#dDe").val();
var datos = new Array();
var nb = new objPrm("Nombre", nombre);
datos.push(nb);
var pb = new objPrm("Descripción", descripcion);
datos.push(pb);
var res = new objRes();
res = validarEsVacido(datos);
if (res.est === "ko") {
alertify.error(res.nombre + " " + res.msj);
alertify.alert()
.setting({
'label': 'Entendido',
'message': 'Por favor rellene el campo de ' + res.nombre,
'onok': function () {
alertify.success('Ahora si vamos a trabajar');
}
}).show();
} else {
$.ajax({
url: "../syModel/departamentos/ifExist.php",
type: 'POST',
dataType: "json",
data: {no: nombre},
beforeSend: function () {
},
success: function (respuesta) {
var tam = respuesta.resultados;
if (tam == 0) {
$.ajax({
url: "../syModel/departamentos/insert.php",
type: 'POST',
dataType: "json",
data: {no: nombre, de: descripcion},
beforeSend: function () {
},
success: function (respuesta) {
showDepartamentos(nombre,"de");
$("#dCancelar").click();
$("#dNb").val("");
$("#dDe").val("");
alertify.success("El departamento a sido agregado.");
},
error: function () {
alert("Ocurrio un error en la llamada Ajax Er:cod 255");
}
});
} else {
alertify.error(res.nombre + " " + res.msj);
alertify.alert()
.setting({
'label': 'Entendido',
'message': 'Ya existe un registro ' + res.nombre,
'onok': function () {
alertify.success('Ahora si vamos a trabajar');
}
}).show();
}
},
error: function () {
alert("Ocurrio un error en la llamada Ajax Er:cod 255");
}
});
}
}
$(document).ready(function () {
$("#dGuardar").click(function () {
insertDepartamentos();
});
});
|
Java
|
UTF-8
| 493 | 2.5 | 2 |
[] |
no_license
|
package cn.com.jdsc;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
public class codeKey {
static RSAPublicKey pubKey;
static RSAPrivateKey priKey;
static void setRSAPublicKey(RSAPublicKey pub){
pubKey = pub;
}
static void setRSAPrivateKey(RSAPrivateKey pri){
priKey = pri;
}
static RSAPublicKey getRSAPublicKey(){
return pubKey;
}
static RSAPrivateKey getRSAPrivateKey(){
return priKey;
}
}
|
C#
|
UTF-8
| 1,457 | 2.734375 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class NavMeshAgentEnemy : MonoBehaviour
{
Camera _target; // <-- Player position
NavMeshAgent _agent; // <-- Get nawMesh Agent component
[SerializeField]
float HP = 100; // <-- Enemy HP (100 by default)
void Start()
{
_agent = GetComponent<NavMeshAgent>();
_target = Camera.main;
// TODO: Remove before release
if (_agent != null)
print($"{_agent}");
if (_target != null)
print($"Target position {_target.transform.position} finded!");
else
print($"Target position not found! Please, set tag MainCamera to Player camera.");
// ---------------------------
}
void Update()
{
_agent.SetDestination(_target.transform.position); // <-- Assigning a destination point
// Check distance between player and enemy
if (Vector3.Distance(_agent.transform.position, _target.transform.position) < 0.5f)
{
// TODO: Fight logic
}
}
// Create take damage method
void TakeDamage(float _damage)
{
HP -= _damage;
print($"Zombie {gameObject.name} take {_damage}. Current lives is {HP}");
// TODO: Die enemy logic
if (HP <= 0)
{
// Start DIE Courutine
}
}
// TODO: DIE Courutine
}
|
Markdown
|
UTF-8
| 883 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
<!--start-code-->
```js
import { ButtonToolbar, Button, DOMHelper } from 'rsuite';
const { on, off } = DOMHelper;
const App = () => {
const btnRef = React.useRef();
const listenerRef = React.useRef();
const handleOnEvent = () => {
if (!listenerRef.current) {
listenerRef.current = on(btnRef.current, 'click', () => {
alert('click');
});
}
};
const handleOffEvent = () => {
if (listenerRef.current) {
listenerRef.current.off();
listenerRef.current = null;
}
};
return (
<div>
<div>
<button ref={btnRef}>click me</button>
</div>
<hr />
<ButtonToolbar>
<Button onClick={handleOnEvent}>on</Button>
<Button onClick={handleOffEvent}>off</Button>
</ButtonToolbar>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
```
<!--end-code-->
|
Markdown
|
UTF-8
| 1,495 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
# Pylot
A Kubernetes deploy tool
## Purpose
Pylot is a prototype exploring ways to provide a more user-friendly way to deploy kubernetes applications.
The main design goals are:
1) to incorporate typing using the client-python Swagger specs, to make writing specs as IDE-friendly as possible
2) to wrap and/or hide the complexity of client-python's Swagger types if/where possible
3) to enable the specification of nontrivial scripted deployment flows in Python, such as canary or green-blue deploys.
## Getting started
### Installing
First install pylot. Currently this project is not hosted on PyPi, so clone the repo and egg-install it:
```bash
git clone git@github.com:paultiplady/pylot.git
cd pylot
pip install -e .
```
### Configuration
The `Configuration` class specifies config values that are to be injected into the application.
```python
class MyConfig(Configuration):
foo = Field()
bar = Field(default='BAR')
```
### Job
The `Job` class encapsulates a deploy job, binding a Configuration to a set of Kubernetes API objects.
At runtime the configuration values will be injected into the Job, producing the final specs to be created.
```python
my_job = Job(
configuration_cls=MyConfig,
objects=[V1Pod()],
)
```
### Deploying
After specifying a job, it can be run like so:
```bash
pylot deploy --dry-run package.job_module
```
Note that the string `package.job_module` refers to the package containing the Job to be run, which must be on the Python path.
|
Java
|
UTF-8
| 1,398 | 1.617188 | 2 |
[] |
no_license
|
package com.google.android.gms.internal.measurement;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.common.internal.Preconditions;
import java.util.ArrayList;
import java.util.List;
final class zzgl implements zzpe, Runnable {
private final /* synthetic */ zzgf zzbim;
private zzgl(zzgf zzgf) {
this.zzbim = zzgf;
}
public final void run() {
Preconditions.checkState(this.zzbim.state == 2);
if (!zzhs.zzrf().zzem(this.zzbim.zzazo)) {
String zzd = this.zzbim.zzazo;
zzhk.m1082v(new StringBuilder(String.valueOf(zzd).length() + 24).append("Refreshing container ").append(zzd).append("...").toString());
List arrayList = new ArrayList();
arrayList.add(Integer.valueOf(0));
this.zzbim.zzbie.zza(this.zzbim.zzazo, this.zzbim.zzbic, this.zzbim.zzbib, arrayList, this, this.zzbim.zzbii);
}
}
public final void zza(zzpm zzpm) {
if (zzpm.getStatus() == Status.RESULT_SUCCESS) {
String zzd = this.zzbim.zzazo;
zzhk.m1082v(new StringBuilder(String.valueOf(zzd).length() + 47).append("Refreshed container ").append(zzd).append(". Reinitializing runtime...").toString());
this.zzbim.zzbif.execute(new zzgm(this.zzbim, zzpm));
return;
}
this.zzbim.zzar(this.zzbim.zzbii.zzoa());
}
}
|
Markdown
|
UTF-8
| 591 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
# Cryptography-Term-Project
Implementation of the learned concepts in cryptography course on blockchain technology
## Project Overview
Implemented an algorithm for first signing any given message, then using this digital signature, generated a block of random transaction and Proof-of-Work for the block. Then integrated elliptic curve digital signature algorithm and created a blockchain by linking blocks using Proof-of-Work. More detailed information can be found in [project description](https://github.com/bubblecounter/Cryptography-Term-Project/blob/master/TermProject_Fall2018.pdf)
|
Shell
|
UTF-8
| 178 | 2.515625 | 3 |
[] |
no_license
|
# 判断build文件夹是否存在,不存在则创建
if [ ! -d "/build" ]; then
mkdir /build
fi
# 进入build
cd build
# 编译并运行
make clean
cmake ..
make
./smooth
|
C++
|
UTF-8
| 990 | 3.265625 | 3 |
[] |
no_license
|
//
// Created by Deepanshu Arora on 03/11/19.
//
class isBSTReturn{
public:
bool isBST ;
int minimum ;
int maximum ;
};
isBSTReturn isBST2(BinaryTreeNode<int>* root){
//Base Case for the Problem :
if(root==NULL){
isBSTReturn output ;
output.isBST=true ;
output.minimum=INT_MAX ;
output.maximum=INT_MIN ;
return output ;
}
isBSTReturn leftOutput = isBST2(root->left);
isBSTReturn rightOutput = isBST2(root->right);
int minimum = min(root->data,min(leftOutput.minimum,rightOutput.minimum)); //For Calculating the OverAll Minimum .
int maximum = max(root->data,max(leftOutput.maximum,rightOutput.maximum)); //For Calculating the Overall Maxium .
bool iSBSTFinal = (root->data > leftOutput.maximum) && (root->data <= rightOutput.minimum) && (leftOutput.isBST) && (rightOutput.isBST);
isBSTReturn output ;
output.minimum=minimum;
output.maximum=maximum;
output.isBST=iSBSTFinal;
return output ;
}
|
C++
|
UTF-8
| 568 | 3.015625 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int arr[15];
int check[15];
int cnt;
bool ans;
void dfs(int n)//int n
{
if (n > cnt)return;
else if (n == cnt) {
int sum1 = 0;
int sum2 = 0;
for (int i = 0; i < cnt; i++) {
if (check[i] == 1) {
sum1 += arr[i];
}
}
if (sum1 == sum2)
ans = true;
else {
sum1 = 0;
sum2 = 0;
}
}
else {
check[n] = 1;
dfs(n + 1);
check[n] = 0;
dfs(n + 1);
}
}
int main()
{
cin >> cnt;
for (int i = 0; i < cnt; i++) {
cin >> arr[i];
}
dfs(0);
if (ans == true)cout << "YES";
else cout << "NO";
}
|
Python
|
UTF-8
| 846 | 2.59375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
import signature_validation as sv
(train_datas, train_labels, train_paths) = sv.get_training_set()
(test_datas, test_labels, test_paths) = sv.get_testing_set()
def run(img_size, K, bins):
print(" Image size: {}\n K={}\n bins={}\n".format(img_size, K, bins))
for bin in bins:
matches, correct, accuracy = sv.validate_sklearn(bin, img_size, K)
print("{} | {}".format(bin, accuracy))
size=(600,200)
k=5
bins=[600, 500, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
run(size, k, bins)
size=(600,200)
k=3
bins=[600, 500, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
run(size, k, bins)
size=(400,200)
k=5
bins=[200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
run(size, k, bins)
size=(200, 100)
k=3
bins=[200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
run(size, k, bins)
|
Python
|
UTF-8
| 1,146 | 2.9375 | 3 |
[] |
no_license
|
DEFAULT_MAP = {
'open' : 'open',
'high' : 'high',
'low' : 'low',
'close' : 'close',
'volume' : 'volume'
}
def load_ohlcv(df, **kwargs):
_map = kwargs.get('column_map', DEFAULT_MAP)
if kwargs.get('symbol'):
_map = _map_symbol(kwargs.get('symbol'))
ohlcv = df[list(_map.values())].copy()
ohlcv.columns = list(_map.keys())
# Slice dataframe so that only valid indexes are kept
ohlcv = ohlcv.loc[ohlcv.first_valid_index():ohlcv.last_valid_index()]
# Check for rows containing NAN values
#null_data = ohlcv.isnull() # Returns dataframe mask where true represents missing value
# Drop nan values
ohlcv.dropna(axis='index', how='any', inplace=True)
# Determine target (Next day close so shift 1 backwards)
#target = ohlcv.close.shift(-1) # Index is already taken care of.
return ohlcv
def ohlcv_pct_change(ohlcv, periods):
# Price pct dataset is well, price from ohlcv but in percent variations
price_pct = ohlcv.pct_change(periods)
return price_pct
def _map_symbol(_sym):
return {
'open': _sym + '_Open',
'high': _sym + '_High',
'low': _sym + '_Low',
'close': _sym,
'volume': _sym + '_Volume'
}
|
Python
|
UTF-8
| 3,398 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
import tensorflow as tf
import numpy as np
from tensorflow.python.framework import tensor_shape
from tensorflow.python.util import nest
def gelu(x):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
x: float Tensor to perform activation.
Returns:
`x` with the GELU activation applied.
"""
cdf = 0.5 * (1.0 + tf.tanh(
(np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))
return x * cdf
def shape_list(x):
"""Deal with dynamic shape in tensorflow cleanly."""
static = x.shape.as_list()
dynamic = tf.shape(x)
return [dynamic[i] if s is None else s for i, s in enumerate(static)]
def get_initializer(initializer_range=0.02):
"""Creates a `tf.initializers.truncated_normal` with the given range.
Args:
initializer_range: float, initializer range for stddev.
Returns:
TruncatedNormal initializer with stddev = `initializer_range`.
"""
return tf.keras.initializers.TruncatedNormal(stddev=initializer_range)
def make_variable_state_initializer(**kwargs):
def variable_state_initializer(shape, batch_size, dtype, index):
args = kwargs.copy()
if args.get('name'):
args['name'] = args['name'] + '_' + str(index)
else:
args['name'] = 'init_state_' + str(index)
args['shape'] = shape
args['dtype'] = dtype
var = tf.get_variable(**args)
var = tf.expand_dims(var, 0)
var = tf.tile(var, tf.pack([batch_size] + [1] * len(shape)))
var.set_shape(_state_size_with_prefix(shape, prefix=[None]))
return var
return variable_state_initializer
def get_initial_cell_state(cell, initializer, batch_size, dtype):
"""Return state tensor(s), initialized with initializer.
Args:
cell: RNNCell.
batch_size: int, float, or unit Tensor representing the batch size.
initializer: function with two arguments, shape and dtype, that
determines how the state is initialized.
dtype: the data type to use for the state.
Returns:
If `state_size` is an int or TensorShape, then the return value is a
`N-D` tensor of shape `[batch_size x state_size]` initialized
according to the initializer.
If `state_size` is a nested list or tuple, then the return value is
a nested list or tuple (of the same structure) of `2-D` tensors with
the shapes `[batch_size x s]` for each s in `state_size`.
"""
state_size = cell.state_size
if nest.is_sequence(state_size):
state_size_flat = nest.flatten(state_size)
init_state_flat = [
initializer(s, batch_size, dtype, i)
for i, s in enumerate(state_size_flat)]
init_state = nest.pack_sequence_as(structure=state_size,
flat_sequence=init_state_flat)
else:
init_state_size = state_size
init_state = initializer(init_state_size, batch_size, dtype, None)
return init_state
def _generate_variable_state(batch_size_tensor, state_size, dtype):
"""Generate a variable tensor with shape [batch_size, state_size]."""
def create_variable(unnested_state_size):
flat_dims = tensor_shape.as_shape(unnested_state_size).as_list()
init_state_size = [batch_size_tensor] + flat_dims
return tf.Variable(init_state_size, dtype=dtype)
if nest.is_sequence(state_size):
return nest.map_structure(create_variable, state_size)
else:
return create_variable(state_size)
|
C#
|
UTF-8
| 998 | 2.78125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Commands {
public class Command {
protected String _Text;
public String Text {
get {
return _Text;
}
set {
_Text = value;
}
}
protected String[] _Usage;
public String[] Usage {
get {
return _Usage;
}
set {
_Usage = value;
}
}
protected String _Description;
public String Description {
get {
return _Description;
}
set {
_Description = value;
}
}
public String GetCommandName() {
return Text.ToLower().Replace(" ", "_");
}
virtual public void RunCommand(Object sender, String[] args) {
}
}
}
|
C#
|
UTF-8
| 972 | 2.84375 | 3 |
[] |
no_license
|
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NewsManagementDotNetCoreApp.Extensions
{
public static class IEnumerableExtension
{
public static IEnumerable<SelectListItem> AnarKerimov<T>(this IEnumerable<T> items, int selectedValue)
{
return from item in items
select new SelectListItem
{
Text = item.AnarKerimovSecirDeyiskenleri("Name"),
Value = item.AnarKerimovSecirDeyiskenleri("ID"),
Selected = item.AnarKerimovSecirDeyiskenleri("ID").Equals(selectedValue.ToString())
};
}
public static string AnarKerimovSecirDeyiskenleri<T>(this T item, string propertyName)
{
return item.GetType().GetProperty(propertyName).GetValue(item, null).ToString();
}
}
}
|
C++
|
UTF-8
| 1,046 | 2.5625 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string s;
int x,y;
vector < int > mv[2];
bool is_possible(int ind, int M)
{
int sm[9000];
for(int i = 0 ; i < 9000;++i)
sm[i] = 0;
sm[0] = 1;
int SM = 0;
for(int i = (ind == 0? 1:0); i< mv[ind].size();++i)
{
SM += mv[ind][i];
for(int j = 8999;j>=mv[ind][i];--j)
if(sm[j-mv[ind][i]] == 1)
sm[j] = 1;
}
//cout << SM << ' ' << M << endl;
if((M >=0 && SM < M) || (M < 0 && SM < -M) )
return false;
if((M >= 0 && ((SM-M)&1)==0 &&sm[(SM-M)/2]==1) || (M < 0 && ((-M+SM)&1) == 0 && sm[(-M+SM)/2]==1))
return true;
return false;
}
int main() {
cin >> s;
cin >> x >> y;
int ind = 0, sm = 0;
for(int i = 0 ; i < s.length();++i)
{
if(s[i]=='T')
{
if(i==0)
mv[ind].push_back(0);
if(sm != 0)
mv[ind].push_back(sm);
ind ^=1;
sm = 0;
continue;
}
sm+=1;
}
if(sm!=0)
mv[ind].push_back(sm);
if(is_possible(0,x-mv[0][0]) && is_possible(1,y))
cout << "Yes\n";
else
cout << "No\n";
// your code goes here
return 0;
}
|
Python
|
UTF-8
| 500 | 2.953125 | 3 |
[] |
no_license
|
# day 40 2019-06-18 Tue
# 217. Contains Duplicate
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
# if len(nums) < 2:
# return False
# nums.sort();
# ahead = nums[0]
# behind = nums[1]
# for i in nums[2:]:
# if ahead == behind: return True
# behind = ahead
# ahead = i
# if behind == ahead: return True
# return False
return len(nums) > len(set(nums))
|
Java
|
UTF-8
| 782 | 2.171875 | 2 |
[] |
no_license
|
package com.example.vinove.listdemo_1;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lview = findViewById(R.id.lview1);
String path = "/storage/emulated/0/";
File f = new File(path);
String[] files = f.list();
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, files);
lview.setAdapter(adapter);
}
}
|
Java
|
UTF-8
| 2,068 | 1.914063 | 2 |
[] |
no_license
|
package com.ta.d3ti.wisnupamungkas.rekammediskeluarga;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.EditText;
public class LihatDetailKandunganActivity extends AppCompatActivity {
protected EditText tanggal_periksa;
protected EditText bulan_hamil;
protected EditText kondisi_janin;
protected String isi_id_detail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lihat_detail_kandungan);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
this.tanggal_periksa = (EditText) findViewById(R.id.tgl_periksa);
this.bulan_hamil = (EditText) findViewById(R.id.bln_hamil);
this.kondisi_janin = (EditText) findViewById(R.id.kondisi);
Bundle b = getIntent().getExtras();
isi_id_detail = b.getString("id_detail");
String isi_tanggal = b.getString("tanggal_periksa");
String isi_bulan = b.getString("bulan_hamil");
String isi_kondisi = b.getString("kondisi_janin");
this.tanggal_periksa.setText(isi_tanggal);
this.bulan_hamil.setText(isi_bulan);
this.kondisi_janin.setText(isi_kondisi);
}
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
finish();
}
}
|
C++
|
UTF-8
| 542 | 2.6875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <string.h>
int main()
{
int k = 0,n;
int a[105];
char s[100000];
printf("PERFECTION OUTPUT\n");
while(~scanf("%d",&n),n)
{
int sum = 1,j;
for(j = 2; j<=n/2; j++)
{
if(n%j == 0)
sum+=j;
}
printf("%5d ",n);
if(sum == n)
printf("PERFECT\n");
else if(sum < n)
printf("DEFICIENT\n");
else
printf("ABUNDANT\n");
}
printf("END OF OUTPUT\n");
return 0;
}
|
Python
|
UTF-8
| 925 | 3.546875 | 4 |
[] |
no_license
|
def find_range(arr, key):
start, end = 0, len(arr) - 1
startKey, endKey = -1, -1
while start <= end:
mid = int((start+end)/2)
#print (start, end, mid)
if arr[mid] == key:
startKey = mid
break
elif arr[mid] < key:
start = mid + 1
else:
end = mid - 1
endKey = startKey
#print (startKey, endKey)
while endKey < len(arr):
if arr[endKey] != key:
#print (arr[endKey])
endKey -= 1
break
endKey += 1
#print(startKey, endKey)
while startKey >= 0:
if arr[startKey] != key:
startKey += 1
break
startKey -= 1
#print(startKey, endKey)
return [startKey, endKey]
def main():
print(find_range([4, 6, 6, 6, 9], 6))
print(find_range([1, 3, 8, 10, 15], 10))
print(find_range([1, 3, 8, 10, 15], 12))
main()
|
C
|
UTF-8
| 548 | 2.765625 | 3 |
[] |
no_license
|
#include <stdio.h>
#if 0
int main ()
{
int n[10];
printf ("%d", sizeof(n));
printf ("%d", sizeof(&n));
printf ("%d", (++ n));
printf ("%d", ++ &n);
return 0;
}
#endif
#if 0
int main ()
{
char c = -20;
printf ("0x%08x", c);
return 0;
}
#endif
# if 0
int main ()
{
int n;
char *str = "9999999999";
n = atoi(str);
printf ("%d", n);
return 0;
}
#endif
#if 0
int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 10;
int main (void)
{
return 0;
}
#endif
#if 1
int main ()
{
int a[1] = {1};
a[3] = 12;
return 0;
}
#endif
|
Java
|
UTF-8
| 2,698 | 3.734375 | 4 |
[
"MIT"
] |
permissive
|
package com.guann1n9.leetcode.problems.backtrack;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
*
* 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
*
*
* 0 <= digits.length <= 4
* digits[i] 是范围 ['2', '9'] 的一个数字。
*
*
* 示例 1:
*
* 输入:digits = "23"
* 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
* 示例 2:
*
* 输入:digits = ""
* 输出:[]
* 示例 3:
*
* 输入:digits = "2"
* 输出:["a","b","c"]
*/
public class PhoneChar {
/**
* 回溯算法实际上一个类似枚举的搜索尝试过程,主要是在搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就 “回溯” 返回,尝试别的路径
* @param digits
* @return
*/
public static List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
//边界处理
if(digits == null || digits.length() == 0){
return list;
}
//数字字符映射
HashMap<Character, String> map = new HashMap<>();
map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");
//从第0个字符回溯
backTrack(0,map,digits,new StringBuilder(),list);
return list;
}
/**
*
* @param idx 回溯的位置
* @param map 映射集
* @param digits 号码
* @param builder 正在回溯的字符串
*/
private static void backTrack(int idx, Map<Character, String> map,String digits, StringBuilder builder,List<String> list){
//已遍历完号码
if(idx == digits.length()){
list.add(builder.toString());
return;
}
char c = digits.charAt(idx);
//遍历所有可能
String chars = map.get(c);
for (char temp : chars.toCharArray()) {
builder.append(temp);
//递归 下一个数字的映射
backTrack(idx+1,map,digits,builder,list);
//移除递归拼接的字符,开始下一轮
builder.deleteCharAt(idx);
}
}
public static void main(String[] args) {
List<String> list = letterCombinations("23");
System.out.println(JSON.toJSONString(list));
}
}
|
Java
|
UTF-8
| 2,667 | 2.375 | 2 |
[] |
no_license
|
package com.example.omar.energy4.ui;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.simplelist.MaterialSimpleListAdapter;
import com.afollestad.materialdialogs.simplelist.MaterialSimpleListItem;
import com.example.omar.energy4.R;
public class SettingUp2Activity extends AppCompatActivity {
private String[] roomName = {
"Bed Room", "Living Room","Office",
"Kitchen", "Path Room" };
private int[] roomImageId = {
R.drawable.bed_512, R.drawable.armchair_512, R.drawable.office_512,
R.drawable.refrigerator_512, R.drawable.pathroom_512};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting_up2);
}
public void addRoom(View view) {
final MaterialSimpleListAdapter adapter = new MaterialSimpleListAdapter(new MaterialSimpleListAdapter.Callback() {
@Override
public void onMaterialListItemSelected(MaterialDialog dialog, int index, MaterialSimpleListItem item) {
Toast.makeText(getApplicationContext(), "You selected: " + item.getContent() , Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
adapter.add(new MaterialSimpleListItem.Builder(this)
.content(roomName[0])
.icon(roomImageId[0])
.backgroundColor(Color.WHITE)
.build());
adapter.add(new MaterialSimpleListItem.Builder(this)
.content(roomName[1])
.icon(roomImageId[1])
.backgroundColor(Color.WHITE)
.build());
adapter.add(new MaterialSimpleListItem.Builder(this)
.content(roomName[2])
.icon(roomImageId[2])
.backgroundColor(Color.WHITE)
.build());
adapter.add(new MaterialSimpleListItem.Builder(this)
.content(roomName[3])
.icon(roomImageId[3])
.backgroundColor(Color.WHITE)
.build());
adapter.add(new MaterialSimpleListItem.Builder(this)
.content(roomName[4])
.icon(roomImageId[4])
.backgroundColor(Color.WHITE)
.build());
new MaterialDialog.Builder(this)
.title("Select Room")
.adapter(adapter, null)
.show();
}
}
|
TypeScript
|
UTF-8
| 2,644 | 2.890625 | 3 |
[] |
no_license
|
/// <reference path="../../../globals.d.ts" />
/// <reference path="./asynctestcase.d.ts" />
/// <reference path="../../../third_party/closure/goog/mochikit/async/deferred.d.ts" />
declare module goog.testing {
class DeferredTestCase extends DeferredTestCase__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class DeferredTestCase__Class extends goog.testing.AsyncTestCase__Class {
/**
* A test case that can asynchronously wait on a Deferred object.
* @param {string=} opt_name A descriptive name for the test case.
* @constructor
* @extends {goog.testing.AsyncTestCase}
*/
constructor(opt_name?: string);
/**
* Handler for when the test produces an error.
* @param {Error|string} err The error object.
* @protected
* @throws Always throws a ControlBreakingException.
*/
onError(err: Error|string): void;
/**
* Handler for when the test succeeds.
* @protected
*/
onSuccess(): void;
/**
* Adds a callback to update the wait message of this async test case. Using
* this method generously also helps to document the test flow.
* @param {string} msg The update wait status message.
* @param {goog.async.Deferred} d The deferred object to add the waitForAsync
* callback to.
* @see goog.testing.AsyncTestCase#waitForAsync
*/
addWaitForAsync(msg: string, d: goog.async.Deferred<any>): void;
/**
* Wires up given Deferred object to the test case, then starts the
* goog.async.Deferred object's callback.
* @param {!string|goog.async.Deferred} a The wait status message or the
* deferred object to wait for.
* @param {goog.async.Deferred=} opt_b The deferred object to wait for.
*/
waitForDeferred(a: string|goog.async.Deferred<any>, opt_b?: goog.async.Deferred<any>): void;
}
}
declare module goog.testing.DeferredTestCase {
/**
* Preferred way of creating a DeferredTestCase. Creates one and initializes it
* with the G_testRunner.
* @param {string=} opt_name A descriptive name for the test case.
* @return {!goog.testing.DeferredTestCase} The created DeferredTestCase.
*/
function createAndInstall(opt_name?: string): goog.testing.DeferredTestCase;
}
|
Python
|
UTF-8
| 312 | 3.671875 | 4 |
[] |
no_license
|
year_start = int(input("Insert year: "))
if( (year_start % 4) == 0):
if ( (year_start % 100 ) == 0):
if ( (year_start % 400) == 0):
print("Is leap year!")
else:
print("Is not leap year!")
else:
print("Is leap year!")
else:
print("Is not leap year!")
|
Java
|
UTF-8
| 1,481 | 2.234375 | 2 |
[] |
no_license
|
package com.xjl.order;
import com.google.common.collect.Maps;
import java.util.Map;
/**
*
* 订单提交模板
*
* @Auther: xiaojinlu1990@163.partten
* @Date: 2020/6/11 22:06
* @Description:
*/
public abstract class HotelOrder {
private ApplicationReturn applicationReturn;
private ProductReturn productReturn;
public ApplicationReturn getApplicationReturn() {
return applicationReturn;
}
public void setApplicationReturn(ApplicationReturn applicationReturn) {
this.applicationReturn = applicationReturn;
}
public ProductReturn getProductReturn() {
return productReturn;
}
public void setProductReturn(ProductReturn productReturn) {
this.productReturn = productReturn;
}
//检验申请单
abstract void chackApplication(OrderParameter orderParameter);
//检验入住人
abstract void checkInPerson(OrderParameter orderParameter);
//检验控制点信息
abstract void chackControllerMessage(OrderParameter orderParameter);
//入库信息
abstract void insertMysql(OrderParameter orderParameter);
public Map bookOrder(OrderParameter orderParameter) {
//检验申请单
chackApplication(orderParameter);
//检验入住人
checkInPerson(orderParameter);
//检验控制点信息
chackControllerMessage(orderParameter);
//入库信息
insertMysql(orderParameter);
return Maps.newConcurrentMap();
}
}
|
C++
|
UTF-8
| 2,325 | 2.703125 | 3 |
[] |
no_license
|
#ifndef _NocheckWriteChannel_h_
#define _NocheckWriteChannel_h_
#include "../cPrimitiveTypes.h"
#include "NocheckUnidirectionalChannel.h"
class NocheckPacket;
class NocheckPacketLayer;
//------------------------------------------------------------------------------------------------
// * class NocheckWriteChannel
//
// Represents a write-only communication stream.
//------------------------------------------------------------------------------------------------
class NocheckWriteChannel : public NocheckUnidirectionalChannel
{
public:
// constructor and destructor
NocheckWriteChannel(NocheckPacketLayer &packetLayer, UInt channelId);
virtual ~NocheckWriteChannel();
// streaming
inline UInt read(void *pDestination, UInt length);
inline UInt read(void *pDestination, UInt length, TimeValue timeout);
inline UInt write(const void *pSource, UInt length);
UInt write(const void *pSource, UInt length, TimeValue timeout);
void flush() {};
// error related
void reset();
};
//------------------------------------------------------------------------------------------------
// * NocheckWriteChannel::read
//
// Read data from the channel.
//------------------------------------------------------------------------------------------------
inline UInt NocheckWriteChannel::read(void *pDestination, UInt length)
{
pDestination = pDestination;
length = length;
return 0;
}
//------------------------------------------------------------------------------------------------
// * NocheckWriteChannel::read
//
// Read data from the channel.
//------------------------------------------------------------------------------------------------
inline UInt NocheckWriteChannel::read(void *pDestination, UInt length, TimeValue timeout)
{
pDestination = pDestination;
length = length;
timeout = timeout;
return 0;
}
//------------------------------------------------------------------------------------------------
// * NocheckWriteChannel::write
//
// Writes data to the channel.
//------------------------------------------------------------------------------------------------
inline UInt NocheckWriteChannel::write(const void *pSource, UInt length)
{
return write(pSource, length, defaultTimeout);
}
#endif // _NocheckWriteChannel_h_
|
Markdown
|
UTF-8
| 1,412 | 2.921875 | 3 |
[] |
no_license
|
# Medidas de posição e Dispersão
## Média, Mediana e Moda
O objetivo desta tarefa é gerar as estatísticas para o atributo age da base de dados do censo
Carregue o arquivo census.csv
Calcule a média aritmética, média harmônica, média geométrica, média quadrática, a mediana e a moda. Compare os resultados
## Avaliação de Algoritmos de Machine Learning
Nas aulas anteriores você aprendeu a dividir a base de dados entre treinamento e teste para avaliar os algoritmos de classificação. Porém, existe uma outra técnica que é mais utilizada no meio científico, que é a validação cruzada. Na próxima aula, você terá uma breve introdução teórica a esta técnica
O objetivo deste exercício é aplicar a validação cruzada e comparar os resultados com a abordagem de treinamento e teste. Acesse [aqui](https://scikit-learn.org/stable/modules/cross_validation.html) a documentação do sklearn para entender melhor sobre a implementação
## Seleção de Atributos com Variância
O objetivo deste exercício é utilizar a base de dados do crédito e aplicar a técnica de seleção de atributos utilizando variância
Carregue o arquivo credit_data.csv
Calcule a variância para os atributos income, age e loan e aplique o método de seleção Low Variance
Faça um teste do accuracy utilizando o algoritmo Naïve Bayes, sem seleção de atributos e com seleção de atributos
|
Markdown
|
UTF-8
| 15,609 | 3.09375 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] |
permissive
|
# 0519: Goal Codes
- Authors: [Daniel Hardman](daniel.hardman@gmail.com)
- Status: [ACCEPTED](/README.md#accepted)
- Since: 2021-04-15
- Status Note: Used in several protocols that are part of [AIP 2.0](../0302-aries-interop-profile/README.md), such as the [Out-of-Band](../../features/0434-outofband/README.md) protocol.
- Start Date: 2020-01-01
- Tags: [concept](/tags.md#concept)
## Summary
Explain how different parties in an SSI ecosystem can communicate about their intentions in a way that is understandable by humans and by automated software.
## Motivation
[Agents](../0004-agents/README.md) exist to achieve the intents of their owners. Those intents largely unfold through [protocols](../0003-protocols/README.md). Sometimes intelligent action in these protocols depends on a party declaring their intent. We need a standard way to do that.
## Tutorial
Our early learnings in SSI focused on VC-based proving with a very loose, casual approach to context. We did demos where Alice connects with a potential employer, Acme Corp -- and we assumed that each of the interacting parties had a shared understanding of one another's needs and purposes.
But in a mature SSI ecosystem, where unknown agents can contact one another for arbitrary reasons, this context is not always easy to deduce. Acme Corp's agent may support many different protocols, and Alice may interact with Acme in the capacity of customer or potential employee or vendor. Although we have [feature discovery](../../features/0031-discover-features/README.md) to learn what's possible, and we have [machine-readable governance frameworks](../0430-machine-readable-governance-frameworks/README.md) to tell us what rules might apply in a given context, we haven't had a way to establish the context in the first place. When Alice contacts Acme, a context is needed before a governance framework is selectable, and before we know which features are desirable.
The key ingredient in context is __intent__. If Alice says to Acme, "I'd like to connect,", Acme wants to be able to trigger different behavior depending on whether Alice's intent is to be a customer, apply for a job, or audit Acme's taxes. This is the purpose of a goal code.
### The goal code datatype
To express intent, this RFC formally introduces the goal code datatype. When a field in a [DIDComm](../0005-didcomm/README.md) message contains a goal code, its semantics and format match the description given here. (Goal codes are often declared via the `~thread` decorator, but may also appear in ordinary message fields. See the [Scope section](#scope) below. Convention is to name this field "goal_code" where possible; however, this is only a convention, and individual protocols may adapt to it however they wish.)
>TODO: should we make a decorator out of this, so protocols don't have to declare it, and so any message can have a goal code? Or should we just let protocols declare a field in whatever message makes sense?
Protocols use fields of this type as a way to express the intent of the message sender, thus coloring the larger context. In a sense, goal codes are to DIDComm what the `subject:` field is to email -- except that goal codes have formalized meanings to make them recognizable to automation.
Goal codes use a standard format. They are lower-cased, kebab-punctuated strings. ASCII and English are recommended, as they are intended to be read by the software developer community, not by human beings; however, full UTF-8 is allowed. They support hierarchical dotted notation, where more general categories are to the left of a dot, and more specific categories are to the right. Some example goal codes might be:
* `aries.sell.consumer.fitness`
* `meetupcorp.personal.date`
* `dif.employment.check-references`
* `cci.healthcare.arrange`
Goals are inherently self-attested. Thus, goal codes don't represent objective fact that a recipient can rely upon in a strong sense; subsequent interactions can always yield surprises. Even so, goal codes let agents triage interactions and find misalignments early; there's no point in engaging if their goals are incompatible. This has significant benefits for spam prevention, among other things.
### Verbs
Notice the verbs in the examples: `sell`, `date`, `hire`, and `arrange`. Goals typically involve action; a complete goal code should have one or more verbs in it somewhere. Turning verbs into nouns (e.g., `employment.references` instead of `employment.check-references`) is considered bad form. (Some namespaces may put the verbs at the end; some may put them in the middle. That's a purely stylistic choice.)
### Directionality
Notice, too, that the verbs may imply directionality. A goal with the `sell` verb implies that the person announcing the goal is a would-be seller, not a buyer. We could imagine a more general verb like `engage-in-commerce` that would allow either behavior. However, that would often be a mistake. The value of goal codes is that they let agents align around intent; announcing that you want to engage in general commerce without clarifying whether you intend to sell or buy may be too vague to help the other party make decisions.
It is conceivable that this would lead to parallel branchs of a goal ontology that differ only in the direction of their verb. Thus, we could imagine `sell.A` and `sell.B` being shadowed by `buy.A` and `buy.B`. This might be necessary if a family of protocols allow either party to initiate an interaction and declare the goal, and if both parties view the goals as perfect mirror images. However, practical considerations may make this kind of parallelism unlikely. A random party contacting an individual to sell something may need to be quite clear about the type of selling they intend, to make it past a spam filter. In contrast, a random individual arriving at the digital storefront of a mega retailer may be quite vague about the type of buying they intend. Thus, the `buy.*` side of the namespace may need much less detail than the `sell.*` side.
### Goals for others
Related to directionality, it may occasionally be desirable to propose goals to others, rather than adovcating your own: "Let <parties = us = Alice, Bob, and Carol> <goal = hold an auction> -- I nominate Carol to be the <role = auctioneer> and get us started." The difference between a normal message and an unusual one like this is not visible in the goal code; it should be exposed in additional fields that associate the goal with a particular identifier+role pair. Essentially, you are proposing a goal to another party, and these extra fields clarify who should receive the proposal, and what role/perspective they might take with respect to the goal.
Making proposals like this may be a feature in some protocols. Where it is, the protocols determine the message field names for the goal code, the role, and the DID associated with the role and goal.
### Matching
The goal code `cci.healthcare` is considered a more general form of the code `cci.healthcare.procedure`, which is more general than `cci.healthcare.procedure.schedule`. Because these codes are hierarchical, wildcards and fuzzy matching are possible for either a sender or a recipient of a message. Filename-style globbing semantics are used.
A sender agent can specify that their owner's goal is just `meetupcorp.personal` without clarifying more; this is like specifying that a file is located under a folder named "meetupcorp/personal" without specifying where; any file "under" that folder -- or the folder itself -- would match the pattern. A recipient agent can have a policy that says, "Reject any attempts to connect if the goal code of the other party is `aries.sell.*`. Notice how this differs from `aries.sell*`; the first looks for things "inside" `aries.sell`; the latter looks for things "inside" `aries` that have names beginning with `sell`.
### Scope
When is a declared goal known to color interactions, and when is it undefined?
We previously noted that goal codes are a bit like the `subject:` header on an email; they contextualize everything that follows *in that thread.* We don't generally want to declare a goal outside of a thread context, because that would prevent an agent from engaging in two goals at the same time.
Given these two observations, we can say that a goal applies as soon as it is declared, and it continues to apply to all messages in the same thread. It is also inherited by implication through a thread's `pthid` field; that is, a parent thread's goal colors the child thread unless/until overridden.
### Namespacing
To avoid collision and ambiguity in code values, we need to support namespacing in our goal codes. Since goals are only a coarse-grained alignment mechanism, however, we don't need perfect decentralized precision. Confusion isn't much more than an annoyance; the worst that could happen is that two agents discover one or two steps into a protocol that they're not as aligned as they supposed. They need to be prepared to tolerate that outcome in any case.
Thus, we follow the same general approach that's used in java's packaging system, where organizations and communities use a self-declared prefix for their ecosystem as the leftmost segment or segments of a family of identifiers (goal codes) they manage. Unlike java, though, these need not be tied to DNS in any way. We recommend a single segment namespace that is a unique string, and that is an alias for a URI identifying the origin ecosystem. (In other words, you don't need to start with "com.yourcorp.yourproduct" -- "yourcorp" is probably fine.)
The `aries` namespace alias is reserved for goal codes defined in Aries RFCs. The URI aliased by this name is TBD. See the [Reference section](#reference) for more details.
### Versioning
Semver-style semantics don't map to goals in an simple way; it is not obvious what constitutes a "major" versus a "minor" difference in a goal, or a difference that's not worth tracking at all. The content of a goal — the only thing that might vary across versions — is simply its free-form description, and that varies according to human judgment. Many different versions of a protocol are likely to share the goal to make a payment or to introduce two strangers. A goal is likely to be far more stable than the details of how it is accomplished.
Because of these considerations, goal codes do not impose an explicit versioning mechanism. However, one is reserved for use, in the unusual cases where it may be helpful. It is to append `-v` plus a numeric suffix: `my-goal-code-v1`, `my-goal-code-v2`, etc. Goal codes that vary only by this suffix should be understood as ordered-by-numeric-suffix evolutions of one another, and goal codes that do not intend to express versioning should not use this convention for something else. A variant of the goal code without any version suffix is equivalent to a variant with the `-v1` suffix. This allows human intuition about the relatedness of different codes, and it allows useful wildcard matching across versions. It also treats all version-like changes to a goal as breaking (semver "major") changes, which is probably a safe default.
Families of goal codes are free to use this convention if they need it, or to invent a non-conflicting one of their own. However, we repeat our observation that versioning in goal codes is often inappropriate and unnecessary.
### Declaring goal codes
#### Standalone RFCs or Similar Sources
Any URI-referencable document can declare famlies or ontologies of goal codes. In the context of Aries, we encourage standalone RFCs for this purpose if the goals seem likely to be relevant in many contexts. Other communities may of course document goal codes in their own specs -- either dedicated to goal codes, or as part of larger topics. The following block is a sample of how we recommend that such goal codes be declared. Note that each code is individually hyperlink-able, and each is associated with a brief human-friendly description in one or more languages. This description may be used in menuing mechanisms such as the one described in [Action Menu Protocol](../../features/0509-action-menu/README.md).
>#### goal codes
>##### `aries.sell`
>__en__: Sell something. Assumes two parties (buyer/seller).
>__es__: Vender algo. Asume que dos partes participan (comprador/vendedor).
>##### `aries.sell.goods.consumer`
>en: Sell tangible goods of interest to general consumers.
>##### `aries.sell.services.consumer`
>en: Sell services of interest to general consumers.
>##### `aries.sell.services.enterprise`
>en: Sell services of interest to enterprises.
#### In DIDComm-based Protocol Specs
Occasionally, goal codes may have meaning only within the context of a specific protocol. In such cases, it may be appropriate to declare the goal codes directly in a protocol spec. This can be done using a section of the RFC as described above.
More commonly, however, a protocol will *accomplish* one or more goals (e.g., when the protocol is fulfilling a co-protocol interface), or will require a participant to *identify* a goal at one or more points in a protocol flow. In such cases, the goal codes are probably declared external to the protocol. If they can be enumerated, they should still be referenced (hyperlinked to their respective definitions) in the protocol RFC.
#### In Governance Frameworks
Goal codes can also be (re-)declared in a [machine-readable governance framework](../0430-machine-readable-governance-frameworks/README.md).
## Reference
#### Known Namespace Aliases
No central registry of namespace aliases is maintained; you need not register with an authority to create a new one. Just pick an alias with good enough uniqueness, and socialize it within your community. For convenience of collision avoidance, however, we maintain a table of aliases that are typically used in global contexts, and welcome PRs from anyone who wants to update it.
alias | used by | URI
-- | -- | --
aries | Hyperledger Aries Community | TBD
#### Well-known goal codes
The following goal codes are defined here because they already have demonstrated utility, based on early SSI work in Aries and elsewhere.
##### `aries.vc`
Participate in some form of VC-based interaction.
##### `aries.vc.issue`
Issue a verifiable credential.
##### `aries.vc.verify`
Verify or validate VC-based assertions.
##### `aries.vc.revoke`
Revoke a VC.
##### `aries.rel`
Create, maintain, or end something that humans would consider a relationship.
This may be accomplished by establishing, updating or deleting a DIDComm
messaging connection that provides a secure communication channel for the
relationship. The DIDComm connection itself is not the relationship, but would
be used to carry out interactions between the parties to facilitate the
relationship.
##### `aries.rel.build`
Create a relationship. Carries the meaning implied today by a LinkedIn
invitation to connect or a Facebook "Friend" request. Could be as limited
as creating a DIDComm Connection.
## Implementations
The following lists the implementations (if any) of this RFC. Please do a pull request to add your implementation. If the implementation is open source, include a link to the repo or to the implementation within the repo. Please be consistent in the "Name" field so that a mechanical processing of the RFCs can generate a list of all RFCs supported by an Aries implementation.
*Implementation Notes* [may need to include a link to test results](/README.md#accepted).
Name / Link | Implementation Notes
--- | ---
|
|
Java
|
UTF-8
| 701 | 2.09375 | 2 |
[] |
no_license
|
package br.com.sysdesc.pesquisa.components.buttonactions;
import java.awt.event.KeyEvent;
public class ButtonActionAvancar extends ButtonAction {
private static final long serialVersionUID = 1L;
public ButtonActionAvancar() {
super("mapAvancar", KeyEvent.VK_PAGE_UP, 0, "next.png", "Avançar");
}
@Override
public void saveEvent() {
setEnabled(Boolean.TRUE);
}
@Override
public void editEvent() {
setEnabled(Boolean.TRUE);
}
@Override
public void newEvent() {
setEnabled(Boolean.TRUE);
}
@Override
public void searchEvent() {
setEnabled(Boolean.TRUE);
}
@Override
public void startEvent() {
setEnabled(Boolean.TRUE);
}
}
|
JavaScript
|
UTF-8
| 659 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
Template.classicSong.onRendered(function() {
var data = this.data;
console.log(data);
var rows = Math.ceil(data.notation.length/returnColNumber(data.taalName));
console.log(rows , " rows -------------");
$(function(){
//console.log(this , " what is this here");
//True indicates whether we want to add the row button below
createNotation(data.taalName,false,rows);
fillNotation(data.notation);
});
});
Template.classicSong.events({
'click .playBtn' : function(tmpl , e ) {
console.log(obj);
var obj = {};
obj.language = this.language;
obj.tempo = this.tempo;
obj.notation = this.notation;
playNotationFromData(obj);
}
})
|
JavaScript
|
UTF-8
| 7,833 | 3.0625 | 3 |
[] |
no_license
|
import React, { useEffect, useRef } from 'react'
const DequeCanvas = ({ dequeItems }) => {
const canvasRef = useRef(null);
useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
const canvasWidth = canvas.offsetWidth;
const canvasHeight = canvas.offsetHeight;
canvas.style.width = '100%';
canvas.style.height = '100%';
canvas.width = canvasWidth;
canvas.height = canvasHeight;
draw(ctx, canvasWidth, canvasHeight);
}, [dequeItems]);
const draw = (ctx, canvasWidth, canvasHeight) => {
let startingPointX;
let startingPointY;
let containerWidth;
let containerHeight;
let fontSize = 16;
if (canvasWidth >= 1408) { // 1440px wide of display
startingPointX = canvasWidth * 0.1;
startingPointY = canvasHeight * 0.1;
containerWidth = canvasWidth * 0.8;
containerHeight = canvasHeight * 0.5;
}
else if (canvasWidth >= 992) { // 1024px wide of display
startingPointX = canvasWidth * 0.08;
startingPointY = canvasHeight * 0.1;
containerWidth = canvasWidth * 0.84;
containerHeight = canvasHeight * 0.5;
}
else if (canvasWidth >= 736) { // 768px wide of display
startingPointX = canvasWidth * 0.06;
startingPointY = canvasHeight * 0.1;
containerWidth = canvasWidth * 0.88;
containerHeight = canvasHeight * 0.5;
}
else if (canvasWidth >= 393) { // 425px wide of display
startingPointX = canvasWidth * 0.03;
startingPointY = canvasHeight * 0.1;
containerWidth = canvasWidth * 0.94;
containerHeight = canvasHeight * 0.5;
}
else { // narrower than 425px wide
startingPointX = canvasWidth * 0.02;
startingPointY = canvasHeight * 0.1;
containerWidth = canvasWidth * 0.96;
containerHeight = canvasHeight * 0.5;
}
const queueSize = dequeItems.length - 1;
dequeItems.forEach((dequeData, i) => {
ctx.textAlign = 'start';
ctx.font = `normal ${fontSize}px sans-serif`;
// each queue item's size property
const dequeItemGap = containerWidth * 0.01;
const dequeItemWidth = containerWidth * 0.091;
const dequeItemHeight = containerHeight * 0.86;
// "staring x, y point of each queue item"
const dequeItemStartX = startingPointX + (dequeItemGap + dequeItemWidth) * i;
const dequeItemStartY = startingPointY + containerHeight * 0.07;
const leftForwardArrowX = 30;
const rightForwardArrowX = startingPointX + containerWidth + 30;
const forwardArrowY = startingPointY + containerHeight / 3;
const backwardArrowY = startingPointY + containerHeight / 3 * 2;
if (i === 0) { // draw container only if it's first time to render
if (canvasWidth >= 1408) {
// forward arrow (->) at the left side
drawForwardArrow(ctx, leftForwardArrowX, forwardArrowY, leftForwardArrowX + 60, forwardArrowY);
// forward arrow (->) at the right side
drawForwardArrow(ctx, rightForwardArrowX, forwardArrowY, rightForwardArrowX + 60, forwardArrowY)
// backward arrow (<-) at the left side
drawBackwardArrow(ctx, leftForwardArrowX, backwardArrowY, leftForwardArrowX + 60, backwardArrowY);
// backward arrow (<-) at the right side
drawBackwardArrow(ctx, rightForwardArrowX, backwardArrowY, rightForwardArrowX + 60, backwardArrowY);
}
drawDequeContainer(ctx, startingPointX, startingPointY, containerWidth, containerHeight);
// draw 'front' text above the container
drawFrontText(ctx, startingPointX, startingPointY - 10, dequeItemWidth);
}
drawDequeItem(ctx, dequeItemWidth, dequeItemHeight, dequeItemStartX, dequeItemStartY);
const printX = startingPointX + dequeItemWidth * 0.07 + (dequeItemGap + dequeItemWidth) * i;
const printY = startingPointY + containerHeight * 0.15;
const maxWidthOfData = dequeItemWidth * 0.9; // maximum width of data inside of each nodes
printData(ctx, dequeData, printX, printY, 18, maxWidthOfData);
if (i === queueSize) {
// draw 'back' text below the container
drawBackText(ctx, startingPointX, startingPointY, dequeItemWidth, dequeItemGap, containerHeight, i);
}
});
}
const drawDequeContainer = (ctx, startX, startY, containerWidth, containerHeight) => {
ctx.lineWidth = 7;
// upper side of the queue container
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(startX + containerWidth, startY);
// bottom side of the queue container
ctx.moveTo(startX, startY + containerHeight);
ctx.lineTo(startX + containerWidth, startY + containerHeight);
ctx.stroke();
}
const drawDequeItem = (ctx, dequeItemWidth, dequeItemHeight, dequeItemStartX, dequeItemStartY) => {
ctx.fillStyle = "#F18677";
ctx.fillRect(dequeItemStartX, dequeItemStartY, dequeItemWidth, dequeItemHeight);
}
function printData(context, text, x, y, lineHeight, fitWidth = 0, lineNum = 0) {
context.fillStyle = "#000";
// if text's width is 0, no need to wrap data
if (fitWidth <= 0) {
context.fillText(text, x, y);
return;
}
// divide data until the substring's width is longer than the specified width
for (let i = 1; i <= text.length; i++) {
let str = text.substr(0, i);
if (context.measureText(str).width > fitWidth) {
if (lineNum < 15) { // truncate data from line number 15
context.fillText(text.substr(0, i - 1), x, y);
}
else {
context.fillText('', x, y);
}
printData(context, text.substr(i - 1), x, y + lineHeight, lineHeight, fitWidth, lineNum + 1);
return;
}
}
if (lineNum < 15) { // truncate data from line number 15
context.fillText(text, x, y);
}
else {
context.fillText('', x, y);
}
}
const drawFrontText = (ctx, startX, startY, itemWidth) => {
ctx.fillStyle = 'red';
const frontTextWidth = ctx.measureText('front').width;
const frontX = startX + (itemWidth - frontTextWidth) / 2;
const frontY = startY;
ctx.fillText('Front', frontX, frontY);
}
const drawBackText = (ctx, startX, startY, itemWidth, itemGap, containerHeight, index) => {
ctx.fillStyle = 'red';
const rearTextWidth = ctx.measureText('Back').width;
const rearX = startX + (itemWidth - rearTextWidth) / 2 + (itemGap + itemWidth) * index;
const rearY = startY + containerHeight + 20;
ctx.fillText('Back', rearX, rearY);
}
const drawForwardArrow = (ctx, fromX, fromY, toX, toY) => {
ctx.beginPath();
let headlen = 9; // length of head in pixels
let dx = toX - fromX;
let dy = toY - fromY;
let angle = Math.atan2(dy, dx);
ctx.strokeStyle = "#000";
ctx.moveTo(fromX, fromY);
ctx.lineTo(toX, toY);
ctx.lineTo(toX - headlen * Math.cos(angle - Math.PI / 6), toY - headlen * Math.sin(angle - Math.PI / 6));
ctx.moveTo(toX, toY);
ctx.lineTo(toX - headlen * Math.cos(angle + Math.PI / 6), toY - headlen * Math.sin(angle + Math.PI / 6));
ctx.stroke();
ctx.closePath();
}
const drawBackwardArrow = (ctx, fromX, fromY, toX, toY) => {
ctx.beginPath();
let headlen = 9; // length of head in pixels
let dx = fromX - toX;
let dy = fromY - toY;
let angle = Math.atan2(dy, dx);
ctx.strokeStyle = "#000";
ctx.moveTo(toX, toY);
ctx.lineTo(fromX, fromY);
ctx.lineTo(fromX - headlen * Math.cos(angle - Math.PI / 6), fromY - headlen * Math.sin(angle - Math.PI / 6));
ctx.moveTo(fromX, fromY);
ctx.lineTo(fromX - headlen * Math.cos(angle + Math.PI / 6), fromY - headlen * Math.sin(angle + Math.PI / 6));
ctx.stroke();
}
return (
<canvas ref={canvasRef}></canvas>
)
}
export default DequeCanvas;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.