language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 1,565 | 2.5 | 2 |
[] |
no_license
|
package com.example.tiago.appbank;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by Tiago on 17/02/2017.
*/
public class BandaAdapter extends ArrayAdapter<Banda> {
List<Banda> bandas;
public BandaAdapter(Context context, List<Banda> bandas) {
super(context, R.layout.banda_item, bandas);
this.bandas = bandas;
}
@Override
public View getView(int position, View contentView, ViewGroup parent) {
View local = contentView;
if (local == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
local = inflater.inflate(R.layout.banda_item, null);
}
Banda banda = bandas.get(position);
if (banda != null) {
TextView textID = (TextView) local.findViewById(R.id.textID);
TextView textNome = (TextView) local.findViewById(R.id.textNome);
TextView textAno = (TextView) local.findViewById(R.id.textAno);
if (textID != null) {
textID.setText(String.valueOf(banda.getId()));
}
if (textNome != null) {
textID.setText(String.valueOf(banda.getNome()));
}
if (textAno != null) {
textID.setText(String.valueOf(banda.getAno()));
}
}
return local;
}
}
|
C
|
UTF-8
| 816 | 2.5625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#define MAXN 10240
int DP[2][1000000 + 5];
int max(int a, int b) {
return a > b? a : b;
}
int main (void) {
int N, M;
int W[MAXN] = {0}, V[MAXN] = {0};
scanf("%d %d", &N, &M);
for (int i = 0; i < N; i++) {
scanf("%d %d", &W[i], &V[i]);
}
int now = 1;
int old = 1 - now;
for (int i = 0; i < N; i++) {
# pragma omp parallel
{
# pragma omp for
for (int j = 1; j <= M; j++) {
DP[now][j] = DP[old][j];
if (j - W[i] >= 0) {
DP[now][j] = max(DP[old][j], DP[old][j - W[i]] + V[i]);
}
}
}
now = old;
old = 1 - now;
}
printf("%d\n", DP[old][M]);
return 0;
}
|
C
|
UTF-8
| 1,984 | 3.03125 | 3 |
[] |
no_license
|
/*
* DAC.c
*
* Created on: Nov 9, 2020
* Author: yamanshrestha
*/
/*
* InitializeDACPins
*
* Set up the direction registers and initial states for the output pins used to interface with the DAC
*
* No arguments
*
* Return type: Void
*/
//void InitializeDACPins(void)
//{
// DISABLE_DAC_CS;
// SET_DAC_CS_AS_AN_OUTPUT;
//
// DISABLE_DAC_CLEAR;
// SET_DAC_CLEAR_AS_AN_OUTPUT;
//
//}
//
///*
// * InitializeDACObject
// *
// * Define the initial values for the DAC struct, as demonstrated in main.c.
// *
// * Arguments:
// * - DAC *Dac: Pointer to DAC struct in use
// * - int DACNum: Identifier for DAC output A through D
// * - unsigned int * ArrayPtr Pointer to the first element of sine table (array) associated with DAC
// * - int ArrayLength Variable for length of sine table associated with DAC
// *
// * Return type: void
// */
//void InitializeDACObject(DAC *Dac, int DACNum, unsigned int * ArrayPtr, int ArrayLength)
//{
// Dac->DACAddress = DACNum;
// Dac->CurrentArrayIndex = 0;
// Dac->ArrayLength = ArrayLength;
// Dac->ArrayValuesPtr = ArrayPtr;
//}
//
///*
// * UpdateDACWithArrayValue
// *
// * Function returns an integer that represents the value in the sinusoid array
// * located at Dac->CurrentArrayIndex. Also, once the value has been obtained,
// * Dac->CurrentArrayIndex is incremented modulo Dac->ArrayLength; that is, if
// * Dac->CurrentArrayIndex is greater than Dac->ArrayLength after its incremented,
// * then reset Dac->CurrentArrayIndex to zero.
// *
// * Arguments:
// * - DAC *Dac Pointer to DAC struct in use
// *
// * Return type: int
// */
//int UpdateDACWithArrayValue(DAC *Dac)
//{
//
// int ArrayValue = 0;
//
// ArrayValue = (*(Dac->ArrayValuesPtr + Dac->CurrentArrayIndex));
// Dac->CurrentArrayIndex++;
// if ((Dac->CurrentArrayIndex) >= (Dac->ArrayLength)) {Dac->CurrentArrayIndex = 0;}
//
// return ArrayValue;
//}
|
Java
|
UTF-8
| 2,062 | 3.53125 | 4 |
[] |
no_license
|
package com.fullofinspiration.github.leetcode;
public class _0045_JumpGame2 {
/**
* https://leetcode.com/problems/jump-game-ii/solutions/18023/single-loop-simple-java-solution/comments/18012
* 1 得到某个节点前能走的最远距离
* 2 如果到达了上个节点走的最远距离,count++, prev更新为当前的最远距离
* 错误
* 原因1:终止条件应该是:i < nums.length-1 而不是 i< nums.length
*/
class Solution {
public int jump(int[] nums) {
int prevMax = 0;
int count = 0;
int curMax = 0;
for (int i = 0; i < nums.length-1; i++) {
curMax = Math.max(curMax, i + nums[i]);
if (i == prevMax) {
count++;
prevMax = curMax;
}
}
return count;
}
}
/**
* 每次跳到一个位置后,选择该位置的值向右的值中最大的值即可,最大值计算:值元素+索引位置(右边值比左边值大1)
* debug
* 错误1:终止条件后没有return
* 错误2:递归条件没有加一:应该是 doJump(nums, idx + i, count + 1) 而不是: doJump(nums, idx, count + 1)
* 错误3:应该写最小值而不是最大值
* 错误4: cornor case: 如果数组长度为1,则返回0
*/
class Solution00 {
int min = Integer.MAX_VALUE;
public int jump(int[] nums) {
if (nums.length == 1) {
return 0;
}
doJump(nums, 0, 0);
return min;
}
private void doJump(int[] nums, int idx, int count) {
if (idx >= nums.length - 1) {
throw new IllegalStateException();
}
if (nums[idx] + idx >= nums.length - 1) {
min = Math.min(count + 1, min);
return;
}
for (int i = 1; i <= nums[idx]; i++) {
doJump(nums, idx + i, count + 1);
}
}
}
}
|
JavaScript
|
UTF-8
| 535 | 2.703125 | 3 |
[] |
no_license
|
import React from 'react'
export const AgeInput = ({age, setAge}) => {
return (
<div className="input input-age">
<h3>How old are you?</h3>
<p>
We can't give a result to under 5s.
</p>
<div className="radio-buttons">
<input type="number" inputMode="numeric" min="5" max="130" name="age" id="age-input" className="age-input" value={age} onChange={e => setAge(e.target.value)} />
<button disabled={!age} onClick={() => setAge("")}>Clear</button>
</div>
</div>
)
};
|
JavaScript
|
UTF-8
| 1,409 | 3.359375 | 3 |
[] |
no_license
|
const gitHubForm = document.getElementById('gitHubForm'); //dohvatanje GitHub username input forme
gitHubForm.addEventListener('submit', (e) => {
e.preventDefault(); //prevent default form action
let usernameInput=document.getElementById('usernameInput'); //dohvatanje GitHub username
let gitHubUsername = usernameInput.value; //dohvatanje vrednosti
requestUserRepos(gitHubUsername); //pokretanje funkcije
});
function requestUserRepos(username){
const xhr = new XMLHttpRequest(); //novi objekat
const url = `https://api.github.com/users/${username}/repos`; //github endpoint
xhr.open('GET', url, true); //nova konekcija koristeci GET
xhr.onload=function(){
const data = JSON.parse(this.response); //parsovanje podataka u JSON
for (let d in data){
let ul = document.getElementById('userRepos');
let li = document.createElement('li');
li.classList.add('list-group-item') //dodavanje bootstrap klase za grupisanje liste
li.innerHTML = (`
<p><strong>Repo:</strong> ${data[d].name}</p>
<p><strong>Description:</strong> ${data[d].description}</p>
<p><strong>URL:</strong> <a href="${data[d].html_url}">${data[d].html_url}</a></p>
`); //ispisivanje u HTML
ul.appendChild(li); //dodaje listi element
}
}
xhr.send();
}
|
Markdown
|
UTF-8
| 2,982 | 2.734375 | 3 |
[] |
no_license
|
# My Educated Guess on the Hardness of Factoring: Not as Hard!
* **Reason 1:** Factoring is in the intersection of NP and coNP, which means that it is (extremely) unlikely to be NP-complete because otherwise NP=coNP which is (in my assessment) less likely to be true than factoring being hard.
* **Reason 2:** Other problems in the intersection of NP and coNP have been falling like domino pieces one after another, e.g., primality testing (already in P), graphisomorphism (already in quasi-P), ....
* **Reason 3:** Knowing (the most or least significsnt) half the bits of one the factors renders the problem in P, and even more it is a very efficien algorithm via the Koppersmith method.
* **Reason 4:** We are 2/3 of the way down the exponent through with NFS algortihm, one more clever idea is needed and we're likely to be home (in my opinion).
* **Reason 5:** Factoring has a lot of structure, it is actually one of th emost fundamentl structures in number theory
* **Reason 6:** Algorithms exploited so far are single-encoding ones, i.e., they are mostly algebraic and exploit algeraic natures of groups or fields these composites live in.
* **Reason 7:** We know that quantumly factoring is in P, and there are very few other natural optimization or numerical problems that enjoy an exponentail speed speedup from (the current understnidng of) quantum algorithms. Just to be clear, I am not
* **Reason 8:** Argument of millenia does not hold. 10 years of research today are easily worth 100s of research fbefore 1900.
* **Reason 9:** Not a lot of people are truly working on factoring (at least not publicly), especially that given my understanding of how availability of fudning is a main driver of what people tend to work on (e.g, the big push in FHE, Obfs, and ZK due to DARPA)
* **Reason 10:** Intimate relation between RSA and factoring could provide more clues. Aside from the fundamental nature of factoring to number theor and math, a major contributor to its notoriotiy is that it could be usd ot break RSA encryption and signatures. It may still be the case that factoring is hard and RSA is easy becasue we still do not havea general reduction realting both (factoring can break RSA, but unclear if breaking RSA result sin a factoring algorithm necessarly, because it may be that knowning e and that it has an inverse congruen to 1 modulo the Euler Totient function provides additional information not present in the composite modulus alone. The best equivalence between RSA and factoring we know (to my best of knowledge) is in the generic group model, unlike discrete logarithm (DL) and Diffie-Hellman (DH) which are proven to be the same in the standard model. This raises an issue though which is that DL and factoring are so intimatly related so it is likely that one such reduction will be found, and then because as I said there is additiona info availble from 2 in RSA then this may make the problem even easier nd thus transfer to factoring.
|
Java
|
UTF-8
| 4,698 | 1.859375 | 2 |
[
"MIT"
] |
permissive
|
package mekanism.client.jei.machine;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import mekanism.api.annotations.NonNull;
import mekanism.api.chemical.gas.GasStack;
import mekanism.api.math.FloatingLong;
import mekanism.api.recipes.NucleosynthesizingRecipe;
import mekanism.client.gui.element.GuiInnerScreen;
import mekanism.client.gui.element.bar.GuiDynamicHorizontalRateBar;
import mekanism.client.gui.element.gauge.GaugeType;
import mekanism.client.gui.element.gauge.GuiEnergyGauge;
import mekanism.client.gui.element.gauge.GuiEnergyGauge.IEnergyInfoHandler;
import mekanism.client.gui.element.gauge.GuiGasGauge;
import mekanism.client.gui.element.gauge.GuiGauge;
import mekanism.client.gui.element.slot.GuiSlot;
import mekanism.client.gui.element.slot.SlotType;
import mekanism.client.jei.BaseRecipeCategory;
import mekanism.client.jei.MekanismJEI;
import mekanism.common.MekanismLang;
import mekanism.common.inventory.container.slot.SlotOverlay;
import mekanism.common.lib.Color;
import mekanism.common.lib.Color.ColorFunction;
import mekanism.common.registries.MekanismBlocks;
import mekanism.common.tile.component.config.DataType;
import mezz.jei.api.constants.VanillaTypes;
import mezz.jei.api.gui.IRecipeLayout;
import mezz.jei.api.gui.ingredient.IGuiItemStackGroup;
import mezz.jei.api.helpers.IGuiHelper;
import mezz.jei.api.ingredients.IIngredients;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
public class NucleosynthesizingRecipeCategory extends BaseRecipeCategory<NucleosynthesizingRecipe> {
private final GuiDynamicHorizontalRateBar rateBar;
private final GuiSlot input;
private final GuiSlot extra;
private final GuiSlot output;
private final GuiGauge<?> gasInput;
public NucleosynthesizingRecipeCategory(IGuiHelper helper) {
super(helper, MekanismBlocks.ANTIPROTONIC_NUCLEOSYNTHESIZER, 6, 18, 182, 80);
input = addSlot(SlotType.INPUT, 26, 40);
extra = addSlot(SlotType.EXTRA, 6, 69);
output = addSlot(SlotType.OUTPUT, 152, 40);
addSlot(SlotType.POWER, 173, 69).with(SlotOverlay.POWER);
addElement(new GuiInnerScreen(this, 45, 18, 104, 68));
gasInput = addElement(GuiGasGauge.getDummy(GaugeType.SMALL_MED.with(DataType.INPUT), this, 5, 18));
addElement(new GuiEnergyGauge(new IEnergyInfoHandler() {
@Override
public FloatingLong getEnergy() {
return FloatingLong.ONE;
}
@Override
public FloatingLong getMaxEnergy() {
return FloatingLong.ONE;
}
}, GaugeType.SMALL_MED, this, 172, 18));
rateBar = addElement(new GuiDynamicHorizontalRateBar(this, getBarProgressTimer(), 5, 88, 183,
ColorFunction.scale(Color.rgbi(60, 45, 74), Color.rgbi(100, 30, 170))));
}
@Override
public Class<? extends NucleosynthesizingRecipe> getRecipeClass() {
return NucleosynthesizingRecipe.class;
}
@Override
public List<ITextComponent> getTooltipStrings(NucleosynthesizingRecipe recipe, double mouseX, double mouseY) {
if (rateBar.isMouseOver(mouseX, mouseY)) {
return Collections.singletonList(MekanismLang.TICKS_REQUIRED.translate(recipe.getDuration()));
}
return Collections.emptyList();
}
@Override
public void setIngredients(NucleosynthesizingRecipe recipe, IIngredients ingredients) {
ingredients.setInputLists(VanillaTypes.ITEM, Collections.singletonList(recipe.getItemInput().getRepresentations()));
ingredients.setInputLists(MekanismJEI.TYPE_GAS, Collections.singletonList(recipe.getChemicalInput().getRepresentations()));
ingredients.setOutputLists(VanillaTypes.ITEM, Collections.singletonList(recipe.getOutputDefinition()));
}
@Override
public void setRecipe(IRecipeLayout recipeLayout, NucleosynthesizingRecipe recipe, IIngredients ingredients) {
IGuiItemStackGroup itemStacks = recipeLayout.getItemStacks();
initItem(itemStacks, 0, true, input, recipe.getItemInput().getRepresentations());
initItem(itemStacks, 1, false, output, recipe.getOutputDefinition());
List<ItemStack> gasItemProviders = new ArrayList<>();
List<@NonNull GasStack> gasInputs = recipe.getChemicalInput().getRepresentations();
for (GasStack gas : gasInputs) {
gasItemProviders.addAll(MekanismJEI.GAS_STACK_HELPER.getStacksFor(gas.getType(), true));
}
initItem(itemStacks, 2, true, extra, gasItemProviders);
initChemical(recipeLayout.getIngredientsGroup(MekanismJEI.TYPE_GAS), 0, true, gasInput, gasInputs);
}
}
|
PHP
|
UTF-8
| 962 | 2.796875 | 3 |
[] |
no_license
|
<?php
namespace App\Security;
use App\Entity\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAccountStatusException;
class UserChecker implements UserCheckerInterface
{
public function checkPreAuth(UserInterface $user): void
{
if (!$user instanceof User) {
return;
}
}
public function checkPostAuth(UserInterface $user): void
{
if (!$user instanceof User) {
return;
}
/* Warning; if you enter a wrong password, the exception will be display. */
if (!$user->getIsVerified()) {
throw new CustomUserMessageAccountStatusException("Votre compte n'est pas actif, veuilez consulter vos mails pour l'activer avant le
{$user->getAccountMustBeVerifiedBefore()->format('d/m/Y à H/hi')}");
}
}
}
|
C++
|
UTF-8
| 636 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <SFML\Graphics.hpp>
namespace mu
{
const float PI = 3.141599265f;
const float TWO_PI = PI * 2;
const sf::Vector2f polarToRectangular(const sf::Vector2f &polarCoordinates);
const sf::Vector2f polarToRectangular(const float &radius, const float &theta);
const sf::Vector2f rectangularToPolar(const sf::Vector2f &rectCoordinates);
const sf::Vector2f rectangularToPolar(const float &x, const float &y);
const sf::Vector2f rotateVector(const sf::Vector2f ¢ered, const float &rotateBy, const bool &polar = false);
const float radToDeg(const float &radians);
const float degToRad(const float °rees);
}
|
Java
|
UTF-8
| 798 | 2.9375 | 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 PunyaAlwi;
import java.util.Scanner;
public class assign2 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int [][]number=new int[3][5];
for(int i=0;i<2;i++){
for(int j=0;j<5;j++){
System.out.print("Input value row "+i+" collumn "+j+" : ");
number[i][j]=input.nextInt();
}
}
System.out.print("Input number you want to search : ");
int search=input.nextInt();
sort2 number2=new sort2(number);
number2.find(search);
number2.print();
}
}
|
JavaScript
|
UTF-8
| 2,358 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
const user = require('../models/user.model');
const validateId = require('../validateObjectId');
exports.getAll = function (req, res) {
if (req.user.role !== 'admin') {
// only admins can get all users
return res.status(403).send('Unauthorized resource access. User does not have valid credentials to perform that action');
}
user.find({}, (error, users) => {
if (error) {
return res.status(400).json(error);
}
return res.status(200).json(users);
});
}
exports.getUser = function (req, res) {
if (!validateId(req.params.id)) {
return res.status(400).json('Invalid user id');
}
user.findById(req.params.id, (error, user) => {
if (error) {
return res.status(500).json(error);
}
return res.status(200).json(user);
});
}
exports.createUser = async function (req, res) {
const validUser = await user.findOne({ email: req.body.email });
if (validUser) {
return res.status(400).send('The email is already registered by another user account');
}
new user({
email: req.body.email,
password: req.body.password,
firstname: req.body.firstname,
lastname: req.body.lastname,
role: req.body.role
}).save(((error, user) => {
if (error) {
return res.status(400).json(error);
}
return res.status(200).json(user);
}));
}
exports.deleteUser = function (req, res) {
if (req.user.role !== 'admin') {
// only admins can get all users
return res.status(403).send('Unauthorized resource access. User does not have valid credentials to perform that action');
}
if (!validateId(req.params.id)) {
return res.status(400).json('Invalid user id');
}
user.findByIdAndRemove(req.params.id, (error, user) => {
if (error) {
return res.status(500).json(error);
}
return res.status(200).json(user);
});
}
exports.updateUser = function (req, res) {
// make sure user is updating their own account details
if (req.user._id !== req.params.id) {
// only admins can get all users
return res.status(403).send('Unauthorized resource access. User does not have valid credentials to perform that action');
}
if (!validateId(req.params.id)) {
return res.status(400).json('Invalid user id');
}
const updatedUser = user.findByIdAndUpdate(req.params.id, req.body, { new: true });
return res.status(200).send(updatedUser);
}
|
Python
|
UTF-8
| 4,340 | 2.65625 | 3 |
[] |
no_license
|
#graphSims
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
from mpldatacursor import datacursor
simZinE1 = pd.read_csv("simZinE1.csv")
simZinE2 = pd.read_csv("simZinE2.csv")
simZoutE1 = pd.read_csv("simZoutE1.csv")
simZoutE2 = pd.read_csv("simZoutE2.csv")
simGanE1 = pd.read_csv("simGanE1.csv")
simGanE2 = pd.read_csv("simGanE2.csv")
simZinEtotal = pd.read_csv("zin.csv")
plt.figure(1) #GRAFICO DE MAGNITUD Zin (E1 y E2 superpuestos)
plt.semilogx(simZinE1["f"], 10**(simZinE1["mag"]/20), label='Etapa 1')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Magnitud (ohms)")
plt.title("Impedancia de Entrada - Magnitud")
plt.grid(True)
plt.semilogx(simZinE2["f"], 10**(simZinE2["mag"]/20), label='Etapa 2')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Magnitud (ohms)")
plt.xticks()
plt.yticks()
plt.legend(loc = 'lower right')
datacursor(formatter="f:{x:.2f} Hz\n mag:{y:.2f} dB".format, display='multiple', draggable=True)
plt.figure(2) #GRAFICO DE Fase Zin (E1 y E2 superpuestos)
plt.semilogx(simZinE1["f"], simZinE1["pha"], label='Etapa 1')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Fase (degrees)")
plt.title("Impedancia de Entrada - Fase")
plt.grid(True)
plt.semilogx(simZinE2["f"], simZinE2["pha"], label='Etapa 2')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Fase (degrees)")
plt.xticks()
plt.yticks()
plt.legend(loc = 'lower right')
datacursor(formatter="f:{x:.2f} Hz\n mag:{y:.2f} dB".format, display='multiple', draggable=True)
plt.figure(3) #GRAFICO DE MAGNITUD Zout (E1 y E2 superpuestos)
plt.semilogx(simZoutE1["f"], 10**(simZoutE1["mag"]/20), label='Etapa 1')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Magnitud (ohms)")
plt.title("Impedancia de Salida - Magnitud")
plt.grid(True)
plt.semilogx(simZinE2["f"], 10**(simZoutE2["mag"]/20), label='Etapa 2')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Magnitud (ohms)")
plt.xticks()
plt.yticks()
plt.legend(loc = 'lower right')
datacursor(formatter="f:{x:.2f} Hz\n mag:{y:.2f} dB".format, display='multiple', draggable=True)
plt.figure(4) #GRAFICO DE Fase Zout (E1 y E2 superpuestos)
plt.semilogx(simZoutE1["f"], simZoutE1["pha"], label='Etapa 1')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Fase (degrees)")
plt.title("Impedancia de Salida - Fase")
plt.grid(True)
plt.semilogx(simZinE2["f"], simZinE2["pha"], label='Etapa 2')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Fase (degrees)")
plt.xticks()
plt.yticks()
plt.legend(loc = 'lower right')
datacursor(formatter="f:{x:.2f} Hz\n mag:{y:.2f} dB".format, display='multiple', draggable=True)
plt.figure(5) #GRAFICO DE MAGNITUD ganancia (E1 y E2 superpuestos)
plt.semilogx(simGanE1["f"], simGanE1["mag"], label='Etapa 1')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Magnitud (dB)")
plt.title("Ganancia - Magnitud")
plt.grid(True)
plt.semilogx(simGanE2["f"], simGanE2["mag"], label='Etapa 2')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Magnitud (dB)")
plt.xticks()
plt.yticks()
plt.legend(loc = 'lower right')
datacursor(formatter="f:{x:.2f} Hz\n mag:{y:.2f} dB".format, display='multiple', draggable=True)
plt.figure(6) #GRAFICO DE Fase ganancia (E1 y E2 superpuestos)
plt.semilogx(simGanE1["f"], simGanE1["pha"], label='Etapa 1')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Fase (degrees)")
plt.title("Ganancia - Fase")
plt.grid(True)
plt.semilogx(simGanE2["f"], simGanE2["pha"], label='Etapa 2')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Fase (degrees)")
plt.xticks()
plt.yticks()
plt.legend(loc = 'lower right')
datacursor(formatter="f:{x:.2f} Hz\n mag:{y:.2f} dB".format, display='multiple', draggable=True)
plt.figure(7) #GRAFICO DE Fase Zin (E1 y E2 superpuestos)
plt.semilogx(simZoutE1["f"], 10**(simZoutE1["mag"]/20), label='Etapa 1 - Zout')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Mag (ohms)")
plt.title("Impedancias Zin/Zout - Magnitud")
plt.grid(True)
plt.semilogx(simZinE2["f"], 10**(simZinE2["mag"]/20), label='Etapa 2 - Zin')
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Mag (ohms)")
plt.xticks()
plt.yticks()
plt.legend(loc = 'lower right')
datacursor(formatter="f:{x:.2f} Hz\n mag:{y:.2f} dB".format, display='multiple', draggable=True)
plt.figure(8) #GRAFICO DE Fase Zin (E1 y E2 superpuestos)
plt.semilogx(simZinEtotal["f"], 10**(simZinEtotal["mag"]/20))
plt.xlabel("Frecuencia (Hz)")
plt.ylabel("Mag (ohms)")
plt.title("Impedancia de Entrada - Magnitud")
plt.grid(True)
plt.show()
|
Java
|
UTF-8
| 10,392 | 2.0625 | 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. change
*/
package XML_Utils;
import Rules_Methods.Rule;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
*
* @author Alain
*/
public class XML_Methods {
public static boolean validateXMLSchema(URL xsdPath, String xmlPath){
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(xsdPath);
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(xmlPath)));
} catch (IOException | SAXException e) {
JOptionPane.showMessageDialog(null,"XML NOT VALID: "+e.getMessage(),"Load Repository",JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
public static boolean saveXMLFile(Document doc, String[] directory){
String xmlPath;
if (directory[0]== null){directory[0] = ".";}
JFileChooser fc = new JFileChooser(directory[0]);
fc.setDialogTitle("Specify a XML to save");
File file = new File("untitled.xml");
fc.setSelectedFile(file);
fc.addChoosableFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "XML Documents (*.xml)";
}
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
} else {
return f.getName().toLowerCase().endsWith(".xml");
}
}
});
if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
xmlPath = fc.getSelectedFile().getAbsolutePath();
directory[0] = fc.getCurrentDirectory().toString();
directory[1] = fc.getSelectedFile().getName();
} else {JOptionPane.showMessageDialog(null, "No file selected.");
return false;}
try{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult streamResult = new StreamResult(new File(xmlPath));
transformer.transform(source, streamResult);
} catch (TransformerException e) {
Logger.getLogger(XML_Methods.class.getName()).log(Level.SEVERE, null, e);
return false;
}
return true;
}
public static Document createXMLDocument(String[] directory){
Document doc = null;
directory[1] = "not saved...";
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element elem = doc.createElement("Repository");
doc.appendChild(elem);
Element elem_date = doc.createElement("Date");
elem_date.appendChild(doc.createTextNode((new SimpleDateFormat( "yyyy-MM-dd")).format(Calendar.getInstance().getTime())));
elem.appendChild(elem_date);
} catch (ParserConfigurationException ex) {
Logger.getLogger(XML_Methods.class.getName()).log(Level.SEVERE, null, ex);
}
return (doc);
}
public static Document loadXMLFile(String[] directory){
if (directory[0]== null){directory[0] = ".";}
JFileChooser fc = new JFileChooser(directory[0]);
fc.setDialogTitle("Specify a XML to load");
fc.addChoosableFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "XML Documents (*.xml)";
}
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
} else {
return f.getName().toLowerCase().endsWith(".xml");
}
}
});
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
directory[0] = fc.getCurrentDirectory().toString();
directory[1] = fc.getSelectedFile().getName();
try {
File file = new File(fc.getSelectedFile().getAbsolutePath());
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = dBuilder.parse(file);
doc.getDocumentElement().normalize();
return doc;
} catch (SAXException | IOException | ParserConfigurationException ex) {
Logger.getLogger(XML_Methods.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
} else {JOptionPane.showMessageDialog(null, "No file selected.");
return null;}
}
public static Document addNewRuleXML(Document doc, Rule new_rule){
Node repository = doc.getFirstChild();
Element elem_rule = doc.createElement("Rule");
repository.appendChild(elem_rule);
elem_rule.setAttribute("rule_id", "ID_" + System.currentTimeMillis());
Element elem_date = doc.createElement("Date");
elem_date.appendChild(doc.createTextNode((new SimpleDateFormat("yyyy-MM-dd")).format(Calendar.getInstance().getTime())));
elem_rule.appendChild(elem_date);
Element elem_active = doc.createElement("Active");
elem_active.appendChild(doc.createTextNode(new_rule.isActive().toString()));
elem_rule.appendChild(elem_active);
Element elem_relt = doc.createElement("Relation");
elem_relt.appendChild(doc.createTextNode(new_rule.getRelation()));
elem_rule.appendChild(elem_relt);
Element elem_ant = doc.createElement("Antecedent");
elem_ant.appendChild(doc.createTextNode(new_rule.getAntecedent()));
elem_rule.appendChild(elem_ant);
Element elem_cons = doc.createElement("Consequent");
elem_cons.appendChild(doc.createTextNode(new_rule.getConsequent()));
elem_rule.appendChild(elem_cons);
Element elem_type = doc.createElement(new_rule.getType());
if (null != new_rule.getType())switch (new_rule.getType()) {
case "Fuzzy_Association_Rule":
for (Rule.Att_Linguistic_labels att_llab : new_rule.getRule_attrib_lab()){
Element elem_att = doc.createElement("Attribute");
Element elem_att_name = doc.createElement("Attribute_Name");
elem_att_name.appendChild(doc.createTextNode(att_llab.att_name));
elem_att.appendChild(elem_att_name);
for (Rule.Linguistic_label lab : att_llab.Linguistic_labels_attribute) {
Element elem_lab = doc.createElement("Linguistic_Label");
Element elem_lab_name = doc.createElement("Label_Name");
elem_lab_name.appendChild(doc.createTextNode(lab.label_name));
elem_lab.appendChild(elem_lab_name);
Element elem_lab_a = doc.createElement("A");
elem_lab_a.appendChild(doc.createTextNode(lab.a.toString()));
elem_lab.appendChild(elem_lab_a);
Element elem_lab_b = doc.createElement("B");
elem_lab_b.appendChild(doc.createTextNode(lab.b.toString()));
elem_lab.appendChild(elem_lab_b);
Element elem_lab_c = doc.createElement("C");
elem_lab_c.appendChild(doc.createTextNode(lab.c.toString()));
elem_lab.appendChild(elem_lab_c);
Element elem_lab_d = doc.createElement("D");
elem_lab_d.appendChild(doc.createTextNode(lab.d.toString()));
elem_lab.appendChild(elem_lab_d);
elem_att.appendChild(elem_lab);
}
elem_type.appendChild(elem_att);
} break;
case "Association_Rule":
Element elem_ar = doc.createElement("Association_Rule");
elem_ar.appendChild(doc.createTextNode(new_rule.getType()));
break;
case "Approximate_Dependence":
Element elem_ad = doc.createElement("Approximate_Dependence");
elem_ad.appendChild(doc.createTextNode(new_rule.getType()));
break;
}
elem_rule.appendChild(elem_type);
return (doc);
}
}
|
C++
|
UTF-8
| 436 | 3.515625 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
void double_data(int *int_ptr){
*int_ptr *= 2;
}
int main(){
int value{10};
int *int_ptr{nullptr};
cout<< "Value : " << value << endl;
double_data(&value);
cout << "Value is " << value << endl;
cout << "__________________________" << endl;
int_ptr=&value;
double_data(int_ptr);
cout << "Value is " << value << endl;
cout << "End of PROGRAM " << endl;
return 0;
}
|
Markdown
|
UTF-8
| 4,576 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: 再见2018:我的个人总结
subtitle: 年初定的flag,你都实现了?
date: 2018-12-31
author: jessehzx
header-img: img/pexels-photo-1654495.jpeg
catalog: true
tags:
- review
---
> 版权声明:本文为 jessehzx 原创文章,支持转载,但必须在明确位置注明出处!!!
2018年即将结束,今年你是否收获满满,年初定的flag都实现了么?此刻,我写下自己的一些感悟,以及做过的几件事情。
#### 1. 认知
今年最大的收获是认知上面的提升。以前很多事情不懂也没去思考,记得高中班主任老说一句话:“其身正,不令而行;其身不正,虽令不从”,一个人只有思想层次提升了,才能更好的落实到行动上,正确的事才会持续发生。当然,这也是在我认知提升了之后才意识到的。
如今的计算机编程分太多领域,到底要去哪一个领域深入钻研,其实是需要一个判断的,而这个判断就要看你能不能下一个决心,有一个稳定的节奏。比如在今后的三年里面我主要的提升是:我在技术方面的思维和管理能力,我的目标是成为一个好的技术人,如果真的有这么好的一个自我认知和方向性的话,那就很好。但是很多年轻人不是这样的,是晃来晃去的,因为现在有趣的事太多了,所谓的大牛也太多了,很容易就被忽悠到不同的领域里去。
画外音:静下心来,选好对的方向做下去试试。。
#### 2. 业务
刚进公司不久,老大说:“业务才是最重要的”,当时没真正理解这句话的意思,好像是在说:你们不懂业务!那我就想反驳了:“我对系统的核心业务流程最熟悉不过了,甚至比那些业务的人更懂”、“系统的数据模型都是我设计的,怎能说我们不懂业务?” ......
后来看了一些相关的书,才有了思考:他所说的懂业务是指,能对业务的下一步发展有着自己的理解和看法,对业务流程如何进一步优化能更好地提升业务,甚至对企业现有的业务提出创新的想法,为企业带来新的增长点。
画外音:业务从不会消亡,技术人员做业务不单是实施者,更高级的玩法是去思考它解决了什么问题,价值在哪里。。
#### 3. 持续
说三件我从今年下半年在坚持做的事情。不是想证明我有多牛,而是想让大家一起来思考:从这些“小事”上面通过持续一段时间去做,能给我们带来了哪些改变?
一是健身。自从上了大一,体重就一直维持在116斤,十年时间不增不减,确是一件相当神奇的事,但对于我176cm的个子确实是偏瘦了,一直想变胖一些,但没找到有效的方法。8月底在网上看到一篇健身的帖子,才找到一点窍门,知道了饮食和锻炼相结合的方式,于是买了器械,晚上回去就是一顿猛搞,再加上加餐的习惯,3个月时间,体重终于升级到了130斤,算是一个小小的里程碑。
画外音:如果身体不重要,那什么重要?
二是学英文。大学只勉强过了四级,自认为自己的英语确实是差。工作前两年,经历过面向Google/stackoverflow编程的时光,搜出来的全是英文,看下来慢,甚至看不懂,甚是恼火。后面虽然好些了,但总感觉还需专门抽出时间来学习一下比较好,10月份在一位朋友的推荐了报了一期薄荷阅读,每天阅读大概一千字,算是坚持的不错,没有出现补卡的情况。英语语感有所增强,畏惧感消失,现在会主动尝试去找一些英文文章阅读和翻译。
画外音:编程、英语、写作,绝对是未来三大最重要的技能。。
三是阅读。微信读书上面时长达到97小时,不是很高,但给我养成一种习惯,就是碎片化时间的利用。平时坐地铁看到太多年轻人刷抖音、刷微博、追剧,但如果你没有一个可以拼的爹,完全要靠自己才能混的好,建议还是克制一下,拿这些时间看一篇公众号文章、读书app上看几页书,如果地铁公交挤得连手机都掏不出,那就理一理今天要做的那些事也挺好。
画外音:阅读是每天必须要做的事,如果太忙,那就读少点。事不怕慢,就怕停。
#### 4. 愿望
。。。
画外音:什么?我的2019新年愿望?我才不说给你听。。
|
PHP
|
UTF-8
| 488 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
<?php
require('connect.php');
$sql = "CREATE TABLE IF NOT EXISTS BUNDESLIGA (
bund_id INT(15) NOT NULL,
user_id INT (11) UNSIGNED NOT NULL,
season INT (4),
matchweek INT (2),
bundarray VARCHAR(510) NOT NULL,
PRIMARY KEY(bund_id),
FOREIGN KEY(user_id) REFERENCES User(user_id)
)ENGINE=InnoDB";
if ($conn->query($sql) === TRUE) {
echo "Table BUNDESLIGA created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
|
PHP
|
UTF-8
| 3,469 | 2.515625 | 3 |
[] |
no_license
|
<?php
/**
* TClientScript class file
*
* @author Wei Zhuo <weizhuo[at]gmail[dot]com>
* @link http://www.pradosoft.com/
* @copyright Copyright © 2005-2008 PradoSoft
* @license http://www.pradosoft.com/license/
* @version $Id: TClientScript.php 2348 2013-12-20 10:20:54Z arun $
* @package System.Web.UI.WebControls
*/
/**
* TClientScript class
*
* Allows importing of Prado Client Scripts from template via the
* {@link setPradoScripts PradoScripts} property. Multiple Prado
* client-scripts can be specified using comma delimited string of the
* javascript library to include on the page. For example,
*
* <code>
* <com:TClientScript PradoScripts="effects, rico" />
* </code>
*
* Custom javascript files can be register using the {@link setScriptUrl ScriptUrl}
* property.
* <code>
* <com:TClientScript ScriptUrl=<%~ test.js %> />
* </code>
*
* Contents within TClientScript will be treated as javascript code and will be
* rendered in place.
*
* @author Wei Zhuo <weizhuo[at]gmail[dot]com>
* @version $Id: TClientScript.php 2348 2013-12-20 10:20:54Z arun $
* @package System.Web.UI.WebControls
* @since 3.0
*/
class TClientScript extends TControl
{
/**
* @return string comma delimited list of javascript libraries to included
* on the page.
*/
public function getPradoScripts()
{
return $this->getViewState('PradoScripts', '');
}
/**
* Include javascript library to the current page. The current supported
* libraries are: "prado", "effects", "ajax", "validator", "logger",
* "datepicker", "colorpicker". Library dependencies are automatically resolved.
*
* @param string comma delimited list of javascript libraries to include.
*/
public function setPradoScripts($value)
{
$this->setViewState('PradoScripts', $value, '');
}
/**
* @return string custom javascript file url.
*/
public function getScriptUrl()
{
return $this->getViewState('ScriptUrl', '');
}
/**
* @param string custom javascript file url.
*/
public function setScriptUrl($value)
{
$this->setViewState('ScriptUrl', $value, '');
}
/**
* Calls the client script manager to add each of the requested client
* script libraries.
* @param mixed event parameter
*/
public function onPreRender($param)
{
parent::onPreRender($param);
$scripts = preg_split('/,|\s+/', $this->getPradoScripts());
$cs = $this->getPage()->getClientScript();
foreach($scripts as $script)
{
if(($script = trim($script))!=='')
$cs->registerPradoScript($script);
}
}
/**
* Renders the body content as javascript block.
* Overrides parent implementation, parent renderChildren method is called during
* {@link registerCustomScript}.
* @param THtmlWriter the renderer
*/
public function render($writer)
{
$this->renderCustomScriptFile($writer);
$this->renderCustomScript($writer);
}
/**
* Renders the custom script file.
* @param THtmLWriter the renderer
*/
protected function renderCustomScriptFile($writer)
{
if(($scriptUrl = $this->getScriptUrl())!=='')
$writer->write("<script type=\"text/javascript\" src=\"$scriptUrl\"></script>\n");
}
/**
* Registers the body content as javascript.
* @param THtmlWriter the renderer
*/
protected function renderCustomScript($writer)
{
if($this->getHasControls())
{
$writer->write("<script type=\"text/javascript\">\n/*<![CDATA[*/\n");
$this->renderChildren($writer);
$writer->write("\n/*]]>*/\n</script>\n");
}
}
}
|
C#
|
UTF-8
| 1,050 | 3.75 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
namespace School
{
public class Teacher : People
{
private IList<Discipline> disciplines;
public Teacher(string name, IList<Discipline> disciplines, string details)
: base(name, details)
{
this.Disciplines = disciplines;
}
public IList<Discipline> Disciplines
{
get { return new List<Discipline>(this.disciplines); }
set
{
if (value == null || value.Count < 1)
{
throw new ArgumentException("Disciplines list can not be null or 0!");
}
this.disciplines = value;
}
}
public override string ToString()
{
string teacher = base.ToString() + "Teaching disciplines:\n";
foreach (var discipline in this.Disciplines)
{
teacher += discipline.Name + " ";
}
return teacher;
}
}
}
|
C++
|
UTF-8
| 784 | 3.515625 | 4 |
[] |
no_license
|
#include <iostream>
#include <random>
using namespace std;
default_random_engine gen(0); //set seed to be 0- useful to debug
//get rid of 0 once you know it works
void fillRandom(int a[], int n ) { //set location array a[] and n elements
uniform_int_distribution<int> distribution(1,n);
for (int i = 0; i < n; i++) {
a[i] = distribution(gen);
}
}
void print(int x[], int n) {
for (int i = 0; i < n; i++)
cout << x[i] << ' '<< endl;
}
double mean(int x[], int n) {
double s = 0;
for (int i = 0; i < n; i++)
s += x[i];
return s / n;
}
int main() {
const int SIZE = 10;
int x[SIZE];
fillRandom(x, SIZE); //fill following array - x, with SIZE random numbers
print(x, SIZE);
cout << mean(x, SIZE) << endl;
}
|
C
|
UTF-8
| 1,449 | 3.46875 | 3 |
[] |
no_license
|
/*
* 信号量级的简单实用
* 首先创建一个值为5的信号量级,在创建10个进程,这10个进程只有5个进程可以同时工作
* 每有一个进程开始工作,信号量的值就减去1,每当有一个进程工作完毕,信号量的值则、
* 自动回复(+1);
* 注意:只有在对信号量+1/-1操作是将sb.sem_flg设置为SEM_UNDO时,在进程结束后信号量
* 的值才会自动回复。
*/
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SEM_KEY 0X8888
int main() {
int id = semget(SEM_KEY, 1, IPC_CREAT|0600);//打开或创建信号量级
if(id == -1) {
perror("semget");
return -1;
}
semctl(id, 0, SETVAL, 5); //设置信号量值
int i = 0;
for(i = 0; i < 10; i++) {
if(fork() == 0) {
struct sembuf sb;
sb.sem_num = 0; //信号量下标
sb.sem_op = 1; //加一减一操作(减一)
sb.sem_flg = SEM_UNDO; //进程结束后回复信号量值
while(semop(id, &sb, 1) == -1) {
;
}
srand(getpid()); //随机数种子
printf("%d进程开始工作\n", getpid());
sleep(rand() % 20);
printf("%d进程工作完毕\n", getpid());
sb.sem_op = +1;
semop(id, &sb, 1);
exit(0);
}
}
/* 等待所有子进程结束 */
while(wait(NULL) != -1);
semctl(id, 0, IPC_RMID, NULL); //删除信号量集
puts("全部子进程结束\n");
return 0;
}
|
Python
|
UTF-8
| 479 | 3.796875 | 4 |
[] |
no_license
|
from datetime import date
print('---------------Analise da idade de pessoas-------------')
ano_atual= date.today().year
maior = 0
menor = 0
for i in range(1, 7):
data = int(input("Em que ano você nasceu? "))
idade = ano_atual - data
print("sua idade é {}.".format(idade))
if idade >= 18:
maior += 1
else:
menor += 1
print("Se tem {} pessoas de maior.".format(maior))
print("Se tem {} pessoas de menor.".format(menor))
|
Python
|
UTF-8
| 1,474 | 2.734375 | 3 |
[] |
no_license
|
import openpyxl as xl
import os
from models import StaticVariables, ComparisonRecord
# Update Excel
app_dir = os.path.dirname(__file__)
file_path = os.path.join(app_dir, 'data_file.xlsx')
data_file = xl.load_workbook(file_path)
data_sheet = data_file.worksheets[0]
# data_sheet.cell(row=1, column=1).value = "test writing"
# print(data_sheet.max_row)
def get_last_record():
StaticVariables.last_record = data_sheet.max_row
def save_record(comparison_record):
data_sheet.cell(row=StaticVariables.current_record, column=8).value = comparison_record.fti_price
data_sheet.cell(row=StaticVariables.current_record, column=9).value = comparison_record.competitor_name
data_sheet.cell(row=StaticVariables.current_record, column=10).value = comparison_record.competitor_price
def save_work():
data_file.save(file_path)
def get_record(row_index):
result = ComparisonRecord(
destination=data_sheet.cell(row=row_index, column=1).value,
arrival=data_sheet.cell(row=row_index, column=2).value,
departure=data_sheet.cell(row=row_index, column=3).value,
duration_from=data_sheet.cell(row=row_index, column=4).value,
duration_till=data_sheet.cell(row=row_index, column=5).value,
hotel_name=data_sheet.cell(row=row_index, column=6).value,
board=data_sheet.cell(row=row_index, column=7).value,
fti_price=None,
competitor_name=None,
competitor_price=None
)
return result
|
Java
|
UTF-8
| 384 | 2.640625 | 3 |
[] |
no_license
|
package mistra.com.StringTest.parameterTransfer;
/**
* Created by Mistra
* Date: 2018/1/25/025
* Time: 23:11
*/
/**
* String传参测试
*/
public class ParameterTransferTest2 {
public static void main(String [] args){
String str = "a";
change(str);
System.out.println(str);
}
public static void change(String i) {
i = "b";
}
}
|
Java
|
UTF-8
| 1,233 | 2.140625 | 2 |
[] |
no_license
|
package com.Requestproject.RequestProject.Service;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.Requestproject.RequestProject.Domain.Systemuser;
import com.Requestproject.RequestProject.Domain.Userprincipal;
import com.Requestproject.RequestProject.Repository.SystemuserRepository;
@Service
public class AuthuserService implements UserDetailsService{
@Autowired
private SystemuserRepository userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
/*
* Optional<Systemuser> optionalUser = userDao.findByUuid(username); if
* (optionalUser.isPresent()) { return optionalUser.get(); } else { throw new
* UsernameNotFoundException("Incorrect credentials"); }
*/
Systemuser systemuser = userDao.findByUsername(username);
if(systemuser==null)
throw new UsernameNotFoundException("User 404");
return systemuser;
}
}
|
PHP
|
UTF-8
| 559 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
<?php namespace App\Forms;
use Distilleries\FormBuilder\FormValidator;
class VenueForm extends FormValidator
{
public static $rules = [];
public static $rules_update = null;
public function buildForm()
{
$this
->add('name', 'textarea')
->add('address', 'address_picker', [
'default_value' => [
'lat' => 10,
'lng' => 10,
'street' => '42 Wallaby Way',
'city' => 'Sydney',
'country' => 'Australia',
'default' => '42 Wallaby Way, Sydney, Australia',
]
]);
$this->addDefaultActions();
}
}
|
Python
|
UTF-8
| 191 | 2.90625 | 3 |
[] |
no_license
|
# 创建临时文件夹和临时文件
import tempfile
dirpath = tempfile.mkdtemp()
print(dirpath)
f = tempfile.NamedTemporaryFile(prefix='haha-', dir=dirpath, delete=False)
print(f.name)
|
C++
|
UTF-8
| 10,180 | 2.78125 | 3 |
[] |
no_license
|
#include "config.h"
#include "asearch.h"
#include "math.h"
#include <vector>
#include <cstring>
#include <stdio.h>
#include <iostream>
#include <queue>
#include <stack>
#include <tuple>
using namespace std;
aStar::aStar(vector<Obstacle> obstacles, int maxDistFromBorder): maxDistFromBorder(maxDistFromBorder){
grid = new Map(obstacles, maxDistFromBorder);
}
void aStar::generatePossibleActions(Obstacle obstacle){
ActionStraight* forward = new ActionStraight(1);
ActionStraight* reverse = new ActionStraight(-1);
ActionTurnOnSpot* leftOnSpot = new ActionTurnOnSpot(90);
ActionTurnOnSpot* rightOnSpot = new ActionTurnOnSpot(-90);
ActionTurn2By4* left = new ActionTurn2By4(90);
ActionTurn2By4* right = new ActionTurn2By4(-90);
ActionReverseTurn2By4* reverseLeft = new ActionReverseTurn2By4(90);
ActionReverseTurn2By4* reverseRight = new ActionReverseTurn2By4(-90);
possibleActions.clear();
possibleActions.push_back(forward);
possibleActions.push_back(reverse);
possibleActions.push_back(leftOnSpot);
possibleActions.push_back(rightOnSpot);
possibleActions.push_back(left);
possibleActions.push_back(right);
possibleActions.push_back(reverseLeft);
possibleActions.push_back(reverseRight);
}
State* aStar::generateGoalState(Obstacle obstacle){
int goalXGrid = obstacle.xGrid + ((int)cos(M_PI/180*obstacle.face_direction))*ROBOT_VIEWING_GRID_LENGTH;
int goalYGrid = obstacle.yGrid + ((int)sin(M_PI/180*obstacle.face_direction))*ROBOT_VIEWING_GRID_LENGTH;
if(!grid->isValidGrid(goalXGrid, goalYGrid)){
cout << "grid at " << goalXGrid << ", " << goalYGrid << " is not empty. Check with the position near to obstacle is available" << endl;
goalXGrid = obstacle.xGrid + ((int)cos(M_PI/180*obstacle.face_direction))*(ROBOT_VIEWING_GRID_LENGTH - 1);
goalYGrid = obstacle.yGrid + ((int)sin(M_PI/180*obstacle.face_direction))*(ROBOT_VIEWING_GRID_LENGTH - 1);
if(!grid->isValidGrid(goalXGrid, goalYGrid)){
cout << "Position near obstacle is also not available. Last check: 40cm from obstacle" << endl;
goalXGrid = obstacle.xGrid + ((int)cos(M_PI/180*obstacle.face_direction))*(ROBOT_VIEWING_GRID_LENGTH + 1);
goalYGrid = obstacle.yGrid + ((int)sin(M_PI/180*obstacle.face_direction))*(ROBOT_VIEWING_GRID_LENGTH + 1);
if(!grid->isValidGrid(goalXGrid, goalYGrid)){
cout << "fail to find goal state. Hamiltonian path cannot be found" << endl;
throw(nullptr);
}
}
}
// create goal state
Vertex* goalPosition = grid->findVertexByGrid(goalXGrid, goalYGrid);
int goalFaceDirection = (obstacle.face_direction + 180)%360;
State* goalState = new State(goalPosition, goalFaceDirection, nullptr);
return goalState;
}
bool aStar::isDestination(const State& curState, const State& goalState){
return (curState.position->xGrid == goalState.position->xGrid &&
curState.position->yGrid == goalState.position->yGrid &&
curState.face_direction == goalState.face_direction);
}
// A Utility Function to calculate the 'h' heuristics.
float aStar::calculateHValue(State& curState, State& goalState){ // tochange
float hCost = 0;
hCost = hCost + abs(goalState.position->xGrid - curState.position->xGrid) + abs(goalState.position->yGrid - curState.position->yGrid);
if((goalState.face_direction == 0 && curState.face_direction == 0 && goalState.position->xGrid + 1 == curState.position->xGrid && goalState.position->yGrid == curState.position->yGrid)
|| (goalState.face_direction == 90 && curState.face_direction == 90 && goalState.position->yGrid + 1 == curState.position->yGrid && goalState.position->xGrid == curState.position->xGrid)
|| (goalState.face_direction == 180 && curState.face_direction == 180 && goalState.position->xGrid - 1 == curState.position->xGrid && goalState.position->yGrid == curState.position->yGrid)
|| (goalState.face_direction == 270 && curState.face_direction == 270 && goalState.position->yGrid - 1 == curState.position->yGrid && goalState.position->xGrid == curState.position->xGrid)
){
hCost+=20; // penalise the algo when it is nearly touching the obstacle
}
return hCost;
}
// Encapsulate g cost calculation
float aStar::calculateGValue(State& curState, Action* action, Map& localMap, Obstacle& obstacle){
return curState.gCost + action->getCost(&curState, localMap, obstacle);
}
// A Utility Function to trace the path from the source to destination
float aStar::tracePath(State* goalState, vector<State*>* states){
stack<State*> Path;
State* next_node = goalState;
// trace from destination back to source
do {
Path.push(next_node);
next_node = next_node->prevState;
} while (next_node != nullptr); // at source, prev_vertex/parent = next_node
// Package into <distance: float, actions: vector<Action>> and modify the memory
states->clear();
while(!Path.empty()){
State* p = Path.top();
states->push_back(p);
Path.pop();
}
return states->back()->gCost;
}
void aStar::changeObstacleFace(Obstacle obstacle, int newFaceDirection){
vector<Obstacle>& obstacles = grid->getObstacles();
for(int i = 0; i < obstacles.size(); i++){
if(obstacles[i].id == obstacle.id){
obstacles[i].face_direction = newFaceDirection;
return;
}
}
}
State* aStar::search(State* initState, Obstacle& dest, float* pathCost, vector<State*>* states){
// Find the goal state
State* goalState = generateGoalState(dest);
// 1. Check if this search definitely fails
// Either the source or the destination is blocked
if (!grid->isAvailableGrid(initState->position->xGrid, initState->position->yGrid)){
printf("Source is blocked\n");
return nullptr;
}
// If the destination cell is the same as source cell
if (isDestination(*initState, *goalState)) {
printf("We already detected %d at (%d, %d)\n", dest.id, dest.xGrid, dest.yGrid);
return nullptr;
}
// 2. Initialise useful variables
// Create a closed list and initialise it to false ie no cell is visited yet
generatePossibleActions(dest); // a. all 5 actions
Map localMap = *grid; // b. local map so that the original map is not modified after every search
bool closedList[X_GRID_COUNT + 2*maxDistFromBorder][Y_GRID_COUNT + 2*maxDistFromBorder][4]; // c. check if the state is visited (5 actions)
memset(closedList, false, sizeof(closedList));
State* cellDetails[X_GRID_COUNT + 2*maxDistFromBorder][Y_GRID_COUNT + 2*maxDistFromBorder][4]; // d. get the latest state detail at that position and face direction
memset(cellDetails, false, sizeof(cellDetails));
priority_queue<Tuple, vector<Tuple>, greater<Tuple> > openList; // e. Priority Queue <f-cost, state>
// for indexing purposes. For cellDetails, 0 degree to 0, 90 corresponds to 1, 180 to 2, -90 to 3
int faceDirection = (int)(initState->face_direction)/90;
// 3. Set up initial state
Vertex* position = initState->position;
initState->gCost = initState->hCost = 0.0;
initState->prevState = nullptr;
cellDetails[position->xGrid + maxDistFromBorder][position->yGrid + maxDistFromBorder][faceDirection] = initState; // mark as visited
openList.emplace(Tuple(0.0, initState));
// 4. A* algorithm begins
while (!openList.empty()) {
const Tuple& p = openList.top();
State* source = get<1>(p);
// Remove this vertex from the open list
openList.pop();
closedList[source->position->xGrid + maxDistFromBorder][source->position->yGrid + maxDistFromBorder][source->face_direction/90] = true;
// start finding next states/ neighbours
for(int i = 0; i < possibleActions.size(); i++){
State* neighbourState = possibleActions[i]->takeAction(source, localMap);
// if action fails to be taken, skip
if(neighbourState == nullptr) continue;
// if action sees the image, proceed to trace path
if(isDestination(*neighbourState, *goalState)){
neighbourState->gCost = calculateGValue(*source, possibleActions[i], localMap, dest);
*pathCost = tracePath(neighbourState, states);
return neighbourState;
}
Vertex* neighbourPosition = neighbourState->position;
int neighbourFaceDirection = (int)(neighbourState->face_direction)/90;
bool newlySeenState = false;
if(cellDetails[neighbourPosition->xGrid + maxDistFromBorder][neighbourPosition->yGrid + maxDistFromBorder][neighbourFaceDirection] != nullptr){
neighbourState = cellDetails[neighbourPosition->xGrid + maxDistFromBorder][neighbourPosition->yGrid + maxDistFromBorder][neighbourFaceDirection];
}
else{
newlySeenState = true;
cellDetails[neighbourPosition->xGrid + maxDistFromBorder][neighbourPosition->yGrid + maxDistFromBorder][neighbourFaceDirection] = neighbourState;
}
// If the successor is not yet in the closed list
if(!closedList[neighbourPosition->xGrid + maxDistFromBorder][neighbourPosition->yGrid + maxDistFromBorder][neighbourFaceDirection]){
float gNew, hNew, fNew;
gNew = calculateGValue(*source, possibleActions[i], localMap, dest);
hNew = calculateHValue(*neighbourState, *goalState);
fNew = gNew + hNew;
if(newlySeenState || neighbourState->gCost + neighbourState->hCost > fNew){
openList.push(Tuple(fNew, neighbourState));
neighbourState->gCost = gNew;
neighbourState->hCost = hNew;
neighbourState->prevState = source; // need to link to previous cellDetail?
}
}
}
}
// When the destination cell is not found
printf("Failed to find the Destination Cell\n");
return nullptr;
}
|
Java
|
UTF-8
| 2,103 | 2.640625 | 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 logica;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.DateTimeException;
import java.time.LocalDate;
import javax.swing.JOptionPane;
import vista.RangoFechasDialogo;
import vista.VPrincipal;
/**
*
* @author ÓSCAR SUÁREZ
*/
public class RangoLog implements ActionListener {
private RangoFechasDialogo ventana;
private LocalDate fechaInicio;
private LocalDate fechaFinal;
public RangoLog(VPrincipal padre) {
ventana = new RangoFechasDialogo(padre, true);
ventana.setOyente(this);
ventana.setLocationRelativeTo(padre);
ventana.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "introducir":
try {
fechaInicio = ventana.getFechaInicio();
fechaFinal = ventana.getFechaFinal();
if (fechaInicio.compareTo(fechaFinal) > 0) {
LocalDate tmp = fechaFinal;
fechaFinal = fechaInicio;
fechaInicio = tmp;
}
ventana.dispose();
} catch (DateTimeException ex) {
JOptionPane.showMessageDialog(ventana, "La fecha es incorrecta");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(ventana, "Solo se admiten numeros enteros");
}
break;
case "cancelar":
fechaInicio = null;
fechaFinal = null;
ventana.dispose();
break;
default:
throw new AssertionError();
}
}
public LocalDate getFechaIni() {
return fechaInicio;
}
public LocalDate getFechaFin() {
return fechaFinal;
}
}
|
Java
|
UTF-8
| 883 | 2.609375 | 3 |
[] |
no_license
|
package console_user_registration;
public class User {
private long Id;
private String login;
private String password;
private UserRole role;
public User() {}
public User(String login, String password,long Id)
{
this.login = login;
this.password = password;
this.Id = Id;
this.role = UserRole.User;
}
public UserRole getRole() { return role; }
public void setRole(UserRole role) { this.role = role; }
public long getId() {
return Id;
}
public void setId(long id) {
this.Id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return "\nYour login: " + login + " \nYour password: " + password + " \nYour ID: " + Id;
}
}
|
Java
|
UTF-8
| 1,106 | 1.921875 | 2 |
[] |
no_license
|
/**
* null
*/
package com.cosmicsms.api.sdk.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.cosmicsms.api.sdk.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* GetRestAccountBalanceResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetRestAccountBalanceResultJsonUnmarshaller implements Unmarshaller<GetRestAccountBalanceResult, JsonUnmarshallerContext> {
public GetRestAccountBalanceResult unmarshall(JsonUnmarshallerContext context) throws Exception {
GetRestAccountBalanceResult getRestAccountBalanceResult = new GetRestAccountBalanceResult();
return getRestAccountBalanceResult;
}
private static GetRestAccountBalanceResultJsonUnmarshaller instance;
public static GetRestAccountBalanceResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new GetRestAccountBalanceResultJsonUnmarshaller();
return instance;
}
}
|
C#
|
UTF-8
| 3,981 | 2.828125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
namespace UniversalAutomaticPackage.Configuration
{
public class StandardConfigurationFile
{
public static readonly Version FileStandardVersion = new Version(1, 0, 0, 0);
Dictionary<string, List<string>> Data = new Dictionary<string, List<string>>();
public StandardConfigurationFile()
{
}
string IniFile = "";
public StandardConfigurationFile(string location)
{
IniFile = location;
LoadFromFile();
}
public List<string> GetValues(string key, string Fallback = "")
{
if (Data.ContainsKey(key)) return Data[key];
else
{
List<string> vs = new List<string>();
vs.Add(Fallback);
return vs;
}
}
public void RemoveKey(string key)
{
if(Data.ContainsKey(key))
Data.Remove(key);
}
public void RemoveAt(string key,int id)
{
if (Data.ContainsKey(key))
Data[key].RemoveAt(id);
}
public void AddValue(string key, string value)
{
if (Data.ContainsKey(key)) Data[key].Add(value);
else
{
Data.Add(key, new List<string>());
Data[key].Add(value);
}
}
public void UpdateValue(string key,int id, string value)
{
if (Data.ContainsKey(key))
{
if (Data[key].Count > id)
{
Data[key][id] = value;
}
}
else
{
Data.Add(key, new List<string>());
Data[key].Add(value);
}
}
public void LoadFromFile()
{
try
{
Data = new Dictionary<string, List<string>>();
var lines = File.ReadAllLines(IniFile);
foreach (var item in lines)
{
if (item.IndexOf('=') > 0 && (!item.StartsWith("#")))
{
string key = item.Substring(0, item.IndexOf("="));
string value = item.Substring(item.IndexOf("=") + 1);
if (Data.ContainsKey(key))
{
Data[key].Add(value);
}
else
{
Data.Add(key, new List<string>());
Data[key].Add(value);
}
}
}
}
catch (Exception)
{
}
}
public void Save(string comment = "")
{
File.WriteAllText(IniFile, $"[Generated by UniversalAutomaticPackage.Configuration,{FileStandardVersion.ToString()}]");
if (comment != "")
{
File.AppendAllText(IniFile, "" + comment);
}
foreach (var item in Data)
{
foreach (var value in item.Value)
{
File.AppendAllText(IniFile, Environment.NewLine + $"{item.Key}={value}");
}
}
}
public void SaveToFile(string location, string comment = "")
{
string OriLoca = IniFile;
IniFile = location;
Save(comment);
IniFile = OriLoca;
}
public void LoadFromFile(string location)
{
IniFile = location;
LoadFromFile();
}
public static StandardConfigurationFile InitFromFile(string location)
{
StandardConfigurationFile standardConfigurationFile = new StandardConfigurationFile(location);
return standardConfigurationFile;
}
}
}
|
Markdown
|
UTF-8
| 17,356 | 2.671875 | 3 |
[] |
no_license
|
谎言也有善意的吗?或许有吧。当“神巫先生”接过陆青递来的不知名杖子时,张世宁从先生的神情中察觉到一丝异样,这令他不安。不过当他意识到对方不太有威胁自己的动机时,心神又舒缓了下来。法杖的震动极有规律,世宁心想,若是自己稍加点拨,听懂这个节律应该不难。先生不愧是先生,他同样察觉到了世宁的微表情,轻声念出了法杖震动的节律:“滴哒滴滴哒滴哒哒哒——”
先生收起法杖,又交还给陆青,说:“马先生无忧了,过几日便会回来。”
山寨一行人吃完饭便收兵回寨,临行前袁先生还叮嘱让世宁收拾停当就尽快过来。世宁当然不会放过这个向大师学习的机会,他帮陈叔家忙完几日的农活,便准备上山。子惜也觉得先生新奇,遂欲上山,两人便一同出了门。
未几,两人来到山寨,子惜照例吹了一声长口哨,看门的小哥打开寨门,说道:“子惜妹妹好久没来了哟。”
子惜笑着说:“本姑娘想来就来,想走就走。”
刚进寨门,世宁便听到一阵琴声。子惜指着前方的某个角落说:“顺着琴声就可以找到神巫先生啦。”
世宁好奇的问:“话说这个‘神巫先生’什么来头呀,‘神巫’不是一个地名吗?”
“你呀你呀,亏你和先生聊了那么久,居然这都不知道。先生当年曾在神巫一家叫什么来着的学院教学生,后来因为支持陈归南先生,被打压了。有一次好几个巫师联合使用巫术偷袭他,结果被他全部反杀,一下子就闻名了。”
言语间,琴声越来越响亮,他们隔着窗户已经能看到神巫先生了。“袁先生,我们过来了!”子惜冲着屋内的袁先生招手。
袁先生也不立刻回话,只是自顾自地弹琴。“读书人就是这样!”子惜气鼓鼓地说到。且待到他一曲弹毕,捋顺衣袍,缓缓起身,这才出门相迎。“子惜,我和世宁有些要事要谈。”袁先生说到。子惜反复端详二人,说:“嚯,原来还有本姑娘不能知道的秘密。”说罢就灰溜溜地走了。
袁先生将世宁请进门,观察了周围无人后,便请世宁坐下,然后问道:“世宁,你知道为什么我一定要带你云游吗?”
“这件事我也很好奇,不过先生如果不说,自然有您的道理。”
“哈哈哈,今天你过来,我就可以跟你细说了。是这样的,之前我们山寨夺来的矿物我们自己没有能力做精加工,只能托黑市转给别的厂家处理,你们家的厂子就是一个重要的处理点。你父亲是不是‘陈党’我不太清楚,毕竟我只是马寨主和他们的中间人,不过他的确帮了我们大忙。这次他入狱,我们也是多方营救,但看守太严,无从下手。现在你既然到这里了,我们也理应以礼相待。我看你颇有天赋,和你交谈之后又觉得你是可塑之才,所以邀你一同云游,弥补之前在矿坑荒废的时间。”
世宁听罢,恍然大悟,之前的疑问烟消云散。“承蒙先生抬爱,能与鼎鼎大名的‘神巫先生’一同云游是小宁的荣幸。”
袁先生点头称是,说到:“我们就不说客套话了,聊一下后面的计划吧。昨天晚上马先生已经被秘密接回来了,现在正在休息。我准备一周后出发,这几天我会教授你一些奥数的基础知识,你好生学习。等我和寨主交接完,咱们就出发。”
世宁问道:“嗯,是这样呀。那我们出发之后准备去什么地方呢?”
“你父亲被关在州治,郡治现在也在通缉你,所以这两个地方我们暂时不要去了。我们沿水路直接去棘州,我和两位老朋友约好在那里见面。在那里玩几天后乘船沿着大隙往东航行,直达天河。那里最近有一场文武会的文武比赛,不可错过。再然后我会回一趟神巫郡,了结一些旧事。”
这几日袁先生白天处理山寨的遗留事务,晚上就给世宁讲课,让他白天自己练习。教习时,袁先生忍不住抱怨山寨的管理过于混乱,他花了将近十天总算是理清了当前的情况,并逐一处理之前的遗留问题。学了数日,世宁觉得教习的内容实在过于简单,抱怨道:“先生,虽然我明白现在是在打基础,可是我每天所学不过是认认新词,闭目养神,然后就是对着烛光发呆。这些与奥数有多大关联呢?”
袁先生对这番质疑似乎毫不惊讶,笑道:“我当年也和你有一样的疑问。既然你已经提出来了,我就细细说来。你看这新词,不过是你之前认识的字的排列组合,可是意思却完全不一样。譬如这个‘相’,在朝廷里是个官职,也可以是一个介词,还可以是棋子的名称。在奥术领域,‘相’是指同一个世界在不同异变分支的表现状态。闭目是为了冥想,你的通感能力需要长期的冥想进行强化,哪怕你冥想过程中睡着了也可以帮助到提升。至于让你观察烛火,是为了提高你的专注度。你现在做事情总是容易分神。猫进来了就撸几下,开饭了就第一时间冲出去,外边有一点风吹草动你就扭过头去看。像你这样分神,什么时候才能打通奥术之门呢?”
世宁自觉惭愧,低下头,继续写字。
“《奥术集》看得懂吗?”袁先生问道。
“我只是之前扫了一眼,里面好多字不认识,完全搞不明白。”世宁尴尬地说。“这是唐征送我的,他说他看不懂,交给我更合适。”
“哈哈,这家伙,装什么呢,他家也不像是白丁呀。上次我回山寨路上还遇到他呢,不知道哪根筋搭错了,就装作不认识我。”袁笑道。
“上次?就是马先生遇袭之后吗?”
“没错,当事我正在郡治和下游接洽,正巧在路上遇到他了。看起来心事重重地。”
“他不是死了吗,怎么会出现在郡治呢?先生可以告诉我更多关于他的信息吗?”
袁先生一时也懵了,说:“这事老马也没跟我说呀,我说他怎么把自家暗桩给撤了呢。待会我去问问他。这个唐征是我们在矿区招募的一位暗桩,负责为我们提供运矿的情报。不过他应该不止为我们一家提供情报,如今结合这件事,我更确定了。真是个复杂的家伙呀。”
结束功课,袁带着世宁一起去探望马哨儿。马哨儿听到动静,早已提前起来,候在门边。与上次码头相遇相比,这次他更消瘦了,脸色也是白的吓人。“袁先生,张小弟,你们过来有什么事情吗?”
“看望一下你算不算要事呀?”袁笑道。
三人进了屋,袁开门见山:“唐征怎么回事呀,为什么都传他已经死了?不干暗桩了吗?”
马哨儿面露难色,但又不好不说清楚:“我自然是没有理由瞒着你了。当时船员遇险,除了他和世宁,其他人确实都死了。他先醒过来,执意要走,还特意叮嘱我保密,就说他已经死了。我感觉他是收到了什么消息,要回去报仇了。”
“原来如此,既然他执意要走,也没必要强留他。马先生,我准备明天就出发了,去趟神巫。”袁先生说到。
马哨儿苦笑:“哎呀,你每次都这么着急走干嘛?我反正是真舍不得你,你看我没啥文化,周围这些村子这么多,管不过来呀。以前我总说做个土匪挺好的,先生一定要教我怎么去做土皇帝。我土皇帝做的累呀,为什么累呢,还不是缺一个常在身边的军师呀。”
袁先生看了看世宁,回复道:“马先生,这次我了解了心愿,以后就常留你身旁,做你的军师,如何?”
“那档子事你还挂念呢?”马哨儿神色黯淡了下来。
“冤有头债有主,我还有大事未完,真的没法安心待在山里。我之前几次出行,已经准备得差不多了,就差这最后一击。”
“你这个样子,像极了唐征!好吧,有仇不报非君子,我等着你平安归来,做我的军师。哈哈哈——”马哨儿笑道。
世宁听着二人交谈,疑惑越来越深,只感觉身边的人都心事重重。二人谈论这些时候,一旁听着的他完全是云里雾里。看起来大家都有深仇大恨未了结,那自己就先默不作声吧。
袁先生突然话锋一转,问世宁:“欸对了,世宁,之前你和唐征在矿区待了那么久,他有没有跟你说过什么关于他自己的情况?”
世宁细思,之前唐征只说自己还有一个远嫁天河的姐姐。不过既然他们与唐征并非完全一条心,自己还是暂时替他保密,免得生出事端吧。“这个他还真没说太多,他就说自己一家人都被仇家烧死了。”
“行吧二位,这么着,明天走之前一起喝我的饯行酒,怎么样?”马哨儿问到。
“恭敬不如从命!”
第二天众人一大早便聚集一堂,为袁先生和世宁送别。喝完饯行酒之后,二人准备出发,山寨众人都在下山路上的崖边向他们挥手送别。快要走出山谷时,远远听见子惜在喊留步。世宁回头望去,她正满头大汗地冲他们跑来。“等一下,世宁,给你一样东西。”
好不容易赶了过来,子惜气喘吁吁地弯下腰撑着膝盖,长吸一口气之后,立身从兜里取出一块玉制的链子。“这个是本地的护身符,保你路上平安。”
“哎呀,我们一行有两个人,怎么只有他有护身符呀?”袁先生逗趣道。
子惜低下头,想了想,说:“神巫先生有神功庇护,那需要我们这些凡人的护身符呀?”
袁先生仰天大笑,说:“我喜欢你的评价。”
二人辞别子惜,登上渡船,一路向东驶去。小舟快速通过了狭窄的水道,来到了宽阔的下游河段。世宁远远望着岸边的家乡,却又不敢上岸,百感交集。顺流而下的小舟不负众望,落日前就抵达了距离州治只有一百五十里的孤雁县城。天色渐晚,船工不愿再行,于是两人便下舟住店,准备第二天再出发。
客店就在码头不远处,一旁也有几家简陋一些的,贩夫走卒们通常就住在那些店中,更窘迫一点的直接在巷子里搭起简易的帐篷,再窘迫一些的直接抓些茅草铺在地上睡觉,嘴里还叼着草茎,一边咀嚼一边吸吮,彷佛在享用陈酿。
夜幕降临,两人吃完晚饭,回到客房准备休息。袁先生又叮嘱了一番功课,然后仰头便睡,双腿交叉搭在床沿上,未几便传来呼噜声。世宁见他睡后轰鸣如此,没了睡意,索性翻起了那本唐征送的《奥术集》。前几天袁先生教他识了许多奥术相关的生字,现在看这本书已经不像之前那么晦涩。这书讲的东西有些简略,世宁翻了好久,也没看明白这个奥术该怎么去学。倒是书上的插画挺有意思,很像自家精炼矿石的场景。
也不知什么时候,世宁突然感觉背后有人拍了一下他,他便一耸,惊得站了起来,回头细看才发现是袁先生过来了。
“看书呢?”
“哦是呢,这本书的字我已经能看懂了,就是觉得书有点简略,没讲什么有用的东西。”
袁先生拿过书来,翻了几页,微微一笑:“我以前看这本书也是这么觉得的,它好像说了些什么,但却什么也没说,最后几章下了一堆稀奇古怪的结论,结果又和现实相印证了。你知道这是为什么吗?”
“这个……我也不太明白。”
“我告诉你吧,这本书其实只是一个目录。他的每一节都是另外一本书的概要介绍,你得顺着作者的思路去把那本书看了,才能明白为什么他会这么下结论或者那样做设想。这书你现在还不要着急看,以后形势改善了,你会去学校系统学习相关知识,到时候有了一定奥术的基础了再看这个一定会有新的收获。”
“去学校?先生不教我了吗?”
“哈哈哈,不是不教你,而是有些东西我也教不了你。我虽然精通奥术,可是会用和会教是两回事。我以前在学院教的都是高阶的奥术知识,那时候下面的学生都困倒一大片。可是他们毕竟已经进了学院,多少都有一些底子,所以上课不听照样不妨碍他们学好。可是你不一样,你还小,的确需要一个循循善诱的导师帮助你入门的。”袁先生解释到。
正在此时,窗外突然传来人群的呼喊声,像是“着火啦”之类的。袁先生扒开窗户,远远望见远处河畔有一宅子着火了。周围人纷纷围过去,有的帮忙打水救火,有的帮不了忙的就躲开看热闹。大火熊熊燃烧,染红了整个江面。两岸的嘈杂声盖过了一切声响。之前还在店里兴致勃勃讲着段子的隔壁小哥也都纷纷冲下楼去欣赏这奇景。
将近深夜,嘈杂声渐渐消散了,原来是火已经被扑灭,江岸围观的人群也都星散。此刻两人早已是困倦不已,于是很快入睡了。
到次日清晨,世宁被先生叫醒,两人一同下到一楼去吃早饭。刚上桌,就听见一旁的人聚在一桌讨论昨天的火灾。“你听说了吗,昨晚益川商会会长庞之龙的宅子着火了,除了几个老人小孩,其他人全被烧死。”
“哎哟,这也太惨了,是意外还是有人放火啊?”
“衙门正在查这件事,听说可能是有人纵火。”
世宁听到“益川商会”,脑海里立刻浮现之前唐征说的话,他与袁先生双目对视,心领神会。正在此时,一队士兵冲进来,四处盘查房客的身份。袁先生望了一眼世宁,示意他先躲起来。世宁借着小二的掩护躲在了后厨。一会后,士兵们离开,世宁这才出来。“以后这种盘查还会很多,我们还是要多留个心眼。”袁先生说到。
“后厨老鼠真大。”世宁撇了撇嘴。
“自这里往下游走就可以行快船了,以前坐过吗?”
“没有,快船大吗?”
“比我们昨天坐的小舟大多了,不用人力,靠烧煤前进。”
世宁却说:“既然你们奥术师那么神通广大,为什么船儿不靠魔法驱动?”
袁先生笑道:“你这小子,奥术是沟通相与相之间的桥梁,开船跑车这种杂事我们可不管哟。”
吃完早饭,二人找了一条快船,只见这船长约二十米,宽约五六米,通身白漆,中间立着一烟囱。上船后进了船舱,逼仄闷热。先前已有许多人上船,占了位置。袁先生从行囊中取出两个小马扎,两人便这样坐着等。乘客们有的穿着长袍,有的短褐,但表情却都一致的木然。所有人都一言不发,呆滞地看着空气。每当有人进来时,所有人的目光都齐刷刷望着门口。
世宁心想既然船上如此无聊,不如静静坐着,闭目冥想,还能蓄来精神,便原地冥想起来。不知过了几时,一阵香气扑鼻而来,世宁睁开双眼,只见一位白衣姑娘从身前走过。“爸爸,船舱里有点闷,我出去透透气。”她对旁边地一位中年男子说道。
眼见她出门,世宁心中仿佛落下了什么,一时竟有些惘然。他起身出门,循着香气,来到船头。那位姑娘正在船头,手中拿着手绢,擦拭嘴角。“想必她是晕船了。”世宁默念道。
他走过去,问道:“姑娘,您这是晕船了吗?”
姑娘轻声回复:“这是我头一次坐船。”
“我叫张牧,龙潭郡人,很高兴认识你。”世宁给了她一个假名字。
“我叫柳思敏,长清郡人。我也很高兴认识你。”
说完她立刻回身返回船舱,世宁独自站在原地,一言未发。
快船的确是快船,顺着江流,下午落日前,船就已经靠棘州岸边了。棘州不愧是水运大港,往来大小船只络绎不绝。在内河难得一见地快船在这里排着队等待进港。棘州是长龙水流入大隙的入口,是水运枢纽。这里的街道宽阔,行人摩肩接踵,店铺许多都是通宵营业。一上岸,袁先生就领着世宁来到棘州最大的酒店——南方大酒店。
“客官,请问住什么间?”大门的经理问道。
“之前一位姓岳的先生是不是订了一个房间?我姓袁,这个房间就是订给我的。”
“嗯,是的。他特意叮嘱过,我这就带您去房间。”
南方大酒店整体采取西洋建筑风格,外面是西式仿古的大理石柱。屋内大堂高穹顶,有些类似于教堂的格局。来到房间,屋内宽敞透亮,全不同于之前的小客店。
“这个地方是真的宽敞呀!”世宁惊叹道。
“将来有机会的话你可以去秀丽城的花都酒店看看,比这个还要豪华。”袁先生说到。
这时,门外传来几声敲门声。“我们的客人到了。”袁先生笑道。
|
PHP
|
UTF-8
| 1,761 | 2.9375 | 3 |
[] |
no_license
|
<?php session_start();
if (isset($_POST['Logout'])) //True if user clicked the logout button
{
session_unset();
session_destroy();
header("location:index.php");
exit();
}?>
<html>
<body>
<form action="index.php" method="post">
User ID: <input type="text" placeholder="Enter user ID" name="ID"><br>
Password: <input type="password" placeholder="Enter password" name="pass"><br>
<input type="submit" value="Log In">
</form>
</body>
</html>
<?php
$id = "";
$pass = "";
if (!empty($_POST))
{
$id = $_POST["ID"];
$pass = $_POST["pass"];
if(!is_numeric($id)) //prevent the error message that would show up in the sql query if user enters a non-integer
{ $id = -1; }
// Create connection
$con=mysqli_connect("localhost","root","","471");
// Check connection
if (mysqli_connect_errno($con))
{ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$sql = mysqli_query($con, "SELECT Admin, Employee_ID FROM Employee WHERE Employee_ID=$id AND Password='$pass'");
if (0 == mysqli_num_rows($sql))
{
$sql = mysqli_query($con, "SELECT Prac_ID FROM Physician WHERE Prac_ID=$id AND Password='$pass'");
if (0 == mysqli_num_rows($sql))
{
echo "Login failed. Please try again. <br>";
}
else
{
$temp = mysqli_fetch_array($sql);
$_SESSION['Admin'] = "0"; //All physicians are not admins
$_SESSION['ID'] = $temp["Prac_ID"];
$_SESSION['EmpPhys'] = "P";
header("Location:home.php");
exit();
}
}
else
{
$temp = mysqli_fetch_array($sql);
$_SESSION['Admin'] = $temp["Admin"];
$_SESSION['ID'] = $temp["Employee_ID"];
$_SESSION['EmpPhys'] = "E";
header("Location:home.php");
exit();
};
mysqli_close($con);
}
?>
|
Ruby
|
UTF-8
| 155 | 2.578125 | 3 |
[] |
no_license
|
puts "Bonjour, monde !"
#puts "Et avec une voix sexy, ça donne : Bonjour, monde !"
#En ajouter un hashtag devant la ligne celle-ci devient un commentaire
|
C++
|
UTF-8
| 1,101 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
#include <gtest/gtest.h>
#include <fstream>
#include "graph.hpp"
#include "errors.hpp"
TEST(GraphTest, SimpleGraphShortestPath) {
ga::Graph::pretty_print_flag(true);
bool set_connected = false;
bool set_use_color = true;
bool set_use_style = true;
bool set_show_labels = true;
bool set_landscape = false;
// ga::Graph *g = ga::random_graph(100, 150, set_connected, set_use_color, set_use_style);
ga::Graph g;
std::fstream f("test_graph.json");
try {
f >> g;
} catch (ga::graph_exception e) {
std::cerr << e.what() << std::endl;
throw e;
}
std::cout << g << std::endl << std::endl;
std::cout << "Shortest path from 'A' to 'D': " << std::flush;
std::list<ga::Node*> path = ga::shortest_path(g.find_node("A"), g.find_node("D"), true);
std::cout << path << std::endl;
std::fstream f_out("test_graph.dot", std::ios::out);
std::unordered_set<std::string> print_labels = {"name", "weight", "path" };
to_graphviz(f_out, g, print_labels, set_use_color, set_use_style, set_landscape) << std::endl;
}
|
Java
|
UTF-8
| 6,200 | 2.296875 | 2 |
[] |
no_license
|
package com.financialassets.entity;
import com.financialassets.apiclient.IEXQuoteClient;
import com.financialassets.apiclient.IEXQuoteResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
@Entity(name = "UserAsset")
@Table(name = "user_asset")
public class UserAsset {
@Transient
private final Logger logger = LogManager.getLogger(this.getClass());
@Column(name = "user_asset_id")
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(name = "native", strategy = "native")
private int userAssetId;
@Column(name = "buy_price")
private double buyPrice;
@Column(name = "sell_price")
private BigDecimal sellPrice;
@Column(name = "buy_date")
private LocalDate buyDate;
@Column(name = "sell_date")
private LocalDate sellDate;
private Integer qty;
@Column(name = "asset_name")
private String assetName;
private double fees;
@ManyToOne
@JoinColumn(name = "user_id",
foreignKey = @ForeignKey(name = "user_asset_id_fk"))
private User user;
@Transient
private double gainOrLossDollar;
@Transient
private double gainOrLossPercent;
public void setQty(Integer qty) {
this.qty = qty;
}
public Integer getQty() {
return qty;
}
/**
*
* @return the gain or loss of the asset in USD
*/
public double getGainOrLossDollar() {
return gainOrLossDollar;
}
/**
*
* @return the gain or loss percent
*/
public double getGainOrLossPercent() {
return gainOrLossPercent;
}
/**
*
* @param name the stock symbol
*
*/
public void setUnsoldGainOrLoss(String name) {
IEXQuoteClient quoteClient = new IEXQuoteClient();
DecimalFormat dollarFormat = new DecimalFormat("#.####");
DecimalFormat percentFormat = new DecimalFormat("#.##");
double longDollar;
double longPercent;
// If unsold
if (sellPrice == null) {
try {
IEXQuoteResponse quote = quoteClient.getJSONResults(this.assetName);
longDollar = (quote.getLatestPrice() - buyPrice) * qty - fees;
longPercent = (longDollar / (buyPrice * qty)) * 100;
this.gainOrLossDollar = Double.parseDouble(dollarFormat.format(longDollar));
this.gainOrLossPercent = Double.parseDouble(percentFormat.format(longPercent));
} catch (Exception e) {
logger.error(e);
}
// If sold
} else {
longDollar = (sellPrice.doubleValue() - buyPrice) * qty - fees;
longPercent = (longDollar / (buyPrice * qty)) * 100;
this.gainOrLossDollar = Double.parseDouble(dollarFormat.format(longDollar));
this.gainOrLossPercent = Double.parseDouble(percentFormat.format(longPercent));
}
}
/**
*
* @return all associated fees
*/
public double getFees() {
return fees;
}
/**
*
* @param fees all asset associated fees
*/
public void setFees(double fees) {
this.fees = fees;
}
/**
* Gets user asset id.
*
* @return the user asset id
*/
public int getUserAssetId() {
return userAssetId;
}
/**
* Sets user asset id.
*
* @param userAssetId the user asset id
*/
public void setUserAssetId(int userAssetId) {
this.userAssetId = userAssetId;
}
/**
* Gets buy price.
*
* @return the buy price
*/
public double getBuyPrice() {
return buyPrice;
}
/**
* Sets buy price.
*
* @param buyPrice the buy price
*/
public void setBuyPrice(double buyPrice) {
this.buyPrice = buyPrice;
}
/**
* Gets sell price.
*
* @return the sell price
*/
public BigDecimal getSellPrice() {
return sellPrice;
}
/**
* Sets sell price.
*
* @param sellPrice the sell price
*/
public void setSellPrice(BigDecimal sellPrice) {
this.sellPrice = sellPrice;
}
/**
* Gets buy date.
*
* @return the buy date
*/
public LocalDate getBuyDate() {
return buyDate;
}
/**
* Sets buy date.
*
* @param buyDate the buy date
*/
public void setBuyDate(LocalDate buyDate) {
this.buyDate = buyDate;
}
/**
* Gets sell date.
*
* @return the sell date
*/
public LocalDate getSellDate() {
return sellDate;
}
/**
* Sets sell date.
*
* @param sellDate the sell date
*/
public void setSellDate(LocalDate sellDate) {
this.sellDate = sellDate;
}
/**
* Gets asset name.
*
* @return the asset name
*/
public String getAssetName() {
return assetName;
}
/**
* Sets asset name.
*
* @param assetName the asset name
*/
public void setAssetName(String assetName) {
this.assetName = assetName;
}
/**
* Gets user.
*
* @return the user
*/
public User getUser() {
return user;
}
/**
* Sets user.
*
* @param user the user
*/
public void setUser(User user) {
this.user = user;
}
/**
* No arg constructor
*/
public UserAsset() {
}
/**
* Instantiates a new User asset.
*
*
* @param buyPrice the buy price
* @param buyDate the buy date
* @param qty the qty
* @param assetName the asset name
*
*/
public UserAsset(User user, double buyPrice, LocalDate buyDate, Integer qty, String assetName, Double fees) {
this.buyPrice = buyPrice;
this.buyDate = buyDate;
this.qty = qty;
this.assetName = assetName;
this.user = user;
this.fees = fees;
}
}
|
C++
|
UTF-8
| 8,397 | 3.03125 | 3 |
[] |
no_license
|
// CCarTests.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "../ConsoleApplication1/Car.h"
struct CCarFixture
{
CCar carTest;
};
/*
ТЕСТЫ:
- Двигатель автомобиля может находиться как во включенном состоянии, так и в выключенном.
- В автомобиле может быть включена одна из следующих передач:
Задний ход (-1)
Нейтральная передача (0)
Первая передача (1)
Вторая передача (2)
Третья передача (3)
Четвертая передача (4)
Пятая передача (5)
Другие передачи включить невозможно
- На каждой передаче можно развить скорость в пределах отведенного данной передаче диапазона.
Задний ход: 0 – 20
Нейтраль: Без ограничений
Первая: 0 – 30
Вторая: 20 – 50
Третья: 30 – 60
Четвертая: 40 – 90
Пятая: 50 – 150
- Нейтральная передача, на которой скорость можно изменить только в сторону нуля.
- На задний ход можно переключиться только с нейтральной или первой передачи на нулевой скорости
- C заднего хода можно переключиться на первую передачу только на нулевой скорости
- Переключившись на заднем ходу на нейтральную передачу на ненулевой скорости, переключиться на первую передачу можно только после остановки
*/
BOOST_FIXTURE_TEST_SUITE(Car, CCarFixture)
BOOST_AUTO_TEST_CASE(EngineCanBeTurnOnOrTurnOff)
{
BOOST_CHECK(carTest.TurnOnEngine());
BOOST_CHECK(carTest.IsTurnedOn());
BOOST_CHECK(carTest.TurnOffEngine());
BOOST_CHECK(!carTest.IsTurnedOn());
}
BOOST_AUTO_TEST_CASE(CarCanSetGearFromMinus1To5)
{
BOOST_CHECK(carTest.TurnOnEngine());
BOOST_CHECK(carTest.IsTurnedOn());
BOOST_CHECK(carTest.SetGear(-1));
BOOST_CHECK_EQUAL(carTest.GetGear(), -1);
BOOST_CHECK(carTest.SetGear(0));
BOOST_CHECK_EQUAL(carTest.GetGear(), 0);
BOOST_CHECK(carTest.SetGear(1));
BOOST_CHECK_EQUAL(carTest.GetGear(), 1);
BOOST_CHECK(carTest.SetSpeed(20));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 20);
BOOST_CHECK(carTest.SetGear(2));
BOOST_CHECK_EQUAL(carTest.GetGear(), 2);
BOOST_CHECK(carTest.SetSpeed(50));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 50);
BOOST_CHECK(carTest.SetGear(3));
BOOST_CHECK_EQUAL(carTest.GetGear(), 3);
BOOST_CHECK(carTest.SetGear(4));
BOOST_CHECK_EQUAL(carTest.GetGear(), 4);
BOOST_CHECK(carTest.SetGear(5));
BOOST_CHECK_EQUAL(carTest.GetGear(), 5);
BOOST_CHECK(!carTest.SetGear(6));
BOOST_CHECK_EQUAL(carTest.GetGear(), 5);
BOOST_CHECK(!carTest.SetGear(-2));
BOOST_CHECK_EQUAL(carTest.GetGear(), 5);
}
BOOST_AUTO_TEST_CASE(CheckSpeedRange)
{
{
BOOST_CHECK(carTest.TurnOnEngine());
BOOST_CHECK(carTest.IsTurnedOn());
BOOST_CHECK(carTest.SetGear(-1));
BOOST_CHECK_EQUAL(carTest.GetGear(), -1);
BOOST_CHECK(carTest.SetSpeed(20));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 20);
BOOST_CHECK(!carTest.SetSpeed(21));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 20);
BOOST_CHECK(!carTest.SetSpeed(-1));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 20);
}
{
BOOST_CHECK(carTest.SetGear(0));
BOOST_CHECK_EQUAL(carTest.GetGear(), 0);
BOOST_CHECK(carTest.SetSpeed(0));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 0);
BOOST_CHECK(carTest.SetGear(1));
BOOST_CHECK_EQUAL(carTest.GetGear(), 1);
BOOST_CHECK(carTest.SetSpeed(30));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 30);
BOOST_CHECK(!carTest.SetSpeed(31));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 30);
BOOST_CHECK(!carTest.SetSpeed(-1));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 30);
}
{
BOOST_CHECK(carTest.SetGear(2));
BOOST_CHECK_EQUAL(carTest.GetGear(), 2);
BOOST_CHECK(carTest.SetSpeed(20));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 20);
BOOST_CHECK(!carTest.SetSpeed(19));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 20);
BOOST_CHECK(carTest.SetSpeed(50));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 50);
BOOST_CHECK(!carTest.SetSpeed(51));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 50);
}
{
BOOST_CHECK(carTest.SetGear(3));
BOOST_CHECK_EQUAL(carTest.GetGear(), 3);
BOOST_CHECK(carTest.SetSpeed(30));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 30);
BOOST_CHECK(!carTest.SetSpeed(29));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 30);
BOOST_CHECK(carTest.SetSpeed(60));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 60);
BOOST_CHECK(!carTest.SetSpeed(61));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 60);
}
{
BOOST_CHECK(carTest.SetGear(4));
BOOST_CHECK_EQUAL(carTest.GetGear(), 4);
BOOST_CHECK(carTest.SetSpeed(40));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 40);
BOOST_CHECK(!carTest.SetSpeed(39));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 40);
BOOST_CHECK(carTest.SetSpeed(90));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 90);
BOOST_CHECK(!carTest.SetSpeed(91));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 90);
}
{
BOOST_CHECK(carTest.SetGear(5));
BOOST_CHECK_EQUAL(carTest.GetGear(), 5);
BOOST_CHECK(carTest.SetSpeed(50));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 50);
BOOST_CHECK(!carTest.SetSpeed(49));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 50);
BOOST_CHECK(carTest.SetSpeed(150));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 150);
BOOST_CHECK(!carTest.SetSpeed(151));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 150);
}
}
BOOST_AUTO_TEST_CASE(CheckNeutralGear)
{
BOOST_CHECK(carTest.TurnOnEngine());
BOOST_CHECK(carTest.IsTurnedOn());
BOOST_CHECK(carTest.SetGear(-1));
BOOST_CHECK_EQUAL(carTest.GetGear(), -1);
BOOST_CHECK(carTest.SetSpeed(20));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 20);
BOOST_CHECK(carTest.SetGear(0));
BOOST_CHECK_EQUAL(carTest.GetGear(), 0);
BOOST_CHECK(carTest.SetSpeed(1));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 1);
BOOST_CHECK(carTest.SetSpeed(0));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 0);
BOOST_CHECK(!carTest.SetSpeed(1));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 0);
}
BOOST_AUTO_TEST_CASE(CheckBackGear)
{
BOOST_CHECK(carTest.TurnOnEngine());
BOOST_CHECK(carTest.IsTurnedOn());
BOOST_CHECK_EQUAL(carTest.GetGear(), 0);
BOOST_CHECK(carTest.SetGear(-1));
BOOST_CHECK_EQUAL(carTest.GetGear(), -1);
BOOST_CHECK(carTest.SetGear(1));
BOOST_CHECK_EQUAL(carTest.GetGear(), 1);
BOOST_CHECK(carTest.SetSpeed(1));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 1);
BOOST_CHECK(!carTest.SetGear(-1));
BOOST_CHECK_EQUAL(carTest.GetGear(), 1);
BOOST_CHECK(carTest.SetSpeed(0));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 0);
BOOST_CHECK(carTest.SetGear(-1));
BOOST_CHECK_EQUAL(carTest.GetGear(), -1);
}
BOOST_AUTO_TEST_CASE(FromBackGear)
{
BOOST_CHECK(carTest.TurnOnEngine());
BOOST_CHECK(carTest.IsTurnedOn());
BOOST_CHECK_EQUAL(carTest.GetGear(), 0);
BOOST_CHECK(carTest.SetGear(1));
BOOST_CHECK_EQUAL(carTest.GetGear(), 1);
BOOST_CHECK(carTest.SetSpeed(20));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 20);
BOOST_CHECK(!carTest.SetGear(-1));
BOOST_CHECK_EQUAL(carTest.GetGear(), 1);
BOOST_CHECK(carTest.SetSpeed(0));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 0);
BOOST_CHECK(carTest.SetGear(-1));
BOOST_CHECK_EQUAL(carTest.GetGear(), -1);
}
BOOST_AUTO_TEST_CASE(FromBackToNeutral)
{
{
BOOST_CHECK(carTest.TurnOnEngine());
BOOST_CHECK(carTest.IsTurnedOn());
BOOST_CHECK_EQUAL(carTest.GetGear(), 0);
BOOST_CHECK(carTest.SetGear(-1));
BOOST_CHECK_EQUAL(carTest.GetGear(), -1);
BOOST_CHECK(carTest.SetSpeed(1));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 1);
BOOST_CHECK(carTest.SetGear(0));
BOOST_CHECK_EQUAL(carTest.GetGear(), 0);
BOOST_CHECK(!carTest.SetGear(1));
BOOST_CHECK_EQUAL(carTest.GetGear(), 0);
}
{
BOOST_CHECK(carTest.SetGear(-1));
BOOST_CHECK_EQUAL(carTest.GetGear(), -1);
BOOST_CHECK(carTest.SetSpeed(0));
BOOST_CHECK_EQUAL(carTest.GetSpeed(), 0);
BOOST_CHECK(carTest.SetGear(0));
BOOST_CHECK_EQUAL(carTest.GetGear(), 0);
BOOST_CHECK(carTest.SetGear(1));
BOOST_CHECK_EQUAL(carTest.GetGear(), 1);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
C++
|
UTF-8
| 689 | 2.734375 | 3 |
[] |
no_license
|
#ifndef TRAVELLINGPATH_H
#define TRAVELLINGPATH_H
#include<bits/stdc++.h>
using namespace std;
class TravellingPath
{
private:
vector<int > path;
int startingCity;
int fitness;
public :
static int numberOfCities;
static int travelCost[350][350];
TravellingPath(int startingCity);
TravellingPath(vector<int> permutationOfCities, int startingCity);
vector<int> getpath();
int getStartingCity();
int getFitness();
void setFitness(int fitness);
int calculateFitness();
void PrintPath();
vector<int> RandomSuffle();
};
#endif // TRAVELLINGPATH_H
|
Python
|
UTF-8
| 13,860 | 3.078125 | 3 |
[] |
no_license
|
#! /usr/bin/env python
#
# Fade an LED (or one color of an RGB LED) using GPIO's PWM capabilities.
#
# Usage:
# sudo python colors.py 255 255 255
#
# @author Jeff Geerling, 2015
import sys
import termios
import tty
import csv
import sys
import socket
import numpy as np
from scipy import stats
from sklearn import linear_model
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
import time
from collections import Counter
import math
from collections import defaultdict
import operator
import json
import argparse
import time
#import RPi.GPIO as GPIO
import pigpio
import pyrebase
import requests
from collections import defaultdict
api_key = ""
#Firebase Configuration
config = {
"apiKey": "apiKey",
"authDomain": "weatherwhisperer.firebaseapp.com",
"databaseURL": "https://weatherwhisperer.firebaseio.com",
"storageBucket": "weatherwhisperer.appspot.com"
}
firebase = pyrebase.initialize_app(config)
#Firebase Database Intialization
db = firebase.database()
# LED pin mapping.
red = 20
green = 26
blue = 21
'''
# GPIO setup.
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(red, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)
GPIO.setup(blue, GPIO.OUT)
# Set up colors using PWM so we can control individual brightness.
RED = GPIO.PWM(red, 100)
GREEN = GPIO.PWM(green, 100)
BLUE = GPIO.PWM(blue, 100)
RED.start(0)
GREEN.start(0)
BLUE.start(0)
'''
pi = pigpio.pi()
'''
Try five different models. Two kinds of linear regression plus polynomial regression with
degree two, three, and four.
Use the R^2 value to pick the most accurate one
There are so few data points, We didn't want to hold any out for cross validation
and are aware that this makes us prone to overfitting.
'''
def learn(features,target):
best_score = 0
best_model = 0
X = np.matrix(features)
Y = np.matrix(target)
ml = -1
for i in range(0,5):
if i==0:
clf = linear_model.LinearRegression()
clf = clf.fit(X,Y)
elif i==1:
clf = linear_model.Ridge(alpha=0.5)
clf = clf.fit(X,Y)
else:
clf = make_pipeline(PolynomialFeatures(i), linear_model.Ridge())
clf = clf.fit(X, Y)
current_score = clf.score(X,Y)
print(current_score)
if abs(current_score)>abs(best_score):
best_score = current_score
best_model = clf
ml = i
print("Best model: ", ml)
return best_model
# Set a color by giving RGB values of 0-255. with GPIO
def setColor(r,g,b):
# Convert 0-255 range to 0-100.
red = (r/255.0) * 100
blue = (b/255.0)*100
green = (g/255.0)*100
print(red)
print(green)
print(blue)
RED.ChangeDutyCycle(red)
GREEN.ChangeDutyCycle(green)
BLUE.ChangeDutyCycle(blue)
# Set a color by giving RGB values of 0-255. with pigpio
def setColor_Pig(r,g,b):
pi.set_PWM_dutycycle(red, r)
pi.set_PWM_dutycycle(green, g)
pi.set_PWM_dutycycle(blue, b)
#print("Red: ",r)
#print("Green: ",g)
#print("Blue: ",b)
# Set hard limits between 0 and 255 for RGB balues
def hard_limits(color):
if color > 255:
return 255
elif color < 0:
return 0
else:
return color
#Grab the current weather conditions from the weather underground API
def current_conditions(city, state, weather_string):
r = requests.get('http://api.wunderground.com/api/'+api_key+'/conditions/q/'+state+'/'+city+'.json')
values = r.json()
if city=="Boulder" and state=="CO":
print("contacting weather station")
temp = int(get_local_temp())
print("done contacting weather station")
else:
temp = round(float(values["current_observation"]["temp_f"]))
wind = float(values["current_observation"]["wind_mph"])
weather = weather_string[values["current_observation"]["weather"]]
return temp,wind,weather
#Determine whether or not we are confident in our prediction based on training data
#Currently based on whether a temperature, wind, and weather are near a training point
def test_sample(temp,wind,weather,temps,winds,weathers):
confident_t = False
confident_w = False
confident_conds = False
for t in temps:
if abs(t-temp)<10:
confident_t = True
for w in winds:
if abs(w-wind)<10:
confident_w = True
if weather in weathers:
confident_conds = True
confident = confident_t and confident_w and confident_conds
return confident
#Predict the RGB values based on the current weather conditions
def predict(reg_model,city,state,weather_string,weather_float,features):
temp,wind,weather = current_conditions(city, state, weather_string)
weather = weather_string[weather]
print([temp,wind,weather])
temps = [f[0] for f in features]
winds = [f[1] for f in features]
weathers = [f[2] for f in features]
confident = test_sample(temp,wind,weather_float[weather],temps,winds,weathers)
print("Confidence: ", confident)
if confident:
db.update({"current_conditions/learn":"Confident"})
else:
db.update({"current_conditions/learn":"Not Confident"})
closest = reg_model.predict(np.matrix([[temp,wind,weather_float[weather]]]))
red = int(np.round(closest[0][0]))
green = int(np.round(closest[0][1]))
blue = int(np.round(closest[0][2]))
#print("red: ",red)
#print("green: ",green)
#print("blue: ",blue)
red = hard_limits(red)
green = hard_limits(green)
blue = hard_limits(blue)
#red = 255
#blue = 255
#green = 0
print(red,green,blue)
setColor_Pig(red,green,blue)
return temp,wind,weather
#Add training point to database
def add_training_point(temp,wind,weather,r,g,b,total_training_points):
id_ = total_training_points
db.child("training").child("ID"+str(id_)).update({"temp":str(temp),"wind": str(wind),\
"weather": weather,"red":r,"green":g,"blue":b})
#Extract historical information for a historical request
#Used for training app
def give_me_data(request,weather_string):
v = request.json()
#print(v)
temp = round(float(v['history']['observations'][0]['tempi']))
wind = v['history']['observations'][0]['wspdi']
weather = weather_string[v['history']['observations'][0]['conds']]
#print("temp_f: " + str(temp))
#print("wind_mph: " + str(wind))
#print("weather: " + str(weather))
return temp,wind,weather
#Update the conditions if in the pre-training phase
def update_conditions(city,state,total_training_points,weather_string):
id_ = total_training_points
temp = ""
wind = ""
weather = ""
#print(city)
#print(state)
if(id_==0):
history = 'history_20160115'
r = requests.get('http://api.wunderground.com/api/'+api_key+'/'+history+'/q/'+state+'/'+city+'.json')
temp,wind,weather = give_me_data(r,weather_string)
elif(id_==1):
history = 'history_20160415'
r = requests.get('http://api.wunderground.com/api/'+api_key+'/'+history+'/q/'+state+'/'+city+'.json')
#print(r)
temp,wind,weather = give_me_data(r,weather_string)
elif(id_==2):
history = 'history_20160715'
r = requests.get('http://api.wunderground.com/api/'+api_key+'/'+history+'/q/'+state+'/'+city+'.json')
#print(r)
temp,wind,weather = give_me_data(r,weather_string)
else:
history = 'history_20161015'
r = requests.get('http://api.wunderground.com/api/'+api_key+'/'+history+'/q/'+state+'/'+city+'.json')
#print(r)
temp,wind,weather = give_me_data(r,weather_string)
return temp,wind,weather
def get_local_temp():
s = socket.socket()
host = '192.168.20.102'# ip of raspberry pi
port = 5568
s.connect((host, port))
temp = s.recv(1024)
print(temp)
s.close()
return temp.decode('utf-16')
#Extract features and target set for machine learning
def get_data(total_training_points,weather_float):
features = []
target = []
for i in range(0,total_training_points):
temp = int(db.child("training/ID"+str(i)+"/temp").get().val())
wind = float(db.child("training/ID"+str(i)+"/wind").get().val())
weather = db.child("training/ID"+str(i)+"/weather").get().val()
red = abs(float(db.child("training/ID"+str(i)+"/red").get().val())-255)
green = abs(float(db.child("training/ID"+str(i)+"/green").get().val())-255)
blue = abs(float(db.child("training/ID"+str(i)+"/blue").get().val())-255)
features.append([temp,wind,weather_float[weather]])
target.append([red,green,blue])
return features,target
#load weather descriptions
def load_conditions():
weather = defaultdict(str)
conditions = defaultdict(float)
weather["Drizzle"]="Rain"
weather["Rain"]="Rain"
weather["Snow"]="Snow"
weather["Snow Grains"]="Snow"
weather["Ice Crystals"]="Snow"
weather["Ice Pellets"]="Snow"
weather["Hail"]="Snow"
weather["Mist"]="Fog"
weather["Fog"]="Fog"
weather["Fog Patches"]="Fog"
weather["Smoke"]="Cloudy"
weather["Volcanic Ash"]="Cloudy"
weather["Widespread Dust"]="Cloudy"
weather["Sand"]="Cloudy"
weather["Haze"]="Cloudy"
weather["Spray"]="Rain"
weather["Dust Whirls"]="Cloudy"
weather["Sandstorm"]="Cloudy"
weather["Low Drifting Snow"]="Snow"
weather["Low Drifting Widespread Dust"]="Cloudy"
weather["Low Drifting Sand"]="Cloudy"
weather["Blowing Snow"]="Snow"
weather["Blowing Widespread Dust"]="Cloudy"
weather["Blowing Sand"]="Cloudy"
weather["Rain Mist"]="Rain"
weather["Rain Showers"]="Rain"
weather["Snow Showers"]="Rain"
weather["Snow Blowing Snow Mist"]="Snow"
weather["Ice Pellet Showers"]="Snow"
weather["Hail Showers"]="Rain"
weather["Small Hail Showers"]="Rain"
weather["Thunderstorm"]="Thunderstorm"
weather["Thunderstorms and Rain"]="Thunderstorm"
weather["Thunderstorms and Snow"]="Thunderstorm"
weather["Thunderstorms and Ice Pellets"]="Thunderstorm"
weather["Thunderstorms with Hail"]="Thunderstorm"
weather["Thunderstorms with Small Hail"]="Thunderstorm"
weather["Freezing Drizzle"]="Rain"
weather["Freezing Rain"]="Rain"
weather["Freezing Fog"]="Fog"
weather["Patches of Fog"]="Fog"
weather["Shallow Fog"]="Fog"
weather["Partial Fog"]="Fog"
weather["Overcast"]="Cloudy"
weather["Clear"]="Clear"
weather["Partly Cloudy"]="Partly Cloudy"
weather["Mostly Cloudy"]="Partly Cloudy"
weather["Scattered Clouds"]="Partly Cloudy"
weather["Small Hail"]="Rain"
weather["Squalls"]="Rain"
weather["Funnel Cloud"]="Cloudy"
weather["Unknown Precipitation"]="Unknown"
weather["Unknown"]="Unknown"
conditions["Snow"]=10.0
conditions["Rain"]=20.0
conditions["Thunderstorm"]=25.0
conditions["Fog"]=35.0
conditions["Cloudy"]=40.0
conditions["Partly Cloudy"]=45.0
conditions["Clear"]=60.0
conditions["Unknown"]=0.0
return weather,conditions
#Get city and state info
def get_local():
city = db.child("info/city").get().val()
state = db.child("info/state").get().val()
if city=="Washington D.C." or city == "Washington, D.C." or city=="Washington DC" or city == "Washington, DC":
city = "Washington"
state = "DC"
city = city.replace(" ","_")
return city,state
if __name__ == "__main__":
api_key = sys.argv[1]
city = ""
state = ""
weather_string,weather_float = load_conditions()
local = True
total = 0
while True:
status = db.child("info/pi_command").get().val()
on_off = db.child("info/led_state").get().val()
city,state = get_local()
total_training_points=len(db.child("training").get().val())
if(on_off=="ON"):
print("current status: ",status)
city,state = get_local()
features,target = get_data(total_training_points,weather_float)
reg_model = learn(features,target)
temp,wind,weather = predict(reg_model,city,state,weather_string,\
weather_float,features)
db.child("current_conditions").update({"temp":str(temp),"wind": str(wind),\
"weather": weather,"status":"not updated"})
db.update({"info/led_state":"limbo"})
db.child("current_conditions").update({"temp":str(temp),"wind": str(wind),\
"weather": weather,"status":"updated"})
print("done learning")
#Keep track of current status
if(on_off=="limbo"):
time.sleep(10)
total+=10
if total>60:
db.update({"info/led_state":"ON"})
total = 0
if(status=="location update"):
print("current status: ",status)
db.update({"current_conditions/learn":"Add Color"})
total_training_points=0
db.update({"info/count":str(total_training_points)})
city,state = get_local()
temp,wind,weather = current_conditions(city, state, weather_string)
db.child("current_conditions").update({"temp":str(temp),"wind": str(wind),\
"weather": weather,"status":"not updated"})
db.update({"info/pi_command":"off"})
db.update({"training":""})
db.child("current_conditions").update({"temp":str(temp),"wind": str(wind),\
"weather": weather,"status":"updated"})
print("done updating location")
'''
if(status=="off"):
print("current status: ",status)
'''
if(status=="training point"):
print("current status: ",status)
temp = int(db.child("current_conditions/temp").get().val())
wind = float(db.child("current_conditions/wind").get().val())
weather = db.child("current_conditions/weather").get().val()
r = int(db.child("color/red").get().val())
g = int(db.child("color/green").get().val())
b = int(db.child("color/blue").get().val())
add_training_point(temp,wind,weather,r,g,b,total_training_points)
if total_training_points >= 5:
temp,wind,weather = current_conditions(city,state,weather_string)
else:
temp,wind,weather = update_conditions(city,state,total_training_points,\
weather_string)
if total_training_points >= 5:
db.update({"info/led_state":"ON"}) #retrain
db.child("current_conditions").update({"temp":str(temp),"wind": str(wind),\
"weather": weather,"status":"not updated"})
db.update({"info/pi_command":"off"})
total_training_points+=1
if total_training_points == 5:
db.update({"current_conditions/learn":"Ready to Train"})
db.update({"info/count":str(total_training_points)})
db.child("current_conditions").update({"temp":str(temp),"wind": str(wind),\
"weather": weather,"status":"updated"})
print("done updating training point")
if(on_off=="OFF" and status=="done"):
print("current status: ",status)
break
pi.stop()
#GPIO.cleanup()
|
Swift
|
UTF-8
| 2,296 | 2.84375 | 3 |
[] |
no_license
|
//
// AppTheme.swift
// SNY
//
// Created by Thanh-Tam Le on 13/04/2019.
// Copyright © 2019 Thanh-Tam Le. All rights reserved.
//
import UIKit
class AppTheme {
class var statusBarStyle: UIStatusBarStyle {
return .lightContent
}
class var primaryColor: UIColor {
return #colorLiteral(red: 0.2431372549, green: 0.4862745098, blue: 0.9529411765, alpha: 1)
}
class var accentColor: UIColor {
return .white
}
class var font: Font {
return Font.roboto
}
}
// MARK: - View
extension AppTheme {
class var viewPrimaryBackgroundColor: UIColor {
return AppTheme.primaryColor
}
class var viewSecondaryBackgroundColor: UIColor {
return .white
}
class var viewShadowColor: UIColor {
return UIColor.black.withAlphaComponent(0.2)
}
class var lineColor: UIColor {
return #colorLiteral(red: 0.8784313725, green: 0.8784313725, blue: 0.8784313725, alpha: 1)
}
}
// MARK: - Label
extension AppTheme {
class var labelPrimaryColor: UIColor {
return #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
}
class var labelSecondaryColor: UIColor {
return #colorLiteral(red: 0.6039215686, green: 0.631372549, blue: 0.7058823529, alpha: 1)
}
class var labelNeutralColor: UIColor {
return #colorLiteral(red: 0.5176470588, green: 0.5333333333, blue: 0.5725490196, alpha: 1)
}
class var labelNegativeColor: UIColor {
return #colorLiteral(red: 1, green: 0, blue: 0.3921568627, alpha: 1)
}
}
// MARK: - Button
extension AppTheme {
class var buttonMainColor: UIColor {
return #colorLiteral(red: 0.2431372549, green: 0.4862745098, blue: 0.9529411765, alpha: 1)
}
class var imageButtonActive: UIColor {
return #colorLiteral(red: 1, green: 0, blue: 0.3921568627, alpha: 1)
}
class var imageButtonInactive: UIColor {
return #colorLiteral(red: 0.5176470588, green: 0.5333333333, blue: 0.5725490196, alpha: 1)
}
}
// MARK: - Tabbar
extension AppTheme {
class var tabBarBackgroundColor: UIColor {
return #colorLiteral(red: 0.09411764706, green: 0.09411764706, blue: 0.1529411765, alpha: 1)
}
}
|
Java
|
UTF-8
| 5,944 | 1.875 | 2 |
[] |
no_license
|
/************************************************************************************
* @File name : GroupServiceImpl.java
*
* @Author : XuYanbo
*
* @Date : 2014年11月4日
*
* @Copyright Notice:
* Copyright (c) 2014 Hunantv.com. All Rights Reserved.
* This software is published under the terms of the HunanTV Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
*
* ----------------------------------------------------------------------------------
* Who Version Comments Date
* XuYanbo 1.0 Initial Version 2014年11月12日 上午11:17:21
************************************************************************************/
package com.xuyanbo.wx.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.xuyanbo.wx.commons.BmcConstants;
import com.xuyanbo.wx.commons.BmcException;
import com.xuyanbo.wx.commons.MbpLog;
import com.xuyanbo.wx.commons.ModuleConstants;
import com.xuyanbo.wx.commons.PageInfo;
import com.xuyanbo.wx.dao.admin.GroupMapper;
import com.xuyanbo.wx.dao.admin.SystemModuleDao;
import com.xuyanbo.wx.entity.admin.Group;
import com.xuyanbo.wx.entity.admin.GroupData;
import com.xuyanbo.wx.service.GroupService;
@Service
public class GroupServiceImpl implements GroupService{
@Resource
private GroupMapper groupMapper;
@Resource
private SystemModuleDao systemModuleDao;
@Override
public Group get(int id) {
return groupMapper.selectById(id);
}
@Override
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
@MbpLog(module=ModuleConstants.SYSTEM_GROUP, type=BmcConstants.LOG_TYPE_UPDATE, desc="创建数据角色")
public void insert(Group Group) {
groupMapper.insert(Group);
}
@Override
@MbpLog(module=ModuleConstants.SYSTEM_GROUP, type=BmcConstants.LOG_TYPE_DELETE, desc="删除数据角色")
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public void delete(int id) {
groupMapper.deleteById(id);
}
@Override
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
@MbpLog(module=ModuleConstants.SYSTEM_GROUP, type=BmcConstants.LOG_TYPE_UPDATE, desc="更新数据角色")
public void update(Group group) {
groupMapper.updateById(group);
}
/**
* 分页查询数据角色列表
* @Author:XuYanbo
* @Date:2014年12月7日
* @param group
* @param page
* @return
* @throws BmcException
*/
@Override
public PageInfo<Group> searchGroups(Group group, PageInfo<Group> page) throws BmcException {
return systemModuleDao.searchGroups(group, page);
}
/**
* 重新设置数据角色-功能关联
* @Author:XuYanbo
* @Date:2014年12月17日
* @param groupId
* @param pids
* @param cids
* @param dids
*/
@Override
@MbpLog(module=ModuleConstants.SYSTEM_GROUP, type=BmcConstants.LOG_TYPE_UPDATE, desc="设置数据角色功能")
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public void saveGroupDatas(Integer groupId, String pids, String cids, String dids) {
groupMapper.deleteGroupDatas(groupId);
List<GroupData> datas = new ArrayList<GroupData>();
if(StringUtils.isNotBlank(pids)){
String[] pidArr = pids.split(BmcConstants.COMMA);
for(String pid:pidArr){
datas.add(new GroupData(BmcConstants.SYSTEM_DATA_TYPE_PLATFORM, pid));
}
}
if(StringUtils.isNotBlank(cids)){
String[] cidArr = cids.split(BmcConstants.COMMA);
for(String cid:cidArr){
datas.add(new GroupData(BmcConstants.SYSTEM_DATA_TYPE_CHANNEL, cid));
}
}
if(StringUtils.isNotBlank(dids)){
String[] didArr = dids.split(BmcConstants.COMMA);
for(String did:didArr){
datas.add(new GroupData(BmcConstants.SYSTEM_DATA_TYPE_DEPARTMENT, did));
}
}
systemModuleDao.insertGroupData(groupId, datas);
}
/**
* 根据用户获取数据角色列表
* @Author:XuYanbo
* @Date:2014年11月7日
* @param userId
* @return
*/
@Override
public List<Group> getUserGroups(Integer userId) {
return groupMapper.getUserGroups(userId);
}
/**
* 根据IDs删除数据角色
* @Author:XuYanbo
* @Date:2014年11月10日
* @param ids
*/
@Override
@MbpLog(module=ModuleConstants.SYSTEM_GROUP, type=BmcConstants.LOG_TYPE_DELETE, desc="删除数据角色")
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public void deleteGroupsByIDs(String ids) {
String[] sids = ids.split(",");
groupMapper.deleteByIds(Arrays.asList(sids));
}
/**
* 获取指定数据角色的功能集合
* @Author:XuYanbo
* @Date:2014年11月7日
* @param groupId
* @return
*/
@Override
public List<GroupData> getGroupDatas(Integer groupId) {
return groupMapper.selectAllGroupDatas(groupId);
}
/**
* 获取数据角色部门信息
* @Author:XuYanbo
* @Date:2014年12月20日
* @param id
*/
@Override
public List<GroupData> getDepartmentGroupDatas(Integer id) {
return groupMapper.getDepartmentGroupDatas(id);
}
/**
* 根据用户获取可视数据
* @Author:XuYanbo
* @Date:2014年12月23日
* @param userId
* @return
*/
@Override
public Map<String, String> getUserGroupDatas(Integer userId, String isAdmin) {
Map<String, String> dataMap = new HashMap<String, String>();
List<GroupData> datas = null;
if(BmcConstants.YES.equals(isAdmin)){
datas = groupMapper.getAllGroupDatas();
} else {
datas = groupMapper.getUserGroupDatas(userId);
}
datas.forEach(d->{ dataMap.put(d.getDataType(), d.getDataId()); });
return dataMap;
}
}
|
Swift
|
UTF-8
| 8,188 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
//
// UIImage+JLExtension.swift
// JLKit_Swift
//
// Created by Jangsy on 2018. 4. 11..
// Copyright © 2018년 Dalkomm. All rights reserved.
//
#if canImport(UIKit)
import UIKit
/*
참고 : https://github.com/melvitax/ImageHelper
*/
extension UIImage {
public enum UIImageResizeMode {
case aspectFit
case aspectFill
func aspectRatio(between size: CGSize, and otherSize: CGSize) -> CGFloat {
let aspectWidth = size.width/otherSize.width
let aspectHeight = size.height/otherSize.height
switch self {
case .aspectFill:
return max(aspectWidth, aspectHeight)
case .aspectFit:
return min(aspectWidth, aspectHeight)
}
}
}
// MARK:
public func withInsets(_ insets: UIEdgeInsets) -> UIImage? {
let size = CGSize(width: self.size.width + insets.left + insets.right, height: self.size.height + insets.top + insets.bottom)
UIGraphicsBeginImageContextWithOptions(size, false, self.scale)
UIGraphicsGetCurrentContext()
draw(at: CGPoint(x: insets.left, y: insets.top))
let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithInsets
}
public func withTint(_ color: UIColor) -> UIImage? {
if #available(iOS 13.0, watchOS 6.0, *) {
return withTintColor(color, renderingMode: .alwaysOriginal)
}else {
/*
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
color.set()
UIRectFill(rect)
draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
*/
defer { UIGraphicsEndImageContext() }
UIGraphicsBeginImageContextWithOptions(size, false, scale)
color.set()
self.withRenderingMode(.alwaysTemplate).draw(in: CGRect(origin: .zero, size: size))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
public func withOrientation(_ orientation: UIImage.Orientation) -> UIImage? {
guard let cgImage = self.cgImage else { return nil }
return UIImage(cgImage: cgImage, scale: scale, orientation: orientation).withRenderingMode(renderingMode)
}
// MARK:
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
var image: UIImage?
#if os(iOS)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
#else
UIGraphicsBeginImageContextWithOptions(size, false, 1)
#endif
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
image = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else {return nil}
self.init(cgImage: cgImage)
}
// MARK: Crop
public func crop(bounds: CGRect) -> UIImage? {
return UIImage(cgImage: (self.cgImage?.cropping(to: bounds)!)!,
scale: 0.0, orientation: self.imageOrientation)
}
public func cropToSquare() -> UIImage? {
let shortest = ceil(min(size.width, size.height))
return resize(rect: CGRect(x: 0, y: 0, width: shortest, height: shortest))
}
// MARK: Resize
public func resize(toMaxPixel pixel: CGFloat) -> UIImage? {
let horizontalRatio = pixel / size.width
let verticalRatio = pixel / size.height
let ratio = min(horizontalRatio, verticalRatio)
return resize(rect: CGRect(x: 0, y: 0, width: ceil(size.width * ratio), height: ceil(size.height * ratio)))
}
public func resize(toMinPixel pixel: CGFloat) -> UIImage? {
let horizontalRatio = pixel / size.width
let verticalRatio = pixel / size.height
let ratio = max(horizontalRatio, verticalRatio)
return resize(rect: CGRect(x: 0, y: 0, width: ceil(size.width * ratio), height: ceil(size.height * ratio)))
}
public func resize(toSize: CGSize, resizeMode: UIImageResizeMode = .aspectFill) -> UIImage? {
let ratio = resizeMode.aspectRatio(between: toSize, and: size)
let rect = CGRect(x: 0, y: 0, width: ceil(size.width * ratio), height: ceil(size.height * ratio))
return resize(rect: rect)
}
public func resize(rect: CGRect) -> UIImage? {
var resultImage = self
UIGraphicsBeginImageContextWithOptions(rect.size, false, 1.0)
self.draw(in: rect)
guard let resizedImage = UIGraphicsGetImageFromCurrentImageContext() else { return resultImage }
resultImage = resizedImage
UIGraphicsEndImageContext()
return resultImage
}
}
public extension UIImage {
var bytesSize: Int {
return jpegData(compressionQuality: 1)?.count ?? 0
}
var kilobytesSize: Int {
return (jpegData(compressionQuality: 1)?.count ?? 0) / 1024
}
enum ImageFormat {
case JPEG(compressionQuality: CGFloat)
case PNG
}
func data(_ format: ImageFormat) -> Data? {
return autoreleasepool { () -> Data? in
let data: Data?
switch format {
case .PNG: data = pngData()
case .JPEG(let compressionQuality): data = jpegData(compressionQuality: compressionQuality)
}
return data
}
}
}
public extension UIImage {
var original: UIImage {
return withRenderingMode(.alwaysOriginal)
}
var template: UIImage {
return withRenderingMode(.alwaysTemplate)
}
#if canImport(CoreImage)
func averageColor() -> UIColor? {
guard let ciImage = ciImage ?? CIImage(image: self) else { return nil }
let parameters = [kCIInputImageKey: ciImage, kCIInputExtentKey: CIVector(cgRect: ciImage.extent)]
guard let outputImage = CIFilter(name: "CIAreaAverage", parameters: parameters)?.outputImage else {
return nil
}
var bitmap = [UInt8](repeating: 0, count: 4)
let workingColorSpace: Any = cgImage?.colorSpace ?? NSNull()
let context = CIContext(options: [.workingColorSpace: workingColorSpace])
context.render(outputImage,
toBitmap: &bitmap,
rowBytes: 4,
bounds: CGRect(x: 0, y: 0, width: 1, height: 1),
format: .RGBA8,
colorSpace: nil)
// Convert pixel data to UIColor
return UIColor(red: CGFloat(bitmap[0]) / 255.0,
green: CGFloat(bitmap[1]) / 255.0,
blue: CGFloat(bitmap[2]) / 255.0,
alpha: CGFloat(bitmap[3]) / 255.0)
}
#endif
}
public extension UIImage {
#if os(iOS)
static func dynamicImage(withLight light: @autoclosure () -> UIImage?,
dark: @autoclosure () -> UIImage?) -> UIImage? {
if #available(iOS 13.0, *) {
let lightTC = UITraitCollection(traitsFrom: [.current, .init(userInterfaceStyle: .light)])
let darkTC = UITraitCollection(traitsFrom: [.current, .init(userInterfaceStyle: .dark)])
var lightImage:UIImage?
var darkImage:UIImage?
lightTC.performAsCurrent {
lightImage = light()
}
darkTC.performAsCurrent {
darkImage = dark()
}
if let darkImage {
lightImage?.imageAsset?.register(darkImage, with: UITraitCollection(userInterfaceStyle: .dark))
}
return lightImage
} else {
return light()
}
}
#endif
}
#endif
|
Markdown
|
UTF-8
| 2,300 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Dinivas
[](https://travis-ci.org/dinivas/dinivas)
AWS, GCP alternative on premise. Dinivas manage your private Cloud (OpenStack) infrastructure by providing many features base on popular Open Source projects [https://dinivas.github.io/dinivas](https://dinivas.github.io/dinivas)
## Why Dinivas?
Many company moved or have planned to move in the public Cloud, Major cloud provier (AWS, GCP, Azure) provide many robust services and could be a very good choice. Nevertheless the downside with major public cloud provider is your are lock in their own solution (RDS, Cloud PubSub...)
Dinivas firts interest is to give the choice to company that wants to keep their stack independent of the public cloud custom solutions. We are talking here about **Cloud native** vs **Cloud Agnostic**.
Some companies also can't just go to public Cloud due to data governance and many other reasons. They usually have their own private Cloud (Openstack). **Dinivas** could provide them the *AWS like* solution on premise (Self service, managed database, managed mesaging solutions...).
**Dinivas** is the on premise solution to get quickly a full managed services (PAAS) based on most popular Opensouce solution, Therefore you will not be *locked* to the Cloud provider.
## Status
Dinivas is still under developement and therefore not ready at all for use. You may watch the repo to keep touched about the evolution.
## Quick Start & Documentation
Technical documentation can be found [here](https://dinivas.github.io/dinivas)
## Quick start (Docker compose)
### Start Api server and console using Docker-compose
```
docker-compose up -d
```
### Keycloak admin
- Connect to Keycloak Admin console [http://localhost:8085](http://localhost:8085)
- Got to `Clients` > `dinivas-api` > `Credentials` and ensure the Secret is well generated and equals to the secret in the configuration
## Quick start without Docker
### Start Keycloak & Databases
docker-compose -p dinivas up -d
### Start Server API
ng serve api
### Start Ansible Galaxy Server
From project Ansible-Galaxy, use Vscode debug launcher
### Start Dinivas console
ng serve
###
## Contributing
See the [contribution guide](./CONTRIBUTING.md).
|
Java
|
UTF-8
| 34,437 | 2.546875 | 3 |
[] |
no_license
|
/**
* For each node, make a list of Nearest Neighbors and then compare with
* other nodes to find those with common NNs.
* Output is a #nodes x #nodes table showing the number of common NN's for
* every pair of nodes in the network, and a text output of node pairs with
* both a high number of nearest neighbors in common, both as a percentage of
* their total NNs and the total number of nodes in the network. These
* nodes are also selected.
*
* @author Greg Carter
* @author Iliana Avila (refactored)
* @version 2.0
*/
package phenotypeGenetics;
import phenotypeGenetics.ui.*;
import phenotypeGenetics.action.*;
import java.util.*;
import java.util.List;
import cytoscape.*;
import cytoscape.view.*;
import java.lang.Math;
import cytoscape.data.*;
import phenotypeGenetics.Utilities;
public class MutualInfoCalculator{
protected static final String divider = "~";
protected static final double DEFAULT_MINSCORE = 3.0;
protected static final int DEFAULT_NUMRANDOMREPS = 100;
protected static final int MIN_OVERLAP = 5;
/**
* The minimum score for signficance
*/
protected static double minScore = DEFAULT_MINSCORE;
/**
* The number of randomizations for calculation of p-value
*/
protected static int numRandomReps = DEFAULT_NUMRANDOMREPS;
/**
* The background probabilities for allele pair types
*/
protected static HashMap bkg;
/**
* Sole constructor
*/
public MutualInfoCalculator (){}//MutualInfoCalculator
/**
* @param cy_net the CyNetwork on which to generate mutual information
* @param task_progress the TaskProgress that this method uses to keep
* track of the progress of this algorithm
* @see cytoscape.utils.CytoscapeProgressMonitor
*/
public static MutualInfo[] findMutualInformation (CyNetwork cy_net,
TaskProgress task_progress) {
// get the edges
Iterator edgesIt = cy_net.edgesIterator();
ArrayList edgeList = new ArrayList();
while(edgesIt.hasNext()){
edgeList.add(edgesIt.next());
}
CyEdge [] edges = (CyEdge[])edgeList.toArray(new CyEdge[edgeList.size()]);
// get the nodes
Iterator nodesIt = cy_net.nodesIterator();
ArrayList nodeList = new ArrayList();
while(nodesIt.hasNext()){
nodeList.add(nodesIt.next());
}
CyNode[] nodes = (CyNode[])nodeList.toArray(new CyNode[nodeList.size()]);
// we're going to select some nodes, so deselect currently selected ones
CyNetworkView netView = Cytoscape.getNetworkView(cy_net.getIdentifier());
if(netView != null){
List selectedNodeViews = netView.getSelectedNodes();
if(selectedNodeViews != null){
for(Iterator it = selectedNodeViews.iterator(); it.hasNext();){
CyNodeView nodeView = (CyNodeView)it.next();
nodeView.setSelected(false);
}
}
}
// Set up the command line output
System.out.print( "Minimum score = " + MutualInfoCalculator.minScore +
". Calculating." );
// Put selected node pairs in a MutualInfo
MutualInfo[] pairs = getPairs( cy_net, nodes, edges,
MutualInfoCalculator.minScore,
false, task_progress );
return (MutualInfo[]) pairs;
}//findMutualInformation
/**
* For each pair of <code>Node</code>s in array nodes, work with given
* <code>Edge</code>s to generate an array of <code>MutualInfo[]</code> of
* mutual information
*/
public static MutualInfo[] getPairs(CyNetwork cy_net,
CyNode[] nodes,
CyEdge[] edges,
double minScore,
boolean quiet,
TaskProgress task_progress){
task_progress.message = "Initializing...";
task_progress.taskName = "Mutual Information Calculation";
int numEdgeTypes = 0;
if (!quiet) { System.out.println(); System.out.print( "Finding alleles..." ); }
if(MutualInfoCalculator.bkg == null){
MutualInfoCalculator.bkg = buildBkg(cy_net);
}
// build an array of alleles which will be cycled over later
Allele[] alleles = getAlleles( nodes, edges);
if (!quiet) { System.out.print( alleles.length + " alleles found."); }
//Get interaction class distributions
HashMap nodeDist = NodalDistributionAnalyzer.calculateNodeDistribution(cy_net,false);
TableDialog td = new TableDialog(nodeDist);
TableDialog.TableDialogModel tdm = td.makeTableDialogModel(nodeDist);
// Turn them into probabilities
HashMap probDist = buildProbDist( tdm );
// Get the list of edge types
numEdgeTypes = tdm.getColumnCount() - 2;
ArrayList edgeTypes = new ArrayList();
for (int iE = 1; iE < tdm.getColumnCount()-1; iE++ ){
edgeTypes.add( tdm.getColumnNameNoTotal( iE ) );
}//iE
// A place to put important MutualInfos when we find them
ArrayList miList = new ArrayList();
// A hashmap keyed on alleles, pointing to an ArrayList of neighbor alleles
HashMap alleleHash = new HashMap();
// A hashmap keyed on alleles, pointing to an ArrayList of interaction types
// for the edge which connects to the corresponding neighbor allele in alleleHash.
HashMap edgeTypeHash = new HashMap();
// A hashmap keyed on alleles, pointing to an ArrayList of flags identifying
// the allele as a source ("s") or target ("t")
// This is only here to keep track for the background randomizations.
HashMap edgeFlagHash = new HashMap();
// A hashmap keyed on alleles, pointing to an ArrayList of relations identifying
// the allele as having a single-mutant phenotype >, <, or = to WT
HashMap edgeRelationHash = new HashMap();
// Cycle over all edges, find connecting nodes A and B with alleleForms
// alleleformA and alleleformB, then put results into HashMaps
if(task_progress.taskLength == 0){
task_progress.taskLength = getLengthOfTask(cy_net);
}
task_progress.currentProgress = 0;
CyAttributes edgeAtts = Cytoscape.getEdgeAttributes();
for (int i=0; i<edges.length; i++) {
CyEdge theEdge = edges[i];
String edgeType = edgeAtts.getStringAttribute(theEdge.getIdentifier(), GeneticInteraction.ATTRIBUTE_GENETIC_CLASS);
// (String)Cytoscape.getEdgeAttributeValue(theEdge,
// GeneticInteraction.ATTRIBUTE_GENETIC_CLASS);
// Build the strings for keying
String aKeyA = edgeAtts.getStringAttribute(theEdge.getIdentifier(), GeneticInteraction.ATTRIBUTE_ALLELE_FORM_A)
// (String)Cytoscape.getEdgeAttributeValue(theEdge,
// GeneticInteraction.ATTRIBUTE_ALLELE_FORM_A)
+ divider +
edgeAtts.getStringAttribute(theEdge.getIdentifier(), GeneticInteraction.ATTRIBUTE_MUTANT_A);
//(String)Cytoscape.getEdgeAttributeValue(theEdge,
// GeneticInteraction.ATTRIBUTE_MUTANT_A);
String aKeyB =
edgeAtts.getStringAttribute(theEdge.getIdentifier(),GeneticInteraction.ATTRIBUTE_ALLELE_FORM_B)
// (String)Cytoscape.getEdgeAttributeValue(theEdge,
// GeneticInteraction.ATTRIBUTE_ALLELE_FORM_B)
+ divider +
edgeAtts.getStringAttribute(theEdge.getIdentifier(),GeneticInteraction.ATTRIBUTE_MUTANT_B);
//(String)Cytoscape.getEdgeAttributeValue(theEdge,
// GeneticInteraction.ATTRIBUTE_MUTANT_B);
// If necessary, find out which is the source and which is the target
Mode mode = (Mode)Mode.modeNameToMode.get(edgeType);
if(mode == null){
throw new IllegalStateException("edgeType " + edgeType + " had no Mode!");
}
String edgeTypeA = edgeType;
String edgeTypeB = edgeType;
String flagA = new String();
String flagB = new String();
if(mode.isDirectional()){
String nodeA_id = edgeAtts.getStringAttribute(theEdge.getIdentifier(), GeneticInteraction.ATTRIBUTE_MUTANT_A);
//(String)Cytoscape.getEdgeAttributeValue(theEdge,
// GeneticInteraction.ATTRIBUTE_MUTANT_A);
// the 2nd argument tells it to not create the node if it is not there
// note that the returned node may belongs to the RootGraph, but not necessarily
// to this CyNetwork
CyNode nodeA = Cytoscape.getCyNode(nodeA_id, false);
if(nodeA == null){
// Figure out what to do here, for now just throw exception
throw new IllegalStateException("Node with identifier " +
nodeA_id + " does not exist in RootGraph!");
}
// we know that it is in RootGraph, now lets make sure that it is in this CyNetwork
if(!cy_net.containsNode(nodeA)){
//Figure out what to do here, for now just throw exception
throw new IllegalStateException("Node with identifier " +
nodeA_id + " does not exist in CyNetwork!");
}
// if ( nodeA == theEdge.getSourceNode() ) {
if(nodeA == theEdge.getSource()){
edgeTypeA = edgeType + "+";
edgeTypeB = edgeType + "-";
flagA = "s";
flagB = "t";
} else {
edgeTypeA = edgeType + "-";
edgeTypeB = edgeType + "+";
flagA = "t";
flagB = "s";
}
}//isDirectional
// Get the single-mutants relative to wild type
GeneticInteraction gi = (GeneticInteraction)GeneticInteraction.EDGE_NAME_GENETIC_INTERACTION_MAP.get(theEdge.getIdentifier());
// (GeneticInteraction)Cytoscape.getEdgeAttributeValue(theEdge,
// GeneticInteraction.ATTRIBUTE_SELF);
DiscretePhenoValueInequality d = gi.getDiscretePhenoValueInequality();
int pA = d.getA();
int pB = d.getB();
int pWT = d.getWT();
String opA = getSingleMutantRelation(pA, pWT);
String opB = getSingleMutantRelation(pB, pWT);
String relations = opA + opB;
if ( !MutualInfoCalculator.bkg.containsKey( relations ) ) {
relations = opB + opA;
}
if ( !MutualInfoCalculator.bkg.containsKey( relations ) ) {
System.out.println("No instances of "+relations+" in background.");
}
// put B in A's list of fellow alleles
alleleHash = updateList( aKeyA, aKeyB, alleleHash );
// put A in B's list of fellow alleles
alleleHash = updateList( aKeyB, aKeyA, alleleHash );
// Put the edgeType in lists for A and B
edgeTypeHash = updateList( aKeyA, edgeTypeA, edgeTypeHash );
edgeTypeHash = updateList( aKeyB, edgeTypeB, edgeTypeHash );
// Put the flags in lists for A and B
edgeFlagHash = updateList( aKeyA, flagA, edgeFlagHash );
edgeFlagHash = updateList( aKeyB, flagB, edgeFlagHash );
// Put the relations in lists for A and B
edgeRelationHash = updateList( aKeyA, relations, edgeRelationHash );
edgeRelationHash = updateList( aKeyB, relations, edgeRelationHash );
if( (edges.length % 100) == 0){
task_progress.currentProgress++;
int percent = (int)((task_progress.currentProgress*100)/task_progress.taskLength);
task_progress.message = "<html>Mutual Information:<br>Completed "
+ Integer.toString(percent) + "%</html>";
}
}// i, the edge at hand
if (!quiet) {System.out.println( "Done. ");}
// Now cycle over all alleles and, drawing from the HashMaps we have just made,
// make a list of nearest-neighbor alleles for each allele.
for (int i = 0; i < alleles.length; i++) {
System.out.print("."); // Let the user know something's going on
Allele allele1 = alleles[i];
// Find the allele's info to make a key
String aKey1 = allele1.getAlleleForm() + divider + allele1.getNode().getIdentifier();
//Cytoscape.getNodeAttributeValue(allele1.getNode(),Semantics.CANONICAL_NAME);
// For this allele, get the list of alleles and interactions to those
// alleles
ArrayList list1 = (ArrayList)alleleHash.get( aKey1 );
ArrayList typeList1 = (ArrayList)edgeTypeHash.get( aKey1 );
ArrayList flagList1 = (ArrayList)edgeFlagHash.get( aKey1 );
ArrayList relationList1 = (ArrayList)edgeRelationHash.get( aKey1 );
// Now cycle over all possible neighbors
for (int j = i+1; j < alleles.length; j++) {
Allele allele2 = alleles[j];
// Find the allele's info to make a key
String aKey2 = allele2.getAlleleForm() + divider + allele2.getNode().getIdentifier();
//Cytoscape.getNodeAttributeValue(allele2.getNode(), Semantics.CANONICAL_NAME);
// For this allele, get the list of alleles and interactions to those
// alleles
ArrayList list2 = (ArrayList)alleleHash.get( aKey2 );
ArrayList typeList2 = (ArrayList)edgeTypeHash.get( aKey2 );
ArrayList flagList2 = (ArrayList)edgeFlagHash.get( aKey2 );
ArrayList relationList2 = (ArrayList)edgeRelationHash.get( aKey2 );
if ( list1==null | list2==null ) {continue;}
// The intersection of these lists gives a set of third-party alleles which
// have been tested with alleles 1 and 2
ArrayList list12 = Utilities.intersection( list1, list2 );
int commonTests = list12.size();
// Make a sublist of neighbor alleles for allele1, which:
// 1) are tested with both 1 and 2
// 2) interact with allele 1
ArrayList interacting1 = new ArrayList();
HashMap typeHash1 = new HashMap();
HashMap flagHash1 = new HashMap();
HashMap relationHash1 = new HashMap();
for ( int k=0; k<list1.size(); k++) {
String allele = (String)list1.get(k);
if ( list12.contains( allele ) && (!interacting1.contains( allele )) ) {
interacting1.add( allele );
typeHash1.put( allele, (String)typeList1.get(k) );
flagHash1.put( allele, (String)flagList1.get(k) );
relationHash1.put( allele, (String)relationList1.get(k) );
}
}
// This is the subgroup of alleles which 1 interacts with and has been tested
// for both 1 and 2
int num1 = interacting1.size();
// Make a sublist of neighbor alleles for allele2, which:
// 1) are tested with both 1 and 2
// 2) interact with allele 2
ArrayList interacting2 = new ArrayList();
HashMap typeHash2 = new HashMap();
HashMap flagHash2 = new HashMap();
HashMap relationHash2 = new HashMap();
for ( int k=0; k<list2.size(); k++) {
String allele = (String)list2.get(k);
if ( list12.contains( allele ) && (!interacting2.contains( allele )) ) {
interacting2.add( allele );
typeHash2.put( allele, (String)typeList2.get(k) );
flagHash2.put( allele, (String)flagList2.get(k) );
relationHash2.put( allele, (String)relationList2.get(k) );
}
}
// This is the subgroup of alleles which 2 interacts with and has been tested
// for both 1 and 2
int num2 = interacting2.size();
if ( num1 == 0 | num2 == 0 | commonTests==0 ) {continue;}
// Find the list of third-party alleles which interact with
// both 1 and 2:
ArrayList interacting12 = Utilities.intersection( interacting1, interacting2 );
int overlap = interacting12.size();
if ( overlap >= MIN_OVERLAP ) {
double score = calculateScore( interacting12, typeHash1, flagHash1,
typeHash2, flagHash2, edgeTypes );
double[] rScores = new double[numRandomReps];
for(int rep=0;rep<numRandomReps;rep++) {
// Score a random configuration
HashMap randomTypeHash1 = getRandomTypes( interacting12,
relationHash1,
flagHash1 );
HashMap randomTypeHash2 = getRandomTypes( interacting12,
relationHash2,
flagHash2 );
double randomScore = calculateScore( interacting12, randomTypeHash1, flagHash1,
randomTypeHash2, flagHash2, edgeTypes );
rScores[rep] = randomScore;
}
double meanRS = Utilities.mean( rScores );
double sdRS = Utilities.standardDeviation( rScores );
double pValue = calculatePValue( score, meanRS, sdRS );
if ( ( pValue >= minScore ) ) {
String nodeName1 = allele1.getNode().getIdentifier();
//(String)Cytoscape.getNodeAttributeValue(allele1.getNode(),
// Semantics.CANONICAL_NAME);
String nodeName2 = allele2.getNode().getIdentifier();
//(String)Cytoscape.getNodeAttributeValue(allele2.getNode(),
// Semantics.CANONICAL_NAME);
// Identify the allele forms
String alleleForm1 = allele1.getAlleleForm();
String alleleForm2 = allele2.getAlleleForm();
// Make a list of the nearest neighbors to send to MutualInfo
ArrayList pairList = new ArrayList();
// Parse the keyNames down to a Node name by pulling alleleForm off
for (int l=0; l<interacting12.size(); l++) {
String allele = (String)interacting12.get(l);
String name = allele.substring( allele.indexOf(divider)+1 );
pairList.add( name );
}
MutualInfo mi = new MutualInfo(
nodeName1, alleleForm1,
nodeName2, alleleForm2,
pairList,
commonTests,
score, pValue, meanRS, sdRS );
//System.out.println( nodeName1+" "+nodeName2+" "+score+" "+pValue );
miList.add( mi );
}// if big p-value
}// overlap>3
}// j allele 2
task_progress.currentProgress++;
int percent = (int)((task_progress.currentProgress * 100)/task_progress.taskLength);
task_progress.message = "<html>Mutual Information:<br>Completed "
+ Integer.toString(percent) + "%</html>";
//System.out.println(task_progress.message);
}// i allele 1
MutualInfo[] pairs = (MutualInfo[])miList.toArray( new MutualInfo[ miList.size() ] );
if ( (pairs.length == 0) && !quiet ) {
System.out.println("No high-scoring pairs present.");
}
System.out.println();
task_progress.done = true;
return pairs;
}//getPairs
/**
* Get a random interaction type hashmap
*/
protected static HashMap getRandomTypes( ArrayList interactingSet,
HashMap relationHash,
HashMap flagHash ){
HashMap randomTypeHash = new HashMap();
for ( int iS=0; iS < interactingSet.size(); iS++ ) {
String alleleString = (String)interactingSet.get(iS);
String key = (String)relationHash.get( alleleString );
HashMap bkgProb = (HashMap)MutualInfoCalculator.bkg.get( key );
Iterator iP = bkgProb.keySet().iterator();
double randomNum = Math.random();
double prevProb = 0.0;
while (iP.hasNext() ) {
String eType = (String)iP.next();
Mode mode = (Mode)Mode.modeNameToMode.get(eType);
double prob = ((Double)bkgProb.get( eType )).doubleValue();
if ( mode.isDirectional() ) {
String flag = (String)flagHash.get( alleleString );
if ( flag.compareTo("s") == 0 ) {
eType += "+";
} else {
eType += "-";
}
}
if ( (randomNum >= prevProb) && (randomNum < (prevProb+prob)) ) {
randomTypeHash.put( alleleString, eType );
}
prevProb += prob;
}
}
return randomTypeHash;
}//getRandomTypes
/**
* Get the single-mutant value for an allele1 in its experiment with allele2
*/
protected static String getSingleMutantRelation (int pA, int pWT){
String opA = new String();
if(pA > pWT){
opA = ">";
}else if(pA == pWT){
opA = "=";
}else if(pA < pWT){
opA = "<";
}
return opA;
}//getSingleMutantRelation
/**
* Get the single-mutant value for an allele1 in its experiment with allele2
*/
protected static String getSingleMutantRelation (Allele allele1, Allele allele2,
CyEdge[] edges){
boolean nodeFound = false;
int iE = -1;
String opA = new String();
CyEdge theEdge = edges[0];
while ( !nodeFound ){
iE ++;
theEdge = edges[iE];
if ( ( (theEdge.getSource() == allele1.getNode()) &&
(theEdge.getTarget() == allele2.getNode()) ) ||
( (theEdge.getSource() == allele2.getNode()) &&
(theEdge.getTarget() == allele1.getNode()) ) ) {
nodeFound = true;
}
}
// TODO: this will need to be in separate data strcuture -iliana
GeneticInteraction gi = (GeneticInteraction)GeneticInteraction.EDGE_NAME_GENETIC_INTERACTION_MAP.get(theEdge.getIdentifier());
// (GeneticInteraction)Cytoscape.getEdgeAttributeValue(theEdge,
// GeneticInteraction.ATTRIBUTE_SELF);
DiscretePhenoValueInequality d = gi.getDiscretePhenoValueInequality();
int pA = 0;
String allele1Name = allele1.getNode().getIdentifier();
//OLD:
//(String)Cytoscape.getNodeAttributeValue(allele1.getNode(),
// Semantics.CANONICAL_NAME
// );
String mutant1Name = Cytoscape.getEdgeAttributes().getStringAttribute(theEdge.getIdentifier(), GeneticInteraction.ATTRIBUTE_MUTANT_A);
//OLD:
// (String)Cytoscape.getEdgeAttributeValue(theEdge,
// GeneticInteraction.ATTRIBUTE_MUTANT_A
// );
if(allele1Name.compareTo(mutant1Name ) == 0 ){
pA = d.getA();
}else{
pA = d.getB();
}
int pWT = d.getWT();
if(pA > pWT){
opA = ">";
}else if(pA == pWT){
opA = "=";
}else if(pA < pWT){
opA = "<";
}
return opA;
}//getSingleMutantRelation
/**
* Compute Mutual Info p-value given a score and a mean and st from random scores
*
* MI Scores are normally distributed. Need to find the mean random score and
* standard deviation to get a p-value for the actual score.
* The p-value will be the 1 - the Cumulative normal distribution at score x, or
* pVal = 1-CDF[x] = 1/2 * ( 1 - Erf[ (x-m)/(Sqrt[2]*sd) ] )
* where m = mean and sd = standard deviation of the distribution.
*/
protected static double calculatePValue (double score, double m, double sd){
double pval;
// erf approximation is really only for score > mean, but it works ok for a
// sd below.
if(score < m){
// The actual values are really on [1.0, 0.5) but close enough.
pval = 1.0;
}else{
pval = 0.5 * ( 1.0 - erf( (score-m)/(Math.sqrt(2.0)*sd) ) );
}
// Take the absolute value to avoid annoying -0.0 output
return Math.abs( -Math.log( pval )/Math.log( 10 ) );
}//calculatePValue
/**
* Compute Mutual Info score
*/
protected static double calculateScore( ArrayList interacting12,
HashMap typeHash1, HashMap flagHash1,
HashMap typeHash2, HashMap flagHash2,
ArrayList edgeTypes ) {
int overlap = interacting12.size();
int numEdgeTypes = edgeTypes.size();
// Find the number of each edgeType combination and build a joint probability matrix
double[][] jointProb = new double[numEdgeTypes][numEdgeTypes];
double[] prob1 = new double[numEdgeTypes];
double[] prob2 = new double[numEdgeTypes];
// Initalize probabilities
for(int r = 0; r < jointProb.length; r++){
for(int c = 0; c < jointProb.length; c++){
jointProb[r][c] = 0.0;
}//for c
prob1[r] = 0.0;
prob2[r] = 0.0;
}//for r
for(int k = 0; k < interacting12.size(); k++){
String allele3 = (String)interacting12.get(k);
String eType1 = (String)typeHash1.get( allele3 );
String eType2 = (String)typeHash2.get( allele3 );
int n1 = edgeTypes.indexOf( eType1 );
int n2 = edgeTypes.indexOf( eType2 );
jointProb[n1][n2] += 1.0/overlap;
prob1[n1] += 1.0/overlap;
prob2[n2] += 1.0/overlap;
}
// Now compute the score
double score = 0;
double log2e = 1.442695041; // Log_2(e) to convert Ln to Log_2
for (int r=0; r < jointProb.length; r++) {
for (int c=0; c < jointProb.length; c++) {
double p12 = jointProb[r][c];
double p1 = prob1[r];
double p2 = prob2[c];
if ( p12 != 0.0 ) {
score += p12 * log2e * Math.log( p12/(p1*p2) );
}
}
}
return score;
}//calculateScore
/**
* For each node, generate a HashMap of probabilities
*/
protected static HashMap buildProbDist (TableDialog.TableDialogModel tdm){
HashMap probDist = new HashMap();
int numCols = tdm.getColumnCount();
int numRows = tdm.getRowCount();
for( int r = 0; r < numRows; r++ ) {
String alleleName = (String)tdm.getValueAt( r, 0 );
HashMap probHash = new HashMap();
double total = ((Integer)tdm.getValueAt( r, numCols-1 )).doubleValue();
for( int c = 1; c < numCols-1; c++ ) {
String intType = (String)tdm.getColumnNameNoTotal( c );
double num = ((Integer)tdm.getValueAt( r,c )).doubleValue();
Double prob = new Double( num/total );
probHash.put( intType, prob );
}//c
probDist.put( alleleName, probHash );
}//r
return probDist;
}//buildProbDist
/**
* Compute background probabilities of interction types given two single mutants.
*/
protected static HashMap buildBkg (CyNetwork cy_net){
String opA = new String();
String opB = new String();
System.out.print("Building background data...");
/*
* There are six possible combinations for any allele pair with
* respect to the wild type: ==, >=, <=, >>, <<, ><. How many
* of each is there in the data?
*/
HashMap bkg = new HashMap();
Iterator it = cy_net.edgesIterator();
CyAttributes edgeAtts = Cytoscape.getEdgeAttributes();
while(it.hasNext()) {
CyEdge theEdge = (CyEdge)it.next();
String edgeType = edgeAtts.getStringAttribute(theEdge.getIdentifier(), GeneticInteraction.ATTRIBUTE_GENETIC_CLASS);
//OLD:
// (String)Cytoscape.getEdgeAttributeValue(theEdge,
// GeneticInteraction.ATTRIBUTE_GENETIC_CLASS);
// TODO: This will need to be stored in a separate data structure -iliana
GeneticInteraction gi = (GeneticInteraction)GeneticInteraction.EDGE_NAME_GENETIC_INTERACTION_MAP.get(theEdge.getIdentifier());
//(GeneticInteraction)Cytoscape.getEdgeAttributeValue(theEdge,
// GeneticInteraction.ATTRIBUTE_SELF);
DiscretePhenoValueInequality d = gi.getDiscretePhenoValueInequality();
int pWT = d.getWT();
int pA = d.getA();
int pB = d.getB();
if ( pA > pWT ) {
opA = ">";
} else if ( pA == pWT ) {
opA = "=";
} else if ( pA < pWT ) {
opA = "<";
}
if ( pB > pWT ) {
opB = ">";
} else if ( pB == pWT ) {
opB = "=";
} else if ( pB < pWT ) {
opB = "<";
}
String key = opA + opB;
if ( key.compareTo( ">=" ) == 0 ) {
key = "=>";
}
if ( key.compareTo( "<=" ) == 0 ) {
key = "=<";
}
if ( key.compareTo( "<>" ) == 0 ) {
key = "><";
}
if ( bkg.containsKey( key ) ) {
HashMap counts = (HashMap)bkg.get( key );
if ( counts.containsKey( edgeType ) ) {
Integer theCount = (Integer)counts.get( edgeType );
counts.put( edgeType, new Integer( theCount.intValue() + 1 ) );
} else {
counts.put( edgeType, new Integer( 1 ) );
}
bkg.put( key, counts );
} else {
HashMap counts = new HashMap();
counts.put( edgeType, new Integer( 1 ) );
bkg.put( key, counts );
}
}
// Go through and make them fractional
Iterator iB = (Iterator)bkg.keySet().iterator();
while (iB.hasNext()) {
double total = 0;
String theKey = (String)iB.next();
HashMap counts = (HashMap)bkg.get( theKey );
Iterator iC = (Iterator)counts.keySet().iterator();
while (iC.hasNext()) {
String key = (String)iC.next();
int num = ((Integer)counts.get( key )).intValue();
total += num;
}
Iterator iD = (Iterator)counts.keySet().iterator();
while (iD.hasNext()) {
String key = (String)iD.next();
int num = ((Integer)counts.get( key )).intValue();
double pct = num/total;
counts.put( key, new Double( pct ) );
}
bkg.put( theKey, counts );
}
System.out.println( "done." );
return bkg;
}// buildBkg
/**
* Update the alleleHash or edgeTypeHash
*/
protected static HashMap updateList (String key, String item, HashMap theMap){
if (theMap.containsKey( key )){
ArrayList list = (ArrayList)theMap.get( key );
list.add( item );
theMap.put( key, list );
} else {
ArrayList list = new ArrayList();
list.add( item );
theMap.put( key, list );
}
return theMap;
}//updateList
/**
* Sets the minimum score for significance
*/
public static void setMinScore (double min_score){
MutualInfoCalculator.minScore = min_score;
}//setMinScore
/**
* Sets the number of random repetitions
*/
public static void setNumRandomReps (int reps){
MutualInfoCalculator.numRandomReps = reps;
}//setNumRandomReps
/**
* Gets the minimum score for significance
*/
public static double getMinScore (){
return MutualInfoCalculator.minScore;
}//getMinScore
/**
* Gets the number of random repetitions
*/
public static int getNumRandomReps (){
return MutualInfoCalculator.numRandomReps;
}//getNumRandomReps
/**
* Estimates how many units it will take to calculate mutual information
* for the given network, used for progress monitors
*
* @see cytoscape.util.CytoscapeProgressMonitor
*/
public static int getLengthOfTask (CyNetwork cy_net){
// get the edges
Iterator edgesIt = cy_net.edgesIterator();
ArrayList edgeList = new ArrayList();
while(edgesIt.hasNext()){
edgeList.add(edgesIt.next());
}
CyEdge [] edges = (CyEdge[])edgeList.toArray(new CyEdge[edgeList.size()]);
// get the nodes
Iterator nodesIt = cy_net.nodesIterator();
ArrayList nodeList = new ArrayList();
while(nodesIt.hasNext()){
nodeList.add(nodesIt.next());
}
CyNode[] nodes = (CyNode[])nodeList.toArray(new CyNode[nodeList.size()]);
Allele [] alleles = getAlleles(nodes,edges);
int l = alleles.length + edges.length/100;
return l;
}//getLengthOfTask
/**
* Gets an array of <code>Allele</code>s given an array of Nodes and a
* GraphObjAttributes.
*/
public static Allele[] getAlleles(CyNode[] nodes, CyEdge[] edges){
ArrayList alleleList = new ArrayList();
for(int i=0; i<nodes.length; i++) {
CyNode node = nodes[i];
String nodeName = node.getIdentifier();
//OLD:
// (String)Cytoscape.getNodeAttributeValue(node,Semantics.CANONICAL_NAME);
String[] alleleForm = Utilities.getAlleleForms(nodeName,edges);
for(int af = 0; af < alleleForm.length; af++ ) {
Allele newAllele = new Allele( node, alleleForm[af] );
alleleList.add( newAllele );
}
System.out.print(".");
}
return (Allele[])alleleList.toArray( new Allele[0] );
}//getAlleles
/**
* @return ???
*/
public static double erf ( double x ){
double a1 = 0.254829592;
double a2 = -0.284496736;
double a3 = 1.421413741;
double a4 = -1.453152027;
double a5 = 1.061405429;
double p = 0.3275911;
double t = 1.0/( 1.0 + p*x );
double ex = 1.0 - Math.exp(-Math.pow(x,2))*( a1*t + a2*Math.pow(t,2) +
a3*Math.pow(t,3) + a4*Math.pow(t,4) +
a5*Math.pow(t,5) );
return ex;
}//erf
// ------------------- Internal classes -----------------------//
static protected class Allele {
protected CyNode node;
protected String alleleForm;
public Allele(CyNode node, String allele) {
setNode(node);
setAlleleForm(allele);
}// Allele constructor
public void setNode( CyNode node ) { this.node = node; }
public CyNode getNode() { return this.node; }
public void setAlleleForm( String alleleForm ) { this.alleleForm = alleleForm; }
public String getAlleleForm() { return this.alleleForm; }
}//internal class Allele
}//class MutualInfoCalculator
|
Ruby
|
UTF-8
| 2,104 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
require 'apidoco'
#
# ApidocoGenerator
#
# @author sufinsha
#
class ApidocoGenerator < Rails::Generators::Base
desc 'This generator creates empty folder for api versions'
def create_apidoco_folder
resource = args[0]
resource_actions = actions(args[1..-1])
resource_actions.each do |action|
create_file "#{Rails.root}/#{Apidoco.base_path}/#{file_name(resource, action)}",
file_content(resource, action)
end
end
private
def actions(args)
return args if args.present?
%i[show index create update destroy]
end
def default_end_points_with_method(action)
end_points_with_method = {
index: {
endpoint: '.json', method: 'GET', collection: true
},
show: {
endpoint: '/:id.json', method: 'GET', collection: false
},
create: {
endpoint: '.json', method: 'POST', collection: true
},
update: {
endpoint: '/:id.json', method: 'PUT|PATCH', collection: false
},
destroy: {
endpoint: '/:id.json', method: 'DELETE', collection: false
}
}
end_points_with_method[action] || {}
end
def api_name(resource, action)
endpoint_with_method = default_end_points_with_method(action.intern)
resource_title = if endpoint_with_method[:collection]
resource.pluralize.titleize
else
resource.singularize.titleize
end
"#{action.to_s.titleize} #{resource_title}"
end
def file_name(resource, action)
"#{resource}/#{action}.json"
end
def resource_name(resource)
resource.split('/').last
end
def file_content(resource, action)
endpoint_with_method = default_end_points_with_method(action.intern)
name = api_name(resource_name(resource), action)
<<-FILE
{
"published": true,
"name": "#{name}",
"end_point": "#{resource}#{endpoint_with_method[:endpoint]}",
"http_method": "#{endpoint_with_method[:method]}",
"params": [],
"header": {},
"examples": [{
"request": {},
"response": {}
}]
}
FILE
end
end
|
Swift
|
UTF-8
| 496 | 2.65625 | 3 |
[] |
no_license
|
//
// SearchRepository.swift
// AppSearchForRx
//
// Created by hyunjun yang on 06/04/2019.
// Copyright © 2019 hyunjun yang. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
class SearchRepository {
let network = Networking()
var searchData = PublishSubject<SearchResponse>()
func search(text : String) {
network.AppleSearch(words: text) { response in
self.searchData.onNext(response)
print(response.resultCount)
}
}
}
|
Markdown
|
UTF-8
| 4,125 | 3.078125 | 3 |
[] |
no_license
|
# TrabajoPractico
Para ejecutar el programa se debe acceder desde la consola a la direccion ...\VirtualDreams\Ejercicio5 y ejecutar el comando node index.js para iniciar el servidor, luego de esto se puede acceder a la carpeta Ejercicio6 para abrir el archivo html con un navegador.
Ejercicio 2: (abrir readme para poder ver formato xml)
1. Un servidor http es un software, cuya función principal es realizar una comunicación con el usuario devolviendo información en función de las peticiones que el mismo realice.
2. Los verbos HTTP son un conjunto de métodos de petición los cuales son utilizados para indicar la acción que se quiere realizar sobre recurso determinado.
Los mas comunes son los verbos: GET,POST,PUT,DELETE,PATCH, entre otros.
3. En una comunicación HTTP los request es una solicitud para realizar una acción determinada, mientras que los response son las respuestas a esas solicitudes realizadas previamente.
Por Otra parte, los headers permiten tanto al cliente como al servidor el envió de información adicional junto con sus requests y responses.
4. Una querry string es una cadena de consulta que puede definir los datos que se envían a través de la URL en el momento de hacer un request a una página web,
5. Los response codes son códigos de estado los cuales indican de que manera se completo una solicitud HTTP especifica. Los valores toman los rangos del 100 al 199 para brindar respuestas informativas, del 200 al 299 para respuestas satisfactorias, del 300 al 399 para redirecciones, del 400 al 499 para errores de los clientes y del 500 al 599 para informar errores de los servidores.
6.El método Get se utiliza para solicitar la representación de un recurso especifico, este método solo debe recuperar datos, usualmente lo realiza mediante querry strings.
Por otra parte, POST, envía datos al servidor. Es bastante común que estos datos sean enviados mediante un formulario de HTML el cual posee la capacidad de poder seleccionar en que formato de envió.
7. El primer verbo HTTP utilizado al acceder a una pagina web es el verbo GET utilizado para cargar el código HTML, si la respuesta del servidor es positiva, comienza con la carga de los encabezados.
8. JSON es un utilizado para representar datos estructurados en la sintaxis de objetos de JavaScript y resultan muy útiles a la hora de transmitir datos a través de una red.
Por otra parte, XML es un lenguaje de marcado que se puede aplicar en el análisis de datos o la lectura de textos creados por computadoras o personas, implementando una jerarquía estructural para expresar la información de la manera más abstracta y reutilizable posible.
Una estructura posible de XML podría ser:
<animal>
<nombre>Bun</nombre>
<tipo>León</tipo>
<color>Marrón</color>
<edad>15</edad>
</animal>
Mientras que una estructura de JSON podría ser:
{
"latitude": 40.417438,
"longitude": -3.693363,
"city": "Madrid",
"description": "Paseo del Prado"
}
9. Soap es un protocolo el cual se encarga de determinar el formato de la solicitud enviada desde el cliente al servidor, estableciendo interfaces entre un dispositivo y un servicio web, permitiendo el intercambio de datos XML, además de contar con la particularidad de que, dentro del formato de la solicitud, puede incluirse datos específicos de la aplicación, lo cual les permite a los servicios web desplegar determinadas aplicaciones.
10. REST full es otro protocolo más moderno que SOAP, la cual transporta datos por medio del protocolo HTTP, utilizando sus verbos como pueden ser los anteriormente mencionados GET, POST, DELETE, etc. Para realizar solicitudes, permitiendo un uso más flexible del formato de los datos como pueden ser XML, JSON, binary o text.
11. Los header en un request contienen información diversa sobre la petición HTTP y sobre el navegador, los mismos pueden contener diversas propiedades las cuales son optativas, un ejemplo de ellas es el Content-Type, la cual le dice al cliente que tipo de contenido será retornado por esa request.
|
C#
|
UTF-8
| 1,142 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace Xyperico.Base.Crypto
{
public static class RandomStringGenerator
{
public const string ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public const string NUMERIC = "0123456789";
public const string ALPHA_NUMERIC = ALPHA + NUMERIC;
public static string GenerateRandomString(int length, string characterSet = ALPHA_NUMERIC)
{
byte[] data = GenerateRandomBytes(length);
string randomString = "";
int characterSetLength = characterSet.Length;
for (int i = 0; i < length; i++)
{
int position = data[i];
position = (position % characterSetLength);
randomString = (randomString + characterSet.Substring(position, 1));
}
return randomString;
}
public static byte[] GenerateRandomBytes(int length)
{
RandomNumberGenerator randomizer = RandomNumberGenerator.Create();
byte[] data = new byte[length];
randomizer.GetBytes(data);
return data;
}
}
}
|
Python
|
UTF-8
| 1,986 | 2.890625 | 3 |
[] |
no_license
|
#!/usr/bin/python
# -*-coding:Utf-8 -*-
from difflib import ndiff
def dictToCsv(dictInfos, sites):
csv = "Site;"
for category in dictInfos.keys():
csv += category.split("/")[0] + ";"
csv += "\n"
for site in sites.keys():
csv += site.split("/")[1] + ";"
for category in dictInfos.keys():
value = dictInfos[category][site.split("/")[0]]
csv += dictInfos[category][site.split("/")[0]] + ";"
csv += "\n"
return csv
def get_most_common(dictInfos):
numericalInfos = ["Length", "Beam", "Draught", "GT", "Speed"]
mostCommonDict = {}
for category in dictInfos.keys():
values = []
for site in dictInfos[category].keys():
value = dictInfos[category][site].decode("utf8")
if value != "":
values.append(value)
cat = category.split("/")[0]
if cat not in numericalInfos:
compare_and_equals(values)
if len(values) != 0:
mostCommonDict[cat] = most_common(values)
else:
mostCommonDict[cat] = ["No value"]
return str(mostCommonDict).replace("[u'", "['").replace(", u'", ", '")
def compare_and_equals(listValues):
for i,value in enumerate(listValues):
for j in range(i):
compValue = listValues[j]
minus = 0
plus = 0
for diff in ndiff(value, compValue):
if diff[0] == "-":
minus += 1
elif diff[0] == "+":
plus += 1
if minus + plus < 4:
if minus >= plus:
listValues[j] = value
else:
listValues[i] = compValue
def most_common(listValues):
countList = [listValues.count(i) for i in listValues]
maxCount = max(countList)
mostCommonValues = set([listValues[i] for i in [i for i,x in enumerate(countList) if x == maxCount]])
return list(mostCommonValues)
|
PHP
|
UTF-8
| 3,559 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Controllers\v1;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Str;
class AuthController extends Controller
{
public function __construct()
{
$this->call = new ResponseController;
}
public function checkAuth(Request $request)
{
$fetchHeader = $request->header('Authorization');
$header = str_replace('Render-App ', '', $fetchHeader);
$user = User::where('token_auth',$header)->first();
if ($user) {
return $this->call->arrays('ok',
'Authenticate',
[
'id' => $user->id,
'privileges' => $user->privileges,
'nama' => $user->first_name . ' ' . $user->last_name,
],
200);
// return $this->call->index('ok','Authenticate', 200);
}else{
return $this->call->index('failed','Silahkan login kembali', 401);
}
}
public function login(Request $request)
{
$user =User::where('username',$request->username)
->orWhere('email',$request->email)
->first();
if($user){
if (Hash::check($request->password, $user->password)) {
$token = Str::random(10);
$user->update([
'token_auth' => $token,
]);
return $this->call->arrays('ok',
'berhasil login',
[
'token' => $token,
'id' => $user->id,
'privileges' => $user->privileges,
'nama' => $user->first_name . ' ' . $user->last_name,
],
200);
}else{
return $this->call->index('failed','Periksa kembali password anda', 401);
}
}else{
return $this->call->index('failed','Email atau username yang anda gunakan tidak ada terdaftar', 401);
}
}
public function logout(Request $request)
{
$fetchHeader = $request->header('Authorization');
$header = str_replace('Render-App ', '', $fetchHeader);
$user = User::where('token_auth',$header)->first();
if ($user) {
$user->update([
'token_auth' => null,
]);
return $this->call->index('ok','Berhasil logout', 200);
}else{
return $this->call->index('failed','Silahkan login kembali', 401);
}
}
public function buatAkun(Request $request)
{
// Dokumentasi Header Request
// $fetchHeader = $request->header('Authorization');
// $header = str_replace('Render-App ', '', $fetchHeader);
// $user = User::where('token_auth',$header)->first();
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'username' => 'required|unique:users',
'password' => 'required',
]);
User::create([
'privileges' => "aparatur",
'first_name'=> $request->first_name,
'last_name'=> $request->last_name,
'email'=> $request->email,
'username' => $request->username,
'password'=> Hash::make($request->password),
]);
return $this->call->index('ok','Berhasil membuat akun aparatur', 200);
}
}
|
PHP
|
UTF-8
| 7,446 | 2.578125 | 3 |
[] |
no_license
|
<?php
class KeyInsert extends Model{
private $db;
private $user;
private $pageTitle;
private $pageHeading;
private $postArray;
private $panelHead_1;
private $panelContent_1;
private $SESSION;
private $pageID;
private $contentVar;
function __construct($user,$pageTitle,$postArray,$pageHead,$database,$pageID){
parent::__construct($user->getLoggedinState());
$this->db=$database;
$this->pageID=$pageID;
$this->user=$user;
//set the PAGE title
$this->setPageTitle($pageTitle);
//set the PAGE heading
$this->setPageHeading($pageHead);
//get the postArray
$this->postArray=$postArray;
//set the FIRST panel content
$this->setPanelHead_1();
$this->setPanelContent_1();
}
public function setPageTitle($pageTitle){ //set the page title
$this->pageTitle="Document Submitted";
} //end METHOD - set the page title
public function setPageHeading($pageHead){ //set the page heading
$this->pageHeading=$pageHead;
} //end METHOD - set the page heading
public function setPanelHead_1(){
if($this->loggedin){
$this->panelHead_1='<h3>Document Submitted</h3>';
}
else{
$this->panelHead_1='<h3>Please Log in to Use this feature</h3>';
}
}
public function setPanelContent_1(){
$UID = $_SESSION['userid'];
$docname = $this->db->real_escape_string($this->postArray['docname']);
$key1=$this->db->real_escape_string($this->postArray['keyword1']);
$key2=$this->db->real_escape_string($this->postArray['keyword2']);
$key3=$this->db->real_escape_string($this->postArray['keyword3']);
$key4=$this->db->real_escape_string($this->postArray['keyword4']);
$key5=$this->db->real_escape_string($this->postArray['keyword5']);
$key6=$this->db->real_escape_string($this->postArray['keyword6']);
$key7=$this->db->real_escape_string($this->postArray['keyword7']);
$key8=$this->db->real_escape_string($this->postArray['keyword8']);
$key9=$this->db->real_escape_string($this->postArray['keyword9']);
$key10=$this->db->real_escape_string($this->postArray['keyword10']);
$UID = $_SESSION['userid'];
$docname = $this->db->real_escape_string($this->postArray['docname']);
$sql="INSERT INTO documents (docname, userid,kw1,kw2,kw3,kw4,kw5,kw6,kw7,kw8,kw9,kw10) ";
$sql.="VALUES (";
$sql.="'".$docname."',";
$sql.="'".$UID."',";
$sql.="'".$key1."',";
$sql.="'".$key2."',";
$sql.="'".$key3."',";
$sql.="'".$key4."',";
$sql.="'".$key5."',";
$sql.="'".$key6."',";
$sql.="'".$key7."',";
$sql.="'".$key8."',";
$sql.="'".$key9."',";
$sql.="'".$key10."'";
$sql.=");";
//execute the INSERT SQL and check that the new row is inserted OK
if(($this->db->multi_query($sql)===TRUE)&&($this->db->affected_rows===1)){
//$sql="SELECT * FROM user";;
$this->panelContent_1.='<h3>Your document: <b>\''.$docname.'\'</b> has been successfully uploaded!</h3><br>';
$this->panelContent_1.='<button class="btn-mine"> <a href = "'.$_SERVER['PHP_SELF'].'?pageID=documents">Click Here</a></button>';
}
else{
$this->panelContent_1.='Unable to add new Document<br>';
$this->panelContent_1.='<button class="btn-mine"> <a href = "'.$_SERVER['PHP_SELF'].'?pageID=documents">Click Here</a></button>';
}
//
}
////////////Functions go below here
public function sendTerms($kw1,$kw2,$kw3,$kw4,$kw5,$kw6,$kw7,$kw8,$kw9,$kw10){
$sql.= "INSERT INTO keywords (docid, kw1,kw2,kw3,kw4,kw5,kw6,kw7,kw8,kw9,kw10)";
$sql.="VALUES (";
$sql.="47,";
$sql.="'".$kw1."',";
$sql.="'".$kw2."',";
$sql.="'".$kw3."',";
$sql.="'".$kw4."',";
$sql.="'".$kw5."',";
$sql.="'".$kw6."',";
$sql.="'".$kw7."',";
$sql.="'".$kw8."',";
$sql.="'".$kw9."',";
$sql.="'".$kw10."'";
$sql.=")";
$returnString = '';
if(($this->db->query($sql)===TRUE)&&($this->db->affected_rows===1)){
$returnString = "<P>Database Updated!</p>";
}
else{
$returnString = "<P>Database unable to Update!</p>";
}
return $returnString;
}
function dbTest($sql){
$returnString='';
if((@$rs=$this->db->query($sql))&&($rs->num_rows)){ //execute the query and check it worked and returned data
//iterate through the resultset to create a HTML table
$returnString.= '<table class="table table-bordered">';
$returnString.='<tr><th>UserID</th><th>Email</th><th>Password</th><th>userType</th></tr>';//table headings
while ($row = $rs->fetch_assoc()) { //fetch associative array from resultset
$returnString.='<tr>';//--start table row
foreach($row as $key=>$value){
$returnString.= "<td>$value</td>";
}
//Edit button
$returnString.= '</tr>'; //end table row
}
$returnString.= '</table>';
}
else{ //resultset is empty or something else went wrong with the query
$returnString.= '<br>No records available to view - please try again<br>';
}
return $returnString;
}
public function getPageTitle(){return $this->pageTitle;}
public function getPageHeading(){return $this->pageHeading;}
public function getMenuNav(){return $this->menuNav;}
public function getPanelHead_1(){return $this->panelHead_1;}
public function getPanelContent_1(){return $this->panelContent_1;}
public function getUser(){return $this->user;}
}
?>
|
JavaScript
|
UTF-8
| 683 | 2.65625 | 3 |
[] |
no_license
|
class Rope{
constructor(body1,body2,offsetX,offsetY){
this.offsetX=offsetX
this.offsetY=offsetY
var options = {
bodyA : body1,
bodyB : body2,
pointB:{x:this.offsetX,y:this.offsetY}
}
this.rope = Constraint.create(options);
World.add(world,this.rope)
}
display(){
var posA=this.rope.bodyA.position
var posB=this.rope.bodyB.position
strokeWeight(5);
var Anchor1X=posA.x;
var Anchor1Y=posA.y;
var Anchor2X=posB.x+this.offsetX
var Anchor2Y=posB.y+this.offsetY
line(Anchor1X,Anchor1Y,Anchor2X,Anchor2Y )
}
}
|
C++
|
UTF-8
| 10,764 | 3.75 | 4 |
[] |
no_license
|
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <chrono>
using namespace std::chrono;
//----------Random Number Generator--------------------
int* randomNumberGenerator(int arraySize, int newSort[]){
//Planting random seed
srand((unsigned)time(NULL));
//Creating array of random number
//Establishing
int random;
bool inserted;
bool isDuplicate;
for(int i = 0; i < arraySize; i++){
inserted = false;
//Checking for duplicates
while(!inserted){
//Random number between 1 and 20,000
random = (rand()%20000)+1;
isDuplicate = false;
for(int x = 0; x < i; x++){
//Checking if the randomly generated number is currently in the array
//If it is in array set bool to True.
if(random == newSort[x]){
isDuplicate = true;
}
}
//Not duplicate, add random number to the array.
if(!isDuplicate){
newSort[i] = random;
std::cout<< newSort[i]<<std::endl;
//Now inserted move on
inserted = true;
}
}
}
return newSort;
}
//------------------Print Array-----------------------
void printArray(int arraySize, int* newSort){
for(int i = 0; i< arraySize; i++){
std::cout<<newSort[i]<<std::endl;
}
}
//--------------Insertion Sort-------------------
void insertionSort(int arraySize, int newSort[]){
//creating temp variable
int j, hold;
for(int i = 0; i< arraySize; i++){
j = i;
while(j>0 && newSort[j]< newSort[j-1]){
hold = newSort[j];
newSort[j] = newSort[j-1];
newSort[j-1] = hold;
j--;
}
}
}
//-------------Merge Sort-------------------------------
void merge(int newSort[], int low, int high, int middle){
int p1, p2, p3;
//Creating two temporary sub arrays to hold smaller portions.
int temp1 = middle - low + 1;
int temp2 = high - middle;
//Creating temporary arrays to be used as sub arrays
int left[temp1], right[temp2];
//For loops to copy the data to the temporary arrays
for(p1 = 0; p1 < temp1; p1++){
left[p1] = newSort[low + p1];
}
for(p2 = 0; p2 < temp2; p2++){
right[p2] = newSort[middle + 1 + p2];
}
//--------------Merging---------------
//Initial indexes
p1 = 0;
p2 = 0;
p3 = low;
//Merge temp arrays into original array
while(p1 < temp1 && p2 < temp2){
if(left[p1]<= right[p2]){
newSort[p3] = left[p1];
p1++;
}
else{
newSort[p3] = right[p2];
p2++;
}
p3++;
}
//Copying remaining elements of sub arrays
while(p1 < temp1){
newSort[p3] = left[p1];
p1++;
p3++;
}
while(p2 < temp2){
newSort[p3] = right[p2];
p2++;
p3++;
}
}
//Actual merge sort
void mergeSort(int newSort[], int low, int high){
int middle;
if(low < high){
//Finding middle of array
//Avoids overflow
middle = (low + high)/2;
//Sorting separate halves
mergeSort(newSort, low, middle);
mergeSort(newSort, middle + 1, high);
//Merge
merge(newSort, low, high, middle);
}
return;
}
//--------------Heap Sort-----------------------
void swapHeap(int* newSort, int i, int j){
if(i == j){
return;
}
int temp;
temp = newSort[i];
newSort[i] = newSort[j];
newSort[j] = temp;
}
void organize(int* newSort, int heapS, int node){
int i, j;
//Largest as root
j = node;
while(i != j){
i = j;
if(((2*i + 1) < heapS) && newSort[j] < newSort[2*i + 1]) {
j = 2*i + 1;
}
if(((2*i + 2) < heapS) && newSort[j] < newSort[2*i + 2]) {
j = 2*i + 2;
}
swapHeap(newSort, i, j);
}
}
//Constructing a heap
void createHeap(int arraySize, int* newSort){
for(int i = arraySize - 1; i >= 0; --i){
organize(newSort, arraySize, i);
}
}
void heapSort(int arraySize, int* newSort){
createHeap(arraySize, newSort);
//Grab an element from the heap
for(int i = arraySize - 1; i > 0; --i){
//Move current root to end
swapHeap(newSort, i, 0);
//call organize
organize(newSort, i, 0);
}
}
//------------ Quick Sort----------------
// The partition function
int partition(int* newSort, int i, int j)
{
//Last element as pivot or furthest to the right
int pivot = newSort[j];
while ( i < j )
{
while ( newSort[i] < pivot )
//Increase index or move to the right
i++;
while ( newSort[j] > pivot )
//Decrease index or move to the left.
j--;
if ( newSort[i] == newSort[j] )
//Increase index
i++;
else if ( i < j )
{
//Swap
int tmp = newSort[i];
newSort[i] = newSort[j];
newSort[j] = tmp;
}
}
return j;
}
// The quicksort recursive function
void quickSort(int* newSort, int i, int j)
{
if ( i < j )
{
//n is the partitioning index
int n = partition(newSort, i, j);
//Before index
quickSort(newSort, i, n-1);
//After index
quickSort(newSort, n+1, j);
}
}
int main()
{
//To be used for finding the execution time.
auto t_start = std::chrono::high_resolution_clock::now();
auto t_end = std::chrono::high_resolution_clock::now();
//Taking in size of List
int size;
std::cout<< "Please enter size of list: "<<std::endl;
std::cin>> size;
int sortThis[size], sortMergeArray[size],sortHeapArray[size],sortQuickArray[size];
std::cout<<"Unsorted"<<std::endl;
//Copying into different arrays for easier access with sorting algorithms
//Wanted to make sure that the first sort was random and not influenced by another sorting algorithm.
randomNumberGenerator(size, sortThis);
std::copy(sortThis, sortThis + size, sortMergeArray);
std::copy(sortThis, sortThis + size, sortHeapArray);
std::copy(sortThis, sortThis + size, sortQuickArray);
std::cout<<"------------------------------------------"<<std::endl;
//------------------------------------------------------------------------
std::cout<<"Insertion Sort" <<std::endl;
//Unsorted
t_start = std::chrono::high_resolution_clock::now();
insertionSort(size, sortThis);
t_end = std::chrono::high_resolution_clock::now();
//printArray(size, sortThis);
std::cout << std::fixed<<"Unsorted: "
<< "Wall clock time passed: "
<< std::chrono::duration<float, std::milli>(t_end-t_start).count()
<< " ms/n"<<std::endl;
t_start = std::chrono::high_resolution_clock::now();
insertionSort(size, sortThis);
t_end = std::chrono::high_resolution_clock::now();
std::cout << std::fixed<<"Sorted: "
<< "Wall clock time passed: "
<< std::chrono::duration<float, std::milli>(t_end-t_start).count()
<< " ms/n"<<std::endl;
std::cout<<"------------------------------------------"<<std::endl;
//--------------------------------------------------------------------------
std::cout<<"Merge Sort"<<std::endl;
t_start = std::chrono::high_resolution_clock::now();
mergeSort(sortMergeArray, 0, size - 1);
t_end = std::chrono::high_resolution_clock::now();
//printArray(size, sortMergeArray);
std::cout << std::fixed<<"Unsorted: "
<< "Wall clock time passed: "
<< std::chrono::duration<float, std::milli>(t_end-t_start).count()
<< " ms/n"<<std::endl;
t_start = std::chrono::high_resolution_clock::now();
mergeSort(sortMergeArray, 0, size - 1);
t_end = std::chrono::high_resolution_clock::now();
std::cout << std::fixed<<"Sorted: "
<< "Wall clock time passed: "
<< std::chrono::duration<float, std::milli>(t_end-t_start).count()
<< " ms/n"<<std::endl;
std::cout<<"------------------------------------------"<<std::endl;
//---------------------------------------------------------------------
std::cout<<"Heap Sort"<<std::endl;
t_start = std::chrono::high_resolution_clock::now();
heapSort(size, sortHeapArray);
t_end = std::chrono::high_resolution_clock::now();
//printArray(size, sortHeapArray);
std::cout << std::fixed<< "Unsorted: "
<< "Wall clock time passed: "
<< std::chrono::duration<float, std::milli>(t_end-t_start).count()
<< " ms/n"<<std::endl;
t_start = std::chrono::high_resolution_clock::now();
heapSort(size, sortHeapArray);
t_end = std::chrono::high_resolution_clock::now();
std::cout << std::fixed<<"Sorted: "
<< "Wall clock time passed: "
<< std::chrono::duration<float, std::milli>(t_end-t_start).count()
<< " ms/n"<<std::endl;
std::cout<<"------------------------------------------"<<std::endl;
//----------------------------------------------------------------------
std::cout<<"Quick Sort"<<std::endl;
t_start = std::chrono::high_resolution_clock::now();
quickSort(sortQuickArray, 0, (size-1));
t_end = std::chrono::high_resolution_clock::now();
//printArray(size, sortQuickArray);
std::cout << std::fixed<<"Unsorted: "
<< "Wall clock time passed: "
<< std::chrono::duration<float, std::milli>(t_end-t_start).count()
<< " ms/n"<<std::endl;
t_start = std::chrono::high_resolution_clock::now();
quickSort(sortQuickArray, 0, size);
t_end = std::chrono::high_resolution_clock::now();
std::cout << std::fixed<<"Sorted: "
<< "Wall clock time passed: "
<< std::chrono::duration<float, std::milli>(t_end-t_start).count()
<< " ms/n"<<std::endl;
std::cout<<"------------------------------------------"<<std::endl;
//------------------------------------------------------------------------
return 0;
}
|
Swift
|
UTF-8
| 647 | 3.140625 | 3 |
[] |
no_license
|
import UIKit
//https://leetcode-cn.com/problems/friend-circles/
func findCircleNum(_ M: [[Int]]) -> Int {
if M.count == 0 || M[0].count == 0 { return 0 }
let n = M.count
var count = 0
var visited = Array(repeating: false, count: n)
for i in 0..<n {
if !visited[i] {
dfs(i, &visited, M)
count += 1
}
}
return count
}
func dfs(_ i: Int, _ visited: inout [Bool], _ M:[[Int]]) {
visited[i] = true
for j in 0..<M.count {
if i == j { continue }
if !visited[j] && M[i][j] == 1 {
visited[j] = true
dfs(j, &visited, M)
}
}
}
|
PHP
|
UTF-8
| 13,329 | 2.59375 | 3 |
[] |
no_license
|
<?php
namespace CommanderZiltoid\lempmetrics;
class Metrics {
private $_access_log_path;
private $_log_lines = [];
private $_logs_to_read;
private $_access_log = [];
private $_callbacks = [];
public function __construct($path='') {
// If no path given, assume default nginx access.log path
if($path === ''){
$this->_access_log_path = '/var/log/nginx/';
} else {
$this->_access_log_path = $path;
}
// Will assume standard nginx log naming convention is followed
// * Most current: access.log
// * Previous: access.log.1
// * Archived: access.log.{number}.gz
}
/***************************************************************************
****************************************************************************
************************** SERVER STATS METHODS ****************************
****************************************************************************
***************************************************************************/
// These methods are useful when you are on a single dedicated server,
// however, if your backend architecture consists of several load balanced
// servers, functionality will need to be added to handle this (for example,
// do this logic but once for each server in pool)
/* Calculate CPU usage percentage since boot
***************************************************************************/
public static function getCPUUsageSinceBoot(){
$cpu = self::_parseProcStatFile();
$total_time_since_boot = $cpu[0] + $cpu[1] + $cpu[2] +
$cpu[3] + $cpu[4] + $cpu[5] + $cpu[6] + $cpu[7];
$total_idle_time_since_boot = $cpu[3] + $cpu[4];
$total_usage_time_since_boot = $total_time_since_boot - $total_idle_time_since_boot;
$total_usage_percentage_since_boot = ($total_usage_time_since_boot / $total_time_since_boot) * 100;
return round($total_usage_percentage_since_boot, 2);
}
/* Calculate CPU usage percentage realtime
***************************************************************************/
public static function getCPUUsageLive(){
$last_idle = 0;
$last_total = 0;
$return_val = 0;
for($i = 0; $i < 2; $i++){
$cpu = self::_parseProcStatFile();
$idle = $cpu[3];
$total = array_sum($cpu);
$idle_delta = $idle - $last_idle;
$total_delta = $total - $last_total;
$last_idle = $idle;
$last_total = $total;
$utilization = 100.0 * (1.0 - $idle_delta / $total_delta);
if($i == 1){
$return_val = $utilization;
break;
}
sleep(1);
}
return round($return_val, 2);
}
/* Obtain current disk usages
***************************************************************************/
public static function getDiskUsageLive(){
$tmp = shell_exec('df -h');
$tmp2 = explode("\n", $tmp);
unset($tmp2[count($tmp2) - 1]); // remove empty element
unset($tmp2[0]); // remove column names row
$tmp2 = array_merge($tmp2);
$return = [];
foreach($tmp2 as $k => $v){
$tmp3 = explode(" ", $v);
foreach($tmp3 as $k2 => $v2){
if($v2 == ''){
unset($tmp3[$k2]);
}
}
$tmp3 = array_merge($tmp3);
$return[] = [
'fs' => $tmp3[0],
'size' => $tmp3[1],
'used' => $tmp3[2],
'available' => $tmp3[3],
'use' => $tmp3[4],
'mounted' => $tmp3[5]
];
}
return $return;
}
/* Obtain current free memory and memory being used
***************************************************************************/
public static function getMemoryUsageLive(){
$o = explode("\n", shell_exec('free -m'));
$mem = explode(" ", $o[1]);
foreach($mem as $k => $v){
if($v == 'Mem:' || $v == ''){
unset($mem[$k]);
}
}
$mem = array_merge($mem);
$buf = explode(" ", $o[2]);
foreach($buf as $k => $v){
if($v == '-/+' || $v == 'buffers/cache:' || $v == ''){
unset($buf[$k]);
}
}
$buf = array_merge($buf);
$swap = explode(" ", $o[3]);
foreach($swap as $k => $v){
if($v == 'Swap:' || $v == ''){
unset($swap[$k]);
}
}
$swap = array_merge($swap);
$return = [
'mem' => [
'total' => $mem[0],
'used' => $mem[1],
'free' => $mem[2],
'shared' => $mem[3],
'buffers' => $mem[4],
'cached' => $mem[5]
],
'buf' => [
'used' => $buf[0],
'free' => $buf[1]
],
'swap' => [
'total' => $swap[0],
'used' => $swap[1],
'free' => $swap[2]
]
];
return $return;
}
/* Calculate CPU usage percentage since boot
* $cpu[0] - user
* $cpu[1] - nice
* $cpu[2] - system
* $cpu[3] - idle
* $cpu[4] - iowait
* $cpu[5] - irq
* $cpu[6] - softirq
* $cpu[7] - steal
***************************************************************************/
private static function _parseProcStatFile(){
return explode(" ", str_replace("cpu ", "",
explode("\n", shell_exec('cat /proc/stat'))[0]));
}
/***************************************************************************
****************************************************************************
*************************** ACCESS LOG METHODS *****************************
****************************************************************************
***************************************************************************/
public function getAccessLogs(){
$files = scandir($this->_access_log_path);
foreach($files as $file){
if(strpos($file, 'access.log') === false){
$key = array_search($file, $files);
unset($files[$key]);
}
}
return $files;
}
/* Set which access.log file or files to read
***************************************************************************/
public function setLogs($logs){
$this->_logs_to_read = $logs;
$this->_readLogs();
}
/* Obtain all requests containing the given substring
***************************************************************************/
public function request($request){
$this->_callbacks[] = function($r) use ($request){
if(strpos($r->request, $request) !== false){
return true;
}
return false;
};
return $this;
}
/* Obtain all requests containing the given status code
***************************************************************************/
public function status($code){
$this->_callbacks[] = function($r) use ($code){
if($r->status == $code){
return true;
}
return false;
};
return $this;
}
/* Obtain all requests made by the given ip address
***************************************************************************/
public function address($address){
$this->_callbacks[] = function($r) use ($address){
if($r->address == $address){
return true;
}
return false;
};
return $this;
}
/* Obtain all requests coming from a specific page...yeah I'm spelling
* referrer correctly...it's confusing but the other way just bothers me.
***************************************************************************/
public function referrer($referrer){
$this->_callbacks[] = function($r) use ($referrer){
if(strpos($r->referrer, $referrer) !== false){
return true;
}
return false;
};
return $this;
}
/* Obtain all requests with a user_agent string containing $agent
***************************************************************************/
public function userAgent($agent){
$this->_callbacks[] = function($r) use ($agent){
if(strpos($r->user_agent, $agent) !== false){
return true;
}
return false;
};
return $this;
}
/* Obtain all requests taking longer than $time to complete
***************************************************************************/
public function requestTime($time){
$this->_callbacks[] = function($r) use ($time){
if((double)$r->request_time > $time){
return true;
}
return false;
};
return $this;
}
/* Return the _access_log array
--------------------------------------------------------------------------*/
public function get(){
$this->_build_access_log();
return $this->_access_log;
}
/* Return number of elements in _access_log array
--------------------------------------------------------------------------*/
public function count(){
$this->_build_access_log();
return count($this->_access_log);
}
/* Read log file/s into memory
--------------------------------------------------------------------------*/
private function _readLogs(){
foreach($this->_logs_to_read as $log){
if(strpos($log, 'access.log') !== false){
$file_contents = file_get_contents($this->_access_log_path . $log);
if(strpos($log, '.gz') !== false){
$file_contents = gzdecode($file_contents);
}
$this->_log_lines = array_merge($this->_log_lines, explode("\n", $file_contents));
}
}
return $this;
}
/* Insure _access_log is empty. Loop through each element in _log_lines and
* determine if line should be added to _access_log using array of callbacks
--------------------------------------------------------------------------*/
private function _build_access_log(){
$this->_clear_access_log();
foreach($this->_log_lines as $line){
$r = new LogEntry($line);
if(($r != '')){
$tmp = [];
foreach($this->_callbacks as $cb){
$tmp[] = $cb($r);
}
//echo var_export($tmp) . '<br/>';
if(!in_array(false, $tmp, true)){
$this->_add_to_access_log_array($r);
}
}
}
$this->_sort_access_log();
}
/* Set _access_log equal to an empty array
***************************************************************************/
private function _clear_access_log(){
$this->_access_log = array();
}
private function _sort_access_log(){
if(count($this->_logs_to_read) > 1){
usort($this->_access_log, function($a, $b){
$ats = strtotime($a->requested_at);
$bts = strtotime($b->requested_at);
if($ats > $bts){
return -1;
} else if($ats < $bts){
return 1;
} else if($ats == $bts){
return 0;
}
});
} else {
$this->_access_log = array_reverse($this->_access_log);
}
}
private function _add_to_access_log_array($r){
$r->requested_at = $this->_format_log_time($r->requested_at);
$this->_access_log[] = $r;
}
private function _format_log_time($t){
if(!$t){
return '';
}
$e1 = explode('/', $t);
$e2 = explode(':', $e1[2]);
$year = $e2[0];
$month = $e1[1];
$day = $e1[0];
$hour = $e2[1];
$minute = $e2[2];
$second = explode(' ', $e2[3])[0];
return date('m/d/Y h:i:s a', strtotime("$month $day $year $hour:$minute:$second"));
}
/* END OF CLASS
--------------------------------------------------------------------------*/
}
|
Java
|
UTF-8
| 81,746 | 2.046875 | 2 |
[
"BSD-3-Clause"
] |
permissive
|
//
// The contents of this file are subject to the Mozilla Public
// License Version 1.1 (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.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an
// "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
// implied. See the License for the specific language governing
// rights and limitations under the License.
//
// The Original Code is State Machine Compiler (SMC).
//
// The Initial Developer of the Original Code is Charles W. Rapp.
// Portions created by Charles W. Rapp are
// Copyright (C) 2005, 2008 - 2009. Charles W. Rapp.
// All Rights Reserved.
//
// Contributor(s):
// Eitan Suez contributed examples/Ant.
// (Name withheld) contributed the C# code generation and
// examples/C#.
// Francois Perrad contributed the Python code generation and
// examples/Python.
// Chris Liscio contributed the Objective-C code generation
// and examples/ObjC.
//
// RCS ID
// $Id: SmcCSharpGenerator.java,v 1.12 2011/11/20 14:58:33 cwrapp Exp $
//
// CHANGE LOG
// (See the bottom of this file.)
//
package net.sf.smc.generator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.sf.smc.model.SmcAction;
import net.sf.smc.model.SmcElement;
import net.sf.smc.model.SmcElement.TransType;
import net.sf.smc.model.SmcFSM;
import net.sf.smc.model.SmcGuard;
import net.sf.smc.model.SmcMap;
import net.sf.smc.model.SmcParameter;
import net.sf.smc.model.SmcState;
import net.sf.smc.model.SmcTransition;
import net.sf.smc.model.SmcVisitor;
/**
* Visits the abstract syntax tree, emitting C# code to an output
* stream.
* @see SmcElement
* @see SmcCodeGenerator
* @see SmcVisitor
* @see SmcOptions
*
* @author <a href="mailto:rapp@acm.org">Charles Rapp</a>
*/
public final class SmcCSharpGenerator
extends SmcCodeGenerator
{
//---------------------------------------------------------------
// Member methods
//
//-----------------------------------------------------------
// Constructors.
//
/**
* Creates a C# code generator for the given options.
* @param options The target code generator options.
*/
public SmcCSharpGenerator(final SmcOptions options)
{
super (options, "cs");
} // end of SmcCSharpGenerator(SmcOptions)
//
// end of Constructors.
//-----------------------------------------------------------
//-----------------------------------------------------------
// SmcVisitor Abstract Method Impelementation.
//
/**
* Emits C# code for the finite state machine.
* Generates the using statements, namespace, the FSM
* context class, the default transitions and the FSM map
* classes.
* @param fsm emit C# code for this finite state machine.
*/
public void visit(SmcFSM fsm)
{
String rawSource = fsm.getSource();
String packageName = fsm.getPackage();
String context = fsm.getContext();
String fsmClassName = fsm.getFsmClassName();
String startState = fsm.getStartState();
String accessLevel = fsm.getAccessLevel();
List<SmcMap> maps = fsm.getMaps();
List<SmcTransition> transitions;
Iterator<SmcParameter> pit;
String transName;
String csState;
String separator;
int index;
List<SmcParameter> params;
String indent2;
// If the access level has not been set, then the
// default is "public".
if (accessLevel == null || accessLevel.length() == 0)
{
accessLevel = "public";
}
// Dump out the raw source code, if any.
if (rawSource != null && rawSource.length() > 0)
{
_source.println(rawSource);
_source.println();
}
// Always include the system package.
_source.println("using System;");
// If debugging code is being generated, then import
// system diagnostics package as well.
if (_debugLevel >= DEBUG_LEVEL_0)
{
_source.println("using System.Diagnostics;");
}
// If serialization is on, then import the .Net
// serialization package.
if (_serialFlag == true)
{
_source.println(
"using System.Runtime.Serialization;");
_source.println("using System.Security;");
_source.println(
"using System.Security.Permissions;");
}
// If reflection is on, then import the .Net collections
// package.
if (_reflectFlag == true)
{
if (_genericFlag == true)
{
_source.println("using System.Collections.Generic;");
}
else
{
_source.println("using System.Collections;");
}
}
_source.println();
// Do user-specified imports now.
for (String imp: fsm.getImports())
{
_source.print("using ");
_source.print(imp);
_source.println(";");
}
// If a package has been specified, generate the package
// statement now and set the indent.
if (packageName != null && packageName.length() > 0)
{
_source.print("namespace ");
_source.println(packageName);
_source.println("{");
_indent = " ";
}
// Does the user want to serialize this FSM?
if (_serialFlag == true)
{
_source.print(_indent);
_source.println("[Serializable]");
}
// Now declare the FSM context class.
_source.print(_indent);
_source.print(accessLevel);
_source.print(" sealed class ");
_source.print(fsmClassName);
_source.println(" :");
_source.print(_indent);
_source.print(" statemap.FSMContext");
if (_serialFlag == false)
{
_source.println();
}
else
{
_source.println(',');
_source.print(_indent);
_source.println(" ISerializable");
}
_source.print(_indent);
_source.println("{");
_source.print(_indent);
_source.println(
"//---------------------------------------------------------------");
_source.print(_indent);
_source.println("// Properties.");
_source.print(_indent);
_source.println("//");
_source.println();
// State property.
_source.print(_indent);
_source.print(" public ");
_source.print(context);
_source.println("State State");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(" get");
_source.print(_indent);
_source.println(" {");
// Again, if synchronization is on, then protect access
// to this FSM.
if (_syncFlag == true)
{
_source.print(_indent);
_source.println(" lock (this)");
_source.print(_indent);
_source.println(" {");
indent2 = _indent + " ";
}
else
{
indent2 = _indent + " ";
}
_source.print(indent2);
_source.println("if (state_ == null)");
_source.print(indent2);
_source.println("{");
_source.print(indent2);
_source.println(" throw(");
_source.print(indent2);
_source.println(
" new statemap.StateUndefinedException());");
_source.print(indent2);
_source.println("}");
_source.println();
_source.print(indent2);
_source.print("return ((");
_source.print(context);
_source.println("State) state_);");
// If we are in a lock block, close it.
if (_syncFlag == true)
{
_source.print(_indent);
_source.println(" }");
}
// Close the State get.
_source.print(_indent);
_source.println(" }");
// Now generate the State set.
_source.print(_indent);
_source.println(" set");
_source.print(_indent);
_source.println(" {");
// Again, if synchronization is on, then protect access
// to this FSM.
if (_syncFlag == true)
{
_source.print(_indent);
_source.println(" lock (this)");
_source.print(_indent);
_source.println(" {");
indent2 = _indent + " ";
}
else
{
indent2 = _indent + " ";
}
_source.print(indent2);
_source.println("SetState(value);");
// If we are in a lock block, close it.
if (_syncFlag == true)
{
_source.print(_indent);
_source.println(" }");
}
// Close the State set.
_source.print(_indent);
_source.println(" }");
// Close the state property.
_source.print(_indent);
_source.println(" }");
_source.println();
// Generate the Owner property.
_source.print(_indent);
_source.print(" public ");
_source.print(context);
_source.println(" Owner");
_source.print(_indent);
_source.println(" {");
// Generate the property get method.
_source.print(_indent);
_source.println(" get");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(" return (_owner);");
_source.print(_indent);
_source.println(" }");
// Generate the property set method.
_source.print(_indent);
_source.println(" set");
_source.print(_indent);
_source.println(" {");
// Again, if synchronization is on, then protect access
// to this FSM.
if (_syncFlag == true)
{
_source.print(_indent);
_source.println(" lock (this)");
_source.print(_indent);
_source.println(" {");
indent2 = _indent + " ";
}
else
{
indent2 = _indent + " ";
}
_source.print(indent2);
_source.println("_owner = value;");
// If we are in a lock block, close it.
if (_syncFlag == true)
{
_source.print(_indent);
_source.println(" }");
}
// Close the Onwer set.
_source.print(_indent);
_source.println(" }");
// Close the Owner property.
_source.print(_indent);
_source.println(" }");
_source.println();
// If reflect is on, then generate the States property.
if (_reflectFlag == true)
{
_source.print(_indent);
_source.print(" public ");
_source.print(context);
_source.println("State[] States");
_source.print(_indent);
_source.println(" {");
// Generate the property get method. There is no set
// method.
_source.print(_indent);
_source.println(" get");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(" return (_States);");
_source.print(_indent);
_source.println(" }");
// Close the States property.
_source.print(_indent);
_source.println(" }");
_source.println();
}
_source.print(_indent);
_source.println(
"//---------------------------------------------------------------");
_source.print(_indent);
_source.println("// Member methods.");
_source.print(_indent);
_source.println("//");
_source.println();
// The state name "map::state" must be changed to
// "map.state".
if ((index = startState.indexOf("::")) >= 0)
{
csState = startState.substring(0, index) +
"." +
startState.substring(index + 2);
}
else
{
csState = startState;
}
// Generate the context class' constructor.
_source.print(_indent);
_source.print(" public ");
_source.print(fsmClassName);
_source.print("(");
_source.print(context);
_source.println(" owner) :");
_source.print(_indent);
_source.print(" base (");
_source.print(csState);
_source.println(")");
_source.print(_indent);
_source.println(" {");
_source.println(" _owner = owner;");
_source.print(_indent);
_source.println(" }");
_source.println();
// The finite state machine start method.
_source.print(_indent);
_source.println(" public override void EnterStartState()");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(" State.Entry(this);");
_source.print(_indent);
_source.println(" return;");
_source.print(_indent);
_source.println(" }");
_source.println();
// If -serial was specified, then generate the
// deserialize constructor.
if (_serialFlag == true)
{
_source.print(_indent);
_source.print(" public ");
_source.print(fsmClassName);
_source.print("(SerializationInfo info, ");
_source.println("StreamingContext context) :");
_source.print(_indent);
_source.println(" base ()");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(" int stackSize;");
_source.print(_indent);
_source.println(" int stateId;");
_source.println();
_source.print(_indent);
_source.print(
" stackSize = ");
_source.println("info.GetInt32(\"stackSize\");");
_source.print(_indent);
_source.println(" if (stackSize > 0)");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(" int index;");
_source.print(_indent);
_source.println(" String name;");
_source.println();
_source.print(_indent);
_source.print(
" for (index = (stackSize - 1); ");
_source.println("index >= 0; --index)");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.print(" ");
_source.println("name = \"stackIndex\" + index;");
_source.print(_indent);
_source.print(" ");
_source.println("stateId = info.GetInt32(name);");
_source.print(_indent);
_source.print(" ");
_source.println("PushState(_States[stateId]);");
_source.print(_indent);
_source.println(" }");
_source.print(_indent);
_source.println(" }");
_source.println();
_source.print(_indent);
_source.println(
" stateId = info.GetInt32(\"state\");");
_source.print(_indent);
_source.println(
" PushState(_States[stateId]);");
_source.print(_indent);
_source.println(" }");
_source.println();
}
// Generate the default transition methods.
// First get the transition list.
transitions = fsm.getTransitions();
for (SmcTransition trans: transitions)
{
transName = trans.getName();
// Ignore the default transition.
if (transName.equals("Default") == false)
{
_source.print(_indent);
_source.print(" public void ");
_source.print(transName);
_source.print("(");
// Now output the transition's parameters.
params = trans.getParameters();
for (pit = params.iterator(), separator = "";
pit.hasNext() == true;
separator = ", ")
{
_source.print(separator);
(pit.next()).accept(this);
}
_source.println(")");
_source.print(_indent);
_source.println(" {");
// If the -sync flag was specified, then output
// "lock (this)" to prevent multiple threads from
// access this state machine simultaneously.
if (_syncFlag == true)
{
_source.print(_indent);
_source.println(" lock (this)");
_source.print(_indent);
_source.println(" {");
indent2 = _indent + " ";
}
else
{
indent2 = _indent + " ";
}
// Save away the transition name in case it is
// need in an UndefinedTransitionException.
_source.print(indent2);
_source.print("transition_ = \"");
_source.print(transName);
_source.println("\";");
_source.print(indent2);
_source.print("State.");
_source.print(transName);
_source.print("(this");
for (SmcParameter param: params)
{
_source.print(", ");
passParameter(param);
}
_source.println(");");
_source.print(indent2);
_source.println("transition_ = \"\";");
// If the -sync flag was specified, then output
// the "End SyncLock".
if (_syncFlag == true)
{
_source.print(_indent);
_source.println(" }");
_source.println();
}
_source.print(_indent);
_source.println(" return;");
_source.print(_indent);
_source.println(" }");
_source.println();
}
}
// If -serial specified, then output the valueOf(int)
// method.
if (_serialFlag == true)
{
_source.print(_indent);
_source.print(" public ");
_source.print(context);
_source.println("State valueOf(int stateId)");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(" return(_States[stateId]);");
_source.print(_indent);
_source.println(" }");
_source.println();
}
// If serialization is turned on, then output the
// GetObjectData method.
if (_serialFlag == true)
{
_source.print(_indent);
_source.print(" [SecurityPermissionAttribute(");
_source.print("SecurityAction.Demand, ");
_source.println("SerializationFormatter=true)]");
_source.print(_indent);
_source.print(" public void GetObjectData(");
_source.println("SerializationInfo info,");
_source.print(_indent);
_source.print(" ");
_source.println("StreamingContext context)");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(" int stackSize = 0;");
_source.println();
_source.print(_indent);
_source.println(" if (stateStack_ != null)");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(
" stackSize = stateStack_.Count;");
_source.print(_indent);
_source.println(" }");
_source.println();
_source.print(_indent);
_source.print(" ");
_source.println(
"info.AddValue(\"stackSize\", stackSize);");
_source.println();
_source.print(_indent);
_source.println(" if (stackSize > 0)");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(" int index = 0;");
_source.print(_indent);
_source.println(" String name;");
_source.println();
_source.print(_indent);
_source.print(" foreach (");
_source.print(context);
_source.println("State state in stateStack_)");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.print(" ");
_source.println("name = \"stackIndex\" + index;");
_source.print(_indent);
_source.print(" info.AddValue(");
_source.println("name, state.Id);");
_source.print(_indent);
_source.println(" ++index;");
_source.print(_indent);
_source.println(" }");
_source.print(_indent);
_source.println(" }");
_source.println();
_source.print(_indent);
_source.println(
" info.AddValue(\"state\", state_.Id);");
_source.println();
_source.print(_indent);
_source.println(" return;");
_source.print(_indent);
_source.println(" }");
_source.println();
}
// Declare member data.
_source.print(_indent);
_source.println(
"//---------------------------------------------------------------");
_source.print(_indent);
_source.println("// Member data.");
_source.print(_indent);
_source.println("//");
_source.println();
_source.print(_indent);
_source.println(" [NonSerialized]");
_source.print(_indent);
_source.print(" private ");
_source.print(context);
_source.println(" _owner;");
_source.println();
// If serialization support is on, then create the state
// array.
if (_serialFlag == true || _reflectFlag == true)
{
String mapName;
_source.print(_indent);
_source.println(
" // Map state IDs to state objects.");
_source.print(_indent);
_source.println(
" // Used to deserialize an FSM.");
_source.print(_indent);
_source.println(" [NonSerialized]");
_source.print(_indent);
_source.print(" private static ");
_source.print(context);
_source.println("State[] _States =");
_source.print(_indent);
_source.print(" {");
separator = "";
for (SmcMap map: maps)
{
mapName = map.getName();
for (SmcState state: map.getStates())
{
_source.println(separator);
_source.print(_indent);
_source.print(" ");
_source.print(mapName);
_source.print(".");
_source.print(state.getClassName());
separator = ",";
}
}
_source.println();
_source.print(_indent);
_source.println(" };");
_source.println();
}
// Declare the inner state class.
_source.print(_indent);
_source.println(
"//---------------------------------------------------------------");
_source.print(_indent);
_source.println("// Inner classes.");
_source.print(_indent);
_source.println("//");
_source.println();
_source.print(_indent);
_source.print(" public abstract class ");
_source.print(context);
_source.println("State :");
_source.print(_indent);
_source.println(" statemap.State");
_source.print(_indent);
_source.println(" {");
// The abstract Transitions property - if reflection was
// is specified.
if (_reflectFlag == true)
{
_source.print(_indent);
_source.println(" //-----------------------------------------------------------");
_source.print(_indent);
_source.println(" // Properties.");
_source.print(_indent);
_source.println(" //");
_source.println();
_source.print(_indent);
_source.print(" ");
_source.print("public abstract IDictionary");
if (_genericFlag == true)
{
_source.print("<string, int>");
}
_source.println(" Transitions");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(" get;");
_source.print(_indent);
_source.println(" }");
_source.println();
}
_source.print(_indent);
_source.println(" //-----------------------------------------------------------");
_source.print(_indent);
_source.println(" // Member methods.");
_source.print(_indent);
_source.println(" //");
_source.println();
// State constructor.
_source.print(_indent);
_source.print(" internal ");
_source.print(context);
_source.println("State(string name, int id) :");
_source.print(_indent);
_source.println(" base (name, id)");
_source.print(_indent);
_source.println(" {}");
_source.println();
// Entry/Exit methods.
_source.print(_indent);
_source.print(
" protected internal virtual void Entry(");
_source.print(fsmClassName);
_source.println(" context)");
_source.print(_indent);
_source.println(" {}");
_source.println();
_source.print(_indent);
_source.print(
" protected internal virtual void Exit(");
_source.print(fsmClassName);
_source.println(" context)");
_source.print(_indent);
_source.println(" {}");
_source.println();
// Transition methods (except default).
for (SmcTransition trans: transitions)
{
transName = trans.getName();
if (transName.equals("Default") == false)
{
_source.print(_indent);
_source.print(
" protected internal virtual void ");
_source.print(transName);
_source.print("(");
_source.print(fsmClassName);
_source.print(" context");
for (SmcParameter param: trans.getParameters())
{
_source.print(", ");
param.accept(this);
}
_source.println(")");
_source.print(_indent);
_source.println(" {");
// If this method is reached, that means this
// transition was passed to a state which does
// not define the transition. Call the state's
// default transition method.
_source.print(_indent);
_source.println(" Default(context);");
_source.print(_indent);
_source.println(" }");
_source.println();
}
}
// Generate the overall Default transition for all maps.
_source.print(_indent);
_source.print(
" protected internal virtual void Default(");
_source.print(fsmClassName);
_source.println(" context)");
_source.print(_indent);
_source.println(" {");
// If generating debug code, then write this trace
// message.
if (_debugLevel >= DEBUG_LEVEL_0)
{
_source.println("#if TRACE");
_source.print(_indent);
_source.println(" Trace.WriteLine(");
_source.print(_indent);
_source.print(
" \"TRANSITION : Default\"");
_source.println(");");
_source.println("#endif");
}
// The default transition action is to throw a
// TransitionUndefinedException.
_source.print(_indent);
_source.println(" throw (");
_source.print(_indent);
_source.print(" ");
_source.println(
"new statemap.TransitionUndefinedException(");
_source.print(_indent);
_source.println(
" \"State: \" +");
_source.print(_indent);
_source.println(
" context.State.Name +");
_source.print(_indent);
_source.println(
" \", Transition: \" +");
_source.print(_indent);
_source.println(
" context.GetTransition()));");
// Close the Default transition method.
_source.print(_indent);
_source.println(" }");
// Close the inner state class declaration.
_source.print(_indent);
_source.println(" }");
// Have each map print out its source code now.
for (SmcMap map: maps)
{
map.accept(this);
}
// Close the context class.
_source.print(_indent);
_source.println("}");
_source.println();
// If a package has been specified, then generate
// the closing brace now.
if (packageName != null && packageName.length() > 0)
{
_source.println("}");
}
return;
} // end of visit(SmcFSM)
/**
* Emits C# code for the FSM map.
* @param map emit C# code for this map.
*/
public void visit(SmcMap map)
{
List<SmcTransition> definedDefaultTransitions;
SmcState defaultState = map.getDefaultState();
String context = map.getFSM().getContext();
String mapName = map.getName();
String indent2;
List<SmcState> states = map.getStates();
// Initialize the default transition list to all the
// default state's transitions.
if (defaultState != null)
{
definedDefaultTransitions =
defaultState.getTransitions();
}
else
{
definedDefaultTransitions =
new ArrayList<SmcTransition>();
}
// Declare the map class and make it abstract to prevent
// its instantiation.
_source.println();
_source.print(_indent);
_source.print(" internal abstract class ");
_source.println(mapName);
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(
" //-----------------------------------------------------------");
_source.print(_indent);
_source.println(" // Member methods.");
_source.print(_indent);
_source.println(" //");
_source.println();
_source.print(_indent);
_source.println(
" //-----------------------------------------------------------");
_source.print(_indent);
_source.println(" // Member data.");
_source.print(_indent);
_source.println(" //");
_source.println();
_source.print(_indent);
_source.println(
" //-------------------------------------------------------");
_source.print(_indent);
_source.println(" // Statics.");
_source.print(_indent);
_source.println(" //");
// Declare each of the state class member data.
for (SmcState state: states)
{
_source.print(_indent);
_source.println(" [NonSerialized]");
_source.print(_indent);
_source.print(
" internal static readonly ");
_source.print(mapName);
_source.print("_Default.");
_source.print(mapName);
_source.print('_');
_source.print(state.getClassName());
_source.print(' ');
_source.print(state.getInstanceName());
_source.println(" =");
_source.print(_indent);
_source.print(" new ");
_source.print(mapName);
_source.print("_Default.");
_source.print(mapName);
_source.print("_");
_source.print(state.getClassName());
_source.print("(\"");
_source.print(mapName);
_source.print(".");
_source.print(state.getClassName());
_source.print("\", ");
_source.print(map.getNextStateId());
_source.println(");");
}
// Create the default state as well.
_source.print(_indent);
_source.println(" [NonSerialized]");
_source.print(_indent);
_source.print(" private static readonly ");
_source.print(mapName);
_source.println("_Default Default =");
_source.print(_indent);
_source.print(" new ");
_source.print(mapName);
_source.print("_Default(\"");
_source.print(mapName);
_source.println(".Default\", -1);");
_source.println();
// End of map class.
_source.print(_indent);
_source.println(" }");
_source.println();
// Declare the map default state class.
_source.print(_indent);
_source.print(" internal class ");
_source.print(mapName);
_source.println("_Default :");
_source.print(_indent);
_source.print(" ");
_source.print(context);
_source.println("State");
_source.print(_indent);
_source.println(" {");
// If reflection is on, generate the Transition property.
if (_reflectFlag == true)
{
_source.print(_indent);
_source.println(
" //-----------------------------------------------------------");
_source.print(_indent);
_source.println(" // Properties.");
_source.print(_indent);
_source.println(" //");
_source.println();
_source.print(_indent);
_source.print(" ");
_source.print("public override IDictionary");
if (_genericFlag == true)
{
_source.print("<string, int>");
}
_source.println(" Transitions");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(" get");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(
" return (_transitions);");
_source.print(_indent);
_source.println(" }");
_source.print(_indent);
_source.println(" }");
_source.println();
}
// Generate the constructor.
_source.print(_indent);
_source.println(
" //-----------------------------------------------------------");
_source.print(_indent);
_source.println(" // Member methods.");
_source.print(_indent);
_source.println(" //");
_source.println();
_source.print(_indent);
_source.print(" internal ");
_source.print(mapName);
_source.println(
"_Default(string name, int id) :");
_source.print(_indent);
_source.println(" base (name, id)");
_source.print(_indent);
_source.println(" {}");
// Declare the user-defined transitions first.
indent2 = _indent;
_indent = _indent + " ";
for (SmcTransition trans: definedDefaultTransitions)
{
trans.accept(this);
}
_indent = indent2;
// Have each state now generate its code. Each state
// class is an inner class.
_source.println();
_source.print(_indent);
_source.println(
" //-----------------------------------------------------------");
_source.print(_indent);
_source.println(" // Inner classes.");
_source.print(_indent);
_source.println(" //");
for (SmcState state: states)
{
state.accept(this);
}
// If reflection is on, then define the transitions list.
if (_reflectFlag == true)
{
List<SmcTransition> allTransitions =
map.getFSM().getTransitions();
String transName;
List<SmcParameter> parameters;
int transDefinition;
_source.println();
_source.print(_indent);
_source.println(
" //-----------------------------------------------------------");
_source.print(_indent);
_source.println(" // Member data.");
_source.print(_indent);
_source.println(" //");
_source.println();
_source.print(_indent);
_source.println(
" //-------------------------------------------------------");
_source.print(_indent);
_source.println(" // Statics.");
_source.print(_indent);
_source.println(" //");
_source.print(_indent);
_source.print(" ");
_source.print("private static IDictionary");
if (_genericFlag == true)
{
_source.print("<string, int>");
}
_source.println(" _transitions;");
_source.println();
_source.print(_indent);
_source.print(" static ");
_source.print(mapName);
_source.println("_Default()");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.print(" ");
_source.print("_transitions = new ");
if (_genericFlag == true)
{
_source.print("Dictionary<string, int>");
}
else
{
_source.print("Hashtable");
}
_source.println("();");
// Now place the transition names into the list.
for (SmcTransition transition: allTransitions)
{
transName = transition.getName();
transName += "(";
parameters = transition.getParameters();
for ( int i = 0; i < parameters.size(); i++)
{
SmcParameter singleParam= parameters.get( i );
transName += singleParam.getType() + " " + singleParam.getName();
if ( i < parameters.size() - 1 )
{
transName += ", ";
}
}
transName += ")";
// If the transition is defined in this map's
// default state, then the value is 2.
if (definedDefaultTransitions.contains(
transition) == true)
{
transDefinition = 2;
}
// Otherwise the value is 0 - undefined.
else
{
transDefinition = 0;
}
_source.print(" ");
_source.print("_transitions.Add(\"");
_source.print(transName);
_source.print("\", ");
_source.print(transDefinition);
_source.println(");");
}
_source.print(_indent);
_source.println(" }");
}
// End of the map default state class.
_source.print(_indent);
_source.println(" }");
return;
} // end of visit(SmcMap)
/**
* Emits C# code for this FSM state.
* @param state emits C# code for this state.
*/
public void visit(SmcState state)
{
SmcMap map = state.getMap();
String context = map.getFSM().getContext();
String fsmClassName = map.getFSM().getFsmClassName();
String mapName = map.getName();
String stateName = state.getClassName();
List<SmcAction> actions;
String indent2;
// Declare the inner state class.
_source.println();
_source.print(_indent);
_source.print(" internal class ");
_source.print(mapName);
_source.print("_");
_source.print(stateName);
_source.println(" :");
_source.print(_indent);
_source.print(" ");
_source.print(mapName);
_source.println("_Default");
_source.print(_indent);
_source.println(" {");
// Generate the Transitions property if reflection is on.
if (_reflectFlag == true)
{
_source.print(_indent);
_source.println(
" //-------------------------------------------------------");
_source.print(_indent);
_source.println(" // Properties.");
_source.print(_indent);
_source.println(" //");
_source.println();
_source.print(_indent);
_source.print(" ");
_source.print("public override IDictionary");
if (_genericFlag == true)
{
_source.print("<string, int>");
}
_source.println(" Transitions");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(" get");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.println(
" return (_transitions);");
_source.print(_indent);
_source.println(" }");
_source.print(_indent);
_source.println(" }");
_source.println();
}
// Add the constructor.
_source.print(_indent);
_source.println(
" //-------------------------------------------------------");
_source.print(_indent);
_source.println(" // Member methods.");
_source.print(_indent);
_source.println(" //");
_source.println();
_source.print(_indent);
_source.print(" internal ");
_source.print(mapName);
_source.print("_");
_source.print(stateName);
_source.println("(string name, int id) :");
_source.print(_indent);
_source.println(" base (name, id)");
_source.print(_indent);
_source.println(" {}");
// Add the Entry() and Exit() methods if this state
// defines them.
actions = state.getEntryActions();
if (actions != null && actions.isEmpty() == false)
{
_source.println();
_source.print(_indent);
_source.print(" ");
_source.print(
"protected internal override void Entry(");
_source.print(fsmClassName);
_source.println(" context)");
_source.print(_indent);
_source.println(" {");
// Declare the "ctxt" local variable.
_source.print(_indent);
_source.print(" ");
_source.print(context);
_source.println(" ctxt = context.Owner;");
_source.println();
// Generate the actions associated with this code.
indent2 = _indent;
_indent = _indent + " ";
for (SmcAction action: actions)
{
action.accept(this);
}
_indent = indent2;
// End of the Entry() method.
_source.print(_indent);
_source.println(" return;");
_source.print(_indent);
_source.println(" }");
}
actions = state.getExitActions();
if (actions != null && actions.isEmpty() == false)
{
_source.println();
_source.print(_indent);
_source.print(" ");
_source.print(
"protected internal override void Exit(");
_source.print(fsmClassName);
_source.println(" context)");
_source.print(_indent);
_source.println(" {");
// Declare the "ctxt" local variable.
_source.print(_indent);
_source.print(" ");
_source.print(context);
_source.println(" ctxt = context.Owner;");
_source.println();
// Generate the actions associated with this code.
indent2 = _indent;
_indent = _indent + " ";
for (SmcAction action: actions)
{
action.accept(this);
}
// End of the Exit() method.
_source.print(_indent);
_source.println(" return;");
_source.print(_indent);
_source.println(" }");
}
// Have each transition generate its code.
indent2 = _indent;
_indent = _indent + " ";
for (SmcTransition trans: state.getTransitions())
{
trans.accept(this);
}
_indent = indent2;
// If reflection is on, then generate the transitions
// map.
if (_reflectFlag == true)
{
List<SmcTransition> allTransitions =
map.getFSM().getTransitions();
List<SmcTransition> stateTransitions =
state.getTransitions();
SmcState defaultState = map.getDefaultState();
List<SmcTransition> defaultTransitions;
String transName;
List<SmcParameter> parameters;
int transDefinition;
// Initialize the default transition list to all the
// default state's transitions.
if (defaultState != null)
{
defaultTransitions =
defaultState.getTransitions();
}
else
{
defaultTransitions =
new ArrayList<SmcTransition>();
}
_source.println();
_source.print(_indent);
_source.println(
" //-------------------------------------------------------");
_source.print(_indent);
_source.println(" // Member data.");
_source.print(_indent);
_source.println(" //");
_source.println();
_source.print(_indent);
_source.println(
" //---------------------------------------------------");
_source.print(_indent);
_source.println(" // Statics.");
_source.print(_indent);
_source.println(" //");
_source.print(_indent);
_source.print(" ");
_source.print("new private static IDictionary");
if (_genericFlag == true)
{
_source.print("<string, int>");
}
_source.println(" _transitions;");
_source.println();
_source.print(_indent);
_source.print(" static ");
_source.print(mapName);
_source.print("_");
_source.print(stateName);
_source.println("()");
_source.print(_indent);
_source.println(" {");
_source.print(_indent);
_source.print(" ");
_source.print("_transitions = new ");
if (_genericFlag == true)
{
_source.print("Dictionary<string, int>");
}
else
{
_source.print("Hashtable");
}
_source.println("();");
// Now place the transition names into the list.
for (SmcTransition transition: allTransitions)
{
transName = transition.getName();
transName += "(";
parameters = transition.getParameters();
for ( int i = 0; i < parameters.size(); i++)
{
SmcParameter singleParam= parameters.get( i );
transName += singleParam.getType() + " " + singleParam.getName();
if ( i < parameters.size() - 1 )
{
transName += ", ";
}
}
transName += ")";
// If the transition is in this state, then its
// value is 1.
if (stateTransitions.contains(
transition) == true)
{
transDefinition = 1;
}
// If the transition is defined in this map's
// default state, then the value is 2.
else if (defaultTransitions.contains(
transition) == true)
{
transDefinition = 2;
}
// Otherwise the value is 0 - undefined.
else
{
transDefinition = 0;
}
_source.print(" ");
_source.print("_transitions.Add(\"");
_source.print(transName);
_source.print("\", ");
_source.print(transDefinition);
_source.println(");");
}
_source.print(_indent);
_source.println(" }");
}
// End of state declaration.
_source.print(_indent);
_source.println(" }");
return;
} // end of visit(SmcState)
/**
* Emits C# code for this FSM state transition.
* @param transition emits C# code for this state transition.
*/
public void visit(SmcTransition transition)
{
SmcState state = transition.getState();
SmcMap map = state.getMap();
String context = map.getFSM().getContext();
String fsmClassName = map.getFSM().getFsmClassName();
String mapName = map.getName();
String stateName = state.getClassName();
String transName = transition.getName();
List<SmcParameter> parameters =
transition.getParameters();
List<SmcGuard> guards = transition.getGuards();
boolean nullCondition = false;
Iterator<SmcGuard> git;
SmcGuard guard;
_source.println();
_source.print(_indent);
_source.print("protected internal override void ");
_source.print(transName);
_source.print("(");
_source.print(fsmClassName);
_source.print(" context");
// Add user-defined parameters.
for (SmcParameter param: parameters)
{
_source.print(", ");
param.accept(this);
}
_source.println(")");
_source.print(_indent);
_source.println("{");
// Almost all transitions have a "ctxt" local variable.
if (transition.hasCtxtReference() == true)
{
_source.println();
_source.print(_indent);
_source.print(" ");
_source.print(context);
_source.println(" ctxt = context.Owner;");
_source.println();
}
// Output transition to debug stream.
if (_debugLevel >= DEBUG_LEVEL_0)
{
_source.println();
_source.println("#if TRACE");
_source.print(_indent);
_source.println(" Trace.WriteLine(");
_source.print(_indent);
_source.print(" \"LEAVING STATE : ");
_source.print(mapName);
_source.print('.');
_source.print(stateName);
_source.println("\");");
_source.println("#endif");
_source.println();
}
// Loop through the guards and print each one.
_guardIndex = 0;
_guardCount = guards.size();
for (git = guards.iterator();
git.hasNext() == true;
++_guardIndex)
{
guard = git.next();
// Count up the guards with no condition.
if (guard.getCondition().length() == 0)
{
nullCondition = true;
}
guard.accept(this);
}
// If all guards have a condition, then create a final
// "else" clause which passes control to the default
// transition. Pass all arguments into the default
// transition.
if (_guardIndex > 0 && nullCondition == false)
{
// If there was only one guard, then we need to close
// of its body.
if (_guardCount == 1)
{
_source.print(_indent);
_source.println("}");
}
_source.print(_indent);
_source.print(" else");
_source.print(_indent);
_source.println(" {");
// Call the super class' transition method using
// the "base" keyword and not the class name.
_source.print(_indent);
_source.print(" base.");
_source.print(transName);
_source.print("(context");
for (SmcParameter param: parameters)
{
_source.print(", ");
passParameter(param);
}
_source.println(");");
_source.print(_indent);
_source.println(" }");
_source.println();
}
// Need to add a final newline after a multiguard block.
else if (_guardCount > 1)
{
_source.println();
_source.println();
}
// End of transition.
_source.print(_indent);
_source.println(" return;");
_source.print(_indent);
_source.println("}");
return;
} // end of visit(SmcTransition)
/**
* Emits C# code for this FSM transition guard.
* @param guard emits C# code for this transition guard.
*/
public void visit(SmcGuard guard)
{
SmcTransition transition = guard.getTransition();
SmcState state = transition.getState();
SmcMap map = state.getMap();
String context = map.getFSM().getContext();
String mapName = map.getName();
String stateName = state.getClassName();
String transName = transition.getName();
TransType transType = guard.getTransType();
boolean loopbackFlag = false;
String indent2;
String indent3;
String indent4;
String endStateName = guard.getEndState();
String fqEndStateName = "";
String pushStateName = guard.getPushState();
String condition = guard.getCondition();
List<SmcAction> actions = guard.getActions();
boolean hasActions = !(actions.isEmpty());
// If this guard's end state is not of the form
// "map::state", then prepend the map name to the
// state name.
// DON'T DO THIS IF THIS IS A POP TRANSITION!
// The "state" is actually a transition name.
if (transType != TransType.TRANS_POP &&
endStateName.length () > 0 &&
endStateName.equals(SmcElement.NIL_STATE) == false)
{
endStateName = scopeStateName(endStateName, mapName);
}
// Qualify the state and push state names as well.
stateName = scopeStateName(stateName, mapName);
pushStateName = scopeStateName(pushStateName, mapName);
// Is this an *internal* loopback?
loopbackFlag = isLoopback(transType, endStateName);
// The guard code generation is a bit tricky. The first
// question is how many guards are there? If there are
// more than one, then we will need to generate the
// proper "if-then-else" code.
if (_guardCount > 1)
{
indent2 = _indent + " ";
// There are multiple guards.
// Is this the first guard?
if (_guardIndex == 0 && condition.length() > 0)
{
// Yes, this is the first. This means an "if"
// should be used.
_source.print(_indent);
_source.print(" if (");
_source.print(condition);
_source.println(")");
_source.print(_indent);
_source.println(" {");
}
else if (condition.length() > 0)
{
// No, this is not the first transition but it
// does have a condition. Use an "else if".
_source.println();
_source.print(_indent);
_source.print(" else if (");
_source.print(condition);
_source.println(")");
_source.print(_indent);
_source.println(" {");
}
else
{
// This is not the first transition and it has
// no condition.
_source.println();
_source.print(_indent);
_source.println(" else");
_source.print(_indent);
_source.println(" {");
}
}
// There is only one guard. Does this guard have
// a condition?
else if (condition.length() == 0)
{
// No. This is a plain, old. vanilla transition.
indent2 = _indent + " ";
}
else
{
// Yes there is a condition.
indent2 = _indent + " ";
_source.print(_indent);
_source.print(" if (");
_source.print(condition);
_source.println(")");
_source.print(_indent);
_source.println(" {");
}
// Now that the necessary conditions are in place, it's
// time to dump out the transition's actions. First, do
// the proper handling of the state change. If this
// transition has no actions, then set the end state
// immediately. Otherwise, unset the current state so
// that if an action tries to issue a transition, it will
// fail.
if (hasActions == false && endStateName.length() != 0)
{
fqEndStateName = endStateName;
}
else if (hasActions == true)
{
// Save away the current state if this is a loopback
// transition. Storing current state allows the
// current state to be cleared before any actions are
// executed. Remember: actions are not allowed to
// issue transitions and clearing the current state
// prevents them from doing do.
if (loopbackFlag == true)
{
fqEndStateName = "endState";
_source.print(indent2);
_source.print(context);
_source.print("State ");
_source.print(fqEndStateName);
_source.println(" = context.State;");
}
else
{
fqEndStateName = endStateName;
}
}
_source.println();
// Dump out the exit actions if
// 1) this is a standard, non-loopback transition or
// 2) a pop transition.
if (transType == TransType.TRANS_POP ||
loopbackFlag == false)
{
if (_debugLevel >= DEBUG_LEVEL_1)
{
_source.println("#if TRACE");
_source.print(indent2);
_source.println("Trace.WriteLine(");
_source.print(indent2);
_source.print(" \"BEFORE EXIT : ");
_source.print(stateName);
_source.println(".Exit(context)\");");
_source.println("#endif");
_source.println();
}
_source.print(indent2);
_source.println("context.State.Exit(context);");
if (_debugLevel >= DEBUG_LEVEL_1)
{
_source.println("#if TRACE");
_source.print(indent2);
_source.println("Trace.WriteLine(");
_source.print(indent2);
_source.print(" \"AFTER EXIT : ");
_source.print(stateName);
_source.println(".Exit(context)\");");
_source.println("#endif");
_source.println();
}
}
if (_debugLevel >= DEBUG_LEVEL_0)
{
List<SmcParameter> parameters =
transition.getParameters();
_source.println("#if TRACE");
_source.print(indent2);
_source.println("Trace.WriteLine(");
_source.print(indent2);
_source.print(" \"ENTER TRANSITION: ");
_source.print(mapName);
_source.print('.');
_source.print(stateName);
_source.print(".");
_source.print(transName);
// Output the transition parameters.
_source.print("(");
for (SmcParameter param: parameters)
{
_source.print(", ");
param.accept(this);
}
_source.print(")");
_source.println("\");");
_source.println("#endif");
_source.println();
}
// Dump out this transition's actions.
if (hasActions == false)
{
if (condition.length() > 0)
{
_source.print(indent2);
_source.println("// No actions.");
}
indent3 = indent2;
}
else
{
// Now that we are in the transition, clear the
// current state.
_source.print(indent2);
_source.println("context.ClearState();");
// v. 2.0.0: Place the actions inside a try/finally
// block. This way the state will be set before an
// exception leaves the transition method.
// v. 2.2.0: Check if the user has turned off this
// feature first.
if (_noCatchFlag == false)
{
_source.println();
_source.print(indent2);
_source.println("try");
_source.print(indent2);
_source.println("{");
indent3 = indent2 + " ";
}
else
{
indent3 = indent2;
}
indent4 = _indent;
_indent = indent3;
for (SmcAction action: actions)
{
action.accept(this);
}
_indent = indent4;
// v. 2.2.0: Check if the user has turned off this
// feature first.
if (_noCatchFlag == false)
{
_source.print(indent2);
_source.println("}");
_source.print(indent2);
_source.println("finally");
_source.print(indent2);
_source.println("{");
}
}
if (_debugLevel >= DEBUG_LEVEL_0)
{
List<SmcParameter> parameters =
transition.getParameters();
_source.println("#if TRACE");
_source.print(indent3);
_source.println("Trace.WriteLine(");
_source.print(indent3);
_source.print(" \"EXIT TRANSITION : ");
_source.print(mapName);
_source.print('.');
_source.print(stateName);
_source.print(".");
_source.print(transName);
// Output the transition parameters.
_source.print("(");
for (SmcParameter param: parameters)
{
_source.print(", ");
param.accept(this);
}
_source.print(")");
_source.println("\");");
_source.println("#endif");
_source.println();
}
// Print the state assignment if necessary. Do NOT
// generate the state assignment if:
// 1. The transition has no actions AND is a loopback OR
// 2. This is a push or pop transition.
if (transType == TransType.TRANS_SET &&
(hasActions == true || loopbackFlag == false))
{
_source.print(indent3);
_source.print("context.State = ");
_source.print(fqEndStateName);
_source.println(";");
}
else if (transType == TransType.TRANS_PUSH)
{
// Set the next state so this it can be pushed
// onto the state stack. But only do so if a clear
// state was done.
// v. 4.3.0: If the full-qualified end state is
// "nil", then don't need to do anything.
if ((loopbackFlag == false || hasActions == true) &&
fqEndStateName.equals(SmcElement.NIL_STATE) == false)
{
_source.print(indent3);
_source.print("context.State = ");
_source.print(fqEndStateName);
_source.println(";");
}
// Before doing the push, execute the end state's
// entry actions (if any) if this is not a loopback.
if (loopbackFlag == false)
{
if (_debugLevel >= DEBUG_LEVEL_1)
{
_source.println("#if TRACE");
_source.print(indent3);
_source.println("Trace.WriteLine(");
_source.print(indent3);
_source.print(" \"BEFORE ENTRY : ");
_source.print(mapName);
_source.print('.');
_source.print(stateName);
_source.println(".Exit(context)\");");
_source.println("#endif");
_source.println();
}
_source.print(indent3);
_source.println("context.State.Entry(context);");
if (_debugLevel >= DEBUG_LEVEL_1)
{
_source.println("#if TRACE");
_source.print(indent3);
_source.println("Trace.WriteLine(");
_source.print(indent3);
_source.print(" \"AFTER ENTRY : ");
_source.print(mapName);
_source.print('.');
_source.print(stateName);
_source.println(".Exit(context)\");");
_source.println("#endif");
_source.println();
}
}
_source.print(indent3);
_source.print("context.PushState(");
_source.print(pushStateName);
_source.println(");");
}
else if (transType == TransType.TRANS_POP)
{
_source.print(indent3);
_source.println("context.PopState();");
}
// Perform the new state's enty actions if:
// 1) this is a standard, non-loopback transition or
// 2) a push transition.
if ((transType == TransType.TRANS_SET &&
loopbackFlag == false) ||
transType == TransType.TRANS_PUSH)
{
if (_debugLevel >= DEBUG_LEVEL_1)
{
_source.println("#if TRACE");
_source.print(indent3);
_source.println("Trace.WriteLine(");
_source.print(indent3);
_source.print(" \"BEFORE ENTRY : ");
_source.print(mapName);
_source.print('.');
_source.print(fqEndStateName);
_source.println(".Exit(context)\");");
_source.println("#endif");
_source.println();
}
_source.print(indent3);
_source.println("context.State.Entry(context);");
if (_debugLevel >= DEBUG_LEVEL_1)
{
_source.println("#if TRACE");
_source.print(indent3);
_source.println("Trace.WriteLine(");
_source.print(indent3);
_source.print(" \"AFTER ENTRY : ");
_source.print(mapName);
_source.print('.');
_source.print(fqEndStateName);
_source.println(".Exit(context)\");");
_source.println("#endif");
_source.println();
}
}
// If there was a try/finally, then put the closing
// brace on the finally block.
// v. 2.2.0: Check if the user has turned off this
// feature first.
if (hasActions == true && _noCatchFlag == false)
{
_source.print(indent2);
_source.println("}");
_source.println();
}
// If there is a transition associated with the pop, then
// issue that transition here.
if (transType == TransType.TRANS_POP &&
endStateName.equals(SmcElement.NIL_STATE) == false &&
endStateName.length() > 0)
{
String popArgs = guard.getPopArgs();
_source.println();
_source.print(indent2);
_source.print("context.");
_source.print(endStateName);
_source.print("(");
// Output any and all pop arguments.
if (popArgs.length() > 0)
{
_source.print(popArgs);
}
_source.println(");");
}
// If this is a guarded transition, it will be necessary
// to close off the "if" body. DON'T PRINT A NEW LINE!
// Why? Because an "else" or "else if" may follow and we
// won't know until we go back to the transition source
// generator whether all clauses have been done.
if (_guardCount > 1)
{
_source.print(_indent);
_source.print(" }");
}
return;
} // end of visit(SmcGuard)
/**
* Emits C# code for this FSM action.
* @param action emits C# code for this action.
*/
public void visit(SmcAction action)
{
String name = action.getName();
List<String> arguments = action.getArguments();
Iterator<String> it;
String sep;
_source.print(_indent);
// Need to distinguish between FSMContext actions and
// application class actions. If the action is
// "emptyStateStack", then pass it to the context.
// Otherwise, let the application class handle it.
if ( action.isEmptyStateStack() == true)
{
_source.println("context.EmptyStateStack();");
}
else
{
if ( action.isStatic() == false )
{
_source.print("ctxt.");
}
_source.print(name);
if (action.isProperty() == true)
{
String arg = arguments.get(0);
_source.print(" = ");
_source.print(arg);
_source.println(";");
}
else
{
_source.print("(");
for (it = arguments.iterator(), sep = "";
it.hasNext() == true;
sep = ", ")
{
_source.print(sep);
_source.print(it.next());
}
_source.println(");");
}
}
return;
} // end of visit(SmcAction)
/**
* Emits C# code for this transition parameter.
* @param parameter emits C# code for this transition parameter.
*/
public void visit(SmcParameter parameter)
{
_source.print(parameter.getType());
_source.print(" ");
_source.print(parameter.getName());
return;
} // end of visit(SmcParameter)
/**
* Emits C# code for passing the transition parameter to another method.
*/
private void passParameter(SmcParameter param)
{
String paramType=param.getType().trim();
if ( paramType.startsWith( "ref " ) )
{
_source.print( "ref ");
} else if (paramType.startsWith( "out " ) )
{
_source.print( "out ");
}
_source.print(param.getName());
}
//
// end of SmcVisitor Abstract Method Impelementation.
//-----------------------------------------------------------
//---------------------------------------------------------------
// Member data
//
} // end of class SmcCSharpGenerator
//
// CHANGE LOG
// $Log: SmcCSharpGenerator.java,v $
// Revision 1.12 2011/11/20 14:58:33 cwrapp
// Check in for SMC v. 6.1.0
//
// Revision 1.11 2009/12/17 19:51:43 cwrapp
// Testing complete.
//
// Revision 1.10 2009/11/25 22:30:19 cwrapp
// Fixed problem between %fsmclass and sm file names.
//
// Revision 1.9 2009/11/25 15:09:45 cwrapp
// Corrected getStates.
//
// Revision 1.8 2009/11/24 20:42:39 cwrapp
// v. 6.0.1 update
//
// Revision 1.7 2009/10/06 15:31:59 kgreg99
// 1. Started implementation of feature request #2718920.
// 1.1 Added method boolean isStatic() to SmcAction class. It returns false now, but is handled in following language generators: C#, C++, java, php, VB. Instance identificator is not added in case it is set to true.
// 2. Resolved confusion in "emtyStateStack" keyword handling. This keyword was not handled in the same way in all the generators. I added method boolean isEmptyStateStack() to SmcAction class. This method is used instead of different string comparisons here and there. Also the generated method name is fixed, not to depend on name supplied in the input sm file.
//
// Revision 1.6 2009/10/05 13:54:45 kgreg99
// Feature request #2865719 implemented.
// Added method "passParameter" to SmcCSharpGenerator class. It shall be used to generate C# code if a transaction parameter shall be passed to another method. It preserves "ref" and "out" modifiers.
//
// Revision 1.5 2009/09/12 21:44:49 kgreg99
// Implemented feature req. #2718941 - user defined generated class name.
// A new statement was added to the syntax: %fsmclass class_name
// It is optional. If not used, generated class is called as before "XxxContext" where Xxx is context class name as entered via %class statement.
// If used, generated class is called asrequested.
// Following language generators are touched:
// c, c++, java, c#, objc, lua, groovy, scala, tcl, VB
// This feature is not tested yet !
// Maybe it will be necessary to modify also the output file name.
//
// Revision 1.4 2009/09/05 15:39:20 cwrapp
// Checking in fixes for 1944542, 1983929, 2731415, 2803547 and feature 2797126.
//
// Revision 1.3 2009/03/30 21:23:47 kgreg99
// 1. Patch for bug #2679204. Source code was compared to SmcJavaGenerator. At the end of function Visit(SmcGuard ... ) the condition to emit Entry() code was changed. Notice: there are other disimilarities in checking conditions in that function !
//
// Revision 1.2 2009/03/03 17:28:53 kgreg99
// 1. Bugs resolved:
// #2657779 - modified SmcParser.sm and SmcParserContext.java
// #2648516 - modified SmcCSharpGenerator.java
// #2648472 - modified SmcSyntaxChecker.java
// #2648469 - modified SmcMap.java
//
// Revision 1.1 2009/03/01 18:20:42 cwrapp
// Preliminary v. 6.0.0 commit.
//
// Revision 1.12 2008/03/21 14:03:16 fperrad
// refactor : move from the main file Smc.java to each language generator the following data :
// - the default file name suffix,
// - the file name format for the generated SMC files
//
// Revision 1.11 2008/01/14 19:59:23 cwrapp
// Release 5.0.2 check-in.
//
// Revision 1.10 2007/02/21 13:54:15 cwrapp
// Moved Java code to release 1.5.0
//
// Revision 1.9 2007/01/15 00:23:50 cwrapp
// Release 4.4.0 initial commit.
//
// Revision 1.8 2006/09/16 15:04:28 cwrapp
// Initial v. 4.3.3 check-in.
//
// Revision 1.7 2006/06/03 19:39:25 cwrapp
// Final v. 4.3.1 check in.
//
// Revision 1.6 2005/11/07 19:34:54 cwrapp
// Changes in release 4.3.0:
// New features:
//
// + Added -reflect option for Java, C#, VB.Net and Tcl code
// generation. When used, allows applications to query a state
// about its supported transitions. Returns a list of transition
// names. This feature is useful to GUI developers who want to
// enable/disable features based on the current state. See
// Programmer's Manual section 11: On Reflection for more
// information.
//
// + Updated LICENSE.txt with a missing final paragraph which allows
// MPL 1.1 covered code to work with the GNU GPL.
//
// + Added a Maven plug-in and an ant task to a new tools directory.
// Added Eiten Suez's SMC tutorial (in PDF) to a new docs
// directory.
//
// Fixed the following bugs:
//
// + (GraphViz) DOT file generation did not properly escape
// double quotes appearing in transition guards. This has been
// corrected.
//
// + A note: the SMC FAQ incorrectly stated that C/C++ generated
// code is thread safe. This is wrong. C/C++ generated is
// certainly *not* thread safe. Multi-threaded C/C++ applications
// are required to synchronize access to the FSM to allow for
// correct performance.
//
// + (Java) The generated getState() method is now public.
//
// Revision 1.5 2005/09/19 15:20:03 cwrapp
// Changes in release 4.2.2:
// New features:
//
// None.
//
// Fixed the following bugs:
//
// + (C#) -csharp not generating finally block closing brace.
//
// Revision 1.4 2005/09/14 01:51:33 cwrapp
// Changes in release 4.2.0:
// New features:
//
// None.
//
// Fixed the following bugs:
//
// + (Java) -java broken due to an untested minor change.
//
// Revision 1.3 2005/08/26 15:21:34 cwrapp
// Final commit for release 4.2.0. See README.txt for more information.
//
// Revision 1.2 2005/06/30 10:44:23 cwrapp
// Added %access keyword which allows developers to set the generate Context
// class' accessibility level in Java and C#.
//
// Revision 1.1 2005/05/28 19:28:42 cwrapp
// Moved to visitor pattern.
//
// Revision 1.2 2005/02/21 15:34:38 charlesr
// Added Francois Perrad to Contributors section for Python work.
//
// Revision 1.1 2005/02/21 15:10:36 charlesr
// Modified isLoopback() to new signature.
//
// Revision 1.0 2005/02/03 17:10:08 charlesr
// Initial revision
//
|
Java
|
UTF-8
| 2,458 | 2.40625 | 2 |
[
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"CDDL-1.0",
"CDDL-1.1",
"ANTLR-PD",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unicode",
"CPL-1.0",
"GPL-2.0-only",
"Classpath-exception-2.0",
"CC-BY-SA-3.0",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"NAIST-2003"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.solr.util;
import java.lang.invoke.MethodHandles;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Simple utilities for working Hostname/IP Addresses */
public final class AddressUtils {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
// normalize host removing any url scheme.
// input can be null, host, or url_prefix://host
public static String getHostToAdvertise() {
String hostaddress;
try {
hostaddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
hostaddress =
InetAddress.getLoopbackAddress()
.getHostAddress(); // cannot resolve system hostname, fall through
}
// Re-get the IP again for "127.0.0.1", the other case we trust the hosts
// file is right.
if ("127.0.0.1".equals(hostaddress)) {
try {
var netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
InetAddress ip = ips.nextElement();
if (ip.isSiteLocalAddress()) {
hostaddress = ip.getHostAddress();
}
}
}
} catch (Exception e) {
log.error("Error while looking for a better host name than 127.0.0.1", e);
}
}
return hostaddress;
}
}
|
Python
|
UTF-8
| 871 | 3.015625 | 3 |
[] |
no_license
|
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
result_str = ""
for char in str:
if ord(char) in range(48,58) :
result_str+=char
elif result_str=="" and (ord(char) == 45 or ord(char) == 43):
result_str+=char
elif result_str=="" and ord(char)==32:
continue
else:
break
# print result_str
if result_str=="" or result_str=="-" or result_str=="+":
return 0
else:
result = int(result_str)
if result > 2**31-1:
return 2**31-1
elif result < -2**31:
return -2**31
else:
return result
|
Java
|
UTF-8
| 8,568 | 1.757813 | 2 |
[
"MIT"
] |
permissive
|
/*******************************************************************************
* The MIT License
*
* Copyright (c) 2019 knokko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
package nl.knokko.story.npc;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import nl.knokko.area.Area;
import nl.knokko.area.creature.AreaCreature;
import nl.knokko.areas.AreaRargia;
import nl.knokko.inventory.trading.ItemStack;
import nl.knokko.inventory.trading.TradeOffer;
import nl.knokko.inventory.trading.TradeOffers;
import nl.knokko.items.Items;
import nl.knokko.main.Game;
import nl.knokko.model.body.BodyHuman;
import nl.knokko.util.bits.BitInput;
import nl.knokko.util.bits.BitOutput;
import nl.knokko.util.color.Color;
import nl.knokko.util.position.SpawnPosition;
import nl.knokko.util.resources.Saver;
public class NPCManager {
private final LazyTrollTraderNPC rargiaBoneSmith = new LazyTrollTraderNPC(AreaRargia.BoneSmith.class, 5, 4, 6, new TradeOffers(
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 5), new ItemStack(Items.POG_SKIN, 10)}, new ItemStack(Items.POG_SHOE)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 5), new ItemStack(Items.POG_SKIN, 20)}, new ItemStack(Items.POG_PANTS)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 5), new ItemStack(Items.POG_SKIN, 30)}, new ItemStack(Items.POG_SHIRT)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 5), new ItemStack(Items.POG_SKIN, 15)}, new ItemStack(Items.POG_GLOBE)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 5), new ItemStack(Items.POG_SKIN, 10)}, new ItemStack(Items.POG_CAP))
));
private final LazyTrollTraderNPC rargiaFarmer = new LazyTrollTraderNPC(AreaRargia.Farmer.class, 5, 4, 6, new TradeOffers(
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 10)}, new ItemStack(Items.POG_BONE)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 2)}, new ItemStack(Items.POG_SKIN)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 25)}, new ItemStack(Items.POG_SHOE)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 45)}, new ItemStack(Items.POG_PANTS)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 65)}, new ItemStack(Items.POG_SHIRT)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 25)}, new ItemStack(Items.POG_GLOBE)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 25)}, new ItemStack(Items.POG_CAP))
));
private final LazyTrollTraderNPC rargiaBlackSmith = new LazyTrollTraderNPC(AreaRargia.BlackSmith.class, 6, 0, 6, new TradeOffers(
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 200)}, new ItemStack(Items.CRYT_HELMET)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 600)}, new ItemStack(Items.CRYT_CHESTPLATE)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 400)}, new ItemStack(Items.CRYT_LEGGINGS)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 200)}, new ItemStack(Items.CRYT_SHOE)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 20)}, new ItemStack(Items.SORG_SPEAR)),
new TradeOffer(new ItemStack[]{new ItemStack(Items.CRYT_PIECE, 60)}, new ItemStack(Items.CRYT_SPEAR))
));
private final LazyTrollTraderNPC rargiaFarmacy = new LazyTrollTraderNPC(AreaRargia.Farmacy.class, 6, 0, 6, new TradeOffers());
private final NPCMyrmora.Intro introMyrmora = new NPCMyrmora.Intro();
private final Random introRandom = new Random(28372837L);
private final IntroHumanNPC introWarrior1 = new IntroHumanNPC(new SpawnPosition(46,13,45), BodyHuman.Models.createSimpleInstance(introRandom, 0.05f), BodyHuman.Textures.createBlanc(new Color(30, 20, 10)), Items.IRON_SWORD);
private final IntroHumanNPC introWarrior2 = new IntroHumanNPC(new SpawnPosition(47,13,46), BodyHuman.Models.createSimpleInstance(introRandom, 0.05f), BodyHuman.Textures.createBrown(new Color(10, 20, 10)), Items.IRON_SPEAR);
private final IntroHumanNPC introWarrior3 = new IntroHumanNPC(new SpawnPosition(48,13,46), BodyHuman.Models.createSimpleInstance(introRandom, 0.05f), BodyHuman.Textures.createBlanc(new Color(250, 250, 75)), Items.IRON_SWORD);
private final IntroHumanNPC introPaladin = new IntroHumanNPC(new SpawnPosition(49,13,44), BodyHuman.Models.createSimpleInstance(introRandom, 0f), BodyHuman.Textures.createBlanc(new Color(230, 250, 220)), Items.BLESSED_IRON_SWORD);
private final IntroHumanNPC introWarrior4 = new IntroHumanNPC(new SpawnPosition(50,13,46), BodyHuman.Models.createSimpleInstance(introRandom, 0.05f), BodyHuman.Textures.createBrown(new Color(100, 70, 0)), Items.IRON_SWORD);
private final IntroTheresa introTheresa = new IntroTheresa(BodyHuman.Models.createSimpleInstance(introRandom, 0.05f), BodyHuman.Textures.createBlanc(new Color(250, 250, 75)));
private final IntroHumanNPC introWarrior6 = new IntroHumanNPC(new SpawnPosition(52,13,45), BodyHuman.Models.createSimpleInstance(introRandom, 0.05f), BodyHuman.Textures.createBlanc(new Color(30, 20, 10)), Items.IRON_SWORD);
private final NPC[] npcs = {
rargiaBoneSmith, rargiaFarmer, rargiaBlackSmith, rargiaFarmacy,
introMyrmora, introWarrior1, introWarrior2, introWarrior3, introPaladin, introWarrior4, introTheresa, introWarrior6
};
private final Map<Class<?>,List<NPC>> areaMap = new TreeMap<Class<?>,List<NPC>>(new Comparator<Class<?>>(){
@Override
public int compare(Class<?> o1, Class<?> o2) {
return o1.getName().compareTo(o2.getName());
}
});
public NPCManager(){
for(NPC npc : npcs){
Class<?>[] areas = npc.getPossibleAreas();
for(Class<?> area : areas){
List<NPC> list = areaMap.get(area);
if(list == null){
list = new ArrayList<NPC>();
areaMap.put(area, list);
}
list.add(npc);
}
}
}
public void save(){
BitOutput buffer = Saver.save("npcs.data", 1000);
//BitBuffer buffer = new BitBuffer(1000);
buffer.addInt(npcs.length);
for(NPC npc : npcs)
npc.save(buffer);
//Saver.save(buffer, "npcs.data");
}
public void load(){
BitInput buffer = Saver.load("npcs.data");
int amount = buffer.readInt();
if(amount != npcs.length)
System.out.println("The loaded save file had less npc's.");
int index;
for(index = 0; index < amount; index++)
npcs[index].load(buffer);
for(; index < npcs.length; index++)
npcs[index].initFirstGame();
}
public void initFirstGame(){
for(NPC npc : npcs)
npc.initFirstGame();
}
public void processArea(Area area){
List<NPC> npcs = areaMap.get(area.getClass());
if(npcs != null){
for(NPC npc : npcs){
AreaCreature creature = npc.createRepresentation(area);
if(creature != null)
area.spawnCreature(creature);
}
}
}
public void refresh(){
processArea(Game.getArea().getArea());
}
public IntroHumanNPC getIntroWarrior1(){
return introWarrior1;
}
public IntroHumanNPC getIntroWarrior2(){
return introWarrior2;
}
public IntroHumanNPC getIntroWarrior3(){
return introWarrior3;
}
public IntroHumanNPC getIntroWarrior4(){
return introWarrior4;
}
public IntroTheresa getIntroTheresa(){
return introTheresa;
}
public IntroHumanNPC getIntroWarrior6(){
return introWarrior6;
}
public IntroHumanNPC getIntroPaladin(){
return introPaladin;
}
}
|
Python
|
UTF-8
| 1,693 | 3.546875 | 4 |
[
"MIT"
] |
permissive
|
from collections import deque
def have_enough_firework_punches(fireworks):
return all([value >= 3 for value in fireworks.values()])
firework_effects = deque(list(map(int, input().split(', '))))
explosive_power = list(map(int, input().split(', ')))
fireworks = {
'Palm Fireworks': 0,
'Willow Fireworks': 0,
'Crossette Fireworks': 0,
}
while firework_effects and explosive_power:
if firework_effects[0] <= 0:
firework_effects.popleft()
continue
if explosive_power[-1] <= 0:
explosive_power.pop()
continue
values_sum = firework_effects[0] + explosive_power[-1]
if values_sum % 3 == 0 and not values_sum % 5 == 0:
fireworks['Palm Fireworks'] += 1
firework_effects.popleft()
explosive_power.pop()
elif values_sum % 5 == 0 and not values_sum % 3 == 0:
fireworks['Willow Fireworks'] += 1
firework_effects.popleft()
explosive_power.pop()
elif values_sum % 3 == 0 and values_sum % 5 == 0:
fireworks['Crossette Fireworks'] += 1
firework_effects.popleft()
explosive_power.pop()
else:
firework_effects[0] -= 1
firework_effects.append(firework_effects.popleft())
if have_enough_firework_punches(fireworks):
print('Congrats! You made the perfect firework show!')
break
else:
print('Sorry. You can’t make the perfect firework show.')
if firework_effects:
print(f'Firework Effects left: {", ".join(map(str, firework_effects))}')
if explosive_power:
print(f'Explosive Power left: {", ".join(map(str, explosive_power))}')
for firework, count in fireworks.items():
print(f'{firework}: {count}')
|
Java
|
UTF-8
| 1,510 | 2.359375 | 2 |
[] |
no_license
|
package usonsonate.com.tukybirth.SQLite;
import java.io.Serializable;
public class DetalleCiclo implements Serializable {
private String id_detalle = "";
private String id_ciclo = "";
private String fecha_introduccion = "";
private String severidad = "";
private String detalle = "";
public DetalleCiclo() {
}
public DetalleCiclo(String id_detalle, String id_ciclo, String fecha_introduccion, String severidad, String detalle) {
this.id_detalle = id_detalle;
this.id_ciclo = id_ciclo;
this.fecha_introduccion = fecha_introduccion;
this.severidad = severidad;
this.detalle = detalle;
}
public String getId_detalle() {
return id_detalle;
}
public void setId_detalle(String id_detalle) {
this.id_detalle = id_detalle;
}
public String getId_ciclo() {
return id_ciclo;
}
public void setId_ciclo(String id_ciclo) {
this.id_ciclo = id_ciclo;
}
public String getFecha_introduccion() {
return fecha_introduccion;
}
public void setFecha_introduccion(String fecha_introduccion) {
this.fecha_introduccion = fecha_introduccion;
}
public String getSeveridad() {
return severidad;
}
public void setSeveridad(String severidad) {
this.severidad = severidad;
}
public String getDetalle() {
return detalle;
}
public void setDetalle(String detalle) {
this.detalle = detalle;
}
}
|
Python
|
UTF-8
| 422 | 4.3125 | 4 |
[] |
no_license
|
print('\nLisitng 4.5: Better Feedback')
dividend, divisor = eval(input('Please enter two numbers to divide: '))
if divisor != 0:
print(dividend, '/', divisor, '=', dividend/divisor)
else:
print('Division by zero is not allowed')
print('\nListing 4.6: Same different')
d1 = 1.11 - 1.10
d2 = 2.11 - 2.10
print('d1 =', d1, ' d2 = ', d2)
if d1 == d2:
print('Same')
else:
print('Different')
|
Python
|
UTF-8
| 847 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
import ast
from functools import wraps
from typing import Callable
from pynano.interfaces import NanoError, Scope, Scopes
class Compiler(ast.NodeTransformer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._scope = Scopes.MODULE
self._symbol_table = Scope()
def compile(self, tree: ast.AST) -> str:
code = self.visit(tree)
return code
class CompilationError(NanoError):
pass
def context_change(func: Callable[[Compiler, ast.AST], "Instruction"]):
@wraps(func)
def wrapper(self: Compiler, node: ast.AST) -> "Instruction":
self._symbol_table.local.clear()
self._scope = Scopes.LOCAL
result = func(self, node)
self._scope = Scopes.MODULE
self._symbol_table.local.clear()
return result
return wrapper
|
PHP
|
UTF-8
| 4,275 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use phpDocumentor\Reflection\Types\Static_;
use Symfony\Component\DomCrawler\Crawler;
class ParsedPost extends Model
{
protected $fillable= ['title','parsed_body'];
public function parsedTags()
{
return $this->belongsToMany('App\ParsedTag', 'parsed_tags_relationship');
}
public function parsePost()
{
$pages = config('pages.pages');
foreach ($pages as $page) {
$html = file_get_contents($page);
$crawler = new Crawler($html);
$posts = $crawler
->filter('a.post__title_link')
->extract(['href']);
foreach ($posts as $post) {
$html = file_get_contents($post);
$crawler = new Crawler($html);
// div.post__body.post__body_full
$body = $crawler->filter('div.post__body.post__body_full')->each(function ($node) {
return $node->html();
});
$tags = $crawler->filter('a.inline-list__item-link.hub-link')->each(function ($node) {
return $node->html();
});
$titles = $crawler->filter('span.post__title-text')->each(function ($node){
return $node->html();
});
// return $array = array("body"=>$body,"tags"=>$tags);
// dd($titles);
$title = array_pop($titles);
$body = str_replace('"""', '', $body[0]);
$post = ParsedPost::firstOrNew(['title'=>$title]);
$post-> parsed_body = $body;
$post->title = $title;
$post->save();
foreach ($tags as $tag) {
$tags=ParsedTag::firstOrCreate(['parsed_tag'=>$tag],['parsed_tag'=>$tag]);
$post->parsedTags()->attach($tags);
}
// print_r($arrays);
// foreach ($arrays as $array) {
// print_r($array);
//// $post = new ParsedPost();
////// dd($array);
//// $post->parsed_body = $array['body'];
//// $post->save();
//
//
// }
// print_r($tag);
// $post = new ParsedPost();
// $post->parsed_body = $body;
// $post->save();
// $tags=Tag::firstOrCreate(['parsed_tag'=>$tag],['parsed_tag'=>$tag]);
// $post->parsedTags()->attach($tags);
}
}
}
//
//
// public function FileManager($i)
// {
// $path = "uploads/posts/id{$i}";
// mkdir($path, '0777', 'true');
// return "/$path/";
//
// }
//
// public function parsePages()
// {
// $pages = config('pages.pages');
// file_put_contents('tags.txt', '');
//
// foreach ($pages as $page) {
//
// $html = file_get_contents($page);
// $crawler = new Crawler($html);
//
//
// return $crawler
// ->filter('a.post__title_link')
// ->extract(['href']);
//
// }
// }
//
// public function parsePosts()
// {
//
// $posts=$this->parsePages();
// dump($posts);
//
// foreach ($posts as $post) {
//
// $html = file_get_contents($post);
// $crawler = new Crawler($html);
//
// $crawler->filter('div.post__wrapper')->each(function ($node) {
//// div.post__body.post__body_full
// echo $node->html();
//// $parsed_post = new ParsedPost();
//// $parsed_post = $node->html();
//// $parsed_post->save();
//
//// $crawler = new Crawler($node);
//// $crawler->filter('a.inline-list__item-link.hub-link')->each(function ($node) {
////
//// $parsed_tag = new ParsedTags();
//// $parsed_tag->parsed_tag = $node->html();
//// $parsed_tag->firstorCreate(['parsed_tag' => $parsed_tag], ['parsed_tag' => $parsed_tag]);
//// $parsed_tag;
//// });
// });
// }
// }
}
|
Java
|
UTF-8
| 4,994 | 2.28125 | 2 |
[] |
no_license
|
package com.berk2s.authorizationserver.services.impl;
import com.berk2s.authorizationserver.domain.oauth.Client;
import com.berk2s.authorizationserver.domain.oauth.GrantType;
import com.berk2s.authorizationserver.repository.ClientRepository;
import com.berk2s.authorizationserver.security.SecurityUserDetails;
import com.berk2s.authorizationserver.services.AuthorizationCodeService;
import com.berk2s.authorizationserver.services.AuthorizationService;
import com.berk2s.authorizationserver.web.models.ErrorDesc;
import com.berk2s.authorizationserver.web.models.ErrorType;
import com.berk2s.authorizationserver.web.exceptions.*;
import com.berk2s.authorizationserver.web.models.AuthorizationCodeDto;
import com.berk2s.authorizationserver.web.models.AuthorizeRequestParamDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@Slf4j
@RequiredArgsConstructor
@Service
public class AuthorizationServiceImpl implements AuthorizationService {
private final ClientRepository clientRepository;
private final AuthorizationCodeService authorizationCodeService;
@Override
public URI authorizeRequest(AuthorizeRequestParamDto params, SecurityUserDetails securityUserDetails) {
try {
if (securityUserDetails == null || securityUserDetails.getId() == null) {
log.warn("Invalid security user details [clientId: {}]", params.getClientId());
throw new InvalidSecurityUserDetailsException(ErrorDesc.BAD_CREDENTIALS.getDesc());
}
Client client = clientRepository
.findByClientId(params.getClientId())
.orElseThrow(() -> {
log.warn("Invalid client id [clientId: {}]", params.getClientId());
throw new InvalidClientException(ErrorDesc.INVALID_CLIENT.getDesc());
});
if (!client.getRedirectUris().contains(params.getRedirectUri())) {
log.warn("Invalid redirect uri, it doesn't contain in Client's URI list [clientId: {}]", params.getClientId());
throw new InvalidRedirectUriException(ErrorDesc.INVALID_REDIRECT_URI.getDesc());
}
if (!client.isConfidential() && (params.getCodeChallenge() == null || params.getCodeChallenge().isBlank())) {
log.warn("Public Client tried request without PKCE [clientId: {}]", params.getClientId());
return redirectError(params.getRedirectUri(), ErrorType.INVALID_REQUEST.getError(), URLEncoder.encode(ErrorDesc.INVALID_CLIENT_TYPE.getDesc(), StandardCharsets.UTF_8), params.getState());
}
if(!client.getGrantTypes().contains(GrantType.AUTHORIZATION_CODE)) {
log.warn("The Client request for authorization but it doesn't has authorization_code grant [clientId: {}]", params.getClientId());
return redirectError(params.getRedirectUri(), ErrorType.INVALID_GRANT.getError(), URLEncoder.encode(ErrorDesc.INSUFFICIENT_CLIENT_GRANT_CODE.getDesc(), StandardCharsets.UTF_8), params.getState());
}
Set<String> scopes = new HashSet<>(Arrays.asList(params.getScope().split(" ")));
AuthorizationCodeDto authorizationCode =
authorizationCodeService.createAuthorizationCode(
params.getClientId(),
params.getRedirectUri(),
scopes,
securityUserDetails.getId().toString(),
params.getNonce(),
params.getCodeChallenge(),
params.getCodeChallengeMethod());
log.info("Redirect uri created. [clientId: {}, uri: {}, code: {}, state: {}]", params.getClientId(),
params.getRedirectUri().toString(),
authorizationCode.getCode(),
params.getState());
return new URI(params.getRedirectUri().toString()
+ "?code="
+ authorizationCode.getCode()
+ "&state="
+ params.getState());
} catch (URISyntaxException e) {
log.warn(e.getMessage() + "[clientId: {}]", params.getClientId());
throw new ServerException(ErrorDesc.SERVER_ERROR.getDesc());
}
}
private URI redirectError(URI redirectUri, String errorType, String errorDescription, String state) throws URISyntaxException {
return new URI(redirectUri.toString()
+ "?error="
+ errorType
+ "&error_description="
+ errorDescription
+ "&state="
+ state);
}
}
|
Python
|
UTF-8
| 2,299 | 2.53125 | 3 |
[] |
no_license
|
from lib.data_loader.atlas_settings import super_regions_atlas
import nibabel as nib
import settings
import numpy as np
import csv
def load_atlas_mri():
img = nib.load(settings.mri_atlas_path)
img_data = img.get_data()
atlasdata = img_data.flatten()
bckvoxels = np.where(atlasdata != 0) #Sacamos los indices que no son 0
atlasdata = atlasdata[bckvoxels] # Mapeamos aplicando los indices
vals = np.unique(atlasdata)
reg_idx = {} # reg_idx contiene los indices de cada region
for i in range(1, max(vals) + 1):
reg_idx[i] = np.where(atlasdata == i)[0] # Saca los indices
return reg_idx
def get_super_region_to_voxels():
"""
This functions returns a dictionary.
Each key of the dictionary is a region and his values are
their voxels associated
:return:
"""
regions_dict = load_atlas_mri() # dictionary
super_region_atlas_voxels = {}
for super_region_key, regions_included in super_regions_atlas.items():
super_region_atlas_voxels[super_region_key] = \
np.concatenate(
[voxels for region_index, voxels in regions_dict.items() if region_index in regions_included],
axis=0)
return super_region_atlas_voxels
def generate_super_regions_csv_template():
regions_dict = get_super_region_to_voxels()
with open('regions_neural_net_setting.template.csv', 'w+') as file:
fieldnames = ['region', 'n_voxels', 'input_layer', 'first_layer', 'second_layer', 'latent_layer']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
for region_name, voxels in regions_dict.items():
aux_dic = {'region': str(region_name), 'n_voxels': str(len(voxels))}
writer.writerow(aux_dic)
def generate_regions_csv_template():
regions_dict = load_atlas_mri()
with open('regions_neural_net_setting.template.csv', 'w+') as file:
fieldnames = ['region', 'n_voxels', 'input_layer', 'first_layer', 'second_layer', 'latent_layer']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
for region_name, voxels in regions_dict.items():
aux_dic = {'region': str(region_name), 'n_voxels': str(len(voxels))}
writer.writerow(aux_dic)
|
Python
|
UTF-8
| 4,085 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
"""
Fully define a 'random' generated setup for the players per specified conditions
"""
import random
import re
from sc2simulator import constants as c
from sc2simulator.scenarioMgr import Scenario, parseBankXml, getBankFilepath
from sc2simulator.setup import mapLocations
from sc2simulator.setup.mapLocations import convertStrToPoint, defineLocs
from sc2simulator.setup.unitSelection import generateUpgrades
from sc2simulator.setup.unitSelection import generatePlayerUnits
################################################################################
def getSetup(mapObj, options, cfg):
"""get the appropriate scenarios, whether predefined or custom generated"""
mdata = None
try:
import sc2maps # Versentiedge closed source package
mData = sc2maps.MapData(mapName=mapObj.name)
mapLocations.mapDimensions = mData.dimensions.toCoords()
mdata = mData.placement.halfGrid
except Exception: # ModuleNotFoundError isn't available in python 3.5
try:
if not options.dimensions: raise ValueError("must provide dims")
mapLocations.mapDimensions = convertStrToPoint(options.dimensions)
if len(mapLocations.mapDimensions) < 2:
raise ValueError("must provide valid dimensions (given: %s)"%(
mapLocations.mapDimensions))
except ValueError:
print("ERROR: must provide valid map dimensions (given: %s"%(
options.dimensions))
return []
mdata = mapLocations.mapDimensions
scenarios = []
if options.cases: # use preloaded cases
try:
bankName = getBankFilepath(mapObj.name) # select the bank repository from the specified map
bank = parseBankXml(bankName) # load the bank's defined scenarios
except:
print("ERROR: failed to load specified bank '%s'"%(mapObj.name))
return scenarios
for scenarioName in re.split("[,;:]+", options.cases): # use options.cases to select which cases to run
try: # attempt to retrieve the specified scenario from the bank
scenarios.append(bank.scenarios[scenarioName])
except:
print("WARNING: scenario '%s' was not found in bank %s"%(
scenarioName, bankName))
else: # dynamically generate the scenario
scenarios += generateScenario(mapObj, options, cfg, mdata)
return scenarios
################################################################################
def generateScenario(mapObj, options, cfg, mdata):
"""override this function is different generation methods are desired"""
scenario = Scenario("custom%s"%mapObj.name)
scenario.duration = options.duration
d = options.distance # generate each player's locations
mapLocs = defineLocs(options.loc, options.enemyloc, d)
givenRaces = [options.race, options.enemyrace]
for i, (pLoc, r) in enumerate(zip(mapLocs, givenRaces)):
race = pickRace(r)
pIdx = i + 1 # player indexes start at one, not zero
scenario.addPlayer(pIdx, loc=pLoc, race=race)
generatePlayerUnits(scenario, pIdx, race, options, pLoc, mapData=mdata)
try: generateUpgrades(scenario, pIdx, options)
except Exception as e:
print("ERROR: %s"%e)
return []
#scenario.players[pIdx].upgradeReqs
#for u in scenario.newBaseUnits(pIdx):
# print("%d %s"%(pIdx, u))
#print()
#for u in scenario.players[pIdx].baseUnits:
# print("%d %s"%(pIdx, u))
#print()
return [scenario]
################################################################################
def pickRace(specifiedRace):
"""ensure the selected race for scenario generation is a race, not random"""
if specifiedRace == c.RANDOM:
choices = list(c.types.SelectRaces.ALLOWED_TYPES.keys())
choices.remove(c.RANDOM) # ensure the new race isn't 'random' again
newRace = random.choice(choices)
return newRace
return specifiedRace
|
Java
|
UTF-8
| 3,394 | 4.0625 | 4 |
[] |
no_license
|
package offer40;
import java.util.Arrays;
import java.util.Random;
/**
* @author wall
* @date 2019/1/20 15:54
* @description 最小的k个数
* 题目:输入n个整数,找出其中最小的k个数。
*/
public class GetLeastNumbers {
//测试
public static void main(String[] args) {
int [] data = new int[]{4,5,1,6,2,7,3,8,9,10,15,12,4,4,4,4};
int k = 4;
getLeastNumbers_solution(data,4);
System.out.println(getNumberK_solution(data,8));
}
/**
* 最简单的思路
* @param data
* @param k
*/
private static void getLeastNumbers_mysolution(int [] data,int k){
//边界测试
if (data == null || k ==0){
return;
}
//排序数组
Arrays.sort(data);
for (int i = 0 ;i < k ; i++){
System.out.println(data[i]);
}
}
/**
* 基于快速排序的思想,利用partition函数取数组中第k大的数字
* @param data
* @param k
*/
private static void getLeastNumbers_solution(int [] data,int k){
//边界测试
if (data == null || data.length < 1 || k <= 0 || k > data.length){
return;
}
int start = 0;
int end = data.length-1;
int index = partition(data,start,end);
while (index != k-1){
if (index > k-1){
index = partition(data,start,index-1);
}else {
index = partition(data,index+1,end);
}
}
for (int i = 0 ; i < k;i++){
System.out.println(data[i]);
}
}
/**
* 返回比随机选取的数组值小的个数,时间复杂度为O(n)
* @param data
* @param start
* @param end
* @return
*/
private static int partition(int [] data,int start,int end){
if (data == null || start > end || start < 0 ){
return -1;
}
//java取指定范围的随机数
int index = new Random().nextInt(end-start+1)+start;
System.out.println("数组下标:"+index);
swap(data,index,end);
System.out.println("数组值:"+data[index]);
int small = start -1;
//从左侧开始移动
for (int i = start;i < end; i++){
if (data[i] < data[end]){
small++;
if (small!=i){
swap(data,small,i);
}
}
}
small++;
swap(data,small,end);
return small;
}
/**
* 交换函数
* @param data
* @param i
* @param j
*/
private static void swap(int [] data,int i,int j){
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
/**
* 求数组中第k大的数字
* @param data
* @param k
* @return
*/
private static int getNumberK_solution(int [] data, int k){
if (data == null || data.length < 1 || k <= 0 || k > data.length){
return -1;
}
int start = 0;
int end = data.length -1;
int index = partition(data,start,end);
while (index != k-1){
if (index>k-1){
index = partition(data,start,index-1);
}else {
index = partition(data,index+1,end);
}
}
return data[k-1];
}
}
|
C++
|
UTF-8
| 1,634 | 3.234375 | 3 |
[] |
no_license
|
class Solution {
public:
vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
int n = mat.size(), m = mat[0].size();
vector<vector<int>> ans(n, vector<int>(m, 0));
vector<vector<int>> dp(n+1, vector<int>(m+1, 0)); // 1-based indexing <-- prefix sums,˘
// compute the prefix sums
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
dp[i][j] = mat[i-1][j-1] + dp[i][j-1] + dp[i-1][j] - dp[i-1][j-1];
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
// compute the ans for (i,j)
int i1 = max(0, i-k), j1 = max(0,j-k);
int i2 = min(n-1, i+k), j2 = min(m-1, j+k);
i1++, i2++, j1++, j2++; //1-based indexing
ans[i][j] = dp[i2][j2] - dp[i2][j1-1] - dp[i1-1][j2] + dp[i1-1][j1-1];
}
},™
return ans;
}
};
/*
prefix sum in 2d approach
dp[i][j] = sum of rect from (0,0) to (i,j) as diagnal points
=> it helps me in computing any rectangle sum in O(1)
(i1, j1) and (i2, j2) i1 < i2 and j1 < j2
dp[i2][j2] - dp[i1][j1-1] - dp[i1-1][j2] + dp[i1-1][j1-1]
prefix sums can be used for each row individually
=> for given row, sum(j-k, j+k) => O(1)
j-k j j+k
i-k
i x
i+k
(i,j) => O(k^2)
O(N^2k^2)
O(N^2 k)
k = 1
[1,2,3],
[4,5,6],
[7,8,9]
9*10/2 = 45
5+6+8+9 = 28
*/
|
Java
|
UTF-8
| 9,546 | 2 | 2 |
[
"BSD-3-Clause"
] |
permissive
|
package org.yinwang.rubysonar;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.jetbrains.annotations.NotNull;
import org.yinwang.rubysonar.ast.Dummy;
import org.yinwang.rubysonar.ast.Node;
import java.io.File;
import java.util.*;
public class Test {
static Gson gson = new GsonBuilder().setPrettyPrinting().create();
Analyzer analyzer;
String inputDir;
boolean exp;
String expecteRefsFile;
String failedRefsFile;
String extraRefsFile;
public Test(String inputDir, boolean exp) {
// make a quiet analyzer
Map<String, Object> options = new HashMap<>();
// options.put("quiet", true);
this.analyzer = new Analyzer(options);
this.inputDir = inputDir;
this.exp = exp;
if (new File(inputDir).isDirectory()) {
expecteRefsFile = _.makePathString(inputDir, "refs.json");
failedRefsFile = _.makePathString(inputDir, "failed_refs.json");
extraRefsFile = _.makePathString(inputDir, "extra_refs.json");
} else {
expecteRefsFile = _.makePathString(inputDir + ".refs.json");
failedRefsFile = _.makePathString(inputDir, ".failed_refs.json");
extraRefsFile = _.makePathString(inputDir, ".extra_refs.json");
}
}
public void runAnalysis(String dir) {
analyzer.analyze(dir);
analyzer.finish();
}
public void generateRefs() {
List<Map<String, Object>> refs = new ArrayList<>();
for (Map.Entry<Node, List<Binding>> e : analyzer.references.entrySet()) {
String file = e.getKey().file;
// only record those in the inputDir
if (file != null && file.startsWith(Analyzer.self.projectDir)) {
file = _.projRelPath(file);
Map<String, Object> writeout = new LinkedHashMap<>();
Map<String, Object> ref = new LinkedHashMap<>();
ref.put("name", e.getKey().name);
ref.put("file", file);
ref.put("start", e.getKey().start);
ref.put("end", e.getKey().end);
List<Map<String, Object>> dests = new ArrayList<>();
for (Binding b : e.getValue()) {
String destFile = b.file;
if (destFile != null && destFile.startsWith(Analyzer.self.projectDir)) {
destFile = _.projRelPath(destFile);
Map<String, Object> dest = new LinkedHashMap<>();
dest.put("name", b.node.name);
dest.put("file", destFile);
dest.put("start", b.start);
dest.put("end", b.end);
dests.add(dest);
}
}
if (!dests.isEmpty()) {
writeout.put("ref", ref);
writeout.put("dests", dests);
refs.add(writeout);
}
}
}
String json = gson.toJson(refs);
_.writeFile(expecteRefsFile, json);
}
public boolean checkRefs() {
List<Map<String, Object>> failedRefs = new ArrayList<>();
List<Map<String, Object>> extraRefs = new ArrayList<>();
String json = _.readFile(expecteRefsFile);
if (json == null) {
_.msg("Expected refs not found in: " + expecteRefsFile +
"Please run Test with -exp to generate");
return false;
}
List<Map<String, Object>> expectedRefs = gson.fromJson(json, List.class);
for (Map<String, Object> r : expectedRefs) {
Map<String, Object> refMap = (Map<String, Object>) r.get("ref");
Dummy dummy = makeDummy(refMap);
List<Map<String, Object>> dests = (List<Map<String, Object>>) r.get("dests");
List<Binding> actualDests = analyzer.references.get(dummy);
List<Map<String, Object>> failedDests = new ArrayList<>();
List<Map<String, Object>> extraDests = new ArrayList<>();
for (Map<String, Object> d : dests) {
// names are ignored, they are only for human readers
String file = _.projAbsPath((String) d.get("file"));
int start = (int) Math.floor((double) d.get("start"));
int end = (int) Math.floor((double) d.get("end"));
if (actualDests == null ||
!checkBindingExist(actualDests, file, start, end))
{
failedDests.add(d);
}
}
if (actualDests != null && !actualDests.isEmpty()) {
for (Binding b : actualDests) {
String destFile = b.file;
if (destFile != null && destFile.startsWith(Analyzer.self.projectDir)) {
destFile = _.projRelPath(destFile);
Map<String, Object> d1 = new LinkedHashMap<>();
d1.put("file", destFile);
d1.put("start", b.start);
d1.put("end", b.end);
extraDests.add(d1);
}
}
}
// record the ref & failed dests if any
if (!failedDests.isEmpty()) {
Map<String, Object> failedRef = new LinkedHashMap<>();
failedRef.put("ref", refMap);
failedRef.put("dests", failedDests);
failedRefs.add(failedRef);
}
if (!extraDests.isEmpty()) {
Map<String, Object> extraRef = new LinkedHashMap<>();
extraRef.put("ref", refMap);
extraRef.put("dests", extraDests);
extraRefs.add(extraRef);
}
}
if (!failedRefs.isEmpty()) {
String failedJson = gson.toJson(failedRefs);
_.testmsg("failed to find refs: " + failedJson);
_.writeFile(failedRefsFile, failedJson);
}
if (!extraRefs.isEmpty()) {
String extraJson = gson.toJson(extraRefs);
_.testmsg("found extra refs: " + extraJson);
_.writeFile(extraRefsFile, extraJson);
}
return failedRefs.isEmpty() && extraRefs.isEmpty();
}
boolean checkBindingExist(@NotNull List<Binding> bs, String file, int start, int end) {
Iterator<Binding> iter = bs.iterator();
while (iter.hasNext()) {
Binding b = iter.next();
if (_.same(b.file, file) &&
b.start == start &&
b.end == end)
{
iter.remove();
return true;
}
}
return false;
}
public static Dummy makeDummy(Map<String, Object> m) {
String file = _.projAbsPath((String) m.get("file"));
int start = (int) Math.floor((double) m.get("start"));
int end = (int) Math.floor((double) m.get("end"));
return new Dummy(file, start, end);
}
public void generateTest() {
runAnalysis(inputDir);
generateRefs();
_.testmsg(" * " + inputDir);
}
public boolean runTest() {
runAnalysis(inputDir);
_.testmsg(" * " + inputDir);
return checkRefs();
}
// ------------------------- static part -----------------------
public static void testAll(String path, boolean exp) {
List<String> failed = new ArrayList<>();
if (exp) {
_.testmsg("generating tests");
} else {
_.testmsg("verifying tests");
}
testRecursive(path, exp, failed);
if (exp) {
_.testmsg("all tests generated");
} else if (failed.isEmpty()) {
_.testmsg("all tests passed!");
} else {
_.testmsg("failed some tests: ");
for (String f : failed) {
_.testmsg(" * " + f);
}
}
}
public static void testRecursive(String path, boolean exp, List<String> failed) {
File file_or_dir = new File(path);
if (file_or_dir.isDirectory()) {
if (path.endsWith(".test")) {
Test test = new Test(path, exp);
if (exp) {
test.generateTest();
} else {
if (!test.runTest()) {
failed.add(path);
}
}
} else {
for (File file : file_or_dir.listFiles()) {
testRecursive(file.getPath(), exp, failed);
}
}
}
}
public static void main(String[] args) {
Options options = new Options();
options.addOption("exp", "expected", false, "generate expected result (for setting up tests)");
CommandLineParser parser = new BasicParser();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (Exception e) {
_.die("failed to parse args: " + args);
return;
}
args = cmd.getArgs();
String inputDir = _.unifyPath(args[0]);
// generate expected file?
boolean exp = cmd.hasOption("expected");
testAll(inputDir, exp);
}
}
|
Markdown
|
UTF-8
| 2,630 | 2.8125 | 3 |
[] |
no_license
|
---
title: "Paul Du Noyer: Classic Albums Students Should Still Be Listening To"
slug: "paul-du-noyer-classic-albums-students-should-still-be-listening-to"
date: "2015-09-17"
author: "Matt Hacke"
rating: "undefined"
---
I have interviewed many hundreds of musicians down the years, including Madonna, Morrissey, U2, and Mick Jagger. But here are six artists that stand out in the memory with my favourite album by each.
**Amy Winehouse – Back To Black** When I met Amy it was in a London café while she was writing what became Back To Black. In fact she kept fishing a notebook out of her handbag to jot down lines as they came to her during our talk. She was a nervous interviewee, with obvious insecurities, but no sign yet of the problems that over came her after she became properly famous.
**David Bowie – Low** Bowie is the artist I grew up feeling obsessed by, and meeting him has never been a disappointment. Low was a very mysterious record, made as if to destroy all his hard-won popularity. I always admired that fearless side to him.
**Bruce Springsteen –** **Nebraska** I only met him once, backstage in Chicago, but he was very generous with his Budweisers, which is the main thing. He can be a big stadium-pleaser but there is also a pretty serious, intimate side to his style where some of his best songs can be found, I think.
**Van Morrison** **–** **Astral Weeks** Van has just been given a knighthood, which certainly wasn’t for his services to journalism. He is a very tough interviewee, but I always took the chance when I could. His music has always moved me so much, especially this mystical stream of consciousness he made when he was only twenty-three.
**Joe Strummer (The Clash) – Sandinista!** I was just the right age to stumble into punk when it erupted in London in 1976. I joined the NME and one day Joe Strummer came round to the office to be interviewed. We went off on a pub crawl around Soho and the whole encounter lasted two days.
**Paul McCartney – Ram** I’ve interviewed this guy so often I decided to make a book out of it: “Conversations With McCartney”, which is out now in hardback. Ram was a record from 1971, when Macca was still in shock from the break-up of The Beatles. He got the whole thing out of his system with a bunch of madly tuneful nonsense that just gets better over time.
_Paul has written for and edited Q, Mojo, and NME over his long career in music journalism. Whilst he has interviewed and met all the artists mentioned above, he will be releasing his compiled portfolio of interviews with Paul McCartney on the 24th September 2015. “Conversations With McCartney” can be ordered in hardcover for £25._
|
PHP
|
UTF-8
| 2,966 | 2.796875 | 3 |
[] |
no_license
|
<!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<pre>
<form action='#' method="post">
Фирма: <input type="text" name="firm"/> <br>
Булстат: <input type="text" name="bulst"/> <br>
Населено Място: <select name="city">
<?php
include "config.php";
$result = mysqli_query($dbConn, "SELECT * FROM City");
while ($row = mysqli_fetch_array($result)) {
echo '<option>' . $row["Name"].'</option>';
}
?>
</select><br>
Телефон: <input type="text" name="ph"/> <br>
Година за регистрация: <input type="text" name="year"/> <br>
Лице за контакти: <input type="text" name="contact"/> <br>
<input type='submit' name='subm' value='Въведи'/>
</form>
</pre>
<?php
include "config.php";
if (isset($_POST['subm'])) {
$firm = $_POST['firm'];
$bulst = $_POST['bulst'];
$city = $_POST['city'];
$ph = $_POST['ph'];
$year = $_POST['year'];
$cont = $_POST['contact'];
if (!empty($firm) && !empty($bulst) && !empty($city) && !empty($ph) && !empty($year) && !empty($cont)) {
$sql3 = "INSERT INTO `Provider` (`Firm`, `Bulstat`, `CityID`, `PhoneNumber`, `YearRegistered`, `Name`) VALUES (' $firm', '$bulst', '$city ', '$ph', '$year', '$cont')";
if ($dbConn->query($sql3) === TRUE) {
$last_id1 = $dbConn->insert_id;
echo "Успесно добавен нов запис с код: " . $last_id1;
echo '<a href="index.php">Назад</a><br>';
} else {
echo "Error: " . $sql3 . "<br>" . $dbConn->error;
}
$result = mysqli_query($dbConn, "SELECT * FROM Provider");
echo "<table border=2px><tr><th>Доставчик</th><th>Булстат</th><th>Адрес</th><th>Телефон</th><th>Година Регистрация</th><th>Лице за контакт</th></tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr><td>" . $row['Firm'] . "</td><td>" . $row['Bulstat'] . "</td><td>" . $row['CityID'] . "</td><td>" . $row['PhoneNumber'] . "</td><td>" . $row['YearRegistered'] . "</td><td>" . $row['Name'] . "</td></tr>";
}
echo "</table>";
}
}
?>
</body>
</html>
|
Shell
|
UTF-8
| 231 | 3.890625 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/bash
# Print a file excluding comments
if [[ -z "$1" ]]; then
echo "Usage: $0 <file>" >&2
exit 1
fi
# check valid file
if [ ! -f "$1" ]; then
echo "File does not exist: $1" >&2
exit 1
fi
grep -v '^$\|^\s*\#' "$1"
|
Shell
|
UTF-8
| 2,048 | 2.765625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env bash
# Copyright 2017 The Kubernetes Authors.
#
# 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.
# Directories.
ROOT_DIR="$(cd $(dirname "${BASH_SOURCE}")/../.. && pwd -P)"
AIO_DIR="${ROOT_DIR}/aio"
I18N_DIR="${ROOT_DIR}/i18n"
TMP_DIR="${ROOT_DIR}/.tmp"
SRC_DIR="${ROOT_DIR}/src"
FRONTEND_DIR="${TMP_DIR}/frontend"
FRONTEND_SRC="${SRC_DIR}/app/frontend"
DIST_DIR="${ROOT_DIR}/dist"
CACHE_DIR="${ROOT_DIR}/.cached_tools"
BACKEND_SRC_DIR="${ROOT_DIR}/src/app/backend"
COVERAGE_DIR="${ROOT_DIR}/coverage"
# Paths.
GO_COVERAGE_FILE="${ROOT_DIR}/coverage/coverage.go.txt"
# Binaries.
NG_BIN="${ROOT_DIR}/node_modules/.bin/ng"
GULP_BIN="${ROOT_DIR}/node_modules/.bin/gulp"
CLANG_FORMAT_BIN="${ROOT_DIR}/node_modules/.bin/clang-format"
SCSSFMT_BIN="${ROOT_DIR}/node_modules/.bin/scssfmt"
BEAUTIFY_BIN="${ROOT_DIR}/node_modules/.bin/js-beautify"
GLOB_RUN_BIN="${ROOT_DIR}/node_modules/.bin/glob-run"
GOLINT_URL="https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh"
GOLINT_BIN="${CACHE_DIR}/golangci-lint"
# Global constants.
ARCH=$(uname | awk '{print tolower($0)}')
# Local cluster configuration (check start-cluster.sh script for more details).
HEAPSTER_VERSION="v1.5.4"
HEAPSTER_PORT=8082
KIND_VERSION="0.1.0"
KIND_BIN=${CACHE_DIR}/kind-${KIND_VERSION}
# Setup logger.
ERROR_STYLE=`tput setaf 1`
INFO_STYLE=`tput setaf 2`
BOLD_STYLE=`tput bold`
RESET_STYLE=`tput sgr0`
function say { echo -e "${INFO_STYLE}${BOLD_STYLE}$@${RESET_STYLE}"; }
function saye { echo -e "${ERROR_STYLE}${BOLD_STYLE}$@${RESET_STYLE}"; }
|
Java
|
UTF-8
| 579 | 2.65625 | 3 |
[] |
no_license
|
package com.example.bishe.Util;
import android.util.Log;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class NumberToChn {
static String CHN_NUMBER[] = {" ", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
public static String inttoCHn(int i) {
Log.e(TAG, "inttoCHn: " + i);
if (i / 10 == 0) {
return CHN_NUMBER[i];
} else {
int j = i / 10;
return j == 1 ?"十" + CHN_NUMBER[i % 10]
:CHN_NUMBER[j] + "十" + CHN_NUMBER[i % 10];
}
}
}
|
Java
|
UTF-8
| 10,096 | 2.1875 | 2 |
[] |
no_license
|
package com.camsys.carmonic.networking;
import com.camsys.carmonic.constants.Constants;
import java.security.cert.CertificateException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public class BackEndDAO {
private static OkHttpClient client = getUnsafeOkHttpClient();
public static OkHttpClient getClient() {
return client;
}
public static String getBackendURL() {
return Constants.EndPoint.Base_URL_remote;
}
public static void signUp(String firstName,
String lastName,
String email,
String password,
String phoneNumber,
String paymentReference,
Callback callback) {
String route = "/signup";
RequestBody requestBody = new FormBody.Builder()
.add("firstname", firstName)
.add("lastname", lastName)
.add("email", email)
.add("password", password)
.add("phoneNumber", phoneNumber)
.add("paymentReference", paymentReference)
.build();
Request request = new Request.Builder()
.url(getBackendURL() + route)
.post(requestBody)
.build();
client.newCall(request).enqueue(callback);
}
public static void getHistoryWithPost(int customerId, String token, Callback callback) {
String route = "/history";
RequestBody requestBody = new FormBody.Builder()
.add("customerId", "86")
.build();
Request request = new Request.Builder()
.addHeader("Authorization", "Bearer " + token)
.url(getBackendURL() + route)
.post(requestBody)
.build();
client.newCall(request).enqueue(callback);
}
public static void signIn(String email, String password, Callback callback) {
String route = "/login";
RequestBody requestBody = new FormBody.Builder()
.add("email", email)
.add("password", password)
.build();
Request request = new Request.Builder()
.url(getBackendURL() + route)
.post(requestBody)
.build();
client.newCall(request).enqueue(callback);
}
public static void getHistory(int userId, String token, Callback callback) {
String route = "/history";
HttpUrl.Builder httpBuider = HttpUrl.parse(getBackendURL() + route).newBuilder();
httpBuider.addQueryParameter("customerId", "86"); //userId + "");
Request request = new Request.Builder()
.addHeader("Authorization", "Bearer " + token)
.url(httpBuider.build())
.build();
client.newCall(request).enqueue(callback);
}
public static void getMechanics(double longitude, double latitude,String token, Callback callback) {
String route = "/getMechanics";
HttpUrl.Builder httpBuider = HttpUrl.parse(getBackendURL() + route).newBuilder();
httpBuider.addQueryParameter("longitude", Double.toString(longitude));
httpBuider.addQueryParameter("latitude", Double.toString(latitude));
Request request = new Request.Builder()
.addHeader("Authorization", "Bearer " + token)
.url(httpBuider.build())
.build();
client.newCall(request).enqueue(callback);
}
public static void initiateJob(String customerId, double longitude, double latitude, String token, String fcmToken, Callback callback) {
String route = "/initiateJob";
HttpUrl.Builder httpBuider = HttpUrl.parse(getBackendURL() + route).newBuilder();
httpBuider.addQueryParameter("longitude", Double.toString(longitude));
httpBuider.addQueryParameter("latitude", Double.toString(latitude));
httpBuider.addQueryParameter("customerId", customerId);
httpBuider.addQueryParameter("fcmtoken", fcmToken);
Request request = new Request.Builder()
.addHeader("Authorization", "Bearer " + token)
.url(httpBuider.build())
.build();
client.newCall(request).enqueue(callback);
}
public static void setCustomerStatusChange(int customerId, double longitude, double latitude, String fcmToken, String accessToken, Callback callback) {
String route = "/custStatusChange";
HttpUrl.Builder httpBuider = HttpUrl.parse(getBackendURL() + route).newBuilder();
httpBuider.addQueryParameter("customerId", String.valueOf(customerId));
httpBuider.addQueryParameter("longitude", Double.toString(longitude));
httpBuider.addQueryParameter("latitude", Double.toString(latitude));
httpBuider.addQueryParameter("fcmToken", fcmToken);
Request request = new Request.Builder()
.addHeader("Authorization", "Bearer " + accessToken)
.url(httpBuider.build())
.build();
System.out.println("fcmToken::: " + fcmToken);
System.out.println("customerId::: " + customerId);
System.out.println("longitude::: " + longitude);
System.out.println("latitude::: " + latitude);
client.newCall(request).enqueue(callback);
}
public static void charge(String amount, String email, String token, Callback callback) {
String route = "/charge";
HttpUrl.Builder httpBuider = HttpUrl.parse(getBackendURL() + route).newBuilder();
httpBuider.addQueryParameter("amount", amount);
httpBuider.addQueryParameter("email", email);
Request request = new Request.Builder()
.addHeader("Authorization", "Bearer " + token)
.url(httpBuider.build())
.build();
client.newCall(request).enqueue(callback);
}
public static void postFeedback(int starRating, String compliment, String feedback, String customerId, String mechanicId, String token, Callback callback) {
String route = "/mechanicFeedback";
feedback = feedback != null ? feedback : "";
compliment = compliment != null ? compliment : "";
RequestBody requestBody = new FormBody.Builder()
.add("customerId", customerId)
.add("mechanicId", mechanicId)
.add("feedback", feedback)
.add("compliment", compliment)
.add("starRating", Integer.toString(starRating))
.build();
Request request = new Request.Builder()
.addHeader("Authorization", "Bearer " + token)
.url(getBackendURL() + route)
.post(requestBody)
.build();
client.newCall(request).enqueue(callback);
}
public static void getEstimatedDistance(double fromLongitude, double fromLatitude, double toLongitude, double toLatitude, String token, Callback callback) {
String route = "/getEstimatedDistance";
HttpUrl.Builder httpBuider = HttpUrl.parse(getBackendURL() + route).newBuilder();
httpBuider.addQueryParameter("fromLongitude", Double.toString(fromLongitude));
httpBuider.addQueryParameter("fromLatitude", Double.toString(fromLatitude));
httpBuider.addQueryParameter("toLongitude", Double.toString(toLongitude));
httpBuider.addQueryParameter("toLatitude", Double.toString(toLatitude));
Request request = new Request.Builder()
.addHeader("Authorization", "Bearer " + token)
.url(httpBuider.build())
.build();
client.newCall(request).enqueue(callback);
}
//ToDo: Configure proper certificate settings when we buy one
private static OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
Python
|
UTF-8
| 33,567 | 3.09375 | 3 |
[] |
no_license
|
import cv2
import numpy as np
import tensorflow as tf
import config
import util
############################################################################################################
# seg_gt calculation #
############################################################################################################
def anchor_rect_height_ratio(anchor, rect):
"""calculate the height ratio between anchor and rect
"""
rect_height = min(rect[2], rect[3])
anchor_height = anchor[2] * 1.0
ratio = anchor_height / rect_height
return max(ratio, 1.0 / ratio)
def is_anchor_center_in_rect(anchor, xs, ys, bbox_idx):
"""tell if the center of the anchor is in the rect represented using xs and ys and bbox_idx
"""
bbox_points = zip(xs[bbox_idx, :], ys[bbox_idx, :])
cnt = util.img.points_to_contour(bbox_points);
acx, acy, aw, ah = anchor
return util.img.is_in_contour((acx, acy), cnt)
def min_area_rect(xs, ys):
"""
Args:
xs: numpy ndarray with shape=(N,4). N is the number of oriented bboxes. 4 contains [x1, x2, x3, x4]
ys: numpy ndarray with shape=(N,4), [y1, y2, y3, y4]
Note that [(x1, y1), (x2, y2), (x3, y3), (x4, y4)] can represent an oriented bbox.
Return:
the oriented rects sorrounding the box, in the format:[cx, cy, w, h, theta].
"""
xs = np.asarray(xs, dtype = np.float32)
ys = np.asarray(ys, dtype = np.float32)
num_rects = xs.shape[0]
box = np.empty((num_rects, 5))#cx, cy, w, h, theta
for idx in range(num_rects):
points = zip(xs[idx, :], ys[idx, :])
cnt = util.img.points_to_contour(points)
rect = cv2.minAreaRect(cnt)
cx, cy = rect[0]
w, h = rect[1]
theta = rect[2]
box[idx, :] = [cx, cy, w, h, theta]
box = np.asarray(box, dtype = xs.dtype)
return box
def tf_min_area_rect(xs, ys):
return tf.py_func(min_area_rect, [xs, ys], xs.dtype)
def transform_cv_rect(rects):
"""Transform the rects from opencv method minAreaRect to our rects.
Step 1 of Figure 5 in seglink paper
In cv2.minAreaRect, the w, h and theta values in the returned rect are not convenient to use (at least for me), so
the Oriented (or rotated) Rectangle object in seglink algorithm is defined different from cv2.
Rect definition in Seglink:
1. The angle value between a side and x-axis is:
positive: if it rotates clockwisely, with y-axis increasing downwards.
negative: if it rotates counter-clockwisely.
This is opposite to cv2, and it is only a personal preference.
2. The width is the length of side taking a smaller absolute angle with the x-axis.
3. The theta value of a rect is the signed angle value between width-side and x-axis
4. To rotate a rect to horizontal direction, just rotate its width-side horizontally,
i.e., rotate it by a angle of theta using cv2 method.
(see the method rotate_oriented_bbox_to_horizontal for rotation detail)
Args:
rects: ndarray with shape = (5, ) or (N, 5).
Return:
transformed rects.
"""
only_one = False
if len(np.shape(rects)) == 1:
rects = np.expand_dims(rects, axis = 0)
only_one = True
assert np.shape(rects)[1] == 5, 'The shape of rects must be (N, 5), but meet %s'%(str(np.shape(rects)))
rects = np.asarray(rects, dtype = np.float32).copy()
num_rects = np.shape(rects)[0]
for idx in range(num_rects):
cx, cy, w, h, theta = rects[idx, ...];
#assert theta < 0 and theta >= -90, "invalid theta: %f"%(theta)
if abs(theta) > 45 or (abs(theta) == 45 and w < h):
w, h = [h, w]
theta = 90 + theta
rects[idx, ...] = [cx, cy, w, h, theta]
if only_one:
return rects[0, ...]
return rects
def rotate_oriented_bbox_to_horizontal(center, bbox):
"""
Step 2 of Figure 5 in seglink paper
Rotate bbox horizontally along a `center` point
Args:
center: the center of rotation
bbox: [cx, cy, w, h, theta]
"""
assert np.shape(center) == (2, ), "center must be a vector of length 2"
assert np.shape(bbox) == (5, ) or np.shape(bbox) == (4, ), "bbox must be a vector of length 4 or 5"
bbox = np.asarray(bbox.copy(), dtype = np.float32)
cx, cy, w, h, theta = bbox;
M = cv2.getRotationMatrix2D(center, theta, scale = 1) # 2x3
cx, cy = np.dot(M, np.transpose([cx, cy, 1]))
bbox[0:2] = [cx, cy]
return bbox
def crop_horizontal_bbox_using_anchor(bbox, anchor):
"""Step 3 in Figure 5 in seglink paper
The crop operation is operated only on the x direction.
Args:
bbox: a horizontal bbox with shape = (5, ) or (4, ).
"""
assert np.shape(anchor) == (4, ), "anchor must be a vector of length 4"
assert np.shape(bbox) == (5, ) or np.shape(bbox) == (4, ), "bbox must be a vector of length 4 or 5"
# xmin and xmax of the anchor
acx, acy, aw, ah = anchor
axmin = acx - aw / 2.0;
axmax = acx + aw / 2.0;
# xmin and xmax of the bbox
cx, cy, w, h = bbox[0:4]
xmin = cx - w / 2.0
xmax = cx + w / 2.0
# clip operation
xmin = max(xmin, axmin)
xmax = min(xmax, axmax)
# transform xmin, xmax to cx and w
cx = (xmin + xmax) / 2.0;
w = xmax - xmin
bbox = bbox.copy()
bbox[0:4] = [cx, cy, w, h]
return bbox
def rotate_horizontal_bbox_to_oriented(center, bbox):
"""
Step 4 of Figure 5 in seglink paper:
Rotate the cropped horizontal bbox back to its original direction
Args:
center: the center of rotation
bbox: [cx, cy, w, h, theta]
Return: the oriented bbox
"""
assert np.shape(center) == (2, ), "center must be a vector of length 2"
assert np.shape(bbox) == (5, ) , "bbox must be a vector of length 4 or 5"
bbox = np.asarray(bbox.copy(), dtype = np.float32)
cx, cy, w, h, theta = bbox;
M = cv2.getRotationMatrix2D(center, -theta, scale = 1) # 2x3
cx, cy = np.dot(M, np.transpose([cx, cy, 1]))
bbox[0:2] = [cx, cy]
return bbox
def cal_seg_loc_for_single_anchor(anchor, rect):
"""
Step 2 to 4
"""
# rotate text box along the center of anchor to horizontal direction
center = (anchor[0], anchor[1])
rect = rotate_oriented_bbox_to_horizontal(center, rect)
# crop horizontal text box to anchor
rect = crop_horizontal_bbox_using_anchor(rect, anchor)
# rotate the box to original direction
rect = rotate_horizontal_bbox_to_oriented(center, rect)
return rect
@util.dec.print_calling_in_short_for_tf
def match_anchor_to_text_boxes(anchors, xs, ys):
"""Match anchors to text boxes.
Return:
seg_labels: shape = (N,), the seg_labels of segments. each value is the index of matched box if >=0.
seg_locations: shape = (N, 5), the absolute location of segments. Only the match segments are correctly calculated.
"""
assert len(np.shape(anchors)) == 2 and np.shape(anchors)[1] == 4, "the anchors must be a tensor with shape = (num_anchors, 4)"
assert len(np.shape(xs)) == 2 and np.shape(xs) == np.shape(ys) and np.shape(ys)[1] == 4, "the xs, ys must be a tensor with shape = (num_bboxes, 4)"
anchors = np.asarray(anchors, dtype = np.float32)
xs = np.asarray(xs, dtype = np.float32)
ys = np.asarray(ys, dtype = np.float32)
num_anchors = anchors.shape[0]
seg_labels = np.ones((num_anchors, ), dtype = np.int32) * -1;
seg_locations = np.zeros((num_anchors, 5), dtype = np.float32)
# to avoid ln(0) in the ending process later.
# because the height and width will be encoded using ln(w_seg / w_anchor)
seg_locations[:, 2] = anchors[:, 2]
seg_locations[:, 3] = anchors[:, 3]
num_bboxes = xs.shape[0]
#represent bboxes using min area rects
rects = min_area_rect(xs, ys) # shape = (num_bboxes, 5)
rects = transform_cv_rect(rects)
assert rects.shape == (num_bboxes, 5)
#represent bboxes using contours
cnts = []
for bbox_idx in range(num_bboxes):
bbox_points = zip(xs[bbox_idx, :], ys[bbox_idx, :])
cnt = util.img.points_to_contour(bbox_points);
cnts.append(cnt)
import time
start_time = time.time()
# match anchor to bbox
for anchor_idx in range(num_anchors):
anchor = anchors[anchor_idx, :]
acx, acy, aw, ah = anchor
center_point_matched = False
height_matched = False
for bbox_idx in range(num_bboxes):
# center point check
center_point_matched = util.img.is_in_contour((acx, acy), cnts[bbox_idx])
if not center_point_matched:
continue
# height height_ratio check
rect = rects[bbox_idx, :]
height_ratio = anchor_rect_height_ratio(anchor, rect)
height_matched = height_ratio <= config.max_height_ratio
if height_matched and center_point_matched:
# an anchor can only be matched to at most one bbox
seg_labels[anchor_idx] = bbox_idx
seg_locations[anchor_idx, :] = cal_seg_loc_for_single_anchor(anchor, rect)
end_time = time.time()
tf.logging.info('Time in For Loop: %f'%(end_time - start_time))
return seg_labels, seg_locations
# @util.dec.print_calling_in_short_for_tf
def match_anchor_to_text_boxes_fast(anchors, xs, ys):
"""Match anchors to text boxes.
Return:
seg_labels: shape = (N,), the seg_labels of segments. each value is the index of matched box if >=0.
seg_locations: shape = (N, 5), the absolute location of segments. Only the match segments are correctly calculated.
"""
assert len(np.shape(anchors)) == 2 and np.shape(anchors)[1] == 4, "the anchors must be a tensor with shape = (num_anchors, 4)"
assert len(np.shape(xs)) == 2 and np.shape(xs) == np.shape(ys) and np.shape(ys)[1] == 4, "the xs, ys must be a tensor with shape = (num_bboxes, 4)"
anchors = np.asarray(anchors, dtype = np.float32)
xs = np.asarray(xs, dtype = np.float32)
ys = np.asarray(ys, dtype = np.float32)
num_anchors = anchors.shape[0]
seg_labels = np.ones((num_anchors, ), dtype = np.int32) * -1;
seg_locations = np.zeros((num_anchors, 5), dtype = np.float32)
# to avoid ln(0) in the ending process later.
# because the height and width will be encoded using ln(w_seg / w_anchor)
seg_locations[:, 2] = anchors[:, 2]
seg_locations[:, 3] = anchors[:, 3]
num_bboxes = xs.shape[0]
#represent bboxes using min area rects
rects = min_area_rect(xs, ys) # shape = (num_bboxes, 5)
rects = transform_cv_rect(rects)
assert rects.shape == (num_bboxes, 5)
# construct a bbox point map: keys are the poistion of all points in bbox contours, and
# value being the bbox index
bbox_mask = np.ones(config.image_shape, dtype = np.int32) * (-1)
for bbox_idx in range(num_bboxes):
bbox_points = zip(xs[bbox_idx, :], ys[bbox_idx, :])
bbox_cnts = util.img.points_to_contours(bbox_points)
util.img.draw_contours(bbox_mask, bbox_cnts, -1, color = bbox_idx, border_width = - 1)
points_in_bbox_mask = np.where(bbox_mask >= 0)
points_in_bbox_mask = set(zip(*points_in_bbox_mask))
points_in_bbox_mask = points_in_bbox_mask.intersection(config.default_anchor_center_set)
for point in points_in_bbox_mask:
anchors_here = config.default_anchor_map[point]
for anchor_idx in anchors_here:
anchor = anchors[anchor_idx, :]
bbox_idx = bbox_mask[point]
acx, acy, aw, ah = anchor
height_matched = False
# height height_ratio check
rect = rects[bbox_idx, :]
height_ratio = anchor_rect_height_ratio(anchor, rect)
height_matched = height_ratio <= config.max_height_ratio
if height_matched:
# an anchor can only be matched to at most one bbox
seg_labels[anchor_idx] = bbox_idx
seg_locations[anchor_idx, :] = cal_seg_loc_for_single_anchor(anchor, rect)
return seg_labels, seg_locations
############################################################################################################
# link_gt calculation #
############################################################################################################
def reshape_link_gt_by_layer(link_gt):
inter_layer_link_gts = {}
cross_layer_link_gts = {}
idx = 0;
for layer_idx, layer_name in enumerate(config.feat_layers):
layer_shape = config.feat_shapes[layer_name]
lh, lw = layer_shape
length = lh * lw * 8;
layer_link_gt = link_gt[idx: idx + length]
idx = idx + length;
layer_link_gt = np.reshape(layer_link_gt, (lh, lw, 8))
inter_layer_link_gts[layer_name] = layer_link_gt
for layer_idx in range(1, len(config.feat_layers)):
layer_name = config.feat_layers[layer_idx]
layer_shape = config.feat_shapes[layer_name]
lh, lw = layer_shape
length = lh * lw * 4;
layer_link_gt = link_gt[idx: idx + length]
idx = idx + length;
layer_link_gt = np.reshape(layer_link_gt, (lh, lw, 4))
cross_layer_link_gts[layer_name] = layer_link_gt
assert idx == len(link_gt)
return inter_layer_link_gts, cross_layer_link_gts
def reshape_labels_by_layer(labels):
layer_labels = {}
idx = 0;
for layer_name in config.feat_layers:
layer_shape = config.feat_shapes[layer_name]
label_length = np.prod(layer_shape)
layer_match_result = labels[idx: idx + label_length]
idx = idx + label_length;
layer_match_result = np.reshape(layer_match_result, layer_shape)
layer_labels[layer_name] = layer_match_result;
assert idx == len(labels)
return layer_labels;
def get_inter_layer_neighbours(x, y):
return [(x - 1, y - 1), (x, y - 1), (x + 1, y - 1), \
(x - 1, y), (x + 1, y), \
(x - 1, y + 1), (x, y + 1), (x + 1, y + 1)]
def get_cross_layer_neighbours(x, y):
return [(2 * x, 2 * y), (2 * x + 1, 2 * y), (2 * x, 2 * y + 1), (2 * x + 1, 2 * y + 1)]
def is_valid_cord(x, y, w, h):
"""
Tell whether the 2D coordinate (x, y) is valid or not.
If valid, it should be on an h x w image
"""
return x >=0 and x < w and y >= 0 and y < h;
def cal_link_labels(labels):
layer_labels = reshape_labels_by_layer(labels)
inter_layer_link_gts = []
cross_layer_link_gts = []
for layer_idx, layer_name in enumerate(config.feat_layers):
layer_match_result = layer_labels[layer_name]
h, w = config.feat_shapes[layer_name]
# initalize link groundtruth for the current layer
inter_layer_link_gt = np.ones((h, w, 8), dtype = np.int32) * (-1)
if layer_idx > 0: # no cross-layer link for the first layer.
cross_layer_link_gt = np.ones((h, w, 4), dtype = np.int32) * (-1)
for x in range(w):
for y in range(h):
# the value in layer_match_result stands for the bbox idx a segments matches
# if less than 0, not matched.
# only matched segments are considered in link_gt calculation
if layer_match_result[y, x] >= 0:
matched_idx = layer_match_result[y, x]
# inter-layer link_gt calculation
# calculate inter-layer link_gt using the bbox matching result of inter-layer neighbours
neighbours = get_inter_layer_neighbours(x, y)
for nidx, nxy in enumerate(neighbours): # n here is short for neighbour
nx, ny = nxy
if is_valid_cord(nx, ny, w, h):
n_matched_idx = layer_match_result[ny, nx]
# if the current default box has matched the same bbox with this neighbour, \
# the linkage connecting them is labeled as positive.
if matched_idx == n_matched_idx:
inter_layer_link_gt[y, x, nidx] = n_matched_idx;
# cross layer link_gt calculation
if layer_idx > 0:
previous_layer_name = config.feat_layers[layer_idx - 1];
ph, pw = config.feat_shapes[previous_layer_name]
previous_layer_match_result = layer_labels[previous_layer_name]
neighbours = get_cross_layer_neighbours(x, y)
for nidx, nxy in enumerate(neighbours):
nx, ny = nxy
if is_valid_cord(nx, ny, pw, ph):
n_matched_idx = previous_layer_match_result[ny, nx]
if matched_idx == n_matched_idx:
cross_layer_link_gt[y, x, nidx] = n_matched_idx;
inter_layer_link_gts.append(inter_layer_link_gt)
if layer_idx > 0:
cross_layer_link_gts.append(cross_layer_link_gt)
# construct the final link_gt from layer-wise data.
# note that this reshape and concat order is the same with that of predicted linkages, which\
# has been done in the construction of SegLinkNet.
inter_layer_link_gts = np.hstack([np.reshape(t, -1) for t in inter_layer_link_gts]);
cross_layer_link_gts = np.hstack([np.reshape(t, -1) for t in cross_layer_link_gts]);
link_gt = np.hstack([inter_layer_link_gts, cross_layer_link_gts])
return link_gt
# @util.dec.print_calling_in_short_for_tf
def encode_seg_offsets(seg_locs):
"""
Args:
seg_locs: a ndarray with shape = (N, 5). It contains the abolute values of segment locations
Return:
seg_offsets, i.e., the offsets from default boxes. It is used as the final segment location ground truth.
"""
anchors = config.default_anchors
anchor_cx, anchor_cy, anchor_w, anchor_h = (anchors[:, idx] for idx in range(4))
seg_cx, seg_cy, seg_w, seg_h = (seg_locs[:, idx] for idx in range(4))
#encoding using the formulations from Euqation (2) to (6) of seglink paper
# seg_cx = anchor_cx + anchor_w * offset_cx
offset_cx = (seg_cx - anchor_cx) * 1.0 / anchor_w
# seg_cy = anchor_cy + anchor_w * offset_cy
offset_cy = (seg_cy - anchor_cy) * 1.0 / anchor_h
# seg_w = anchor_w * e^(offset_w)
offset_w = np.log(seg_w * 1.0 / anchor_w)
# seg_h = anchor_w * e^(offset_h)
offset_h = np.log(seg_h * 1.0 / anchor_h)
# prior scaling can be used to adjust the loss weight of loss on offset x, y, w, h, theta
seg_offsets = np.zeros_like(seg_locs)
seg_offsets[:, 0] = offset_cx / config.prior_scaling[0]
seg_offsets[:, 1] = offset_cy / config.prior_scaling[1]
seg_offsets[:, 2] = offset_w / config.prior_scaling[2]
seg_offsets[:, 3] = offset_h / config.prior_scaling[3]
seg_offsets[:, 4] = seg_locs[:, 4] / config.prior_scaling[4]
return seg_offsets
def decode_seg_offsets_pred(seg_offsets_pred):
anchors = config.default_anchors
anchor_cx, anchor_cy, anchor_w, anchor_h = (anchors[:, idx] for idx in range(4))
offset_cx = seg_offsets_pred[:, 0] * config.prior_scaling[0]
offset_cy = seg_offsets_pred[:, 1] * config.prior_scaling[1]
offset_w = seg_offsets_pred[:, 2] * config.prior_scaling[2]
offset_h = seg_offsets_pred[:, 3] * config.prior_scaling[3]
offset_theta = seg_offsets_pred[:, 4] * config.prior_scaling[4]
seg_cx = anchor_cx + anchor_w * offset_cx
seg_cy = anchor_cy + anchor_h * offset_cy # anchor_h == anchor_w
seg_w = anchor_w * np.exp(offset_w)
seg_h = anchor_h * np.exp(offset_h)
seg_theta = offset_theta
seg_loc = np.transpose(np.vstack([seg_cx, seg_cy, seg_w, seg_h, seg_theta]))
return seg_loc
# @util.dec.print_calling_in_short_for_tf
def get_all_seglink_gt(xs, ys, ignored):
# calculate ground truths.
# for matching results, i.e., seg_labels and link_labels, the values stands for the
# index of matched bbox
assert len(np.shape(xs)) == 2 and \
np.shape(xs)[-1] == 4 and \
np.shape(ys) == np.shape(xs), \
'the shape of xs and ys must be (N, 4), but got %s and %s'%(np.shape(xs), np.shape(ys))
assert len(xs) == len(ignored), 'the length of xs and `ignored` must be the same, \
but got %s and %s'%(len(xs), len(ignored))
anchors = config.default_anchors
seg_labels, seg_locations = match_anchor_to_text_boxes_fast(anchors, xs, ys);
link_labels = cal_link_labels(seg_labels)
seg_offsets = encode_seg_offsets(seg_locations)
# deal with ignored: use -2 to denotes ignored matchings temporarily
def set_ignored_labels(labels, idx):
cords = np.where(labels == idx)
labels[cords] = -2
ignored_bbox_idxes = np.where(ignored == 1)[0]
for ignored_bbox_idx in ignored_bbox_idxes:
set_ignored_labels(link_labels, ignored_bbox_idx)
set_ignored_labels(seg_labels, ignored_bbox_idx)
# deal with bbox idxes: use 1 to replace all matched label
def set_positive_labels_to_one(labels):
cords = np.where(labels >= 0)
labels[cords] = 1
set_positive_labels_to_one(seg_labels)
set_positive_labels_to_one(link_labels)
# deal with ignored: use 0 to replace all -2
def set_ignored_labels_to_zero(labels):
cords = np.where(labels == -2)
labels[cords] = 0
set_ignored_labels_to_zero(seg_labels)
set_ignored_labels_to_zero(link_labels)
# set dtypes
seg_labels = np.asarray(seg_labels, dtype = np.int32)
seg_offsets = np.asarray(seg_offsets, dtype = np.float32)
link_labels = np.asarray(link_labels, dtype = np.int32)
return seg_labels, seg_offsets, link_labels
def tf_get_all_seglink_gt(xs, ys, ignored):
"""
xs, ys: tensors reprensenting ground truth bbox, both with shape=(N, 4), values in 0~1
"""
h_I, w_I = config.image_shape
xs = xs * w_I
ys = ys * h_I
seg_labels, seg_offsets, link_labels = tf.py_func(get_all_seglink_gt, [xs, ys, ignored], [tf.int32, tf.float32, tf.int32]);
seg_labels.set_shape([config.num_anchors])
seg_offsets.set_shape([config.num_anchors, 5])
link_labels.set_shape([config.num_links])
return seg_labels, seg_offsets, link_labels;
############################################################################################################
# linking segments together #
############################################################################################################
def group_segs(seg_scores, link_scores, seg_conf_threshold, link_conf_threshold):
"""
group segments based on their scores and links.
Return: segment groups as a list, consisting of list of segment indexes, reprensting a group of segments belonging to a same bbox.
"""
assert len(np.shape(seg_scores)) == 1
assert len(np.shape(link_scores)) == 1
valid_segs = np.where(seg_scores >= seg_conf_threshold)[0];# `np.where` returns a tuple
assert valid_segs.ndim == 1
mask = {}
for s in valid_segs:
mask[s] = -1;
def get_root(idx):
parent = mask[idx]
while parent != -1:
idx = parent
parent = mask[parent]
return idx
def union(idx1, idx2):
root1 = get_root(idx1)
root2 = get_root(idx2)
if root1 != root2:
mask[root1] = root2
def to_list():
result = {}
for idx in mask:
root = get_root(idx)
if root not in result:
result[root] = []
result[root].append(idx)
return [result[root] for root in result]
seg_indexes = np.arange(len(seg_scores))
layer_seg_indexes = reshape_labels_by_layer(seg_indexes)
layer_inter_link_scores, layer_cross_link_scores = reshape_link_gt_by_layer(link_scores)
for layer_index, layer_name in enumerate(config.feat_layers):
layer_shape = config.feat_shapes[layer_name]
lh, lw = layer_shape
layer_seg_index = layer_seg_indexes[layer_name]
layer_inter_link_score = layer_inter_link_scores[layer_name]
if layer_index > 0:
previous_layer_name = config.feat_layers[layer_index - 1]
previous_layer_seg_index = layer_seg_indexes[previous_layer_name]
previous_layer_shape = config.feat_shapes[previous_layer_name]
plh, plw = previous_layer_shape
layer_cross_link_score = layer_cross_link_scores[layer_name]
for y in range(lh):
for x in range(lw):
seg_index = layer_seg_index[y, x]
_seg_score = seg_scores[seg_index]
if _seg_score >= seg_conf_threshold:
# find inter layer linked neighbours
inter_layer_neighbours = get_inter_layer_neighbours(x, y)
for nidx, nxy in enumerate(inter_layer_neighbours):
nx, ny = nxy
# the condition of connecting neighbour segment: valid coordinate,
# valid segment confidence and valid link confidence.
if is_valid_cord(nx, ny, lw, lh) and \
seg_scores[layer_seg_index[ny, nx]] >= seg_conf_threshold and \
layer_inter_link_score[y, x, nidx] >= link_conf_threshold:
n_seg_index = layer_seg_index[ny, nx]
union(seg_index, n_seg_index)
# find cross layer linked neighbours
if layer_index > 0:
cross_layer_neighbours = get_cross_layer_neighbours(x, y)
for nidx, nxy in enumerate(cross_layer_neighbours):
nx, ny = nxy
if is_valid_cord(nx, ny, plw, plh) and \
seg_scores[previous_layer_seg_index[ny, nx]] >= seg_conf_threshold and \
layer_cross_link_score[y, x, nidx] >= link_conf_threshold:
n_seg_index = previous_layer_seg_index[ny, nx]
union(seg_index, n_seg_index)
return to_list()
############################################################################################################
# combining segments to bboxes #
############################################################################################################
def tf_seglink_to_bbox(seg_cls_pred, link_cls_pred, seg_offsets_pred, image_shape,
seg_conf_threshold = None, link_conf_threshold = None):
if len(seg_cls_pred.shape) == 3:
assert seg_cls_pred.shape[0] == 1 # only batch_size == 1 supported now TODO
seg_cls_pred = seg_cls_pred[0, ...]
link_cls_pred = link_cls_pred[0, ...]
seg_offsets_pred = seg_offsets_pred[0, ...]
image_shape = image_shape[0, :]
assert seg_cls_pred.shape[-1] == 2
assert link_cls_pred.shape[-1] == 2
assert seg_offsets_pred.shape[-1] == 5
seg_scores = seg_cls_pred[:, 1]
link_scores = link_cls_pred[:, 1]
image_bboxes = tf.py_func(seglink_to_bbox,
[seg_scores, link_scores, seg_offsets_pred, image_shape, seg_conf_threshold, link_conf_threshold],
tf.float32);
return image_bboxes
def seglink_to_bbox(seg_scores, link_scores, seg_offsets_pred,
image_shape = None, seg_conf_threshold = None, link_conf_threshold = None):
"""
Args:
seg_scores: the scores of segments being positive
link_scores: the scores of linkage being positive
seg_offsets_pred
Return:
bboxes, with shape = (N, 5), and N is the number of predicted bboxes
"""
seg_conf_threshold = seg_conf_threshold or config.seg_conf_threshold
link_conf_threshold = link_conf_threshold or config.link_conf_threshold
if image_shape is None:
image_shape = config.image_shape
seg_groups = group_segs(seg_scores, link_scores, seg_conf_threshold, link_conf_threshold);
seg_locs = decode_seg_offsets_pred(seg_offsets_pred)
bboxes = []
ref_h, ref_w = config.image_shape
for group in seg_groups:
group = [seg_locs[idx, :] for idx in group]
bbox = combine_segs(group)
image_h, image_w = image_shape[0:2]
scale = [image_w * 1.0 / ref_w, image_h * 1.0 / ref_h, image_w * 1.0 / ref_w, image_h * 1.0 / ref_h, 1]
bbox = np.asarray(bbox) * scale
bboxes.append(bbox)
bboxes = bboxes_to_xys(bboxes, image_shape)
return np.asarray(bboxes, dtype = np.float32)
def sin(theta):
return np.sin(theta / 180.0 * np.pi)
def cos(theta):
return np.cos(theta / 180.0 * np.pi)
def tan(theta):
return np.tan(theta / 180.0 * np.pi)
def combine_segs(segs, return_bias = False):
segs = np.asarray(segs)
assert segs.ndim == 2
assert segs.shape[-1] == 5
if len(segs) == 1:
return segs[0, :]
# find the best straight line fitting all center points: y = kx + b
cxs = segs[:, 0]
cys = segs[:, 1]
## the slope
bar_theta = np.mean(segs[:, 4])# average theta
k = tan(bar_theta);
## the bias: minimize sum (k*x_i + b - y_i)^2
### let c_i = k*x_i - y_i
### sum (k*x_i + b - y_i)^2 = sum(c_i + b)^2
### = sum(c_i^2 + b^2 + 2 * c_i * b)
### = n * b^2 + 2* sum(c_i) * b + sum(c_i^2)
### the target b = - sum(c_i) / n = - mean(c_i) = mean(y_i - k * x_i)
b = np.mean(cys - k * cxs)
# find the projections of all centers on the straight line
## firstly, move both the line and centers upward by distance b, so as to make the straight line crossing the point(0, 0): y = kx
## reprensent the line as a vector (1, k), and the projection of vector(x, y) on (1, k) is: proj = (x + k * y) / sqrt(1 + k^2)
## the projection point of (x, y) on (1, k) is (proj * cos(theta), proj * sin(theta))
t_cys = cys - b
projs = (cxs + k * t_cys) / np.sqrt(1 + k**2)
proj_points = np.transpose([projs * cos(bar_theta), projs * sin(bar_theta)])
# find the max distance
max_dist = -1;
idx1 = -1;
idx2 = -1;
for i in range(len(proj_points)):
point1 = proj_points[i, :]
for j in range(i + 1, len(proj_points)):
point2 = proj_points[j, :]
dist = np.sqrt(np.sum((point1 - point2) ** 2))
if dist > max_dist:
idx1 = i
idx2 = j
max_dist = dist
assert idx1 >= 0 and idx2 >= 0
# the bbox: bcx, bcy, bw, bh, average_theta
seg1 = segs[idx1, :]
seg2 = segs[idx2, :]
bcx, bcy = (seg1[:2] + seg2[:2]) / 2.0
bh = np.mean(segs[:, 3])
bw = max_dist + (seg1[2] + seg2[2]) / 2.0
if return_bias:
return bcx, bcy, bw, bh, bar_theta, b# bias is useful for debugging.
else:
return bcx, bcy, bw, bh, bar_theta
def bboxes_to_xys(bboxes, image_shape):
"""Convert Seglink bboxes to xys, i.e., eight points
The `image_shape` is used to to make sure all points return are valid, i.e., within image area
"""
if len(bboxes) == 0:
return []
assert np.ndim(bboxes) == 2 and np.shape(bboxes)[-1] == 5, 'invalid `bboxes` param with shape = ' + str(np.shape(bboxes))
h, w = image_shape[0:2]
def get_valid_x(x):
if x < 0:
return 0
if x >= w:
return w - 1
return x
def get_valid_y(y):
if y < 0:
return 0
if y >= h:
return h - 1
return y
xys = np.zeros((len(bboxes), 8))
for bbox_idx, bbox in enumerate(bboxes):
bbox = ((bbox[0], bbox[1]), (bbox[2], bbox[3]), bbox[4])
#points = cv2.cv.BoxPoints(bbox)
points = cv2.boxPoints(bbox)
points = np.int0(points)
for i_xy, (x, y) in enumerate(points):
x = get_valid_x(x)
y = get_valid_y(y)
points[i_xy, :] = [x, y]
points = np.reshape(points, -1)
xys[bbox_idx, :] = points
return xys
|
SQL
|
UTF-8
| 1,157 | 4.03125 | 4 |
[] |
no_license
|
CREATE DEFINER=`administrator`@`localhost` FUNCTION `is_active`(DID INT) RETURNS tinyint(1)
BEGIN
-- Check if deal is active, returning 1 if true or 0 if false.
-- Select Deal Type then check if active based on whether deal is recurring or limited.
SELECT bdv.deal_type into @type
FROM business_deals_view bdv
WHERE bdv.deal_id = DID LIMIT 1;
SET @is_active = 0;
IF @type = 'Recurring' THEN
SET @weekday = DAYNAME(CURRENT_DATE());
SELECT bdv.deal_start_time, bdv.deal_end_time
into @start, @end
FROM business_deals_view bdv
WHERE bdv.deal_id = DID
AND bdv.deal_weekday = @weekday;
IF (CURRENT_TIME() BETWEEN @start and @end) THEN
SET @is_active = 1;
ELSE
SET @is_active = 0;
END IF;
ELSEIF @type = 'Limited' THEN
SET @is_active = 0;
SELECT bdv.deal_start_date, bdv.deal_end_date
into @startDate, @endDate
FROM business_deals_view bdv
WHERE bdv.deal_id = DID;
IF (CURRENT_TIMESTAMP() BETWEEN @startDate and @endDate) THEN
SET @is_active = 1;
ELSE
SET @is_active = 0;
END IF;
ELSE
SET @is_active = 0;
END IF;
RETURN @is_active;
END
|
Java
|
UTF-8
| 1,083 | 2.390625 | 2 |
[] |
no_license
|
package com.ifc.myelinflow.dto;
import java.io.Serializable;
import java.util.Objects;
import java.util.Set;
public class SourceSchemas implements Serializable {
private String key;
private Set<String> schemas;
public SourceSchemas(String key, Set<String> schemas) {
this.key = key;
this.schemas = schemas;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Set<String> getSchemas() {
return schemas;
}
public void setSchemas(Set<String> schemas) {
this.schemas = schemas;
}
@Override
public String toString() {
return schemas.toString().replaceAll("(\\[|\\])", "");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SourceSchemas that = (SourceSchemas) o;
return Objects.equals(key, that.key);
}
@Override
public int hashCode() {
return Objects.hash(key);
}
}
|
C#
|
UTF-8
| 991 | 2.625 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraRotate : MonoBehaviour
{
private enum RotationAxis
{
MouseX = 1,
MouseY = 2
}
[SerializeField] private RotationAxis axis = RotationAxis.MouseX;
private float minimumVert = -90f;
private float maximumVert = 90f;
private float sensHorizontal = 10.0f;
private float sensVertical = 10.0f;
private float rotationX = 0;
void Update()
{
if(axis == RotationAxis.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensHorizontal, 0);
}
else if(axis == RotationAxis.MouseY)
{
rotationX -= Input.GetAxis("Mouse Y") * sensVertical;
rotationX = Mathf.Clamp(rotationX, minimumVert, maximumVert);
float rotationY = transform.localEulerAngles.y;
transform.localEulerAngles = new Vector3(rotationX, rotationY, 0);
}
}
}
|
JavaScript
|
UTF-8
| 444 | 3.28125 | 3 |
[] |
no_license
|
var http = require('http');
var underscore = require('underscore');
//variable declaration
var num = [1, 2, 3];
var newNum = [];
var server = http.createServer(function (request, response) {
response.writeHead(200, { "content-type": "text/plain" });
underscore.map(num, function(num){
newNum.push(num * 3);
});
console.log("Numbers are " + newNum);
response.end("Numbers are " + newNum);
});
server.listen(3000);
|
JavaScript
|
UTF-8
| 2,554 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
const path = require('path');
const fs = require('fs-extra-promise');
const matchAll = require('string.prototype.matchall');
const baseDir = path.join(__dirname, 'src');
const selectedFiles = [];
const processFile = async function(filePath) {
const stats = await fs.statAsync(filePath);
if(stats.isDirectory()) {
const files = await fs.readdirAsync(filePath);
for(const file of files) {
await processFile(path.join(filePath, file));
}
} else if(['.js', '.ts', '.html'].includes(path.extname(filePath).toLowerCase())) {
selectedFiles.push(filePath);
}
};
const functionPatt = /Localize\.text\('(.+?)',\s*?'(.+?)'/g;
const componentPatt0 = /<Localize\s+context="(.+?)"\s+key=["'](.+?)["']>/g;
const componentPatt1 = /<Localize\s+key=["'](.+?)["']\s+context="(.+?)">/g;
(async function() {
try {
const locale = 'en';
const matches = [];
await processFile(baseDir);
for(const file of selectedFiles) {
let contents = await fs.readFileAsync(file, 'utf8');
contents = contents.replace(/\\'/g, `'`);
[...matchAll(contents, functionPatt)]
.filter(arr => arr.length > 1)
.reduce((arr, a) => {
return [...arr, a.slice(1, 3)];
}, [])
.forEach(([ key, context ]) => matches.push({ key, context }));
[...matchAll(contents, componentPatt0)]
.filter(arr => arr.length > 1)
.reduce((arr, a) => {
return [...arr, a.slice(1, 3)];
}, [])
.forEach(([ context, key ]) => matches.push({ key: key.replace(/\\/g, ''), context}));
[...matchAll(contents, componentPatt1)]
.filter(arr => arr.length > 1)
.reduce((arr, a) => {
return [...arr, a.slice(1, 3)];
}, [])
.forEach(([ key, context ]) => matches.push({ key: key.replace(/\\/g, ''), context}));
}
const localeData = {
locale
};
for(const { key, context } of matches) {
if(localeData[key]) {
localeData[key] = {
...localeData[key],
[context]: {
val: key,
note: ''
}
};
} else {
localeData[key] = {
[context]: {
val: key,
note: ''
}
};
}
}
const json = JSON.stringify(localeData, null, ' ');
console.log(json);
const localesDir = path.join(__dirname, 'locales');
await fs.ensureDirAsync(localesDir);
await fs.writeFileAsync(path.join(localesDir, locale + '.json'), json);
} catch(err) {
console.error(err);
}
})();
|
Python
|
UTF-8
| 1,245 | 2.78125 | 3 |
[] |
no_license
|
import random
from Items import *
from Classes import *
def Online_Combat(AtkPlayer, DefPlayer, skill):
if skill != "melee" and skill != "magic" and skill != "range":
#if skill != 0:
if AtkPlayer.skilltree[skill][4] == 0:
return random.randint(int(AtkPlayer.skilltree[skill][0]/3), int(AtkPlayer.skilltree[skill][0]))
elif AtkPlayer.skilltree[skill][4] == 1:
"""
while target != "ally" or target != "self":
print "Do you want to target yourself or ally?"
print "1.) Self"
print "2.) Ally"
if target == "1":
target = "self"
elif target == "2":
target = "ally"
target = raw_input('>>> ')
target.health += skill(1)
"""
PlayerIG.health += AtkPlayer.skilltree[skill][1]
#elif skill(4) == 2:
# PlayerIG.health += skill(1)
elif skill == "melee":
return random.randint(int(AtkPlayer.attack)/3, AtkPlayer.attack)
elif skill == "magic":
pass
else:
pass
#return random.randint(int(AtkPlayer.attack/3), AtkPlayer.attack)
#target = 3 && 4
#damage = 0
|
C++
|
UTF-8
| 3,230 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
/*
* Copyright (C) 2012-2014 Alexey Shcherbakov
* Copyright (C) 2014-2015 Matt Broadstone
* Contact: https://github.com/mbroadst/qamqp
*
* This file is part of the QAMQP Library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
#include "qamqpqueue.h"
#include "qamqpexchange.h"
#include "qamqpchannelhash_p.h"
/*!
* Retrieve a pointer to the named channel.
*
* A NULL string is assumed to be equivalent to "" for the purpose
* of retrieving the nameless (default) exchange.
*
* \param[in] name The name of the channel to retrieve.
* \retval NULL Channel does not exist.
*/
QAmqpChannel* QAmqpChannelHash::get(const QString& name) const
{
if (name.isEmpty())
return m_channels.value(QString());
return m_channels.value(name);
}
QStringList QAmqpChannelHash::channels() const
{
return m_channels.keys();
}
/*!
* Return true if the named channel exists.
*/
bool QAmqpChannelHash::contains(const QString& name) const
{
if (name.isEmpty())
return m_channels.contains(QString());
return m_channels.contains(name);
}
/*!
* Store an exchange in the hash. The nameless exchange is stored under
* the name "".
*/
void QAmqpChannelHash::put(QAmqpExchange* exchange)
{
if (exchange->name().isEmpty())
put(QString(), exchange);
else
put(exchange->name(), exchange);
}
/*!
* Store a queue in the hash. If the queue is nameless, we hook its
* declared signal and store it when the queue receives a name from the
* broker, otherwise we store it under the name given.
*/
void QAmqpChannelHash::put(QAmqpQueue* queue)
{
if (queue->name().isEmpty())
connect(queue, SIGNAL(declared()), this, SLOT(queueDeclared()));
else
put(queue->name(), queue);
}
/*!
* Handle destruction of a channel. Do a full garbage collection run.
*/
void QAmqpChannelHash::channelDestroyed(QObject* object)
{
QList<QString> names(m_channels.keys());
QList<QString>::iterator it;
for (it = names.begin(); it != names.end(); it++) {
if (m_channels.value(*it) == object)
m_channels.remove(*it);
}
}
/*!
* Handle a queue that has just been declared and given a new name. The
* caller is assumed to be a QAmqpQueue instance.
*/
void QAmqpChannelHash::queueDeclared()
{
QAmqpQueue *queue = qobject_cast<QAmqpQueue*>(sender());
if (queue)
put(queue);
}
/*!
* Store a channel in the hash. The channel is assumed
* to be named at the time of storage. This hooks the 'destroyed' signal
* so the channel can be removed from our list.
*/
void QAmqpChannelHash::put(const QString& name, QAmqpChannel* channel)
{
connect(channel, SIGNAL(destroyed(QObject*)), this, SLOT(channelDestroyed(QObject*)));
m_channels[name] = channel;
}
/* vim: set ts=4 sw=4 et */
|
C
|
UTF-8
| 1,403 | 3.296875 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <time.h>
#include <omp.h>
#include <stdlib.h>
// generate a random between low to high inclusive
int generateRandom(int low, int high)
{
int n = high - low + 1;
int rd = rand();
int ret = rd%n + low;
return ret;
}
int main(int argc, char *argv[])
{
srand((unsigned int)time(NULL));
// generate random threads
// int nIteration = generateRandom(10, 100);
// int nThreads = generateRandom(3, 15);
// int nChunk = generateRandom(3, 15);
int nIteration = random() % 91 + 10;
int nThreads = random() % 13 + 3;
int nChunk = random() % 13 + 3;
// record that each number is allocated to which thread
int arr[nIteration];
// display 3 random imformation
printf("Iterations: %d\n", nIteration);
printf("Threads: %d\n", nThreads);
printf("Chunk: %d\n", nChunk);
// schedule thread
#pragma omp parallel for num_threads(nThreads) schedule(static, nChunk)
for (int i = 0; i < nIteration; i++)
{
int id = omp_get_thread_num();
arr[i] = id;
}
// show the allocate information
for (int id = 0; id < nThreads; id++)
{
printf("Thread %d ", id);
for (int i = 0; i < nIteration; i++)
{
if (arr[i] == id)
{
printf("%2d, ", i);
}
}
printf("\n");
}
return 0;
}
|
JavaScript
|
UTF-8
| 924 | 2.703125 | 3 |
[] |
no_license
|
import React, { PureComponent,createRef,forwardRef } from "react";
class Home extends PureComponent {
render() {
return <div>
<h2>Home</h2>
</div>;
}
}
const EnhanceAbout = forwardRef(
function(props,ref){
return(
<p ref={ref}>About</p>
)
}
)
export default class App extends PureComponent {
constructor(props){
super(props);
this.titleRef = createRef()
this.titleEle = createRef()
this.aboutRef = createRef()
}
render() {
return (
<div>
<h2 ref = {this.titleRef}>hello World</h2>
<Home ref = {this.titleEle}/>
<EnhanceAbout ref={this.aboutRef} />
<button onClick={e => this.printRef()}>打印</button>
</div>
);
}
printRef(){
console.log(this.titleRef.current)
console.log(this.titleEle.current);
console.log(this.aboutRef.current);
}
}
|
Python
|
UTF-8
| 2,273 | 2.921875 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
"""Script for Tkinter GUI chat client."""
import socket
from socket import AF_INET, SOCK_STREAM
from threading import Thread
from tkinter import *
firstclick = True
def on_entry_click(event):
"""function that gets called whenever entry1 is clicked"""
global firstclick
if firstclick: # if this is the first time they clicked it
firstclick = False
entry_field.delete(0, "end") # delete all the text in the entry
def receive():
"""Handles receiving of messages."""
while True:
try:
msg = client_socket.recv(BUFSIZ).decode("utf8")
msg_list.insert(END, msg)
except OSError: # Possibly client has left the chat.
break
def send(event=None): # event is passed by binders.
"""Handles sending of messages."""
msg = my_msg.get()
my_msg.set("") # Clears input field.
client_socket.send(bytes(msg, "utf8"))
if msg == "{quit}":
client_socket.close()
root.quit()
def on_closing(event=None):
"""This function is to be called when the window is closed."""
my_msg.set("{quit}")
send()
root = Tk()
root.title("ChatIO")
messages_frame = Frame(root)
my_msg = StringVar() # For the messages to be sent.
my_msg.set("Type your messages here.")
scrollbar = Scrollbar(messages_frame) # To navigate through past messages.
# Following will contain the messages.
msg_list = Listbox(messages_frame, height=15, width=50, yscrollcommand=scrollbar.set)
scrollbar.pack(side=RIGHT, fill=Y)
msg_list.pack(side=LEFT, fill=BOTH)
msg_list.pack()
messages_frame.pack()
entry_field = Entry(root, textvariable=my_msg)
entry_field.bind('<FocusIn>', on_entry_click)
entry_field.bind("<Return>", send)
entry_field.pack()
send_button = Button(root, text="Send", command=send)
send_button.pack()
root.protocol("WM_DELETE_WINDOW", on_closing)
#----Socket code----
HOST = input('Enter host: ')
PORT = input('Enter port: ')
if not PORT:
PORT = 33002
else:
PORT = int(PORT)
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket.socket(AF_INET, SOCK_STREAM)
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
client_socket.connect(ADDR)
receive_thread = Thread(target=receive)
receive_thread.start()
root.mainloop()
|
C#
|
UTF-8
| 1,510 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace BuildsAppReborn.Infrastructure
{
public static class HttpRequestHelper
{
#region Public Static Methods
public static async Task<HttpResponseMessage> GetRequestResponse(String url, ICredentials credentials)
{
using (var handler = new HttpClientHandler())
{
handler.Credentials = credentials;
using (var client = new HttpClient(handler))
{
return await client.GetAsync(url);
}
}
}
public static async Task<HttpResponseMessage> GetRequestResponse(String url, String personalAccessToken)
{
using (var client = new HttpClient())
{
AddAccessTokenToHeader(personalAccessToken, client);
return await client.GetAsync(url);
}
}
#endregion
#region Private Static Methods
private static void AddAccessTokenToHeader(String personalAccessToken, HttpClient client)
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($":{personalAccessToken}")));
}
#endregion
}
}
|
JavaScript
|
UTF-8
| 978 | 2.515625 | 3 |
[] |
no_license
|
/**
* Created by Matt on 4/14/2016.
*/
var SchedulerProcess1 = function(counter)
{
switch(counter)
{
case 0:
console.log("case 0 Processes 1");
OS.FS.create("file", "file Content");
//this.program_counter++;
break;
case 1:
console.log("case 1 Processes 1");
OS.FS.create("file", "file Content");
//this.program_counter++;
break;
case 2:
console.log("case 2 Processes 1");
OS.FS.create("file", "file Content");
//this.program_counter++;
break;
case 3:
console.log("case 3 Processes 1");
OS.FS.create("file", "file Content");
//this.program_counter++;
break;
default:
this.state = "Stop";
this.program_counter = 0;
}
};
Processes.listOfProcesses.push(new Process("SchedulerProcess1",SchedulerProcess1));
|
PHP
|
UTF-8
| 2,777 | 2.5625 | 3 |
[] |
no_license
|
<?php
session_start();
if (isset($_GET['deleteId'])) {
$id= $_GET['deleteId'];
include_once("../const/mysqli-connection.php");
$query = "DELETE FROM interviews WHERE id =$id";
$result = mysqli_query($dbConnection, $query);
if ($result==true) {
$_SESSION['interview-delete-success'] = '
<div class="alert container alert-success alert-dismissible fade show">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Interview Deleted SuccessFully!</strong>
</div>
';
header("location: interviews.php");
}
}
if (isset($_POST['update-interview'])) {
$updateDate = $_POST['date'];
$updateTIme = $_POST['time'];
echo $updateDate.$updateTIme;
include_once("../const/mysqli-connection.php");
$updateQuery = "UPDATE interviews SET date = '$updateDate', time= '$updateTIme'";
$updateResult = mysqli_query($dbConnection,$updateQuery);
if ($updateResult==true) {
$_SESSION['interview-update-success'] = '
<div class="alert container alert-success alert-dismissible fade show">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Interview Updated SuccessFully!</strong>
</div>
';
header("location: interviews.php");
}
}
if (isset($_POST['add-interview'])) {
include_once("../const/mysqli-connection.php");
$companyId = $_POST['companyId'];
$studentId = $_POST['studentId'];
$interviewDate = $_POST['date'];
$interviewTime = $_POST['time'];
// print_r($studentId.$companyId.$interviewDate.$interviewTime);
// die();
$addQuery = "INSERT INTO interviews (student_id,company_id,date,time) Values($studentId,$companyId,'$interviewDate','$interviewTime')";
$addResult = mysqli_query($dbConnection,$addQuery);
if ($addResult==true) {
// SET APPROVED APPLICATIONS STATE TO 1
$approvedQuery = "UPDATE applications SET is_accepted = 1 WHERE applications.student_id = $studentId AND applications.company_id = $companyId";
$approvedResult = mysqli_query($dbConnection, $approvedQuery);
if ($approvedResult=true) {
header("location: index.php");
}
$_SESSION['interview-add-success'] = '
<div class="alert container alert-success alert-dismissible fade show">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Interview Add SuccessFully!</strong>
</div>
';
header("location: interviews.php");
}
}
?>
|
Python
|
UTF-8
| 2,118 | 2.75 | 3 |
[] |
no_license
|
from django.db import models
from search.models import *
from account.models import *
def put_offer(offer):
'''Put offer in table of offers, and update table of users
'''
# create offer
new_offer = Offer(**offer)
# put in table of offers
new_offer.save()
course = offer['course']
book = Book.objects.get(isbn=new_offer.isbn)
if not course in book.course_list:
if book.course_list:
book.course_list = book.course_list + ' ' + course
else:
book.course_list = course
book.save()
return new_offer.id
def get_offer_info(offer_id):
# get info of offer with given id
# FILTER
qset = Offer.objects.filter(id=offer_id)
for object in qset:
offer = { 'course':object.course, 'seller_id': object.seller_id, 'price':object.price, 'condition':object.condition, 'description':object.description, 'isbn':object.isbn }
return offer
return None
def put_auction(auction):
'''Put an auction in table of auctions, and update table of users
'''
import time
from datetime import datetime
pattern = '%m/%d/%y %H:%M'
epoch = int(time.mktime(time.strptime(auction['end_time'], pattern)))
auction['epoch'] = epoch
new_auction = Auction(**auction)
new_auction.save()
course = auction['course']
book = Book.objects.get(isbn=new_auction.isbn)
if not course in book.course_list:
if book.course_list:
book.course_list = book.course_list + ' ' + course
else:
book.course_list = course
book.save()
return new_auction.id
def get_auction_info(auction_id):
''''Get auction info given auction_id
'''
qset = Auction.objects.filter(id=auction_id)
for object in qset:
auction = { 'course':object.course, 'seller_id': object.seller_id, 'current_price':object.current_price, 'buy_now_price':object.buy_now_price, 'end_time':object.end_time,
'condition':object.condition, 'description':object.description, 'isbn':object.isbn }
return auction
return None
|
C++
|
UTF-8
| 10,021 | 3.765625 | 4 |
[] |
no_license
|
/**
* Howon Kim
* CIS 22C
* List.cpp
*/
#include <iostream>
#include <cstdlib>
#include "List.h"
using namespace std;
/*
//**************************************************
// Constructor *
// Initialize the fields inside the list class *
//**************************************************
template <class listitem>
List<listitem>::List(): size(0), first(NULL), last(NULL), current(NULL){};
//**************************************************
// Destructor *
// Free object's resources *
//**************************************************
template <class listitem>
List<listitem>::~List()
{
while (first)
{
Nodeptr move = first;
first = first->nextnode;
delete move;
}
}
//**************************************************
// Copy Constructor *
// Initializes list to have the same *
// elements as another list *
//**************************************************
template <class listitem>
List<listitem>::List(const listitem &list)
{
Nodeptr move = first;
Nodeptr move2 = list.first;
while(move != NULL)
{
move2 = move;
move = move->nextnode;
move2 = move2->nextnode;
}
size = list.size;
}
//**************************************************
// Get the first data of the node *
//**************************************************
template <class listitem>
listitem List<listitem>::get_first()
{
if (is_empty())
{
cout << "get_first(): List is empty. No first element." << endl;
exit(-1);
}
else
{
return first -> data;
}
}
//**************************************************
// Get the last data of the node *
//**************************************************
template <class listitem>
listitem List<listitem>::get_last()
{
if (is_empty())
{
cout << "get_last(): List is empty. No last element." << endl;
exit(-1);
}
else
{
return last -> data;
}
}
//**************************************************
// Returns the element pointed to by the iterator *
//**************************************************
template <class listitem>
listitem List<listitem>::get_current()
{
if (is_empty())
{
cout << "get_current() : List is empty. No current element." << endl;
exit(-1);
}
else if(off_end())
{
cout << "get_current() : Iterator is off the end of the List" << endl;
exit(-1);
}
else
{
return current -> data;
}
}
//**************************************************
// It check the node is empty or not *
// If the list is empty it returns true, else false*
//**************************************************
template <class listitem>
bool List<listitem>::is_empty()
{
if (size == 0)
return 1;
else
return 0;
}
//**************************************************
// It check the current pointer is null or not *
//**************************************************
template <class listitem>
bool List<listitem>::off_end()
{
if (current == NULL)
return 1;
else
return 0;
}
//**************************************************
// Return the length of the list *
//**************************************************
template <class listitem>
int List<listitem>::get_size()
{
int size = 0;
Nodeptr move = first;
while(move != NULL)
{
move = move->nextnode;
size++;
}
return size;
}
//**************************************************
// Move the iterator to the first data of the node *
//**************************************************
template <class listitem>
void List<listitem>::begin()
{
if (is_empty())
{
cout << "begin() : List is empty. There is no first Data." << endl;
exit(-1);
}
current = first;
}
//**************************************************
// Inserts a new element into the list in the *
// position after the iterator *
//**************************************************
template <class listitem>
void List<listitem>::insert_current(listitem data)
{
Nodeptr newNode = new Node(data);
if (is_empty())
{
cout << "insert_current(): List is empty. No current element." << endl;
exit(-1);
}
else if (off_end())
{
cout << "insert_current(): Current is Null" << endl;
exit(-1);
}
// EDGE CASE : IF CURRENT IS END OF THE LIST
else if (current == last)
{
current -> nextnode = newNode;
newNode -> previousnode = current;
newNode -> nextnode = NULL;
last = newNode;
}
else
{
newNode -> nextnode = current -> nextnode;
current -> nextnode -> previousnode = newNode;
current -> nextnode = newNode;
newNode -> previousnode = current;
}
size++;
}
//**************************************************
// Remove the last data of the node *
//**************************************************
template <class listitem>
void List<listitem>::remove_last()
{
if (is_empty())
{
cout << "remove_last(): List is empty. No first element." << endl;
exit(-1);
}
else
{
Nodeptr temp = last->previousnode;
delete last;
if(temp != NULL)
{
last = temp;
last -> nextnode = NULL;
}
else
last = NULL;
}
--size;
}
//**************************************************
// Remove the first data of the node *
//**************************************************
template <class listitem>
void List<listitem>::remove_first()
{
if (is_empty())
{
cout << "remove_first(): List is empty. No first element." << endl;
exit(-1);
}
else
{
Nodeptr temp = first->nextnode;
delete first;
if(temp != NULL)
{
first = temp;
first->previousnode = NULL;
}
else
first = NULL;
}
size--;
}
//**************************************************
// Add a new Node to the very end of the list *
//**************************************************
template <class listitem>
void List<listitem>::insert_last(listitem data)
{
if (is_empty())
{
Nodeptr newNode = new Node(data);
first = last = newNode;
}
else
{
Nodeptr newNode = new Node(data);
last -> nextnode = newNode;
newNode -> previousnode = last;
last = newNode;
}
size++;
}
//**************************************************
// Add a new Node to the very front of the list *
//**************************************************
template <class listitem>
void List<listitem>::insert_first(listitem data)
{
if (is_empty())
{
Nodeptr newNode = new Node(data);
first = last = newNode;
}
else
{
Nodeptr newNode = new Node(data);
newNode->nextnode = first;
first -> previousnode = newNode;
first = newNode;
}
size++;
}
//**************************************************
// removes the element currently pointed to by the *
// iterator *
//**************************************************
template <class listitem>
void List<listitem>::delete_current()
{
if (off_end())
{
cout << "delete_current(): Current is NULL" << endl;
exit(-1);
}
else
{
//Remove First
if(current == first)
{
remove_first();
}
//Remove_last
else if(current == last)
{
remove_last();
}
else
{
Nodeptr temp1 = current -> previousnode;
Nodeptr temp2 = current -> nextnode;
temp1 -> nextnode = temp2;
temp2 -> previousnode = temp1;
delete current;
current = NULL; //VERY IMPORTANT
}
}
size--;
}
//**************************************************
// Moves the iterator forward by one element *
// in the list *
//**************************************************
template <class listitem>
void List<listitem>::scroll()
{
if(is_empty())
{
cout << "scroll() : Node is empty" << endl;
exit(-1);
}
else if(off_end())
{
cout << "scroll() : Current is NULL" << endl;
exit(-1);
}
else
current = current -> nextnode;
}
//**************************************************
// Display the list of the nodes *
//**************************************************
template <class listitem>
void List<listitem>::print()
{
Nodeptr move = first;
while (move != NULL)
{
cout << move -> data
<< " ";
move = move -> nextnode;
}
cout << endl;
}
//**************************************************
// Tests two lists to determine whether *
// their contents are equal *
//**************************************************
template <class listitem>
bool List<listitem>::operator==(const List& list)
{
if(size != list.size)
return false;
current = first;
Nodeptr temp = list.first;
while(current != NULL)
{
if(current->data != temp->data)
return false;
temp = temp->nextnode;
current = current->nextnode;
}
return true;
}
*/
|
Markdown
|
UTF-8
| 8,208 | 2.625 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Sola V2
A simple golang web framwork based middleware.
+ [Change Log](./CHANGELOG.md)
## 内部错误(无法修复)
+ v2.1.0 & v2.1.1 内部版本号变量误标记为 `2.0.0`
## Quick Start
基本的 sola 程序 (Hello World) 如下:
```go
package main
import (
"net/http"
"github.com/ddosakura/sola/v2"
)
// handler
func hw(c sola.Context) error {
// 输出 Hello World
return c.String(http.StatusOK, "Hello World")
}
func main() {
// 将 handler 包装为中间件
m := sola.Handler(hw).M()
// 使用中间件
sola.Use(m)
// 监听 127.0.0.1:3000
sola.ListenKeep("127.0.0.1:3000")
}
```
## Hot Update
```bash
# 安装
go get -u -v github.com/ddosakura/sola/v2/cli/sola-hot
# 在开发目录执行
sola-hot
```
执行 `sola-hot` 进行热更新,运行过程中将生成临时可执行文件 `sola-dev`。
linux 系统使用 `sola-linux` 监听端口可实现平滑切换(不中断请求)。
```go
import (
linux "github.com/ddosakura/sola/v2/extension/sola-linux"
)
linux.Listen("127.0.0.1:3000", app)
linux.Keep()
```
## Extension
+ hot 动态模块加载(使用了 plugin,仅 linux 可用)
+ sola-linux 平滑切换(使用了大量系统调用,仅 linux 可用)
### More Example
+ [Example 仓库地址](https://github.com/it-repo/box-example)
## 废弃说明
即将废弃的中间件/方法会在注释中标注 `@deprecated`
## About Reader
Reader 可简化 Request 的读取:
```go
var a ReqLogin
if err := c.GetJSON(&a); err != nil {
return err
}
```
### Builtin Reader
+ [x] GetJSON JSON
## About Writer
Writer 可简化 Response 的书写:
```go
// String Writer
c.String(http.StatusOK, "Hello World")
// JSON Writer
c.JSON(http.StatusOK, &MyResponse{
Code: 0,
Msg: "Success",
Data: "Hello World!",
})
```
### Builtin Writer
+ [x] Blob 二进制
+ [x] HTML HTML(text/html)
+ [x] String 普通文本(text/plain)
+ [x] JSON JSON(application/json)
+ [x] File 文件 - 兼容 afero
## About Middleware
中间间的定义如下:
```go
type (
// Context for Middleware
Context interface {
// Set/Get
Store() map[string]interface{}
Origin() Context
Shadow() Context
Set(key string, value interface{})
Get(key string) interface{}
// API
Sola() *Sola
SetCookie(cookie *http.Cookie)
Request() *http.Request
Response() http.ResponseWriter
// Writer
Blob(code int, contentType string, bs []byte) (err error)
HTML(code int, data string) error
String(code int, data string) error
JSON(code int, data interface{}) error
File(f File) (err error)
// Reader
GetJSON(data interface{}) error
// Handler
Handle(code int) Handler
}
context struct {
origin Context
lock sync.RWMutex
store map[string]interface{}
}
// Handler func
Handler func(Context) error
// Middleware func
Middleware func(Handler) Handler
)
```
关于 Context 键值的约定:
+ sola 框架
+ sola *sola.Sola
+ sola.request *http.Request
+ sola.response http.ResponseWriter
+ auth 认证中间件
+ auth.username Base Auth 用户名
+ auth.password Base Auth 密码
+ auth.claims JWT Auth Payload
+ auth.token 签发的 JWT
+ logger 日志中间件
+ logger message chan
+ x/router 旧路由中间件
+ x.router.param.* 路径参数
+ router 新路由中间件
+ router.meta 路由元数据
+ router.param.* 路径参数
+ hot 动态模块加载扩展
+ ext.hot *Hot
> **注意:请尽量使用中间件包中提供的标准方法、常量读取上下文数据,防止内部逻辑修改导致的向后不兼容。**
### Builtin Middleware
+ [x] auth 认证中间件
+ [x] 自定义返回内容
+ [x] Dev Mode(500)
+ [x] cors 跨域中间件 - 参考 [koa2-cors](https://github.com/zadzbw/koa2-cors)
+ [x] graphql GraphQL 中间件
+ [x] logger 日志中间件
+ [x] native go 原生 handler 转换中间件(取代原静态文件中间件)
+ [x] static 原静态文件中间件
+ 可用于静态文件
+ 可用于 statik
+ 可用于 afero
+ ...
+ [x] proxy 反向代理中间件(取代原 backup、favicon 中间件)
+ [x] backup 301 to other host - e.g. http -> https
+ [x] favicon 301 to Online Favicon
+ 嵌入 lua 脚本:https://github.com/yuin/gopher-lua
+ [x] 负载均衡
+ [x] rest RESTful API 中间件
+ [x] swagger API 文档中间件
+ [x] ws WebSocket 中间件
+ [x] x/router 旧路由中间件 (@deprecated 预计在 v2.2.x 移除)
+ [x] router 新路由中间件
#### router 匹配规则
+ 完整版 `GET localhost:3000/user/:id` (注意 Host 直接匹配 *http.Request 中的 Host)
+ 不指定 Method `localhost:3000/user/:id`
+ 不指定 Host `GET /user/:id`
+ 不指定 Method & Host `/user/:id`
+ 默认路径匹配(仅在 Bind 中使用,一般作为最后一个路径) `/*`
+ 特殊用法:仅指定 Method(用于 Bind,Path 由 Router 的 Pattern 匹配) `GET` - 支持 `net/http` 包中的所有 `Method*`
样例解释:
```go
// 匹配 /api/v1/*
r := router.New(&router.Option{
Pattern: "/api/v1",
})
// 严格匹配 /api/v1/hello
r.Bind("/hello", hello("Hello World!"))
{
// 匹配 /api/v1/user/*
sub := r.Sub(&router.Option{
Pattern: "/user",
})
// 严格匹配 /api/v1/user/hello
sub.Bind("/hello", hello("Hello!"))
// 严格匹配 /api/v1/user/hello 失败后执行该中间件
sub.Use(func(next sola.Handler) sola.Handler {
return func(c sola.Context) error {
fmt.Println("do auth")
return next(c)
}
})
// 严格匹配 /api/v1/user/info
sub.Bind("/info", hello("user info"))
// 匹配 /api/v1/user/infox/*
sub.Bind("/infox/*", hello("user infox"))
// 严格匹配 /api/v1/user/:id (路径参数 id)
sub.Bind("/:id", get("id"))
// sub 没有默认匹配
// 如果 sub 加了 UseNotFound 选项,将调用 sola 的 404 Handler
// 否则不会调用,将继续匹配后面的 `/*`
}
// 匹配 /api/v1/* (默认匹配)
r.Bind("/*", error404)
// 使用路由
app.Use(r.Routes())
```
## About Config
+ [x] Dev Mode
+ see [viper](https://github.com/spf13/viper)
## About ORM
+ [x] Debug in Dev Mode
+ see [gorm](https://github.com/jinzhu/gorm)
## About API Doc
+ [swagger](https://github.com/swaggo/swag)
以下例子仅作为 API Doc 使用说明,未实现具体功能:
```go
package main
import (
"github.com/ddosakura/sola/v2"
"github.com/ddosakura/sola/v2/middleware/auth"
"github.com/ddosakura/sola/v2/middleware/x/router"
"github.com/ddosakura/sola/v2/middleware/swagger"
_ "example/sola-example/api-doc/docs"
"example/sola-example/api-doc/handler"
)
// @title Swagger Example API
// @version 1.0
// @host localhost:3000
// @BasePath /api/v1
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
// @x-extension-openapi {"example": "value on a json format"}
func main() {
_sign := auth.Sign(auth.AuthJWT, []byte("sola_key"))
_auth := auth.Auth(auth.AuthJWT, []byte("sola_key"))
app := sola.New()
r := router.New()
r.BindFunc("GET /swagger", swagger.WrapHandler)
sub := router.New()
sub.Prefix = "/api/v1"
{
sub.BindFunc("GET /hello", handler.Hello)
sub.BindFunc("POST /login", auth.NewFunc(_sign, tmp, handler.Hello))
sub.BindFunc("/logout", auth.CleanFunc(handler.Hello))
third := router.New()
third.Prefix = sub.Prefix
{
third.BindFunc("GET /list", handler.List)
third.BindFunc("GET /item/:id", handler.Item)
}
sub.Bind("", auth.New(_auth, nil, third.Routes()))
}
r.Bind("/api/v1", sub.Routes())
app.Use(r.Routes())
sola.Listen("127.0.0.1:3000", app)
sola.Keep()
}
func tmp(sola.Handler) sola.Handler {
return handler.Hello
}
```
```go
// Hello godoc
// @Summary Say Hello
// @Description Print Hello World!
// @Produce plain
// @Success 200 {string} string "Hello World!"
// @Router /hello [get]
func Hello(c sola.Context) error {
return c.String(http.StatusOK, "Hello World!")
}
```
|
Java
|
UTF-8
| 664 | 2.71875 | 3 |
[] |
no_license
|
public class LogicaVenda {
private Custo iv = new CustoValorTotal();
private Custo taxa;
public Custo getSeguro() {
return taxa;
}
public void setSeguro(Custo taxa) {
this.taxa = taxa;
}
public double calcularTotal(Venda venda) {
venda.setTotal(0.0);
for (ItemVenda item: venda.getItens()) {
if (item != null) {
venda.setTotal(venda.getTotal() + item.getSubTotal());
}
}
if ( this.iv != null) {
venda.setTotal(venda.getTotal() + this.iv.calcularCusto(venda));
}
return venda.getTotal();
}
}
|
C#
|
UTF-8
| 1,465 | 3.359375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Day_12
{
class Program
{
static void Main(string[] args)
{
var lines = File.ReadLines("./input.txt");
IDictionary<int, ICollection<int>> pipes = new Dictionary<int, ICollection<int>>();
foreach(var line in lines)
{
var splitLine = line.Split("<->");
pipes[int.Parse(splitLine[0])] = splitLine[1].Split(", ").Select(s => int.Parse(s)).ToList();
}
var groups = 0;
while(pipes.Any()){
List<int> pipesToCheck = pipes.First().Value.ToList();
var pipesUnderFirst = new List<int>();
while (pipesToCheck.Any())
{
var currentPipe = pipesToCheck[0];
pipesToCheck.Remove(currentPipe);
pipesUnderFirst.Add(currentPipe);
pipesToCheck.AddRange(pipes[currentPipe].ToList());
pipesToCheck.Distinct();
pipesToCheck.RemoveAll(p => pipesUnderFirst.Contains(p));
}
Console.WriteLine(pipesUnderFirst.Count());
groups ++;
foreach(var thing in pipesUnderFirst){
pipes.Remove(thing);
}
}
Console.WriteLine(groups);
}
}
}
|
C#
|
UTF-8
| 1,514 | 2.515625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mp3TagLib;
using Mp3TagLib.Operations;
using Mp3TagLib.Plan;
using Mp3TagLib.Sync;
namespace mp3tager.Operations
{
class LateSync:Operation
{
public const int ID = 8;
private Synchronizer _synchronizer;
public LateSync()
{
OperationId = ID;
}
public override void Call()
{
if (IsCanceled)
{
_synchronizer.Redo();
return;
}
var path = Menu.GetUserInput("Load your plan\npath:");
var planLoader = new PlanProvider();
var tager = new Tager(new FileLoader());
_synchronizer = new Synchronizer(tager);
_synchronizer.Sync(planLoader.Load(path));
Menu.PrintChanges(_synchronizer.ModifiedFiles);
if (Menu.GetYesNoAnswer("Save changes?\nY/N:"))
{
_synchronizer.Save();
Menu.PrintMessage("Successfully");
Menu.PrintCollection(string.Format("with {0} errors", _synchronizer.ErrorFiles.Count), _synchronizer.ErrorFiles, ConsoleColor.Red);
Menu.GetUserInput("Press enter...");
}
}
public override void Cancel()
{
IsCanceled = true;
_synchronizer.Restore();
}
}
}
|
Python
|
UTF-8
| 1,988 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
import queue
import threading
import logging
import time
import math
import win32api
import engine.worlds.message as world
logger = logging.getLogger(__name__)
class SimpleInput(threading.Thread):
def __init__(self, queue_world):
threading.Thread.__init__(self)
self.event_end = threading.Event()
self.queue_world = queue_world
def run(self):
player_id = 0
x_res = 1920
y_res = 1080
x_old = x_res/2
y_old = y_res/2
key_forward = 87
key_backward = 83
while not self.event_end.is_set():
time_begin = time.time()
translate = [0.0,0.0,0.0]
rotate = [0.0,0.0,0.0]
x_new, y_new = win32api.GetCursorPos()
#logger.debug("x: {}, y: {}".format(x_new, y_new))
rotate[0] = (x_old - x_new) / x_res
rotate[1] = (y_old - y_new) / y_res
logger.debug("rotate: {}".format(rotate))
event_forward = win32api.GetKeyState(87)
#logger.debug("forward: {}".format(event_forward))
if event_forward == -127 or event_forward == -128:
translate[0] = -1.0
event_backward = win32api.GetKeyState(key_backward)
#logger.debug("backward: {}".format(event_backward))
if event_backward == -127 or event_backward == -128:
translate[0] = -1.0
queue_world_data = world.entity_move(camera_id, translate, rotate)
#logger.debug("world queue data: {}".format(queue_world_data))
try:
self.queue_world.put(queue_world_data, block=False)
except:
logger.warning("world queue is full")
time_end = time.time()
#logger.debug("frame time: {}".format(time_begin-time_end))
time.sleep(0.01)
logger.warning("stopped")
def stop(self):
logger.warning("stopping")
self.event_end.set()
|
C#
|
UTF-8
| 2,515 | 2.859375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Text;
using DataAccessLayer.Entities;
using DataAccessLayer.Repostiory;
namespace DataAccessLayer.UnitOfWork
{
public class UnitOfWork : IUnitOfWork
{
public FinalWordLearn Context { get; set; }
private Dictionary<Type, object> repositories;
private bool disposed;
public UnitOfWork()
{
Context = new FinalWordLearn();
repositories = new Dictionary<Type, object>();
}
public UnitOfWork(FinalWordLearn context)
{
Context = context;
repositories = new Dictionary<Type, object>();
}
public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
{
if (repositories.ContainsKey(typeof (TEntity)))
return repositories[typeof (TEntity)] as IRepository<TEntity>;
var repository = new Repository<TEntity>(Context);
repositories.Add(typeof (TEntity), repository);
return repository;
}
public void Save()
{
try
{
Context.SaveChanges();
}
catch (DbEntityValidationException e)
{
StringBuilder sb = new StringBuilder();
foreach (var eve in e.EntityValidationErrors)
{
sb.AppendLine(
string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name,
eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
sb.AppendLine(string.Format("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName,
ve.ErrorMessage));
}
}
throw new DbEntityValidationException(sb.ToString(), e);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
if (disposing)
Context.Dispose();
disposed = true;
}
}
}
|
Python
|
UTF-8
| 1,589 | 3.046875 | 3 |
[] |
no_license
|
import gviz_api
from flight_scraper.utils.scraper import get_prices_by_query_dates
def graph_prices(flight_scraper):
"""
This function creates a Google Visualizations DataTable JSON object.
It is then passed to the Google Visualizations API to be rendered.
"""
description = {"query_date" : ("datetime", "Query Date"),
"min_price" : ("number", "%s to %s" % (flight_scraper.depart_date, flight_scraper.return_date))}
dates = list()
dates.append(flight_scraper.depart_date)
dates.append(flight_scraper.return_date)
result = get_prices_by_query_dates(flight_scraper)
data = list()
for r in result:
for p in result[r]:
v = {"query_date" : r, "min_price" : p}
data.append(v)
data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
return data_table.ToJSon(columns_order=("query_date", "min_price"), order_by="query_date")
def graph_seats(origin, dest, dept_date):
""" TODO: Refactor """
#description = {"query_date" : ("datetime", "Query Date"),
# "seat_avail" : ("number", "%s" % (dept_date))}
#
#seat_query = scraper.get_total_seat_availability(origin, dest, dept_date)
#data = list()
#for query_date, avail in seat_query.iteritems():
# v = {"query_date" : query_date, "seat_avail" : avail}
# data.append(v)
#
#data_table = gviz_api.DataTable(description)
#data_table.LoadData(data)
#
#return data_table.ToJSon(columns_order=("query_date", "seat_avail"), order_by="query_date")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.