language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
C
|
UTF-8
| 1,090 | 2.734375 | 3 |
[] |
no_license
|
#include "r.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <stdlib.h>
struct UrandomRandomContext
{
struct RandomContext b;
int rand_fd;
};
static void rand_init(struct RandomContext *cntx)
{
struct UrandomRandomContext *rc = (struct UrandomRandomContext *) cntx;
rc->rand_fd = open("/dev/urandom", O_RDONLY);
assert(rc->rand_fd >= 0);
}
static int rand_n(struct RandomContext *cntx, int n)
{
struct UrandomRandomContext *rc = (struct UrandomRandomContext *) cntx;
unsigned val;
read(rc->rand_fd, &val, sizeof(val));
return val % n;
}
static void rand_destroy(struct RandomContext *cntx)
{
struct UrandomRandomContext *rc = (struct UrandomRandomContext *) cntx;
close(rc->rand_fd);
free(rc);
}
static const struct RandomOperations ops =
{
rand_init,
rand_destroy,
rand_n
};
struct RandomContext *
create_urandom_random()
{
struct UrandomRandomContext *rc = calloc(1, sizeof(*rc));
rc->b.ops = &ops;
rc->rand_fd = -1;
return &rc->b;
}
|
Markdown
|
UTF-8
| 7,003 | 2.625 | 3 |
[] |
no_license
|
# Jils Joseph
# About me
I am a quick learning adaptive individual I being in the development industry for more than 3 years most of my skills are related to data analysis. I have advanced ability in MS excel, SQL, Tableau, power Bi, problem solving and data analytic skill. I have experiened different programming language and work in different environments. Handling pressure and high work loads. I am always trying to improve my skills. I like to try new thing and learn them so that i can extent my reach. I am fasinated by data and how we can analyse the data.
# Education
* PG Certificate in Data Analytics, *St Clair College*, 2018-2020
* Bachelors of Engineering (Computer Science), *M G University*, 2011-2016
# Skills
• Microsoft excel, word, PowerPoint, Project, Outlook
• Programming languages: C, C++, C#, Java, Python, R, HTML, CSS
• IBM Cognos, Tableau, Goggle analytics, Power BI
• SQL, MySQL, ASP.NET
• Crystal reports, SQl reporting services
• Unity 3d, making strip sheets, photoshop
• Data modelling, mining and cleaning
• Data Visualization and reporting techniques
• Detailed and organized
• Quick and Adaptive learner
• Project Management
# [Project 1: Toronto Crime Analysis](https://github.com/jilsjoseph/project/blob/master/capstone%20report.pdf)
.jpg)
Photo by <a href="https://unsplash.com/@adityachinchure?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Aditya Chinchure</a> on <a href="https://unsplash.com/s/photos/toronto-city?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
* **Python libraries used:** Streamlit, Huggingface, TensorFlow, numpy , pandas , TensorFlow, matplotlib, seaborn, sklearn. keras, mglearn, folium
Collect and analysis past crime data of Toronto region. Using Excel clean and
plot initial analysis. Provide visualization using tableau for different analysis and
find different patterns. Run different models like ARIMA, Random Forest, KNN,
Decision Tree and LSTM to predict accuracy and optimize the neural networks
to get good prediction for the models. Using packages like Folium, Seaborn
plot different graphs in python. Predict which type of crime at which region
and at what time using our analysis.
# [Project 2: Health care analysis](https://github.com/jilsjoseph/project/blob/faf726d25a80884d10b533c31284bd29769506ea/Healthcare_Anlytics.pdf)
Analysis data related to liver cancer. Use excel and tableau to plot and
analysis the dataset. Use multiple resources to research and consulted
professional about the factors and terminologies in this field. Able to find
critical feature of patients diagnosed with cancer using our analysis. Use
different machine learning models to predict the survival of patients. Were
able to observe and identify different interline factors affecting liver cancer.
# Project 3: Project-stocks
Basic analysis using excel and use simple linear regression to forecast stock price.
This uses dataset from yahoo and using intel stock price from 2016 to 2021 a 5 year.
* Basic Analysis using [Ecxel](https://github.com/jilsjoseph/Portfolio/blob/1979fecc49ccecebd237f2ffab77e4b008a645fa/Basic%20analysis%20using%20Excel.pdf)
Analyse the difference between stocks bought all at the beginning and stocks bought each month (dollar cost averaging) for a time of five years
* Excel linear [Forecasting](https://github.com/jilsjoseph/Portfolio/blob/1f029872afb8ad8fb3c09a200fbe8d5d25b1c749/Stock%20Forecasting%20using%20Excel.pdf)
We are going to use a simple linear regression to forecast stock price. We are checking to see if we can predict the stock price.
All the calculations are done in excel.
Link to [excel](https://github.com/jilsjoseph/Portfolio/blob/91541dd81b5332902696af755c767948aae9492f/INTC%20(1).csv)
# Project 4: Financial Analysis and stock comparison
Compare different brands to find out the best one. Analyze different types of
data of different products to identify which one has more buyers and are
more profitable. Use stock price of these to predict and analyze the
performance of the company throughout years. Using Neural Networks, we
can predict the stock trends and forecast the sales.
# Project 5: Online Survey
Using google forms to create a survey among different groups, Collect, clean,
and analyze the data in excel and plot and present theses analysis. Use IBM
Cognos to analyze and report data. Making user that Ethics for analysis is
properly followed.
# Project : [Online Market Analysis](https://github.com/jilsjoseph/Market-.git)
* **Python libraries used:** numpy , pandas , TensorFlow, matplotlib, seaborn, sklearn. keras, mglearn
This project is helpful for the companies to increase their profits by marketing their products effectively. The data set is explored using different classification methods and the behavior of online shoppers is identified. This work illustrates the trends behind online shopping, abandonment statistics, and gives us a clear picture of how to prevent it. We will try to arrive at these predictions and observations through various machine learning algorithms. The performances were compared, and we will obtain a final algorithm, with which we can improve the revenue of online shopping.
# Work Experience
* **Concentrix- Technical service advisor, ON 2020-present**
Provide technical assistance to customers experiencing software, hardware or technical issues via calls and emails. Asist and interact with customer. Offer advice and suggestions to specialists. Making sure that customers are assured, and queries are solved in a timely manner.
* **Central Transport-Billing clerk, ON 2018–2020**
Check the data input in the system to ensure accuracy of final bill
Review invoices to idenA quick learning adaptive
individual seeking to contribute
knowledge to the benefit of the
company and its clients. Seeking to
use my advanced ability in all
aspect of excel, SQL, Tableau,
problem solving and data analytic
skill. With my years of expertise in
different programming language
and work environments will make
me a positive asset in your
organization.tify any errors before invoice delivery, Compile and
maintain documents and records of all billings, Package, post weights, and
shipping charges and determine methods of shipment. Audit to check before
the final dispatch of shipment from the terminal.
* **Bead Technology – Software Developer 2016-2017**
Requirement gathering for new projects, database, and UI design,
Collaborate closely with clients. Write new code as well as customize and
optimize existing code like sql, C#. Knowledge in Widows form, web
applications, win desktop application and web services Clean large size
data’s, process, analysis and verify data, Part of different project and data
collection teams. Making sure that projects tested for QA
* **Soften Technology – Junior Programmer[intern] 2016**
Intern as a junior programmer in ASP.NET, Create and optimized
|
Java
|
UTF-8
| 296 | 1.664063 | 2 |
[] |
no_license
|
package com.stage2.dao;
import com.stage2.entities.Projet;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource
public interface ProjetRepository extends CrudRepository<Projet,Long> {
}
|
C
|
UTF-8
| 1,615 | 3.484375 | 3 |
[] |
no_license
|
#include<stdio.h>
#include <stdlib.h>
int main()
{
int c;
FILE *fp = fopen("data.txt", "r");
int var1[1000], n, count, remain, flag=0,time_quantum;
float var2[1000], var3[1000], time, wait_time=0, turnaround_time=0;
printf("Enter Total Process:\t ");
scanf("%d",&n);
remain=n;
//store arrival time and amount of time process requires to complete
while ((c = fgetc(fp)) != EOF) {
int count = 0;
fscanf(fp, "%d%f",&var1[count], &var2[count]);
var3[count]=var2[count];
count++;
}
printf("Enter Time Quantum:\t");
scanf("%d",&time_quantum);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
//all processes one by one repeatedly
for(time=0,count=0;remain!=0;)
{
if(var3[count]<=time_quantum && var3[count]>0)
{
time+=var3[count];
var3[count]=0;
flag=1;
}
// Decrease burst_time by quantum
else if(var3[count]>0)
{
var3[count]-=time_quantum;
time+=time_quantum;
}
//Calculate wait time and turnaround time
if(var3[count]==0 && flag==1)
{
remain--;
printf("P[%d]\t|\t%f\t|\t%f\n", count+1, time-var1[count],time-var1[count]-var2[count]);
wait_time+=time-var1[count]-var2[count];
turnaround_time+=time-var1[count];
flag=0;
}
if(count==n-1)
count=0;
else if(var1[count+1]<=time)
count++;
else
count=0;
// If all processes are done break;
}
printf("%f\n", wait_time);
printf("%f\n", turnaround_time);
printf("\nAverage Waiting Time= %f\n",wait_time/n);
printf("Avg Turnaround Time = %f",turnaround_time/n);
fclose(fp);
return 0;
}
|
Go
|
UTF-8
| 2,510 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
package test_test
import (
"os"
"path/filepath"
"testing"
"github.com/Jeffail/benthos/v3/lib/service/test"
yaml "gopkg.in/yaml.v3"
)
func TestGenerateDefinitions(t *testing.T) {
testDir, err := initTestFiles(t, map[string]string{
"foo.yaml": `
pipeline:
processors:
- text:
ignored: this field is ignored
operator: to_upper`,
"unrelated.json": `{"foo":"bar"}`,
"bar.yaml": `
pipeline:
processors:
- text:
operator: to_upper`,
"bar_benthos_test.yaml": `
tests:
- name: example test
target_processors: '/pipeline/processors'
environment: {}
input_batch:
- content: 'example content'
output_batches:
-
- content_equals: example content`,
})
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(testDir)
var defaultDefBytes []byte
if defaultDefBytes, err = yaml.Marshal(test.ExampleDefinition()); err != nil {
t.Fatal(err)
}
defaultDef := string(defaultDefBytes)
if err = test.Generate(testDir, "_benthos_test"); err != nil {
t.Fatal(err)
}
if _, err = os.Stat(filepath.Join(testDir, "unrelated_benthos_test.json")); !os.IsNotExist(err) {
t.Errorf("Expected not exist error, got %v", err)
}
actBytes, err := os.ReadFile(filepath.Join(testDir, "foo_benthos_test.yaml"))
if err != nil {
t.Fatal(err)
}
if exp, act := defaultDef, string(actBytes); exp != act {
t.Errorf("Definition does not match default: %v != %v", act, exp)
}
if actBytes, err = os.ReadFile(filepath.Join(testDir, "bar_benthos_test.yaml")); err != nil {
t.Fatal(err)
}
if exp, act := defaultDef, string(actBytes); exp == act {
t.Error("Existing definition was overridden")
}
}
func TestGenerateDefinitionFile(t *testing.T) {
testDir, err := initTestFiles(t, map[string]string{
"foo.yaml": `
pipeline:
processors:
- text:
ignored: this field is ignored
operator: to_upper`,
"unrelated.json": `{"foo":"bar"}`,
})
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(testDir)
var defaultDefBytes []byte
if defaultDefBytes, err = yaml.Marshal(test.ExampleDefinition()); err != nil {
t.Fatal(err)
}
defaultDef := string(defaultDefBytes)
if err = test.Generate(filepath.Join(testDir, "foo.yaml"), "_benthos_test"); err != nil {
t.Fatal(err)
}
actBytes, err := os.ReadFile(filepath.Join(testDir, "foo_benthos_test.yaml"))
if err != nil {
t.Fatal(err)
}
if exp, act := defaultDef, string(actBytes); exp != act {
t.Errorf("Definition does not match default: %v != %v", act, exp)
}
}
|
Java
|
UTF-8
| 142 | 1.851563 | 2 |
[] |
no_license
|
package com.demo.repository;
import java.util.List;
import com.demo.model.Blog;
public interface BlogRepository {
List<Blog> findAll();
}
|
Markdown
|
UTF-8
| 3,610 | 2.515625 | 3 |
[] |
no_license
|
---
title: CLI の例 - ドメイン名のための DNS ゾーンとレコードの作成 - Azure | Microsoft Docs
description: この Azure CLI スクリプトの例では、ドメイン名のための DNS ゾーンとレコードを作成する方法を示しています
services: load-balancer
documentationcenter: traffic-manager
author: vhorne
manager: jeconnoc
editor: tysonn
tags: ''
ms.assetid: ''
ms.service: traffic-manager
ms.devlang: azurecli
ms.topic: sample
ms.tgt_pltfrm: ''
ms.workload: infrastructure
ms.date: 04/30/2018
ms.author: victorh
ms.openlocfilehash: b8a69b44714a24c78bf4077c27b5bf5633cc56d3
ms.sourcegitcommit: 1d850f6cae47261eacdb7604a9f17edc6626ae4b
ms.translationtype: HT
ms.contentlocale: ja-JP
ms.lasthandoff: 08/02/2018
ms.locfileid: "39431768"
---
# <a name="azure-cli-script-example-create-a-dns-zone-and-record"></a>Azure CLI スクリプトの例: DNS ゾーンとレコードの作成
この Azure CLI スクリプトの例では、ドメイン名のための DNS ゾーンとレコードを作成します。
[!INCLUDE [sample-cli-install](../../../includes/sample-cli-install.md)]
[!INCLUDE [quickstarts-free-trial-note](../../../includes/quickstarts-free-trial-note.md)]
## <a name="sample-script"></a>サンプル スクリプト
```azurecli-interactive
# Create a resource group.
az group create \
-n myResourceGroup \
-l eastus
# Create a DNS zone. Substitute zone name "contoso.com" with the values for your own.
az network dns zone create \
-g MyResourceGroup \
-n contoso.com
# Create a DNS record. Substitute zone name "contoso.com" and IP address "1.2.3.4* with the values for your own.
az network dns record-set a add-record \
-g MyResourceGroup \
-z contoso.com \
-n www \
-a 1.2.3.4
# Get a list the DNS records in your zone
az network dns record-set list \
-g MyResourceGroup \
-z contoso.com
```
## <a name="clean-up-deployment"></a>デプロイのクリーンアップ
次のコマンドを実行して、リソース グループ、DNS ゾーン、およびすべての関連リソースを削除します。
```azurecli
az group delete -n myResourceGroup
```
## <a name="script-explanation"></a>スクリプトの説明
このスクリプトでは、次のコマンドを使用して、リソース グループ、仮想マシン、可用性セット、ロード バランサー、およびすべての関連リソースを作成します。 表内の各コマンドは、それぞれのドキュメントにリンクされています。
| コマンド | メモ |
|---|---|
| [az group create](/cli/azure/group#az-group-create) | すべてのリソースを格納するリソース グループを作成します。 |
| [az network dns zone create](/cli/azure/network/dns/zone#az-network-dns-zone-create) | Azure DNS ゾーンを作成します。 |
| [az network dns record-set a add-record](/cli/azure/network/dns/record-set#az-network-dns-record-set-a-add-record) | DNS ゾーンに *A* レコードを追加します。 |
| [az network dns record-set list](/cli/azure/network/dns/record-set#az-network-dns-record-set-a-list) | DNS ゾーン内のすべての *A* レコード セットを一覧表示します。 |
| [az group delete](https://docs.microsoft.com/cli/azure/vm/extension#az-vm-extension-set) | 入れ子になったリソースすべてを含むリソース グループを削除します。 |
## <a name="next-steps"></a>次の手順
Azure CLI の詳細については、[Azure CLI のドキュメント](https://docs.microsoft.com/cli/azure)のページをご覧ください。
|
Java
|
UTF-8
| 989 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
package KOE;
// Tomi Salin a1600563
class Opettaja {
private String tunnus, etunimi, sukunimi;
private double palkka;
public Opettaja(){
tunnus="";
etunimi="";
sukunimi="";
palkka=0;
}
public Opettaja(String tunnus, String etunimi, String sukunimi, double palkka){
this.tunnus=tunnus;
this.etunimi=etunimi;
this.sukunimi=sukunimi;
this.palkka=palkka;
}
public String getTunnus() {
return tunnus;
}
public void setTunnus(String tunnus) {
this.tunnus = tunnus;
}
public String getEtunimi() {
return etunimi;
}
public void setEtunimi(String etunimi) {
this.etunimi = etunimi;
}
public String getSukunimi() {
return sukunimi;
}
public void setSukunimi(String sukunimi) {
this.sukunimi = sukunimi;
}
public double getPalkka() {
return palkka;
}
public void setPalkka(double palkka) {
this.palkka = palkka;
}
@Override
public String toString() {
return "Opettaja [tunnus=" + tunnus + ", etunimi=" + etunimi
+ ", sukunimi=" + sukunimi + ", palkka=" + palkka + "]";
}
}
|
JavaScript
|
UTF-8
| 1,668 | 2.78125 | 3 |
[] |
no_license
|
const sectionCards = document.querySelector("section.cards");
const card = document.querySelector("div.card");
const conteudos = [
{
title: "Portais de transparência",
thumb: "img/icone.png",
description: "Tenha acesso aos principais portais de transparência do RN.",
conteudo_id: "GykTLqODQuU"
},
{
title: "Planos de Dados Abertos",
thumb: "img/icone-database.png",
description: "Tenha acesso aos principais planos de dados abertos do RN. ",
conteudo_id: "HN1UjzRSdBk"
},
{
title: "Projetos de controle social",
thumb: "img/icone-nave.png",
description: "Tenha acesso aos principais projetos de controle social ou dados abertos do RN. ",
conteudo_id: "rAzHvYnQ8DY"
},
{
title: "Eventos no estado",
thumb: "img/icone-calendario.png",
description: "Tenha acesso aos principais eventos que ocorre no RN. ",
conteudo_id: "ghTrp1x_1As"
},
{
title: "Notícias no estado ",
thumb: "img/icone-jornal.png",
description: "Tenha acesso as principais notícias no estado do RN. ",
conteudo_id: "GSqR2i-Pq6o"
},
{
title: "Produções acadêmicas",
thumb: "img/icone-academico.png",
description: "Tenha acesso as produções acadêmicas desenvolvidas no RN.",
conteudo_id: "2alg7MQ6_sI"
}
];
conteudos.map(element => {
const cardClone = card.cloneNode(true)
cardClone.setAttribute("id", element.conteudo_id)
cardClone.querySelector("img").src = element.thumb
cardClone.querySelector(".title").innerHTML = element.title
cardClone.querySelector(".description").innerHTML = element.description
sectionCards.appendChild(cardClone)
})
card.remove()
|
Java
|
UTF-8
| 876 | 2.90625 | 3 |
[] |
no_license
|
package com.games.LeetCode.Problems.OrderedStream;
import com.games.LeetCode.Problems.OrderedStream.Solution.OrderedStream;
import com.games.Utils;
import org.junit.jupiter.api.Test;
import java.util.List;
import static com.games.Utils.assertSameList;
class SolutionTest {
@Test
void testOrderedStream() {
OrderedStream os = new OrderedStream(5);
assertSameList(List.of(), os.insert(3, "ccccc")); // Inserts (3, "ccccc"), returns [].
assertSameList(List.of("aaaaa"), os.insert(1, "aaaaa")); // Inserts (1, "aaaaa"), returns ["aaaaa"].
assertSameList(List.of("bbbbb", "ccccc"), os.insert(2, "bbbbb")); // Inserts (2, "bbbbb"), returns ["bbbbb", "ccccc"].
assertSameList(List.of(), os.insert(5, "eeeee")); // Inserts (5, "eeeee"), returns [].
assertSameList(List.of("ddddd", "eeeee"), os.insert(4, "ddddd"));
}
}
|
JavaScript
|
UTF-8
| 933 | 2.65625 | 3 |
[] |
no_license
|
import React, { PropTypes } from 'react'
class Vote extends React.Component {
constructor(props) {
super(props);
this.getPair = this.getPair.bind(this);
this.isDisabled = this.isDisabled.bind(this);
this.votedFor = this.votedFor.bind(this);
}
getPair() {
return this.props.pair || [];
}
isDisabled() {
return !!this.props.hasVoted;
}
votedFor(entry) {
return this.props.hasVoted === entry;
}
render () {
const buttons = this.getPair().map((entry) => {
let subtitle = null;
if (this.votedFor(entry)) {
subtitle = ( <span className="VotingBtn__subtitle">Voted</span> );
}
return (
<button key={entry}
className="Voting__btn VotingBtn"
disabled={this.isDisabled()}
onClick={() => this.props.vote(entry)}
>
{entry}
{subtitle}
</button>
);
});
return (
<div className="Voting__buttons">
{buttons}
</div>
);
}
}
export default Vote;
|
Java
|
UTF-8
| 1,003 | 2.84375 | 3 |
[] |
no_license
|
package org.apache.tools.ant.taskdefs;
import org.apache.tools.ant.*;
import org.apache.tools.ant.types.*;
import java.util.*;
import java.text.*;
import java.lang.RuntimeException;
/**
* Implements a single threaded task execution.
* <p>
* @author Thomas Christen <a href="mailto:chr@active.ch">chr@active.ch</a>
*/
public class Sequential extends Task
implements TaskContainer {
/** Optional Vector holding the nested tasks */
private Vector nestedTasks = new Vector();
/**
* Add a nested task to Sequential.
* <p>
* @param nestedTask Nested task to execute Sequential
* <p>
*/
public void addTask(Task nestedTask) {
nestedTasks.addElement(nestedTask);
}
/**
* Execute all nestedTasks.
*/
public void execute() throws BuildException {
for (Enumeration e = nestedTasks.elements(); e.hasMoreElements();) {
Task nestedTask = (Task)e.nextElement();
nestedTask.perform();
}
}
}
|
C++
|
UTF-8
| 858 | 2.90625 | 3 |
[] |
no_license
|
//
// Created by Lucas on 11/2/2019.
//
#include "OvernightPackage.h"
#include <iostream>
using namespace std;
OvernightPackage::OvernightPackage(char *n1, char *a1, char *c1, char *z1, char *n2, char *a2, char *c2, char *z2, double w,
double c, double f)
: Package(n1, a1, c1, z1, n2, a2, c2, z2, w, c) {
setFlat2(f);
}
double OvernightPackage::getFlat2() const {
return Flat2;
}
void OvernightPackage::setFlat2(double flat2) {
Flat2=flat2;
}
double OvernightPackage::calculateCost() const {
return Package::calculateCost()+getWeight()*getFlat2();
}
void OvernightPackage::printForcost() const {
cout << "\nWeight of package: " << getWeight() << " ounces" << endl;
cout << "Type of delivery: Overnight Delivery" << endl;
cout << "Cost of package: $" << calculateCost() << endl;
}
|
C
|
UTF-8
| 355 | 2.75 | 3 |
[] |
no_license
|
#pragma once
#include "common.h"
int twoCitySchedCost(vector<vector<int>>& costs) {
sort(begin(costs), end(costs), [](const vector<int>& o1, const vector<int>& o2) {
return (o1[0] - o1[1] < o2[0] - o2[1]);
});
int reuslt = 0;
int n = costs.size() / 2;
for (int i = 0; i < n; i++)
{
reuslt += costs[i][0] + costs[i + n][1];
}
return reuslt;
}
|
C++
|
UTF-8
| 1,047 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
#include "ElementsManager.h"
int ElementsManager::elementNums = 0;
std::vector<ElementsManager::ElementWrapper> ElementsManager::elementsContainer;
const int ElementsManager::getIndexByID(int id) {
std::vector<ElementWrapper>::iterator it;
for (it = elementsContainer.begin(); it != elementsContainer.end(); ++it) {
if (it->id == id) return it - elementsContainer.begin();
}
return -1;
}
const ElementsManager::ETYPES ElementsManager::getTypeByID(int id) {
int index = getIndexByID(id);
return index > -1 ? elementsContainer[index].type : ETYPES::NONE;
}
const int ElementsManager::createElement(ETYPES type) {
int id = ++elementNums;
ElementWrapper element = { id, type };
elementsContainer.push_back(element);
return id;
}
const bool ElementsManager::removeElement(int id) {
int index = getIndexByID(id);
if (index < 0 || elementsContainer[index].type == ETYPES::NONE) {
return false;
}
elementsContainer[index].type = ETYPES::NONE;
return true;
}
const int ElementsManager::getElementsNumber() {
return elementNums;
}
|
C++
|
UTF-8
| 4,479 | 2.859375 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* FragTrap.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: whortenc <whortenc@student.21-school.ru +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/25 20:11:08 by whortenc #+# #+# */
/* Updated: 2021/04/25 20:14:23 by whortenc ### ########.fr */
/* */
/* ************************************************************************** */
#include "FragTrap.hpp"
FragTrap::FragTrap(std::string name):
_hit_points(100),
_max_hit_points(100),
_energy_point(100),
_max_energy_point(100),
_level(1),
_name(name),
_mel_dmg(30),
_ran_dmg(20),
_armor(5)
{
srand(time(NULL));
std::cout << "FRAG <" << this->_name << "> created" << std::endl;
return;
}
FragTrap::FragTrap(void):
_hit_points(100),
_max_hit_points(100),
_energy_point(100),
_max_energy_point(100),
_level(1),
_name(""),
_mel_dmg(30),
_ran_dmg(20),
_armor(5)
{
srand(time(NULL));
std::cout << "FRAG without name created" << std::endl;
return;
}
FragTrap::~FragTrap(void)
{
std::cout << "FRAG <" << this->_name << "> died" << std::endl;
return;
}
FragTrap &FragTrap::operator=(FragTrap const &el){
if (this != &el)
{
this->_hit_points = el._hit_points;
this->_max_hit_points = el._max_hit_points;
this->_energy_point = el._energy_point;
this->_max_energy_point = el._max_energy_point;
this->_level = el._level;
this->_name = el._name;
this->_mel_dmg = el._mel_dmg;
this->_ran_dmg = el._ran_dmg;
this->_armor = el._armor;
}
return *this;
}
FragTrap::FragTrap(FragTrap const &el) :
_hit_points(el._hit_points),
_max_hit_points(el._max_hit_points),
_energy_point(el._energy_point),
_max_energy_point(el._max_energy_point),
_level(el._level),
_name(el._name),
_mel_dmg(el._mel_dmg),
_ran_dmg(el._ran_dmg),
_armor(el._armor)
{ return; }
void FragTrap::rangedAttack(std::string const &target){
std::cout << "FRAG <" << this->_name << "> attacks <" << target << "> at range, causing <" << this->_ran_dmg << "> points of damage!" << std::endl;
}
void FragTrap::meleeAttack(std::string const &target){
std::cout << "FRAG <" << this->_name << "> attacks <" << target << "> melee, causing <" << this->_mel_dmg << "> points of damage!" << std::endl;
}
int FragTrap::takeDamage(unsigned int amount){
int dmg = 0;
if ((int)amount > (this->_hit_points + this->_armor))
{
dmg = this->_hit_points;
this->_hit_points = 0;
}
else if (this->_armor < (int)amount)
{
dmg = amount - this->_armor;
this->_hit_points -= dmg;
}
std::cout << "FRAG <" << this->_name << "> takes <" << dmg << "> damage, actual hit_points <" << this->_hit_points << ">" << std::endl;
return dmg;
}
int FragTrap::beRepaired(unsigned int amount){
int heal = 0;
if (this->_hit_points < this->_max_hit_points)
{
if (this->_max_hit_points - this->_hit_points < (int)amount)
{
heal = this->_max_hit_points - this->_hit_points;
this->_hit_points = this->_max_hit_points;
}
else
{
heal = amount;
this->_hit_points += amount;
}
}
std::cout << "FRAG <" << this->_name << "> repaired <" << heal << "> heal_points, actual hit_points <" << this->_hit_points << ">" << std::endl;
return heal;
}
std::string FragTrap::getName(void) const { return this->_name; }
void setWpn(wpn &wpn, std::string weapon, int dmg)
{
wpn.weapon = weapon;
wpn.dmg = dmg;
}
void FragTrap::vaulthunter_dot_exe(std::string const &target)
{
if (this->_energy_point < 25)
{
std::cout << "FRAG <" << this->_name << "> tried to use random weapon, but hasn't enought energy <" << this->_energy_point << ">" << std::endl;
return;
}
wpn wpn[5];
int choice;
setWpn(wpn[0], "Banana machine", 5);
setWpn(wpn[1], "Duck", 10);
setWpn(wpn[2], "Apple", 15);
setWpn(wpn[3], "Ponycorn", 20);
setWpn(wpn[4], "Atomic bomb", 1000);
choice = rand() % 5;
std::cout << "FRAG <" << this->_name << "> attacks <" << target << "> with " << wpn[choice].weapon << ", causing <" << wpn[choice].dmg << "> points of damage!" << std::endl;
this->_energy_point -= 25;
}
|
Java
|
UTF-8
| 804 | 1.789063 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.ley.springcloud.stream.rabbit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
* @see org.springframework.cloud.stream.binder.rabbit.properties.RabbitBinderConfigurationProperties
* @see org.springframework.cloud.stream.config.BindingProperties
* @see org.springframework.cloud.stream.binder.ConsumerProperties
* @see org.springframework.cloud.stream.binder.ProducerProperties
**/
@SpringBootApplication
@ComponentScan("com.ley.springcloud.stream.rabbit.group.consumer")
public class StreamRabbitReceiverApplication {
public static void main(String[] args) {
SpringApplication.run(StreamRabbitReceiverApplication.class, args);
}
}
|
Python
|
UTF-8
| 1,516 | 2.609375 | 3 |
[] |
no_license
|
import datetime
import logging
import os
import sys
class Logger(object):
_privateLogger = None
logFileName = ""
def __init__(self):
if not Logger._privateLogger:
Logger.logFileName = "%s.log" % datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
Logger.logFileName = os.path.join(os.path.dirname(__file__), "..", "logs", Logger.logFileName)
Logger.logFileName = os.path.abspath(Logger.logFileName)
# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S", filename=Logger.logFileName, filemode="a")
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
# set a format which is simpler for console use
formatter = logging.Formatter('%(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
Logger._privateLogger = logging.getLogger()
Logger._privateLogger.addHandler(console)
def log(self, msg, level=logging.DEBUG):
if level == logging.DEBUG:
self._privateLogger.debug(msg)
elif level == logging.INFO:
self._privateLogger.info(msg)
elif level == logging.WARNING:
self._privateLogger.warning(msg)
elif level == logging.ERROR:
self._privateLogger.error(msg)
elif level == logging.FATAL:
self._privateLogger.fatal(msg)
else:
self._privateLogger.debug(msg)
|
Shell
|
UTF-8
| 430 | 3.703125 | 4 |
[] |
no_license
|
#!/bin/bash
show_help() {
echo ""
echo "USAGE: $(basename $0) [-h] [-s sep]"
echo ""
echo " sep : the field separator used in the input data"
echo " h : show this help text"
echo ""
}
SEPARATOR=${CSV_UTILS_SEPARATOR:-,}
while getopts "hs:" opt
do
case "$opt" in
s) SEPARATOR="$OPTARG"
;;
h)
show_help
exit 0
;;
esac
done
shift $((OPTIND-1))
cat | column -s $SEPARATOR -t
|
SQL
|
UTF-8
| 12,137 | 3.015625 | 3 |
[] |
no_license
|
use hr_database;
insert into Regions (region_ID, region_name)
values
(1, "Asia"),
(2, "Middle East"),
(3, "Europe"),
(4, "North America"),
(5, "Central America"),
(6, "South America"),
(7, "Sub-Saharan Africa"),
(8, "Australia and Oceania");
insert into Countries (country_ID, country_name, region_id)
values
(1, "Bangladesh", 1),
(2, "Bhutan", 1),
(3, "Brunei", 1),
(4, "Cambodia", 1),
(5, "China", 1),
(6, "India", 1),
(7, "Indonesia", 1),
(8, "Japan", 1),
(9, "Kazakhstan", 1),
(10, "North Korea", 1),
(11, "South Korea", 1),
(12, "Kyrgyzstan", 1),
(13, "Laos", 1),
(14, "Malaysia", 1),
(15, "Maldives", 1),
(16, "Mongolia", 1),
(17, "Myanmar", 1),
(18, "Nepal", 1),
(19, "Philippines", 1),
(20, "Singapore", 1),
(21, "Sri Lanka", 1),
(22, "Taiwan", 1),
(23, "Tajikistan", 1),
(24, "Thailand", 1),
(25, "Turkmenistan", 1),
(26, "Uzbekistan", 1),
(27, "Vietnam", 1),
(28, "Afghanistan", 2),
(29, "Algeria", 2),
(30, "Azerbaijan", 2),
(31, "Bahrain", 2),
(32, "Egypt", 2),
(33, "Iran", 2),
(34, "Iraq", 2),
(35, "Israel", 2),
(36, "Jordan", 2),
(37, "Kuwait", 2),
(38, "Lebanon", 2),
(39, "Libya", 2),
(40, "Morocco", 2),
(41, "Oman", 2),
(42, "Pakistan", 2),
(43, "Qatar", 2),
(44, "Saudi Arabia", 2),
(45, "Somalia", 2),
(46, "Syria", 2),
(47, "Tunisia", 2),
(48, "Turkey", 2),
(49, "The United Arab Emirates", 2),
(50, "Yemen", 2),
(51, "Albania", 3),
(52, "Andorra", 3),
(53, "Armenia", 3),
(54, "Austria", 3),
(55, "Belarus", 3),
(56, "Belgium", 3),
(57, "Bosnia and Herzegovina", 3),
(58, "Bulgaria", 3),
(59, "Croatia", 3),
(60, "Cyprus", 3),
(61, "Czech Republic", 3),
(62, "Denmark", 3),
(63, "Estonia", 3),
(64, "Finland", 3),
(65, "France", 3),
(66, "Georgia", 3),
(67, "Germany", 3),
(68, "Greece", 3),
(69, "Hungary", 3),
(70, "Iceland", 3),
(71, "Ireland", 3),
(72, "Italy", 3),
(73, "Kosovo", 3),
(74, "Latvia", 3),
(75, "Liechtenstein", 3),
(76, "Lithuania", 3),
(77, "Luxembourg", 3),
(78, "Macedonia", 3),
(79, "Malta", 3),
(80, "Moldova", 3),
(81, "Monaco", 3),
(82, "Montenegro", 3),
(83, "Netherlands", 3),
(84, "Norway", 3),
(85, "Poland", 3),
(86, "Portugal", 3),
(87, "Romania", 3),
(88, "Russia", 3),
(89, "San Marino", 3),
(90, "Serbia", 3),
(91, "Slovakia", 3),
(92, "Slovenia", 3),
(93, "Spain", 3),
(94, "Sweden", 3),
(95, "Switzerland", 3),
(96, "Ukraine", 3),
(97, "United Kingdom", 3),
(98, "Vatican City", 3),
(99, "Canada", 4),
(100, "Greenland ", 4),
(101, "Mexico", 4),
(102, "The United States of America", 4),
(103, "Antigua and Barbuda", 5),
(104, "The Bahamas", 5),
(105, "Barbados", 5),
(106, "Belize", 5),
(107, "Costa Rica", 5),
(108, "Cuba", 5),
(109, "Dominica", 5),
(110, "Dominican Republic", 5),
(111, "El Salvador", 5),
(112, "Grenada", 5),
(113, "Guatemala", 5),
(114, "Haiti", 5),
(115, "Honduras", 5),
(116, "Jamaica", 5),
(117, "Nicaragua", 5),
(118, "Panama", 5),
(119, "Saint Kitts and Nevis", 5),
(120, "Saint Lucia", 5),
(121, "Saint Vincent and the Grenadines", 5),
(122, "Trinidad and Tobago", 5),
(123, "Argentina", 6),
(124, "Bolivia", 6),
(125, "Brazil", 6),
(126, "Chile", 6),
(127, "Colombia", 6),
(128, "Ecuador", 6),
(129, "Guyana", 6),
(130, "Paraguay", 6),
(131, "Peru", 6),
(132, "Suriname", 6),
(133, "Uruguay", 6),
(134, "Venezuela", 6),
(135, "Angola", 7),
(136, "Benin", 7),
(137, "Botswana", 7),
(138, "Burkina Faso", 7),
(139, "Burundi", 7),
(140, "Cameroon", 7),
(141, "Cape Verde", 7),
(142, "The Central African Republic", 7),
(143, "Chad", 7),
(144, "Comoros", 7),
(145, "Republic of the Congo", 7),
(146, "The Democratic Republic of the Congo", 7),
(147, "Cote d'Ivoire", 7),
(148, "Djibouti", 7),
(149, "Equatorial Guinea", 7),
(150, "Eritrea", 7),
(151, "Ethiopia", 7),
(152, "Gabon", 7),
(153, "The Gambia", 7),
(154, "Ghana", 7),
(155, "Guinea", 7),
(156, "Guinea-Bissau", 7),
(157, "Kenya", 7),
(158, "Lesotho", 7),
(159, "Liberia", 7),
(160, "Madagascar", 7),
(161, "Malawi", 7),
(162, "Mali", 7),
(163, "Mauritania", 7),
(164, "Mauritius", 7),
(165, "Mozambique", 7),
(166, "Namibia", 7),
(167, "Niger", 7),
(168, "Nigeria", 7),
(169, "Rwanda", 7),
(170, "Sao Tome and Principe", 7),
(171, "Senegal", 7),
(172, "Seychelles", 7),
(173, "Sierra Leone", 7),
(174, "South Africa", 7),
(175, "South Sudan", 7),
(176, "Sudan", 7),
(177, "Swaziland", 7),
(178, "Tanzania", 7),
(179, "Togo", 7),
(180, "Uganda", 7),
(181, "Zambia", 7),
(182, "Zimbabwe", 7),
(183, "Australia", 8),
(184, "East Timor", 8),
(185, "Fiji", 8),
(186, "Kiribati", 8),
(187, "Marshall Islands", 8),
(188, "The Federated States of Micronesia", 8),
(189, "Nauru", 8),
(190, "New Zealand", 8),
(191, "Palau", 8),
(192, "Papua New Guinea", 8),
(193, "Samoa", 8),
(194, "Solomon Islands", 8),
(195, "Tonga", 8),
(196, "Tuvalu", 8),
(197, "Vanuatu", 8);
insert into Locations (location_ID, street_address, postal_code, city, state_province, country_id)
values
(1, "No 4, Kaduna Road", 384, "Kaduna", "Kaduna", 181),
(2, "No 8, sabo Road", 345, "Benin", "Edo", 197),
(3, "No 81, Lagos Street", 306, "Kaduna", "Kaduna", 30),
(4, "No 10, Abel Road", 267, "Benin", "Edo", 10),
(5, "No 82, Silent Road", 228, "Kaduna", "Kaduna", 34),
(6, "No 923, Beauty Road", 189, "Benin", "Edo", 12),
(7, "No 67, Kelly Avenue", 150, "Kaduna", "Kaduna", 18),
(8, "No 32, Grade Road", 111, "Benin", "Edo", 32),
(9, "No 46, Yolo Road", 72, "Kaduna", "Kaduna", 14),
(10, "No 23, Cabri Road", 33, "Benin", "Edo", 1);
insert into managers (manager_ID, manager_name)
values
(100, "Morten Tyldum"),
(101, "David Yates"),
(103, "Theodore Melfi"),
(108, "Gareth Edwards"),
(114, "Ron Clements"),
(120, "Nacho Vigalondo"),
(147, "Chris Renaud"),
(148, "Mel Gibson"),
(149, "Paul Greengrass");
insert into Departments (department_ID, department_name,manager_id, location_id)
values
(30, "Production", 120, 4),
(50, "Research and Development", 101, 1),
(60, "Purchasing", 147, 7),
(80, "Marketing", 149, 3),
(100, "Human Resource Management", 108, 9),
(120, "Accounting and Finance", 100, 6);
insert into Jobs (job_ID, job_title, min_salary, max_salary)
values
("IT_PROG", "IT Programmer", 120000.00, 170000.00),
("FI_MGR", "Financial Manager", 900.00, 40000.00),
("FI_ACCOUNT", "Accountant", 1000.00, 30000.00),
("PU_MAN", "PU Manager", 1000.00, 15000.00),
("PU_CLERK", "PU Clerk", 1000.00, 18000.00),
("ST_MAN", "ST Manager", 1000.00, 10000.00),
("ST_CLERK", "ST Clerk", 2000.00, 25000.00),
("SA_REP", "Sales Representative", 1500.00, 82000.00);
insert into Employees (employee_ID, firstname, lastname, email, phonenumber, hire_date, job_id, salary, commission_pct, manager_id, department_id)
values
(106, "Valli", "Pataballa", "VPATABAL", "590.423.4560", '2006-02-05', "IT_PROG", 4800.00, 0.00, 103, 60),
(107, "Diana", "Lorentz", "DLORENTZ", "590.423.5567", '2007-02-07', "IT_PROG", 4200.00, 0.00, 103, 60),
(108, "Nancy", "Greenberg", "NGREENBE", "515.124.4569", '2002-08-17', "FI_MGR", 12008.00, 0.00, 101, 100),
(109, "Daniel", "Faviet", "DFAVIET", "515.124.4169", '2002-08-16', "FI_ACCOUNT", 9000.00, 0.00, 108, 100),
(110, "John", "Chen", "JCHEN", "515.124.4269", '2005-09-28', "FI_ACCOUNT", 8200.00, 0.00, 108, 100),
(111, "Ismael", "Sciarra", "ISCIARRA", "515.124.4369", '2005-09-30', "FI_ACCOUNT", 7700.00, 0.00, 108, 100),
(112, "Jose Manuel", "Urman", "JMURMAN", "515.124.4469", '2006-03-07', "FI_ACCOUNT", 7800.00, 0.00, 108, 100),
(113, "Luis", "Popp", "LPOPP", "515.124.4567", '2007-12-07', "FI_ACCOUNT", 6900.00, 0.00, 108, 100),
(114, "Den", "Raphaely", "DRAPHEAL", "515.127.4561", '2002-12-07', "PU_MAN", 11000.00, 0.00, 100, 30),
(115, "Alexander", "Khoo", "AKHOO", "515.127.4562", '2003-05-18', "PU_CLERK", 3100.00, 0.00, 114, 30),
(116, "Shelli", "Baida", "SBAIDA", "515.127.4563", '2005-12-24', "PU_CLERK", 2900.00, 0.00, 114, 30),
(121, "Adam", "Fripp", "AFRIPP", "650.123.2234", '2005-04-10', "ST_MAN", 8200.00, 0.00, 100, 50),
(122, "Payam", "Kaufling", "PKAUFLIN", "650.123.3234", '2003-05-01', "ST_MAN", 7900.00, 0.00, 100, 50),
(123, "Shanta", "Vollman", "SVOLLMAN", "650.123.4234", '2005-10-10', "ST_MAN", 6500.00, 0.00, 100, 50),
(124, "Kevin", "Mourgos", "KMOURGOS", "650.123.5234", '2007-11-16', "ST_MAN", 5800.00, 0.00, 100, 50),
(125, "Julia", "Nayer", "JNAYER", "650.124.1214", '2005-07-16', "ST_CLERK", 3200.00, 0.00, 120, 50),
(126, "Irene", "Mikkilineni", "IMIKKILI", "650.124.1224", '2006-09-28', "ST_CLERK", 2700.00, 0.00, 120, 50),
(164, "Mattea", "Marvins", "MMARVINS", "011.44.1346.329268", '2008-01-24', "SA_REP", 7200.00, 0.10, 147, 80),
(165, "David", "Lee", "DLEE", "011.44.1346.529268", '2008-02-23', "SA_REP", 6800.00, 0.10, 147, 80),
(166, "Sundar", "Ande", "SANDE", "011.44.1346.629268", '2008-03-24', "SA_REP", 6400.00, 0.10, 147, 80),
(167, "Amit", "Banda", "ABANDA", "011.44.1346.729268", '2008-04-21', "SA_REP", 6200.00, 0.10, 147, 80),
(168, "Lisa", "Ozer", "LOZER", "011.44.1343.929268", '2005-03-11', "SA_REP", 11500.00, 0.25, 148, 80),
(169, "Harrison", "Bloom", "HBLOOM", "011.44.1343.829268", '2006-03-23', "SA_REP", 10000.00, 0.20, 148, 80),
(170, "Tayler", "Fox", "TFOX", "011.44.1343.729268", '2006-01-24', "SA_REP", 9600.00, 0.20, 148, 80),
(171, "William", "Smith", "WSMITH", "011.44.1343.629268", '2007-02-23', "SA_REP", 7400.00, 0.15, 148, 80),
(172, "Elizabeth", "Bates", "EBATES", "011.44.1343.529268", '2007-03-24', "SA_REP", 7300.00, 0.15, 148, 80),
(173, "Sundita", "Kumar", "SKUMAR", "011.44.1343.329268", '2008-04-21', "SA_REP", 6100.00, 0.10, 148, 80),
(174, "Ellen", "Abel", "EABEL", "011.44.1644.429267", '2004-05-11', "SA_REP", 11000.00, 0.30, 149, 80),
(175, "Alyssa", "Hutton", "AHUTTON", "011.44.1644.429266", '2005-03-19', "SA_REP", 8800.00, 0.25 , 149, 80),
(176, "Jonathon", "Taylor", "JTAYLOR", "011.44.1644.429265", '2006-03-24', "SA_REP", 8600.00, 0.20, 149, 80),
(177, "Jack", "Livingston", "JLIVINGS", "011.44.1644.429264", '2006-04-23', "SA_REP", 8400.00, 0.20, 149, 80),
(178, "Kimberely", "Grant", "KGRANT", "011.44.1644.429263", '2007-05-24', "SA_REP", 7000.00, 0.15, 149, 80);
insert employees (employee_ID, firstname, lastname, email, phonenumber, hire_date, job_id, salary, commission_pct, manager_id, department_id)
values
(179, "Doyin" , "McEwen", "DMCEWEN", "022.43.2123.43.2332", '2018-02-14', "IT_PROG", 12000.00, 0.15, 149, 60);
insert into job_history values (106, '2006-02-05', '2008-01-24', "SA_REP", 50),
(107, '2007-02-07', '2005-03-11', "FI_MGR", 30),
(108, '2002-08-17', '2006-04-11', "ST_CLERK", 100),
(109, '2002-08-16', '2008-04-21', "PU_MAN", 60),
(110, '2005-09-28', '2008-03-11', "PU_CLERK", 80),
(111, '2005-09-30', '2008-07-11', "FI_ACCOUNT", 60),
(112, '2006-03-07', '2006-09-24', "ST_MAN", 30),
(113, '2007-12-07', '2005-01-11', "IT_PROG", 60),
(114, '2002-12-07', '2007-03-24', "SA_REP", 50),
(115, '2003-05-18', '2008-05-11', "PU_CLERK", 50),
(116, '2005-12-24', '2006-08-20', "FI_ACCOUNT", 30),
(121, '2005-04-10', '2006-09-19', "PU_CLERK", 100),
(122, '2003-05-01', '2006-03-24', "FI_ACCOUNT", 60),
(123, '2005-10-10', '2006-04-23', "ST_MAN", 50),
(124, '2007-11-16', '2006-04-11', "FI_MGR", 30),
(125, '2005-07-16', '2008-01-24', "ST_CLERK", 100),
(126, '2006-09-28', '2009-02-23', "PU_MAN", 80),
(164, '2008-01-24', '2009-03-11', "IT_PROG", 60),
(165, '2008-02-23', '2009-04-21', "SA_REP", 80),
(166, '2008-03-24', '2009-03-12', "PU_CLERK", 60),
(167, '2008-04-21', '2010-03-11', "FI_ACCOUNT", 50),
(168, '2005-03-11', '2016-01-24', "ST_MAN", 50),
(169, '2006-03-23', '2017-02-23', "IT_PROG", 30),
(170, '2006-01-24', '2017-03-24', "SA_REP", 50),
(171, '2007-02-23', '2018-04-21', "FI_MGR", 50),
(172, '2007-03-24', '2018-03-11', "ST_CLERK", 30),
(173, '2008-04-21', '2015-03-19', "PU_MAN", 100),
(174, '2004-05-11', '2015-03-11', "PU_CLERK", 60),
(175, '2005-03-19', '2016-04-23', "FI_ACCOUNT", 50),
(176, '2006-03-24', '2017-05-24', "ST_MAN", 30),
(177, '2006-04-23', '2017-03-11', "IT_PROG", 100),
(178, '2007-05-24', '2017-06-11', "SA_REP", 80);
insert into job_grades values
("06", 1000.00, 3000.00, 5000.00),
("07", 3001.00, 5000.00, 7000.00),
("08", 5001.00, 7000.00, 10000.00),
("09", 7001.00, 9000.00, 13000.00),
("10", 9001.00, 11000.00, 15000.00),
("11", 11001.00, 13000.00, 17000.00),
("12", 13001.00, 15000.00, 25000.00),
("13", 15001.00, 17000.00, 22000.00),
("14", 17001.00, 19000.00, 27000.00),
("15", 19001.00, 21000.00, 30000.00);
|
C++
|
UTF-8
| 736 | 2.578125 | 3 |
[] |
no_license
|
// =====================================================================================
//
// Filename: main.cpp
//
// Description: Main file in which Game loops.
//
// Version: 1.0
// Created: 06/16/2020 06:21:24 AM
// Revision: none
// Compiler: g++
//
// Author: Itziar Morales Rodríguez (IMR), itzimr97@outlook.com
// Organization: UTAD
//
// =====================================================================================
#include <iostream>
#include "game.hpp"
#include "constants.hpp"
int main(int arg, char* args[])
{
Game game = Game::GetInstance();
game.Initialize(WINDOW_WIDTH, WINDOW_HEIGHT);
while (game.IsRunning()) {
game.Update();
game.Render();
}
game.Destroy();
return 0;
}
|
Python
|
UTF-8
| 3,337 | 2.96875 | 3 |
[] |
no_license
|
from arcball.arcball import ArcBall
FOV = PI/3.0
angle = 0.0
ANGLE_STEP = PI / 180.0
menger = []
def setup():
size(800,600, P3D)
global arcball
camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 / 180.0), 0, 0, 0, 0, 1, 0)
arcball = ArcBall(0, 0, height * 0.6)
def draw():
background(0, 0, 200)
lights()
defineLights()
update()
create_menger(0, 0, 0, arcball.radius)
def create_menger(xx, yy, zz, sz):
"""
Create a recursive menger sponge using my Cube class
"""
global menger
u = sz / 3.0
if (sz < 50):
my_cube(xx, yy, zz, sz)
else:
for i in range(-1, 2, 1):
for j in range(-1, 2, 1):
for k in range(-1, 2, 1):
if ((abs(i) + abs(j) + abs(k)) > 1):
create_menger(xx + (i * u), yy + (j * u), zz + (k * u), u)
def my_cube(xx, yy, zz, sz):
"""
Draw a cube with centre xx, yy, zz and size sz
"""
beginShape(QUADS)
normal(0, 0, 1)
vertex(-sz / 2.0 + xx, -sz / 2.0 + yy, -sz / 2.0 + zz)
vertex(+sz / 2.0 + xx, -sz / 2.0 + yy, -sz / 2.0 + zz)
vertex(+sz / 2.0 + xx, +sz / 2.0 + yy, -sz / 2.0 + zz)
vertex(-sz / 2.0 + xx, +sz / 2.0 + yy, -sz / 2.0 + zz)
#Back face
normal(0, 0, -1)
vertex(-sz / 2.0 + xx, -sz / 2.0 + yy, +sz / 2.0 + zz)
vertex(+sz / 2.0 + xx, -sz / 2.0 + yy, +sz / 2.0 + zz)
vertex(+sz / 2.0 + xx, +sz / 2.0 + yy, +sz / 2.0 + zz)
vertex(-sz / 2.0 + xx, +sz / 2.0 + yy, +sz / 2.0 + zz)
#Left face
normal(1, 0, 0)
vertex(-sz / 2.0 + xx, -sz / 2.0 + yy, -sz / 2.0 + zz)
vertex(-sz / 2.0 + xx, -sz / 2.0 + yy, +sz / 2.0 + zz)
vertex(-sz / 2.0 + xx, +sz / 2.0 + yy, +sz / 2.0 + zz)
vertex(-sz / 2.0 + xx, +sz / 2.0 + yy, -sz / 2.0 + zz)
#Right face
normal(-1, 0, 0)
vertex(+sz / 2.0 + xx, -sz / 2.0 + yy, -sz / 2.0 + zz)
vertex(+sz / 2.0 + xx, -sz / 2.0 + yy, +sz / 2.0 + zz)
vertex(+sz / 2.0 + xx, +sz / 2.0 + yy, +sz / 2.0 + zz)
vertex(+sz / 2.0 + xx, +sz / 2.0 + yy, -sz / 2.0 + zz)
#Top face
normal(0, 1, 0)
vertex(-sz / 2.0 + xx, -sz / 2.0 + yy, -sz / 2.0 + zz)
vertex(+sz / 2.0 + xx, -sz / 2.0 + yy, -sz / 2.0 + zz)
vertex(+sz / 2.0 + xx, -sz / 2.0 + yy, +sz / 2.0 + zz)
vertex(-sz / 2.0 + xx, -sz / 2.0 + yy, +sz / 2.0 + zz)
#Bottom face
normal(0, -1, 0)
vertex(-sz / 2.0 + xx, +sz / 2.0 + yy, -sz / 2.0 + zz)
vertex(+sz / 2.0 + xx, +sz / 2.0 + yy, -sz / 2.0 + zz)
vertex(+sz / 2.0 + xx, +sz / 2.0 + yy, +sz / 2.0 + zz)
vertex(-sz / 2.0 + xx, +sz / 2.0 + yy, +sz / 2.0 + zz)
endShape()
def defineLights():
"""
Without lights you wouldn't see the menger
"""
ambient(20, 20, 20)
ambientLight(50, 50, 50)
pointLight(30, 30, 30, 200, -150, 0)
directionalLight(0, 30, 50, 1, 0, 0)
spotLight(30, 30, 30, 0, 40, 200, 0, -0.5, -0.5, PI / 2, 2)
def update():
"""
wrap arcball update and rotation as a local function
"""
theta, x, y, z = arcball.update()
rotate(theta, x, y, z)
def mousePressed():
arcball.mousePressed(mouseX, mouseY)
def mouseDragged():
arcball.mouseDragged(mouseX, mouseY)
|
Swift
|
UTF-8
| 5,516 | 3.390625 | 3 |
[] |
no_license
|
//
// FormulaViewController.swift
// MathBeginner
//
// Created by Aluno Mack on 20/09/19.
// Copyright © 2019 Aluno Mack. All rights reserved.
//
import UIKit
class FormulaViewController: UIViewController {
@IBOutlet weak var DescricaoTexto: UITextView!
@IBOutlet weak var ImagemFormula: UIImageView!
@IBOutlet weak var ImagemExemplo: UIImageView!
var subtopicos = [["Triangulo","Triangulo Retangulo","Quadrado","Retangulo"],
["Polinomios","Fração","Exponenciação","Radiação"],
["Funções Trigonometrica","Lei das Tangentes" ,"Lei dos Senos" ,"Lei dos Cossenos"],
["Equação Linear", "Equação de 2 Grau","Equação Exponencial"],
["Limite","Derivada"]]
var descricaotopicos = [[
["Triângulo é um polígono de três lados e três ângulos. Há sete tipos de triângulos e sua classificação depende da disposição dos ângulos podendo ser: isósceles, equilátero, escaleno, retângulo, obtuso, agudo ou equiângulo."],
["Triângulo retângulo é um triângulo que possui um ângulo reto e outros dois ângulos agudos, para tanto basta que tenha um ângulo reto (90°), pois a soma dos três ângulos internos é igual a um ângulo raso (180°). Em um triângulo retângulo, sabendo-se as medidas de dois lados ou a medida de um lado mais a medida de um ângulo agudo, é possível calcular a medida dos demais lados e ângulos."],
["O quadrado é um polígono convexo que possui quatro lados. Em outras palavras, é uma figura geométrica plana que possui quatro lados congruentes e quatro ângulos retos. Dessa maneira, é chamado também de quadrilátero."],
["O retângulo é uma figura geométrica plana formada por quatro lados (quadrilátero) e apresenta os quatro ângulos internos congruentes (mesma medida) e retos (90°)."]],
[["Os polinômios são expressões algébricas formadas por números (coeficientes) e letras (partes literais). As letras de um polinômio representam os valores desconhecidos da expressão."],
["Fração é a forma de dividir alguma coisa através da razão de dois números inteiros. Dessa forma, nada mais é do que uma divisão onde o dividendo é numerador e o divisor é o denominador."],
["Exponenciação. da mesma forma que a multiplicação de n por a pode ser vista como uma soma de n parcelas iguais a a, ou seja, O expoente geralmente é indicado à direita da base, aparecendo sobrescrito ou separado da base por um circunflexo. Pode-se ler ancomo a elevado à n-ésima potência, ou simplesmente a elevado a n."],
["A radiciação é a operação inversa da potenciação. ... O símbolo utilizado para representar a raiz enésima de x é e é chamado de radical. Nesse símbolo, x é o radicando e n é o índice."]],
[["As funções trigonométricas são as funções relacionadas aos triângulos retângulos, que possuem um ângulo de 90°. São elas: seno, cosseno e tangente."],
["O círculo trigonométrico ou círculo unitário é usado no estudo das funções trigonométricas: seno, cosseno e tangente."],
["A Lei dos Senos serve para relacionar o seno do ângulo de um triângulo qualquer com o lado oposto a este ângulo."],
["A Lei dos Cossenos diz que podemos encontrar a medida de um lado de um triângulo, somando os lados opostos a ele e subtraindo pelo dobro do produto entre os lados opostos e o cosseno do ângulo, também, dos lados opostos."]],
[["Equaçao com um certo numero de variaveis onde cada termo não pode ter grau diferente de 1."],
["A equação do segundo grau recebe esse nome porque é uma equação polinomial cujo termo de maior grau está elevado ao quadrado."],
["As equações exponenciais são aquelas que possuem pelos menos uma incógnita no expoente e bases positivas diferentes de 1."]],
[["O limite de uma função é um conceito fundamental em cálculo e análise sobre o comportamento desta função quando próxima a um valor particular de sua variável independente."],
["No cálculo, a derivada em um ponto de uma função representa a taxa de variação instantânea de em relação a neste ponto."]],
]
var id:Int?
var subid:Int?
override func viewDidLoad() {
super.viewDidLoad()
if let identificador = id,let identificado_subid = subid
{
self.navigationItem.title = subtopicos[identificador][identificado_subid]
DescricaoTexto?.text = descricaotopicos[identificador][identificado_subid][0] as! String
ImagemFormula?.image = UIImage(named: "\(subtopicos[identificador][identificado_subid])Area")
ImagemExemplo?.image = UIImage(named: "\(subtopicos[identificador][identificado_subid])Exemplo")
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
C++
|
UTF-8
| 948 | 2.84375 | 3 |
[] |
no_license
|
swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
void permuteRec(vector<int> &a, vector<vector<int>> &b, int m, set<vector<int>> &s){
if(m == a.size()-1){
if(s.find(a) == s.end()) {
b.push_back(a);
s.insert(a);
}
} else{
for(int i = m; i < a.size(); i++){
swap(a[m], a[i]);
permuteRec(a, b, m+1, s);
swap(a[m], a[i]);
}
}
}
vector<vector<int> > Solution::permute(vector<int> &A) {
vector<vector<int>> ret_vec;
set<vector<int>> s;
permuteRec(A, ret_vec, 0, s);
sort(ret_vec.begin(), ret_vec.end());
return ret_vec;
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
}
|
PHP
|
UTF-8
| 4,611 | 2.671875 | 3 |
[] |
no_license
|
<?php
require_once('../../config.php');
//Start session
require_once('../../auth.php');
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" />
<title>Public Page</title>
<!--external style sheet-->
<link rel="stylesheet" type="text/css" href="../../mystyle.css" />
<link REL="SHORTCUT ICON" HREF="../../images/ico/public.ico">
</head>
<body>
<?php
//user.php
$userid=$_REQUEST["userid"];
$query = "SELECT fname,lname FROM users WHERE id=$userid";
$result = mysql_query($query);
while(list($fname,$lname)= mysql_fetch_row($result))
{
$name= $fname." ".$lname;
?>
<div id="container">
<div id="header">
<h1 color="blue">
Welcome to Reflective <i>e</i>Journal!
</h1>
</div>
<!-- his friends @ <a href="../friends.php?userid= echo $userid; ">Friends</a>-->
<div id="navigation">
<table width="800" border=0 align="center">
<tr>
<td><ul>
<li><a href="public.php?userid=<?php echo $userid; ?>"> <?php echo $fname; ?></a></li>
<li><a href="../friends.php"><?php echo $fname; ?>'s Friends</a></li>
<li><a href="../message/index.php?userid=<?php echo $userid; ?>">Leave a Message</a></li>
</ul></td>
<td width="150"> </td>
<td align="right"><ul class="a">
<li><a href="student_home.php">My Home</a></li>
<li><a href="../settings.php">My Settings</a></li>
<li><a href="../../logout.php">Logout</a></li>
</ul></td>
</tr>
</table>
</div>
<?php } ?>
<br><br>
<h1><?php echo $name; ?>'s Page</h1>
<table width=800 border=2 align="center">
<tr ><td width=550 height="300">
<div id="content-container">
<div id="content">
<h2>
List of <?php echo $name; ?>'s journals
</h2>
<?php
//$userid=clean($_SESSION['SESS_MEMBER_ID']);
// how many rows to show per page
$rowsPerPage = 50;
// by default we show first page
$pageNum = 1;
// if $_GET['page'] defined, use it as page number
if(isset($_GET['page']))
{
$pageNum = $_GET['page'];
}
// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;
$query1 = "SELECT log_id,title,author,add_time,language,content
FROM journals
where user_id=$userid
ORDER BY log_id DESC
LIMIT $offset, $rowsPerPage";
$result1 = mysql_query($query1) or die('Error, query failed');
$total_items = mysql_num_rows($result1);
echo "<br/><p align='center'>Totle number of journals is ".$total_items."!</p>";
// print the journals info in table
while(list($log_id,$title, $author, $add_time, $language,$content) = mysql_fetch_array($result1))
{
?>
<table width=400 height="10">
<tr><td colspan = 3 ><h3><li><a href="../journals/journal_content.php?logid=<?php echo $log_id; ?>&userid=<?php echo $userid; ?>" target="_parent"/><?php echo $title; ?></a></li></h3></td></tr>
<tr><td>posted by: <?php echo $author;?></td><td>| at: <?php echo $add_time;?></td><td>| about: <?php echo $language;?></td></tr>
</table>
<?php
};
echo '<br>';
// how many rows we have in database
$query = "SELECT COUNT(log_id) AS numrows FROM journals";
$result = mysql_query($query) or die('Error, query failed');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
// ... just the same code that prints the prev & next link
?>
</div>
</td><td align="justify">
<table border=3 width=250 height="200" >
<tr width=250 height="200">
<td height="200">
<div id="aside">
<h3>
<?php echo $name; ?>'s Profile
</h3>
<br/>
<?php
$query2 = "SELECT matric,semester,session,gp,email,website
FROM users where id=$userid";
$result2 = mysql_query($query2) or die('Error, query failed');
while(list($matric,$semester,$session,$gp,$email,$website)= mysql_fetch_row($result2))
{
echo "-id is ".$userid."<br/>-Matric Number is ".$matric."<br/>-Semester $semester Session $session<br>" .
"-$gp Group<br>" .
"-email: $email<br>".
"-website: <a href=".$website. ">$website</a><br>";
}
?></div></td></tr>
<br><br><br>
<tr><td height="300" align="center">
<?php
$pathToShoutBox = '../shoutbox/';
include("$pathToShoutBox/shoutbox.inc.php");
date_default_timezone_set('Asia/Brunei'); //set time zone as UTC+8
?>
</td></tr></table></td></tr></table>
<div id="footer">
copyright © Universiti Kebangsaan Malaysia
</div>
</body>
</html>
|
C++
|
UTF-8
| 3,929 | 3.046875 | 3 |
[] |
no_license
|
#include "UtilFunctions.h"
#include <iostream>
#include <math.h>
#include <stdlib.h>
namespace easymath{
double L2_norm(matrix1d a, matrix1d b){
try{
if (a.size() != b.size())
throw "Cannot compute L2 norm, vectors of different size!" ;
matrix1d c = dot_multiply(a-b) ;
return sqrt(sum(c)) ;
}
catch(const char * msg){
std::cerr << msg << std::endl ;
}
}
double L2_norm(XY a, XY b){
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)) ;
}
matrix1d dot_multiply(matrix1d a){
matrix1d c ;
for (size_t i = 0; i < a.size(); i++)
c.push_back(a[i]*a[i]) ;
return c ;
}
matrix1d dot_multiply(matrix1d a, matrix1d b){
try{
if (a.size() != b.size())
throw "Cannot compute dot product, vectors of different size!" ;
matrix1d c ;
for (size_t i = 0; i < a.size(); i++)
c.push_back(a[i]*b[i]) ;
return c ;
}
catch(const char * msg){
std::cerr << msg << std::endl ;
}
}
matrix2d matrix_mult(matrix2d A, matrix2d B){
try{
if (A[0].size() != B.size())
throw "ERROR [mxn]: Cannot compute matrix multiplication, matrix dimensions do not match!" ;
matrix2d C = zeros(A.size(),B[0].size()) ;
for (size_t i = 0; i < C.size(); i++){
for (size_t j = 0; j < C[0].size(); j++){
matrix1d b ;
for (size_t k = 0; k < B.size(); k++)
b.push_back(B[k][j]) ;
C[i][j] = sum(dot_multiply(A[i],b)) ;
}
}
return C ;
}
catch(const char * msg){
std::cerr << msg << std::endl ;
}
}
matrix1d matrix_mult(matrix1d A, matrix2d B){
try{
if (A.size() != B.size())
throw "ERROR [1xn]: Cannot compute matrix multiplication, matrix dimensions do not match!" ;
matrix1d C = zeros(B[0].size()) ;
for (size_t j = 0; j < C.size(); j++){
matrix1d b ;
for (size_t k = 0; k < B.size(); k++)
b.push_back(B[k][j]) ;
C[j] = sum(dot_multiply(A,b)) ;
}
return C ;
}
catch(const char * msg){
std::cerr << msg << std::endl ;
std::cout << A.size() << " " << B.size() << std::endl ;
}
}
matrix1d matrix_mult(matrix2d A, matrix1d B){
try{
if (A[0].size() != B.size())
throw "ERROR [nx1]: Cannot compute matrix multiplication, matrix dimensions do not match!" ;
matrix1d C = zeros(A.size()) ;
for (size_t i = 0; i < C.size(); i++)
C[i] = sum(dot_multiply(A[i],B)) ;
return C ;
}
catch(const char * msg){
std::cerr << msg << std::endl ;
}
}
double determinant(matrix2d A){
try{
if (A.size() != A[0].size())
throw "ERROR [matrix determinant]: Cannot compute matrix determinant of non-square matrix!" ;
// Calculate determinant
double det ;
return det ;
}
catch(const char * msg){
std::cerr << msg << std::endl ;
}
}
matrix2d chol(matrix2d A){
try{
if (A.size() != A[0].size())
throw "ERROR [Cholesky decomposition]: Cannot compute Cholesky decomposition of non-square matrix!" ;
// Calculate Cholesky decomposition
matrix2d cholesky ;
return cholesky ;
}
catch(const char * msg){
std::cerr << msg << std::endl ;
}
}
matrix2d inverse(matrix2d A){
try{
if (A.size() != A[0].size())
throw "ERROR [Matrix inverse]: Cannot compute inverse of non-square matrix!" ;
// Calculate Cholesky decomposition
matrix2d inv ;
return inv ;
}
catch(const char * msg){
std::cerr << msg << std::endl ;
}
}
matrix1d unit_vector(matrix1d v){
matrix1d origin = zeros(2) ;
double norm = L2_norm(v,origin) ;
matrix1d u ;
u.push_back(v[0]/norm) ;
u.push_back(v[1]/norm) ;
return u ;
}
double rand(double low, double high) {
double r = static_cast<double>(std::rand()) / static_cast<double>(RAND_MAX);
return r*(high - low) + low;
}
double pi_2_pi(double x){
x = fmod(x+PI,2.0*PI) ;
if (x < 0.0)
x += 2.0*PI ;
return x - PI ;
}
} // namespace easymath
|
C++
|
UTF-8
| 2,245 | 3.6875 | 4 |
[] |
no_license
|
/* CPSC2380
* Department of Computer Science, UALR
* Project 3
* Student Name: Thomas Marcoux
* Student UALR ID (last four digits): 5564
* Project Descriptions:
* This project takes an arithmetic expression as input,
* converts it to postfix, then to a binary tree which it prints
* along with its infix, postfix and prefix expression
* as well as the evaulation of the tree.
* Project Due Date: 12/4/2014
* Project Revised Date: 11/30/2014, 12/03/2014
*/
#include <iostream>
#include <iomanip>
#include <stack>
#include "node.h"
Node::Node(std::string value)
: value(value), leftChild(NULL), rightChild(NULL) {}
Node::Node(std::string value, Node* leftChild, Node* rightChild)
: value(value), leftChild(leftChild), rightChild(rightChild) {}
Node::~Node()
{
delete this->leftChild;
delete this->rightChild;
}
std::string Node::getValue() const
{
return this->value;
}
Node* Node::getLeftChild() const
{
return this->leftChild;
}
Node* Node::getRightChild() const
{
return this->rightChild;
}
void Node::setLeftChild(Node* leftChild)
{
this->leftChild = leftChild;
}
void Node::setRightChild(Node* rightChild)
{
this->rightChild = rightChild;
}
void Node::printTree(int w) const
{
if (!this)
return;
Node* l = this->getLeftChild();
Node* r = this->getRightChild();
std::cout << std::setw(w);
std::cout << this->getValue();
if (l || r)
std::cout << ":";
std::cout << std::endl;
w += 2;
l->printTree(w);
r->printTree(w);
}
void Node::printInfix() const
{
if (!this)
return;
Node* l = this->getLeftChild();
Node* r = this->getRightChild();
l->printInfix();
std::cout << this->getValue() << " ";
r->printInfix();
}
void Node::printPostfix() const
{
if (!this)
return;
Node* l = this->getLeftChild();
Node* r = this->getRightChild();
l->printPostfix();
r->printPostfix();
std::cout << this->getValue() << " ";
}
void Node::printPrefix()
{
std::stack<Node*> stk;
Node* node = this;
while (!stk.empty() || node)
{
if (node)
{
std::cout << node->getValue() << " ";
if (node->getRightChild())
stk.push(node->getRightChild());
node = node->getLeftChild();
}
else
{
node = stk.top();
stk.pop();
}
}
}
|
Python
|
UTF-8
| 820 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
import libs
import struct
import math
import os
from libs import Bitmap
from libs import word
#Objet to draw
img = None
#Constructor
def glInit():
return None
#Init FrameBuffer
def glCreateWindow(width, height):
global img
img = Bitmap(width,height)
#Delete actual image
def glClear():
img.clear()
#Image area can draw
def glViewPort(x,y,widht, height):
img.viewPort(x,y,widht, height)
#Get Color
def glColor(r,g,b):
img.color(r,g,b)
#Init canvas with new color
def glClearColor(r,g,b):
img.clearColor(0,0,0)
#Get new x,y points
def glVertex(x,y):
img.vertex(x,y)
#Show new image
def glFinish():
img.display("materials.bmp")
glCreateWindow(800,600)
glViewPort(0,0,799,599)
glClear()
img.load( 'chip.obj', 'chip.mtl', (0.5, 0.5, 0.5), (500, 500, 500))
glFinish()
|
Java
|
UTF-8
| 705 | 2.234375 | 2 |
[] |
no_license
|
package com.employee.service.request.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
public class GenericMessage<T> {
@JsonProperty("message")
private String message;
@JsonProperty("responseBody")
private T messageBody;
public GenericMessage(String message, T messageBody) {
this.message = message;
this.messageBody = messageBody;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getMessageBody() {
return messageBody;
}
public void setMessageBody(T messageBody) {
this.messageBody = messageBody;
}
}
|
Python
|
UTF-8
| 239 | 2.5625 | 3 |
[
"MIT",
"LicenseRef-scancode-public-domain"
] |
permissive
|
from puq import *
def run():
x = UniformParameter('x', 'x', min=0, max=10)
host = InteractiveHost()
uq = LHS([x], 100, True)
prog = TestProgram('python poly_prog.py', desc='1D Polynomial')
return Sweep(uq, host, prog)
|
Java
|
UTF-8
| 7,378 | 1.820313 | 2 |
[] |
no_license
|
package com.dmeyc.dmestoreyfm.ui;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.dmeyc.dmestoreyfm.R;
import com.dmeyc.dmestoreyfm.base.BaseActivity;
import com.dmeyc.dmestoreyfm.base.BaseFragment;
import com.dmeyc.dmestoreyfm.bean.SearchKeyBean;
import com.dmeyc.dmestoreyfm.constant.Constant;
import com.dmeyc.dmestoreyfm.fragment.SearchRecordFragment;
import com.dmeyc.dmestoreyfm.fragment.SearchResultFragment;
import com.dmeyc.dmestoreyfm.net.DmeycBaseSubscriber;
import com.dmeyc.dmestoreyfm.net.ParamMap;
import com.dmeyc.dmestoreyfm.net.RestClient;
import com.dmeyc.dmestoreyfm.present.SearchPresenter;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.OnClick;
public class SearchGoodsActivity extends BaseActivity<SearchPresenter> {
@Bind(R.id.et_search_title)
EditText etSearchTitle;
@Bind(R.id.tv_search)
TextView tvSearch;
@Bind(R.id.ll_list)
LinearLayout ll_list;
private SearchRecordFragment searchFragment;
private SearchResultFragment resultFragment;
private List<SearchKeyBean> searchKeyBeanList = new ArrayList<>();
private boolean isSearch = true;
@Override
protected SearchPresenter initPresenter() {
return new SearchPresenter();
}
@Override
protected int getLayoutRes() {
return R.layout.activity_search;
}
@Override
protected void initData() {
searchFragment = new SearchRecordFragment();
resultFragment = new SearchResultFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.frame_container, searchFragment)
.add(R.id.frame_container, resultFragment)
.show(searchFragment)
.hide(resultFragment)
.commit();
etSearchTitle.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (hasFocus && searchFragment.isHidden()) {
// fragmentTransaction.show(searchFragment).hide(resultFragment);
// fragmentTransaction.commit();
showFragment(searchFragment);
}
}
});
etSearchTitle.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
if (!isSearch) {
return;
}
RestClient.getNovate(SearchGoodsActivity.this).get(Constant.API.PRODUCT_SEARCH_KEY, new ParamMap.Build().addParams("keyword", etSearchTitle.getText().toString()).build()
, new DmeycBaseSubscriber<SearchKeyBean>(SearchGoodsActivity.this) {
@Override
public void onSuccess(SearchKeyBean bean) {
searchKeyBeanList.clear();
searchKeyBeanList.add(bean);
if (searchKeyBeanList != null && searchKeyBeanList.get(0).getData().size() > 0) {
addSonView();
}
}
});
}
});
}
private void addSonView() {
ll_list.setVisibility(View.VISIBLE);
ll_list.removeAllViews();
for (int i = 0; i < searchKeyBeanList.get(0).getData().size(); i++) {
final LinearLayout sonView = (LinearLayout) LayoutInflater.from(SearchGoodsActivity.this).inflate(
R.layout.son_ll_search_list, null);
TextView text_name = sonView.findViewById(R.id.text_name);
text_name.setText(searchKeyBeanList.get(0).getData().get(i));
final int finalI = i;
text_name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ll_list.setVisibility(View.GONE);
if (!resultFragment.isAdded() || resultFragment.isHidden()) {
isSearch = false;
etSearchTitle.setText(searchKeyBeanList.get(0).getData().get(finalI));
doSearch(searchKeyBeanList.get(0).getData().get(finalI));
searchFragment.addHistoryRecord(searchKeyBeanList.get(0).getData().get(finalI));
}
}
});
ll_list.addView(sonView);
}
}
@OnClick({R.id.tv_search})
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_search:
ll_list.setVisibility(View.GONE);
isSearch = true;
if (TextUtils.equals("取消", tvSearch.getText().toString())) {
etSearchTitle.setText("");
onBackPressed();
} else {
if (TextUtils.isEmpty(etSearchTitle.getText().toString())) {
Toast.makeText(this, "搜索不能为空", Toast.LENGTH_SHORT).show();
return;
}
if (!resultFragment.isAdded() || resultFragment.isHidden()) {
doSearch(etSearchTitle.getText().toString());
searchFragment.addHistoryRecord(etSearchTitle.getText().toString());
}
}
break;
}
}
/**
* 设置搜索结果
*
* @param content
*/
public void setEtSearchContent(String content) {
etSearchTitle.setText(content);
etSearchTitle.setSelection(content.length());
}
public void doSearch(String content) {
tvSearch.setText("取消");
etSearchTitle.clearFocus();
showFragment(resultFragment);
resultFragment.search(content);
}
@Override
protected boolean isContainTitle() {
return false;
}
public void showFragment(BaseFragment fm) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (fm instanceof SearchRecordFragment) {
fragmentTransaction.show(searchFragment).hide(resultFragment).commit();
} else if (fm instanceof SearchResultFragment) {
fragmentTransaction.show(resultFragment).hide(searchFragment).commit();
}
}
@Override
public void onBackPressed() {
if (!searchFragment.isAdded() || searchFragment.isHidden()) {
showFragment(searchFragment);
tvSearch.setText("搜索");
return;
}
super.onBackPressed();
}
}
|
JavaScript
|
UTF-8
| 24,742 | 2.6875 | 3 |
[
"Apache-2.0"
] |
permissive
|
class ultimateFormHandler {
constructor() {
this.inputTypes = {
'str': ['checkbox', 'color', 'date', 'datetime-local', 'hidden', 'month', 'password', 'radio', 'search', 'text', 'time', 'url', 'week'],
'int': ['number', 'range', 'tel'],
'eml': ['email'],
'bol': ['button', 'image', 'reset', 'submit'],
'obj': ['file']
};
this.formHandlers = {
'errors': {}
};
this.formError = {};
// get all the forms in the page with a valid
var forms = document.forms;
// foreach of the forms add an event listener and stop browser default
for (let index = 0; index < forms.length; index++) {
const form = forms[index];
// check to see if the system should handle form
if (form.hasAttribute('data-form-validate') && form.getAttribute('data-form-validate') != false) {
// get error file if set
this.loadJsonErrorFile(form);
form.addEventListener('submit', (e) => {
this.processForm(e);
});
// check if the user has live validate
if (form.getAttribute('data-form-validate') == 'live') {
var inputs = form.elements;
for (let i = 0; i < inputs.length; i++) {
const element = inputs[i];
// check if live update is set for this item
if (element.hasAttribute('data-live')) {
element.addEventListener('input', el => {
this.processLiveInput(el.target);
});
}
}
}
}
}
}
/**
* loadJsonErrorFile
* @param {*} form
* @return boleand
* @description this method initias errors to be used for each form element.
*/
loadJsonErrorFile(form) {
if (form.hasAttribute('data-form-error-file') && form.getAttribute('data-form-error-file').length > 5) {
// send get request to obtain json file
$.ajax({
url: form.getAttribute('data-form-error-file'),
type: 'get',
dataType: 'JSON',
success: function (response) {
if (Object.keys(response).indexOf(form.getAttribute('id').toLowerCase) !== false) {
this.formHandlers.errors[form.getAttribute('id').toLowerCase] = response[form.getAttribute('id').toLowerCase];
} else {
this.formHandlers.errors[form.getAttribute('id').toLowerCase] = response;
}
},
}).fail(e => {
console.log(form.getAttribute('id') + ' Failed to load error file.', e);
})
}
}
/**
* ProcessForm
* @param {*} e instance of the form element
* @returns null
*/
processForm(e) {
e.preventDefault();
var form = e.target;
// check for call backs
var callback;
if (form.hasAttribute('data-form-callback') && form.getAttribute('data-form-callback').length > 1) {
callback = form.getAttribute('data-form-callback');
}
// check to see if you can submit with ajax or normally
var processAjax = true;
if (form.hasAttribute('data-form-ajax-request') && form.getAttribute('data-form-ajax-request') != 'true') {
if (form.getAttribute('data-form-ajax-request') == 'false') {
processAjax = false;
} else {
processAjax = 'function';
}
}
var inputs = form.elements;
var formAuth = true;
var submitButton;
for (let i = 0; i < inputs.length; i++) {
const element = inputs[i];
// register submit button
if(element.getAttribute('type') == 'submit'){ submitButton = element; continue; }
// check if live update is set for this item
var check = this.processElements(element);
if (check === false) {// there is an error in the file
formAuth = false;
break;
}
}
// handle result
if (formAuth == true) {
// check if submit button has action to wait
if(submitButton && submitButton.hasAttribute('data-action') && submitButton.getAttribute('data-action') == 'disabled'){
submitButton.disabled = true;
}
if (processAjax == 'function') {
// find object
var fn = window[callback];
// is object a function?
var formData = new FormData(form);
if (typeof fn === "function") { fn(formData, this); } else {
console.log('Could not find function ' + callback);
};
} else if (processAjax === true) {
var action = form.getAttribute('action');
var method = form.getAttribute('method') || 'get';
var formData = new FormData(form);
$.ajax({
url: action,
type: method,
dataType: 'JSON',
data: formData,
processData: false,
contentType: false
}).done(response => {
if (callback) {
// find object
var fn = window[callback];
// is object a function?
if (typeof fn === "function") { fn(response, this); } else {
console.log('Could not find ajax callback function ' + callback);
};
}
// reset button
if(submitButton && submitButton.hasAttribute('data-action') && submitButton.getAttribute('data-action') == 'disabled'){
submitButton.disabled = false;
}
}).fail(error => {
console.log('Post route not found.\nError:: ', error);
// reset button
if(submitButton && submitButton.hasAttribute('data-action') && submitButton.getAttribute('data-action') == 'disabled'){
submitButton.disabled = false;
}
});
} else { // remove event listener and submit
form.removeEventListener('submit', e => { console.log(e) });
form.removeAttribute('onsubmit');
// submit form
form.submit();
}
} else {
// send error to approprait screen
var message = (Object.keys(this.formHandlers.errors).indexOf(form.getAttribute('id').toLowerCase()) >= 0) ? this.formHandlers.errors[form.getAttribute('id').toLowerCase()][this.formError.input.getAttribute('id')] : (this.formError.input.getAttribute('data-message') || '');
// check if append is allowed
if (form.hasAttribute('data-form-append-errors') && form.getAttribute('data-form-append-errors') != 'false') {
message += ' ' + this.formError.append;
}
this.formErr(this.formError.input, message);
}
}
// send request to user after custom implementations
/**
* sendRequest for action called out of the class
* @param {*} url
* @param {*} type
* @param {*} data
* @param {*} callback
* @returns empty or string on failed. ON Ajax completion returns a call to callback function
*/
sendRequest(url, type, data, callback) {
var error = '';
if (url.length > 1) {
if (type.length > 0) {
$.ajax({
url: url,
type: type,
dataType: 'JSON',
data: data,
processData: false,
contentType: false
}).done(response => {
if (callback) {
// find object
var fn = window[callback];
// is object a function?
if (typeof fn === "function") { fn(response, this); } else {
console.log('Could not find function ' + callback);
};
}
}).fail(error => {
console.log(error);
});
} else {
error = 'Invalid request type.';
}
} else {
error = 'Invalid request url.';
}
if (error) {
return error;
}
}
/**
* ProcessLiveInput
* @param {*} input the input field itself
* @description an event listener which will handle user inputs as they key in values to the live validate fields
*/
processLiveInput(input) {
var response = this.processElements(input);
var form = input.form;
if (response === false) {
// send error to approprait screen
var message = (Object.keys(this.formHandlers.errors).indexOf(form.getAttribute('id').toLowerCase()) >= 0) ? this.formHandlers.errors[form.getAttribute('id').toLowerCase()][this.formError.input.getAttribute('id')] : (this.formError.input.getAttribute('data-message') || '');
// check if append is allowed
if (form.hasAttribute('data-form-append-errors')) {
message += ' ' + this.formError.append;
}
this.formErr(this.formError.input, message);
}
}
/**
* scrollToInput
* @param {*} input
* @description Scroll an input element into view
*/
scrollToInput(input) {
input.parentNode.scrollIntoView();
input.scrollIntoView(true);
// add space to inview
var scrolledY = window.scrollY;
if (scrolledY) {
window.scroll(0, scrolledY - 100);
}
}
// function for content form error
/**
* FormErr
* @param {*} input the input field with invalid data
* @param {*} msg the error message to display to the user
* @description return an alert to the user of inputs with invalid data.
*/
formErr(input, msg) {
try {
if (input) {
// var input = idAppend + id;
this.scrollToInput(input);
$(input).addClass('is-invalid');
$(input).removeClass('mb-3');
// check for error container
var parent = input.parentElement;
var errorId = (input.getAttribute('id') || input.getAttribute('name')) + '_msg';
var span = parent.querySelector('#' + errorId) != undefined;
if (span != undefined) {
span = document.createElement('div');
span.setAttribute('id', errorId);
span.setAttribute('class', 'text-danger mb-3');
parent.appendChild(span);
}
$('#' + errorId).html(msg);
// remove error from page after view
setTimeout(() => {
$(input).removeClass('is-invalid');
$(input).addClass('mb-3');
$('#' + errorId).html('');
}, 5000);
}
} catch (e) {
console.log(e);
}
}
/**
* ProcessElements
* @param {*} input
* @returns boolean
*/
processElements(input) {
// convert all attributes to lowercase for standardization
var attributes = input.attributes;
for (let index = 0; index < attributes.length; index++) {
const element = attributes[index].nodeName;
input.setAttribute(element.toLowerCase(), input.getAttribute(element))
}
switch (input.tagName) {
case 'INPUT':
// code block
return this.input(input);
case 'SELECT':
// code block
return this.select(input);
case 'TEXTAREA':
return this.input(input);
default:
// code block
}
}
/**
* Input handles all input other than select input field
* @param {*} input
* @returns bolean true for is valid false for invalid input field.
*/
input(input) {
var type = input.hasAttribute('type') ? input.getAttribute('type').toLowerCase() : '';
// check the input type
for (const [key, value] of Object.entries(this.inputTypes)) {
if (value.indexOf(type) >= 0) {
switch (key) {
case 'eml':
return this.validateEmail(input);
case 'str':
return this.validateString(input);
case 'int':
return this.validateInteger(input)
case 'obj':
return this.validateObject(input);
default:
break;
}
break;
}
}
}
/**
* Hanndle select input fields
* @param {*} input
* @returns boolean
* @description This function handles input type select for both single and multiple select input fields
*/
select(input) {
// for select we will need to create a text element
var inputElement = document.createElement('input');
var value = input.value;
if (input.hasAttribute('multiple')) {
value = $(input).val().toString();
}
inputElement.setAttribute('type', 'text');
inputElement.setAttribute('value', value);
for (let index = 0; index < input.attributes.length; index++) {
var attribute = input.attributes[index];
var attributeValue = attribute.nodeValue;
if (['id', 'name'].indexOf(attribute.nodeName.toLowerCase()) >= 0) {
attributeValue += '_' + Math.random();
}
inputElement.setAttribute(attribute.nodeName.toLowerCase(), attributeValue);
}
var check = this.validateString(inputElement);
// check to see if the item has min or max values
if (input.hasAttribute('multiple')) {
var min = input.hasAttribute('data-select-min') ? input.getAttribute('data-select-min') * 1 : 0;
var max = input.hasAttribute('data-select-max') ? input.getAttribute('data-select-max') * 1 : 0;
var object = $(input).val();
if (min > 0 && object.length < min) {
check = false;
this.formError.input = input;
this.formError.append = ' Select at lease ' + min + ' item' + (min > 1 ? 's' : '') + '.';
} else if (max > 0 && object.length > max) {
check = false;
this.formError.input = input;
this.formError.append = ' Select at most ' + max + ' item' + (max > 1 ? 's' : '') + '.';
}
}
return check
}
/**
* ValidateEmail Address
* @param {*} input
* @returns boolean
* @description This functions checks to ensure a valid email address has been inserted into the form field.
*/
// process validations for str, int and bol
validateEmail(input) {
var value = input.value();
// check if it has a full stop and
var exp = value.split('@');
if (exp.length == 2) {
var expdot = val.split('.');
if (expdot.length > 0) {
return this.validateString(value);
} else {
this.formError.input = input;
this.formError.append = 'Invalid email.';
}
} else {
this.formError.input = input;
this.formError.append = 'Invalid email address.';
}
}
/**
* ValidateString
* @param {*} input
* @returns boolean
* @description This function will validate a string base on the regular expression provided bellow
*/
validateString(input) {
var value = input.value;
value = value.replace(/[^a-zA-Z0-9 \_\-\,\(\)\!\=\.\@\'\"]/gim, '');
// check conditions
var minLength = input.hasAttribute('minlength') ? input.getAttribute('minlength').replace(/[^0-9]/g, '') * 1 : 0;
var maxLength = input.hasAttribute('maxlength') ? input.getAttribute('maxlength').replace(/[^0-9]/g, '') * 1 : 0;
var check = false;
if (!input.hasAttribute('data-validate') || (input.hasAttribute('data-validate') && input.getAttribute('data-validate') != false)) {
if (value.length < minLength) {
// error
this.formError.input = input;
this.formError.append = 'Input must be at least ' + minLength + ' character' + (minLength > 1 ? 's' : '') + '.';
} else if (maxLength > 0 && value.length > maxLength) {
// error
this.formError.input = input;
this.formError.append = 'Input must be at most ' + maxLength + ' character' + (maxLength > 1 ? 's' : '') + '.';
} else {
check = true;
}
}
if (check !== false && value != '') {
check = value;
input.value = value;
}
return check;
}
/**
* Validate Integer
* @param {*} input
* @returns bolean
*/
validateInteger(input) {
var value = input.value;
try {
value = value.replace(/[^0-9.]/g, '');
// check conditions
var minLength = input.hasAttribute('minlength') ? input.getAttribute('minlength').replace(/[^0-9]/, '') * 1 : 0;
var min = input.hasAttribute('min') ? input.getAttribute('min').replace(/[^0-9]/, '') * 1 : 0;
var maxLength = input.hasAttribute('maxlength') ? input.getAttribute('maxlength').replace(/[^0-9]/, '') * 1 : 0;
var max = input.hasAttribute('max') ? input.getAttribute('max').replace(/[^0-9]/, '') * 1 : 0;
var check = false;
if (!input.hasAttribute('data-validate') || (input.hasAttribute('data-validate') && input.getAttribute('data-validate') != 'false')) {
if (value.length < minLength) {
// error
this.formError.input = input;
this.formError.append = 'Input must be at least ' + minLength + ' character' + (minLength > 1 ? 's' : '') + '.';
} else if (maxLength > 0 && value.length > maxLength) {
// error
this.formError.input = input;
this.formError.append = 'Input must be at most ' + maxLength + ' character' + (maxLength > 1 ? 's' : '') + '.';
} else if (value < min) {
// error
this.formError.input = input;
this.formError.append = 'Minimum allowed value ' + min + '.';
} else if ((max > 0 && value > max)) {
this.formError.input = input;
this.formError.append = 'Maximum allowed value ' + max + '.';
} else {
check = true;
}
} else {
check = true;
}
} catch (e) {
console.log(e);
this.formError.input = input;
this.formError.append = 'Cannot process interger.';
}
if (check !== false) {
check = value;
input.value = value;
}
return check;
}
/**
* ValidateRadio, Used for input radio validations
* @param {*} input
* @returns boolean
*/
validateRadio(input) {
// get all the raio with this name
var name = input.getAttribute('name');
var radios = document.querySelector(`input[name=${name}]`);
var value = document.querySelector(`input[name=${name}:checked]`);
// the first radio will carry the settings
var inputElement = document.createElement('input');
inputElement.setAttribute('type', 'text');
inputElement.setAttribute('value', value);
// get attributes of the first radio
for (let index = 0; index < radios[0].length; index++) {
const attributes = radios[0][index].attributes;
attributes.forEach(attribute => {
inputElement.setAttribute(attribute.nodeName.toLowerCase, attribute.nodeValue);
});
}
// send element to be processed
return this.validateString(inputElement);
}
/**
* Validate objects mostly used for file processing
* @param {*} input
* @returns boolean
*/
validateObject(input) {
var files = input.files;
// get specifications such as required, min size, count max size
var maxSize = input.hasAttribute('data-file-max-size') ? input.getAttribute('data-file-max-size').replace(/[^0-9.]/g, '') * 1 : null; // in mb
var minSize = input.hasAttribute('data-file-min-size') ? input.getAttribute('data-file-min-size').replace(/[^0-9.]/g, '') * 1 : null; // in mb
var extensions = input.hasAttribute('data-file-extensions') ? input.getAttribute('data-file-extensions').replace(/[^a-zA-Z\,]\s/g, '').toLowerCase() : ''; // separate types with comma or use detault image [jpg, png, gif], doc
var fileCountMax = input.hasAttribute('data-file-max-count') ? input.getAttribute('data-file-max-count').replace(/[^0-9]/g, '') * 1 : 0;// how many files expected
var fileCountMin = input.hasAttribute('data-file-min-count') ? input.getAttribute('data-file-min-count').replace(/[^0-9]/g, '') * 1 : 0;// how many files expected
if (files.length <= fileCountMax) {
if (files.length >= fileCountMin) {
var extensionList = extensions.split(',');
for (let index = 0; index < files.length; index++) {
const file = files[index];
var fileName = file.name;
var fileSize = (file.size / 1052675.49738).toFixed(2);// files.size;
var fileType = file.type;
var fileExtension = fileType.split('/')[1];
if (minSize < 1 || fileSize >= minSize) {
if (maxSize < 1 || fileSize <= maxSize) {
if (extensionList.length < 1 || extensionList.indexOf(fileExtension) !== false) {
// all is well
check = true;
} else {
this.formError.input = input;
this.formError.append = fileName + ' an has invalid file type. Accepted file formats are ' + extensions;
break;
}
} else {
this.formError.input = input;
this.formError.append = fileName + ' filesize must be at most ' + maxSize + 'mb.';
break;
}
} else {
this.formError.input = input;
this.formError.append = fileName + ' filesize must be at least ' + minSize + 'mb.';
break;
}
}
} else {
if (!input.hasAttribute('required')) {
// place error
this.formError.input = input;
this.formError.append = 'Select at least ' + fileCountMin + ' file' + (fileCountMin > 1 ? 's' : '') + '.';
}
}
} else {
if (!input.hasAttribute('required')) {
// place error
this.formError.input = input;
this.formError.append = 'Select at most ' + fileCountMax + ' file' + (fileCountMax > 1 ? 's' : '') + '.';
}
}
if (!input.hasAttribute('required')) {
check = true;
}
return check;
}
}
|
Python
|
UTF-8
| 127 | 3.046875 | 3 |
[] |
no_license
|
x=int(input('nr total de pasari de la ferma:'))
g=x//2
r=g//4
gs=x-g-r
print(g,'gaini')
print(r,'rate')
print(gs,'gaste')
|
Python
|
UTF-8
| 1,454 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
from PIL import Image
import os
from img_process import rotate_and_cut
import random
import math
from utils import str2vec
import numpy as np
def load_templates():
""" load the letter template from ./templates """
templates = []
for i in range(10):
image_path = os.path.join(".", "templates", "%d.png" % i)
templates.append(Image.open(image_path).convert("L"))
return templates
def create_captcha(templates):
captcha = Image.new('RGBA', (100, 40), (255, 255, 255, 0))
captcha_str = ""
for i in range(4):
number = random.randint(0, 9)
captcha_str += str(number)
template = templates[number]
template = rotate_and_cut(template, random.randint(-45, 45))
width_range = math.fabs(25 - template.size[0])
height_range = math.fabs(40 - template.size[1])
start_x_pos = i * 25 + random.randint(-width_range-5, width_range+5)
start_y_pos = random.randint(0, height_range)
captcha.paste(template, (start_x_pos, start_y_pos), mask=template)
return captcha, captcha_str
def gen_dataset(num, templates):
# print("generating %d dataset..." % num)
dataset = []
labels = []
for _ in range(num):
captcha, captcha_str = create_captcha(templates)
dataset.append(np.asarray(captcha.convert("L")).reshape([40 * 100]) / 255)
labels.append(str2vec(captcha_str))
return np.array(dataset), np.array(labels)
|
Java
|
UTF-8
| 2,672 | 2.75 | 3 |
[] |
no_license
|
package server.udpresponder;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Map;
public class MulticastAddressResponder {
public static final int TIME_500MS = 500;
protected MulticastSocket socket = null;
private int port;
private int tcpPort;
private Map<String, String> serversData;
private String ipAddress;
public MulticastAddressResponder(String ipAddress, int port, int tcpPort,
Map<String, String> serversData) {
this.ipAddress = ipAddress;
this.port = port;
this.tcpPort = tcpPort;
this.serversData = serversData;
}
// public static void main(String[] args) {
//// Scanner in = new Scanner(System.in);
// //:todo rand port, now u dont know the range
// int port = 7;
//// String input;
//// System.out.println("Type ip:");
//// input = in.nextLine();
//// String ipAddress = input.toString();
// String ipAddress = SystemConsts.multicastGroupIp;
// MulticastReceiver multicastReceiver = new MulticastReceiver(ipAddress,port, tcpPort);
// multicastReceiver.run();
// }
public void startResponding() {
try {
socket = new MulticastSocket(port);
InetAddress group = InetAddress.getByName(this.ipAddress);
socket.joinGroup(group);
while (true) {
byte[] buf = new byte[65535];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(
packet.getData(), 0, packet.getLength());
System.out.println(received);
if ("DISCOVERY".equals(received)) {
sendResponsesWithIp(packet);
}
if ("exit".equals(received)) {
break;
}
}
socket.leaveGroup(group);
socket.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private void sendResponsesWithIp(DatagramPacket packetToSend)
throws IOException, InterruptedException {
waitForClientReceiver(TIME_500MS);
String serverInformation = parseToCsvServerInformation(serversData);
byte[] buf = serverInformation.getBytes();
packetToSend = new DatagramPacket(buf, buf.length, packetToSend.getAddress(), 8);
socket.send(packetToSend);
}
private String parseToCsvServerInformation(Map<String, String> serversData) {
StringBuilder result = new StringBuilder("");
for (String serverIp : serversData.keySet()) {
String serverPort = serversData.get(serverIp);
result.append(serverIp + "," + serverPort + "\n");
}
return result.toString();
}
private void waitForClientReceiver(long timeMs) throws InterruptedException {
Thread.sleep(timeMs);
}
}
|
JavaScript
|
UTF-8
| 6,378 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
/**
* Created by jacky on 12/27/14.
* Main Scene File
* Depends on three leap controller and leap controller and all their dependencies
*/
//array of nodes that have already been constructed
var occupied = [],
constructed = [];
//world wide length dimension scale. used to easily control relative distances and size of 3D objects.
const scale = 0.7;
//maximum nodes that can be constructed
const constructed_limit = 15;
var changeLoadingMsg = function(msg){
$('.loading-msg').html(msg);
};
var resetLoadingMsg = function(){
changeLoadingMsg('');
};
var showLoadingScreen = function(message){
changeLoadingMsg(message);
$('.loading-screen').show();
};
var hideLoadingScreen = function(){
$('.loading-screen').hide();
resetLoadingMsg();
};
//Text Geometry Constructor
var geo_TextGeometry = function(text,size){
return new THREE.TextGeometry( text, {
size: size,
height: 0.05,
curveSegments: 6,
font: "helvetiker",
weight: "normal",
style: "normal" });
};
//Materials
var matte_browishgreen = new THREE.MeshPhongMaterial( { color: 0xD0D45D } );
function checkPosition(pos){
var hasRepeats = false;
for(var i = 0;i<occupied.length;i++)
if(occupied[i].equals(pos)){
hasRepeats = true;
break;
}
if(hasRepeats)
return checkPosition(pos.add(new THREE.Vector3(0,0,2)));
else{
occupied.push(pos);
return pos;
}
}
var constructWelcomeTexts = function(){
//Welcome Text
//title
var welcome_texts = [
'Wave is an interactive web app',
'that generates 3D visualizations',
'of relationships among',
'Wikipedia articles',
'(compatible with LeapMotion and ',
'Oculus Rift!!!)'
];
var init_pos = new THREE.Vector3(-2,1.0,0);
welcome_texts.forEach(function(text){
var text_geo = geo_TextGeometry(text,0.2);
text_geo.castShadow = true;
text_geo.receiveShadow = true;
var text_obj = new THREE.Mesh(text_geo,matte_browishgreen);
all_orientables.add(text_obj);
setPosition(text_obj,init_pos);
init_pos = init_pos.add(new THREE.Vector3(0,-0.4,0));
});
};
var initScene = function(){
showLoadingScreen('Scene');
constructWelcomeTexts();
// create the geometry sphere
var bg_geo = new THREE.SphereGeometry(200, 32, 32),
bg_mat = new THREE.MeshBasicMaterial();
bg_mat.map = THREE.ImageUtils.loadTexture('assets/space.jpg');
bg_mat.side = THREE.BackSide;
var bg = new THREE.Mesh(bg_geo, bg_mat);
scene.add(bg);
//Lighting
var amb_light = new THREE.AmbientLight( 0x404040 ); // soft white light
var dir_light_warm = new THREE.DirectionalLight( 0xFFECD1, 0.5 );
dir_light_warm.position.set( 5, 10, 5 );
dir_light_warm.castShadow = true;
dir_light_warm.receiveShadow = true;
var dir_light_cold = new THREE.DirectionalLight( 0xD1EAFF, 1.0 );
dir_light_cold.position.set( -5, -10, -5 );
dir_light_cold.castShadow = true;
dir_light_cold.receiveShadow = true;
scene.add( dir_light_warm );
scene.add( dir_light_cold );
scene.add( amb_light );
hideLoadingScreen();
};
//Helper functions to turn nodes into 3D objects
var placeNodeInScene = function(node,origin,angle,weight){
//places node in scene as object
//returns position of object
constructed.push(node);
//new position
var new_pos = new THREE.Vector3(
scale*(weight*Math.cos(angle) + origin.x),
scale*(weight*Math.sin(angle) + origin.y),
scale*(node.name.getDepth() + origin.z)
);
new_pos = checkPosition(new_pos);
changeLoadingMsg(node.name.title);
//title
var node_title_geo = geo_TextGeometry(node.name.title,scale*0.8);
node_title_geo.castShadow = true;
node_title_geo.receiveShadow = true;
var node_title_obj = new THREE.Mesh(node_title_geo,matte_browishgreen);
//add objects to scene
all_orientables.add(node_title_obj);
//set positions
setPosition(node_title_obj,new_pos);
return new_pos;
};
var construct_scene_children = function(node,origin,angle,weight){
var node_pos = placeNodeInScene(node,origin,angle,weight);
//add line to connect node to parent
all_connections.add(origin,node_pos);
var adj = [];
node.adjList.forEach(function(cur_node){
if(constructed.indexOf(cur_node) == -1)
adj.push(cur_node);
});
var num_adj = adj.length,
weights = node.weight,
angle_offset = 2*Math.PI/num_adj;
for (var i = 0; i<num_adj; i++)
construct_scene_children(adj[i],node_pos,angle_offset*i,weights[i]);
};
var construct_scene_parent = function(graph){
var nodes = graph.getAllNodes(),
pivot_node = nodes[0];
var pivot_pos = placeNodeInScene(pivot_node,new THREE.Vector3(0,0,0),0,0);
//call construct_scene_children on adjs
var adj = pivot_node.adjList,
num_adj = adj.length,
weights = pivot_node.weight,
angle_offset = 2*Math.PI/num_adj;
for (var j = 0; j<num_adj; j++)
construct_scene_children(adj[j],pivot_pos,angle_offset*j,weights[j]);
};
var resetScene = function(){
all_orientables.reset();
all_connections.reset();
};
var populateScene = function(items){
resetScene();
var graph = getSceneGraph(items);
construct_scene_parent(graph);
hideLoadingScreen();
};
//Getting desired title from user
var form = $('#generateTreeForm');
form.keypress(function(e){
e.stopPropagation();
if(e.which == 13){
var value = form.val();
if(value){
showLoadingScreen(value);
getWikiData(value,constructed_limit,populateScene);
form.focusout();
}
}
});
form.focus(function(){
allow_key_board = false;
});
form.focusout(function(){
allow_key_board = true;
});
initScene();
//Settings
var reset = function(){
console.log("resetting everything");
showLoadingScreen();
resetScene();
constructWelcomeTexts();
resetCamera();
hideLoadingScreen();
};
$("#reset").click(function(){
reset();
});
$("#origin").click(function(){
resetCamera();
});
$("#enableVR").click(function(){
enableVRMode();
});
$("#toggleOrient").click(function(){
toggleOrient();
});
|
C
|
UTF-8
| 1,504 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <stdio.h> //if you don't use scanf/printf change this include
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/msg.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
typedef short bool;
#define true 1
#define false 0
#define SHKEY 300
///==============================
//don't mess with this variable//
int *shmaddr; //
//===============================
int getClk()
{
return *shmaddr;
}
/*
* All process call this function at the beginning to establish communication between them and the clock module.
* Again, remember that the clock is only emulation!
*/
void initClk()
{
int shmid = shmget(SHKEY, 4, 0444);
while ((int)shmid == -1)
{
//Make sure that the clock exists
printf("Wait! The clock not initialized yet!\n");
sleep(1);
shmid = shmget(SHKEY, 4, 0444);
}
shmaddr = (int *)shmat(shmid, (void *)0, 0);
}
/*
* All process call this function at the end to release the communication
* resources between them and the clock module.
* Again, Remember that the clock is only emulation!
* Input: terminateAll: a flag to indicate whether that this is the end of simulation.
* It terminates the whole system and releases resources.
*/
void destroyClk(bool terminateAll)
{
shmdt(shmaddr);
if (terminateAll)
{
killpg(getpgrp(), SIGINT);
}
}
|
C
|
UTF-8
| 26,509 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
/* The common simulator framework for GDB, the GNU Debugger.
Copyright 2002-2019 Free Software Foundation, Inc.
Contributed by Andrew Cagney and Red Hat.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef SIM_ALU_H
#define SIM_ALU_H
#include "symcat.h"
/* INTEGER ALU MODULE:
This module provides an implementation of 2's complement arithmetic
including the recording of carry and overflow status bits.
EXAMPLE:
Code using this module includes it into sim-main.h and then, as a
convention, defines macro's ALU*_END that records the result of any
arithmetic performed. Ex:
#include "sim-alu.h"
#define ALU32_END(RES) \
(RES) = ALU32_OVERFLOW_RESULT; \
carry = ALU32_HAD_CARRY_BORROW; \
overflow = ALU32_HAD_OVERFLOW
The macro's are then used vis:
{
ALU32_BEGIN (GPR[i]);
ALU32_ADDC (GPR[j]);
ALU32_END (GPR[k]);
}
NOTES:
Macros exist for efficiently computing 8, 16, 32 and 64 bit
arithmetic - ALU8_*, ALU16_*, .... In addition, according to
TARGET_WORD_BITSIZE a set of short-hand macros are defined - ALU_*
Initialization:
ALU*_BEGIN(ACC): Declare initialize the ALU accumulator with ACC.
Results:
The calculation of the final result may be computed a number
of different ways. Three different overflow macro's are
defined, the most efficient one to use depends on which other
outputs from the alu are being used.
ALU*_RESULT: Generic ALU result output.
ALU*_HAD_OVERFLOW: Returns a nonzero value if signed overflow
occurred.
ALU*_OVERFLOW_RESULT: If the macro ALU*_HAD_OVERFLOW is being
used this is the most efficient result available. Ex:
#define ALU16_END(RES) \
if (ALU16_HAD_OVERFLOW) \
sim_engine_halt (...); \
(RES) = ALU16_OVERFLOW_RESULT
ALU*_HAD_CARRY_BORROW: Returns a nonzero value if unsigned
overflow or underflow (also referred to as carry and borrow)
occurred.
ALU*_CARRY_BORROW_RESULT: If the macro ALU*_HAD_CARRY_BORROW is being
used this is the most efficient result available. Ex:
#define ALU64_END(RES) \
State.carry = ALU64_HAD_CARRY_BORROW; \
(RES) = ALU64_CARRY_BORROW_RESULT
Addition:
ALU*_ADD(VAL): Add VAL to the ALU accumulator. Record any
overflow as well as the final result.
ALU*_ADDC(VAL): Add VAL to the ALU accumulator. Record any
carry-out or overflow as well as the final result.
ALU*_ADDC_C(VAL,CI): Add VAL and CI (carry-in). Record any
carry-out or overflow as well as the final result.
Subtraction:
ALU*_SUB(VAL): Subtract VAL from the ALU accumulator. Record
any underflow as well as the final result.
ALU*_SUBC(VAL): Subtract VAL from the ALU accumulator using
negated addition. Record any underflow or carry-out as well
as the final result.
ALU*_SUBB(VAL): Subtract VAL from the ALU accumulator using
direct subtraction (ACC+~VAL+1). Record any underflow or
borrow-out as well as the final result.
ALU*_SUBC_X(VAL,CI): Subtract VAL and CI (carry-in) from the
ALU accumulator using extended negated addition (ACC+~VAL+CI).
Record any underflow or carry-out as well as the final result.
ALU*_SUBB_B(VAL,BI): Subtract VAL and BI (borrow-in) from the
ALU accumulator using direct subtraction. Record any
underflow or borrow-out as well as the final result.
*/
/* Twos complement arithmetic - addition/subtraction - carry/borrow
(or you thought you knew the answer to 0-0)
Notation and Properties:
Xn denotes the value X stored in N bits.
MSBn (X): The most significant (sign) bit of X treated as an N bit
value.
SEXTn (X): The infinite sign extension of X treated as an N bit
value.
MAXn, MINn: The upper and lower bound of a signed, two's
complement N bit value.
UMAXn: The upper bound of an unsigned N bit value (the lower
bound is always zero).
Un: UMAXn + 1. Unsigned arithmetic is computed `modulo (Un)'.
X[p]: Is bit P of X. X[0] denotes the least significant bit.
~X[p]: Is the inversion of bit X[p]. Also equal to 1-X[p],
(1+X[p])mod(2).
Addition - Overflow - Introduction:
Overflow/Overflow indicates an error in computation of signed
arithmetic. i.e. given X,Y in [MINn..MAXn]; overflow
indicates that the result X+Y > MAXn or X+Y < MIN_INTx.
Hardware traditionally implements overflow by computing the XOR of
carry-in/carry-out of the most significant bit of the ALU. Here
other methods need to be found.
Addition - Overflow - method 1:
Overflow occurs when the sign (most significant bit) of the two N
bit operands is identical but different to the sign of the result:
Rn = (Xn + Yn)
V = MSBn (~(Xn ^ Yn) & (Rn ^ Xn))
Addition - Overflow - method 2:
The two N bit operands are sign extended to M>N bits and then
added. Overflow occurs when SIGN_BIT<n> and SIGN_BIT<m> do not
match.
Rm = (SEXTn (Xn) + SEXTn (Yn))
V = MSBn ((Rm >> (M - N)) ^ Rm)
Addition - Overflow - method 3:
The two N bit operands are sign extended to M>N bits and then
added. Overflow occurs when the result is outside of the sign
extended range [MINn .. MAXn].
Addition - Overflow - method 4:
Given the Result and Carry-out bits, the oVerflow from the addition
of X, Y and carry-In can be computed using the equation:
Rn = (Xn + Yn)
V = (MSBn ((Xn ^ Yn) ^ Rn)) ^ C)
As shown in the table below:
I X Y R C | V | X^Y ^R ^C
---------------+---+-------------
0 0 0 0 0 | 0 | 0 0 0
0 0 1 1 0 | 0 | 1 0 0
0 1 0 1 0 | 0 | 1 0 0
0 1 1 0 1 | 1 | 0 0 1
1 0 0 1 0 | 1 | 0 1 1
1 0 1 0 1 | 0 | 1 1 0
1 1 0 0 1 | 0 | 1 1 0
1 1 1 1 1 | 0 | 0 1 0
Addition - Carry - Introduction:
Carry (poorly named) indicates that an overflow occurred for
unsigned N bit addition. i.e. given X, Y in [0..UMAXn] then
carry indicates X+Y > UMAXn or X+Y >= Un.
The following table lists the output for all given inputs into a
full-adder.
I X Y R | C
------------+---
0 0 0 0 | 0
0 0 1 1 | 0
0 1 0 1 | 0
0 1 1 0 | 1
1 0 0 1 | 0
1 0 1 0 | 1
1 1 0 0 | 1
1 1 1 1 | 1
(carry-In, X, Y, Result, Carry-out):
Addition - Carry - method 1:
Looking at the terms X, Y and R we want an equation for C.
XY\R 0 1
+-------
00 | 0 0
01 | 1 0
11 | 1 1
10 | 1 0
This giving us the sum-of-prod equation:
MSBn ((Xn & Yn) | (Xn & ~Rn) | (Yn & ~Rn))
Verifying:
I X Y R | C | X&Y X&~R Y&~R
------------+---+---------------
0 0 0 0 | 0 | 0 0 0
0 0 1 1 | 0 | 0 0 0
0 1 0 1 | 0 | 0 0 0
0 1 1 0 | 1 | 1 1 1
1 0 0 1 | 0 | 0 0 0
1 0 1 0 | 1 | 0 0 1
1 1 0 0 | 1 | 0 1 0
1 1 1 1 | 1 | 1 0 0
Addition - Carry - method 2:
Given two signed N bit numbers, a carry can be detected by treating
the numbers as N bit unsigned and adding them using M>N unsigned
arithmetic. Carry is indicated by bit (1 << N) being set (result
>= 2**N).
Addition - Carry - method 3:
Given the oVerflow bit. The carry can be computed from:
(~R&V) | (R&V)
Addition - Carry - method 4:
Given two signed numbers. Treating them as unsigned we have:
0 <= X < Un, 0 <= Y < Un
==> X + Y < 2 Un
Consider Y when carry occurs:
X + Y >= Un, Y < Un
==> (Un - X) <= Y < Un # rearrange
==> Un <= X + Y < Un + X < 2 Un # add Xn
==> 0 <= (X + Y) mod Un < X mod Un
or when carry as occurred:
(X + Y) mod Un < X mod Un
Consider Y when carry does not occur:
X + Y < Un
have X < Un, Y >= 0
==> X <= X + Y < Un
==> X mod Un <= (X + Y) mod Un
or when carry has not occurred:
! ( (X + Y) mod Un < X mod Un)
hence we get carry by computing in N bit unsigned arithmetic.
carry <- (Xn + Yn) < Xn
Subtraction - Introduction
There are two different ways of computing the signed two's
complement difference of two numbers. The first is based on
negative addition, the second on direct subtraction.
Subtraction - Carry - Introduction - Negated Addition
The equation X - Y can be computed using:
X + (-Y)
==> X + ~Y + 1 # -Y = ~Y + 1
In addition to the result, the equation produces Carry-out. For
succeeding extended precision calculations, the more general
equation can be used:
C[p]:R[p] = X[p] + ~Y[p] + C[p-1]
where C[0]:R[0] = X[0] + ~Y[0] + 1
Subtraction - Borrow - Introduction - Direct Subtraction
The alternative to negative addition is direct subtraction where
`X-Y is computed directly. In addition to the result of the
calculation, a Borrow bit is produced. In general terms:
B[p]:R[p] = X[p] - Y[p] - B[p-1]
where B[0]:R[0] = X[0] - Y[0]
The Borrow bit is the complement of the Carry bit produced by
Negated Addition above. A dodgy proof follows:
Case 0:
C[0]:R[0] = X[0] + ~Y[0] + 1
==> C[0]:R[0] = X[0] + 1 - Y[0] + 1 # ~Y[0] = (1 - Y[0])?
==> C[0]:R[0] = 2 + X[0] - Y[0]
==> C[0]:R[0] = 2 + B[0]:R[0]
==> C[0]:R[0] = (1 + B[0]):R[0]
==> C[0] = ~B[0] # (1 + B[0]) mod 2 = ~B[0]?
Case P:
C[p]:R[p] = X[p] + ~Y[p] + C[p-1]
==> C[p]:R[p] = X[p] + 1 - Y[0] + 1 - B[p-1]
==> C[p]:R[p] = 2 + X[p] - Y[0] - B[p-1]
==> C[p]:R[p] = 2 + B[p]:R[p]
==> C[p]:R[p] = (1 + B[p]):R[p]
==> C[p] = ~B[p]
The table below lists all possible inputs/outputs for a
full-subtractor:
X Y I | R B
0 0 0 | 0 0
0 0 1 | 1 1
0 1 0 | 1 1
0 1 1 | 0 1
1 0 0 | 1 0
1 0 1 | 0 0
1 1 0 | 0 0
1 1 1 | 1 1
Subtraction - Method 1
Treating Xn and Yn as unsigned values then a borrow (unsigned
underflow) occurs when:
B = Xn < Yn
==> C = Xn >= Yn
*/
/* 8 bit target expressions:
Since the host's natural bitsize > 8 bits, carry method 2 and
overflow method 2 are used. */
#define ALU8_BEGIN(VAL) \
unsigned alu8_cr = (unsigned8) (VAL); \
signed alu8_vr = (signed8) (alu8_cr)
#define ALU8_SET(VAL) \
alu8_cr = (unsigned8) (VAL); \
alu8_vr = (signed8) (alu8_cr)
#define ALU8_SET_CARRY_BORROW(CARRY) \
do { \
if (CARRY) \
alu8_cr |= ((signed)-1) << 8; \
else \
alu8_cr &= 0xff; \
} while (0)
#define ALU8_HAD_CARRY_BORROW (alu8_cr & LSBIT32(8))
#define ALU8_HAD_OVERFLOW (((alu8_vr >> 8) ^ alu8_vr) & LSBIT32 (8-1))
#define ALU8_RESULT ((unsigned8) alu8_cr)
#define ALU8_CARRY_BORROW_RESULT ((unsigned8) alu8_cr)
#define ALU8_OVERFLOW_RESULT ((unsigned8) alu8_vr)
/* #define ALU8_END ????? - target dependant */
/* 16 bit target expressions:
Since the host's natural bitsize > 16 bits, carry method 2 and
overflow method 2 are used. */
#define ALU16_BEGIN(VAL) \
signed alu16_cr = (unsigned16) (VAL); \
unsigned alu16_vr = (signed16) (alu16_cr)
#define ALU16_SET(VAL) \
alu16_cr = (unsigned16) (VAL); \
alu16_vr = (signed16) (alu16_cr)
#define ALU16_SET_CARRY_BORROW(CARRY) \
do { \
if (CARRY) \
alu16_cr |= ((signed)-1) << 16; \
else \
alu16_cr &= 0xffff; \
} while (0)
#define ALU16_HAD_CARRY_BORROW (alu16_cr & LSBIT32(16))
#define ALU16_HAD_OVERFLOW (((alu16_vr >> 16) ^ alu16_vr) & LSBIT32 (16-1))
#define ALU16_RESULT ((unsigned16) alu16_cr)
#define ALU16_CARRY_BORROW_RESULT ((unsigned16) alu16_cr)
#define ALU16_OVERFLOW_RESULT ((unsigned16) alu16_vr)
/* #define ALU16_END ????? - target dependant */
/* 32 bit target expressions:
Since most hosts do not support 64 (> 32) bit arithmetic, carry
method 4 and overflow method 4 are used. */
#define ALU32_BEGIN(VAL) \
unsigned32 alu32_r = (VAL); \
int alu32_c = 0; \
int alu32_v = 0
#define ALU32_SET(VAL) \
alu32_r = (VAL); \
alu32_c = 0; \
alu32_v = 0
#define ALU32_SET_CARRY_BORROW(CARRY) alu32_c = (CARRY)
#define ALU32_HAD_CARRY_BORROW (alu32_c)
#define ALU32_HAD_OVERFLOW (alu32_v)
#define ALU32_RESULT (alu32_r)
#define ALU32_CARRY_BORROW_RESULT (alu32_r)
#define ALU32_OVERFLOW_RESULT (alu32_r)
/* 64 bit target expressions:
Even though the host typically doesn't support native 64 bit
arithmetic, it is still used. */
#define ALU64_BEGIN(VAL) \
unsigned64 alu64_r = (VAL); \
int alu64_c = 0; \
int alu64_v = 0
#define ALU64_SET(VAL) \
alu64_r = (VAL); \
alu64_c = 0; \
alu64_v = 0
#define ALU64_SET_CARRY_BORROW(CARRY) alu64_c = (CARRY)
#define ALU64_HAD_CARRY_BORROW (alu64_c)
#define ALU64_HAD_OVERFLOW (alu64_v)
#define ALU64_RESULT (alu64_r)
#define ALU64_CARRY_BORROW_RESULT (alu64_r)
#define ALU64_OVERFLOW_RESULT (alu64_r)
/* Generic versions of above macros */
#define ALU_BEGIN XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_BEGIN)
#define ALU_SET XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_SET)
#define ALU_SET_CARRY XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_SET_CARRY)
#define ALU_HAD_OVERFLOW XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_HAD_OVERFLOW)
#define ALU_HAD_CARRY XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_HAD_CARRY)
#define ALU_RESULT XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_RESULT)
#define ALU_OVERFLOW_RESULT XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_OVERFLOW_RESULT)
#define ALU_CARRY_RESULT XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_CARRY_RESULT)
/* Basic operation - add (overflowing) */
#define ALU8_ADD(VAL) \
do { \
unsigned8 alu8add_val = (VAL); \
ALU8_ADDC (alu8add_val); \
} while (0)
#define ALU16_ADD(VAL) \
do { \
unsigned16 alu16add_val = (VAL); \
ALU16_ADDC (alu8add_val); \
} while (0)
#define ALU32_ADD(VAL) \
do { \
unsigned32 alu32add_val = (VAL); \
ALU32_ADDC (alu32add_val); \
} while (0)
#define ALU64_ADD(VAL) \
do { \
unsigned64 alu64add_val = (unsigned64) (VAL); \
ALU64_ADDC (alu64add_val); \
} while (0)
#define ALU_ADD XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_ADD)
/* Basic operation - add carrying (and overflowing) */
#define ALU8_ADDC(VAL) \
do { \
unsigned8 alu8addc_val = (VAL); \
alu8_cr += (unsigned8)(alu8addc_val); \
alu8_vr += (signed8)(alu8addc_val); \
} while (0)
#define ALU16_ADDC(VAL) \
do { \
unsigned16 alu16addc_val = (VAL); \
alu16_cr += (unsigned16)(alu16addc_val); \
alu16_vr += (signed16)(alu16addc_val); \
} while (0)
#define ALU32_ADDC(VAL) \
do { \
unsigned32 alu32addc_val = (VAL); \
unsigned32 alu32addc_sign = alu32addc_val ^ alu32_r; \
alu32_r += (alu32addc_val); \
alu32_c = (alu32_r < alu32addc_val); \
alu32_v = ((alu32addc_sign ^ - (unsigned32)alu32_c) ^ alu32_r) >> 31; \
} while (0)
#define ALU64_ADDC(VAL) \
do { \
unsigned64 alu64addc_val = (unsigned64) (VAL); \
unsigned64 alu64addc_sign = alu64addc_val ^ alu64_r; \
alu64_r += (alu64addc_val); \
alu64_c = (alu64_r < alu64addc_val); \
alu64_v = ((alu64addc_sign ^ - (unsigned64)alu64_c) ^ alu64_r) >> 63; \
} while (0)
#define ALU_ADDC XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_ADDC)
/* Compound operation - add carrying (and overflowing) with carry-in */
#define ALU8_ADDC_C(VAL,C) \
do { \
unsigned8 alu8addcc_val = (VAL); \
unsigned8 alu8addcc_c = (C); \
alu8_cr += (unsigned)(unsigned8)alu8addcc_val + alu8addcc_c; \
alu8_vr += (signed)(signed8)(alu8addcc_val) + alu8addcc_c; \
} while (0)
#define ALU16_ADDC_C(VAL,C) \
do { \
unsigned16 alu16addcc_val = (VAL); \
unsigned16 alu16addcc_c = (C); \
alu16_cr += (unsigned)(unsigned16)alu16addcc_val + alu16addcc_c; \
alu16_vr += (signed)(signed16)(alu16addcc_val) + alu16addcc_c; \
} while (0)
#define ALU32_ADDC_C(VAL,C) \
do { \
unsigned32 alu32addcc_val = (VAL); \
unsigned32 alu32addcc_c = (C); \
unsigned32 alu32addcc_sign = (alu32addcc_val ^ alu32_r); \
alu32_r += (alu32addcc_val + alu32addcc_c); \
alu32_c = ((alu32_r < alu32addcc_val) \
|| (alu32addcc_c && alu32_r == alu32addcc_val)); \
alu32_v = ((alu32addcc_sign ^ - (unsigned32)alu32_c) ^ alu32_r) >> 31;\
} while (0)
#define ALU64_ADDC_C(VAL,C) \
do { \
unsigned64 alu64addcc_val = (VAL); \
unsigned64 alu64addcc_c = (C); \
unsigned64 alu64addcc_sign = (alu64addcc_val ^ alu64_r); \
alu64_r += (alu64addcc_val + alu64addcc_c); \
alu64_c = ((alu64_r < alu64addcc_val) \
|| (alu64addcc_c && alu64_r == alu64addcc_val)); \
alu64_v = ((alu64addcc_sign ^ - (unsigned64)alu64_c) ^ alu64_r) >> 63;\
} while (0)
#define ALU_ADDC_C XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_ADDC_C)
/* Basic operation - subtract (overflowing) */
#define ALU8_SUB(VAL) \
do { \
unsigned8 alu8sub_val = (VAL); \
ALU8_ADDC_C (~alu8sub_val, 1); \
} while (0)
#define ALU16_SUB(VAL) \
do { \
unsigned16 alu16sub_val = (VAL); \
ALU16_ADDC_C (~alu16sub_val, 1); \
} while (0)
#define ALU32_SUB(VAL) \
do { \
unsigned32 alu32sub_val = (VAL); \
ALU32_ADDC_C (~alu32sub_val, 1); \
} while (0)
#define ALU64_SUB(VAL) \
do { \
unsigned64 alu64sub_val = (VAL); \
ALU64_ADDC_C (~alu64sub_val, 1); \
} while (0)
#define ALU_SUB XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_SUB)
/* Basic operation - subtract carrying (and overflowing) */
#define ALU8_SUBC(VAL) \
do { \
unsigned8 alu8subc_val = (VAL); \
ALU8_ADDC_C (~alu8subc_val, 1); \
} while (0)
#define ALU16_SUBC(VAL) \
do { \
unsigned16 alu16subc_val = (VAL); \
ALU16_ADDC_C (~alu16subc_val, 1); \
} while (0)
#define ALU32_SUBC(VAL) \
do { \
unsigned32 alu32subc_val = (VAL); \
ALU32_ADDC_C (~alu32subc_val, 1); \
} while (0)
#define ALU64_SUBC(VAL) \
do { \
unsigned64 alu64subc_val = (VAL); \
ALU64_ADDC_C (~alu64subc_val, 1); \
} while (0)
#define ALU_SUBC XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_SUBC)
/* Compound operation - subtract carrying (and overflowing), extended */
#define ALU8_SUBC_X(VAL,C) \
do { \
unsigned8 alu8subcx_val = (VAL); \
unsigned8 alu8subcx_c = (C); \
ALU8_ADDC_C (~alu8subcx_val, alu8subcx_c); \
} while (0)
#define ALU16_SUBC_X(VAL,C) \
do { \
unsigned16 alu16subcx_val = (VAL); \
unsigned16 alu16subcx_c = (C); \
ALU16_ADDC_C (~alu16subcx_val, alu16subcx_c); \
} while (0)
#define ALU32_SUBC_X(VAL,C) \
do { \
unsigned32 alu32subcx_val = (VAL); \
unsigned32 alu32subcx_c = (C); \
ALU32_ADDC_C (~alu32subcx_val, alu32subcx_c); \
} while (0)
#define ALU64_SUBC_X(VAL,C) \
do { \
unsigned64 alu64subcx_val = (VAL); \
unsigned64 alu64subcx_c = (C); \
ALU64_ADDC_C (~alu64subcx_val, alu64subcx_c); \
} while (0)
#define ALU_SUBC_X XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_SUBC_X)
/* Basic operation - subtract borrowing (and overflowing) */
#define ALU8_SUBB(VAL) \
do { \
unsigned8 alu8subb_val = (VAL); \
alu8_cr -= (unsigned)(unsigned8)alu8subb_val; \
alu8_vr -= (signed)(signed8)alu8subb_val; \
} while (0)
#define ALU16_SUBB(VAL) \
do { \
unsigned16 alu16subb_val = (VAL); \
alu16_cr -= (unsigned)(unsigned16)alu16subb_val; \
alu16_vr -= (signed)(signed16)alu16subb_val; \
} while (0)
#define ALU32_SUBB(VAL) \
do { \
unsigned32 alu32subb_val = (VAL); \
unsigned32 alu32subb_sign = alu32subb_val ^ alu32_r; \
alu32_c = (alu32_r < alu32subb_val); \
alu32_r -= (alu32subb_val); \
alu32_v = ((alu32subb_sign ^ - (unsigned32)alu32_c) ^ alu32_r) >> 31; \
} while (0)
#define ALU64_SUBB(VAL) \
do { \
unsigned64 alu64subb_val = (VAL); \
unsigned64 alu64subb_sign = alu64subb_val ^ alu64_r; \
alu64_c = (alu64_r < alu64subb_val); \
alu64_r -= (alu64subb_val); \
alu64_v = ((alu64subb_sign ^ - (unsigned64)alu64_c) ^ alu64_r) >> 31; \
} while (0)
#define ALU_SUBB XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_SUBB)
/* Compound operation - subtract borrowing (and overflowing) with borrow-in */
#define ALU8_SUBB_B(VAL,B) \
do { \
unsigned8 alu8subbb_val = (VAL); \
unsigned8 alu8subbb_b = (B); \
alu8_cr -= (unsigned)(unsigned8)alu8subbb_val; \
alu8_cr -= (unsigned)(unsigned8)alu8subbb_b; \
alu8_vr -= (signed)(signed8)alu8subbb_val + alu8subbb_b; \
} while (0)
#define ALU16_SUBB_B(VAL,B) \
do { \
unsigned16 alu16subbb_val = (VAL); \
unsigned16 alu16subbb_b = (B); \
alu16_cr -= (unsigned)(unsigned16)alu16subbb_val; \
alu16_cr -= (unsigned)(unsigned16)alu16subbb_b; \
alu16_vr -= (signed)(signed16)alu16subbb_val + alu16subbb_b; \
} while (0)
#define ALU32_SUBB_B(VAL,B) \
do { \
unsigned32 alu32subbb_val = (VAL); \
unsigned32 alu32subbb_b = (B); \
ALU32_ADDC_C (~alu32subbb_val, !alu32subbb_b); \
alu32_c = !alu32_c; \
} while (0)
#define ALU64_SUBB_B(VAL,B) \
do { \
unsigned64 alu64subbb_val = (VAL); \
unsigned64 alu64subbb_b = (B); \
ALU64_ADDC_C (~alu64subbb_val, !alu64subbb_b); \
alu64_c = !alu64_c; \
} while (0)
#define ALU_SUBB_B XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_SUBB_B)
/* Basic operation - negate (overflowing) */
#define ALU8_NEG() \
do { \
signed alu8neg_val = (ALU8_RESULT); \
ALU8_SET (1); \
ALU8_ADDC (~alu8neg_val); \
} while (0)
#define ALU16_NEG() \
do { \
signed alu16neg_val = (ALU16_RESULT); \
ALU16_SET (1); \
ALU16_ADDC (~alu16neg_val); \
} while (0)
#define ALU32_NEG() \
do { \
unsigned32 alu32neg_val = (ALU32_RESULT); \
ALU32_SET (1); \
ALU32_ADDC (~alu32neg_val); \
} while(0)
#define ALU64_NEG() \
do { \
unsigned64 alu64neg_val = (ALU64_RESULT); \
ALU64_SET (1); \
ALU64_ADDC (~alu64neg_val); \
} while (0)
#define ALU_NEG XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_NEG)
/* Basic operation - negate carrying (and overflowing) */
#define ALU8_NEGC() \
do { \
signed alu8negc_val = (ALU8_RESULT); \
ALU8_SET (1); \
ALU8_ADDC (~alu8negc_val); \
} while (0)
#define ALU16_NEGC() \
do { \
signed alu16negc_val = (ALU16_RESULT); \
ALU16_SET (1); \
ALU16_ADDC (~alu16negc_val); \
} while (0)
#define ALU32_NEGC() \
do { \
unsigned32 alu32negc_val = (ALU32_RESULT); \
ALU32_SET (1); \
ALU32_ADDC (~alu32negc_val); \
} while(0)
#define ALU64_NEGC() \
do { \
unsigned64 alu64negc_val = (ALU64_RESULT); \
ALU64_SET (1); \
ALU64_ADDC (~alu64negc_val); \
} while (0)
#define ALU_NEGC XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_NEGC)
/* Basic operation - negate borrowing (and overflowing) */
#define ALU8_NEGB() \
do { \
signed alu8negb_val = (ALU8_RESULT); \
ALU8_SET (0); \
ALU8_SUBB (alu8negb_val); \
} while (0)
#define ALU16_NEGB() \
do { \
signed alu16negb_val = (ALU16_RESULT); \
ALU16_SET (0); \
ALU16_SUBB (alu16negb_val); \
} while (0)
#define ALU32_NEGB() \
do { \
unsigned32 alu32negb_val = (ALU32_RESULT); \
ALU32_SET (0); \
ALU32_SUBB (alu32negb_val); \
} while(0)
#define ALU64_NEGB() \
do { \
unsigned64 alu64negb_val = (ALU64_RESULT); \
ALU64_SET (0); \
ALU64_SUBB (alu64negb_val); \
} while (0)
#define ALU_NEGB XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_NEGB)
/* Other */
#define ALU8_OR(VAL) \
do { \
error("ALU16_OR"); \
} while (0)
#define ALU16_OR(VAL) \
do { \
error("ALU16_OR"); \
} while (0)
#define ALU32_OR(VAL) \
do { \
alu32_r |= (VAL); \
alu32_c = 0; \
alu32_v = 0; \
} while (0)
#define ALU64_OR(VAL) \
do { \
alu64_r |= (VAL); \
alu64_c = 0; \
alu64_v = 0; \
} while (0)
#define ALU_OR(VAL) XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_OR)(VAL)
#define ALU16_XOR(VAL) \
do { \
error("ALU16_XOR"); \
} while (0)
#define ALU32_XOR(VAL) \
do { \
alu32_r ^= (VAL); \
alu32_c = 0; \
alu32_v = 0; \
} while (0)
#define ALU64_XOR(VAL) \
do { \
alu64_r ^= (VAL); \
alu64_c = 0; \
alu64_v = 0; \
} while (0)
#define ALU_XOR(VAL) XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_XOR)(VAL)
#define ALU16_AND(VAL) \
do { \
error("ALU_AND16"); \
} while (0)
#define ALU32_AND(VAL) \
do { \
alu32_r &= (VAL); \
alu32_c = 0; \
alu32_v = 0; \
} while (0)
#define ALU64_AND(VAL) \
do { \
alu64_r &= (VAL); \
alu64_c = 0; \
alu64_v = 0; \
} while (0)
#define ALU_AND(VAL) XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_AND)(VAL)
#define ALU16_NOT(VAL) \
do { \
error("ALU_NOT16"); \
} while (0)
#define ALU32_NOT \
do { \
alu32_r = ~alu32_r; \
alu32_c = 0; \
alu32_v = 0; \
} while (0)
#define ALU64_NOT \
do { \
alu64_r = ~alu64_r; \
alu64_c = 0; \
alu64_v = 0; \
} while (0)
#define ALU_NOT XCONCAT3(ALU,WITH_TARGET_WORD_BITSIZE,_NOT)
#endif
|
Markdown
|
UTF-8
| 797 | 3.234375 | 3 |
[] |
no_license
|
---
layout: default
title: "Easy Stuffed Shells"
tags: pasta,easy,stuffed,shells,main,course,dinner,kristi,grubbs
---
# Easy Stuffed Shells
#### Ingredients:
- 36 uncooked jumbo pasta shells
- 1 jar (24 ounces) spaghetti sauce
- 36 frozen fully cooked Italian meatballs (1/2 ounce each), thawed
- 2 cups shredded part-skim mozzarella cheese
- Note: i like more sauce, so i usually add 2 cans/jars instead of 1
#### Instructions:
1. Preheat oven to 350°. Cook pasta shells according to package directions; drain and rinse in cold water.
2. Spread 1/2 cup sauce into a greased 13x9-in. baking dish. Fill each shell with a meatball; place over sauce. Top with remaining sauce and the cheese.
3. Bake, covered, 35 minutes. Uncover; bake 3-5 minutes longer or until bubbly and cheese is melted.
|
TypeScript
|
UTF-8
| 583 | 3.09375 | 3 |
[] |
no_license
|
import { deepClone } from './deepClone'
describe('deepClone tests', () => {
it('clones an object', () => {
let fruitColors = {bananas: 'yellow'}
let clonedFruitColors = deepClone(fruitColors)
clonedFruitColors['apples'] = 'red'
expect(Object.keys(fruitColors)).toEqual(['bananas'])
expect(Object.keys(clonedFruitColors)).toEqual(['bananas', 'apples'])
})
it('clones an array', () => {
let numbers = [1, 2, 3]
let clonedNumbers = deepClone(numbers)
clonedNumbers.push(4)
expect(clonedNumbers.length).toBeGreaterThan(numbers.length)
})
})
|
JavaScript
|
UTF-8
| 1,655 | 2.640625 | 3 |
[] |
no_license
|
import { useEffect, useState } from 'react';
import Row from './Row';
import { getDataByRange } from '../helpers/dataHelpers';
import '../style/Table.css';
const Table = ({ desde, hasta }) => {
const [row, setRow] = useState({});
const [keys, setKeys] = useState([]);
const initData = () => {
let data = [];
let firstRow = {};
let keys = [];
data = getDataByRange(desde, hasta);
keys = Object.keys(data[0]).reduce((prevVal, val) => {
if (val !== 'Dia' && val !== 'Day') {
return [
...prevVal,
val,
];
}
return prevVal;
}, []);
data.forEach(value => {
keys.forEach(key => {
const sum = firstRow[key] ? firstRow[key] : 0;
firstRow = {
...firstRow,
[key]: value[key] + sum,
}
});
});
setRow(firstRow);
setKeys(keys);
};
useEffect(() => {
initData();
}, []);
return (
<div className="table-wrapper">
<table>
<tbody>
<tr>
<th className="table-header" colSpan={2}>
{`Cubeta ${desde} a ${hasta}`}
</th>
</tr>
<Row data={{
[keys[0]]: row[keys[0]],
[keys[1]]: row[keys[1]],
}}
/>
<Row data={{
[keys[2]]: row[keys[2]],
[keys[3]]: row[keys[3]],
}}
circleColor="green"
/>
<Row data={{
[keys[4]]: row[keys[4]],
[keys[5]]: row[keys[5]],
}}
circleColor="gray"
/>
</tbody>
</table>
</div>
)
};
export default Table;
|
JavaScript
|
UTF-8
| 1,958 | 3 | 3 |
[] |
no_license
|
function salvarForm(id) {
switch (id) {
case 'produto':
let descricao = document.getElementById("descricao").value;
let marca = document.getElementById("nome_produto").value;
let fornecedor = document.getElementById("fornecedor").value;
let preco_atacado = document.getElementById("preco_atacado").value;
let preco_varejo = document.getElementById("preco_varejo").value;
let dados_produto = {
descricao,
nome_produto,
fornecedor,
preco_atacado,
preco_varejo,
}
let produtoJson = JSON.stringify(dados_produto);
localStorage.setItem("produtos", produtoJson);
break;
case 'cliente':
let nome = document.getElementById("nome").value;
let cpf = document.getElementById("cpf").value;
let data_nascimento = document.getElementById("data_nascimento").value;
let telefone = document.getElementById("telefone").value;
let email = document.getElementById("email").value;
let cep = document.getElementById("cep").value;
let endereco = document.getElementById("endereco").value;
let numero = document.getElementById("numero").value;
let complemento = document.getElementById("complemento").value;
let bairro = document.getElementById("bairro").value;
let cidade = document.getElementById("cidade").value;
let estado = document.getElementById("estado").value;
let dados_cliente = {
nome,
cpf,
data_nascimento,
telefone,
email,
cep,
endereco,
numero,
complemento,
bairro,
cidade,
estado,
}
let clientesJson = JSON.stringify(dados_cliente);
localStorage.setItem("clientes", clientesJson);
break;
}
}
|
C#
|
UTF-8
| 2,841 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
namespace Bitifier.Configuration
{
class ConfigDownloader
{
private readonly Uri[] _configUris;
private string _latestSha1Hash;
private string _latestEtag;
public ConfigDownloader(params Uri[] configUris)
{
_configUris = configUris;
}
public bool DownloadIfChanged(out string configuration, out string extension)
{
var exceptions = new List<Exception>();
foreach (var uri in _configUris)
{
try
{
extension = Path.GetExtension(uri.AbsolutePath);
return DownloadIfChanged(uri, out configuration);
}
catch (Exception exception)
{
exceptions.Add(exception);
}
}
throw new AggregateException(Messages.ConfigLoadFailedMessage, exceptions);
}
private bool DownloadIfChanged(Uri uri, out string configuration)
{
if (uri.IsFile)
{
var filePath = uri.AbsolutePath;
configuration = File.ReadAllText(filePath);
_latestEtag = null;
}
else
{
var request = WebRequest.Create(uri);
if (_latestEtag != null)
request.Headers.Add("If-None-Match", _latestEtag);
try
{
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var streamReader = new StreamReader(responseStream))
{
_latestEtag = response.Headers[HttpResponseHeader.ETag];
configuration = streamReader.ReadToEnd();
}
}
catch (WebException exception)
{
if (exception.Status == WebExceptionStatus.ProtocolError)
{
var response = (HttpWebResponse) exception.Response;
if (response.StatusCode == HttpStatusCode.NotModified)
{
configuration = null;
return false;
}
}
throw;
}
}
var hash = GetHash(configuration);
if (hash != _latestSha1Hash)
{
_latestSha1Hash = hash;
return true;
}
return false;
}
private static string GetHash(string configuration)
{
var data = System.Text.Encoding.ASCII.GetBytes(configuration);
using (var sha1 = System.Security.Cryptography.SHA1.Create())
{
var hash = sha1.ComputeHash(data);
return Convert.ToBase64String(hash);
}
}
}
}
|
Markdown
|
UTF-8
| 2,305 | 3.046875 | 3 |
[] |
no_license
|
# PK2 Praktikum 7 - LinkedList
Eine LinkedList in C++ mit den Standardfunktionen.
## Getting Started
Einfach auschecken und die ausführbare Datei in einer Konsole ausführen.
### Prerequisites
Texteditor,
Windows-Betriebssystem,
ggf. GNU-Compiler
### Task
Implementieren Sie nun eine Klasse LinkedList in der Programmiersprache C++. Die
Klasse LinkedList soll die folgenden Elementfunktionen anbieten:
/* Erzeugt eine leere Liste. */
LinkedList();
/* Fuegt den Text (in konstanter Zeit) an der letzten */
/* Listenposition hinzu. */
/* Liefert den Wert 1, wenn das Element eingefuegt werden */
/* konnte. Ansonsten wird der Wert 0 geliefert. */
int append(const char* text);
/* Fuegt ein neues Element an der Position p ein. */
/* Das erste Element der Liste befindet sich an der */
/* Position 0. */
/* Das Element, das sich aktuell an der Position p befindet,*/
/* wird nach rechts geschoben. */
/* Falls sich weniger als p Elemente in der Liste befinden, */
/* wird der Text am Ende angefuegt. */
int insert(const char* text, int p);
/* Loescht das Element an der Position p. Das erste */
/* Element befindet sich an der Position 0. */
/* Falls das p-te Element nicht existiert, wird das letzte */
/* Element geloescht. Die Anzahl der geloeschten Elemente */
/* wird als Funktionswert geliefert. */
int remove(int p);
/* Liefert den Text an der p-ten Listenposition. */
/* Das erste Listenelement befindet sich an der Position 0. */
/* Falls das p-te Element nicht existiert, wird nullptr */
/* geliefert. */
const char *get(int p);
/* Berechnet den Index des ersten Elements, das den Text */
/* text enthaelt. Falls kein Element den gesuchten Text */
/* enthaelt, wird -1 geliefert. */
int index_of(const char *text);
/* Liefert den Text des ersten Elements der Liste (in */
/* konstanter Zeit). */
const char *first();
/* Liefert den Text des letzten Elements der Liste (in */
/* konstanter Zeit). */
const char *last();
/* Besucht alle Elemente der Liste und ruft fuer jedes */
/* Element die Funktion work auf. */
void visit_all(void (*work)(const char* t));
Vermeiden Sie ein Speicherleck. Denken Sie auch an die Initialisierung eines Werte-
objekts mit einem bereits existierenden Objekts. Schreiben Sie zudem ein Hauptpro-
gramm, das jede Elementfunktion der Klasse LinkedList anwendet.
|
JavaScript
|
UTF-8
| 2,683 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
function TaskNode(options) {
var distance_between_nodes = 400;
var state = options.state;
var x = options.x;
var y = options.y;
var width = options.width;
var height = options.height;
var color = options.color || 0xffffff;
var borderColor = options.borderColor || 0;
var borderWidth = options.borderWidth || 0;
var name = options.name || "Unnamed Job";
var graphics = state.add.graphics(x,y);
graphics.addChild(new Phaser.Text(game, 10, 10, name,
{ font: "12pt Courier", fill: "#FCAE1C", stroke: "#FCAE1C", strokeThickness: 1 }));
//Public members
graphics.upperEdge = function(){
return {x: width /2, y: graphics.y};
};
graphics.lowerEdge = function(){
return {x: width/2, y: height};
};
graphics.leftEdge = function(){
return {x: graphics.x, y: height/2};
};
graphics.rightEdge = function(){
return {x: width, y: height/2};
};
//Methods
graphics.addConnectedNode = function(otherNode, direction, lineColor) {
lineColor = lineColor || borderColor;
direction = direction || directions.right;
function getNodeEdge(node, direction) {
switch(direction) {
case directions.left : return node.leftEdge();
case directions.right : return node.rightEdge();
case directions.up : return node.upperEdge();
case directions.down : return node.lowerEdge();
}
}
function setConnectedNodePosition(node, direction){
node.x = 0;
node.y = 0;
switch(direction) {
case directions.left : return node.x = -distance_between_nodes;
case directions.right : return node.x = distance_between_nodes;
case directions.up : return node.x = -distance_between_nodes;
case directions.down : return node.x = distance_between_nodes;
}
}
//make the other node anchored relative to this one
graphics.addChild(otherNode);
setConnectedNodePosition(otherNode, direction);
//draw a line between them
var start = getNodeEdge(graphics, direction);
var end = getNodeEdge(otherNode, -direction);
graphics.lineStyle(borderWidth, lineColor);
graphics.moveTo(start.x, start.y);
graphics.lineTo(end.x, end.y);
return otherNode;
}
graphics.redraw = draw;
function draw() {
//Draw the rectangle
graphics.beginFill(color);
graphics.drawRect(0, 0, width, height);
graphics.endFill();
//Draw the outline
if(borderWidth > 0) {
graphics.lineStyle(borderWidth, borderColor);
graphics.moveTo(0,0);
graphics.lineTo(0, height);
graphics.lineTo(width, height);
graphics.lineTo(width, 0);
graphics.lineTo(0, 0);
}
}
//draw immediatly on creation
draw();
return graphics;
}
|
Markdown
|
UTF-8
| 7,220 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: "Ski touring in the rockies"
date: 2021-03-29
categories: mountaineering
---
Hello again friends,
Hope everyone is keeping safe. My mom has been informing me about the COVID situation in India which
is worsening and that the vaccines have not been effective in mitigating the disease spread and
preventing infection amongst the vaccinated individuals either. Sticking to our protocols is the
only reliable tool in our arsenal that we know we have.
Sunrises are stunning to look at and when the conditions are just perfect, I can’t resist taking a
picture even if I have seen the sun rise at the same location before.

Yet another beautiful sunrise
Obviously, I am very lucky that I am able to do this course but one of the more underrated moments
is when I sit down to write my weekly newsletter. I get to take in this view while I reflect on the
past week!

We just had a fresh dumping of snow today
Mother Nature has been our friend on this course so far (hopefully not jinxed by saying that). We
got warm temps and clear weather for the most part during the ice climbing section and a dumping of
snow and lower temperatures as we came into the ski section!
**Ski resort day**
We woke up on the first day of the section with a massive dumping of snow the night before with more
snow continuing to fall.

Best feeling waking up to fresh snow
This was a day for the instructors to figure out the ski skills of the group. By far I was the
weakest skier of the group and while expected, is never a fun place to be in! I had rented skis that
I had never used before and had not skied in about 6 years so was completely overwhelmed. However,
the instructors Grant and Larry helped me deal with the situation and helped me through feeling more
accustomed to the skis again. It was nice to be back at the ski hill though and brought up some
nostalgic memories of skiing with my close friends in college.
**Ski tour day**
The following day we headed up to a mountain called Black Prince. While we didn’t go up to the
summit, we used the region to practice our avalanche rescue drills and ski touring for our upcoming
trip.
The road heading up to the trailhead is a rough one. While Grant was our primary guide, Pat was our
secondary guide and our van driver for the day and he was quite the character. On the ride to the
trailhead, he essentially spoke non-stop for 30 mins and had no dearth of chatter at any point
during the day. He drove us down that bumpy road at 110 km/h screaming that it is a smoother ride if
we go faster over the bumps. And while that may be true, it was a roller coaster at the back with
the sliding on snow and the hard bumps. A ride to remember!

Getting ready for out avalanche rescue drill

Grant looking up at Black Prince
It was a great day out. We had fresh powder to ski on, I crashed on the way down like 3 times
including inventing a new tree hook stopping technique. Grant says I should patent it - its quite
simple really. If you think you’re going too fast, just stick your leg out and hopefully you hook
onto a tree to bring you to a stop - extremely effective but would not recommend.
**Ski tour expedition**
The next few days were spent prepping for the expedition and then heading out. Given my performance
over the past few days, I was extremely nervous but my course mates are great - they helped me calm
my nerves. We started off right next to the Sunshine ski hill (where we went for our ski day)
You might be wondering what ski touring means. Essentially, we use special skis - they use a
different kind of bindings for your shoes that let you transition from ski to walk mode. The ski
mode operates like traditional downhill skis and the walk mode lets you walk around with the skis
and even uphill when you add put skins on the bottom. The skins let the skis slide forward but not
back on snow. This allows you to gain elevation and when you decide to ski down, you simply
transition the skis to ski mode and then you can ski down like normal.

A lot of our time was spent transitioning from ski to walk mode and vice versa
Our plan was to ski up the Healy Creek Trail to the Monarch Ramparts which is the ridge line of
Monarch mountain. Sadly the entire time we were up there, the cloudy skies prevented us from getting
a clear picture of this scenic mountain.

Looking up at the Ramparts which are visible but the Monarch barely visible behind the
clouds
We spent the first day getting to camp and setting it up. Once we got the kitchen going, everyone
got excited and we started cooking. Much of our time during the mornings and evenings was spent
melting snow into water for cooking and filling up our bottles.

We spent some time setting up our kitchen where we spent most of our trip down time
melting water

Grant and Tak were our guides for this trip and they were awesome. Grant met his wife
Meagan on Everest and had so many amazing personal stories
The next day was spent skiing around the area and exploring the monarch ramparts. We spent a lot of
time on the previous days discussing the avalanche risks which we concluded were low where we would
ski. I spent a lot of my time wiping out skiing downhill and then spending more time going uphill.
It was extremely tiring! But I was able to see gorgeous landscapes while at the top - a teaser for
the upcoming sections.

Part of the Monarch became visible later during the day

Skiing along side the towering snow covered trees which was the norm for our ski in and
out
We spent most of yesterday enjoying a hearty breakfast of eggs and hash browns with some bacon and
then skiing via the Healy creek trail. I fell numerous times on the way out but I managed to get out
somehow and without any injuries. Super happy about that! Also Grant, our guide, said that I should
be good enough for the following sections of skiing and I am excited that I can fully partake!
Today is our rest day to organize our things, recover from our weekend activities and get ready for
our trip starting on Wednesday. Next week will be our AST 2 (avalanche safety training level 2)
which will be done while backcountry camping.
Overall its been a relatively rough week with my skiing skills holding me back a bit and exhausting
me more than others because of poor technique. In addition, it has been a fight against my internal
negative voice which has been draining a bit mentally as well. Still an awesome week which included
lots of learning and looking forward to the next week!
Thanks for reading! Stay safe and look out for the next email next week!
-- G
|
JavaScript
|
UTF-8
| 584 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
var fs = require('fs');
//Constructor accepts 2 arguments
var BasicCard = function(front, back){
//Front contains front card text
this.front = front;
//Back contains back card text
this.back = back;
this.create = function(){
//Create var with card data
var cardData = {
front : this.front,
back : this.back,
type: 'basic',
};
//Append card data to text file
fs.appendFile('questions.txt', JSON.stringify(cardData) + ';','utf8', function(error){
if(error){
console.log(error);
}
})
};
};
//Exports the constructor
module.exports = BasicCard;
|
Java
|
UTF-8
| 298 | 2.328125 | 2 |
[] |
no_license
|
package com.mgl.neural;
public class ActivationFunction {
public ActivationFunction(){}
public float executeFunction(float entry, float activationVal){
try {
if(entry>=activationVal){
return 1;
}
return 0;
} catch (Exception e) {
}
return 0;
}
}
|
C#
|
UTF-8
| 1,487 | 3.40625 | 3 |
[] |
no_license
|
using System;
namespace server.Models
{
public class GeoName: IEquatable<GeoName>
{
public string ToponymName { get; set; }
public string AdminName1 { get; set; }
public string CountryName { get; set; }
public bool Equals(GeoName other)
{
//Check whether the compared object is null.
if (Object.ReferenceEquals(other, null)) return false;
//Check whether the compared object references the same data.
if (Object.ReferenceEquals(this, other)) return true;
//Check whether the products' properties are equal.
return ToponymName.Equals(other.ToponymName) &&
AdminName1.Equals(other.AdminName1) &&
CountryName.Equals(other.CountryName);
}
public override int GetHashCode()
{
//Get hash code for the ToponymName field if it is not null.
int hashToponymName = ToponymName == null ? 0 : ToponymName.GetHashCode();
//Get hash code for the AdminName1 field.
int hashAdminName1 = AdminName1 == null ? 0 : AdminName1.GetHashCode();
//Get hash code for the CountryName field.
int hashCountryName = CountryName == null ? 0 : CountryName.GetHashCode();
//Calculate the hash code for the GeoName.
return hashToponymName ^ hashAdminName1 ^ hashCountryName;
}
}
}
|
TypeScript
|
UTF-8
| 381 | 2.65625 | 3 |
[] |
no_license
|
import { treeTraverser } from '../traversers';
import { ConditionFn, ObjectTreeNode } from '../types';
export function findNodes<T extends ObjectTreeNode>(
root: T,
condition: ConditionFn,
strategy = treeTraverser,
): T[] {
const matches: T[] = [];
strategy(root, node => {
if (condition(node) === true) {
matches.push(node);
}
});
return matches;
}
|
Java
|
UTF-8
| 1,081 | 3.265625 | 3 |
[] |
no_license
|
/**
* @author DengYouming
* @since 2016-7-29 下午2:25:54
*/
package org.hpin.webservice.util;
import java.util.Comparator;
/**
* ASCII码比较器
* @author DengYouming
* @since 2016-7-29 下午2:25:54
*/
public class AsciiComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return compareOneByOne(o1, o2);
}
/**
* 逐字比较字符串ascii码
* @param o1
* @param o2
* @return int
* @author DengYouming
* @since 2016-7-29 下午4:33:42
*/
private static int compareOneByOne(String o1, String o2){
int res = 0;
if(o1!=null&&o1.length()>0&&o2!=null&&o2.length()>0){
int len = o1.length()<=o2.length()?o1.length():o2.length();
for (int i = 0; i < len; i++) {
if(o1.charAt(i)==o2.charAt(i)){
if(i==len-1){
if(o1.length()>o2.length()){
res = 1;
break;
}else{
res = -1;
break;
}
}
continue;
}
if(o1.charAt(i)>o2.charAt(i)){
res = 1;
break;
}else{
res = -1;
break;
}
}
}
return res;
}
}
|
Java
|
UTF-8
| 1,342 | 2.265625 | 2 |
[] |
no_license
|
package mandatory.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@Controller
public class HomeController {
Purchase purchase = new Purchase();
@GetMapping("/")
public String home(){
return "index";
}
@PostMapping("/check-InternetConnection")
public @ResponseBody int checkInternetConnection(boolean internetConnection){
return purchase.checkInternetConnection(internetConnection);
}
@PostMapping("/add-PhoneLine")
public @ResponseBody int addPhoneLine(){
return purchase.addPhoneLine();
}
@PostMapping("/remove-PhoneLine")
public @ResponseBody int removePhoneLine(){
return purchase.removePhoneLine();
}
@PostMapping("/add-CellPhone")
public @ResponseBody int addCellPhone(String cellphone){
return purchase.addCellPhone(cellphone);
}
@PostMapping("/remove-CellPhone")
public @ResponseBody int removeCellPhone(String cellphone){
return purchase.removeCellPhone(cellphone);
}
@PostMapping("/buy")
public @ResponseBody String buyProducts() {
return purchase.buy();
}
@PostMapping("/reset")
public @ResponseBody String reset(){
return purchase.reset();
}
}
|
Python
|
UTF-8
| 1,121 | 2.78125 | 3 |
[] |
no_license
|
# Python Application Logging
# Dealing with handlers that block
# The advantage of having a separate QueueListener class
# is that you can use the same instance to service multiple
# QueueHandlers. This is more resource-friendly than, say,
# having threaded versions of the existing handler classes,
# which would eat up one thread per handler for no particular
# benefit.
# An example of using these two classes follows (imports omitted):
import logging
import logging.config
import time
import os
import socket, sys, struct
que = queue.Queue(-1) # no limit on size
queue_handler = QueueHandler(que)
handler = logging.StreamHandler()
listener = QueueListener(que, handler)
root = logging.getLogger()
root.addHandler(queue_handler)
formatter = logging.Formatter('%(threadName)s: %(message)s')
handler.setFormatter(formatter)
listener.start()
# The log output will display the thread which generated
# the event (the main thread) rather than the internal
# thread which monitors the internal queue. This is what
# you want to happen.
root.warning('Look out!')
listener.stop()
|
Java
|
UTF-8
| 5,926 | 1.96875 | 2 |
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.neevtech.callguard.services;
import com.neevtech.callguard.ReportedNumbers;
import com.neevtech.callguard.Users;
import com.neevtech.callguard.request.Paging;
import com.neevtech.callguard.response.BannedNumberResponseDTO;
import com.neevtech.callguard.response.ReportedNumberResp;
import com.neevtech.callguard.utils.Constants;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
/**
*
* @author ashish
*/
@Stateless
@Path("reportednumbers")
public class ReportedNumbersFacadeREST extends AbstractFacade<ReportedNumbers> {
// @Inject
// private ReportedNumberResp resp;
@Inject
private BannedNumberResponseDTO bnrdto;
@PersistenceContext(unitName = "com.neevtech.callguard_CallGuard_war_1.0SNAPSHOTPU")
private EntityManager em;
public ReportedNumbersFacadeREST() {
super(ReportedNumbers.class);
}
// @POST
// @Override
// @Consumes({"application/xml", "application/json"})
public void create(ReportedNumbers entity) {
super.create(entity);
}
//
// @PUT
// @Override
@Consumes({"application/xml", "application/json"})
public void edit(ReportedNumbers entity) {
super.edit(entity);
}
// @DELETE
// @Path("{id}")
public void remove(@PathParam("id") Integer id) {
super.remove(super.find(id));
}
// @GET
// @Path("{id}")
@Produces({"application/xml", "application/json"})
public ReportedNumbers find(@PathParam("id") Integer id) {
return super.find(id);
}
// @GET
// @Override
@Produces({"application/xml", "application/json"})
public List<ReportedNumbers> findAll() {
return super.findAll();
}
// @GET
// @Path("{from}/{to}")
@Produces({"application/xml", "application/json"})
public List<ReportedNumbers> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}
// @GET
// @Path("count")
// @Produces("text/plain")
public String countREST() {
return String.valueOf(super.count());
}
@Override
protected EntityManager getEntityManager() {
return em;
}
public ReportedNumbers findByNumber(String number) {
Query q = em.createNamedQuery("ReportedNumbers.findByNumber", ReportedNumbers.class);
q.setParameter("number", number);
if (q.getResultList().size() == 1) {
ReportedNumbers u = (ReportedNumbers) q.getResultList().get(0);
return u;
} else {
return null;
}
}
@POST
@Path("getBannedNumbers")
@Consumes("application/json")
@Produces("application/json")
public Response getBannedNumbers(Paging p) {
try {
int from = Integer.parseInt(p.getFrom());
int to = Integer.parseInt(p.getTo());
List<ReportedNumbers> response = super.findRange(new int[]{from, to});
Users u = getUserObject(p.getToken());
if (u != null) {
List<ReportedNumberResp> respList = processCallResponse(response);
System.err.println("List" + respList.toString());
if (respList.size() > 0) {
bnrdto.setStatus(Constants.STATUS_SUCCESS);
bnrdto.setMessage(Constants.RESPONSE_SUCCESS_MSG);
bnrdto.setList(respList);
return Response.status(200).entity(bnrdto).build();
} else {
bnrdto.setStatus(Constants.STATUS_FAILURE);
bnrdto.setMessage(Constants.RESPONSE_FAILURE_MSG);
bnrdto.setList(respList);
return Response.status(200).entity(bnrdto).build();
}
} else {
bnrdto.setStatus(Constants.STATUS_FAILURE);
bnrdto.setMessage(Constants.TOKEN_EXPIRED);
bnrdto.setList(null);
return Response.status(403).entity(bnrdto).build();
}
} catch (Exception e) {
bnrdto.setStatus(Constants.STATUS_FAILURE);
bnrdto.setMessage(Constants.RESPONSE_FAILURE_MSG);
bnrdto.setList(null);
return Response.status(503).entity(bnrdto).build();
}
}
private List<ReportedNumberResp> processCallResponse(List<ReportedNumbers> list) {
List<ReportedNumberResp> reportResponses = new ArrayList<ReportedNumberResp>();
for (ReportedNumbers cr : list) {
ReportedNumberResp resp = new ReportedNumberResp();
resp.setBanned(cr.getBanned());
resp.setPhoneNumber(cr.getNumber());
System.err.println("Returning item" + resp.toString());
reportResponses.add(resp);
}
System.err.println("Process response item" + reportResponses.toString());
return reportResponses;
}
private Users getUserObject(String token) {
Query q = getEntityManager().createNamedQuery("Users.findByToken", Users.class);
q.setParameter("token", token);
if (q.getResultList().size() == 1) {
Users u = (Users) q.getResultList().get(0);
System.err.println("Found User Object in reported Number" + u.getEmailId());
return u;
} else {
System.err.println("Reported Number User Object null");
return null;
}
}
}
|
Markdown
|
UTF-8
| 2,168 | 2.8125 | 3 |
[] |
no_license
|
# daf2-dauer-comparisons
Comparison analysis of daf-2 dauer connectome dataset with wildtype nondauer connectome datasets
## Required Software
- Python 3.8.2
## Usage
Install project dependencies
`pip3 install -r requirements.txt `
Make new folders `output`, `graphs` and `analysis`
1. Edit data_organizer.py wity your values for:
- ```connection_type```: cell-to-cell or neuron_pair
- ```compare_contactome_with```: all_nondauer or L1-L3
- ```normalize_by```: input, output or entire_dataset
- ```synapse_type```: count or size
2. Run `data_organizer.py`
3. Edit generate_tables.py with your values for:
- ```connection_type```: cell-to-cell or neuron_pair (Make sure this matches data_organizer.py)
- ```compare_contactome_with```: all_nondauer or L1-L3 (Make sure this matches data_organizer.py)
- ```synapse_type```: count or size(Make sure this matches data_organizer.py)
- ```zero_filter```: 10 (all data) or 'early_development' (filter to allow 1 zero in early development)
- ```compare```: daf2-dauer or L3 (L3 was added for proof of concept purposes)
- ```pvalue_cutoff```: Your desired pvalue threshold, 0.05 is default
- ```fdr_correction```: True or False
4. Run generate_tables.py
5. Repeat steps 1-4 until your required conditions are completed.
6. Make new folder in `graphs` folder, name using your value entered for `compare` in the previous step
7. Within the `{your value for compare}` folder, make new folder called `nonparametric_bootstrapping`
8. Edit connection_classification.py with your values for:
- ```filter``` = '1_zero_in_early_development' or 'all_connections'
- ```cutoff``` = pvalue threshold, 0.05 is default
- ```find_shared_stable_pvalues``` = True or False (Whether you want to only look at connections with pvalues under the threshold for all 3 normalization methods)
- ```compare``` = daf2-dauer or L3
9. Make new folder in `output` folder called `connection_lists`
10. Run `connection_classification.py`
11. Edit summary_plot.py with your values for:
- ```compare``` = daf2-dauer or L3 (Make sure this is the same value as above)
12. Run `summary_plot.py`
|
Java
|
UTF-8
| 8,709 | 2.09375 | 2 |
[] |
no_license
|
package com.example.demo.Controller;
import com.alibaba.fastjson.JSON;
import com.example.demo.Model.PayPosal;
import com.example.demo.Model.Scanner;
import com.example.demo.Model.Wechat;
import com.example.demo.Repository.PayPosalRepository;
import com.example.demo.Repository.WechatRepository;
import com.example.demo.Utils.Config;
import com.example.demo.Utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/**
* Created by snsoft on 19/12/2018.
*/
@Controller
@RequestMapping("/")
public class DemoController {
@Autowired
PayPosalRepository payPosalRepository;
@Autowired
private WechatRepository wechatRepository;
/*
* forward 示例: 以字符串的形式构建目标url, url 需要加上 forward: 前缀
* */
@RequestMapping("/forwardTest1")
public String forwardTest1() {
return "forward:/forwardTarget?param1=v1¶m2=v2";
}
/*
* forward 示例: 使用 ModelAndView() 设置转发的目标url
* */
@RequestMapping("/forwardTest2")
public ModelAndView forwardTest2() {
ModelAndView mav = new ModelAndView("/forwardTarget"); // 绝对路径OK
//ModelAndView mav=new ModelAndView("forwardTarget"); // 相对路径也OK
mav.addObject("param1", "value1");
mav.addObject("param2", "value2");
return mav;
}
@RequestMapping("/forwardTarget")
public String forwardTargetView(Model model, @RequestParam("param1") String param1,
@RequestParam("param2") String param2) {
model.addAttribute("param1", param1);
model.addAttribute("param2", param2);
return "forwardTarget";
}
/*
* redirect 目标有三种构建方式
* 1. 使用 redirect: 前缀url方式构建目标url
* 2. 使用 RedirectView 类型指定目标
* 3. 使用 ModelAndView 类型指定目标, ModelAndView 视图名默认是forward, 所以对于redirect, 需要加上 redirect: 前缀
* */
@RequestMapping("/noParamRedirect")
public RedirectView noParamTest() {
RedirectView redirectTarget = new RedirectView();
redirectTarget.setContextRelative(true);
redirectTarget.setUrl("noParamTarget");
return redirectTarget;
}
@RequestMapping("/noParamTarget")
public String redirectTarget() {
return "noParamTarget";
}
@RequestMapping("/withParamRedirect")
public RedirectView withParamRedirect(RedirectAttributes redirectAttributes) {
RedirectView redirectTarget = new RedirectView();
redirectTarget.setContextRelative(true);
redirectTarget.setUrl("withParamTarget");
redirectAttributes.addAttribute("param1", "value1");
redirectAttributes.addAttribute("param2", "value2");
return redirectTarget;
}
@RequestMapping("/withParamTarget")
public String withParamTarget(Model model, @RequestParam("param1") String param1,
@RequestParam("param2") String param2) {
model.addAttribute("param1", param1);
model.addAttribute("param2", param2);
return "withParamTarget";
}
@RequestMapping("/withFlashRedirect")
public RedirectView withFlashTest(RedirectAttributes redirectAttributes) {
RedirectView redirectTarget = new RedirectView();
redirectTarget.setContextRelative(true);
redirectTarget.setUrl("withFlashTarget");
redirectAttributes.addAttribute("param", "value");
redirectAttributes.addFlashAttribute("flashParam", "flashValue");
return redirectTarget;
}
/*
* redirectAttributes.addAttribute加的attr, 使用 @RequestParam()来fetch
* redirectAttributes.addFlashAttribute()加的attr, 使用 @ModelAttribute()来fetch
* */
@RequestMapping("/withFlashTarget")
public String withFlashTarget(Model model, @RequestParam("param") String param,
@ModelAttribute("flashParam") String flashParam) {
model.addAttribute("param", param);
model.addAttribute("flashParam", flashParam);
return "withFlashTarget";
}
@GetMapping("/input")
public String input() {
return "input";
}
@GetMapping("/scanner")
public RedirectView scanner(@RequestParam String depositNumber) {
RedirectView redirectTarget = new RedirectView();
PayPosal payProposalDeposit = payPosalRepository.findBydepositNumber(depositNumber);
if (payProposalDeposit == null || !Config.Normal.equals(payProposalDeposit.getState()))
redirectTarget.setUrl("https://www.baidu.com");
else {
Wechat wechat = wechatRepository.findByOnlyName(payProposalDeposit.getPayAccont());
if (wechat == null || !"1".equals(wechat.getType()))
redirectTarget.setUrl("https://www.baidu.com");
else {
redirectTarget.setUrl(wechat.getQrurl());
}
}
redirectTarget.setEncodingScheme("GBK");
URLDecoder.decode(redirectTarget.getUrl());
// redirectTarget.set
// redirectAttributes.addFlashAttribute("errorMessage", "some error information here");
return redirectTarget;
}
/*
* form 提交后, 如果form数据有问题, 使用redirectAttributes.addFlashAttribute()加上 flash message.
* addFlashAttribute()可以是任意类型的数据(不局限在String等基本类型)
* addFlashAttribute() 加的 attr, 不会出现在url 地址栏上.
* addFlashAttribute() 加的 attr, 一旦fetch后, 就会自动清空, 非常适合 form 提交后 feedback Message.
* */
@GetMapping("/submit")
public RedirectView submit(Model model, RedirectAttributes redirectAttributes, @RequestParam(value = "money", required = false) String money, @RequestParam(value = "userId", required = false) String userId, @RequestParam(value = "memo", required = false) String memo) throws Exception {
// public RedirectView submit(Model model, RedirectAttributes redirectAttributes) {
boolean passed = false;
if (passed == false) {
RedirectView redirectTarget = new RedirectView();
redirectTarget.setContextRelative(true);
Map<String, Object> map = new HashMap<>();
Map<String, Object> mapitem = new HashMap<>();
Scanner scanner = new Scanner(userId, money, memo);
mapitem.put("u", userId);
mapitem.put("m", memo);
mapitem.put("a", money);
mapitem.put("s", "money");
String biz_data = JSON.toJSON(scanner).toString();
System.out.println("biz_data:" + biz_data);
map.put("biz_data", URLDecoder.decode(biz_data, "UTF-8"));
// map.put("biz_data", "{s:money,u:2088332303970141,a:51,m:120181219001389}");
// map.put("biz_data", "'a':'51','s':'money','u':'2088332303970141','m':'120181219001389'");
map.put("appId", "20000123");
map.put("actionType", "scan");
// redirectTarget.setUrl("input");
// redirectTarget.setUrl("alipays://platformapi/startapp?appId=20000123&actionType=scan&biz_data={\"s\":\"money\",\"u\":\"" + userId + "\",\"a\":\"51\",\"m\":\"" + memo + "\"}");
model.addAttribute("biz_data", "{\"s\":\"money\",\"u\":\"2088332303970141\",\"a\":\"51\",\"m\":\"120181219001389\"}");
model.addAttribute("appId", "20000123");
model.addAttribute("actionType", "scan");
redirectTarget.setUrl("alipays://platformapi/startapp");
// redirectTarget.setEncodingScheme(“”);
// redirectTarget.setUrl("alipays://platformapi/startapp"+);
redirectTarget.setAttributesMap(map);
redirectTarget.setEncodingScheme("GBK");
URLDecoder.decode(redirectTarget.getUrl());
// redirectTarget.set
redirectAttributes.addFlashAttribute("errorMessage", "some error information here");
return redirectTarget;
} else {
RedirectView redirectTarget = new RedirectView();
redirectTarget.setContextRelative(true);
redirectTarget.setUrl("inputOK");
return redirectTarget;
}
}
}
|
Java
|
UTF-8
| 1,335 | 4.125 | 4 |
[] |
no_license
|
//Design and implement a TwoSum class. It should support the following operations: add and find.
//add - Add the number to an internal data structure.
//find - Find if there exists any pair of numbers which sum is equal to the value.
public class TwoSum {
/**
* @param number: An integer
* @return: nothing
*/
private List<Integer> list = null;
private Map<Integer, Integer> map = null;
public TwoSum() {
list = new ArrayList<Integer>();
map = new HashMap<Integer, Integer>();
}
public void add(int number) {
// write your code here
if(map.containsKey(number)){
map.put(number,map.get(number)+1);
}
else{
map.put(number,1);
list.add(number);
}
}
/**
* @param value: An integer
* @return: Find if there exists any pair of numbers which sum is equal to the value.
*/
public boolean find(int value) {
// write your code here
for(int i=0;i<list.size();i++){
int num1=list.get(i),num2=value-num1;//!important note: do not forget to include the condition that value%2==0
if((num1==num2&&map.get(num1)>1)||(num1!=num2&&map.containsKey(num2))){
return true;
}
}
return false;
}
}
|
Java
|
UTF-8
| 1,002 | 2.25 | 2 |
[] |
no_license
|
package es.blog.springBlog.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import es.blog.springBlog.dao.PublicationRepository;
import es.blog.springBlog.model.Publication;
@Service
public class PublicationServiceImpl implements PublicationService {
@Autowired
protected PublicationRepository publicationRepository;
@Override
public Publication save(Publication publication) {
return this.publicationRepository.save(publication);
}
@Override
public List<Publication> findAll() {
return this.publicationRepository.findAll();
}
@Override
public Publication findOneById(Long id) {
Optional<Publication> optional = this.publicationRepository.findById(id);
if(optional.isPresent()) {
return optional.get();
}
return new Publication();
}
@Override
public void deletePublication(Long id) {
this.publicationRepository.deleteById(id);
}
}
|
Ruby
|
UTF-8
| 610 | 2.953125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
## Code your solution below. Note that your SQL queries should be in quotation marks.
#def highest_student_gpa
#end
#def lowest_student_gpa
#end
#def average_student_gpa
#end
#def total_tardies_for_all_students
#end
#def average_gpa_for_9th_grade
#end
def highest_student_gpa
"SELECT MAX(gpa) FROM students"
end
def lowest_student_gpa
"SELECT MIN(gpa) FROM students"
end
def average_student_gpa
"SELECT AVG(gpa) FROM students"
end
def total_tardies_for_all_students
"SELECT SUM(tardies) FROM students"
end
def average_gpa_for_9th_grade
"SELECT AVG(gpa) FROM students WHERE grade = 9"
end
|
Java
|
UTF-8
| 2,627 | 3.3125 | 3 |
[
"MIT"
] |
permissive
|
package hr.fer.zemris.image.binarization;
import hr.fer.zemris.image.ImageUtility;
import java.awt.Color;
import java.awt.image.BufferedImage;
/**
* Binarization algorithm that uses otsu binarization method.
*
* @author Domagoj Pluscec
* @version v1.0, 20.5.2017.
*/
public class OtsuAlgorithm implements IBinarizationAlgorithm {
/**
* Method calculates threshold using Otsu's method.
*
* @param original
* original image
* @return otsu threshold
*/
private static int otsuTreshold(BufferedImage original) {
int[] histogram = ImageUtility.imageHistogram(original);
int total = original.getHeight() * original.getWidth();
float sum = 0;
final int maxIntensityLength = 256;
for (int i = 0; i < maxIntensityLength; i++) {
sum += i * histogram[i];
}
float sumB = 0;
int wB = 0;
int wF = 0;
float varMax = 0;
int threshold = 0;
for (int i = 0; i < maxIntensityLength; i++) {
wB += histogram[i];
if (wB == 0) {
continue;
}
wF = total - wB;
if (wF == 0) {
break;
}
sumB += i * histogram[i];
float mB = sumB / wB;
float mF = (sum - sumB) / wF;
float varBetween = (float) wB * (float) wF * (mB - mF) * (mB - mF);
if (varBetween > varMax) {
varMax = varBetween;
threshold = i;
}
}
return threshold;
}
@Override
public BufferedImage toBinary(BufferedImage original) {
int red;
int newPixel;
int threshold = otsuTreshold(original);
BufferedImage binarized = new BufferedImage(original.getWidth(), original.getHeight(), original.getType());
final int maxIntensity = 255;
for (int i = 0; i < original.getWidth(); i++) {
for (int j = 0; j < original.getHeight(); j++) {
// Get pixels
red = new Color(original.getRGB(i, j)).getRed();
int alpha = new Color(original.getRGB(i, j)).getAlpha();
if (red > threshold) {
newPixel = maxIntensity;
} else {
newPixel = 0;
}
newPixel = ImageUtility.colorToRGB(alpha, newPixel, newPixel, newPixel);
binarized.setRGB(i, j, newPixel);
}
}
return binarized;
}
@Override
public String toString() {
return "Otsu";
}
}
|
C
|
UTF-8
| 6,521 | 3.375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define queueSize_Max 256 //队列的最大长度
#define code_Max 256 //编码的最大长度
typedef struct hfmTreeNode{
int symbol;
struct hfmTreeNode *left;
struct hfmTreeNode *right;
} hfmTreeNode, *phTreeNode;
typedef struct hHfmTreeNode{
hfmTreeNode* rootNode;
} hHfmTreeNode;
typedef struct queueNode{
phTreeNode ptr;
int count;
struct queueNode *next;
} queueNode, *ptrQueue;
typedef struct hQueueNode{
int size;
ptrQueue first;
} hQueueNode;
typedef struct tableNode{
char symbol;
char* code;
struct tableNode *next;
} tableNode;
typedef struct hdTableNode{
tableNode *first;
tableNode *last;
} hdTableNode;
void initQueue(hQueueNode** hQueue)
{
*hQueue=(hQueueNode*)malloc(sizeof(hQueueNode));
(*hQueue)->size=0;
(*hQueue)->first=NULL;
}
void addQueueNode(hQueueNode **hQueue,hfmTreeNode *hNode,int count)//新建一个队列节点并按统计的结果从小到大的顺序加入队列
{
queueNode *qNode=NULL;
if((*hQueue)->size==queueSize_Max)//队列规模检查,正常情况下不会出现
{
printf("\nERR: The queue is full!!!");
}
else //如果正常,则按照从小到大的顺序,寻找正确的位置插入节点
{
if(0==(*hQueue)->size)//如果是添加的第一个节点,直接添加即可
{
qNode=(queueNode*)malloc(sizeof(queueNode));
(*hQueue)->first=qNode;
qNode->count=count;
qNode->ptr=hNode;
qNode->next=NULL;
(*hQueue)->size++;
}
else if(count<(*hQueue)->first->count)//如果要添加的字符的统计数量小于现有最小的,则直接放在第一个节点处
{
qNode=(queueNode*)malloc(sizeof(queueNode));
qNode->next=(*hQueue)->first;
(*hQueue)->first=qNode;
qNode->count=count;
qNode->ptr=hNode;
(*hQueue)->size++;
}
else //对于第三类情况,则需要遍历队列,直到寻找到合适的位置
{
queueNode* p=(*hQueue)->first;
qNode=(queueNode*)malloc(sizeof(queueNode));
qNode->count=count;
qNode->ptr=hNode;
(*hQueue)->size++;
while(p->next!=NULL && count>=p->next->count)
p=p->next;
qNode->next=p->next;
p->next=qNode;
}
}
}
hfmTreeNode* getHfmTreeNode(hQueueNode* hQueue)
{
hfmTreeNode* getNode;
if(hQueue->size>0)
{
getNode=hQueue->first->ptr;
hQueue->first=hQueue->first->next;
hQueue->size--;
}
else
{
printf("\nERR: Can't get a node\n");
}
return getNode;
}
hHfmTreeNode* crtHfmTree(hQueueNode** hQueue)
{
int count=0;
hfmTreeNode *left, *right;
while((*hQueue)->size>1)
{
count=(*hQueue)->first->count+(*hQueue)->first->next->count;
left=getHfmTreeNode(*hQueue);
right=getHfmTreeNode(*hQueue);
hfmTreeNode *newNode=(hfmTreeNode*)malloc(sizeof(hfmTreeNode));
newNode->left=left;
newNode->right=right;
addQueueNode(hQueue,newNode,count);
}
hHfmTreeNode* tree=(hHfmTreeNode*)malloc(sizeof(hHfmTreeNode));
tree->rootNode=getHfmTreeNode(*hQueue);
return tree;
}
hHfmTreeNode* creatTree(void)
{
int *countArray;
char c;
int i;
countArray=(int*)malloc(sizeof(int)*256);//分配空间用于存储各字符出现的次数,并初始化为零
for(i=0;i<256;i++)
{
countArray[i]=0;
}
hQueueNode *hQueue;
initQueue(&hQueue);
for(i=0;i<256;i++)
{
if(countArray[i])
{
//printf("%c %d\n",i, countArray[i] );
hfmTreeNode *hNode=(hfmTreeNode*)malloc(sizeof(hfmTreeNode));//创建一个树节点,并初始化(用来对应队列queueNode中的ptr)
hNode->symbol=(char)i;
hNode->left=NULL;
hNode->right=NULL;
addQueueNode(&hQueue,hNode,countArray[i]);//将该节点插入队列中的适当位置(按统计的结果,从小到大排列)
}
}
free(countArray);//释放不用的内存
queueNode* q=hQueue->first;
printf("\n");
do
{
printf("\n%c %d",q->ptr->symbol, q->count);
q=q->next;
} while(q!=NULL);
//printf("%d",hQueue->size);
hHfmTreeNode *tree=crtHfmTree(&hQueue);
return tree;
}
void traverseTree( hdTableNode** table, hfmTreeNode* tree, char* code, int k)
{
if(tree->left==NULL && tree->right==NULL) //递归结束检查,即找到叶子节点
{
code[k]='\0'; //添加字符串结束标记
tableNode *tNode=(tableNode*)malloc(sizeof(tableNode)); //创建一个节点,并将其添加到table链表中
tNode->code=(char*)malloc(sizeof(char)*256+1);
strcpy(tNode->code,code);
tNode->symbol=tree->symbol;
tNode->next=NULL;
if((*table)->first==NULL) //如果是第一个节点,直接添加即可, 否则添加到尾部即可
{
(*table)->first=tNode;
(*table)->last=tNode;
}
else
{
(*table)->last->next=tNode;
(*table)->last=tNode;
}
}
if(tree->left!=NULL) //向左边递归,并记录编码为0
{
code[k]='0';
traverseTree(table,tree->left, code, k+1);
}
if(tree->right!=NULL) //向右边递归,并记录编码为1
{
code[k]='1';
traverseTree(table, tree->right, code, k+1);
}
}
hdTableNode* crtTable(hHfmTreeNode* hfmTree)
{
hdTableNode* hdTable=(hdTableNode*)malloc(sizeof(hdTableNode));
hdTable->first=NULL;
hdTable->last=NULL;
char code[code_Max];
int k=0; //记录树的层级
traverseTree(&hdTable, hfmTree->rootNode, code, k);
return hdTable;
}
int main(void)
{
hHfmTreeNode* tree;
hdTableNode* table;
tree=creatTree();
table=crtTable(tree);
int i=0, j=0;
tableNode* t=table->first;
char* s=t->code;
printf("The Huffman code is:\n");
while(t!=NULL)
{
for(i=0;i<257;i++)
{
if((*s)!='\0')
{
printf("%c",*s);
s++;
}
}
printf("%8c\n",t->symbol);
t=t->next;
if(t)
s=t->code;
}
}
|
Markdown
|
UTF-8
| 15,197 | 3.296875 | 3 |
[] |
no_license
|
---
layout: page
date: 2023-05-14 01:17:16 -0700
fullPath: /home/ubuntu/Git/CloudNotes/elvenware/development/web/JavaScript/NodeJade.md
directoryPath: /home/ubuntu/Git/CloudNotes/elvenware/development/web/JavaScript
fileName: NodeJade.md
relativePath: /web/JavaScript/NodeJade.md
title: NodeJade
directoryName: JavaScript
category: JavaScript-guide
---
# Pug and Jade
[Pug][pug] is a template library similar to [HAML](http://haml.info/) and not totally unlike other popular template libraries such as [Handlebars](http://handlebarsjs.com/). It also is a bit like Markdown, in that it provides a shorthand syntax for composing HTML pages.
**NOTE**: _The pug library used to be called Jade._
## Overview
We will use Pug as a template engine. It allows us to:
- Use a very readable shorthand for creating HTML
- Use JavaScript declared variables in our HTML so we can make a change in one place and see it propagated everywhere
- Divide our pages up into composable, reusable modules. For instance, on all our pages we can use a header and footer that we define only once in specific place.
- Use Mixins, which are reusable chunks of HTML that can be inserted anywhere in our pages. For instance, a specific kind of customized button.
- To understand all this takes time, but it is a very useful skill to develop.
There are other templates engines. Which one you use can be a matter of taste or a matter of fitting the right tool to the right use case. We will focus mostly on Pug because it is widely used and well written and well integrated into Express.
Pug used to be called Jade. There was a copyright issue regarding the name, so we now call it pug. I didn't like the new name at first, but it has grown on me. Certainly, it is short! There may be assignments where I talk about Jade, just remind me to update the assignment, and mentally change the word Jade to Pug.
## Clean
Many developers like to use Pug instead of raw HTML for several reasons:
- It has a clean easy to read syntax
- It is more succinct than HTML
- It is also more flexible than HTML. For instance, it allows developers to declare variables and reuse code.
Here is an example of how to layout a pug template:
```text
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
nav
ul
li
a(href="/") page01
li
a(href="/page02") page02
li
a(href="/page03") page03
h1 #{title}
block content
```
When working with Pug, indentation is crucial. You should indent with either tabs or spaces, but not both. You frequently need to open your file in an editor that allows you to visualize your white space. Then you should count your spaces, and make sure it follows an exact pattern. Suppose, for instance, that you are using tabs for your indentation. In the pseudo code shown below, each hyphen (dash -) represents one tab. Example 1 is like what's shown above:
```
doctype html
html
- head
- - title
- - link
- body
- - nav
- - - ul
- - - - li
- - - - li
- - - - li
- - h1
- - block content
```
Example 2 is a common pattern in bootstrap files:
```
block content
- container
- - header
- - navbar
- - - nav
- - - - ul
- - - - - li
- - - - - li
- - - - - h3
- - - h1
- - - p
- - - h1
- - - div
- - - footer
- - - - p
```
When looking at the pseudo code above, the point is that you can explicitly count how many tabs appear before each HTML element. You want to achieve that level of specificity when working with Pug.
## Rendering Jade/Pug {#render-basics}
Pug allows us to "pass in" variables (locals) that can be used on the page. This is known as templating.
When Pug is being translated to HTML, the renderer looks at the locals that are passed to it and substitutes these variables for markers on the page.
For instance, in this well-known chunk of code, where the locals have a property called title:
```javascript
router.get('/', routeParamMiddleware, function(req, res, next) {
'use strict';
res.render('index', {
title: 'Week09-SessionBasics'
});
});
```
We can then reference this in our Pug like this:
```text
p Welcome to #{title}
For more details on this process, see the overview here:
```
https://pugjs.org/api/getting-started.html (Links to an external site.)
Even if all this is clear, it still may not be obvious that the locals can take a complex object like user, and that we can reference the fields of that object in our Pug:
```javascript
response.render('account', {
title: 'Google Account',
user: request.user
});
```
And in the Pug:
```text
p DisplayName: #{user.displayName}
```
## Input Controls
Declare a text Input:
```JavaScript
input#dirToWalk(type='text', name='dirToWalk')
```
Put text in it with jQuery:
```javascript
$('#dirToWalk').val('/home/charlie/Documents/AllTest');
```
## Editors
**HINT**: *Here are some ways to turn on visual whitespace in various editors:*
- NotePad++: **View | Show Symbol | Show White Space and Tab**
- Geany: **View | Editor | Show White Space**
Most programming editors have options like these.
## Loading Pug
While reading this section, you might want to also run the accompanying example program, found in the [JadeRoutes][jade-routes] program from JsObjects.
[jade-routes]: https://github.com/charliecalvert/JsObjects/tree/master/JavaScript/NodeCode/JadeRoutes
In the next few paragraphs I describe how Pug templates get loaded in to our web applications. Much of the code I describe is autogenerated for you when you first create the express application. However, some of the code you have to write yourself. Of course, whether the code is autogenerated, or created automatically, you should be sure that you understand all the pieces and what they do.
In our **app.js** file we link in the views directory and tell express to use Pug. Note that their other ways for express to generate or **render** HTML files. But we are asking it to render HTML from Pug templates. We do so with code like this:
```javascript
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
```
Once again, this code is found in **app.js**. It is frequently, perhaps even usually, auto-generated by the **express-generator**. But you should understand what it does.
After processing the above code, express knows to look for Pug files in the **views** directory. It also knows to **render** views using the Pug engine.
Our next chore is to tell express where to send requests sent from the browser. The user typically uses HTTP to compose URLs which are sent back to our express server. Depending on the shape of the URL, the express app can handle the request in any number of ways. The following code in **app.js** tells express where to send requests with a particular type of URL. This is known as routing:
```javascript
// Link in the index.js file from the routes directory
var routes = require('./routes/index');
// Tell the program to send routes of a certain type to **routes/index.js**.
app.use('/', routes.index);
```
The above code tells express the following:
- If the user types in [http://www.example.com][wec]
- route the request to **routes/index.js**.
- If he types in [http://www.example.com/foo][wec] the code is also routed to **routes/index.js**.
In fact, with the code shown above, most requests from the server will end up going to **routes/index.js**. However, we shall see that it is possible to tell the server to route requests of a certain type to another file. For instance, requests to [http://www.example.com/foo][wec] could be sent to **routes/foo.js**. But we need to add more code to make that happen. The code shown above sends requests of this type to the home page. We will need to set up a second route (endpoint) for handling the **foo** route.
## Render Examples {#render-examples}
When the browser sends a request for an HTML page, express can send the request to **routes/index.js**). Routes found in that file detail how our Pug templates should be rendered.
Here is an example **routes/index.js**. Study it with care:
```javascript
var express = require('express');
var router = express.Router();
/* ONE: GET home page. */
router.get('/', function(request, response, next) {
'use strict';
response.render('index', {
author: 'Charlie Calvert',
title: 'Solar Explorer'
});
});
/* TWO: Energy Types Pug files routed here. The Pug is in the energy-types directory. */
router.get('/energy-types/:id', function(request, response) {
'use strict';
response.render('energy-types/' + request.params.id, {
title: 'Energy Types'
});
});
/* THREE: Renewable Pug files routed here. The Pug is in the renewables directory */
router.get('/renewables/:id', function(request, response, next) {
'use strict';
response.render('renewables/' + request.params.id, {
title: 'Renewable Types'
});
});
/* FOUR: Other Pug files routed here. The Pug is in the views directory. */
router.get('/:id', function(request, response, next) {
'use strict';
response.render(request.params.id, {
title: 'Random types'
});
});
module.exports = router;
```
Once again, I ask the you study this example carefully. All the routes in this file translate Pug into HTML and send the result to the server using HTTP. I have labeled each method as ONE, TWO, THREE and FOUR.
- ONE: This is where requests for the home page go. **http://www.example.com**
- TWO: This is where requests for energy-types pages go: [http://www.example.com/energy-types/solar-page][wec]
- THREE: This is where requests for renewable pages go: [http://www.example.com/renewables/hydro-page][wec]
- FOUR: This where requests for uncategorized files go: [http://www.example.com/about-page][wec]
**NOTE**: _We don't explicitly ask for HTML even though it is HTML that will be sent back to the brower. In other words, instead of writing this: [http://example.com/about.html][wec], we write this: [http://example.com/about][wec]. It is a simple matter to teach express to respond properly to either request, but I find it simpler to dismiss with the HTML extension. But this is a matter of taste, and you should feel free to do what seems best to you._
Now let's consider the case where we want requests for anything have to do with renewables to be sent not to **routes/index.js** but to **routes/renewables.js**. We do this in large programs where we don't want to overload **index.js** with too many methods.
Suppose you create a file called **routes/renewables.js**. To set it up, do this in **app.js**:
```javascript
var renewables = require('./routes/renewables');
var routes = require('./routes/index');
// It's usually safest to insert the renewables middleware
// before the middleware found in **routes/index.js**
app.use('/renewables/', renewables);
app.use('/', routes);
```
In **routes/renewables.js**, add, for now, just one route:
```javascript
var express = require('express');
var router = express.Router();
router.get('/:id', function(request, response) {
'use strict';
response.render('renewables/' + request.params.id, {
title: 'ElfComponent'
});
});
module.exports = router;
```
Now consider where our different URLs lead:
- **http://www.example.com** => **routes/index.js**
- [http://www.example.com/energy-types/my-jade-file][wec] => **routes/index.js**
- [http://www.example.com/renewables/my-jade-file][wec] => **routes/renewables.js**
- [http://www.example.com/about][wec] => **routes/index.js**
Notice that the third request routes URLs with [http://example.com/renewables/][wec] in them to the routes found in our **routes/renewables.js** file.
The next logical step would be to create **routes/energy-types.js**. To do so, just follow the template established by the example shown above for **renewables**.
Finally, we can, of course, define other routes in these files that have nothing to do with Pug. For instance, we might define a route in **renewables.js** that loads a JSON file:
```javascript
var express = require('express');
var router = express.Router();
/* ONE */
router.get('/getRenewables', function(request, response) {
'use strict';
fs.readFile('data/renewables.json', 'utf8', function(err, data) {
if (err) {
response.status(404).send(err);
} else {
var jsonAsObject = JSON.parse(data);
response.send({ renewables: jsonAsObject });
}
});
});
/* TWO */
router.get('/:id', function(request, response) {
'use strict';
response.render('renewables/' + request.params.id, {
title: 'ElfComponent'
});
});
module.exports = router;
```
Looking at the above code, it should be obvious that route ONE has nothing to do with Pug. It is about loading JSON. Route TWO, on the other hand, has to be about Pug, since it calls render. As explained above, we have configured our express program to render Pug as HTML and send it back to the browser via HTTP.
Some resources:
- [Home page](http://jade-lang.com/)
- [HTML to Pug](http://html2pug.com/)
- [HTML to Jade](http://html2jade.aaron-powell.com/)
## Use Unique Names {#unique-names}
Don't define the same name for different tasks. If you have a javascript file called **/public/javascript/renewables.js**, consider avoiding creating entities such as:
- **views/renewables.jade**
- **routes/renewables.js**
Also consider avoiding creating routes in **routes/renewables.js** that look like this:
```javascript
router.post('/renewables', function(request, response) { ... })
```
It is not necessarily an error to do this, but it can cause confusion. Consider instead:
- **views/renewables-page.jade**
- **routes/renewables-routes.js**
- **router.post('/getRenewables', function(request, response) { ... })**
This may not be an idea solution, but it can help you sort out your code. If you don't like this kind of solution, then just be careful when loading javascript, Pug and calling routes.
## Pug Indent {#jade-indent}
When thinking about Pug, indentation is crucial. Suppose I write this:
```
div
p
```
That creates two separate, unrelated elements, a div and paragraph.
```
<div></div>
<p></p>
```
Suppose I write this:
```
div
p
```
Now the paragraph is part of the div because it is indented to the right beneath it.
```
<div>
<p></p>
</div>
```
Suppose you create a div and make it your controller:
```
div(ngController="MyController")
p {{firstName}}
```
The above code probably won't work because the paragraph is not part of the controller and hence **{{firstName}}** is out of scope. To fix it, do this:
```
div(ngController="MyController")
p {{firstName}}
```
Now the paragraph is part of the controller.
When trying to see exactly what is going on with the spacing in a Pug file, considering opening it in geany and turning on **View | Editor | Show White Space**. Or open it in NotePad++ and choose **View | Show Symbol | Show White Space and Tab**.
In WebStorm, you can also turn on visible white space, I believe it is: **File | Settings | Editor | General | Appearance | White Space**.
[pug]: https://pugjs.org/api/getting-started.html
[wec]: http://www.example.com
|
Markdown
|
UTF-8
| 1,912 | 2.515625 | 3 |
[] |
no_license
|
# Article R1333-8
Lorsque la demande d'autorisation porte sur un même établissement, ou un même transport dans le même véhicule, ou un flux
d'importations et d'exportations sur une durée de douze mois, l'autorisation définie au présent paragraphe est requise si la
quantité de l'un des éléments détenus ou mis en mouvement atteint ou dépasse les seuils suivants :
1° Plutonium ou uranium 233 : 3 g ;
2° Uranium enrichi à 20 % ou plus en uranium 235 : 15 g d'uranium 235 contenu ;
3° Uranium enrichi à moins de 20 % en uranium 235 : 250 g d'uranium 235 contenu ;
4° Uranium naturel ou appauvri en uranium 235 par rapport à l'uranium naturel : 500 kg ;
5° Thorium, à l'exclusion des alliages contenant moins de 5 % en masse de thorium : 500 kg ;
6° Tritium : 2 g ;
7° Lithium enrichi en lithium 6 : 1 kg de lithium 6 contenu.
Lorsque l'un de ces seuils est atteint, l'autorisation prend en compte l'ensemble des matières détenues dans une installation
ou un établissement, quelles que soient leurs quantités.
**Liens relatifs à cet article**
_Anciens textes_:
- Décret n°81-512 du 12 mai 1981 - art. 8 (Ab)
_Modifié par_:
- Décret n°2009-1120 du 17 septembre 2009 - art. 1
_Cité par_:
- Arrêté du 31 mai 2011 - art. 3 (V)
- Arrêté du 10 juin 2011 - art. 1 (V)
- Arrêté du 9 juin 2011 - art. 1 (V)
- Arrêté du 9 juin 2011 - art. 17 (V)
- Arrêté du 9 juin 2011 - art. 18 (V)
- Arrêté du 5 août 2011 - art. 1 (V)
- Arrêté du 3 août 2011 - art. 1 (V)
- Décret n°2016-1243 du 23 septembre 2016 (V)
- Code de l'environnement - art. R542-64 (V)
- Code de la défense. - art. R*1411-11-22 (V)
- Code de la défense. - art. R*1411-11-33 (V)
- Code de la défense. - art. R1333-14 (V)
- Code de la défense. - art. R1333-17 (V)
- Code de la défense. - art. R1333-77 (V)
- Code de la défense. - art. R1333-9 (V)
|
Markdown
|
UTF-8
| 2,263 | 2.5625 | 3 |
[] |
no_license
|
Formats: [HTML](/news/2009/09/15/gabonese-firefighters-battle-a-blaze-at-the-heart-of-libreville-as-fire-consumes-the-nation-s-largest-market.html) [JSON](/news/2009/09/15/gabonese-firefighters-battle-a-blaze-at-the-heart-of-libreville-as-fire-consumes-the-nation-s-largest-market.json) [XML](/news/2009/09/15/gabonese-firefighters-battle-a-blaze-at-the-heart-of-libreville-as-fire-consumes-the-nation-s-largest-market.xml)
### [2009-09-15](/news/2009/09/15/index.md)
##### Gabon
# Gabonese firefighters battle a blaze at the heart of Libreville as fire consumes the nation's largest market.
### Sources:
1. [IOL](http://www.int.iol.co.za/index.php?set_id=1&click_id=136&art_id=nw20090916082550586C938366)
### Related:
1. [Large explosions and gunfire are reported in the Gabonese capital Libreville as security forces clash with supporters of opposition presidential candidate Jean Ping protesting the election results indicating a narrow victory by President Ali Bongo Ondimba. ](/news/2016/09/1/large-explosions-and-gunfire-are-reported-in-the-gabonese-capital-libreville-as-security-forces-clash-with-supporters-of-opposition-presiden.md) _Context: Gabon, Libreville_
2. [At least 45 people drown and 60 are missing after a boat carrying Nigerian migrants capsizes and sinks off shore from Libreville, Gabon. ](/news/2013/03/21/at-least-45-people-drown-and-60-are-missing-after-a-boat-carrying-nigerian-migrants-capsizes-and-sinks-off-shore-from-libreville-gabon.md) _Context: Gabon, Libreville_
3. [ The state funeral in Libreville of former President of Gabon Omar Bongo is attended by dignitaries from 40 nations. ](/news/2009/06/16/the-state-funeral-in-libreville-of-former-president-of-gabon-omar-bongo-is-attended-by-dignitaries-from-40-nations.md) _Context: Gabon, Libreville_
4. [Ali Bongo is re-elected President of Gabon. ](/news/2016/08/31/ali-bongo-is-re-elected-president-of-gabon.md) _Context: Gabon_
5. [The president of Gabon Ali Bongo calls for calm following clashes between police and anti-government protesters and a subsequent attack on an opposition television station. ](/news/2012/08/17/the-president-of-gabon-ali-bongo-calls-for-calm-following-clashes-between-police-and-anti-government-protesters-and-a-subsequent-attack-on-a.md) _Context: Gabon_
|
Python
|
UTF-8
| 1,173 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
import subprocess
import os
def download_file(url, output_path, debug=True):
if debug:
print('\t[Download Utility] Downloading %s to %s' % (url, output_path))
remote_bytes = get_remote_bytes(url, debug)
if debug:
print('\t[Download Utility] Downloading %d bytes' % remote_bytes)
partial_name = output_path.split('.')[0] + '.partial'
call = subprocess.run(['curl', '-o', partial_name, url])
call.check_returncode()
local_bytes = os.path.getsize(partial_name)
if local_bytes != remote_bytes:
raise Exception('Local bytes does not match remote bytes')
os.rename(partial_name, output_path)
if debug:
print('\t[Download Utility] Download complete: %s' % output_path)
return output_path
def get_remote_bytes(dataset_url, _debug):
call = subprocess.run(['curl', '-I', dataset_url], stdout=subprocess.PIPE)
call.check_returncode()
lines = call.stdout.decode('utf-8').split("\n")
for line in lines:
if not line.startswith('Content-Length:'):
continue
return int(line.split(': ')[-1])
raise Exception('Could not find the number of remote bytes')
|
Shell
|
UTF-8
| 207 | 2.65625 | 3 |
[] |
no_license
|
#!/bin/bash -x
exec 4< inp2.txt # opening file via descriptor
while read LINE <&4; do
printf "%s\n" "$LINE" # just to watch that command is proper
$LINE # execute command
done
|
C++
|
ISO-8859-1
| 6,970 | 3.234375 | 3 |
[] |
no_license
|
#include <Program.h>
#include <asm_mipsyac.h>
extern void programparse(string) ;
extern Program prog ;
Program::Program(){
_head= NULL;
_length=0;
}
//constructeur de copie
Program::Program(Program const& otherprogram){
//On initialise la liste.
_head= NULL;
_length= 0;
// On copie la liste.
Node * tmp = otherprogram._head;
while (tmp != NULL){
add_line(tmp->get_line());
tmp = tmp->get_next();
}
}
//constructeur qui vas permettre de parser un fichier
Program::Program (string const file){
_head = NULL ;
_length = 0 ;
programparse(file) ;
Node * tmp = prog._head;
while (tmp != NULL){
add_line(tmp->get_line());
tmp = tmp->get_next();
}
}
Program::~Program(){
delete _head;
_head=NULL;
_length=0;
}
void Program::add_line(Line * newline){
Node *nod = new Node(newline);
if(!_head){
_head= nod;
_end=nod;
}
else{
nod->set_prev(_end);
_end->set_next(nod);
_end=nod;
}
_length++;
}
void Program::del_line(int index){
Node * to_delete;
Node * prec;
if (index >= 0 && index < _length){
if (index == 0){
if (_length > 0){
// On efface le maillon.
to_delete = _head;
_head = _head->get_next();
_head->set_prev(NULL);
}
}
else { // On se place sur le precedent.
prec = _head;
for (int i = 0; i < index-1; ++i){
prec = prec->get_next();
}
// On retire le maillon.
to_delete = prec->get_next();
prec->set_next( to_delete->get_next() );
}
delete to_delete;
--_length;
}
}
int Program::add_line_at(Line *newline, int position)
{
if (position <= 0){
Node * new_nod = new Node(newline);
if (new_nod == NULL) // Y avait-il assez de mémoire ?
return 0;
new_nod->set_next(_head);// new_nod pointe sur le premier.
_head->set_prev(new_nod);
new_nod->set_prev(NULL);
_head = new_nod; // new_nod est maintenant premier.
++_length;
return 1;
}
else if (position >= _length)
add_line(newline);
else
{
Node * new_nod = new Node(newline);
Node * prec = _head;
if (new_nod == NULL)// Y avait-il assez de memoire?
return 0;
// On se place sur le precedent.
for (int i = 0; i < position - 1; ++i){
prec = prec->get_next();
}
// On ajuste les pointeurs.
new_nod->set_next(prec->get_next());
prec->get_next()->set_prev(new_nod);
prec->set_next(new_nod);
new_nod->set_prev(prec);
++_length;
return 1;
}
return 1;
}
void Program::display()
{
Node* element = _head;
while(element != NULL){
cout << element->get_line()-> get_content() <<endl;
if(element->get_next()==NULL)
break;
else
element = element->get_next();
}
if (is_empty())
cout<<"The program is empty"<<endl;
cout << endl;
}
void Program::flush(){
while(!is_empty()){
del_line(0);
}
}
void Program::exchange_line(int line1, int line2){
Line * lg1,*lg2;
lg1=find_line(line1);
lg2=find_line(line2);
del_line(line1);
add_line_at(lg2,line1);
del_line(line2);
add_line_at(lg1,line2);
}
Line* Program::find_line(int index){
int j;
Node *e = _head;
for (j=0; j< _length ;j++) {
if(j==index) {
return e->get_line();
}
e = e->get_next();
}
return NULL;
}
int Program::size(){
return _length;
}
bool Program::is_empty(){
if(!_head)
return true;
return false;
}
void Program::in_file(string const filename){
Node* element = _head;
ofstream monflux(filename.c_str());
if(monflux){
while(element != NULL)
{
if(element->get_line()->type_line()==line_Instru ||
element->get_line()->type_line()== line_Direct)
monflux<<"\t";
monflux << element->get_line()-> get_content();
if(element->get_next()==NULL)
break;
else {
if(element->get_line()->get_content().compare("nop"))
monflux<<endl;
element = element->get_next();
}
}
}
else {
cout<<"Error cannot open the file"<<endl;
}
monflux.close();
}
/* Il faut ici dlimite les fonctions du fichier assembleur en dtectant les directives .ent et .end qui indique le dbut et la function d'une fonction
Il faut donc parcourir toutes les lignes d'un programme et construire avec chaque couple de ligne comportant les directives .ent FCT et .end FCT une nouvelle fonction et l'ajouter la liste des fonctions du programme
*/
/* NB : la mthode get_content() permet de rcuprer une chaine de caractre correspondant au contenu d'une ligne/directive/label/instruction. Par exemple :
string ma_chaine = ma_ligne->get_content();
On peut comparer ensuite si la chaine commencer par quelquechose avec :
if( ma_chaine.compare(0, 6, "coucou")==0){
//la chaine commence par "coucou"
....
}
*/
void Program::comput_function(){
Function *func;
Node *element_debut=NULL;
Node* current = _head;
Line *l=NULL;
Directive *d=NULL;
string direct;
// A REMPLIR
while(current != NULL) {
l = current->get_line();
if(l->type_line() == line_Direct) {
direct = l->get_content();
if(direct.compare(0, 4, ".ent") == 0) {
func = new Function();
func->set_head(current);
} else if (direct.compare(0, 4, ".end") == 0) {
func->set_end(current);
_myfunc.push_back(func);
}
}
current = current->get_next();
}
if (is_empty())
cout<<"The program is empty"<<endl;
}
int Program::nbr_func(){
return _myfunc.size();
}
Function* Program::get_function(int index){
list<Function*>::iterator it;
it=_myfunc.begin();
int size=(int)_myfunc.size();
if (index < size){
for (int i = 0; i<index; i++)
it++;
return *it;
}
return NULL;
}
list<Function*>::iterator Program::function_list_begin(){
return _myfunc.begin();
}
list<Function*>::iterator Program::function_list_end(){
return _myfunc.end();
}
/* Pour chaque fonction du programme, donc de la liste _myfunc, il faut crer un CFG et l'ajouter la liste _myCFG ;
La cration d'un CFG se fait avec un appel au constructeur, par exemple :
Cfg * cfg = new Cfg(bb0, n);
cre un CFG dont le BB d'entre est bb0 et contenant n BBs.
Il faut avoir calcul les blocs de base des fonctions et les succ/pred des BB sinon le CFG n'aura qu'un bloc, le premier (meme si on dit qu'il en a n en paramtre)
*/
void Program::comput_CFG(){
list<Function*>::iterator it;
Function *current;
it=_myfunc.begin();
int size=(int)_myfunc.size();
for(int i=0; i<size; i++){ // parcours des functions du programme
current=*it;
// A REMPLIR
Cfg *cfg = new Cfg(current->get_firstBB(), current->nbr_BB());
_myCFG.push_back(cfg);
it++;
}
return;
}
Cfg* Program::get_CFG(int index)
{
list<Cfg*>::iterator it;
it=_myCFG.begin();
if (index< (int)_myCFG.size()){
for (int i = 0; i<index;i++)
it++;
return *it;
}
return NULL;
}
|
JavaScript
|
UTF-8
| 1,132 | 3.28125 | 3 |
[] |
no_license
|
// output format for the chart:
/*{
"date":" 2010-01-03T23:00:00.000Z",
"open": 25.436282332605284,
"high": 25.835021381744056,
"low": 25.411360259406774,
"close": 25.710416,
"volume": 38409100,
"split":"",
"dividend":""
}
*/
export function readFormat(heading) {
if (heading == "Date,Open,Close,High,Low,Volume") {
// convert into candles, move to its own file
return 'CSV_DOCHLV';
}
throw new Error("Format not supported: "+heading);
}
export function readBlock(format, block) {
return formats[format](block);
}
const formats = {
CSV_DOCHLV: (block) => {
return block.map((line) => {
const [date, open, close, high, low, volume] = line.split(',');
const candle = {
"date": new Date(date),
"open": parseFloat(open),
"high": parseFloat(high),
"low": parseFloat(low),
"close": parseFloat(close),
"volume": parseFloat(volume),
"split": "",
"dividend": ""
};
//console.log([date, open, close, high, low, volume]);
//console.log(JSON.stringify(candle));
return candle;
});
}
}
|
Ruby
|
UTF-8
| 540 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
require 'spec_helper'
describe Immutable::SortedSet do
describe '#delete_at' do
let(:sorted_set) { SS[1,2,3,4,5] }
it 'removes the element at the specified index' do
sorted_set.delete_at(0).should eql(SS[2,3,4,5])
sorted_set.delete_at(2).should eql(SS[1,2,4,5])
sorted_set.delete_at(-1).should eql(SS[1,2,3,4])
end
it 'makes no modification if the index is out of range' do
sorted_set.delete_at(5).should eql(sorted_set)
sorted_set.delete_at(-6).should eql(sorted_set)
end
end
end
|
Python
|
UTF-8
| 106 | 3.28125 | 3 |
[] |
no_license
|
fruits = ['apple', 'banana', 'orange', 'mango']
my_favourite_fruit = fruits[1]
print(my_favourite_fruit)
|
C++
|
UTF-8
| 3,425 | 2.921875 | 3 |
[] |
no_license
|
// ---------------------------------------------------------------------------
// - Unitabler.hpp -
// - standard object library - unicode table class definition -
// ---------------------------------------------------------------------------
// - This program is free software; you can redistribute it and/or modify -
// - it provided that this copyright notice is kept intact. -
// - -
// - This program 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. In no event shall -
// - the copyright holder be liable for any direct, indirect, incidental or -
// - special damages arising in any way out of the use of this software. -
// ---------------------------------------------------------------------------
// - copyright (c) 1999-2021 amaury darsch -
// ---------------------------------------------------------------------------
#ifndef AFNIX_UNITABLER_HPP
#define AFNIX_UNITABLER_HPP
#ifndef AFNIX_STRING_HPP
#include "String.hpp"
#endif
namespace afnix {
/// The Unitabler class is a container class which can be used to map
/// a unicode character with an object. The table is similar to the quark
/// table and provides the same functionnality. A nil object can be
/// associated with a character making the table operating as a set when
/// using the exists method only.
/// @author amaury darsch
class Unitabler : public virtual Object {
private:
/// the table size
long d_size;
/// the number of elements
long d_count;
/// threshold before resizing
long d_thrs;
/// table of buckets
struct s_utnode** p_table;
public:
/// create a unicode table with a default size
Unitabler (void);
/// create a unicode table with an initial size
Unitabler (const long size);
/// destroy the unicode table.
~Unitabler (void);
/// return the class name
String repr (void) const;
/// reset the unicode table
void reset (void);
/// @return the number of elements
long length (void) const;
/// @return the element key by index
t_quad getkey (const long index) const;
/// @return the element object by index
Object* getobj (const long index) const;
/// set or create a new entry in the table by key and object
/// @param key the unicode key to use
/// @param object the object to map
void add (const t_quad key, Object* object);
/// get an object by key
/// @param key the unicode key to search
Object* get (const t_quad key) const;
/// get an object by key or raise an exception
/// @param key the unicode key to find
Object* lookup (const t_quad key) const;
/// remove an object by key
/// @param key the object key to remove
void remove (const t_quad key);
/// @return true if the key exists
bool exists (const t_quad key) const;
private:
// make the copy constructor private
Unitabler (const Unitabler&);
// make the assignment operator private
Unitabler& operator = (const Unitabler&);
// resize this hash table
void resize (const long size);
};
}
#endif
|
JavaScript
|
UTF-8
| 651 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
/*jslint browser: true */
define( function() {
'use strict';
return {
/**
* @param {string} name
* @param {function()} require
* @param {function()} onload
* @param {Object} config
*/
load: function( name, require, onload, config ) {
var xhr = new XMLHttpRequest();
if (config.paths[name]) name = config.paths[name];
xhr.open( 'GET', name, true );
xhr.responseType = 'arraybuffer';
xhr.onload = function( evt ) {
onload( this.response );
};
xhr.send();
}
};
} );
|
Shell
|
UTF-8
| 901 | 3.859375 | 4 |
[] |
no_license
|
#!/bin/bash
kill_all() {
for pid in `printf "$PSDATA" | awk '{print $2}'`
do
echo "kill $1 Pid $pid"
kill $1 $pid
done
PSDATA=`ps aux | grep "$PROG" | grep -v grep | grep -v kill`
if [ ! -z "$PSDATA" ]; then
echo '-------------------Fail----------------------'
printf "$PSDATA" | grep --color=auto "$PROG"
fi
}
PROG=$1
if [ -z "$1" ]; then echo "Usage: `basename $0` [Program_Name]"; exit; fi
PSDATA=`ps aux | grep "$1" | grep -v grep | grep -v kill`
if [ ! -z "$PSDATA" ]; then
echo `ps aux|head -n1`
printf "$PSDATA" | grep --color=auto "$1"
fi
echo '------------------------------------------'
if [ -z "$PSDATA" ]; then
echo 'No progress found.'
exit
fi
read -p "Do you want to kill all processes (y/n)? " yn
case $yn in
[Yy]* ) kill_all $2; exit;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
|
Markdown
|
UTF-8
| 720 | 2.6875 | 3 |
[] |
no_license
|
## What is it all about?
This repository contains my slides and sample codes that I used for my talk in DDD Melbourne 2017.
## Files in the repository
* ML.key
- Slides in Keynote format (Original format)
* ML.pptx
- Slides in PowerPoint format (Converted from Keynote)
* simple.js
- A simple implementation of a neuron in JavaScript (inspired by [iamtrask](https://iamtrask.github.io/2015/07/12/basic-python-network/)
* 3layer.js
- Add a hidden layer to simple.js
* simple.py
- A simple neural network implemented using TensorFlow
* summary.py
- Same as simple.py with support for summaries for TensorBoard
## License
Just keep my name and a link to this repository and do whatever you want with this!
|
Java
|
UTF-8
| 668 | 1.992188 | 2 |
[] |
no_license
|
package com.baidu.fbu.frontsystem.server;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* 版权信息
* 文件名
* 描述 前置信息上下文类
* 创建人 panhongshuang
* 创建时间 2017-07-07
* 修改日志
*/
public class FrontSystemContext {
private static final String CONTEXT_FILE_PATH = "classpath:FrontSystemContext.xml";
public static ApplicationContext applicationContext;
public static void initialize() {
// 加载Spring上下文
applicationContext = new ClassPathXmlApplicationContext(CONTEXT_FILE_PATH);
}
}
|
C
|
UTF-8
| 938 | 2.890625 | 3 |
[] |
no_license
|
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int language = 0;
int greetuser(char *str){
char buf[72];
if (language == 1)
strncpy(buf, "HyvÃÃ pÃivÃÃ", 19); // 19 because of unicode : check x/s 0x8048717
if (language == 2)
strncpy(buf, "Goedemiddag! ", 14);
else
strncpy(buf, "Hello ", 7);
strcat(buf, str);
puts(buf);
return 0;
}
int main (int argc, char **argv) {
char buf[72]; // at $esp + 0x50 => Line<+31>
char *l;
if (argc == 3){
bzero(buf, 72); // Line<+35> to <+49>. 0x13 = 19 => ecx is decremented for each 4 bytes copied! 19 * 4 = 76, but the last one is 0 and get out
strncpy(buf, argv[1], 40); // 0x28 = 40 -- Line<+78>
strncpy(buf + 40, argv[2], 32); // 0x20 = 32 -- Line <+113>
l = getenv("LANG");
if (l) {
if (memcmp(l, "fi", 0x2) == 0)
language = 0x1;
else if (memcmp(l, "nl", 0x2) == 0)
language = 0x2;
}
return (greetuser(buf));
}
return 1;
}
|
JavaScript
|
UTF-8
| 124 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
var c = 0
while (c < 5) {
console.log(c)
c++
}
console.log('')
for (var c = 0; c < 5; c++) {
console.log(c)
}
|
TypeScript
|
UTF-8
| 2,592 | 2.84375 | 3 |
[] |
no_license
|
import { IProgress, IProgressProps } from "./types";
import { ClassNames } from "../classNames";
import { Base } from "../base";
import { HTML } from "./templates";
/**
* Progress Bar Types
*/
export enum ProgressBarTypes {
Danger = 1,
Dark = 2,
Info = 3,
Light = 4,
Primary = 5,
Secondary = 6,
Success = 7,
Transparent = 8,
Warning = 9,
White = 10
}
/**
* Progress Bar Class Names
*/
export const ProgressBarClassNames = new ClassNames([
"bg-danger",
"bg-dark",
"bg-info",
"bg-light",
"bg-primary",
"bg-secondary",
"bg-success",
"bg-transparent",
"bg-warning",
"bg-white"
]);
/**
* Progress
*/
class _Progress extends Base<IProgressProps> implements IProgress {
// Constructor
constructor(props: IProgressProps, template: string = HTML) {
super(template, props);
// Configure the collapse
this.configure();
// Configure the parent
this.configureParent();
}
// Configure the card group
private configure() {
// Set the default values
let maxValue = typeof (this.props.max) === "number" ? this.props.max : 100;
let minValue = typeof (this.props.min) === "number" ? this.props.min : 0;
let size = typeof (this.props.size) === "number" ? this.props.size : 0;
// Update the progress bar
let progressBar = this.el.querySelector(".progress-bar") as HTMLDivElement;
if (progressBar) {
progressBar.style.width = size + "%";
progressBar.setAttribute("aria-valuenow", size.toString());
progressBar.setAttribute("aria-valuemin", minValue.toString());
progressBar.setAttribute("aria-valuemax", maxValue.toString());
this.props.isAnimated ? progressBar.classList.add("progress-bar-animated") : null;
this.props.isStriped ? progressBar.classList.add("progress-bar-striped") : null;
this.props.label ? progressBar.innerHTML = this.props.label : null;
// See if a type exists
let className = ProgressBarClassNames.getByType(this.props.type);
if (className) {
// Add the class name
progressBar.classList.add(className);
}
}
}
/**
* Public Interface
*/
// Return the progress bar element
get progressBar() { return this.el.querySelector(".progress-bar") as HTMLDivElement; }
}
export const Progress = (props: IProgressProps, template?: string): IProgress => { return new _Progress(props, template); }
|
SQL
|
UTF-8
| 3,112 | 4 | 4 |
[
"Apache-2.0",
"BSD-2-Clause"
] |
permissive
|
DROP TABLE IF EXISTS AcadProgram;
CREATE TABLE AcadProgram (
programID INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
title VARCHAR ( 30 ) NOT NULL,
type ENUM('Coursework', 'B.A.', 'B.S.', 'M.Sc.', 'Ph.D.', 'Major', 'Minor')
NOT NULL DEFAULT 'Coursework',
school VARCHAR ( 30 ) NOT NULL,
division VARCHAR ( 30 ),
department VARCHAR ( 30 ),
startDate DATE NOT NULL,
endDate DATE,
updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP
);
INSERT INTO AcadProgram (programID, title, type,
school, department, startDate, endDate)
VALUES
(1, "Bachelor of Arts", "B.A.", "K", DEFAULT, "1833-09-01", NULL)
, (10, "Computer Science", "Major", "K", "Math/CS", "1979-09-01", NULL)
, (11, "Computer Science", "Minor", "K", "Math/CS", "1979-09-01", NULL)
, (20, "Literature", "Major", "K", "Literature/Writing", "1950-09-01", NULL)
, (21, "Literature", "Minor", "K", "Literature/Writing", "1970-09-01", NULL)
, (22, "Creative Writing", "Major", "K", "Literature/Writing", "1950-09-01", NULL)
, (23, "Creative Writing", "Minor", "K", "Literature/Writing", "1970-09-01", NULL)
, (05, "Rhetoric", "Major", "K", "Literature/Writing", "1870-09-01", "1950-09-01")
, (06, "Mathematics", "Major", "K", "Mathematics", "1870-09-01", "1979-09-01")
, (07, "Mathematics", "Minor", "K", "Mathematics", "1970-09-01", "1979-09-01")
, (30, "Mathematics", "Major", "K", "Math/CS", "1979-09-01", NULL)
, (31, "Mathematics", "Minor", "K", "Math/CS", "1979-09-01", NULL)
;
DROP TABLE IF EXISTS Requirements;
CREATE TABLE Requirements (
requirementID INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
requirementName VARCHAR ( 30 ) NOT NULL,
parentRequirementID INT NULL,
startDate DATE NOT NULL,
endDate DATE,
updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (parentRequirementID) REFERENCES Requirements (requirementID)
ON UPDATE CASCADE ON DELETE RESTRICT,
);
DROP TABLE IF EXISTS ProgramRequirements;
CREATE TABLE ProgramRequirements (
programID INT NOT NULL,
requirementID INT NOT NULL,
startDate DATE NOT NULL,
endDate DATE,
updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (programID, requirementID, startDate)
FOREIGN KEY (programID) REFERENCES Program (programID),
FOREIGN KEY (requirementID) REFERENCES Requirements (requirementID)
);
# /*
# Start date is part of primary key in case of a rare situation
# where a program is associated with requirement set 1 for a while,
# then with requirement set 2, then back with requirement set 1.
# Program requirements should only change at clean boundaries,
# e.g., the start of an academic year.
# A program should only have one active requirement set at any one
# time. There might be different students complete different
# requirements, based on the requirement set that was active when
# they started the program, but there should be no ambiguity about
# the requirements associated with a particular program at a particular
# date.
# */
|
Java
|
UTF-8
| 2,314 | 3.140625 | 3 |
[] |
no_license
|
package bqb;
import java.util.ArrayList;
public class QuoteSearcher {
public static ArrayList searchThroughQuote(String chatMessage) {
String searchTerm = chatMessage.substring(14); //cuts out !searchquotes
// System.out.println(searchTerm); (debug)
boolean didIfStatement = true;
int ifCounter = 0;
int quotePartition = 0;
ArrayList<Integer> quoteNumbers = new ArrayList<>(); //Init variables for later
int fileLength = 0;
try {
fileLength = FileHandler.getFileLength("quotes"); //Tries to get number of lines from quotes.txt
}
catch(Exception e) {
System.err.println("Not able to find file length: " + e);
}
//goes through every line (quote)
for(int i= 0; i<fileLength - 1; i++) {
String quoteLine = "";
try {
quoteLine = FileHandler.readFromFile("quotes", i); //Tries to get quote from file
}
catch(Exception e) {
System.err.println("Not able to read quotes from file: " + e);
}
// Goes through every character in quote
for(int j = 0; j<quoteLine.length(); j++) {
String letter = String.valueOf(quoteLine.charAt(j)); //Gets character (not char because it broke the thing for some reason
//Goes through and checks for the second pair of double quotes
if(letter == "\"" && didIfStatement) {
quotePartition = j;
if(ifCounter < 1) {
ifCounter = 1;
} else {
didIfStatement = false;
}
}
}
// System.out.println(quotePartition); (debug)
String quote = quoteLine.substring(quotePartition); // separates quote from date
// System.out.println(quote); (debug)
if(quote.contains(searchTerm)) {
quoteNumbers.add(i); //Searches the quote for the searchterm and adds the quote # to array list if true
}
}
return quoteNumbers;
}
}
|
C++
|
UTF-8
| 227 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
// Welcome to the Interactive C++ Tutorial.
// Start by choosing a chapter and
// write your code in this window.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
|
Python
|
UTF-8
| 1,146 | 4.34375 | 4 |
[] |
no_license
|
food = ['치즈', '바나나', '사과', '커피']
print(food[0])
print(food[1])
# 리스트 원소 위치를 인덱스로 가리킬 수 있으며
# 인덱스는 0부터 시작
val = [10, 20, 30, 40]
print(val)
print(val[0])
val[0] = 50
val[1] = -30
print(val)
# 원소의 순서를 바꾸거나, 다른 원소로 바꿀수 있다.
# 문자열은 X
f = 'hello'
print(f)
print(f[1])
""" f[1]='o'
print(f) """
# TypeError TypeError: 'str' object does not support item assignment
# ==> '스트링형' 객체는 원소들에 대한 대입을 지원하지 않습니다.
val = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = 2
print(val[x])
# 수식 등으로 표현된 정수 표현식도 인덱스로 사용할 수 있다.
""" y = 11
print(val[y]) """
# 존재하지 않는 원소를 읽거나 쓰려고 하면 indexError가 발생
arr = [1, 2, 3, 4, 5]
print(arr[-1])
print(arr[-2])
print(arr[-3])
# 인덱스의 값이 음수면 리스트 끝부터 역방향으로 계산
brr = [11, 12, 13, 14]
print(brr)
x = 12
y = x in brr
print(y)
print(80 in brr)
# in 연산자를 사용해, 특정 원소가 리스트의 한 원소인지를 알아낼 수 있다
|
Java
|
UTF-8
| 292 | 1.867188 | 2 |
[] |
no_license
|
package com.appl_maint_mngt.repositories.maintenance_schedule;
import com.appl_maint_mngt.models.maintenance_schedule.MaintenanceSchedule;
/**
* Created by Kyle on 23/03/2017.
*/
public interface IMaintenanceScheduleUpdateableRepository {
void addItem(MaintenanceSchedule sched);
}
|
JavaScript
|
UTF-8
| 1,891 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
"use strict";
var aws = require("./util.js");
var uuid = require('uuid');
const tableName = "transactions";
exports.ClearTransactions = async function () {
var allItems = await aws.ScanItems({
TableName: tableName
})
var ps = [];
var i = 0
const l = allItems.Items.length
do {
const delItems = allItems.Items.slice(i * 25, ++i * 25)
const batchDel = delItems.map((item) => {
return {
DeleteRequest: {
Key: {
id: item.id,
product:item.product
}
}
}
})
if (batchDel.length <= 0){
break
}
ps.push(new Promise(async function (resolve, reject) {
try {
var params = {
RequestItems : {
}
}
params.RequestItems[tableName] = batchDel
await aws.BatchWrite(params)
resolve();
} catch (err) {
console.log(err)
reject()
}
}));
} while (i * 25 < l)
return await Promise.all(ps)
}
exports.PutTransaction = async function (buyer,product) {
return await aws.PutItem({
TableName: tableName,
Item: {
id: uuid.v1(),
buyer: buyer,
product: product
}
});
}
exports.GetTransactionsByProductID = async function (productID) {
var res = await aws.QueryItems({
TableName: tableName,
KeyConditionExpression: "#product = :getID",
ExpressionAttributeNames: {
"#product": "product"
},
ExpressionAttributeValues: {
":getID": productID
}
});
return res.Items
}
this.PutTransaction("da","do")
|
Java
|
UTF-8
| 107 | 1.679688 | 2 |
[] |
no_license
|
package com.syntax.class20_1;
public class A {
public void showA() {
System.out.println("Class A");
}
}
|
C
|
UTF-8
| 1,332 | 2.75 | 3 |
[] |
no_license
|
#ifndef _DHAT_H
#define _DHAT_H
#include <wchar.h>
enum key_type {
WCHAR,
CHAR,
VOID,
};
struct entry {
enum key_type keytype;
size_t keysize;
wchar_t *key;
const void *value;
struct entry *next;
};
typedef struct dhat {
unsigned int size;
int maxdepth;
int factor;
struct entry **entry;
size_t (*gethash_external)(const void *s, size_t size, size_t mod);
} dhat;
dhat *dhat_new(unsigned int size, int depth, int factor);
void dhat_hashfunc(dhat *ht, size_t (*gethash)(const void *s, size_t size, size_t mod));
#define dhat_put (ht, key, val) dhat_nput(ht, key, (strlen(key)+1) * sizeof (char), val)
#define dhat_wput(ht, key, val) dhat_nput(ht, key, (wcslen(key)+1) * sizeof (wchar_t), val)
dhat *dhat_nput(dhat *ht, const void *key, size_t size, const void *value);
#define dhat_get (ht, key, val) dhat_nget(ht, key, (strlen(key)+1) * sizeof (char), val)
#define dhat_wget(ht, key, val) dhat_nget(ht, key, (wcslen(key)+1) * sizeof (wchar_t), val)
int dhat_nget(dhat *ht, const void *key, size_t size, void **value);
#define dhat_remove (ht, key) dhat_nremove(ht, key, (strlen(key)+1) * sizeof (char))
#define dhat_wremove(ht, key) dhat_nremove(ht, key, (wcslen(key)+1) * sizeof (wchar_t))
void dhat_nremove(dhat *ht, const void *key, size_t size);
void dhat_destroy(dhat *ht);
#endif //_DHAT_N
|
Python
|
UTF-8
| 2,371 | 2.640625 | 3 |
[] |
no_license
|
#!/usr/bin/python
from optparse import OptionParser
import os
def match():
f = open("results/mapping.txt","rb")
mapping = {}
for line in f.readlines():
k,v = line.split(",")
mapping[k.strip()] = v.strip()
return mapping
def gen_csv(fname, mapping):
name = fname[:-4]
ID = mapping[name]
day = fname[-4:]
session = open("data/gabor/"+fname+"/session.log", "rb")
csv = open("results/gabor/"+ID+day+".csv", "wb")
# the format for the file
header = "ID, day,TrialNum,Response,RT,T,TOr,TPos,D1,D1Or,D1Pos,D2,D2Or,D2Pos,NumDist,Presence\n"
positions = {"square":4, "red":5, "size":6}
def drill(cols, position, out):
item, other = cols[position].split("=")
orient,pos = other.split("|")
out.append(item)
out.append(orient)
out.append(pos)
csv.write(header)
for line in session.readlines():
dists = [4,5,6]
main = line.split('\t')[2]
if ',' in main:
cols = main.split(",")
out = [ID,day]
out.extend(cols[:3])
target = positions[cols[3]]
dists.remove(target)
if cols[target]:
drill(cols, target, out)
else:
out.extend["","",""])
if cols[dists[0]]:
drill(cols, dists[0], out)
if cols[dists[1]]:
drill(cols, dists[1], out)
out.extend(["","",""]* (2-int(cols[7])) )
out.extend(cols[7:])
print out
csv.write(",".join(out))
session.close()
csv.close()
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("-f", "--file", dest="file",
help="filename for the stat generation", metavar="FILE")
parser.add_option("-a", "--all", action="store_true", dest="all", default=False,
help="generate csv for all the logs in data" )
(options, args) = parser.parse_args()
mapping = match()
if not (options.file or options.all):
print "Usage is getStats.py <-f|--file file> <-a|-all>"
if options.file:
gen_csv(options.file, mapping)
if options.all:
names = os.popen("ls data/gabor")
for name in names.readlines():
gen_csv(name.strip(),mapping)
print "done "+name.strip()
|
Python
|
UTF-8
| 611 | 4.3125 | 4 |
[] |
no_license
|
print("1st list")
lst=[2,566,4,7,73,44,23]
new_lst=[]
for i in range(2,5):
new_lst.append(lst[i])
print(new_lst)
print(lst[2:5])
print("2nd list")
lst1=[2,3,4,5]
lst2=lst1
print(lst1)
lst2.append(20)
print(lst1) #here lst will be same as lst 2 although we didn't append 20 with lst.the reason is in this case reference(address) is copying
print(lst2)
print("3rd list")
#to reverse slicing
lst3=[2,3,4,5]
lst4=lst3[3::-1]
print(lst3)
lst4.append(20)
print(lst3) #here lst will be same as lst 2 although we didn't append 20 with lst.the reason is in this case reference(address) is copying
print(lst4)
|
Rust
|
UTF-8
| 913 | 2.53125 | 3 |
[
"LicenseRef-scancode-unknown",
"MIT"
] |
permissive
|
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct NodePartitionsNode {
/// Count of how many partitions are included.
#[serde(rename = "count")]
pub count: Option<i32>,
/// Error message, if the HTTP status returned from this node was not 200.
#[serde(rename = "error")]
pub error: Option<String>,
/// Node ID of the node reporting this information.
#[serde(rename = "id")]
pub id: Option<i32>,
/// Logical node number of the node reporting this information.
#[serde(rename = "lnn")]
pub lnn: Option<i32>,
/// Partition information.
#[serde(rename = "partitions")]
pub partitions: Option<Vec <crate::models::NodePartitionsNodePartition>>,
/// Status of the HTTP response from this node if not 200. If 200, this field does not appear.
#[serde(rename = "status")]
pub status: Option<i32>,
}
|
JavaScript
|
UTF-8
| 2,783 | 2.828125 | 3 |
[] |
no_license
|
$(document).ready(function(){
// KHAI BAO
const LENGTH = $('.images-item').length ;
const listSlide = Array.from($('.list-images ul .images-item'));
let count = 0 ;
// lặp lại các nút
for(let i = 2 ; i < LENGTH + 1; i++){
$('.list-icon .dot').append(`
<a href="#">${i}</a>
`);
}
const list_number = $('.list-icon .dot a');
// FUNCTION
function reset(){
$('.list-icon .dot a').removeClass('active');
}
function nextImages(){
let temp = 0 ;
$(".list-images ul li").animate({
right : "+=800px",
},
{
complete: function(){
temp++;
if(temp === LENGTH){
let right = parseFloat(listSlide[count].style.right.slice(0,listSlide[count].style.right.length - 2))
right+=-(LENGTH)*800;
listSlide[count].style.right = `${right}px`
if(count === LENGTH - 1) count=0
else count = count + 1 ;
reset();
$(list_number[count]).addClass('active');
}
}
})
}
function setCss(element){
element.css({
'display' : 'list-item',
'float' : 'left',
})
}
function removeCss(){
}
// function nextImages(){
// if(count == LENGTH - 1){
// $(".list-images ul").animate({
// right : "0",
// })
// count = -1 ;
// }else {
// $(".list-images ul").animate({
// right : "+=800px",
// })
// }
// count = count + 1 ;
// reset();
// $(list_number[count]).addClass('active');
// }
function prevImages(){
if(count == 0){
$(".list-images ul").animate({
right : `${(LENGTH - 1) * 800}px`,
})
count = LENGTH - 1;
}else {
$(".list-images ul").animate({
right : `-=800px`,
})
count = count - 1 ;
}
reset();
$(list_number[count]).addClass('active');
}
// EVENT
$('.next').click(nextImages);
$('.prev').click(prevImages);
$('.list-icon .dot a').click(function(e){
e.preventDefault();
count = $(this).text() - 1;
let right = count * 800 ;
$(".list-images ul").animate({
right : `+${right}px`,
})
reset();
$(list_number[count]).addClass('active');
})
// SET TIME AUTO
// setInterval(nextImages,3000);
})
|
Python
|
UTF-8
| 280 | 2.890625 | 3 |
[] |
no_license
|
S = input()
scales = {
"WBWBWWBWBWBWWBWBWWBW": "Do",
"WBWWBWBWBWWBWBWWBWBW": "Re",
"WWBWBWBWWBWBWWBWBWBW": "Mi",
"WBWBWBWWBWBWWBWBWBWW": "Fa",
"WBWBWWBWBWWBWBWBWWBW": "So",
"WBWWBWBWWBWBWBWWBWBW": "La",
"WWBWBWWBWBWBWWBWBWWB": "Si",
}
print(scales[S])
|
Python
|
UTF-8
| 2,842 | 3.015625 | 3 |
[] |
no_license
|
"""todo model module contains the logic for handling,
manipulating, storing, etc. todo objects"""
import uuid
from dragon.common.types import JsonSerializable
from dragon.common import exceptions
from dragon.common import constants
from dragon.aws.services import dynamo
class Todo(JsonSerializable):
schema = dict(
TableName='dragon-todos',
KeySchema=[
{
'AttributeName': 'todo_id',
'KeyType': 'HASH'
}
],
AttributeDefinitions=[
{
'AttributeName': 'todo_id',
'AttributeType': 'S'
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
})
def __init__(self, data):
store = dict(
todo_id=data.get('todo_id', uuid.uuid4().hex),
is_starred=data.get('is_starred'),
title=data.get('title'),
deadline=data.get('deadline'),
attachment=data.get('attachment'))
super().__init__(store)
@classmethod
def validate_file_type(cls, filename):
is_valid = '.' in filename and filename.rsplit('.', 1)[1].lower() in constants.FILE_TYPE_WHITELIST
if not is_valid:
raise exceptions.invalid_file_type.add(filename)
@classmethod
def table(cls):
return Todo.schema['TableName']
def save(self):
data = {}
for key, val in self.store.items():
if val is not None and val != '':
data[key] = val
dynamo.add(table_name=Todo.table(), attributes=data)
def patch(self, patch_obj):
patch_else_store = lambda prop: patch_obj[prop] if prop in patch_obj else self.store[prop]
result = dynamo.update(
table_name=Todo.table(),
key={
'todo_id': self.store['todo_id']
},
attributes={
'title': patch_else_store('title'),
'is_starred': patch_else_store('is_starred'),
'deadline': patch_else_store('deadline'),
'attachment': patch_else_store('attachment')
})
return Todo(result)
def delete(self):
result = dynamo.delete(
table_name=Todo.table(),
key={
'todo_id': self.store['todo_id']
})
return result
@classmethod
def find(cls, todo_id):
result = dynamo.find(table_name=Todo.table(), key={
'todo_id': todo_id
})
if result is None:
raise exceptions.entity_not_found.add(f'todo_id: {todo_id}')
return Todo(result)
@classmethod
def get_all(cls):
result = dynamo.scan(table_name=Todo.table())
return [Todo(item) for item in result]
|
Python
|
UTF-8
| 1,157 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
from problem_solving.algorithms.debugging import *
def test_q1_prime_date(capsys, monkeypatch):
inputs = ["02-08-2025 04-09-2025"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q1_prime_date.main()
captured = capsys.readouterr()
output = "5\n"
assert captured.out == output
def test_q3_strings_xor(capsys, monkeypatch):
inputs = ["10101", "00101"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q3_strings_xor.main()
captured = capsys.readouterr()
output = "10000\n"
assert captured.out == output
def test_q4_zig_zag_sequence(capsys, monkeypatch):
inputs = ["1", "7", "1 2 3 4 5 6 7"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q4_zig_zag_sequence.main()
captured = capsys.readouterr()
output = "1 2 3 7 6 5 4\n"
assert captured.out == output
def test_q5_smart_number(capsys, monkeypatch):
inputs = ["4", "1", "2", "7", "169"]
monkeypatch.setattr('builtins.input', lambda: inputs.pop(0))
q5_smart_number.main()
captured = capsys.readouterr()
output = "YES\nNO\nNO\nYES\n"
assert captured.out == output
|
C#
|
UTF-8
| 10,556 | 2.9375 | 3 |
[] |
no_license
|
using ServiceStack.Redis;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace RedisConsoleDemoOne
{
class Program
{
static void Main(string[] args)
{
//在Redis中存储常用的5种数据类型:String,Hash,List,SetSorted set
// RedisClient client = new RedisClient("127.0.0.1", 6379);
//client.FlushAll();
#region 正则表达式
//定义正则表达式规则
//StringBuilder strValue = new StringBuilder();
//Regex reg = new Regex(@"([^\[^\]])*");
////返回一个结果集
//MatchCollection result = reg.Matches("[[[bug管理]]]");
////遍历每个结果
//foreach (Match m in result)
//{
// //输出结果
// strValue.AppendFormat(m.ToString());
//}
//Console.WriteLine(strValue.ToString());
//Console.ReadKey();
#endregion
#region string
//client.Add<string>("StringValueTime", "我已设置过期时间噢30秒后会消失", DateTime.Now.AddMilliseconds(30000));
//while (true)
//{
// if (client.ContainsKey("StringValueTime"))
// {
// Console.WriteLine("String.键:StringValue,值:{0} {1}", client.Get<string>("StringValueTime"), DateTime.Now);
// Thread.Sleep(10000);
// }
// else
// {
// Console.WriteLine("键:StringValue,值:我已过期 {0}", DateTime.Now);
// break;
// }
//}
//client.Add<string>("StringValue", " String和Memcached操作方法差不多");
//Console.WriteLine("数据类型为:String.键:StringValue,值:{0}", client.Get<string>("StringValue"));
//Student stud = new Student() { id = "1001", name = "李四" };
//client.Add<Student>("StringEntity", stud);
//Student Get_stud = client.Get<Student>("StringEntity");
//Console.WriteLine("数据类型为:String.键:StringEntity,值:{0} {1}", Get_stud.id, Get_stud.name);
//client.Set<Student>("student", stud, new TimeSpan(1, 0, 0));
//Student get_stu=client.Get<Student>("student");
//Console.WriteLine("student设置一小时过期时间{0}{1}", get_stu.id, get_stu.name);
//Console.ReadKey();
#endregion
#region Hash
//Console.WriteLine("----------Redis Hash处理------------");
//client.SetEntryInHash("HashID", "name", "Daniel");
//client.SetEntryInHash("HashID", "Age", "24");
//client.SetEntryInHash("HashID", "Sex", "男");
//client.SetEntryInHash("HashID", "Address", "上海市XX号XX室");
//List<string> HaskKey = client.GetHashKeys("HashID");
//foreach (var key in HaskKey)
//{
// Console.WriteLine("HashID-key:{0}", key);
//}
//List<string> HaskValue = client.GetHashValues("HashID");
//foreach (string value in HaskValue)
//{
// Console.WriteLine("HashID--Value:{0}", value);
//}
//List<string> AllKey = client.GetAllKeys();
//foreach (string Key in AllKey)
//{
// Console.WriteLine("AllKey--Key:{0}", Key);
//}
//Console.ReadKey();
#endregion
#region list
#region 解释
/*
* list是一个链表结构,主要功能是push,pop,获取一个范围的所有的值等,操作中key理解为链表名字。
* Redis的list类型其实就是一个每个子元素都是string类型的双向链表。我们可以通过push,pop操作从链表的头部或者尾部添加删除元素,
* 这样list既可以作为栈,又可以作为队列。Redis list的实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销,
* Redis内部的很多实现,包括发送缓冲队列等也都是用的这个数据结构
*/
#endregion
//client.EnqueueItemOnList("QueueListId", "redis队列1");//入队
//client.EnqueueItemOnList("QueueListId", "redis队列2");
//client.EnqueueItemOnList("QueueListId", "redis队列3");
//client.EnqueueItemOnList("QueueListId", "redis队列4");
//int q = client.GetListCount("QueueListId");
//for (int i = 0; i < q; i++)
//{
// Console.WriteLine("QueueListId出队值:{0}", client.DequeueItemFromList("QueueListId")); //出队(队列先进先出)
//}
//client.PushItemToList("StackListId", "redis队列1"); //入栈
//client.PushItemToList("StackListId", "redis队列2");
//client.PushItemToList("StackListId", "redis队列3");
//client.PushItemToList("StackListId", "redis队列4");
//int p = client.GetListCount("StackListId");
//for (int i = 0; i < p; i++)
//{
// Console.WriteLine("StackListId出栈值:{0}", client.PopItemFromList("StackListId")); //出栈(栈先进后出)
//}
//Console.ReadKey();
#endregion
#region Set无序集合
/*
它是string类型的无序集合。set是通过hash table实现的,添加,删除和查找,对集合我们可以取并集,交集,差集
*/
//client.AddItemToSet("Set1001", "小A");
//client.AddItemToSet("Set1001", "小B");
//client.AddItemToSet("Set1001", "小C");
//client.AddItemToSet("Set1001", "小D");
//HashSet<string> hastsetA = client.GetAllItemsFromSet("Set1001");
//foreach (string item in hastsetA)
//{
// Console.WriteLine("Set无序集合ValueA:{0}", item); //出来的结果是无须的
//}
//client.AddItemToSet("Set1002", "小K");
//client.AddItemToSet("Set1002", "小C");
//client.AddItemToSet("Set1002", "小A");
//client.AddItemToSet("Set1002", "小J");
//HashSet<string> hastsetB = client.GetAllItemsFromSet("Set1002");
//foreach (string item in hastsetB)
//{
// Console.WriteLine("Set无序集合ValueB:{0}", item); //出来的结果是无须的
//}
//HashSet<string> hashUnion = client.GetUnionFromSets(new string[] { "Set1001", "Set1002" });
//foreach (string item in hashUnion)
//{
// Console.WriteLine("求Set1001和Set1002的并集:{0}", item); //并集
//}
//HashSet<string> hashG = client.GetIntersectFromSets(new string[] { "Set1001", "Set1002" });
//foreach (string item in hashG)
//{
// Console.WriteLine("求Set1001和Set1002的交集:{0}", item); //交集
//}
//HashSet<string> hashD = client.GetDifferencesFromSet("Set1001", new string[] { "Set1002" }); //[返回存在于第一个集合,但是不存在于其他集合的数据。差集]
//foreach (string item in hashD)
//{
// Console.WriteLine("求Set1001和Set1002的差集:{0}", item); //差集
//}
//Console.ReadKey();
#endregion
#region SetSorted 有序集合
/*
sorted set 是set的一个升级版本,它在set的基础上增加了一个顺序的属性,这一属性在添加修改.元素的时候可以指定,
* 每次指定后,zset(表示有序集合)会自动重新按新的值调整顺序。可以理解为有列的表,一列存 value,一列存顺序。操作中key理解为zset的名字.
*/
//client.AddItemToSortedSet("SetSorted1001", "1.刘仔",2);
//client.AddItemToSortedSet("SetSorted1001", "3.猪仔",1);
//client.AddItemToSortedSet("SetSorted1001", "2.星仔",3);
//List<string> listSetSorted = client.GetAllItemsFromSortedSet("SetSorted1001");
//foreach (string item in listSetSorted)
//{
// Console.WriteLine("SetSorted有序集合{0}", item);
//}
//Console.ReadKey();
#endregion
#region 发布订阅
using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379"))
{
ISubscriber sub = redis.GetSubscriber();
Thread.Sleep(1000);
Console.WriteLine("请输入发布订阅类型?");
Thread.Sleep(5000);
var type = Console.ReadLine();
if (type == "publish")
{
while (true)
{
Console.WriteLine("请输入要发布向哪个通道?");
var channel = Console.ReadLine();
Console.WriteLine("请输入要发布的消息内容.");
var message = Console.ReadLine();
sub.Publish(channel, message);
}
}
else
{
Console.WriteLine("请输入您要订阅哪个通道的信息?");
var channelKey = Console.ReadLine();
sub.Subscribe(channelKey, (channel, message) =>
{
Console.WriteLine("接受到发布的内容为:" + message);
});
Console.WriteLine("您订阅的通道为:<< " + channelKey + " >> ! 一切就绪,等待发布消息!勿动,一动就没啦!!");
Task.Run(()=>{
//
});
Task a = Task.Factory.StartNew(() => {
//
});
Console.ReadKey();
}
}
#endregion
}
}
}
|
Java
|
UTF-8
| 420 | 1.789063 | 2 |
[] |
no_license
|
package com.secl.eservice.requisition.road.response;
import com.google.gson.annotations.Expose;
import com.secl.eservice.util.constant.Constant;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class GetCommentList {
private @Expose String oid, roadrequisitionoid, comment, stepoid, createdby, createdon;
@Override
public String toString() {
return Constant.print(this);
}
}
|
Python
|
UTF-8
| 561 | 3.234375 | 3 |
[] |
no_license
|
# 21. 1. 2. 행렬의 덧셈
# 넘파이로 한줄컷 가능했지만 다른풀이 도출하는데 꽤 시간이 걸렸다
# 의외로 list comprehension이 가장 빨랐다
import numpy as np
def solution_numpy(arr1, arr2):
return np.add(np.array(arr1), np.array(arr2)).tolist()
def solution_map(arr1, arr2):
ans = []
for i in range(len(arr1)):
a = list(map(sum, zip(arr1[i],arr2[i])))
ans.append(a)
return ans
# fastest
def solution_lc_zip(arr1, arr2):
return [[x+y for x,y in zip(a1,a2)] for a1, a2 in zip(arr1, arr2)]
|
C#
|
UTF-8
| 977 | 2.5625 | 3 |
[] |
no_license
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
public class MachineBuilder : MonoBehaviour
{
// Can access any component in the grid via its coordinates
public static Dictionary<Vector2, GameObject> componentGrid = new Dictionary<Vector2, GameObject>();
public GameObject componentContainer;
void Start()
{
DestroyGameObjects(componentContainer.transform);
}
public void DestroyGameObjects(Transform container)
{
foreach (Transform _transform in container)
{
Destroy(_transform.gameObject);
}
}
public static string LogComponentGrid()
{
string log = string.Empty;
int counter = 0;
foreach (KeyValuePair<Vector2, GameObject> entry in componentGrid)
{
log += $"ComponentGrid entry #{counter}: {entry} \n";
counter++;
}
return log;
}
}
|
Markdown
|
UTF-8
| 9,205 | 2.75 | 3 |
[
"0BSD"
] |
permissive
|
---
title: OCR API 비교
tags:
- Android
date: 2020-02-12
---
OCR(Optical character recognition)은 사람이 쓰거나 기계로 인쇄한 문자의 영상을 기계가 읽을 수 있는 문자로 변환하는것이다.
최근 ML이 트렌드로 떠오르면서 다양한 기업들에서 이를 기반으로 한 OCR API를 제공하고 있는데 몇개를 사용해보고 정리해보고자 한다.
# Firebase ML Kit
Google에서 제공하는 모바일용 ML kit이다. 무료이지만 라틴 문자만 인식이 가능하다.
인식속도가 빠르고 이미지만 전송하면 텍스트를 뽑아주기 때문에 사용도 편리하다.
### 사용법
1. Firebase 프로젝트를 생성한다. [Firebase 콘솔](https://console.firebase.google.com/u/0/?hl=ko) 에 로그인하여 프로젝트 추가 버튼을 누르고, 가이드대로 따라한다.
2. 프로젝트의 왼쪽사이드바에서 개발> ML kit를 클릭한다.
3. 텍스트 인식을 눌러 시작한다.
### 예제 코드
```kotlin
private fun googleAnalyze(path: String){
val image: FirebaseVisionImage
try {
image = FirebaseVisionImage.fromFilePath(this, Uri.fromFile(File(path)))
val detector = FirebaseVision.getInstance().onDeviceTextRecognizer
val result = detector.processImage(image)
.addOnSuccessListener {
Log.d(TAG, it.text)
}.addOnFailureListener {
Log.d(TAG, it.message)
}
}catch (e: IOException){
e.printStackTrace()
}
}
```
# KaKao Vision API
카카오에서 제공하는 Rest API에 속해있다.
이미지에서 문자영역을 감지하여 문자영역의 좌표값과 이미지를 던지면 텍스트가 출력된다.
이미지에서 문자영역을 추출하는 API와 텍스트를 인식하는 API가 따로따로 있기때문에 API를 두번 콜해야 문자 값을 얻을 수 있다.
### 사용법
1. [카카오 개발자 페이지](https://developers.kakao.com/) 에 접속하여 로그인한다.
2. 새로운 앱을 만든다.
3. Rest API 키 값을 얻어 API를 호출한다.
### 예제코드
먼저 이미지 파일을 https://kapi.kakao.com/v1/vision/text/detect 에 POST 방식으로 넘겨 텍스트 영역의 좌표값을 얻는다.
##### APIManager.kt
카카오 비전 API 호출 시 이미지 사이즈는 4096x4096이하여야 하고 최대 용량은 2MB이기 때문에 파일을 POST로 넘기기 전에 용량을 줄여주었다.
```kotlin
object ApiManager {
private val TAG = ApiManager::class.java.simpleName
fun getKakaoBoxes(fileUri: String): Observable<DataModel.boxResult> {
val kakaoBoxService = KakaoVisionApiService.createKakaoOCR()
scaleDown(fileUri)
val file = File(fileUri)
val requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
return kakaoBoxService.getKakaoBoxresult(KAKAO_KEY, requestBody)
}
fun scaleDown(path: String) {
var photo = BitmapFactory.decodeFile(path)
photo = Bitmap.createScaledBitmap(photo, 1000, 1000, false)
var bytes = ByteArrayOutputStream()
photo.compress(Bitmap.CompressFormat.JPEG, 80, bytes)
var file = File(path)
file.createNewFile()
var output = FileOutputStream(file)
output.write(bytes.toByteArray())
output.close()
}
}
```
##### DataModel.kt
```kotlin
object DataModel {
data class boxResult(@SerializedName("result") val result : boxes)
data class boxes( @SerializedName("boxes") val boxes : JsonArray)
}
```
API의 응답 형태가 아래와 같으므로 data class를 만들어 준다.
```json
{"result":{"boxes":[[[345,554],[417,554],[417,638],[345,638]]]}}
```
##### KaKaoVisionApiService.kt
```kotlin
interface KakaoVisionApiService {
@POST(KAKAO_BOX_SUB_URL)
@Multipart
fun getKakaoBoxresult(@Header("Authorization") key: String, @Part("file\"; filename=\"photo.jpg\"") file: RequestBody) : Observable<DataModel.boxResult>
companion object{
fun createKakaoOCR(): KakaoVisionApiService{
return getKakaoOCRApiService().create(KakaoVisionApiService::class.java)
}
private fun getKakaoOCRApiService() : Retrofit {
return Retrofit.Builder()
.client(provideOkHttpClient(provideLoggingInterceptor()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(KAKAO_BASE_URL)
.build()
}
private fun provideOkHttpClient(interceptor: HttpLoggingInterceptor): OkHttpClient {
val b = OkHttpClient.Builder()
b.addInterceptor(interceptor)
return b.build()
}
private fun provideLoggingInterceptor(): HttpLoggingInterceptor {
val interceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger {
Log.d("DEBUG-API-LOG", it)
})
interceptor.level = HttpLoggingInterceptor.Level.BODY
return interceptor
}
}
}
```
Retrofit 객체를 생성하는 인터페이스를 만들어준다.
Multipart로 파일을 넘기는 부분에서 삽질을 많이했는데, 검색하면 죄다 MultipartBody.Part로 넘기라고 나온다. 그런데 그렇게 넘기면 illegal type 이라고 오류가 리턴된다. RequestBody로 넘겨주고 Part에는 요청 파라미터 이름인 file을 설정해준다.
##### MainActivity.kt
```kotlin
private fun kakaoAnalyzeBox(path: String){
ApiManager.getKakaoBoxes(path).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext {
Log.d(TAG, "type= ${it.result.boxes}")
kakaoAnalyzeOcr(path, "${it.result.boxes}")
}
.subscribe({
Log.d(TAG, "subscribe" + it.result)
}, {t: Throwable? ->
Log.e(TAG, "kakaoAnalyzeBox"+t?.message.toString())
})
}
```
메인액티비티에서 카메라로 사진을 찍은 후 Path를 넣어 콜해준다. 그리고 이후에 텍스트 인식 API를 콜한다.
##### MainActivity.kt
kakaoAnalyzeBox 함수에서 호출하는 OCR함수는 다음과 같다.
```kotlin
private fun kakaoAnalyzeOcr(path: String, box: String){
ApiManager.getKakaoOCR(path, box).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers. mainThread())
.subscribe ({
tv_result.text = it.result.get("recognition_words").asString
},{t: Throwable? ->
Log.e(TAG, "kakaoAnalyzeOcr"+t?.message.toString())
tv_result.text = "사진이 인식되지 않습니다. 다시 촬영해주세요."
})
}
```
마찬가지로 ApiManager와 KakaoVisionApiService에 함수를 만들고 DataModel에도 응답 JSON 형식의 객체를 만들어 준다.
##### DataModel.kt
```kotlin
data class ocrResult(var result: JsonObject, var recognition_words: JsonArray)
```
##### ApiManager.kt
```kotlin
fun getKakaoOCR(fileUri: String, box: String): Observable<DataModel.ocrResult> {
val kakaoOcrService = KakaoVisionApiService.createKakaoOCR()
val file = File(fileUri)
val requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
return kakaoOcrService.getKakaoOCRresult(KAKAO_KEY, requestBody, box)
}
```
##### KakoVisionApiService.kt
```kotlin
@POST(KAKAO_OCR_SUB_URL)
@Multipart
fun getKakaoOCRresult(@Header("Authorization") key: String,@Part("file\"; filename=\"photo.jpg\"") file: RequestBody, @Query("boxes")box: String) : Observable<DataModel.ocrResult>
```
이렇게 해서 실행하면 kakao OCR API를 사용하여 텍스트를 추출할 수 있다.
# Google Cloud Vision
Firebase ML kit와 같이 구글에서 제공하는 서비스이지만, ML kit와 다르게 Cloud Vision은 라틴어 뿐만아니라 한국어를 포함한 다양한 언어를 제공한다. (물론 FIrebase에서 Blazer 요금제를 사용해야한다.) 하지만 1000회까지는 무료이고, Blazer요금제를 사용하더라도 무료 사용량 안에서는 과금이 되지 않기 때문에 사용량이 적다면 사용해볼 만 하다.
사용방법은 Firebase ML Kit와 거의 유사하다. 한가지 다른 점은 Option을 설정해서 감지 언어를 설정할 수 있다.
```kotlin
private fun gcpAnalyze(path: String){
val image: FirebaseVisionImage = FirebaseVisionImage.fromFilePath(this, Uri.fromFile(File(path)))
val options = FirebaseVisionCloudTextRecognizerOptions.Builder().setLanguageHints(listOf("ko")).build()
val dectector = FirebaseVision.getInstance().getCloudTextRecognizer(options)
val result = dectector.processImage(image).addOnSuccessListener {
Log.d(TAG, it.text)
}.addOnFailureListener { e->
Log.d(TAG, e.message)
}
}
```
Full Code는 [여기](https://github.com/coooldoggy/OCRApiTest) 에서 확인할 수 있다.
|
Python
|
UTF-8
| 7,830 | 2.734375 | 3 |
[
"Apache-2.0"
] |
permissive
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the MergeAdjacentBarriers pass"""
import unittest
from qiskit.transpiler.passes import MergeAdjacentBarriers
from qiskit.converters import circuit_to_dag
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
class TestMergeAdjacentBarriers(QiskitTestCase):
"""Test the MergeAdjacentBarriers pass"""
def test_two_identical_barriers(self):
""" Merges two barriers that are identical into one
░ ░ ░
q_0: |0>─░──░─ -> q_0: |0>─░─
░ ░ ░
"""
qr = QuantumRegister(1, 'q')
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_numerous_identical_barriers(self):
""" Merges 5 identical barriers in a row into one
░ ░ ░ ░ ░ ░ ░
q_0: |0>─░──░──░──░──░──░─ -> q_0: |0>─░─
░ ░ ░ ░ ░ ░ ░
"""
qr = QuantumRegister(1, 'q')
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_of_different_sizes(self):
""" Test two barriers of different sizes are merged into one
░ ░ ░
q_0: |0>─░──░─ q_0: |0>─░─
░ ░ -> ░
q_1: |0>────░─ q_1: |0>─░─
░ ░
"""
qr = QuantumRegister(2, 'q')
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_not_overlapping_barriers(self):
""" Test two barriers with no overlap are not merged
(NB in these pictures they look like 1 barrier but they are
actually 2 distinct barriers, this is just how the text
drawer draws them)
░ ░
q_0: |0>─░─ q_0: |0>─░─
░ -> ░
q_1: |0>─░─ q_1: |0>─░─
░ ░
"""
qr = QuantumRegister(2, 'q')
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.barrier(qr[1])
expected = QuantumCircuit(qr)
expected.barrier(qr[0])
expected.barrier(qr[1])
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_obstacle_before(self):
""" Test with an obstacle before the larger barrier
░ ░ ░
q_0: |0>──░───░─ q_0: |0>──────░─
┌───┐ ░ -> ┌───┐ ░
q_1: |0>┤ H ├─░─ q_1: |0>┤ H ├─░─
└───┘ ░ └───┘ ░
"""
qr = QuantumRegister(2, 'q')
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.h(qr[1])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.h(qr[1])
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_obstacle_after(self):
""" Test with an obstacle after the larger barrier
░ ░ ░
q_0: |0>─░───░── q_0: |0>─░──────
░ ┌───┐ -> ░ ┌───┐
q_1: |0>─░─┤ H ├ q_1: |0>─░─┤ H ├
░ └───┘ ░ └───┘
"""
qr = QuantumRegister(2, 'q')
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.barrier(qr[0])
circuit.h(qr[1])
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected.h(qr[1])
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle(self):
""" Test that barriers don't merge if there is an obstacle that
is blocking
░ ┌───┐ ░ ░ ┌───┐ ░
q_0: |0>─░─┤ H ├─░─ -> q_0: |0>─░─┤ H ├─░─
░ └───┘ ░ ░ └───┘ ░
"""
qr = QuantumRegister(1, 'q')
circuit = QuantumCircuit(qr)
circuit.barrier(qr)
circuit.h(qr)
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr)
expected.h(qr)
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
def test_barriers_with_blocking_obstacle_long(self):
""" Test that barriers don't merge if there is an obstacle that
is blocking
░ ┌───┐ ░ ░ ┌───┐ ░
q_0: |0>─░─┤ H ├─░─ q_0: |0>─░─┤ H ├─░─
░ └───┘ ░ -> ░ └───┘ ░
q_1: |0>─────────░─ q_1: |0>─────────░─
░ ░
"""
qr = QuantumRegister(2, 'q')
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0])
circuit.h(qr[0])
circuit.barrier(qr)
expected = QuantumCircuit(qr)
expected.barrier(qr[0])
expected.h(qr[0])
expected.barrier(qr)
pass_ = MergeAdjacentBarriers()
result = pass_.run(circuit_to_dag(circuit))
self.assertEqual(result, circuit_to_dag(expected))
if __name__ == '__main__':
unittest.main()
|
PHP
|
UTF-8
| 1,413 | 2.515625 | 3 |
[] |
no_license
|
<?php
namespace App\shopping;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class SeatRegister extends Model
{
protected $table = 'seat_registers';
protected $fillable = ['visit', 'sale_ticket_id', 'seat_id'];
public $timestamps = false;
public function seat()
{
return $this->belongsTo('App\shopping\Seat');
}
public function SaleTicket()
{
return $this->belongsTo('App\shopping\SaleTicket');
}
public function scopeCheckVisit($query, $seatId, $date)
{
return $query ->where([
['visit', $date],
['seat_id', '=', $seatId]
])
->count();
}
public function scopeRegisterDetail($query, $sale_ticket_detail)
{
return $query
->select(
'seat_registers.visit',
'seats.name as seatName',
'tickets.id as ticketId',
'tickets.name as ticketName'
)
->join('sale_tickets', 'seat_registers.sale_ticket_id', '=', 'sale_tickets.id')
->join('seats', 'seat_registers.seat_id', '=', 'seats.id')
->join('tickets', 'seats.ticket_id', '=', 'tickets.id')
->where([
['sale_ticket_id', '=', $sale_ticket_detail]
]);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.