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
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 11,429 | 2.6875 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: Ativar o acesso de leitura público para contentores e blobs no armazenamento de Blobs do Azure | Documentos da Microsoft
description: Saiba como tornar disponível para acesso anónimo a contentores e blobs e como devem ser acessados por meio de programação.
services: storage
author: tamram
ms.service: storage
ms.topic: article
ms.date: 04/30/2019
ms.author: tamram
ms.reviewer: cbrooks
ms.openlocfilehash: e0f93b0a95a228b26fae266129aea4b595b05e0f
ms.sourcegitcommit: d4dfbc34a1f03488e1b7bc5e711a11b72c717ada
ms.translationtype: MT
ms.contentlocale: pt-PT
ms.lasthandoff: 06/13/2019
ms.locfileid: "65148364"
---
# <a name="manage-anonymous-read-access-to-containers-and-blobs"></a>Gerir o acesso de leitura anónimo a contentores e blobs
Pode ativar o acesso de leitura anónimo, público para um contentor e respetivos blobs no armazenamento de Blobs do Azure. Ao fazê-lo, pode conceder acesso só de leitura a esses recursos sem partilhar a sua chave de conta e sem a necessidade de uma assinatura de acesso partilhado (SAS).
Acesso de leitura público é melhor para cenários onde pretende que determinados blobs para estar sempre disponíveis para acesso de leitura anónimo. Para um controlo mais detalhado, pode criar uma assinatura de acesso partilhado. Assinaturas de acesso partilhado permitem-lhe proporcionar acesso restrito com permissões diferentes, para um período de tempo específico. Para obter mais informações sobre a criação de partilhado assinaturas de acesso, consulte [Using partilhado assinaturas de acesso (SAS) no armazenamento do Azure](../common/storage-dotnet-shared-access-signature-part-1.md?toc=%2fazure%2fstorage%2fblobs%2ftoc.json).
## <a name="grant-anonymous-users-permissions-to-containers-and-blobs"></a>Conceder permissões de utilizadores anónimos a contentores e blobs
Por predefinição, um contentor e os blobs dentro da mesma podem ser acedidos apenas por um utilizador que tenha recebido as permissões adequadas. Para conceder acesso de leitura de usuários anônimos para um contentor e respetivos blobs, pode definir o nível de acesso público do contentor. Quando concede acesso público a um contentor, usuários anônimos podem ler blobs num contentor acessível ao público sem autorizar a solicitação.
Pode configurar um contentor com as seguintes permissões:
* **Sem acesso de leitura público:** O contentor e respetivos blobs podem ser acedidos apenas pelo proprietário da conta de armazenamento. Esta é a predefinição para todos os novos contentores.
* **Acesso de leitura público para blobs apenas:** Os BLOBs no contentor podem ser lidos por pedido anónimo, mas os dados de contentor não estão disponíveis. Clientes anônimos não é possível enumerar os blobs no contentor.
* **Acesso para o contentor e respetivos blobs de leitura pública:** Todos os dados de BLOBs e contentores podem ser lidos por pedido anónimo. Os clientes podem enumerar os blobs no contentor ao pedido anónimo, mas não é possível enumerar os contentores na conta de armazenamento.
Pode utilizar o seguinte para definir permissões de contentor:
* [Portal do Azure](https://portal.azure.com)
* [Azure PowerShell](../common/storage-powershell-guide-full.md?toc=%2fazure%2fstorage%2fblobs%2ftoc.json)
* [CLI do Azure](../common/storage-azure-cli.md?toc=%2fazure%2fstorage%2fblobs%2ftoc.json#create-and-manage-blobs)
* Por meio de programação, ao utilizar uma das bibliotecas de cliente do armazenamento ou a API REST
### <a name="set-container-public-access-level-in-the-azure-portal"></a>Definir o nível de acesso público do contentor no portal do Azure
Partir do [portal do Azure](https://portal.azure.com), pode atualizar o nível de acesso público para um ou mais contentores:
1. Navegue para a sua conta de armazenamento no portal do Azure.
1. Sob **serviço Blob** no painel de menu, selecione **Blobs**.
1. Selecione os contentores para o qual pretende definir o nível de acesso público.
1. Utilize o **nível de acesso de alteração** botão para apresentar as definições de acesso público.
1. Selecione o nível de acesso de público pretendido do **nível de acesso público** lista pendente e clique no botão OK para aplicar a alteração para os contentores selecionados.
Captura de ecrã seguinte mostra como alterar o nível de acesso público para os contentores selecionados.

> [!NOTE]
> Não é possível alterar o nível de acesso público para um blob individual. Nível de acesso público é definido apenas ao nível do contentor.
### <a name="set-container-public-access-level-with-net"></a>Definir o nível de acesso público do contentor com o .NET
Para definir permissões para um contentor com o c# e a biblioteca de cliente de armazenamento para .NET, obter permissões existentes que o contentor ao chamar o **GetPermissions** método. Em seguida, defina o **PublicAccess** propriedade para o **BlobContainerPermissions** objeto devolvido pelos **GetPermissions** método. Por fim, chame o **SetPermissions** método com as permissões atualizadas.
O exemplo seguinte define as permissões o contentor para acesso de leitura público completa. Para definir permissões para acesso de leitura público para blobs apenas, defina o **PublicAccess** propriedade **BlobContainerPublicAccessType.Blob**. Para remover todas as permissões para utilizadores anónimos, defina a propriedade **BlobContainerPublicAccessType.Off**.
```csharp
public static void SetPublicContainerPermissions(CloudBlobContainer container)
{
BlobContainerPermissions permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissions(permissions);
}
```
## <a name="access-containers-and-blobs-anonymously"></a>Aceder anonimamente a contentores e blobs
Um cliente que acede aos contentores e blobs anonimamente pode utilizar construtores que não necessitam de credenciais. Os exemplos seguintes mostram algumas formas diferentes de fazer referência a contentores e blobs anonimamente.
### <a name="create-an-anonymous-client-object"></a>Criar um objeto de cliente anônimo
Pode criar um novo objeto de cliente de serviço para acesso anónimo ao fornecer o ponto final de armazenamento de BLOBs para a conta. No entanto, também deve saber o nome de um contentor nessa conta que está disponível para acesso anónimo.
```csharp
public static void CreateAnonymousBlobClient()
{
// Create the client object using the Blob storage endpoint.
CloudBlobClient blobClient = new CloudBlobClient(new Uri(@"https://storagesample.blob.core.windows.net"));
// Get a reference to a container that's available for anonymous access.
CloudBlobContainer container = blobClient.GetContainerReference("sample-container");
// Read the container's properties. Note this is only possible when the container supports full public read access.
container.FetchAttributes();
Console.WriteLine(container.Properties.LastModified);
Console.WriteLine(container.Properties.ETag);
}
```
### <a name="reference-a-container-anonymously"></a>Fazer referência a um contentor anonimamente
Se tiver o URL para um contentor que está disponível de forma anônima, pode utilizá-lo para referenciar diretamente o contentor.
```csharp
public static void ListBlobsAnonymously()
{
// Get a reference to a container that's available for anonymous access.
CloudBlobContainer container = new CloudBlobContainer(new Uri(@"https://storagesample.blob.core.windows.net/sample-container"));
// List blobs in the container.
foreach (IListBlobItem blobItem in container.ListBlobs())
{
Console.WriteLine(blobItem.Uri);
}
}
```
### <a name="reference-a-blob-anonymously"></a>Um blob de referência anonimamente
Se tiver o URL para um blob que está disponível para acesso anónimo, pode referenciar o blob diretamente usando esse URL:
```csharp
public static void DownloadBlobAnonymously()
{
CloudBlockBlob blob = new CloudBlockBlob(new Uri(@"https://storagesample.blob.core.windows.net/sample-container/logfile.txt"));
blob.DownloadToFile(@"C:\Temp\logfile.txt", System.IO.FileMode.Create);
}
```
## <a name="features-available-to-anonymous-users"></a>Recursos disponíveis para utilizadores anónimos
A tabela seguinte mostra as operações que podem ser chamadas anonimamente quando um contentor está configurado para acesso público.
| Operação REST | Acesso de leitura público ao contentor | Acesso de leitura público para blobs apenas |
| --- | --- | --- |
| Lista de contentores | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Criar contentor | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Obter as propriedades do contentor | Pedidos anónimos permitidos | Apenas pedidos autorizados |
| Obter metadados do contentor | Pedidos anónimos permitidos | Apenas pedidos autorizados |
| Metadados do conjunto de contentor | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Obter o contentor ACL | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Definir o contentor de ACL | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Eliminar contentor | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Listar os Blobs | Pedidos anónimos permitidos | Apenas pedidos autorizados |
| Colocar o Blob | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Obter o Blob | Pedidos anónimos permitidos | Pedidos anónimos permitidos |
| Obter as propriedades do Blob | Pedidos anónimos permitidos | Pedidos anónimos permitidos |
| Definir as propriedades do Blob | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Obter metadados do Blob | Pedidos anónimos permitidos | Pedidos anónimos permitidos |
| Definir metadados do Blob | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Colocar o bloco | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Obter lista de bloqueios (apenas blocos confirmados) | Pedidos anónimos permitidos | Pedidos anónimos permitidos |
| Obter a lista de bloqueios (apenas os blocos não consolidados ou todos os blocos) | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Colocar a lista de bloqueios | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Eliminar Blob | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Copiar Blob | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Blob de instantâneo | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Blob de concessão | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Colocar a página | Apenas pedidos autorizados | Apenas pedidos autorizados |
| Os intervalos obter páginas | Pedidos anónimos permitidos | Pedidos anónimos permitidos |
| Blob de acréscimo | Apenas pedidos autorizados | Apenas pedidos autorizados |
## <a name="next-steps"></a>Passos Seguintes
* [Autorização para os serviços de armazenamento do Azure](https://docs.microsoft.com/rest/api/storageservices/authorization-for-the-azure-storage-services)
* [Utilizar assinaturas de acesso partilhado (SAS)](../common/storage-dotnet-shared-access-signature-part-1.md?toc=%2fazure%2fstorage%2fblobs%2ftoc.json)
|
C
|
UTF-8
| 2,508 | 3.15625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
#ifdef _MSC_VER
#include <direct.h>
#endif
#include "../feat2macros.h"
int mkdir_wrapper(const char* buff)
{
/* catch MSC compiler; this does not support the POSIX-style mkdir */
#ifdef _MSC_VER
return _mkdir(buff);
#else
return mkdir(buff, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
#endif
}
/* This function does about the same as "mkdir -p":
* It assumes *path_name to contain the path to a directory.
* All the nodes in the path_name-part are created (if they do not yet exist),
* duplicate slashes are ignored.
*
* "/path//to/" , "/path/to/" and "//path//to/" all should give the same result.
*
* Function fails on first (unrecoverable) error.
*
* Upon return ierr contains:
* (ierr >= 0) := number of subdirectories created
* (ierr < 0) := -errno
*
* Based on an implementation discussed in newsgroup comp.unix.programmer in April 2010
*/
void mkdir_recursive(const char *path_name, int* ierr)
{
char *buff;
char *slash;
size_t len;
int rc = 0;
int count = 0;
struct stat statbuff;
#if FEAT2_PP_OS_IS_WIN()
const char *separator = "/\\";
#else
const char *separator = "/";
#endif
len = strlen(path_name);
buff = (char *)malloc((len+1) * sizeof(char *));
if (buff == NULL) {
*ierr = -EINVAL;
return;
}
/* Create a copy of the given path/file name because we will
* - add a trailing slash and
* - blank every separator occurrence later, at least temporarily */
memcpy(buff, path_name, len);
/* strncpy(buff, path_name, len); */
buff[len] = '/';
buff[++len] = 0;
for (slash = buff; (slash = strpbrk(slash+1, separator)); ) {
/* this is to catch double / in paths */
if (
#if FEAT2_PP_OS_IS_WIN()
slash[-1] == '\\' ||
#endif
slash[-1] == '/') {
continue;
}
*slash = 0;
rc = stat(buff, &statbuff);
if (!rc) {
/* path already exists, skip it */
*ierr = EEXIST;
} else {
rc = mkdir_wrapper(buff);
*ierr = (rc) ? errno : 0;
}
switch(*ierr) {
case 0:
count++;
case EEXIST:
break;
case ENOTDIR:
case EACCES:
default:
goto quit;
}
*slash = '/';
}
quit:
*ierr = (*ierr) ? -(*ierr) : count;
free(buff); buff = NULL;
}
void mkdir_recursive_(const char *path_name, int* ierr)
{
mkdir_recursive(path_name, ierr);
}
void mkdir_recursive__(const char *path_name, int* ierr)
{
mkdir_recursive(path_name, ierr);
}
|
C++
|
UTF-8
| 344 | 2.65625 | 3 |
[] |
no_license
|
#ifndef SLLNODE_H
#define SLLNODE_H
using namespace std;
class SllNode
{
public:
SllNode();
virtual ~SllNode();
int getData();
bool setData(int);
SllNode* getNextPtr();
bool setNextPtr(SllNode*);
protected:
private:
int data;
SllNode* next;
};
#endif // SLLNODE_H
|
C#
|
UTF-8
| 1,047 | 2.984375 | 3 |
[] |
no_license
|
using System;
namespace AggregateSource.Testing {
/// <summary>
/// The given-when-then test specification builder bootstrapper.
/// </summary>
public class Scenario : IGivenStateBuilder {
/// <summary>
/// Given the following events occured.
/// </summary>
/// <param name="id">The aggregate the events occured to.</param>
/// <param name="events">The events that occurred.</param>
/// <returns>A builder continuation.</returns>
public IGivenStateBuilder Given(Guid id, params object[] events) {
if (events == null) throw new ArgumentNullException("events");
return new TestSpecificationBuilder().Given(id, events);
}
/// <summary>
/// When a command occurs.
/// </summary>
/// <param name="message">The command message.</param>
/// <returns>A builder continuation.</returns>
public IWhenStateBuilder When(object message) {
if (message == null) throw new ArgumentNullException("message");
return new TestSpecificationBuilder().When(message);
}
}
}
|
Shell
|
UTF-8
| 395 | 3.125 | 3 |
[] |
no_license
|
#!/bin/bash
if [ $# -ne 3 ]
then
echo "Usage: ./genACC <tgt_name> <tmp_root> <home_root>"
exit
fi
# ---- get arguments ----#
tgt_name=$1
tmp_root=$2
home_root=$3
# ---- process -----#
ACCPred=$home_root/util/ACC_Predict/acc_pred
$ACCPred $tmp_root/$tgt_name.hhm $tmp_root/$tgt_name.ss2 $tmp_root/$tgt_name.ss8 $home_root/util/ACC_Predict/model.accpred $tmp_root/$tgt_name.acc
|
Java
|
UTF-8
| 1,114 | 2.40625 | 2 |
[] |
no_license
|
@Test
public void testProxyWithRequestContentAndResponseContent() throws Exception
{
startServer(new HttpServlet()
{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
if (req.getHeader("Via") != null)
resp.addHeader(PROXIED_HEADER, "true");
IO.copy(req.getInputStream(), resp.getOutputStream());
}
});
startProxy();
startClient();
byte[] content = new byte[1024];
new Random().nextBytes(content);
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.method(HttpMethod.POST)
.content(new BytesContentProvider(content))
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
Assert.assertArrayEquals(content, response.getContent());
}
|
JavaScript
|
UTF-8
| 3,496 | 2.96875 | 3 |
[] |
no_license
|
//传入一个object
export default function combineReducers(reducers){
//获取该object的key值
const reducerKeys = Object.keys(reducers)
//过滤后的reducers
const finalReducers = {}
//获取每一个key对应的value
//在开发环境下判断是不是undefined
//然后将值类型是函数的值放入finalreducers
for(let i = 0;i<reducerKeys.length;i++){
const key = reducerKeys[i]
if(ProcessingInstruction.env.NODE_ENV !=='production'){
if(typeof reducers[key] === undefined){
warning("err")
}
}
if(typeof reducers[key] === 'function'){
finalReducers[key] = reducers[key]
}
}
//拿到过滤后的reducers的key值
const finalReducersKeys = Object.keys(finalReducers)
//在开发环境下判断,保存不期望key的缓存可以用下面做警告
if (process.env.NODE_ENV !== 'production') {
unexpectedKeyCache = {}
}
let shapeAssertionError
try {
// 该函数解析在下面
assertReducerShape(finalReducers)
} catch (e) {
shapeAssertionError = e
}
// combineReducers 函数返回一个函数,也就是合并后的 reducer 函数
// 该函数返回总的 state
// 并且你也可以发现这里使用了闭包,函数里面使用到了外面的一些属性
return function combination(state = {}, action) {
if (shapeAssertionError) {
throw shapeAssertionError
}
// 该函数解析在下面
if (process.env.NODE_ENV !== 'production') {
const warningMessage = getUnexpectedStateShapeWarningMessage(
state,
finalReducers,
action,
unexpectedKeyCache
)
if (warningMessage) {
warning(warningMessage)
}
}
//state是否改变
let hasChanged = false
//改变后的state
const nextState = {}
for(let i = 0;i<finalReducersKeys.length;i++){
//拿到相应的key
const key = finalReducersKeys[i]
//获得key对应的reducer函数
const reducer = finalReducers[key]
//states树下key是与finreducers下的key相同的
//所以你在combinereducers中传入的key即代表了各个reducer和state
const previousStateForKey = state[key]
//然后执行reducr函数获取该key值对应的state
const nextStateForKey = reducer(previousStateForKey, action)
//判断state的值,undefined的话就报错
if(typeof nextStateForKey === 'undefined'){
const err = getundefinde(key,action)
throw new Error(err)
}
//然后将value塞进去
nextState[key] = nextStateForKey
//如果state改变
hasChanged = hasChanged ||nextStateForKey !=previousStateForKey
}
//只要state改变过就返回新的state
return hasChanged?nextState:state
}
}
// 这是执行的第一个用于抛错的函数
function assertReducerShape(reducers) {
//将conbinereducers中的参数遍历
Object.keys(reducers).forEach(key=>{
const reducer = reducers[key]
//给她传入一个action
const initialState = reducer(undefined,{type:ActionType.INIT})
//如果得到的state为undefined就报错
})
}
|
Java
|
UTF-8
| 1,234 | 2.25 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.audio.player.databases;
import android.app.Application;
import com.audio.player.databases.dao.AudioBookChapterDao;
import com.audio.player.databases.dao.AudioBookProgressDao;
import com.audio.player.databases.table.AudioBookChapter;
import com.audio.player.databases.table.AudioBookProgress;
import com.audio.player.util.ApplicationUtils;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
@Database(entities = {AudioBookProgress.class, AudioBookChapter.class},exportSchema = false, version = 1)
public abstract class AudioBookDatabase extends RoomDatabase {
private static volatile AudioBookDatabase INSTANCE;
public abstract AudioBookProgressDao progressDao();
public abstract AudioBookChapterDao chapterDao();
public static AudioBookDatabase getInstance() {
if (INSTANCE == null) {
synchronized (AudioBookDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(ApplicationUtils.getApplication(),
AudioBookDatabase.class, DBHelper.DB_NAME)
.build();
}
}
}
return INSTANCE;
}
}
|
Go
|
UTF-8
| 2,828 | 3.21875 | 3 |
[] |
no_license
|
package monit
import (
"encoding/json"
"fmt"
"strconv"
"strings"
)
const (
// Underline constant
Underline = "\n================================\n"
// NotAvailable constant
NotAvailable = "N.A"
// Byte size
Byte = 1.0
// KiloByte size
KiloByte = 1024 * Byte
// MegaByte size
MegaByte = 1024 * KiloByte
// GigaByte size
GigaByte = 1024 * MegaByte
// TeraByte size
TeraByte = 1024 * GigaByte
)
// ==================
// byte converters
// ==================
func parseString(data []byte, err error) string {
if err != nil {
return NotAvailable
}
return asString(data)
}
func parseInt(data []byte, err error) int {
if err != nil {
return -1
}
return asInteger(data)
}
// ==================
// string converters
// ==================
func parseInt64(data string, err error) uint64 {
if err != nil {
return 0
}
return asUInt64(data)
}
func parseFloat(data string, err error) float64 {
if err != nil {
return -1
}
return asFloat(data)
}
// ==================
// generic converters
// ==================
func asInteger(data []byte) int {
i, err := strconv.Atoi(asString(data))
if err != nil {
return -1
}
return i
}
func asUInt64(data string) uint64 {
i64, err := strconv.ParseInt(data, 10, 0)
if err != nil {
return 0
}
return uint64(i64)
}
func asString(data []byte) string {
return asSafeString(string(data))
}
func asSafeString(data string) string {
stringData := strings.TrimSpace(string(data))
return strings.TrimRight(stringData, "\n")
}
func asFloat(data string) float64 {
safeString := asSafeString(data)
floatVal, err := strconv.ParseFloat(safeString, 64)
if err != nil {
return -1
}
return floatVal
}
// ==================
// json converter
// ==================
func asPrettyJSON(data interface{}) string {
jsonD, err := json.MarshalIndent(data, "", " ")
dealWithError("json", err)
return string(jsonD)
}
func asJSON(data interface{}) string {
jsonD, err := json.Marshal(data)
dealWithError("json", err)
fmt.Println(string(jsonD))
fmt.Println("====")
rawJSON := json.RawMessage(jsonD)
bytes, err := rawJSON.MarshalJSON()
dealWithError("json", err)
fmt.Println(string(bytes))
return string(bytes)
}
// ==================
// size converter
// ==================
func asHumanBytes(bytes uint64) string {
unit := ""
value := float32(bytes)
switch {
case bytes >= TeraByte:
unit = "T"
value = value / TeraByte
case bytes >= GigaByte:
unit = "G"
value = value / GigaByte
case bytes >= MegaByte:
unit = "M"
value = value / MegaByte
case bytes >= KiloByte:
unit = "K"
value = value / KiloByte
case bytes >= Byte:
unit = "B"
case bytes == 0:
return "0"
}
stringValue := fmt.Sprintf("%.1f", value)
stringValue = strings.TrimSuffix(stringValue, ".0")
return fmt.Sprintf("%s%s", stringValue, unit)
}
|
Java
|
UTF-8
| 1,495 | 2.421875 | 2 |
[] |
no_license
|
package on2021_08.on2021_08_25_AtCoder___AtCoder_Beginner_Contest_214.F___Substrings;
import template.io.FastInput;
import template.io.FastOutput;
import template.primitve.generated.graph.LongDijkstraMinimumCostFlow;
import template.utils.Debug;
import java.util.Arrays;
public class FSubstrings {
int mod = (int) 1e9 + 7;
public void solve(int testNumber, FastInput in, FastOutput out) {
char[] s = in.rs().toCharArray();
int n = s.length;
int charset = 'z' - 'a' + 1;
int[][] next = new int[charset][n];
for (int i = 0; i < charset; i++) {
next[i][n - 1] = n;
}
int[] reg = new int[charset];
Arrays.fill(reg, n);
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j < charset; j++) {
next[j][i] = reg[j];
}
if (i + 1 < n) {
reg[s[i + 1] - 'a'] = i + 1;
}
}
reg[s[0] - 'a'] = 0;
long[] dp = new long[n + 1];
for (int x : reg) {
dp[x]++;
}
for (int i = 0; i < n; i++) {
dp[i] %= mod;
for (int j = 0; j < charset; j++) {
int to = next[j][i];
dp[to] += dp[i];
}
}
debug.debug("dp", dp);
long sum = 0;
for (int i = 0; i < n; i++) {
sum += dp[i];
}
sum %= mod;
out.println(sum);
}
Debug debug = new Debug(false);
}
|
JavaScript
|
UTF-8
| 2,253 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
const gfm = require('..');
const { convert, convertUnsafe } = gfm;
const assert = require('assert');
it('passing empty string', () => {
assert.equal(convert(''), '');
});
it('strikethrough', () => {
assert.equal(convert('# Hi\nThis ~text~~~~ is ~~~~curious 😡🙉🙈~.'), '<h1>Hi</h1>\n<p>This <del>text</del> is <del>curious 😡🙉🙈</del>.</p>\n');
});
it('table-1', () => {
assert.equal(convert(`| foo | bar |
| --- | --- |
| baz | bim |`), `<table>
<thead>
<tr>
<th>foo</th>
<th>bar</th>
</tr>
</thead>
<tbody>
<tr>
<td>baz</td>
<td>bim</td>
</tr></tbody></table>
`);
});
it('table-2', () => {
assert.equal(convert(`| abc | def |
| --- | --- |`), `<table>
<thead>
<tr>
<th>abc</th>
<th>def</th>
</tr>
</thead></table>
`);
});
it('autolinks', () => {
assert.equal(convert('<p><a href="http://www.commonmark.org">www.commonmark.org</a></p>'), '<p><a href="http://www.commonmark.org">www.commonmark.org</a></p>\n');
});
it('autolinks-2', () => {
assert.equal(convert('www.commonmark.org/he<lp'), '<p><a href="http://www.commonmark.org/he">www.commonmark.org/he</a><lp</p>\n');
});
it('autolinks-3', () => {
assert.equal(convert(`a.b-c_d@a.b
a.b-c_d@a.b.
a.b-c_d@a.b-
a.b-c_d@a.b_`), `<p><a href="mailto:a.b-c_d@a.b">a.b-c_d@a.b</a></p>
<p><a href="mailto:a.b-c_d@a.b">a.b-c_d@a.b</a>.</p>
<p>a.b-c_d@a.b-</p>
<p>a.b-c_d@a.b_</p>
`);
});
it('tagfilter (GFM)', () => {
assert.equal(convert(`<strong> <title> <style> <em>
<blockquote>
<xmp> is disallowed. <XMP> is also disallowed.
</blockquote>`), `<p><strong> <title> <style> <em></p>
<blockquote>
<xmp> is disallowed. <XMP> is also disallowed.
</blockquote>
`);
});
it('no-tagfilter', () => {
assert.equal(convertUnsafe(`<strong> <title> <style> <em>
<blockquote>
<xmp> is disallowed. <XMP> is also disallowed.
</blockquote>`), `<p><strong> <title> <style> <em></p>
<blockquote>
<xmp> is disallowed. <XMP> is also disallowed.
</blockquote>
`);
});
it('opt.sourcePos', () => {
assert.equal(convert('# 1\n2\n# 3\n> 4\n5', gfm.Option.sourcePos), `<h1 data-sourcepos="1:1-1:3">1</h1>
<p data-sourcepos="2:1-2:1">2</p>
<h1 data-sourcepos="3:1-3:3">3</h1>
<blockquote data-sourcepos="4:1-5:1">
<p data-sourcepos="4:3-5:1">4
5</p>
</blockquote>
`);
});
|
Python
|
UTF-8
| 520 | 2.59375 | 3 |
[
"LicenseRef-scancode-other-permissive",
"MIT"
] |
permissive
|
from django.db import models
from django.utils import timezone
from datetime import datetime, timedelta
class Item(models.Model):
name = models.CharField(max_length=30)
price = models.IntegerField()
image = models.ImageField(upload_to="webpage/images/items/")
dato = models.DateTimeField(default=timezone.now)
expiration = models.DateTimeField(default=datetime.now() +
timedelta(hours=9))
def __str__(self):
return f"{self.name}: {self.price},-"
|
Java
|
UTF-8
| 426 | 2.125 | 2 |
[] |
no_license
|
package nl.hu.prbed.airline.flightroute.presentation.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "No such flightroute")
public class FlightRouteNotFoundHTTPException extends RuntimeException {
public FlightRouteNotFoundHTTPException() {
super("No flightroute with that id");
}
}
|
JavaScript
|
UTF-8
| 1,576 | 2.921875 | 3 |
[] |
no_license
|
App.filter('toShortDate', function () {
return function (t) {
if (!t || !moment(t).isValid()) {
return '-';
} else {
var year = moment(t).get('year');
var month = moment(t).get('month') + 1;
var day = moment(t).get('date');
var newYear = year + 543;
var thaiYear = [day, month, newYear].join('/');
return thaiYear;
}
};
});
App.filter('toShortDateTime', function () {
return function (t) {
if (!t || !moment(t).isValid()) {
return '-';
} else {
var year = moment(t).get('year');
var month = moment(t).get('month') + 1;
var day = moment(t).get('date');
var minute = moment(t).get('minute');
var hour = moment(t).get('hour');
var second = moment(t).get('second');
var newYear = year + 543;
var thaiYear = [day, month, newYear].join('/');
var shortDateTime = thaiYear + ' ' + [hour, minute, second].join(':');
return shortDateTime;
}
};
});
App.filter('toDateTime', function () {
return function (dt) {
if (moment(dt).isValid()) {
return moment(dt).format('LLL');
} else {
return '-';
}
};
});
App.filter('toLongDate', function () {
return function (dt) {
if (moment(dt).isValid()) {
return moment(dt).format('LLL');
} else {
return '-';
}
};
});
|
Python
|
UTF-8
| 4,001 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import re
import time
import numpy as np
from mmdet.datasets import DATASETS
from .base_sot_dataset import BaseSOTDataset
@DATASETS.register_module()
class OTB100Dataset(BaseSOTDataset):
"""OTB100 dataset of single object tracking.
The dataset is only used to test.
"""
def __init__(self, *args, **kwargs):
"""Initialization of SOT dataset class."""
super().__init__(*args, **kwargs)
def load_data_infos(self, split='test'):
"""Load dataset information.
Args:
split (str, optional): Dataset split. Defaults to 'test'.
Returns:
list[dict]: The length of the list is the number of videos. The
inner dict is in the following format:
{
'video_path': the video path
'ann_path': the annotation path
'start_frame_id': the starting frame number contained
in the image name
'end_frame_id': the ending frame number contained in
the image name
'framename_template': the template of image name
'init_skip_num': (optional) the number of skipped
frames when initializing tracker
}
"""
print('Loading OTB100 dataset...')
start_time = time.time()
data_infos = []
data_infos_str = self.loadtxt(
self.ann_file, return_array=False).split('\n')
# the first line of annotation file is a dataset comment.
for line in data_infos_str[1:]:
# compatible with different OS.
line = line.strip().replace('/', os.sep).split(',')
if line[0].split(os.sep)[1] == 'Board':
framename_template = '%05d.jpg'
else:
framename_template = '%04d.jpg'
data_info = dict(
video_path=line[0],
ann_path=line[1],
start_frame_id=int(line[2]),
end_frame_id=int(line[3]),
framename_template=framename_template)
# Tracker initializatioin in `Tiger1` video will skip the first
# 5 frames. Details can be seen in the official file
# `tracker_benchmark_v1.0/initOmit/tiger1.txt`.
# Annotation loading will refer to this information.
if line[0].split(os.sep)[1] == 'Tiger1':
data_info['init_skip_num'] = 5
data_infos.append(data_info)
print(f'OTB100 dataset loaded! ({time.time()-start_time:.2f} s)')
return data_infos
def get_bboxes_from_video(self, video_ind):
"""Get bboxes annotation about the instance in a video.
Args:
video_ind (int): video index
Returns:
ndarray: in [N, 4] shape. The N is the bbox number and the bbox
is in (x, y, w, h) format.
"""
bboxes_file = osp.join(self.img_prefix,
self.data_infos[video_ind]['ann_path'])
bboxes = []
bboxes_info = self.loadtxt(bboxes_file, return_array=False).split('\n')
for bbox in bboxes_info:
bbox = list(map(int, re.findall(r'-?\d+', bbox)))
bboxes.append(bbox)
bboxes = np.array(bboxes, dtype=float)
if 'init_skip_num' in self.data_infos[video_ind]:
init_skip_num = self.data_infos[video_ind]['init_skip_num']
bboxes = bboxes[init_skip_num:]
end_frame_id = self.data_infos[video_ind]['end_frame_id']
start_frame_id = self.data_infos[video_ind]['start_frame_id']
assert len(bboxes) == (
end_frame_id - start_frame_id + 1
), f'{len(bboxes)} is not equal to {end_frame_id}-{start_frame_id}+1'
assert bboxes.shape[1] == 4
return bboxes
|
Java
|
UTF-8
| 533 | 2.84375 | 3 |
[] |
no_license
|
package singleton;
/**
* @author raguiarperez
*/
public class Singleton {
public static void main(String[] args) {
NewSingleton obx1 = NewSingleton.Instanciar();
NewSingleton obx2 = NewSingleton.Instanciar();
obx1.setNombre("carlos");
obx1.setApellido("Gomez");
obx1.setDni("1");
obx1.mostrar();
obx2.setNombre("pedro");
obx2.setApellido("Rodriguez");
obx2.setDni("2");
obx1.mostrar();
obx2.mostrar();
}
}
|
Markdown
|
UTF-8
| 365 | 2.546875 | 3 |
[] |
no_license
|
# Automated tweeting
## :point_right: This project was created for my personal needs but might help you too:point_left:<br>
### Using Selenium automation tool in **Python** the app opens my personal Video portfolio on stock website **Pond5**, picks 10 random video clips from my whole portfolio, and tweets links to each clip using my **Twitter** account.<br>
___
|
Markdown
|
UTF-8
| 742 | 2.765625 | 3 |
[] |
no_license
|
# tarification
Le projet met en place un model flexible qui implémente les différents schémas de tarification présentés dans l'exercie,
et est capable de recevoir assez facilement d'autres schémas de tarification. pour le faire il faut:
- Etendre le model de base des tarifications et définir les propriétés en plus du nouveau schéma qu'on veut ajouter.
- Ajouter le type de tarification à l'énumération qui défini les différents type de tarification utilisés par le model.
- Implémenter le generateur de tarification qui fixe le prix du produit selon la nouvelle tarification pour cette tarification. Puis l'ajouter à la factory qui le fournira
lorsqu'on voudra fixer le prix du produit en utilisant cette tarification.
|
SQL
|
UTF-8
| 918 | 4.53125 | 5 |
[] |
no_license
|
#8. What query would you run to get a list of client names and the total # of leads we've generated for each of our clients'
#sites between January 1, 2011 to December 31, 2011?
#Order this query by client id.
#Come up with a second query that shows all the clients, the site name(s), and the total number of leads generated from each site for all time.
select
cl.client_id,
cl.first_name,
cl.last_name,
count(le.leads_id) as 'number of leads 2011'
from clients cl
join sites si on cl.client_id = si.client_id
join leads le on si.site_id = le.site_id
where le.registered_datetime >= '2011-01-01 00:00:00' and le.registered_datetime < '2012-01-01 00:00:00'
group by cl.client_id
select
cl.client_id,
si.domain_name,
count(le.leads_id) as 'number of leads all time'
from clients cl
join sites si on cl.client_id = si.client_id
join leads le on si.site_id = le.site_id
group by cl.client_id
|
Markdown
|
UTF-8
| 555 | 3.625 | 4 |
[] |
no_license
|
# GCI-Fedora-Project
_Google Code-In 2019:_
In this GCI Task by Fedora Project, we were tasked to create a simple program that returns the number of divisors a number has in a given range.
Examples:
1. input: 5, output: 5 is divisible by 2 numbers
2. input: 10, output: 10 is divisible by 4 numbers
I chose to complete this using Python and list comprehensions. For every divisor in a specified range, an item was appended to an existing list. At the end of the program, I simply returned the number of items in the list.
Thanks for checking it out!
|
PHP
|
UTF-8
| 6,234 | 2.71875 | 3 |
[] |
no_license
|
<?php
require_once "conexion.php";
class ModeloAcumuladoMensual{
/*=============================================
MOSTRAR Acumulado
=============================================*/
static public function mdlMostrarReportAcumuladoMensual($tabla, $item, $valor){
$stmt = Conexion::conectar()->prepare("SELECT agenteVentas, SUM(unidades) as unidades, SUM(importeInicial) as importeInicial, SUM(unidSurt) as unidSurt, SUM(importSurt) as importSurt, fechaPedido FROM $tabla WHERE estado = 1 and SUBSTRING(fechaPedido, 4, 2) = :$item and agenteVentas = 'ROCIO MARTINEZ MORALES'");
$stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetchAll();
$stmt-> close();
$stmt = null;
}
static public function mdlMostrarAcumRocio($tabla, $item, $valor){
$stmt = Conexion::conectar()->prepare("SELECT agenteVentas, SUM(unidades) as unidades, SUM(importeInicial) as importeInicial, SUM(unidSurt) as unidSurt, SUM(importSurt) as importSurt, fechaPedido FROM $tabla WHERE estado = 1 and SUBSTRING(fechaPedido, 4, 2) = :$item and agenteVentas = 'ROCIO MARTINEZ MORALES'");
$stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetchAll();
$stmt-> close();
$stmt = null;
}
static public function mdlMostrarAcumLuis($tabla, $item, $valor){
$stmt = Conexion::conectar()->prepare("SELECT agenteVentas, SUM(unidades) as unidades, SUM(importeInicial) as importeInicial, SUM(unidSurt) as unidSurt, SUM(importSurt) as importSurt, fechaPedido FROM $tabla WHERE estado = 1 and SUBSTRING(fechaPedido, 4, 2) = :$item and agenteVentas = 'LUIS ENRIQUE BUSTOS MONTERD'");
$stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetchAll();
$stmt-> close();
$stmt = null;
}
static public function mdlMostrarAcumErik($tabla, $item, $valor){
$stmt = Conexion::conectar()->prepare("SELECT agenteVentas, SUM(unidades) as unidades, SUM(importeInicial) as importeInicial, SUM(unidSurt) as unidSurt, SUM(importSurt) as importSurt, fechaPedido FROM $tabla WHERE estado = 1 and SUBSTRING(fechaPedido, 4, 2) = :$item and agenteVentas = 'GOMEZ RODRIGUEZ ERICK'");
$stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetchAll();
$stmt-> close();
$stmt = null;
}
static public function mdlMostrarAcumOrlando($tabla, $item, $valor){
$stmt = Conexion::conectar()->prepare("SELECT agenteVentas, SUM(unidades) as unidades, SUM(importeInicial) as importeInicial, SUM(unidSurt) as unidSurt, SUM(importSurt) as importSurt, fechaPedido FROM $tabla WHERE estado = 1 and SUBSTRING(fechaPedido, 4, 2) = :$item and agenteVentas = 'ORLANDO BRIONES AGUIRRE'");
$stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetchAll();
$stmt-> close();
$stmt = null;
}
static public function mdlMostrarAcumJonathan($tabla, $item, $valor){
$stmt = Conexion::conectar()->prepare("SELECT agenteVentas, SUM(unidades) as unidades, SUM(importeInicial) as importeInicial, SUM(unidSurt) as unidSurt, SUM(importSurt) as importSurt, fechaPedido FROM $tabla WHERE estado = 1 and SUBSTRING(fechaPedido, 4, 2) = :$item and agenteVentas = 'JONATHAN GONZALEZ SANCHEZ'");
$stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetchAll();
$stmt-> close();
$stmt = null;
}
static public function mdlMostrarAcumAlfredo($tabla, $item, $valor){
$stmt = Conexion::conectar()->prepare("SELECT agenteVentas, SUM(unidades) as unidades, SUM(importeInicial) as importeInicial, SUM(unidSurt) as unidSurt, SUM(importSurt) as importSurt, fechaPedido FROM $tabla WHERE estado = 1 and SUBSTRING(fechaPedido, 4, 2) = :$item and agenteVentas = 'ALFREDO MENDOZA SEGURA'");
$stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetchAll();
$stmt-> close();
$stmt = null;
}
static public function mdlMostrarAcumArturo($tabla, $item, $valor){
$stmt = Conexion::conectar()->prepare("SELECT agenteVentas, SUM(unidades) as unidades, SUM(importeInicial) as importeInicial, SUM(unidSurt) as unidSurt, SUM(importSurt) as importSurt, fechaPedido FROM $tabla WHERE estado = 1 and SUBSTRING(fechaPedido, 4, 2) = :$item and agenteVentas = 'CASTOLO GALINDO ARTURO'");
$stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetchAll();
$stmt-> close();
$stmt = null;
}
static public function mdlMostrarAcumuladoAgenteImporteInicial($tabla, $item, $valor){
$stmt = Conexion::conectar()->prepare("SELECT SUM(importeInicial) as importeInicial, SUM(importSurt) as importSurt, fechaPedido FROM $tabla WHERE estado = 1 and $item = :$item GROUP by SUBSTRING(fechaPedido, 4, 2)");
$stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetchAll(PDO::FETCH_COLUMN, 0);
$stmt-> close();
$stmt = null;
}
static public function mdlMostrarAcumuladoAgenteImporteSurtido($tabla, $item, $valor){
$stmt = Conexion::conectar()->prepare("SELECT SUM(importeInicial) as importeInicial, SUM(importSurt) as importSurt, fechaPedido FROM $tabla WHERE estado = 1 and $item = :$item GROUP by SUBSTRING(fechaPedido, 4, 2)");
$stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetchAll(PDO::FETCH_COLUMN, 1);
$stmt-> close();
$stmt = null;
}
static public function mdlMostrarAcumuladoAgenteMeses($tabla, $item, $valor){
$stmt = Conexion::conectar()->prepare("SELECT SUM(importeInicial) as importeInicial, SUM(importSurt) as importSurt, fechaPedido FROM $tabla WHERE estado = 1 and $item = :$item GROUP by SUBSTRING(fechaPedido, 4, 2)");
$stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR);
$stmt -> execute();
return $stmt -> fetchAll(PDO::FETCH_COLUMN, 2);
$stmt-> close();
$stmt = null;
}
}
?>
|
Java
|
UTF-8
| 1,857 | 2.9375 | 3 |
[] |
no_license
|
package crono.inf;
import java.util.*;
public class InfTriple
{
private InfClass subject;
private InfClass predicate;
private InfClass object;
private boolean entailed;
//constructors
public InfTriple()
{
this.subject = new InfClass();
this.predicate = new InfClass();
this.object = new InfClass();
this.entailed = entailed;
}
public InfTriple(InfClass subject,InfClass predicate,InfClass object)
{
this.subject = subject;
this.predicate = predicate;
this.object = object;
this.entailed = entailed;
}
public InfTriple(InfClass subject,InfClass predicate,InfClass object,boolean entailed){
this.subject = subject;
this.predicate = predicate;
this.object = object;
this.entailed = entailed;
}
//accessors/mutators
public InfClass getSubject(){
return subject;
}
public InfClass getPredicate(){
return predicate;
}
public InfClass getObject(){
return object;
}
public boolean isEntailed(){
return entailed;
}
//overrides
@Override public String toString()
{
return "Triple:("+getSubject().getName()+"("+getSubject().getID()+"),"
+getPredicate().getName()+"("+getPredicate().getID()+"),"
+getObject().getName()+"("+getObject().getID()+"))"+(isEntailed()?" - Entailed":"");
}
@Override public boolean equals(Object triple2)
{
if(triple2 instanceof InfTriple)
{
InfTriple that = (InfTriple)triple2;
return this.getSubject().getID() == that.getSubject().getID() &&
this.getPredicate().getID() == that.getPredicate().getID() &&
this.getObject().getID() == that.getObject().getID();
//return this.hashCode() == ((InfClass)triple2).hashCode();
}
return false;
}
@Override public int hashCode()
{
return (41*(41+getSubject().getID())) + (23*(23+getPredicate().getID())) + getObject().getID();
}
}
|
Markdown
|
UTF-8
| 2,750 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
# alicloud_slb_master_slave_server_group
[back](../alicloud.md)
### Index
- [Example Usage](#example-usage)
- [Variables](#variables)
- [Resource](#resource)
- [Outputs](#outputs)
### Terraform
```terraform
terraform {
required_providers {
alicloud = ">= 1.120.0"
}
}
```
[top](#index)
### Example Usage
```terraform
module "alicloud_slb_master_slave_server_group" {
source = "./modules/alicloud/r/alicloud_slb_master_slave_server_group"
# delete_protection_validation - (optional) is a type of bool
delete_protection_validation = null
# load_balancer_id - (required) is a type of string
load_balancer_id = null
# name - (required) is a type of string
name = null
servers = [{
is_backup = null
port = null
server_id = null
server_type = null
type = null
weight = null
}]
}
```
[top](#index)
### Variables
```terraform
variable "delete_protection_validation" {
description = "(optional)"
type = bool
default = null
}
variable "load_balancer_id" {
description = "(required)"
type = string
}
variable "name" {
description = "(required)"
type = string
}
variable "servers" {
description = "nested block: NestingSet, min items: 0, max items: 2"
type = set(object(
{
is_backup = number
port = number
server_id = string
server_type = string
type = string
weight = number
}
))
default = []
}
```
[top](#index)
### Resource
```terraform
resource "alicloud_slb_master_slave_server_group" "this" {
# delete_protection_validation - (optional) is a type of bool
delete_protection_validation = var.delete_protection_validation
# load_balancer_id - (required) is a type of string
load_balancer_id = var.load_balancer_id
# name - (required) is a type of string
name = var.name
dynamic "servers" {
for_each = var.servers
content {
# is_backup - (optional) is a type of number
is_backup = servers.value["is_backup"]
# port - (required) is a type of number
port = servers.value["port"]
# server_id - (required) is a type of string
server_id = servers.value["server_id"]
# server_type - (optional) is a type of string
server_type = servers.value["server_type"]
# type - (optional) is a type of string
type = servers.value["type"]
# weight - (optional) is a type of number
weight = servers.value["weight"]
}
}
}
```
[top](#index)
### Outputs
```terraform
output "id" {
description = "returns a string"
value = alicloud_slb_master_slave_server_group.this.id
}
output "this" {
value = alicloud_slb_master_slave_server_group.this
}
```
[top](#index)
|
TypeScript
|
UTF-8
| 1,910 | 2.546875 | 3 |
[] |
no_license
|
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import {Proveedor} from './proveedor';
import { environment } from '../../environments/environment';
const API_URL = environment.apiURL;
const proveedores = '/proveedores';
import { ProveedorDetail } from './proveedor-detail';
/**
* The service provider for everything related to proveedores
*/
@Injectable()
export class ProveedorService {
/**
* Constructor of the service
* @param http The HttpClient - This is necessary in order to perform requests
*/
constructor(private http: HttpClient) {}
/**
* Returns the Observable object containing the list of proveedores retrieved from the API
* @returns The list of proveedores in real time
*/
getProveedores(): Observable<Proveedor[]> {
return this.http.get<Proveedor[]>(API_URL + proveedores);
}
getProveedorDetail(proveedorId): Observable<ProveedorDetail> {
return this.http.get<ProveedorDetail>(API_URL + proveedores + '/' + proveedorId);
}
/**
* Crea un proveedor
* @param proveedor The new proveedor
* @returns The new proveedor with the new id
*/
createProveedor(proveedor): Observable<Proveedor> {
return this.http.post<Proveedor>(API_URL + proveedores, proveedor);
}
/**
* Updates an author
* @param author The author's information updated
* @returns The confirmation that the author was updated
*/
updateProveedor(proveedor): Observable<ProveedorDetail> {
return this.http.put<ProveedorDetail>(API_URL + proveedores + '/' + proveedor.id, proveedor);
}
/**
* Deletes a book
* @param bookId The book's id
* @returns True if the book was deleted, false otherwise
*/
deleteProveedor(proveedorId): Observable<ProveedorDetail> {
return this.http.delete<ProveedorDetail>(API_URL + proveedores + '/' + proveedorId);
}
}
|
C#
|
UTF-8
| 1,151 | 2.796875 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
using System;
namespace Jint
{
public class EvalCodeScope : IDisposable
{
private readonly bool _eval;
private readonly bool _force;
private readonly int _forcedRefCount;
private static int _refCount;
public EvalCodeScope(bool eval = true, bool force = false)
{
_eval = eval;
_force = force;
if (_force)
{
_forcedRefCount = _refCount;
_refCount = 0;
}
if (_eval)
{
_refCount++;
}
}
public void Dispose()
{
if (_eval)
{
_refCount--;
}
if (_force)
{
_refCount = _forcedRefCount;
}
}
public static bool IsEvalCode
{
get { return _refCount > 0; }
}
public static int RefCount
{
get
{
return _refCount;
}
set
{
_refCount = value;
}
}
}
}
|
Python
|
UTF-8
| 2,097 | 2.71875 | 3 |
[] |
no_license
|
import datetime as dt
import xlrd
import xlutils as xlutils
import xlwt
"""
在 xlutils的init文件中导入这些功能才能使用
from .compat import *
from .copy import *
from .display import *
from .filter import *
from .margins import *
from .save import *
from .styles import *
from .view import *
"""
import time
class connect_excel:
def __init__(self,excel_name,sheet_name):
self.excel_name=excel_name
self.sheet_name=sheet_name
def read_date(self):
data=xlrd.open_workbook(self.excel_name)
sheet=data.sheet_by_name(self.sheet_name)
#获取第一行的数据
row_first=sheet.row_values(0)
data_list=[]
#获取其余行的数据
for i in range(1,sheet.nrows):
rows = sheet.row_values(i)
bb=dict(zip(row_first,rows))
data_list.append(bb)
print(data_list)
return data_list
def write_excel(self ,row, column, value):
data = xlrd.open_workbook(self.excel_name)
table = data.sheet_by_name(self.sheet_name)
workbook = xlutils.copy(data)
worksheet = workbook.get_sheet(self.sheet_name)
worksheet.write(row-1, column-1, value)
workbook.save(self.excel_name)
#写入最后一行
def write_excel_lastline(self,value):
# current_time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
#打开excel表格
data = xlrd.open_workbook(self.excel_name)
workbook = xlutils.copy(data)
#得到表格的sheet的名称
worksheet = workbook.get_sheet(self.sheet_name)
#获取表格sheet的队形
table = data.sheet_by_name(self.sheet_name)
rowNum = table.nrows #行数
#样式
style = xlwt.XFStyle()
worksheet.write(rowNum, 0, value)
worksheet.write(rowNum, 1, time.strftime("%Y-%m-%d %X", time.localtime()), style)
workbook.save(self.excel_name)
if __name__ == '__main__':
cases=connect_excel("/Users/xiaoff/python/pytest/test_03/data/test_new.xlsx","Sheet1").read_date()
|
Java
|
UTF-8
| 1,381 | 2.96875 | 3 |
[] |
no_license
|
package br.ufc.quixada.cripto;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;
import br.ufc.quixada.cripto.GeradorChave;
public class Main {
public static void main(String[] args) throws Exception{
// -- Gera o par de chaves, em dois arquivos (chave.publica e
// chave.privada)
GeradorChave gerador = new GeradorChave();
gerador.geraParChaves(new File("chave.publica"), new File("chave.privada"));
// -- Cifrando a mensagem "Hello, world!"
byte[] textoClaro = "Hello, world!".getBytes("ISO-8859-1");
PublicKey pub = gerador.LerChavePublica(new File("chave.publica"));
Enc cf = new Enc();
byte[][] encriptado = cf.cifra(pub, textoClaro);
// printHex(encriptado[0]);
// printHex(encriptado[1]);
// -- Decifrando a mensagem
PrivateKey pvk = gerador.LerChavePriv(new File("chave.privada"));
Decript decripta = new Decript();
byte[] decifrado = decripta.decifra(pvk, encriptado[0], encriptado[1]);
System.out.println ("Texto claro: \n"+new String (textoClaro, "ISO-8859-1"));
System.out.println("\nTexto cifrado: ");
for(int i=0; i < decifrado.length; i++) {
System.out.print(decifrado[i]);
}
System.out.println("\n\nTexto decifrado:");
System.out.println (new String(decifrado, "ISO-8859-1"));
// printHex(decifrado);
}
}
|
Java
|
UTF-8
| 1,142 | 3.921875 | 4 |
[] |
no_license
|
package com.company.day4.Functinal_Interface;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.ToIntFunction;
/**
* Function 계열
* - Mapping: 입력 -> 출력의 Mapping을 하는 함수형 인터페이스
* - 입력 타입과 출력 타입은 다를 수 있다.
*/
public class Function_test {
public static void main(String[] args) {
Function<String, Integer> func = (s) -> s.length(); // 첫번째 파라미터가 입력 타입, 두번째 파라미터가 출력 타입
System.out.println(func.apply("Four"));
BiFunction<String, String, Integer> funcTwo = (s, u) -> s.length() + u.length();
System.out.println(funcTwo.apply("sdf", "sdfw"));
// P Type Function은 입력을 P Type으로 받는다.
IntFunction<String> funcTree = value -> ""+value;
System.out.println(funcTree.apply(3212));
// ToP Type Function은 출력을 P타입으로 한다.
ToIntFunction<String> funcFour = (s)->s.length();
System.out.println(funcFour.applyAsInt("ABCDE"));
}
}
|
Java
|
ISO-8859-7
| 244 | 2.171875 | 2 |
[] |
no_license
|
package com.test8;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cat c = new Cat();
c.setName("");
c.setAge(2);
c.setSex('');
c.setType("è");
c.ShowData();
}
}
|
Python
|
UTF-8
| 261 | 4.3125 | 4 |
[] |
no_license
|
name = "Mike"
# f stringという昨日を使う
message = f"ようこそ、{name}さん"
# 表示して確認
print(message)
name2 = "Kate"
age = 18
# 複数の変数がある場合(数字もそのまま使える)
print(f"{name2}は、{age}歳です")
|
JavaScript
|
UTF-8
| 1,809 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
/*
* This is not a reusable component.
* This is a simple pattern and should serve as a base
* for development of custom components that intelligently
* render children based on user input or certain logic
*/
import React, { Component } from 'react';
import Registry from '../utils/Registry';
import BaseComponent from './BaseComponent';
import Card from './Card';
export default class Multi extends BaseComponent {
renderChildren() {
let curEls;
let output;
if (typeof this.state.data === 'string') { // Multi-component data should be a string
curEls = this.props.elements[this.state.data];
} else if (this.props.initVal) {
curEls = this.props.elements[this.props.initVal];
} else {
return console.error('No valid key is defined in initVal or in data for elements object');
}
return curEls.map((element, key) => {
let props = Object.assign(element, {globalData: this.props.globalData});
if (element.cardStyle) {
output =
<Card key={key} {...element}>
{React.createElement(Registry.get(element.type), props)}
</Card>
} else {
output =
React.createElement(Registry.get(element.type), props);
}
return output;
});
}
/*
* The render method, in this case, renders a select which triggers
* our change listener.
* A helper function renders an array of elements from the appropriate
* section of the multi component's settings
*/
render() {
let filters = this.getFilters();
let v =
<div class="multi-container">
{filters}
<div class="multi-elements-container">
{this.renderChildren()}
</div>
</div>
return v;
}
}
Registry.set('Multi', Multi);
|
Ruby
|
UTF-8
| 450 | 2.71875 | 3 |
[] |
no_license
|
require './test/test_helper'
class CardTest < Minitest::Test
def test_it_belongs_to_a_suit
card = Card.new("2", "heart")
assert Card.suits.include?(card.suit)
assert_equal "heart", card.suit
end
def test_it_has_a_rank
card = Card.new("2", "heart")
assert Card.ranks.include?(card.rank)
assert "2", card.rank
end
def test_it_has_a_score
card = Card.new("2", "heart")
assert_equal 2, card.score
end
end
|
Markdown
|
UTF-8
| 27,405 | 2.671875 | 3 |
[] |
no_license
|
# 为什么一定要拼尽全力考上985、211大学? - 算法与数学之美 - CSDN博客
2018年12月06日 21:00:00[算法与数学之美](https://me.csdn.net/FnqTyr45)阅读数:216

曾在知乎上看到这样一段话:
>
渣学校意味着渣教学,渣教学意味着渣学历,渣学历意味着渣就业...就算以后考了研究生,也可能因为你的第一学历不过关而被拒之门外。
真是这样吗?很多同学都有过这样的问题——
>
很多人说考上二本没前途,没上985、211没前途,我想知道除了一本院校,其他学校真的一团糟吗?哪怕认真学也没前途吗?
现在成绩勉强充二本,一本线差得太远。可是二本院校,哪怕二A的也很差吗?
那么,真正的好大学到底是哪些高校?这些顶尖名校和一般大学带来的差距本质上在哪里?为什么高中生要拼命努力考名校?小编今天就用数据和事实作出回答!
日前,华东师范大学社会调查中心发布《大学录取分数最新五年总排名》。其中,列出了近年来高考最难考取的30所大学——


一所不是那么优秀的高校,最可怕的就是给你带来一种温水煮青蛙的安逸感。
在这类学校里你能找到聪明的同学,能找到用功读书的同学,但是就是很难找到比你聪明五倍但比你努力十倍的人。
迟早有一天,等你真正进入社会的时候,你会发现那些有吸引力的工作岗位、那些能吸引风投的创业机会、那些留给下一辈配置社会财富的渠道,已经被这类人牢牢占据了。
当然,慢慢你还会发现,这类人往往情商高,涵养好,家里也有背景。
噢!对了,恰好还比你帅。
然而这些人,你在你的大学里,一个都没见过。
这个时候你才会发现,自己被大学耍了。
但是你已经很难去弥补了。就算你还能重新鼓起勇气上路,但还能够给你留下的路,已经很窄很窄了。

层次相对较低的环境,最可怕的不在于资源匮乏,而是在最该开阔眼界的年龄限制了人的眼界,在最该严格要求自己的阶段降低了标准。而且这些影响是潜移默化、根深蒂固的,最终导致“强者愈强、弱者愈弱”。
在一些二本/三本学校里,那些实际上能力绝不算出众的人,因为“矮子里面拔将军”的缘故,也会被树立为榜样。
同时学校又热衷一轮又一轮地宣传和神话这些人来鼓吹自己的办学成绩,而且越是层次低,学校的举动越夸张,从挂红榜到开专场报告会。
于是初入大学的你,缺乏对大学生活的基本了解和判断能力,你会不由自主地认为:
>
哇,过六级好厉害——于是你大学连四级也没过;
哇,课程好难我一定会挂 ——于是你大学四年确实挂了一片;
哇,过注册会计好厉害哦——于是大学四年你连个从业资格证也没考出来;
哇,考上211研究生好厉害——于是...
可你不知道在另一所大学中(或许就是你的隔壁),你的同龄人(或许曾经是你的同桌),在他们的生活里:
>
其实,不过六级是难以启齿的事情,大多数人的目标是550乃至600;
其实,“要挂科了”是用来自黑的,期末考试绝大多数的人是奔着4.0的绩点去考的,结果你还都信了;
其实,“什么都没学会”也是用来自黑的,于是被很多人拿来作为名牌大学无用的主要论据;
其实,各种从业考试是有人能考满分的,大家关注的是司考、CPA、CFA;
其实,研究生学校的目标是海外名校,要么也是清北复交,再不济也得是C9其他...
也许你们高考前的水平和能力并没有本质性的差别,普通985、211高校和正经二本能差多少分?顶多五六十分而已,根本不是什么天才和常人的差别!考上211的人,若是高考手抖两下真可能连一本线也过不了。可是大学四年的耳濡目染,让考上二本你给自己的人生加了一个不可逾越的透明天花板,差距就不是高考那些分数了。

因为这四年你啥都没学会,就学会了瞻前顾后,很多事情还没了解和尝试就已经预判,因为你扒拉扒拉周围的人,好像做到这些事情就是大神了,而我不是大神,所以我一准做不到。周围的环境限制了你的眼界、降低了你的标准。
于是久而久之,你和那些进入名校的高中同学的差别,已经变成了质的差别。

我一直没法清楚地描述这种差距,直到我最近看了《精进》这本书中的一段话,描述得非常贴切:
>
一个成熟的人,他的标准来自他的内心,而大多数人,却受环境所左右。一个年轻人,进入一所不那么优秀的高校,对自己的标准会不由自主的降低,以适应这个环境,减少自身与环境的冲突,而这种做法对他们的人生也许是致命的。
那些考入二三流大学的学生,因为高考本身带来的挫败感,二三流高校学生的身份设定及环境暗示,不称职的老师所引发的失望以及同学间放任自流气氛的带动作用,都容易让他们在一个低标准下,自觉“满意”地度过每一天。
看到这段话的时候,我想到大三大四在北大交流学习时的感受。在北大,最让我震撼的不是老师多牛、同学多聪明,而是一种大家都积极努力的氛围。比如期末考试过后自习室依然灯火通明,上课永远都人满为患,课间20分钟换教室时,学校里到处都是叼着面包奔跑的人。
每个人都毫无时间观念地疯狂学习,参加各种活动。在我眼里,他们永远充满了斗志,谈起各种竞赛和活动都特别兴奋,每天从睁眼就忙得不可开交,到晚上一两点睡觉都是常事。没人抱怨自己辛苦,也没人抱怨生活艰难,大家每天都忙得鸡飞狗跳,但又特别开心的样子。
我一直记得的,是这种从每个人身上散发出的生活学习的精神状态。这种状态不由得带动着我,虽然我跟他们差距很大,但也不断激发我向他们看齐的标准。直到现在,我一直用我能见到的周围最牛的人的标准来要求自己,虽然也经常做不到,但这让我觉得我是一个对自己有要求的人,在自律和自省中生活,辛苦但总有很大进步。
其实每一个同学进入大学的时候都怀着努力学习的心态,一二三本都有好学生,也都有特别努力勤奋的人,但为什么走着走着就会消失一大半呢?其实就是《精进》里的这几句话:“对自己的标准会不由自主的降低以适应这个环境,减少自身与环境的冲突,在一个低标准下,自觉‘满意’的度过每一天。”


以前,知名企业在招聘时会明文规定“须985院校毕业”。现在有法律法规限制,很多不敢直接这么说,但会在审核简历时用“毕业院校”作条件,悄悄地筛掉非985/211出身的人。
其实,有时候也不见得是因为歧视,企业知道普通高校也有人才。但简历实在太多,企业需要花最短的时间和成本找到能力较强的人,一个一个来筛选,这个人力物力和时间成本,没企业愿意出。所以,用“985”和“211”大学这样的标签来筛选人才,就成了成本最低的方法!

心灵鸡汤常说,"看一个人是否优秀,要看他和谁在一起"。很多企业也是看重“985”和“211”大学学生背后的资源,这样可以连成一张大大的关系网,相互提携。
举例来说,银行业务员揽储,一个“985”和“211”大学出来的,他参加两次校友会、同学会,可能就能把任务完成。这比等待着普通高校的毕业生一点一点积累人脉,可节约了太多的成本。
找工作时,“985”和“211”大学的校友也是重要资源。尤其是中央国家机关和大型企事业单位,你在面试时很可能会见到面试官和应聘的师弟师妹一起聊下家常。不见得只有北大、清华才有这样的优势,像地处东北的吉大,地域优势无法和北上广相比。于是吉大学生自发抱团,已毕业找到好工作的人自发回校分享,还成立了 "合协一家"协会。
这种做法,其实在很多非“985”和“211”大学里也流行,但是毕竟名校前辈们已经占了先机。

企业公开招聘,只能把985/211作为隐形条件。非“985”和“211”大学毕业生最可怜的,是根本就不知道还有一些部门和岗位在招聘,所以他们连投简历的机会都没有。
比如,很多中央部委的选调生,或是一些涉密部门的招聘,都在“985”和“211”大学进行定点招录和前期筛查。通过定点招录和筛查的人,才有报考的资格。举个最简单的例子,很多男生想当中国的007,可你什么时候听说过国家安全机关去普通大学招录毕业生?除此之外,像大学生村官计划、还有部分省份的选调生,也会有同样的限制条件。
可不要小看这些岗位!可能收入不高、条件艰苦,但毕业生一旦被录用就拿到了公务员身份!
解释一下:千万别以为国家发工资的就是公务员!每年国家和地方的所谓公务员考试,其实真正能享受公务员身份的岗位很少。普通高校毕业生费劲考了进去,苦苦工作了好几年,才发现自己只是事业编制。而那些985大学的选调生一开始就有公务员身份!
差别在哪里?福利待遇、职务晋升、公开选考...只有在党政机关待过的人,才知道“公务员身份”一词的含金量!有多稀有?你觉得厉害的不得了的高中校长,都没有公务员身份,80%的县教育局长也没有公务员身份...他们都是事业编制或行政编制。
对想留在高校教书的同学,985出身更重要!在高校老师的招录上,越好的院校越严苛,哪怕你博士是在美国常青藤院校拿的,如果在国内读的本科不是985,一样有可能被拒绝。当老师要求高点儿也正常,可辅导员、行政人员(有事业编制),好一点的高校也是要求你本硕都是985、211。
实话实说,招聘时学历歧视最严重的,就是高校!不仅985、211高校,好一点的本科院校基本如此。

说到985的优势,还有一个容易被忽视的指标,就是保研率!为什么这个指标也很重要?因为随着就业压力不断增大,以及用人单位对学历要求的不断提高,读研究生成为很多本科毕业生的选择。很多考生填报志愿时,也会考虑报考的大学和专业是否容易读研。而保送研究生的比例高,意味着这所大学的本科生读研的几率非常大。
什么是保研率?得先弄懂大学怎么保研。保研,是指推荐少数优秀应届本科毕业生免试为硕士研究生。关于大学保研率,国家是这样规定的:
>
有研究生院的高等学校,保送研究生名额一般按该校应届本科毕业生数的15%左右确定。
对未设立研究生院的“211工程”高校,要求一般要按应届本科毕业生数的5%左右确定。“
经教育部确定的人文、理科等人才培养基地的高等学校,按教育部批准的基地班招生人数的50%左右,单独增加推免生名额,由学校统筹安排;对国家发展急需的专业适当增加推免生名额。
设有研究生院的高等学校接收该校推免生的人数,不得超过该校推免生总数的65%,其中地处西部省份或军工、矿业、石油、地质、农林等特殊类型的高等学校,上述比例可适当放宽,但不得超过75%。
相比于地方院校而言,名校的保研率基本都超高。
● 清华大学以58.14%的保研率高居榜首,也是全国高校中唯一一所保研率超过50%的高校,意味着清华过半的本科生能得到保研机会。
● 北京大学以48.36%紧随其后,中科大以36.11%排名第三,复旦以30.39%排名第四,全国也只有这四所大学的保研率超过了30%。
● 除此之外,上海交通大学、南京大学、西安交通大学、南开大学、中国农业大学和浙江大学都进入前十,进入前十的保研率也都超过了24%。

曾经听过某二本院校的老师激励学生说:你要是考研分数刚过控制线那基本就没戏,没使劲考出400以上你怎么和985、211出来的学生竞争?
这话虽然夸张点儿,但也有道理。比如,两名学生同时参加复试,甲来自"985"院校,初试成绩370分;乙来自二本院校,初试成绩380分。面试表现两人难分伯仲,如果你是教授,你选谁?
认识的一位导师说,他选甲。倒不是学历歧视,而是他觉得二本院校的学生,尤其某些考研名校,大多很早就开始准备考研,基本上都是考试能力强、综合能力差。而"985"的学生往往不会像二本学生那么重视考研,他们可能在做实验,做项目,写论文,最后才为考研做准备。虽然他们可能不会像二本学生那样得高分。但在理论上能接触到更广的知识面,这对今后的学习研究更有帮助。
还有一位负责研究生招生的"985"高校老师透露:985、211院校导师更愿意接收985、211院校的本科生,若是录取了普通院校的本科生,他们会觉得自己是下嫁。高校愿意花钱来提前抢人,都是想让自己的生源质量好看一点,985、211的生源占比高一些,学科评比时也会占优势。

>
@西柚西柚
学习环境和氛围上
985名校真的比我们学校学霸太多!!!
他们每学期开始的时候去图书馆都找不到位置,我们学校期末考试临近图书馆也都还是轻松有位置的。
男朋友周末的时候就是各种去实验室,去上自习,各种努力学习,我这种就是大一大二的时候有空就宅宿舍,更不用说上自习了。
他们学校的好多人从大二的时候都开始想着保研好好学,我大二的时候还在各种混社团,混着玩。
当然985/211也有学渣,二本也有学霸。
可是,再怎样985还是一个985。
拿某银行招聘来说,要求的条件直接985院校和指定的几所财经院校,所以说,不管再怎样强调能力的问题,进入壁垒这么高,没学历进去哪里能发挥你的能力。
生活条件上
他们学校4800多亩地,各种小商业街,生活条件各种便利。我们学校比较小,离他们学校差3公里左右远,只有学校里边的小商店周围基本什么都没有了,对了,大一的时候学校南门还是玉米地。没有体育馆,没有游泳池。
他们学校四个体育馆,各种体育场,游泳池,大大的校医院,我们的校医院只有两三间小房间的那种。
交通,他们的公交地铁是直接通到市中心的不用换乘的那种,我们学校前些年不通公交车,都是坐小黑车去他们学校门口坐车,也是心酸。
眼界不一样
感觉自己眼界好肤浅…
他们的实习真的是走出去!
我们的见习,两周停课,没有任何活动,自己写个报告交了就好。
他们的实习去的某油田待了一个月,学校报销住宿,都是标准间那种。
我们学校工科的实习,搬去老区住,然后去造锤子,对,就是自己做锤子。我们这种专业的都是直接参观工厂,走马观花的看一看,然后听各种报告。
社交圈子
等到毕业的时候就会体现出来差别了。
男朋友宿舍一个保研的,两个考研考上的,班里好多出国和名牌研究生,还有各种好企业。
真心建议,好好努力,能考多少分考多少分,如果是普通家庭的话,高考真的很重要。
>
@林途里
主要差别表现在五个方面:
1.教学资源
毫无疑问,985院校是在所有层次学校是最好的,其他按上述顺序,无论是教研实力还是校园环境,最直观的表现可以查询各学校简介里拥有多少两院院士、长江学者、国家千人计划等等,还有博硕士点的数量以及图书馆的藏书量。
2.平台不一样,眼界不一样
学校越好,举办顶级学术活动越多,学校对外学术交流和合作的越多,提供深造的机会同样也越多。
3.学校不一样,氛围不一样
能考进越好学校的等于高考分数越高,这说明要不就是智商相对较高,要不就更勤奋和自主学习能力越强,总得来说综合能力更强。你大学四年周围的人以及学习氛围会对你的影响很大。可能很多人说大学里逃课打机颓废每间学校都会有,但可以肯定的是学校越好这部分人的比例越小。
4.学校不一样,你结识的人脉不一样
对你未来的帮助也不一样,这点在你将来步入社会可能体会更深,更好的学校毕业出来的学生普遍平台更高,所以可以获得的校友资源也更多。
5.社会对学校的认同度不一样
到你毕业出来找工作你会发现,很多企业就是认定非985、211的不要,很多企业就觉得非本科不要,如果你达不到就变成跨不过的门槛了。
毕竟随着近年来的不断扩招现在高校毕业生越来越多,就业机会的增长速度远远跟不上毕业生增长速度,供远远大于求,企业的选择太多了。
举个栗子:企业招聘一个人,有十位毕业生面试,五位211和五位非211,在第一轮大部分HR想都不会多想直接就筛掉后五位了。
虽然都说现在人人平等,但记住:平等不是完全对等,其实这个社会很容易潜移默化地给人划分阶级的,或以权力,或以金钱,或以学历……
>
@薪程
真人真事。
1.今年找工作投简历,我前面有三个同学,好像是哈理工的,hr看了一下简历,说了一句:同学对不起,我们不收你们学校的,简历都没让留。
2.也是找工作,在招聘现场遇到了一位本科同学(211研究生),我问他找的怎么样了,他说这些单位只收工大的学生。。。
3.我个人也是深有体会的,我是从普通211考到工大的,即使研究生是985了,但是找工作的时候依然被本科学校扯后腿。面试一汽的时候,面试官直接和我说了,你本科学校不好,被调剂了,如果你也是工大的本科,你就能去汽研了。。。
人总是往上走的,想要吃到更好的羊,你得有身皮才行。
这就好比去电影院看电影,你有了票你进去之后想看就看,不看还可以睡觉。但是你没有票,工作人员都不让你进去。
其实我个人认为能力应该是被看重的,但是你能证明你有能力吗?而且你去了好学校会发现,你周围的人的能力真的很强,来到工大之后,一直处于被吊打的状态。。。但是人家比我还要努力。。。
如果你要问本质区别,我认为是,当你没法在有限时间证明你的能力(比如找工作)的时候,你的学校毕业证最能证明你。
>
@匿名用户
我今年参加高考,现在大一在一个三本院校。
没错是三本,我匿了
你看我自己都自卑(ಥ_ಥ)
我觉得除了前面回答的那些之外综合起来就是:你在后青春的培养。你接触的人,见过的事,身边的一切直接影响你的气息。
气息没错,和你的同龄人我相信4年后,清北和3本的是不一样的。导致后面40年也是不一样的。
当你们颜值相当时 年轻的妹子们可能觉得:哇,清北学霸,3本好像都是本科也没差,但是当你们开始交谈后差距应该能显现。
况且生活中不只有妹子还有更现实的就像之前某答的HR论:我要是HR节约成本直接选学历高的。
当然个人与个人不一样,不是说除了985/211其他学校的学生就都是平庸的或者他们就一定优秀,只是概率更大。
作为一个依托一本大学的三本学院,我来说说直观感受。
身边的同学除了看剧打游戏谈恋爱没见到有想法的。各种社团活动,他们本部的楼道很清爽,我们各种宣传海报。我们的老师是本部的,但是然并卵。
985/211的师资,设施就不用说了吧。
我们没有设施,不过是财经类院校确实也用不到吧~
因为本人不在985/211所以用户体验我就不说啦。最后上两张图说明:


**END**
∑编辑 | Gemini
*来源 | 搜狐教育*
**更多精彩:**
☞ [哈尔莫斯:怎样做数学研究](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554187&idx=1&sn=35143b89b06fe4f5273f210b2d6a7c91&chksm=8b7e3290bc09bb86f7bb3f158d993df3f019a7e9ce3bc8897e164e35a2ebe5a4e0bdcc111089&scene=21#wechat_redirect)
☞ [扎克伯格2017年哈佛大学毕业演讲](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554187&idx=2&sn=c75293463823e4d6769638e54b64f3ec&chksm=8b7e3290bc09bb86dc1e3f8e78d0b6de8811d75f3dcb092766fcb8ba0bab1cd9ba1ddfcef3b9&scene=21#wechat_redirect)
☞ [线性代数在组合数学中的应用](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554141&idx=1&sn=74a74c4e4d08eba0dd734528aa0b08e7&chksm=8b7e32c6bc09bbd073b34c22004ac6e4d99c8a0caa64c7d3dbaa8fd55e6ef1fc87ed545b8b7e&scene=21#wechat_redirect)
☞ [你见过真的菲利普曲线吗?](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554105&idx=1&sn=224ab0d38fb57facea70081385360d58&chksm=8b7e3222bc09bb34d3b6df665087e64b233778ed427598d08e809f96261e898c1c0de6188bbc&scene=21#wechat_redirect)
☞ [支持向量机(SVM)的故事是这样子的](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554096&idx=1&sn=46783e6ace661a3ccbd8a6e00fb17bf9&chksm=8b7e322bbc09bb3d73dc240f2280bddf2ef8b7824a459a24bd7f6eeadd60edb96e690d467f6e&scene=21#wechat_redirect)
☞ [深度神经网络中的数学,对你来说会不会太难?](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554077&idx=2&sn=3ecd63f2205fd59df8c360c97c943ef6&chksm=8b7e3206bc09bb10a36b09547efe0c54f41423b180622c1fdc7f14747ccc8f8fecee3a12e2cd&scene=21#wechat_redirect)
☞ [编程需要知道多少数学知识?](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652554062&idx=1&sn=17f0a88d5e15d1adfc29c690a0b1b89b&chksm=8b7e3215bc09bb038c6caa59d0f49cedd929f9be1104beea3411186cf4c81de69efc71a17883&scene=21#wechat_redirect)
☞ [陈省身——什么是几何学](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553994&idx=2&sn=74f67a1a3ac5c705f51f2ba619b717f6&chksm=8b7e3251bc09bb47dce73319948780081efe0333ffae99ea04a9eeabbcfcb38a29b4b73fb7c1&scene=21#wechat_redirect)
☞ [模式识别研究的回顾与展望](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553949&idx=2&sn=d171680964df774397efd9db81c00347&chksm=8b7e3386bc09ba90bf0f6e1cabf82ba86ff94630cb5ee2e0f14ff9455db52be32ddbc289d237&scene=21#wechat_redirect)
☞ [曲面论](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553747&idx=1&sn=e25f866d510cf2338b6d9e1b32bafb62&chksm=8b7e3348bc09ba5ea1caaf2a7bfcd80a7e7559b1983e473eda2206e56df7f38ef3cecf2f77c7&scene=21#wechat_redirect)
☞ [自然底数e的意义是什么?](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553811&idx=1&sn=000305074471c3d4c681c9cfd4e4bc93&chksm=8b7e3308bc09ba1e3043f5568a3a75a045285a1de97e4da36918bac68e7c6d579ad5d8cc25ab&scene=21#wechat_redirect)
☞ [如何向5岁小孩解释什么是支持向量机(SVM)?](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553670&idx=1&sn=ea75a448c016f7229e4cb298f6017614&chksm=8b7e309dbc09b98bc622acdf1223c7c2f743609d0a577dd43c9e9d98ab4da4314be7c1002bd5&scene=21#wechat_redirect)
☞ [华裔天才数学家陶哲轩自述](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553646&idx=2&sn=bbf8f1be1ca1c66ad3f3270babea6885&chksm=8b7e30f5bc09b9e3e1a4fa735412e2fcb20df9e78f2f346bf578018ceab77de6326095d1bf71&scene=21#wechat_redirect)
☞ [代数,分析,几何与拓扑,现代数学的三大方法论](http://mp.weixin.qq.com/s?__biz=MzA5ODUxOTA5Mg==&mid=2652553596&idx=1&sn=bc5064e871831f862db6d19c3de6327e&chksm=8b7e3027bc09b93194fa09b25e2df400421c062927bb9120912875f8aaf0bb25553fc8f51e3b&scene=21#wechat_redirect)

算法数学之美微信公众号欢迎赐稿
稿件涉及数学、物理、算法、计算机、编程等相关领域,经采用我们将奉上稿酬。
投稿邮箱:math_alg@163.com
|
Markdown
|
UTF-8
| 1,035 | 3.15625 | 3 |
[] |
no_license
|
# realm-android-app
O objetivo deste experimento é construir um aplicativo que gerencie quadros de tarefas, utilizando a biblioteca Realm para a persistência dos dados. Para enriquecer ainda mais a experiência, escreveremos a lógica utilizando a linguagem Kotlin. :yum:
### Requisitos mínimos :white_check_mark:
* Um quadro deve ter um nome, data de criação e uma lista de tarefas;
* Uma tarefa deve ter uma descrição, data de criação e um indicador de estado (completa ou ativa);
* Deve ser possível realizar o cadastro de quadros;
* Deve ser possível realizar o cadastro de tarefas dentro de quadros;
* A aplicação deve apresentar uma listagem de quadros, apenas com informações básicas;
* Ao clicar em um quadro, deve ser possível visualizar seu conteúdo;
* O quadro deve permitir um meio de adicionar tarefas dentro de si;
### Bônus :star2:
* Permitir a edição das informações de um quadro;
* Permitir a edição de uma tarefa;
* Permitir a exclusão de um quadro;
* Permitir a exclusão de uma tarefa;
|
C++
|
UTF-8
| 1,348 | 2.84375 | 3 |
[] |
no_license
|
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 32, &Wire);
void setup() {
Serial.begin(9600);
Serial.println("OLED FeatherWing test");
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Address 0x3C for 128x32
Serial.println("OLED begun");
// Show image buffer on the display hardware.
// Since the buffer is intialized with an Adafruit splashscreen
// internally, this will display the splashscreen.
display.display();
delay(1000);
// Clear the buffer.
display.clearDisplay();
display.display();
// text display tests
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.print("Prueba pantalla OLED:");
display.print("Hola Mundo!!!");
display.setCursor(0,0);
display.display(); // actually display all of the above
delay(2000);
display.clearDisplay();
display.display();
}
void loop() {
display.drawPixel(0, 0, WHITE);
display.drawPixel(127, 0, WHITE);
display.drawPixel(0, 31, WHITE);
display.drawPixel(127, 31, WHITE);
display.setCursor(0,10);
display.println("Hola Mundo Arduino!!");
display.display();
delay(500);
display.clearDisplay();
display.display();
delay(500);
}
|
Java
|
UTF-8
| 644 | 2.875 | 3 |
[] |
no_license
|
package com.aweful.PdfBox;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws IOException
{
System.out.println( "Hello World!" );
PDDocument document = new PDDocument();
for(int i=0; i<10; i++){
PDPage my_page = new PDPage();
document.addPage(my_page);
}
document.save("C:\\Users\\amcdonald\\Desktop\\myDoc.pdf");
System.out.println("PDF Created");
document.close();
}
}
|
Python
|
UTF-8
| 16,061 | 3.03125 | 3 |
[
"LicenseRef-scancode-other-permissive",
"MIT"
] |
permissive
|
from aerosandbox import AeroSandboxObject
from aerosandbox.geometry.common import *
from typing import List, Dict, Any, Union, Tuple, Optional
from pathlib import Path
import aerosandbox.geometry.mesh_utilities as mesh_utils
import copy
class Fuselage(AeroSandboxObject):
"""
Definition for a fuselage or other slender body (pod, etc.).
For now, all fuselages are assumed to be circular and fairly closely aligned with the body x axis. (<10 deg or
so) # TODO update if this changes
"""
def __init__(self,
name: str = "Untitled",
xsecs: List['FuselageXSec'] = None,
analysis_specific_options: Optional[Dict[type, Dict[str, Any]]] = None,
symmetric: bool = False, # Deprecated
xyz_le: np.ndarray = None, # Deprecated
):
"""
Defines a new fuselage.
Args:
name: Name of the fuselage [optional]. It can help when debugging to give each fuselage a sensible name.
xsecs: A list of fuselage cross ("X") sections in the form of FuselageXSec objects.
analysis_specific_options: Analysis-specific options are additional constants or modeling assumptions
that should be passed on to specific analyses and associated with this specific geometry object.
This should be a dictionary where:
* Keys are specific analysis types (typically a subclass of asb.ExplicitAnalysis or
asb.ImplicitAnalysis), but if you decide to write your own analysis and want to make this key
something else (like a string), that's totally fine - it's just a unique identifier for the
specific analysis you're running.
* Values are a dictionary of key:value pairs, where:
* Keys are strings.
* Values are some value you want to assign.
This is more easily demonstrated / understood with an example:
>>> analysis_specific_options = {
>>> asb.AeroBuildup: dict(
>>> include_wave_drag=True,
>>> )
>>> }
"""
### Set defaults
if xsecs is None:
xsecs: List['FuselageXSec'] = []
if analysis_specific_options is None:
analysis_specific_options = {}
### Initialize
self.name = name
self.xsecs = xsecs
self.analysis_specific_options = analysis_specific_options
### Handle deprecated parameters
if symmetric:
import warnings
warnings.warn(
"The `symmetric` argument for Fuselage objects will be deprecated soon. Make your fuselages separate instead!",
stacklevel=2
)
self.symmetric = symmetric
if xyz_le is not None:
import warnings
warnings.warn(
"The `xyz_le` input for Fuselage is DEPRECATED and will be removed in a future version. Use Fuselage().translate(xyz) instead.",
stacklevel=2
)
self.xsecs = [
xsec.translate(xyz_le)
for xsec in self.xsecs
]
def __repr__(self) -> str:
n_xsecs = len(self.xsecs)
return f"Fuselage '{self.name}' ({len(self.xsecs)} {'xsec' if n_xsecs == 1 else 'xsecs'})"
def translate(self,
xyz: np.ndarray
):
"""
Translates the entire Fuselage by a certain amount.
Args:
xyz:
Returns: self
"""
new_fuse = copy.copy(self)
new_fuse.xsecs = [
xsec.translate(xyz)
for xsec in new_fuse.xsecs
]
return new_fuse
def area_wetted(self) -> float:
"""
Returns the wetted area of the fuselage.
If the Fuselage is symmetric (i.e. two symmetric wingtip pods),
returns the combined wetted area of both pods.
:return:
"""
area = 0
for i in range(len(self.xsecs) - 1):
this_radius = self.xsecs[i].radius
next_radius = self.xsecs[i + 1].radius
x_separation = self.xsecs[i + 1].xyz_c[0] - self.xsecs[i].xyz_c[0]
area += np.pi * (this_radius + next_radius) * np.sqrt(
(this_radius - next_radius) ** 2 + x_separation ** 2)
if self.symmetric:
area *= 2
return area
def area_projected(self) -> float:
"""
Returns the area of the fuselage as projected onto the XY plane (top-down view).
If the Fuselage is symmetric (i.e. two symmetric wingtip pods),
returns the combined projected area of both pods.
:return:
"""
area = 0
for i in range(len(self.xsecs) - 1):
this_radius = self.xsecs[i].radius
next_radius = self.xsecs[i + 1].radius
x_separation = self.xsecs[i + 1].xyz_c[0] - self.xsecs[i].xyz_c[0]
area += (this_radius + next_radius) * x_separation
if self.symmetric:
area *= 2
return area
def area_base(self) -> float:
"""
Returns the area of the base (i.e. "trailing edge") of the fuselage. Useful for certain types of drag
calculation.
Returns:
"""
return np.pi * self.xsecs[-1].radius ** 2
def fineness_ratio(self) -> float:
"""
Approximates the fineness ratio using the volume and length.
Formula derived from a generalization of the relation from a cylindrical fuselage.
For a cylindrical fuselage, FR = l/d, where l is the length and d is the diameter.
Returns:
"""
return np.sqrt(
self.length() ** 3 / self.volume() * np.pi / 4
)
def length(self) -> float:
"""
Returns the total front-to-back length of the fuselage. Measured as the difference between the x-coordinates
of the leading and trailing cross sections.
:return:
"""
return np.fabs(self.xsecs[-1].xyz_c[0] - self.xsecs[0].xyz_c[0])
def volume(self) -> float:
"""
Gives the volume of the Fuselage.
Returns:
Fuselage volume.
"""
volume = 0
for xsec_a, xsec_b in zip(self.xsecs, self.xsecs[1:]):
h = np.abs(xsec_b.xyz_c[0] - xsec_a.xyz_c[0])
r_a = xsec_a.radius
r_b = xsec_b.radius
volume += np.pi * h / 3 * (
r_a ** 2 + r_a * r_b + r_b ** 2
)
return volume
def x_centroid_projected(self) -> float:
"""
Returns the x_g coordinate of the centroid of the planform area.
"""
total_x_area_product = 0
total_area = 0
for xsec_a, xsec_b in zip(self.xsecs, self.xsecs[1:]):
x = (xsec_a.xyz_c[0] + xsec_b.xyz_c[0]) / 2
area = (xsec_a.radius + xsec_b.radius) / 2 * np.abs(xsec_b.xyz_c[0] - xsec_a.xyz_c[0])
total_area += area
total_x_area_product += x * area
x_centroid = total_x_area_product / total_area
return x_centroid
def mesh_body(self,
method="quad",
chordwise_resolution: int = 1,
spanwise_resolution: int = 36,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Meshes the fuselage as a solid (thickened) body.
Uses the `(points, faces)` standard mesh format. For reference on this format, see the documentation in
`aerosandbox.geometry.mesh_utilities`.
Args:
method: Allows choice between "tri" and "quad" meshing.
chordwise_resolution: Controls the chordwise resolution of the meshing.
spanwise_resolution: Controls the spanwise resolution of the meshing.
TODO add mesh_trailing_edge argument.
Returns: (points, faces) in standard mesh format.
"""
theta = np.linspace(
0,
2 * np.pi,
spanwise_resolution + 1,
)[:-1]
x_nondim = np.sin(theta)
y_nondim = np.cos(theta)
chordwise_strips = []
for x_n, y_n in zip(x_nondim, y_nondim):
chordwise_strips.append(
self.mesh_line(
x_nondim=x_n,
y_nondim=y_n,
chordwise_resolution=chordwise_resolution
)
)
points = np.concatenate(chordwise_strips)
faces = []
num_i = len(chordwise_strips)
num_j = chordwise_resolution * (len(self.xsecs) - 1)
def index_of(iloc, jloc):
return jloc + (iloc % spanwise_resolution) * (num_j + 1)
def add_face(*indices):
entry = list(indices)
if method == "quad":
faces.append(entry)
elif method == "tri":
faces.append([entry[0], entry[1], entry[3]])
faces.append([entry[1], entry[2], entry[3]])
for i in range(num_i):
for j in range(num_j):
add_face(
index_of(i, j),
index_of(i, j + 1),
index_of(i + 1, j + 1),
index_of(i + 1, j),
)
faces = np.array(faces)
if self.symmetric:
flipped_points = np.array(points)
flipped_points[:, 1] = flipped_points[:, 1] * -1
points, faces = mesh_utils.stack_meshes(
(points, faces),
(flipped_points, faces)
)
return points, faces
def mesh_line(self,
x_nondim: Union[float, List[float]] = 0,
y_nondim: Union[float, List[float]] = 0,
chordwise_resolution: int = 1,
) -> np.ndarray:
xsec_points = []
try:
if len(x_nondim) != len(self.xsecs):
raise ValueError(
"If x_nondim is going to be an iterable, it needs to be the same length as Fuselage.xsecs."
)
except TypeError:
pass
try:
if len(y_nondim) != len(self.xsecs):
raise ValueError(
"If y_nondim is going to be an iterable, it needs to be the same length as Fuselage.xsecs."
)
except TypeError:
pass
for i, xsec in enumerate(self.xsecs):
origin = xsec.xyz_c
xg_local, yg_local, zg_local = self._compute_frame_of_FuselageXSec(i)
try:
xsec_x_nondim = x_nondim[i]
except (TypeError, IndexError):
xsec_x_nondim = x_nondim
try:
xsec_y_nondim = y_nondim[i]
except (TypeError, IndexError):
xsec_y_nondim = y_nondim
xsec_point = origin + (
xsec_x_nondim * xsec.radius * yg_local +
xsec_y_nondim * xsec.radius * zg_local
)
xsec_points.append(xsec_point)
mesh_sections = []
for i in range(len(xsec_points) - 1):
mesh_section = np.linspace(
xsec_points[i],
xsec_points[i + 1],
chordwise_resolution + 1
)
if not i == len(xsec_points) - 2:
mesh_section = mesh_section[:-1]
mesh_sections.append(mesh_section)
mesh = np.concatenate(mesh_sections)
return mesh
def draw(self, *args, **kwargs):
"""
An alias to the more general Airplane.draw() method. See there for documentation.
Args:
*args: Arguments to pass through to Airplane.draw()
**kwargs: Keyword arguments to pass through to Airplane.draw()
Returns: Same return as Airplane.draw()
"""
from aerosandbox.geometry.airplane import Airplane
return Airplane(fuselages=[self]).draw(*args, **kwargs)
def _compute_frame_of_FuselageXSec(self, index: int):
if index == len(self.xsecs) - 1:
index = len(self.xsecs) - 2 # The last FuselageXSec has the same frame as the last section.
xyz_c_a = self.xsecs[index].xyz_c
xyz_c_b = self.xsecs[index + 1].xyz_c
vector_between = xyz_c_b - xyz_c_a
xg_local_norm = np.linalg.norm(vector_between)
if xg_local_norm != 0:
xg_local = vector_between / xg_local_norm
else:
xg_local = np.array([1, 0, 0])
zg_local = np.array([0, 0, 1]) # TODO
yg_local = np.cross(zg_local, xg_local)
return xg_local, yg_local, zg_local
class FuselageXSec(AeroSandboxObject):
"""
Definition for a fuselage cross section ("X-section").
"""
def __init__(self,
xyz_c: Union[np.ndarray, List] = np.array([0, 0, 0]),
radius: float = 0,
analysis_specific_options: Optional[Dict[type, Dict[str, Any]]] = None,
):
"""
Defines a new fuselage cross section.
Args:
xyz_c: An array-like that represents the xyz-coordinates of the center of this fuselage cross section,
in geometry axes.
radius: Radius of the fuselage cross section.
analysis_specific_options: Analysis-specific options are additional constants or modeling assumptions
that should be passed on to specific analyses and associated with this specific geometry object.
This should be a dictionary where:
* Keys are specific analysis types (typically a subclass of asb.ExplicitAnalysis or
asb.ImplicitAnalysis), but if you decide to write your own analysis and want to make this key
something else (like a string), that's totally fine - it's just a unique identifier for the
specific analysis you're running.
* Values are a dictionary of key:value pairs, where:
* Keys are strings.
* Values are some value you want to assign.
This is more easily demonstrated / understood with an example:
>>> analysis_specific_options = {
>>> asb.AeroBuildup: dict(
>>> include_wave_drag=True,
>>> )
>>> }
"""
### Set defaults
if analysis_specific_options is None:
analysis_specific_options = {}
### Initialize
self.xyz_c = np.array(xyz_c)
self.radius = radius
self.analysis_specific_options = analysis_specific_options
def __repr__(self) -> str:
return f"FuselageXSec (xyz_c: {self.xyz_c}, radius: {self.radius})"
def xsec_area(self):
"""
Returns the FuselageXSec's cross-sectional (xsec) area.
:return:
"""
return np.pi * self.radius ** 2
def translate(self,
xyz: np.ndarray
) -> "FuselageXSec":
"""
Returns a copy of this FuselageXSec that has been translated by `xyz`.
Args:
xyz: The amount to translate the FuselageXSec. Given as a 3-element NumPy vector.
Returns: A new FuselageXSec object.
"""
new_xsec = copy.copy(self)
new_xsec.xyz_c = new_xsec.xyz_c + np.array(xyz)
return new_xsec
if __name__ == '__main__':
fuse = Fuselage(
xyz_le=[0, 0, 2],
xsecs=[
FuselageXSec(
xyz_c=[0, 0, 1],
radius=0,
),
FuselageXSec(
xyz_c=[1, 0, 1],
radius=0.3,
),
FuselageXSec(
xyz_c=[2, 0, 1],
radius=0.2,
)
]
)
fuse.draw()
|
JavaScript
|
UTF-8
| 10,565 | 2.640625 | 3 |
[] |
no_license
|
"use strict";
var canvas;
var gl;
var points = [];
var colors = [];
var NumTimesToSubdivide = 3;
var theta = [-10, 225, 0];
var thetaLoc;
var vertices = [vec3( -0.5, -0.5, -0.5),
vec3( -0.5, -0.5, 0.5),
vec3( -0.5, 0.5, -0.5),
vec3( -0.5, 0.5, 0.5),
vec3( 0.5, -0.5, -0.5),
vec3( 0.5, -0.5, 0.5),
vec3( 0.5, 0.5, -0.5),
vec3( 0.5, 0.5, 0.5)];
var rotating = false;
var cursorStart;
function clone(arr1, arr2){
//arr1 = source, arr2 = dest
//quicker (for me) than using the polyfill for Array.from and forEach
for (var i=0; i<arr1.length; ++i){
arr2.push(arr1[i]);
}
}
function retpush(arr1, item){
arr1.push(item);
return arr1;
}
function cubes_equal(cube1, cube2){
if (cube1.length != cube2.length){
return false;
}
for (var i = 0; i < cube1.length; ++i){
if (cube1[i].length != cube2[i].length) {return false;}
for (var j = 0; j < cube1[i].length; ++j){
if (Math.round(cube1[i][j]*100000)/100000 != Math.round(cube2[i][j]*100000)/100000){
return false;
}
}
}
return true;
}
function v3compare(a, b){
//trivial case
if (a == b){
return 0;
}
//first, enforce this order: ---, --+, -+-, -++, +--, +-+, ++-, +++
/*var sign_a = (a[0] > 0 ? 4 : 0)|(a[1] > 0 ? 2 : 0)|(a[2] > 0 ? 1 : 0);
var sign_b = (b[0] > 0 ? 4 : 0)|(b[1] > 0 ? 2 : 0)|(b[2] > 0 ? 1 : 0);
if (sign_a != sign_b){
return sign_a - sign_b;
}*/
//make sure numbers that are /really/ close count as equal
for (var i=0; i<a.length; ++i){
a[i] = Math.round(a[i]*100000)/100000;
b[i] = Math.round(b[i]*100000)/100000;
}
/*
var xdiff = a[0]-b[0];
if (xdiff != 0){ return xdiff;}
var ydiff = a[1]-b[1];
if (ydiff != 0){ return ydiff;}
var zdiff = a[2]-b[2];
if (zdiff != 0){ return zdiff;}
return 0;
*/
var diff_a = ((a[0] > b[0]) ? 4 : 0)|((a[1] > b[1]) ? 2 : 0)|((a[2] > b[2]) ? 1 : 0);
var diff_b = ((a[0] < b[0]) ? 4 : 0)|((a[1] < b[1]) ? 2 : 0)|((a[2] < b[2]) ? 1 : 0);
//console.log(a, b, diff_a, diff_b);
return diff_a - diff_b;
}
function group_planes(arr){
//take in a (sorted) array of vertices, and return 8 groups of co-planar vertices, two for each dimension
var x1 = [ arr[0] ];
var x2 = [];
var y1 = [ arr[0] ];
var y2 = [];
var z1 = [ arr[0] ];
var z2 = [];
for (var i = 1; i < arr.length; ++i){
if (arr[i][0] == arr[0][0]){
x1.push(arr[i]);
}
else { x2.push(arr[i]); }
if (arr[i][1] == arr[0][1]){
y1.push(arr[i]);
}
else { y2.push(arr[i]); }
if (arr[i][2] == arr[0][2]){
z1.push(arr[i]);
}
else { z2.push(arr[i]); }
}
return [ x1, y1, z1, x2, y2, z2 ];
}
function translate(verts, axes, amount){
//x = 1, y = 2, z = 4
var res = [];
for (var i = 0; i < verts.length; ++i){
var tmp = [];
if (axes & 1){
tmp.push(verts[i][0]+amount);
}
else tmp.push(verts[i][0]);
if (axes & 2){
tmp.push(verts[i][1]+ amount);
}
else tmp.push(verts[i][1]);
if (axes & 4){
tmp.push(verts[i][2] + amount);
}
else tmp.push(verts[i][2]);
res.push(tmp);
}
return res;
}
function test_v3compare(){
//test the initial cube, which has vectors with differently signed components
//but equal absolute values
var sorted_testcube0 = [];
console.log("Test 0 - all vectors equal absolute value; different sign");
clone(vertices, sorted_testcube0);
sorted_testcube0.sort(v3compare);
console.log(vertices);
console.log(sorted_testcube0);
console.log(cubes_equal(vertices, sorted_testcube0));
var testcube1 = [vec3(-0.5, 0.16667, 0.16667),
vec3(-0.5, 0.16667, 0.5),
vec3(-0.5, 0.5, 0.16667),
vec3(-0.5, 0.5, 0.5),
vec3(-0.16667, 0.16667, 0.16667),
vec3(-0.16667, 0.16667, 0.5),
vec3(-0.16667, 0.5, 0.16667),
vec3(-0.16667, 0.5, 0.5)];
var sorted_testcube1 = [];
clone(testcube1, sorted_testcube1);
sorted_testcube1.sort(v3compare);
console.log("Test 1 - all vectors equal sign");
console.log(testcube1);
console.log(sorted_testcube1);
console.log(cubes_equal(testcube1, sorted_testcube1));
}
window.onload = function init()
{
canvas = document.getElementById( "gl-canvas" );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" ); }
//
// Initialize our data for the Sierpinski Gasket
//
// First, initialize the vertices of our 3D gasket
// Four vertices on unit circle
// Intial tetrahedron with equal length sides
var args = [];
clone(vertices, args);
args.push(NumTimesToSubdivide);
divideCube.apply(this, args);
//
// Configure WebGL
//
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 0.3, 0.3, 0.3, 1.0 );
// enable hidden-surface removal
gl.enable(gl.DEPTH_TEST);
// Load shaders and initialize attribute buffers
var program = initShaders( gl, "vertex-shader", "fragment-shader" );
gl.useProgram( program );
// Create a buffer object, initialize it, and associate it with the
// associated attribute variable in our vertex shader
var cBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(colors), gl.STATIC_DRAW );
var vColor = gl.getAttribLocation( program, "vColor" );
gl.vertexAttribPointer( vColor, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vColor );
var vBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW );
var vPosition = gl.getAttribLocation( program, "vPosition" );
gl.vertexAttribPointer( vPosition, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vPosition );
thetaLoc = gl.getUniformLocation(program, "theta");
canvas.onmousedown = function(event){
rotating = true;
cursorStart = [event.clientX, event.clientY];
}
canvas.onmousemove = function(event){
if (rotating != false){
var cursorEnd = [event.clientX, event.clientY];
theta[1] += (cursorEnd[0]-cursorStart[0]);
theta[0] += (cursorEnd[1]-cursorStart[1]);
requestAnimFrame(render);
cursorStart = cursorEnd;
}
}
canvas.onmouseup = function(event){
rotating = false;
}
render();
};
function triangle( a, b, c, color )
{
// add colors and vertices for one triangle
var baseColors = [
vec3(0.0, 0.5, 0.0),
vec3(0.0, 0.0, 0.0),
vec3(0.5, 0.0, 0.25),
vec3(1.0, 0.0, 0.0),
vec3(0.0, 0.0, 0.5),
vec3(1.0, 0.5, 0.0)
];
colors.push( baseColors[color] );
points.push( a );
colors.push( baseColors[color] );
points.push( b );
colors.push( baseColors[color] );
points.push( c );
}
function square( a, b, c, d, color)
{
var sq = [a, b, c, d].sort();
triangle(sq[0], sq[1], sq[2], color);
triangle(sq[1], sq[3], sq[2], color);
}
function cube( a, b, c, d, e, f, g, h)
{
var cb = [a, b, c, d, e, f, g, h].sort(v3compare);
cb = group_planes(cb);
for (var i=0; i<cb.length; ++i){
square.apply(this, retpush(cb[i], i));
}
}
function divideCube( a, b, c, d, e, f, g, h, count)
{
if ( count === 0 ) {
cube( a, b, c, d, e, f, g, h);
}
else {
//first cube with corner at vertex a:
//a, ab, abdc, ad, ae, aebf, aedh, aedhbcfg
var cb = [a, b, c, d, e, f, g, h].sort(v3compare);
a = cb[3]; b = cb[2]; c = cb[6]; d = cb[7];
e = cb[1]; f = cb[0]; g = cb[4]; h = cb[5];
var ab = mix(a, b, 1/3);
var dc = mix(d, c, 1/3);
var abdc = mix(ab, dc, 1/3);
var ad = mix(a, d, 1/3);
var ae = mix(a, e, 1/3);
var bf = mix(b, f, 1/3);
var aebf = mix(ae, bf, 1/3);
var dh = mix(d, h, 1/3);
var aedh = mix(ae, dh, 1/3);
var bc = mix(b, c, 1/3);
var fg = mix(f, g, 1/3);
var bcfg = mix(bc, fg, 1/3);
var aedhbcfg = mix(aedh, bcfg, 1/3);
--count;
var tlen = ad[0]-a[0];
//now, all the cubes
var cube1 = [a, ab, abdc, ad, ae, aebf, aedh, aedhbcfg];
var cube2 = translate(cube1, 1, ad[0]-a[0]);
var cube3 = translate(cube2, 1, ad[0]-a[0]);
var cube4 = translate(cube1, 4, ab[2]-a[2]);
var cube5 = translate(cube4, 4, ab[2]-a[2]);
var cube6 = translate(cube5, 1, ad[0]-a[0]);
var cube7 = translate(cube6, 1, ad[0]-a[0]);
var cube8 = translate(cube3, 4, ab[2]-a[2]);
var cube1r = translate(cube1, 2, (ae[1]-a[1])*2);
var cube2r = translate(cube2, 2, (ae[1]-a[1])*2);
var cube3r = translate(cube3, 2, (ae[1]-a[1])*2);
var cube4r = translate(cube4, 2, (ae[1]-a[1])*2);
var cube5r = translate(cube5, 2, (ae[1]-a[1])*2);
var cube6r = translate(cube6, 2, (ae[1]-a[1])*2);
var cube7r = translate(cube7, 2, (ae[1]-a[1])*2);
var cube8r = translate(cube8, 2, (ae[1]-a[1])*2);
var cube1m = translate(cube1, 2, ae[1]-a[1]);
var cube2m = translate(cube3, 2, ae[1]-a[1]);
var cube3m = translate(cube5, 2, ae[1]-a[1]);
var cube4m = translate(cube7, 2, ae[1]-a[1]);
divideCube.apply(this, retpush(cube1, count));
divideCube.apply(this, retpush(cube2, count));
divideCube.apply(this, retpush(cube3, count));
divideCube.apply(this, retpush(cube4, count));
divideCube.apply(this, retpush(cube5, count));
divideCube.apply(this, retpush(cube6, count));
divideCube.apply(this, retpush(cube7, count));
divideCube.apply(this, retpush(cube8, count));
divideCube.apply(this, retpush(cube1r, count));
divideCube.apply(this, retpush(cube2r, count));
divideCube.apply(this, retpush(cube3r, count));
divideCube.apply(this, retpush(cube4r, count));
divideCube.apply(this, retpush(cube5r, count));
divideCube.apply(this, retpush(cube6r, count));
divideCube.apply(this, retpush(cube7r, count));
divideCube.apply(this, retpush(cube8r, count));
divideCube.apply(this, retpush(cube1m, count));
divideCube.apply(this, retpush(cube2m, count));
divideCube.apply(this, retpush(cube3m, count));
divideCube.apply(this, retpush(cube4m, count));
}
}
function render()
{
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.uniform3fv(thetaLoc, theta);
gl.drawArrays( gl.TRIANGLES, 0, points.length );
}
|
Python
|
UTF-8
| 22,277 | 2.890625 | 3 |
[] |
no_license
|
# coding:utf-8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mountain_car_env import MountainCarEnv
from random import sample, seed
class GridCoder:
'''
网格编码
'''
def __init__(self, size_arr, obs_low, obs_scale):
'''
不同维度上的网格大小
size_arr
'''
self.size_arr = np.array(size_arr)
self.dim_num = len(self.size_arr)
self.dim_w = np.ones(self.dim_num)
self.obs_low = obs_low
self.obs_scale = obs_scale
w = 1
for i, axis_size in enumerate(reversed(size_arr)):
self.dim_w[self.dim_num - i - 1] = w
w *= axis_size
self.state_num = w
def __call__(self, states=()):
'''
将观测值向量转化为 坐标
states 特征值 向量 即观测值映射从[下界,上界]到[0, 1]的映射 分位数
action 动作
返回 Q值坐标 (position, action)
'''
position = np.floor((np.array(states[:2]) - self.obs_low) / self.obs_scale * self.size_arr) @ self.dim_w
return int(position)
class TileCoder:
'''
砖瓦编码
'''
def __init__(self, layers, features):
'''
layers 要用到几层砖瓦编码
features 砖瓦编码应该得到多少特征
'''
self.layers = layers
self.features = features
self.codebook = {}
def get_feature(self, codeword):
'''
codeword 数据坐标(层数 坐标 坐标 动作)
'''
if codeword in self.codebook:
return self.codebook[codeword]
count = len(self.codebook)
if count >= self.features: # 冲突处理
return hash(codeword) % self.features
else:
self.codebook[codeword] = count
return count
def __call__(self, floats=(), ints=()):
'''
将观测值向量转化为 坐标
floats 特征值 向量 即观测值映射从[下界,上界]到[0, 1]的映射 分位数
ints 动作
返回 features 不同层次的编码的位置1*feature_num的向量
'''
scaled_floats = tuple(f * self.layers * self.layers for f in floats)
features = []
for layer in range(self.layers):
codeword = (layer,) + tuple(int((f + layer) / self.layers) for f in scaled_floats) + ints
feature = self.get_feature(codeword)
features.append(feature)
return features
class TileCoderMAT(TileCoder):
'''
砖瓦编码
'''
def __init__(self, layers, feature_n, action_n):
'''
layers 要用到几层砖瓦编码
features 砖瓦编码应该得到多少特征
'''
self.layers = layers
self.feature_n = feature_n
self.codeword_w = np.ones(feature_n + 2)
self.codeword_w[0] = action_n
for i in range(self.feature_n):
self.codeword_w[i + 1] = self.codeword_w[i] * layers
def __call__(self, floats=(), ints=()):
'''
将观测值向量转化为 坐标
floats 特征值 向量 即观测值映射从[下界,上界]到[0, 1]的映射 分位数
ints 动作
返回 features 不同层次的编码的位置1*feature_num的向量
'''
scaled_floats = tuple(f * self.layers * self.layers for f in floats)
features = []
for layer in range(self.layers):
codeword = (layer,) + tuple(int((f + layer) / self.layers) for f in scaled_floats) + ints
feature = np.array(codeword) @ self.codeword_w
features.append(feature)
return features
class Agent:
'''
智能体
'''
def __init__(self, env):
self.action_n = env.action_space.n # 动作数
def decide(self, observation):
'''
决策函数
observation 状态观测值 (位置 速度 时间)
'''
return np.random.randint(self.action_n)
def encode(self, observation, action):
'''
将观测值编码为数据坐标值 index
observation 状态观测值
action 动作
'''
states = tuple((observation[:2] - self.obs_low) / self.obs_scale)
actions = (action,)
return self.encoder(states, actions)
def get_q(self, observation, action):
'''
获取动作价值
observation 状态观测值 (位置 速度 时间)
action 动作 0, 1, 2
'''
features = self.encode(observation[:2], action)
return self.w[features].sum()
def learn(self, observation, action, reward, time_interval, next_observation, done, next_action):
'''
学习函数
observation 状态观测值 位置 速度
action 动作
reward 奖励
next_state 下一状态 观测值
done 是否完成
next_action 下一动作
'''
pass
class RandomAgent(Agent):
'''
随机决策智能体
'''
def decide(self, observation):
'''
决策函数
observation 状态观测值 (位置 速度 时间)
'''
return np.random.randint(self.action_n)
class SARSAAgent(Agent):
def __init__(self, env, layers=8, features=1893, gamma=1., learning_rate=0.03, epsilon=0.001):
'''
学习函数
env 环境
layers 要用到几层砖瓦编码
features 砖瓦编码应该得到多少特征 总特征数 8*8 + (8+1) * (8+1) * (8-1)
gamma 收益衰减速率
learning_rate 学习速率
epsilon 执行探索策略概率
'''
self.action_n = env.action_space.n # 动作数
self.obs_low = env.observation_space.low
self.obs_scale = env.observation_space.high - env.observation_space.low # 观测空间范围
self.encoder = TileCoder(layers, features) # 砖瓦编码器
self.w = np.zeros(features) # 权重
self.gamma = gamma # 折扣
self.learning_rate = learning_rate # 学习率
self.epsilon = epsilon # 探索
def encode(self, observation, action):
'''
将观测值编码为数据坐标值 index
observation 状态观测值
action 动作
'''
states = tuple((observation[:2] - self.obs_low) / self.obs_scale)
actions = (action,)
return self.encoder(states, actions)
def get_q(self, observation, action):
'''
获取动作价值
observation 状态观测值 (位置 速度 时间)
action 动作 0, 1, 2
'''
features = self.encode(observation[:2], action)
return self.w[features].sum()
def decide(self, observation):
'''
决策函数
observation 状态观测值 (位置 速度 时间)
'''
if np.random.rand() < self.epsilon:
return np.random.randint(self.action_n)
else:
qs = [self.get_q(observation, action) for action in range(self.action_n)]
return np.argmax(qs)
def learn(self, observation, action, reward, time_interval, next_observation, done, next_action):
'''
学习函数
observation 状态观测值 位置 速度
action 动作
reward 奖励
next_state 下一状态 观测值
done 是否完成
next_action 下一动作
'''
u = reward + (1. - done) * self.gamma * self.get_q(next_observation, next_action)
td_error = u - self.get_q(observation, action)
features = self.encode(observation, action)
self.w[features] += (self.learning_rate * td_error * time_interval)
class SARSALambdaAgent(SARSAAgent):
'''
SARSA(λ)算法
'''
def __init__(self, env, layers=8, features=1893, gamma=1.,
learning_rate=0.03, epsilon=0.001, lambd=0.9):
super().__init__(env=env, layers=layers, features=features,
gamma=gamma, learning_rate=learning_rate, epsilon=epsilon)
self.lambd = lambd
self.z = np.zeros(features) # 初始化资格迹
def learn(self, observation, action, reward, time_interval, next_observation, done, next_action):
u = reward
if not done:
u += (self.gamma * self.get_q(next_observation, next_action))
self.z *= (self.gamma * self.lambd)
features = self.encode(observation, action)
self.z[features] = 1. # 替换迹
td_error = u - self.get_q(observation, action)
self.w += (self.learning_rate * td_error * self.z * time_interval)
if done:
self.z = np.zeros_like(self.z) # 为下一回合初始化资格迹
class DiffAgent(SARSAAgent):
'''
异策略回合更新策略寻找最优策略
'''
def __init__(self, env, layers=8, features=1893, gamma=1., learning_rate=0.03, epsilon=0.001):
SARSAAgent.__init__(self, env, layers, features, gamma, learning_rate, epsilon)
self.c = np.zeros_like(self.w)
self.layer_n = layers
def learn(self, trajectory):
'''
学习函数
observation 状态观测值 位置 速度
action 动作
reward 奖励
next_state 下一状态 观测值
done 是否完成
next_action 下一动作
'''
# rho = np.ones(self.layer_n)
for observation, action, reward, time_interval, next_observation, done, next_action in reversed(trajectory):
u = reward + (1. - done) * self.gamma * self.get_q(next_observation, next_action)
td_error = u - self.get_q(observation, action)
features = self.encode(observation, action)
self.w[features] += (self.learning_rate * td_error * time_interval)
# features = self.encode(observation, action)
# self.c[features] += np.ones(self.layer_n) / self.layers
# self.w[features] += rho / self.c[features] * (reward - self.w[features].sum())
# rho *= (self.w[features] / self.w[features])
class SARSAAgent_grid(Agent):
'''
网格太细会带来训练速度慢的问题 本质是q值表更新的不充分 不能从临近的网格获取数据
'''
def __init__(self, env, dim_size_arr=[50, 50], gamma=1., learning_rate=0.03, epsilon=0.001):
'''
学习函数
env 环境
dim_size_arr 各个维度上的网格数量
gamma 收益衰减速率
learning_rate 学习速率
epsilon 执行探索策略概率
'''
self.action_n = env.action_space.n # 动作数
self.obs_low = env.observation_space.low
self.obs_scale = env.observation_space.high - env.observation_space.low # 观测空间范围
self.encoder = GridCoder(dim_size_arr, self.obs_low, self.obs_scale)
self.w = np.zeros((self.encoder.state_num, self.action_n)) # Q值
self.c = np.zeros_like(self.w)
self.w += np.random.rand(self.encoder.state_num, self.action_n) * 0.01
self.gamma = gamma # 折扣
self.learning_rate = learning_rate # 学习率
self.epsilon = epsilon # 探索
def decide(self, observation):
'''
决策函数
observation 状态观测值 (位置 速度 时间)
'''
if np.random.rand() < self.epsilon:
return np.random.randint(self.action_n)
else:
qs = self.w[self.encoder(observation), :]
action = np.argmax(qs)
return action
def learn(self, observation, action, reward, time_interval, next_observation, done, next_action):
'''
学习函数
observation 状态观测值 位置 速度
action 动作
reward 奖励
next_state 下一状态 观测值
done 是否完成
next_action 下一动作
'''
u = reward + (1. - done) * self.gamma * self.w[self.encoder(next_observation), next_action]
td_error = u - self.w[self.encoder(observation), action]
self.w[self.encoder(observation), action] += (self.learning_rate * td_error * time_interval)
class VPGAgent(Agent):
'''
回合更新策略梯度算法寻找最优策略
'''
def __init__(self, env, layers=8, features=1893, gamma=1., learning_rate=0.03, epsilon=0.001, baseline=True):
'''
学习函数
env 环境
layers 要用到几层砖瓦编码
features 砖瓦编码应该得到多少特征 总特征数 8*8 + (8+1) * (8+1) * (8-1)
gamma 收益衰减速率
learning_rate 学习速率
epsilon 执行探索策略概率
'''
self.action_n = env.action_space.n # 动作数
self.obs_low = env.observation_space.low
self.obs_scale = env.observation_space.high - env.observation_space.low # 观测空间范围
self.encoder = TileCoder(layers, features) # 砖瓦编码器
self.w = np.zeros(features) # 权重
self.feature_list = [] # 坐标列表
self.trajectory = [] # 经验
self.gamma = gamma # 折扣
self.learning_rate = learning_rate # 学习率
self.epsilon = epsilon # 探索
self.layers = layers
def decide(self, observation):
'''
决策函数
observation 状态观测值 (位置 速度 时间)
'''
if np.random.rand() < self.epsilon:
return np.random.randint(self.action_n)
else:
qs = [self.get_q(observation[:2], action) for action in range(self.action_n)]
return np.argmax(qs)
def learn(self, observation, action, reward, done):
'''
学习函数
observation 状态观测值 位置 速度
action 动作
reward 奖励
done 是否完成
next_action 下一动作
'''
q = self.get_q(observation[:2], action)
self.trajectory.append((observation, action, reward, q))
self.feature_list.append(self.encode(observation[:2], action))
# 如果程序结束 储存数据
if done:
fertures_array = np.array(self.feature_list)
df = pd.DataFrame(self.trajectory, columns=['observation', 'action', 'reward', 'q'])
df['discount'] = self.gamma ** df.index.to_series()
df['discounted_reward'] = df['discount'] * df['reward']
df['discounted_return'] = df['discounted_reward'][::-1].cumsum()
df['derivative'] = df['discounted_return'] - df['q']
df['discounted_derivative'] = (df['discount'] * df['derivative'])
# G = df['discounted_return']
df['psi'] = df['discounted_return']
# x = np.stack(df['observation'])
# # 更新基线
# # np.newaxis的作用就是在这一位置增加一个维度 例如一维向量变二维矩阵
# # 基线的学习目标是 未来回报的贴现值
# if self.baseline:
# df['baseline'] = self.baseline_net.predict(x)
# df['psi'] -= (df['baseline'] * df['discount'])
# df['return'] = df['discounted_return'] / df['discount']
# y = df['return'].values[:, np.newaxis]
# 策略学习
loss = df['discounted_derivative']
for i in range(self.layers):
self.w[fertures_array[:, i]] += self.learning_rate * loss
# 为下一回合初始化经验列表
self.trajectory = []
self.feature_list = []
def play_sarsa(env, agent, train=False, render=False, collect_ex=False):
'''
智能体环境交互逻辑
env 环境
agent 智能体
train 是否训练
render 是否显示
返回期望收益
'''
episode_reward = 0
trajectory = []
observation = env.reset()
action = agent.decide(observation)
while True:
if render:
env.render()
next_observation, reward, done, time_interval = env.step(action)
episode_reward += reward
next_action = agent.decide(next_observation) # 终止状态时此步无意义
if train:
agent.learn(observation, action, reward, time_interval, next_observation, done, next_action)
if collect_ex: # 搜集经验
trajectory.append((observation, action, reward, time_interval, next_observation, done, next_action))
if done:
break
observation, action = next_observation, next_action
return episode_reward, trajectory
def play_learn_at_done(env, agent, train=False, render=False, collect_ex=False):
'''
智能体环境交互逻辑 在回合运行结束时学习
env 环境
agent 智能体
train 是否训练
render 是否显示
返回期望收益
'''
observation = env.reset()
episode_reward = 0.
done = False
while not done:
if render:
env.render()
action = agent.decide(observation)
next_observation, reward, done, _ = env.step(action)
episode_reward += reward
if train:
agent.learn(observation, action, reward, done)
observation = next_observation
return episode_reward, []
def train(env, agent, play_fun):
# 训练
env.continuous_time = False
episodes = 300
episode_rewards = []
for episode in range(episodes):
episode_reward, _ = play_fun(env, agent, train=True)
episode_rewards.append(episode_reward)
print("{}/{} sum_w:{:.2f} score:{:.2f}".format(episode, episodes, np.sum(np.sum(agent.w)), episode_reward))
plt.plot(episode_rewards)
plt.show()
# 测试
env.continuous_time = False
agent.epsilon = 0.0
episodes = 100
sum_rewards = 0.0
for episode in range(episodes):
episode_reward, _ = play_fun(env, agent, train=False)
sum_rewards += episode_reward
# print("train {}/{}".format(episode + 1, episodes))
print('平均回合奖励 = {} / {} = {}'.format(sum_rewards, episodes, sum_rewards / episodes))
def train_difference_strayegy_orderly(env, learn_agent, behavior_agent, play_fun):
'''
异策略有序训练
'''
# 训练
env.continuous_time = False
episodes = 300
episode_rewards = []
for episode in range(episodes):
_, trajectory = play_fun(env, behavior_agent, train=False, collect_ex=True)
learn_agent.learn(trajectory)
episode_reward, _ = play_fun(env, learn_agent, train=False)
episode_rewards.append(episode_reward)
# print("{}/{} sum_w:{:.2f} score:{:.2f}".format(episode, episodes, np.sum(np.sum(learn_agent.w)), episode_reward))
plt.plot(episode_rewards)
plt.show()
# 测试
env.continuous_time = False
learn_agent.epsilon = 0.0
episodes = 100
sum_rewards = 0.0
for episode in range(episodes):
episode_reward, _ = play_fun(env, learn_agent, train=False)
sum_rewards += episode_reward
# print("train {}/{}".format(episode + 1, episodes))
print('平均回合奖励 = {} / {} = {}'.format(sum_rewards, episodes, sum_rewards / episodes))
def train_difference_strayegy_sample(env, learn_agent, behavior_agent, play_fun):
'''
异策略随机抽样训练
'''
# 训练
env.continuous_time = False
episodes = 300
episode_rewards = []
trajectorys = []
for episode in range(episodes):
_, trajectory = play_fun(env, behavior_agent, train=False, collect_ex=True)
trajectorys += trajectory
seed(0)
sample_n = int(len(trajectorys) / episodes)
for episode in range(episodes):
trajectory = sample(trajectorys, sample_n)
learn_agent.learn(trajectory)
episode_reward, _ = play_fun(env, learn_agent, train=False)
episode_rewards.append(episode_reward)
# print("{}/{} sum_w:{:.2f} score:{:.2f}".format(episode, episodes, np.sum(np.sum(learn_agent.w)), episode_reward))
plt.plot(episode_rewards)
plt.show()
# 测试
env.continuous_time = False
learn_agent.epsilon = 0.0
episodes = 100
sum_rewards = 0.0
for episode in range(episodes):
episode_reward, _ = play_fun(env, learn_agent, train=False)
sum_rewards += episode_reward
# print("{}/{} sum_w:{:.2f} score:{:.2f}".format(episode, episodes, np.sum(np.sum(learn_agent.w)), episode_reward))
# print("train {}/{}".format(episode + 1, episodes))
print('平均回合奖励 = {} / {} = {}'.format(sum_rewards, episodes, sum_rewards / episodes))
def main():
np.random.seed(0)
env = MountainCarEnv()
env.seed(0)
env.continuous_time = False
# sarsa_agent = SARSAAgent(env)
# print(">>>>>>>>>>>>>>>>>>>>SARSA 算法<<<<<<<<<<<<<<<<<<<<<")
# train(env, sarsa_agent, play_sarsa)
vpg_agent = VPGAgent(env, gamma=1.0)
print(">>>>>>>>>>>>>>>>>>>>VPG 算法<<<<<<<<<<<<<<<<<<<<<")
train(env, vpg_agent, play_learn_at_done)
return 0
# lambda_agent = SARSALambdaAgent(env)
# print(">>>>>>>>>>>>>>>>>>>>SARSA(λ) 算法<<<<<<<<<<<<<<<<<<<<<")
# train(env, lambda_agent, play_sarsa)
random_agent = RandomAgent(env)
diff_agent_orderly = DiffAgent(env, learning_rate=0.03)
diff_agent_sample = DiffAgent(env, learning_rate=0.03)
# sarsa_agent.epsilon = 0.3
print(">>>>>>>>>>>>>>>>>>>>SARSA离线学习 按序更新 算法<<<<<<<<<<<<<<<<<<<<<")
train_difference_strayegy_orderly(env, diff_agent_orderly, random_agent, play_sarsa)
print(">>>>>>>>>>>>>>>>>>>>SARSA离线学习 随机抽样 算法<<<<<<<<<<<<<<<<<<<<<")
train_difference_strayegy_sample(env, diff_agent_sample, random_agent, play_sarsa)
# train(env, random_agent, play_sarsa)
# sarsa_grid_agent = SARSAAgent_grid(env, dim_size_arr=(16, 16), learning_rate=0.05, gamma=0.97)
# print(">>>>>>>>>>>>>>>>>>>>SARSA_grid 算法<<<<<<<<<<<<<<<<<<<<<")
# train(env, sarsa_grid_agent, play_sarsa)
# print("program__end")
if __name__ == "__main__":
main()
|
Python
|
UTF-8
| 10,484 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
#how do we write python code again?
import sys
#Setup some global values
NonPrefixed = False
CBPrefixed = False
Parenthesies = False
Commas = False
Curlies = False
Numbers = False
#replace these letters with the propper values later
r = ["REG_B", "REG_C", "REG_D", "REG_E", "REG_H", "REG_L", "ADDRESS_REG_HL", "REG_A"]
rp = ["REG_BC", "REG_DE", "REG_HL", "REG_SP"]
rp2 = ["REG_BC", "REG_DE", "REG_HL", "REG_AF"]
cc = ["NZ", "Z", "NC", "C", "_err", "_err", "_err", "_err"]
alu = ["OP_ADD8", "OP_ADC", "OP_SUB", "OP_SBC", "OP_AND", "OP_XOR", "OP_OR", "OP_CP"]
rot = ["OP_RLC", "OP_RRC", "OP_RL", "OP_RR", "OP_SLA", "OP_SRA", "OP_SWAP", "OP_SRL"]
def main():
#user code here
#first checkout user input
userInput()
if(NonPrefixed):
for opcode in range(0, 256):
printBegin()
PrintNoPrefix(opcode)
printEnd(opcode)
if(CBPrefixed):
for opcode in range(0, 256):
printBegin()
printCBprefixed(opcode)
printEnd(opcode)
def printBegin():
if Parenthesies:
print("( ", end="")
elif Curlies:
print("{ ", end = "")
def printEnd(_opcode):
if Parenthesies:
print(" )", end = "")
elif Curlies:
print(" }", end = "")
if Commas:
print(",", end="")
if Numbers:
print("\t", end="")
print(_opcode, end=" ")
print("")
#Validate user input
def userInput():
args = len(sys.argv)
if args < 2:
print("Not enough arguments\n")
print("Opcode set selection")
print("Use -a for '-n -c -com'")
print("Use -n for non Prefixed opcodes")
print("Use -c for CB prefixed opcodes")
print("\nMaking lines look pretty")
print("Use -com to seperate each opcode with a ','")
print("Use -num to number each opcode, mainly used for debugging")
print("Use -par for parenthesies '()'")
print("Use -curl for curly brackets '{}'")
exit(0)
else:
global NonPrefixed
global CBPrefixed
global Parenthesies
global Commas
global Curlies
global Numbers
for arg in range(0, args):
if str(sys.argv[arg]) == '-a':
NonPrefixed = True
CBPrefixed = True
Commas = True
elif str(sys.argv[arg]) == '-n':
NonPrefixed = True
elif str(sys.argv[arg]) == "-c":
CBPrefixed = True
elif str(sys.argv[arg]) == "-com":
Commas = True
elif str(sys.argv[arg]) == "-num":
Numbers = True
elif str(sys.argv[arg]) == "-par":
Parenthesies = True
Curlies = False
elif str(sys.argv[arg]) == "-curl":
Curlies = True
Parenthesies = False
#Man this is badly structured...
def PrintNoPrefix( _opcode ):
#get the letter values for the opcode
x = (_opcode & 0b11000000) >> 6
y = (_opcode & 0b00111000) >> 3
z = (_opcode & 0b00000111)
p = (_opcode & 0b00110000) >> 4
q = (_opcode & 0b00001000) >> 3
#find x
if x == 0:
if z == 0:
if y == 0:
print("OP_NOP, NONE, NONE", end="")
elif y == 1:
print("OP_LD16, ADDRESS_16BIT, REG_SP", end="") #load SP into a16
elif y == 2:
print("OP_STOP, NONE, NONE", end="")
elif y == 3:
print("OP_JR, RELATIVE_8BIT, NONE", end="") #jump r8 ahead
else:
print("OP_JR_%s, RELATIVE_8BIT, NONE"% cc[y-4], end="") #jump with condition, might need to get rolled out, or filtered (like put the condition in the second spot, so we can check it depending on that)
elif z ==1:
if q == 0:
print("OP_LD16, %s, IMMEDIATE_16BIT"% rp[p], end="") #load d16 into rp[p]
else:
print("OP_ADD16, REG_HL, %s"% rp[p], end="")
elif z ==2:
if q == 0:
if p == 0:
print("OP_LD8, ADDRESS_REG_BC, REG_A", end="")
elif p == 1:
print("OP_LD8, ADDRESS_REG_DE, REG_A", end="")
elif p == 2:
print("OP_LD8, ADDRESS_REG_HLI, REG_A", end="")
elif p == 3:
print("OP_LD8, ADDRESS_REG_HLD, REG_A", end="")
else:
if p == 0:
print("OP_LD8, REG_A, ADDRESS_REG_BC", end="")
elif p == 1:
print("OP_LD8, REG_A, ADDRESS_REG_DE", end="")
elif p == 2:
print("OP_LD8, REG_A, ADDRESS_REG_HLI", end="")
elif p == 3:
print("OP_LD8, REG_A, ADDRESS_REG_HLD", end="")
elif z ==3:
if q == 0:
print("OP_INC16, %s, NONE"% rp[p], end="")
else:
print("OP_DEC16, %s, NONE"% rp[p], end="")
elif z ==4:
print("OP_INC8, %s, NONE"% r[y], end="")
elif z ==5:
print("OP_DEC8, %s, NONE"% r[y], end="")
elif z ==6:
print("OP_LD8, %s, IMMEDIATE_8BIT"% r[y], end="")
elif z ==7:
if y == 0:
print("OP_RLCA, NONE, NONE", end="")
elif y == 1:
print("OP_RRCA, NONE, NONE", end="")
elif y == 2:
print("OP_RLA, NONE, NONE", end="")
elif y == 3:
print("OP_RRA, NONE, NONE", end="")
elif y == 4:
print("OP_DAA, NONE, NONE", end="")
elif y == 5:
print("OP_CPL, NONE, NONE", end="")
elif y == 6:
print("OP_SCF, NONE, NONE", end="")
elif y == 7:
print("OP_CCF, NONE, NONE", end="")
elif x == 1:
if z == 6 and y == 6:
print("OP_HALT, NONE, NONE", end="")
else:
print("OP_LD8, %s, %s"% (r[y], r[z]), end="")
elif x == 2:
print("%s, REG_A, %s"% (alu[y], r[z]), end="")
elif x == 3:
if z == 0:
if q == 0:
if p == 0:
print("OP_RET_NZ, NONE, NONE", end="")
elif p == 1:
print("OP_RET_NC, NONE, NONE", end="")
elif p == 2:
print("OP_LD8, ADDRESS_8BIT, REG_A", end="") #NONE is (a8)
elif p == 3:
print("OP_LD8, REG_A, ADDRESS_8BIT", end="") #NONE is (a8)
else:
if p == 0:
print("OP_RET_Z, NONE, NONE", end="")
elif p == 1:
print("OP_RET_C, NONE, NONE", end="")
elif p == 2:
print("OP_ADD16, REG_SP, RELATIVE_8BIT", end="")
elif p == 3:
print("OP_LDHL, REG_HL, REG_SP", end="") #NONE is SP+r8, look into this
elif z ==1:
if q == 0:
print("OP_POP, %s ,NONE"%(rp2[p]), end="")
else:
if p == 0:
print("OP_RET, NONE, NONE", end="")
elif p == 1:
print("OP_RETI, NONE, NONE", end="")
elif p == 2:
print("OP_JP, REG_HL, NONE", end="")
elif p == 3:
print("OP_LD16, REG_SP, REG_HL", end="")
elif z ==2:
if q == 0:
if p == 0:
print("OP_JP_NZ, IMMEDIATE_16BIT, NONE", end="")
elif p == 1:
print("OP_JP_NC, IMMEDIATE_16BIT, NONE", end="")
elif p == 2:
print("OP_LD8, RELATIVE_REG_C, REG_A", end="")
elif p == 3:
print("OP_LD8, REG_A, RELATIVE_REG_C", end="")
else:
if p == 0:
print("OP_JP_Z, IMMEDIATE_16BIT, NONE", end="") #NONE = a16
elif p == 1:
print("OP_JP_C, IMMEDIATE_16BIT, NONE", end="") #NONE = a16
elif p == 2:
print("OP_LD8, ADDRESS_16BIT, REG_A", end="") #NONE = (a16)
elif p == 3:
print("OP_LD8, REG_A, ADDRESS_16BIT", end="") #NONE = (a16)
elif z ==3:
if y == 0:
print("OP_JP, IMMEDIATE_16BIT, NONE", end="") #first NONE = a16
elif y == 1:
print("OP_CBpref, NONE, NONE", end="") #CB Prefix
elif y == 6:
print("OP_DI, NONE, NONE", end="")
elif y == 7:
print("OP_EI, NONE, NONE", end="")
else:
print("OP_ERROR, NONE, NONE", end="") #something went wrong if you get here
elif z ==4:
if y < 4:
print("OP_CALL_%s, IMMEDIATE_16BIT, NONE"%(cc[y]), end="")
else:
print("OP_ERROR, NONE, NONE", end="")
elif z ==5:
if q == 0:
print("OP_PUSH, %s, NONE"%(rp2[p]), end="")
elif p == 0:
print("OP_CALL, IMMEDIATE_16BIT, NONE", end="") #NONE = a16s
else:
print("OP_ERROR, NONE, NONE", end="")
elif z ==6:
print("%s, REG_A, IMMEDIATE_8BIT"%(alu[y]), end="")
elif z ==7:
print("OP_RST, RESET_%s, NONE"%(y), end="") #the numarical value is an interger, not a pointer. look into this.
#==============
# CB Prefixed Opcodes
#==============
def printCBprefixed(_opcode):
#get the letter values for the opcode
x = (_opcode & 0b11000000) >> 6
y = (_opcode & 0b00111000) >> 3
z = (_opcode & 0b00000111)
p = (_opcode & 0b00110000) >> 4
q = (_opcode & 0b00001000) >> 3
#real wonkey code this right here
if x == 0:
print("%s, 0, %s"%(rot[y], r[z]), end="")
elif x ==1:
print("OP_BIT, %s, %s"%(y, r[z]), end="")
elif x ==2:
print("OP_RES, %s, %s"%(y, r[z]), end="")
elif x ==3:
print("OP_SET, %s, %s"%(y, r[z]), end="")
main()
|
PHP
|
UTF-8
| 647 | 2.59375 | 3 |
[] |
no_license
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRestaurantsTable extends Migration {
public function up()
{
Schema::create('restaurants', function(Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name');
$table->string('image');
$table->float('less_price', 8,2);
$table->float('delivery_price', 8,3);
$table->boolean('active')->default(1);
$table->text('details');
$table->integer('city_id')->unsigned();
$table->integer('area_id')->unsigned();
});
}
public function down()
{
Schema::drop('restaurants');
}
}
|
Java
|
UTF-8
| 744 | 1.890625 | 2 |
[] |
no_license
|
package zhiyuan.com.loan.activity;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.umeng.analytics.MobclickAgent;
import zhiyuan.com.loan.R;
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
}
@Override
protected void onResume() {
super.onResume();
MobclickAgent.onResume(this);
}
@Override
protected void onPause() {
super.onPause();
MobclickAgent.onPause(this);
}
public void back(View view){
finish();
}
}
|
Java
|
UTF-8
| 911 | 1.953125 | 2 |
[] |
no_license
|
package com.cn.wms_system_new.bean;
public class FunctionItem {
private String title;
private String viewType;
private String imageName;
private String operateName;
private int unFinishedNum;
public FunctionItem() {
}
public String getViewType() {
return viewType;
}
public void setViewType(String viewType) {
this.viewType = viewType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
public String getOperateName() {
return operateName;
}
public void setOperateName(String operateName) {
this.operateName = operateName;
}
public int getUnFinishedNum() {
return unFinishedNum;
}
public void setUnFinishedNum(int unFinishedNum) {
this.unFinishedNum = unFinishedNum;
}
}
|
Python
|
UTF-8
| 899 | 3.296875 | 3 |
[] |
no_license
|
# 5kyu
# chameleons is int[3], desiredColor is int from 0 to 2
def check_input(chameleons):
check = [1 if e == 0 else 0 for e in chameleons]
if sum(check) >= 2:
return False
def chameleon(chameleons, desiredColor):
desired, moves = chameleons[desiredColor], 0
if check_input(chameleons) == False:
if chameleons[desiredColor]> 0:
return 0
else:
return -1
chameleons.pop(desiredColor)
small, big = min(chameleons), max(chameleons)
while small < big:
small += 2
big -= 1
desired -= 1
moves += 1
if small == big:
return small + moves
else:
return -1
#test.describe("All chameleons are wrong color")
print(chameleon([0, 0, 17], 1)) #, -1)
#test.describe("One step solution")
print(chameleon([1, 1, 15], 2)) #, 1)
#test.describe("Average situation")
print(chameleon([34, 32, 35], 0)) #, 35, "Wrong answer")
print(chameleon([0, 0, 0], 0)) #, 35, "Wrong answer")
|
Java
|
UTF-8
| 818 | 2.34375 | 2 |
[] |
no_license
|
package com.lowry.lapspace3;
/**
* Created by lowry on 04/04/2018.
*/
public class ClassNotificationDetails {
private int company_id;
private int lap_id;
private String company_name;
private String company_image_string;
public ClassNotificationDetails(int company_id, int lap_id, String company_name, String company_image_string) {
this.company_id = company_id;
this.lap_id = lap_id;
this.company_name = company_name;
this.company_image_string = company_image_string;
}
public int getCompanyId() {
return company_id;
}
public int getLapId() {
return lap_id;
}
public String getCompanyImageString() {
return company_image_string;
}
public String getCompanyName() {
return company_name;
}
}
|
Java
|
UTF-8
| 7,568 | 2.03125 | 2 |
[] |
no_license
|
package com.jiayi.platform.security.gataway.filter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.jiayi.platform.security.core.dto.JsonObject;
import com.jiayi.platform.security.gataway.core.config.AuthCodes;
import com.jiayi.platform.security.core.util.JWTUtil;
import com.jiayi.platform.security.gataway.service.AuthenticationService;
import io.netty.buffer.ByteBufAllocator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.apache.commons.lang.StringUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
private final AuthenticationService authenticationService;
private final byte[] UN_AUTH = "{\"payLoad\": null,\"message\": \"非法操作\",\"code\": 401}"
.getBytes(StandardCharsets.UTF_8);
private final byte[] TOKEN_EXPIRED = "{\"payLoad\": null,\"message\": \"token 过期\",\"code\": 100}"
.getBytes(StandardCharsets.UTF_8);
private final byte[] UNKNOWN_USER = "{\"payLoad\": null,\"message\": \"未知用户,请重新登录\",\"code\": 101}"
.getBytes(StandardCharsets.UTF_8);
private final Map<String, String> AUTH_CODES;
private final String SPILT_STR;
private final String PARAM_STR;
@Autowired
public AuthFilter (AuthCodes authCodes, AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
AUTH_CODES = authCodes.getCodes();
SPILT_STR = authCodes.getSplit();
PARAM_STR = authCodes.getParam();
}
@Override
public Mono<Void> filter (ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
List<String> authorization = headers.get("Authorization");
String token = null;
if (authorization != null && authorization.size() > 0) token = authorization.get(0);
String userId = null;
//获取user ID
if (token != null) userId = JWTUtil.getUserId(token);
//判断token的合法性
boolean pass;
String path = request.getPath().value();
String ip = getClientIP(request);
try {
pass = (userId != null && JWTUtil.verify(token, userId));
} catch (TokenExpiredException ex) {
log.warn(String.format("用户ID[%s] ip[%s] 访问 %s token 失效![%s]", userId, ip, path, ex.getMessage()));
return unPass(exchange, HttpStatus.INTERNAL_SERVER_ERROR, TOKEN_EXPIRED);
}
if (userId == null) {
log.warn("未知用户,请重新登录");
return unPass(exchange, HttpStatus.SWITCHING_PROTOCOLS, UNKNOWN_USER);
}
//进行权限验证
if (pass) {
int pl = path.length();
if (path.endsWith("/") && pl > 1) path = path.substring(0, pl - 1);
String method = "METHOD_NULL";
try {
method = Objects.requireNonNull(request.getMethod()).name();
} catch (NullPointerException ex) {
log.warn(String.format("用户ID[%s] ip[%s] 访问 %s 无 method!", userId, ip, path));
pass = false;
}
Object body=null;
if ("POST".equals(method)) {
body = exchange.getAttribute("cachedRequestBodyObject");
} else {
Map requestQueryParams = request.getQueryParams();
body =JSONObject.toJSON(requestQueryParams);
}
//获取权限code
String code = null;
String path_=null;
if (pass) {
StringBuilder buffer = new StringBuilder();
for (String p : path.split("/")) {
if (p.length() > 0) {
buffer.append("_");
if (StringUtils.isNumeric(p)) buffer.append(PARAM_STR);
else buffer.append(p);
}
}
buffer.append(SPILT_STR);
buffer.append(method);
path_ = buffer.toString();
code = AUTH_CODES.getOrDefault(path_, null);
}
if (code == null) {
path_="ONLY_LOGIN";
code ="ONLY_LOGIN";
pass = true;
} else {
//判断用户是否拥有该code的权限
long uid = -1L;
try {
uid = Long.parseLong(userId);
} catch (NumberFormatException ex) {
log.warn(String.format("用户ID[%s] ip[%s] 访问 %s 用户ID非法!", userId, ip, path));
pass = false;
}
if (pass) {
Set<String> acs = authenticationService.getAuthCodes(uid);
if (code.contains(",")) {
for (String c : code.split(",")) {
pass = acs.contains(c);
if (pass) break;
}
} else pass = acs.contains(code);
}
}
if (!pass)
log.warn(String.format("用户ID[%s] ip[%s] 访问 %s[%s] 无系统权限!", userId, ip, code, path));
else {
if(path.indexOf("#")>=0||path_.indexOf("#")>=0||code.indexOf("#")>=0){
log.error("path:{},path_:{},code:{}",pass,path_,code);
}
if(body==null){
body="";
}
log.info(String.format("userId==%s#ip==%s#path==%s#key==%s#code==%s#param==%s", userId, ip, path, path_, code,body.toString()));
}
} else {
log.warn(String.format("用户ID[%s] ip[%s] 访问 %s token验证未通过!", userId, ip, path));
}
if (!pass) {
log.warn(String.format("用户ID[%s] ip[%s] 访问 %s 权限验证未通过!", userId, ip, path));
return unPass(exchange, HttpStatus.UNAUTHORIZED, UN_AUTH);
}
return chain.filter(exchange);
}
private Mono<Void> unPass (ServerWebExchange exchange, HttpStatus status, byte[] info) {
ServerHttpResponse response = exchange.getResponse();
DataBuffer buffer = response.bufferFactory().wrap(info);
response.setStatusCode(status);
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
return response.writeWith(Mono.just(buffer));
}
@Override
public int getOrder () {
return 0;
}
public static String getClientIP (ServerHttpRequest request) {
String fromSource = "X-Real-IP";
String ip = request.getHeaders().getFirst("X-Real-IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeaders().getFirst("X-Forwarded-For");
fromSource = "X-Forwarded-For";
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeaders().getFirst("Proxy-Client-IP");
fromSource = "Proxy-Client-IP";
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeaders().getFirst("WL-Proxy-Client-IP");
fromSource = "WL-Proxy-Client-IP";
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeaders().getHost().getHostString();
fromSource = "request.getRemoteAddr";
}
log.debug("App Client IP: " + ip + ", fromSource: " + fromSource);
return ip;
}
}
|
JavaScript
|
UTF-8
| 847 | 3.015625 | 3 |
[] |
no_license
|
function MarkdownWidget() {
this.italicsRegex = /\*(\w+)\*{1}/gi;
this.altItalicsRegex = /\_(\w+)\_/gi;
this.boldRegex = /\*\*(\w+)\*\*/gi;
};
MarkdownWidget.prototype.italics = function(input) {
var text = input;
var test = text.replace(this.italicsRegex, "<i> $1 </i>" );
console.log(test);
return test;
};
MarkdownWidget.prototype.bold = function(input) {
var text = input;
var test = text.replace(this.boldRegex, "<b>$1</b>" );
console.log(test);
return test;
};
MarkdownWidget.prototype.altItalics = function(input) {
var text = input;
var test = text.replace(this.altItalicsRegex, "<i> $1 </i>" );
console.log(test);
return test;
};
MarkdownWidget.prototype.convertAll = function(input) {
output = this.bold(input);
output = this.altItalics(output);
output = this.italics(output);
return output;
}
|
Java
|
UTF-8
| 281 | 1.882813 | 2 |
[] |
no_license
|
package factory;
public class MysqlUserFactory implements IFactory {
@Override
public IUserOperation getUserOperation() {
return new MysqlUser();
}
@Override
public IProductOperation getProductOperation() {
return new SnakeOperation();
}
}
|
Java
|
UTF-8
| 682 | 1.75 | 2 |
[] |
no_license
|
package com.huya.dbms.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import com.github.obase.webc.Kits;
import com.github.obase.webc.Webc;
import com.github.obase.webc.annotation.ServletMethod;
@Controller(value = Webc.$)
public class ConsoleController extends BaseController {
@ServletMethod(value = Webc.$, csrf = false)
public void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Kits.render(request, response, "/view/console.jsp");
}
}
|
Python
|
UTF-8
| 756 | 3.703125 | 4 |
[] |
no_license
|
"""
二进制和字符串之间的转化
"""
def encode(s):
return ' '.join([bin(ord(c)).replace('0b', '') for c in s])
def decode(s):
return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])
result = encode('hello')
# print('hello 的二进制是:\n', result)
results = decode('1101000 1100101 1101100 1101100 1101111')
# print('\n1101000 1100101 1101100 1101100 1101111 二进制解码后是:\n', results)
"""
编码解码之间得到转换
"""
str_unicode = b'\xe6\x88\x91\xe6\x98\xaf\xe6\x96\x87\xe6\x9c\xac'
str_utf8 = str_unicode.decode(encoding="utf-8", errors="strict")
print('\x04\x10 解码后是:\n', str_utf8)
str_utf8_2 = '平安银行'
str_2 = str_utf8_2.encode()
print('\n平安银行编码后是:\n', str_2)
|
Java
|
UTF-8
| 1,072 | 2.203125 | 2 |
[] |
no_license
|
package me.himi.love.entity.loader.impl;
import me.himi.love.IAppService.UploadFaceResponse;
import me.himi.love.entity.loader.IUploadFileResponseLoader;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @ClassName:LoginedUserLoaderImpl
* @author sparklee liduanwei_911@163.com
* @date Nov 4, 2014 9:02:06 PM
*/
public class UploadFileResponseLoaderImpl implements IUploadFileResponseLoader {
@Override
public UploadFaceResponse load(String response) {
System.out.println("upload" + response);
try {
JSONObject fileJsonObj = new JSONObject(response);
int status = fileJsonObj.getInt("status");
if (0 == status) {// 上传失败
return null;
}
UploadFaceResponse uploadFileResponse = new UploadFaceResponse();
uploadFileResponse.imageUrl = fileJsonObj.getString("image_url");
uploadFileResponse.review = fileJsonObj.getInt("review");
uploadFileResponse.faceId = fileJsonObj.getInt("face_id");
return uploadFileResponse;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
|
Python
|
UTF-8
| 1,203 | 3.203125 | 3 |
[] |
no_license
|
import math
import os
import random
import re
import sys
#
# Complete the 'countingValleys' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER steps
# 2. STRING path
#
# def countingValleys(steps, path):
# level = 0
# valleys = 0
# for p in path:
# if p == "U":
# level = level + 1
# if level > 0:
# print(f"mountain step {level}")
# elif level == 0:
# print("SEA after VALLEY")
# valley = valley + 1
# elif p == "D":
# level = level - 1
# if level < 0:
# print(f"we are in VALLEY {level}")
# elif level == 0:
# print("SEA after MOUNTAIN")
#
#
# countingValleys(, ["U","U","U","D","D","D","U","U"])
#
def countingValleys(steps, path):
level = 0
valleys = 0
for steps, p in enumerate(path):
if p == "U":
level = level + 1
if level == 0:
valleys = valleys + 1
elif p == "D":
level = level - 1
return valleys
print(countingValleys(16, "DDUUUUDDDDUUUUDD"))
|
JavaScript
|
UTF-8
| 868 | 3.375 | 3 |
[] |
no_license
|
var ES6 = React.createClass({
// shortcut to write methods
// equivalent to `render: function()`
render() {
// const allows to declare a variable that cant
// change value (that stays 'constant')
const x = 1
// [param] => [eval] is a shortcut to write functions
// it is an arrow function
// this code is equal to
// var result = function(x) { return x * 2}
const result = x => x * 2
const styleContainer = {
textAlign: "center", // commas will be tranformed to semicolons
padding: 5, // trailing coma is supported in arrays and objects
// no need to write px
}
return (
<div style={ styleContainer } className="container">
<h1>The result is { result(x) }</h1>
<p>ES6 is awesome!</p>
</div>
)
}
})
ReactDOM.render(
<ES6 />,
document.getElementById('example')
)
|
C
|
UTF-8
| 3,851 | 2.859375 | 3 |
[] |
no_license
|
#include <sys/ipc.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#define TMPFILE "./tmpmatrix.txt"
int count_of_alocated_pointers = 0;
void ** array_of_alocated_pointers = NULL;
void my_error (char* message);
void add_pointer (void* new_pointer);
int getnumber (char* string);
void free_all_pointers ();
void file_check();
int get_number_symbols (int x);
int main(int argc, char **argv) {
int i, fork_result;
char *client_number = NULL;
int total_cleints;
int file_id, dimension;
umask (0);
if (argc<2)
my_error ("You should enter a number of clients!\n\0");
total_cleints = getnumber (argv[1]);
file_check();
if ((file_id=open (TMPFILE,O_RDONLY))<0)
my_error ("Error when open file!\n\0");
if (read(file_id,&dimension,sizeof(int))!=sizeof(int))
my_error ("error when reading from file!\n\0");
if ( total_cleints > dimension * dimension )
total_cleints = dimension * dimension;
if (close(file_id) < 0)
my_error ("Error when closing file!\n\0");
printf (" total %i clients \n",total_cleints);
for (i=0; i<total_cleints; ++i) {
fork_result=fork();
if (fork_result < 0)
my_error ("Can not run fork!\n\0");
else if (fork_result == 0) {
client_number = (char*) malloc (sizeof(char)*(get_number_symbols (i+1) + 1));
snprintf (client_number, get_number_symbols (i+1)+1, "%i", i + 1);
execl ("./client.out","./client.out" , client_number , NULL);
my_error ("Can not run client application!\n\0");
}
}
free_all_pointers();
execl ("./server.out","./server.out", argv [1], NULL);
my_error ("Can not run server!\n\0");
return -1;
}
void add_pointer (void* new_pointer) {
count_of_alocated_pointers ++;
if (array_of_alocated_pointers == NULL )
array_of_alocated_pointers = (void**) malloc (sizeof (void*) );
else
array_of_alocated_pointers = (void**) realloc (array_of_alocated_pointers , count_of_alocated_pointers * sizeof (void*) );
array_of_alocated_pointers [count_of_alocated_pointers - 1] = new_pointer;
return;
}
void my_error (char* message) {
int i;
write (STDERR_FILENO, message, strlen (message));
for (i = 0; i < count_of_alocated_pointers; ++i)
free (array_of_alocated_pointers [i]);
free (array_of_alocated_pointers);
exit (-1);
}
void free_all_pointers () {
int i;
for (i = 0; i < count_of_alocated_pointers; ++i)
free (array_of_alocated_pointers [i]);
free (array_of_alocated_pointers);
return;
}
int get_number_symbols (int x) {
int i = 1;
x=x/10;
while (x>0) {
x=x/10;
++i;
}
return i;
}
int getnumber (char* string) {
int i,answer=0;
char c,flag=1;
for (i=0;i<sizeof(string);++i) {
c=string[i];
if ((flag==1)&&( (c>'9')||(c<'0') )) {
my_error ("NOT A NUMBER!\n\0");
}
if ( (c>='0')&&(c<='9') ) {
answer=answer*10+c-'0';
flag=0;
}
if ((flag==0)&&( (c>'9')||(c<'0') ))
break;
}
return answer;
}
void file_check() {
int file_id;
char c;
pid_t fork_result,w;
if ((file_id=open (TMPFILE,O_RDONLY))<0)
printf("It seems that you haven't run the first application! Would you like to run it? (Y/n)\n");
else {
if (close(file_id) < 0)
my_error ("Can not close file!\n\0");
return;
}
while (1) {
c=getchar();
if ( (c=='Y')||(c=='y'))
break;
if ( (c=='N')||(c=='n')) {
free_all_pointers ();
exit(0);
}
if (c!='\n')
printf ("Enter, please, 'y' or 'n' -> ");
}
fork_result=fork();
if (fork_result<0)
my_error("Error! Can not creare a child process!\n\0");
else if (fork_result==0) {
execl("./matrix.out","./matrix.out", NULL);
my_error ("Can not run the first application!\n\0");
}
w=waitpid (fork_result , NULL , 0);
if (w == -1) {
my_error("waitpid error! Disk C: will be destroyed!\n\0");
}
return;
}
|
JavaScript
|
UTF-8
| 371 | 4.21875 | 4 |
[] |
no_license
|
// Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters,
// each taken only once - coming from s1 or s2.
function longest(s1, s2) {
// your code
s1 = "aretheyhere";
s2 = "yestheyarehere";
let long = [...new Set(s1 + s2)].sort().join("");
console.log(long);
return long;
}
|
SQL
|
UTF-8
| 736 | 4.25 | 4 |
[
"MIT"
] |
permissive
|
CREATE VIEW `constraints` AS
SELECT usg.table_schema as table_catalog,
usg.table_name as table_name,
usg.column_name as referencing_column_name,
usg.REFERENCED_TABLE_NAME as referenced_table_name,
usg.ORDINAL_POSITION as ordinal_position,
usg.REFERENCED_COLUMN_NAME as referenced_column_name,
cst.constraint_name as constraint_name
FROM information_schema.key_column_usage usg
LEFT JOIN information_schema.table_constraints cst
ON usg.table_schema = cst.table_schema
AND usg.constraint_name = cst.constraint_name
WHERE cst.constraint_type = 'FOREIGN KEY'
and usg.table_schema = ':DATABASE_NAME'
|
C++
|
UTF-8
| 1,164 | 3.5 | 4 |
[] |
no_license
|
#include "Phonebook.hpp"
Phonebook::Phonebook()
{
this->amount = 0;
}
Phonebook::~Phonebook()
{
}
void Phonebook::add_new_contact(void)
{
if (this->amount == 8)
std::cout << "Contact list is full!\n";
else
if (this->contact_list[this->amount].create_contact() == true)
this->amount++;
}
void Phonebook::show_contact_info(void)
{
std::cout << " Index|" << "First Name|" << " Last Name|" << " Nickname|" << std::endl;
for(int i = 0; i < this->amount; i++)
this->contact_list[i].display_descr(i);
}
void Phonebook::find_contact(void)
{
int cont_num;
if (this->amount == 0)
{
std::cout << "-- Contact list is empty!\n";
return ;
}
this->show_contact_info();
while (true)
{
std::cout << "Choose contact number (0 for exit): ";
std::cin >> cont_num;
if (std::cin.fail() || cont_num < 0 || cont_num > this->amount)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "-- Invalid index.\n";
continue ;
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if (cont_num)
this->contact_list[(int)cont_num - 1].display_contact();
return ;
}
}
|
C++
|
UTF-8
| 979 | 3.796875 | 4 |
[
"MIT"
] |
permissive
|
#include<iostream>
#include<string>
#include "dna.h"
using::std::cout;
using::std::cin;
using::std::string;
/*
Write code that prompts user to enter 1 for Get GC Content,
or 2 for Get DNA Complement. The program will prompt user for a
DNA string and call either get gc content or get dna complement
function and display the result. Program runs as long as
user enters a y or Y.
*/
int main()
{
char choice;
int menu_choice;
do
{
string dna;
cout << "Enter '1' to get the GC content of DNA or '2' to get the DNA's complement: ";
cin >> menu_choice;
cout << "Enter DNA sequence: ";
cin >> dna;
if(menu_choice == 1)
{
cout << "GC Content: " << get_gc_content(dna) << "\n";
}
else
{
cout << "DNA Complement: " << get_dna_complement(dna) <<"\n";
}
cout << "Would you like to continue to work with DNA? Enter 'Y' if yes: ";
cin >> choice;
} while (choice == 'Y' || choice == 'y');
}
|
Markdown
|
UTF-8
| 1,687 | 3.34375 | 3 |
[
"0BSD"
] |
permissive
|
# As You Wish
I really like the _The Princess Bride_ and "as you wish" was the first thing that popped into my head when I was thinking about making decisions. While some might think there's a wholesome or romantic reasoning behind it, I'm certain it's because I'm horrible at making decisions and I'll go along with whatever someone decides; so cute, right?
Well, this simple web app does the decision making for you. There is absolutely nothing smart about how the decision is made, one of the choices provided is just chosen at random. But just like Westley, whatever the app says, I will do "as you wish".
Try it out: https://as-you-wish-prod.herokuapp.com/
## Features
Here are all the features currently available in the web app:
- Choose a random activity
- Choose a random movie or TV show
- Choose a random restaurant or recipe
- Choose a random option from your own custom set of options
- Edit possible options
## Technologies
Because this was meant to help me stop wasting so much of my life to indecision, this web app is quite simple. The technologies used include:
- Gatsby
- React
- Plain CSS
- Heroku
The decision making is done by using `Math.random()` :)
## In Development
There is still much to do, and here are the (tentative) plans moving forward:
- Managing possible activities
- Maintaining activities across sessions
- Choosing a random movie or TV show
- Pulling movie and TV show data from video streaming service libraries
- Filter by genre
- Filter by length
- Choosing a random restaurant
- Pulling restaurant data for restaurants open now
- Filter by distance
- Filter by cuisine
- Responsive design for mobile users
|
Java
|
UTF-8
| 7,414 | 1.648438 | 2 |
[] |
no_license
|
package com.ganesh.mahindra.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class GetBreakdown {
@Id
private int id;
private int machineId;
private String machineNo;
private String machineName;
private String month;
private String date;
private String dept;
private String cellCircle;
private String problemReported;
private int bdTimeLoss;
private String engineLoss;
private String partStatus;
private String partDesc;
private String bdMsPt;
private String action;
private String why1;
private String why2;
private String why3;
private String why4;
private String why5;
private String rootCause;
private String clarificationOfCause;
private String failureCode;
private String counterMeasure;
private String category;
private String recurNonRecurr;
private String linkageWith;
private int status;
private String refNo;
private String sapNotifNo;
private int delStatus;
private String repairedBy;
private String repairStartTime;
private String repairFinishTime;
private String idea;
private String preparedBy;
private String mgrorhead;
private String subcommMember;
private String prevOccDate;
public String getRepairedBy() {
return repairedBy;
}
public void setRepairedBy(String repairedBy) {
this.repairedBy = repairedBy;
}
public String getRepairStartTime() {
return repairStartTime;
}
public void setRepairStartTime(String repairStartTime) {
this.repairStartTime = repairStartTime;
}
public String getRepairFinishTime() {
return repairFinishTime;
}
public void setRepairFinishTime(String repairFinishTime) {
this.repairFinishTime = repairFinishTime;
}
public String getIdea() {
return idea;
}
public void setIdea(String idea) {
this.idea = idea;
}
public String getPreparedBy() {
return preparedBy;
}
public void setPreparedBy(String preparedBy) {
this.preparedBy = preparedBy;
}
public String getMgrorhead() {
return mgrorhead;
}
public void setMgrorhead(String mgrorhead) {
this.mgrorhead = mgrorhead;
}
public String getSubcommMember() {
return subcommMember;
}
public void setSubcommMember(String subcommMember) {
this.subcommMember = subcommMember;
}
public String getPrevOccDate() {
return prevOccDate;
}
public void setPrevOccDate(String prevOccDate) {
this.prevOccDate = prevOccDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMachineId() {
return machineId;
}
public void setMachineId(int machineId) {
this.machineId = machineId;
}
public String getMachineNo() {
return machineNo;
}
public void setMachineNo(String machineNo) {
this.machineNo = machineNo;
}
public String getMachineName() {
return machineName;
}
public void setMachineName(String machineName) {
this.machineName = machineName;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getCellCircle() {
return cellCircle;
}
public void setCellCircle(String cellCircle) {
this.cellCircle = cellCircle;
}
public String getProblemReported() {
return problemReported;
}
public void setProblemReported(String problemReported) {
this.problemReported = problemReported;
}
public int getBdTimeLoss() {
return bdTimeLoss;
}
public void setBdTimeLoss(int bdTimeLoss) {
this.bdTimeLoss = bdTimeLoss;
}
public String getEngineLoss() {
return engineLoss;
}
public void setEngineLoss(String engineLoss) {
this.engineLoss = engineLoss;
}
public String getPartStatus() {
return partStatus;
}
public void setPartStatus(String partStatus) {
this.partStatus = partStatus;
}
public String getPartDesc() {
return partDesc;
}
public void setPartDesc(String partDesc) {
this.partDesc = partDesc;
}
public String getBdMsPt() {
return bdMsPt;
}
public void setBdMsPt(String bdMsPt) {
this.bdMsPt = bdMsPt;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getWhy1() {
return why1;
}
public void setWhy1(String why1) {
this.why1 = why1;
}
public String getWhy2() {
return why2;
}
public void setWhy2(String why2) {
this.why2 = why2;
}
public String getWhy3() {
return why3;
}
public void setWhy3(String why3) {
this.why3 = why3;
}
public String getWhy4() {
return why4;
}
public void setWhy4(String why4) {
this.why4 = why4;
}
public String getWhy5() {
return why5;
}
public void setWhy5(String why5) {
this.why5 = why5;
}
public String getRootCause() {
return rootCause;
}
public void setRootCause(String rootCause) {
this.rootCause = rootCause;
}
public String getClarificationOfCause() {
return clarificationOfCause;
}
public void setClarificationOfCause(String clarificationOfCause) {
this.clarificationOfCause = clarificationOfCause;
}
public String getFailureCode() {
return failureCode;
}
public void setFailureCode(String failureCode) {
this.failureCode = failureCode;
}
public String getCounterMeasure() {
return counterMeasure;
}
public void setCounterMeasure(String counterMeasure) {
this.counterMeasure = counterMeasure;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getRecurNonRecurr() {
return recurNonRecurr;
}
public void setRecurNonRecurr(String recurNonRecurr) {
this.recurNonRecurr = recurNonRecurr;
}
public String getLinkageWith() {
return linkageWith;
}
public void setLinkageWith(String linkageWith) {
this.linkageWith = linkageWith;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getRefNo() {
return refNo;
}
public void setRefNo(String refNo) {
this.refNo = refNo;
}
public String getSapNotifNo() {
return sapNotifNo;
}
public void setSapNotifNo(String sapNotifNo) {
this.sapNotifNo = sapNotifNo;
}
public int getDelStatus() {
return delStatus;
}
public void setDelStatus(int delStatus) {
this.delStatus = delStatus;
}
@Override
public String toString() {
return "GetBreakdown [id=" + id + ", machineId=" + machineId + ", machineNo=" + machineNo + ", machineName="
+ machineName + ", month=" + month + ", date=" + date + ", dept=" + dept + ", cellCircle=" + cellCircle
+ ", problemReported=" + problemReported + ", bdTimeLoss=" + bdTimeLoss + ", engineLoss=" + engineLoss
+ ", partStatus=" + partStatus + ", partDesc=" + partDesc + ", bdMsPt=" + bdMsPt + ", action=" + action
+ ", why1=" + why1 + ", why2=" + why2 + ", why3=" + why3 + ", why4=" + why4 + ", why5=" + why5
+ ", rootCause=" + rootCause + ", clarificationOfCause=" + clarificationOfCause + ", failureCode="
+ failureCode + ", counterMeasure=" + counterMeasure + ", category=" + category + ", recurNonRecurr="
+ recurNonRecurr + ", linkageWith=" + linkageWith + ", status=" + status + ", refNo=" + refNo
+ ", sapNotifNo=" + sapNotifNo + ", delStatus=" + delStatus + "]";
}
}
|
C#
|
UTF-8
| 3,657 | 3.390625 | 3 |
[] |
no_license
|
using System;
using VirtualCard.Interfaces;
namespace VirtualCard
{
/// <summary>
/// An implementation of <see cref="ICard"/> for a virtual payment card
/// </summary>
public class VirtualCard : ICard
{
private decimal _currentBalance;
private readonly ITransactionResponseFactory _transactionResponseFactory;
private readonly string _pin;
private const decimal _minimumTopUp = 0M;
private const decimal _maximumTopUp = 100M;
private const decimal _minimumExpense = 0.01M;
private const decimal _maximumExpense = 100000M;
private readonly object _lockObject = new object();
/// <summary>
/// Gets the current card balance
/// </summary>
public decimal CurrentBalance => _currentBalance;
/// <summary>
/// Instantiates a new instance of the <see cref="VirtualCard"/> class.
/// </summary>
/// <param name="balance">The initial card balance</param>
/// <param name="pin">The card pin</param>
/// <param name="transactionResponseFactory">The transaction response factory</param>
public VirtualCard(decimal balance, string pin, ITransactionResponseFactory transactionResponseFactory)
{
_currentBalance = balance;
_pin = pin;
_transactionResponseFactory = transactionResponseFactory;
}
/// <summary>
/// Tops up the card with the amount specified
/// </summary>
/// <param name="amount">The amount to top up</param>
/// <returns>An instance of <see cref="ITransactionResponse"/> containing information about the transaction</returns>
public ITransactionResponse TopUpCard(decimal amount)
{
if (amount <= _minimumTopUp)
{
throw new ArgumentException($"{nameof(amount)} must exceed minimum top up of {_minimumTopUp}");
}
if (amount > _maximumTopUp)
{
throw new ArgumentException($"{nameof(amount)} must not exceed maximum top up of {_maximumTopUp}");
}
_currentBalance += amount;
return _transactionResponseFactory.Create(true, CurrentBalance);
}
/// <summary>
/// Withdraws funds from the card
/// </summary>
/// <param name="pin">The personal identification number for the card</param>
/// <param name="amount">The amount to withdraw</param>
/// <returns>An instance of <see cref="ITransactionResponse"/> containing information about the transaction</returns>
public ITransactionResponse WithdrawFunds(string pin, decimal amount)
{
lock (_lockObject)
{
if (amount <= _minimumExpense)
{
throw new ArgumentException($"{nameof(amount)} must exceed minimum expense of {_minimumExpense}");
}
if (amount > _maximumTopUp)
{
throw new ArgumentException($"{nameof(amount)} must not exceed maximum expense of {_maximumExpense}");
}
if (pin != _pin)
{
throw new ArgumentException($"Incorrect PIN supplied");
}
if (amount > _currentBalance)
{
throw new ArgumentException($"Withdrawal amount exceeds current card balance");
}
_currentBalance -= amount;
return _transactionResponseFactory.Create(true, CurrentBalance);
}
}
}
}
|
TypeScript
|
UTF-8
| 572 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
import request from 'supertest'
import {app} from "../../app";
const createJob = (title: string, price: number) => {
return request(app)
.post('/api/v1/jobs')
.set('Cookie', global.login())
.send({
title,
price
})
}
it('can fetch a list of jobs', async () => {
await createJob("job1", 10)
await createJob("job2", 20)
await createJob("job3", 30)
const response = await request(app)
.get('/api/v1/jobs')
.send()
.expect(200)
expect(response.body.length).toEqual(3)
})
|
C
|
UTF-8
| 600 | 3.375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void copy(int fdsrc,int fddst){
char c; int n;
while((n = read(fdsrc,&c,1)) != 0)
write(fddst,&c,1);
}
int main(int argc, char const *argv[]){
int tube[2]; // two files descriptors for piping, tube[0] --> reading, tube[1] --> writing
int v = pipe(tube);
if(v == -1)
exit(3);
pid_t pid = fork();
if(pid == -1){
printf("cannot fork!\n");
exit(5);
}else if(pid == 0){ // child
close(tube[1]);
copy(tube[0],1);
close(tube[0]);
}
else{ // parent
close(tube[0]);
copy(0,tube[1]);
close(tube[1]);
}
return 0;
}
|
PHP
|
UTF-8
| 4,431 | 2.53125 | 3 |
[] |
no_license
|
<?php
include_once '../../inc/databaseConnection.php';
if (isset($_REQUEST['action'])) {
$_REQUEST['action']();
}
function getCourier()
{
global $con;
$sql = "select * from courier";
$results = mysqli_query($con, $sql);
$temp = array();
while ($result = mysqli_fetch_assoc($results)) {
$temp[] = $result;
}
$data['data'] = $temp;
echo json_encode($data);
die();
}
function save()
{
global $con;
$CourierName = $_REQUEST['CourierName'];
$CourierCharge = $_REQUEST['CourierCharge'];
$HasCity = $_REQUEST['HasCity'] == "true" ? '1' : '0';
$HasZone = $_REQUEST['HasZone'] == "true" ? '1' : '0';
$results = array();
$sql = "INSERT INTO courier VALUES (NULL,'" . $CourierName . "', '" . $HasCity . "','" . $HasZone . "', '" . $CourierCharge . "', '1')";
$result = mysqli_query($con, $sql);
if ($result) {
$results['status'] = 'success';
$results['message'] = 'Successfully Add Courier';
} else {
$results['status'] = 'failed';
$results['message'] = 'Unsuccessful to add Courier';
}
echo json_encode($results);
die();
}
function update()
{
global $con;
$CourierName = $_REQUEST['CourierName'];
$CourierCharge = $_REQUEST['CourierCharge'];
$HasCity = $_REQUEST['HasCity'] == "true" ? '1' : '0';
$HasZone = $_REQUEST['HasZone'] == "true" ? '1' : '0';
$courierID = $_REQUEST['courierID'];
if ($courierID) {
$sql = "UPDATE courier SET CourierName='" . $CourierName . "',HasCity='" . $HasCity . "',HasZone='" . $HasZone . "',CourierCharge='" . $CourierCharge . "' WHERE courierID='" . $courierID . "' ";
$result = mysqli_query($con, $sql);
if ($result) {
$results['status'] = 'success';
$results['message'] = 'Successfully Update Courier';
} else {
$results['status'] = 'failed';
$results['message'] = 'Unsuccessful to Update Courier';
}
} else {
$results['status'] = 'failed';
$results['message'] = 'Unsuccessful to Update Courier';
}
echo json_encode($results);
die();
}
function single()
{
global $con;
$storeID = $_REQUEST['courierID'];
$sql = "select * from courier where courierID = '" . $_REQUEST['courierID'] . "'";
$results = mysqli_query($con, $sql);
$data = array();
$result = mysqli_fetch_assoc($results);
$response = array(
"status" => 'success',
"data" => $result
);
echo json_encode($response);
die();
}
function changeStatus()
{
global $con;
$result = array();
if (isset($_REQUEST['status'])) {
if (!empty($_REQUEST['courierID'])) {
$sql = "update courier set status='" . $_REQUEST['status'] . "' where courierID='" . $_REQUEST['courierID'] . "'";
$results = mysqli_query($con, $sql);
if ($results) {
$result['status'] = 'success';
$result['message'] = 'Successfully Update Courier';
} else {
$result['status'] = 'failed';
$result['message'] = 'Unsuccessful to Update Courier';
}
}
} else {
$result['status'] = 'failed';
}
echo json_encode($result);
die();
}
function action($id)
{
return '<button type="button" value="' . $id . '" class="btn btn-cyan btn-sm">Edit</button>
<button type="button" value="' . $id . '" class="btn btn-danger btn-sm">Delete</button>';
}
function status($id, $status)
{
if ($status) {
return '<button type="button" class="btn btn-success btn-sm status" data-status="0" name="status" value="' . $id . '">Active</button>';
} else {
return '<button type="button" class="btn btn-warning btn-sm status" data-status="1" name="status" value="' . $id . '" >Inactive</button> ';
}
}
function delete()
{
global $con;
$data = array();
$courierID = $_REQUEST['courierID'];
if (!empty($courierID)) {
$sql = "delete from courier where courierID=$courierID";
$result = mysqli_query($con, $sql);
if ($result) {
$data['status'] = 'success';
$data['message'] = 'Successfully remove Courier';
} else {
$data['status'] = 'failed';
$data['message'] = 'Unsuccessful to remove Courier';
}
}
echo json_encode($data);
die();
}
|
C++
|
UTF-8
| 341 | 3.609375 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
class Convert
{ public :
int i;
void increment(Convert &obj)
{ obj.i=obj.i*2;
cout << "Value of i in member function : " << obj.i;
}
};
int main ()
{ Convert obj1;
obj1.i=3; obj1.increment(obj1);
cout << "\nValue of i in main : " << obj1.i << "\n";
return 0; }
|
JavaScript
|
UTF-8
| 3,071 | 2.703125 | 3 |
[] |
no_license
|
import React from 'react';
export default class NewThreads extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidUpdate() {
console.log('updated');
}
parsePosts = (subreddit) => {
const subreddits = JSON.parse(localStorage.getItem('subreddits'));
const { posts = [] } = subreddits[subreddit];
return posts.map(({ data }) => data);
}
// all { posts, seenIds,}
markRead = (post) => {
console.log(post);
const {subreddit, id, num_comments: numComments} = post;
const subreddits = JSON.parse(localStorage.getItem('subreddits'));
subreddits[subreddit.toLowerCase()].posts = subreddits[subreddit.toLowerCase()].posts.filter( ({data: {id: postId}}) => postId !== id );
subreddits[subreddit.toLowerCase()].seenIds[id] = numComments;
localStorage.setItem('subreddits', JSON.stringify(subreddits));
this.setState({});
chrome.tabs.create({ url: `https://www.reddit.com${post.permalink}` });
}
markAllRead = () => {
const subreddits = JSON.parse(localStorage.getItem('subreddits'));
const subredditNames = Object.keys(subreddits);
for (let subreddit of subredditNames) {
subreddits[subreddit.toLowerCase()].posts.forEach( ({ data: { id } }) => subreddits[subreddit.toLowerCase()].seenIds[id] = true);
subreddits[subreddit.toLowerCase()].posts = [];
}
localStorage.setItem('subreddits', JSON.stringify(subreddits));
chrome.browserAction.setBadgeText({text: ""});
this.setState({});
}
getSubreddits = () => {
const subreddits = JSON.parse(localStorage.getItem('subreddits'));
if (subreddits) {
return Object.keys(subreddits);
} else {
return [];
}
}
getPostsUnderSubreddit = (subreddit) => {
const { isDarkMode } = this.props;
const color = isDarkMode ? '#fff' : '#000';
const posts = this.parsePosts(subreddit);
console.log(posts);
return (
<div>
<h1>📖 {subreddit}</h1>
{posts.map( (post) =>
(<div style={{border: `1px solid ${color}`, cursor: "pointer", margin: '5px', padding: '5px', display: 'flex', alignItems: 'center', justifyContent: 'space-between'}} onClick={() => this.markRead(post)}>
<span>{post.title} - {post.author} </span>
<img src={post.thumbnail} />
</div>) )}
</div>
);
}
getContent = () => {
const subreddits = this.getSubreddits();
console.log(subreddits);
return (
<div>
{subreddits.map( (subreddit) => {
return this.getPostsUnderSubreddit(subreddit);
})}
</div>
);
}
render() {
// const subreddits = this.getSubreddits();
console.log('render');
return (
<div className="tab-body-container">
{this.getContent()}
{/* {this.parsePosts('nfl').map( (post) => <div style={{border: "1px solid red"}} onClick={() => this.markRead(post)}>{post.title} - {post.id} </div> )} */}
<button onClick={this.markAllRead}>Mark All Read</button>
</div>
)
}
}
|
Shell
|
UTF-8
| 4,678 | 3.671875 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/bash
# script to run a simple load test for a serial key:
# 1. Generate 1000 rows with known distribution
# 2. Count rows - should be 1000
# 3. Count rows where str column = "a" - should be 100
# 4. Update all rows where str column = "a"
# 5. Count rows where str column = "a" - should be 0
# 6. Delete all rows where int column < 101
# 7. Count all rows - should be 900
# 8. Delete all rows where 1=1
# 7. Count all rows - should be 0
testcount=0
passcount=0
errorcount=0
SQLCMD0="dbaccess - "
SQLCMD="dbaccess batchertestdb "
comp () {
if [ $2 != $3 ]
then
errorcount=$(( errorcount + 1 ))
printf "F($1: expected $2, got $3)"
else
passcount=$(( passcount + 1 ))
printf "."
#printf "($1: expected $2, got $3)"
fi
testcount=$(( testcount + 1 ))
}
printf "Preparing load script..."
echo "DROP DATABASE IF EXISTS batchertestdb;
CREATE DATABASE IF NOT EXISTS batchertestdb;
CREATE TABLE IF NOT EXISTS serialtest (pk SERIAL NOT NULL PRIMARY KEY, intcol INT, strcol VARCHAR(20));" > /tmp/$$.sql
for i in {1..1000}
do
if [ $i -le 100 ]
then
s='a'
else
s='b'
fi
echo "INSERT INTO serialtest (intcol, strcol) VALUES ($i, '$s');" >> /tmp/$$.sql
done
# No UUID test as Informix doesn't support functions for DEFAULT values. Plus UUID performance in Informix sucks ass, it's a complete anti-pattern
# same test but with a composite key
echo "
CREATE TABLE IF NOT EXISTS compositetest (pk1 INT NOT NULL, pk2 VARCHAR(10) NOT NULL, intcol INT, strcol VARCHAR(20), PRIMARY KEY(pk1, pk2));" >> /tmp/$$.sql
for i in {1..1000}
do
if [ $i -le 100 ]
then
s='a'
else
s='b'
fi
echo "INSERT INTO compositetest (pk1, pk2, intcol, strcol) VALUES ($i, '$s', $i, '$s');" >> /tmp/$$.sql
done
echo "done"
printf "Populating test database..."
$SQLCMD0 /tmp/$$ > /dev/null 2>&1
echo "done"
printf "Starting tests"
exptot=1000
expa=100
sertot=$( echo "SELECT COUNT(1) FROM serialtest;" | $SQLCMD | grep -iv count | grep -iv row )
comp "Initial serial total" $exptot $sertot
sera=$( echo "SELECT COUNT(1) FROM serialtest WHERE strcol = 'a';" | $SQLCMD | grep -iv count | grep -iv row )
comp "Initial serial a" $expa $sera
cmptot=$( echo "SELECT COUNT(1) FROM compositetest;" | $SQLCMD | grep -iv count | grep -iv row )
comp "Initial composite total" $exptot $cmptot
cmpa=$( echo "SELECT COUNT(1) FROM compositetest WHERE strcol = 'a';" | $SQLCMD | grep -iv count | grep -iv row )
comp "Initial composite a" $expa $cmpa
exptot=900
expa=0
../batcher update -concurrency 4 -database batchertestdb -dbtype postgres -host localhost -opts "" -password btest -portnum 26257 -table serialtest -set "strcol='b'" -user circleci -where "strcol='a'" -execute
sera=$( echo "SELECT COUNT(1) FROM serialtest WHERE strcol = 'a';" | $SQLCMD | grep -iv count | grep -iv row )
comp "Updated serial a" $expa $sera
../batcher delete -concurrency 4 -database batchertestdb -dbtype postgres -host localhost -opts "" -password btest -portnum 26257 -table serialtest -user circleci -where "intcol<101" -execute
sertot=$( echo "SELECT COUNT(1) FROM serialtest;" | $SQLCMD | grep -iv count | grep -iv row )
comp "Small delete serial total" $exptot $sertot
../batcher update -concurrency 4 -database batchertestdb -dbtype postgres -host localhost -opts "" -password btest -portnum 26257 -set "strcol='b'" -table compositetest -user circleci -where "strcol='a'" -execute
cmpa=$( echo "SELECT COUNT(1) FROM compositetest WHERE strcol = 'a';" | $SQLCMD | grep -iv count | grep -iv row )
comp "Updated composite a" $expa $cmpa
../batcher delete -concurrency 4 -database batchertestdb -dbtype postgres -host localhost -opts "" -password btest -portnum 26257 -table compositetest -user circleci -where "intcol<101" -execute
cmptot=$( echo "SELECT COUNT(1) FROM compositetest;" | $SQLCMD | grep -iv count | grep -iv row )
comp "Small delete composite total" $exptot $cmptot
exptot=0
../batcher delete -concurrency 4 -database batchertestdb -dbtype postgres -host localhost -opts "" -password btest -portnum 26257 -table serialtest -user circleci -where "1=1" -execute
sertot=$( echo "SELECT COUNT(1) FROM serialtest;" | $SQLCMD | grep -iv count | grep -iv row )
comp "Full delete serial total" $exptot $sertot
../batcher delete -concurrency 4 -database batchertestdb -dbtype postgres -host localhost -opts "" -password btest -portnum 26257 -table compositetest -user circleci -where "1=1" -execute
cmptot=$( echo "SELECT COUNT(1) FROM compositetest;" | $SQLCMD | grep -iv count | grep -iv row )
comp "Full delete composite total" $exptot $cmptot
echo "done"
echo "Informix Tests: $testcount Passed: $passcount Failed: $errorcount"
exit $errorcount
|
Ruby
|
UTF-8
| 3,372 | 2.640625 | 3 |
[] |
no_license
|
class Purchase < ApplicationRecord
# relacionamento com o Revendedor
belongs_to :user
# virtual fields
attr_accessor :cpf, :original_value
# emun status da compra
enum status: [ :in_validation, :approved ]
# validações e campos obrigatórios
before_validation :set_value, on: [:create, :update]
before_validation :set_status, on: [:create]
before_save :calc_cashback, on: [:create, :update]
validates :cpf, presence: true, on: :create
validates :purchase_date, presence: true
validates :code, presence: true
validates :value, presence: true, numericality: { greater_than: 0, less_than: 1000000 }
validate :check_cpf_owner?, on: :create
validate :allow_update, on: :update
# valida status antes da exclusão
before_destroy do
cannot_delete_approved
throw(:abort) if errors.present?
end
# define status da compra antes da inclusão
def set_status
if !self.cpf.blank?
@user_approved = UserApproved.where(cpf: self.raw_cpf).first
if !@user_approved.nil?
self.status = 'approved'
else
self.status = 'in_validation'
end
end
end
# valida se status permite alteração da compra
def allow_update
if self.status != 'in_validation'
errors.add(:status, :not_valid, message: "atual da compra não permite alteração")
throw(:abort) if errors.present?
end
end
# CPF somente números
def raw_cpf
self.cpf.gsub('.','').gsub('-','') if !self.cpf.nil?
end
# tratamento para atribuição do valor da compra
def set_value
self.value = self.original_value.to_s.gsub(',','.') if !self.value.nil?
end
# status em portugês
def status_desc
Purchase.human_enum_name(:status, self.status)
end
# formatação do valor
def value_formated
ActionController::Base.helpers.number_to_currency(self.value, :unit => "R$ ", :separator => ",", :delimiter => ".")
end
# formatação do cashback
def cashback_formated
ActionController::Base.helpers.number_to_currency(self.cashback, :unit => "R$ ", :separator => ",", :delimiter => ".")
end
# metodo para formatação da consulta de compras
def as_json options={}
{
id: id,
code: code,
value: value_formated,
date: purchase_date.strftime("%d/%m/%Y"),
cash_back_percent: cashback_percentual.to_s,
cash_back_value: cashback_formated,
status: self.status_desc
}
end
# calcula cashback da compra
def calc_cashback
@percent = CashBackRange.where('? between min_value and max_value', self.value).first
if @percent.nil?
errors.add(:base, 'A tabela com as faixas de cashback não foi inicializada')
throw(:abort) if errors.present?
else
self.cashback_percentual = @percent.percentage
self.cashback = ((self.value.to_f/100)*@percent.percentage).round(2)
end
end
private
# status aprovado não permite exclusão
def cannot_delete_approved
errors.add(:base, 'Status da compra não permite exclusão') if self.status != 'in_validation'
end
# valida se o CPF da compra é o mesmo do usuário
def check_cpf_owner?
if self.raw_cpf != self.user.raw_cpf
errors.add(:base, 'CPF inválido. CPF não corresponde ao revendedor logado')
end
if errors.present?
false
else
true
end
end
end
|
Markdown
|
UTF-8
| 5,032 | 2.609375 | 3 |
[] |
no_license
|
---
description: "Steps to Prepare Award-winning Easy! My Melody Onigiri For Charaben (Decorative Bentos)"
title: "Steps to Prepare Award-winning Easy! My Melody Onigiri For Charaben (Decorative Bentos)"
slug: 1116-steps-to-prepare-award-winning-easy-my-melody-onigiri-for-charaben-decorative-bentos
date: 2020-09-20T11:25:03.237Z
image: https://img-global.cpcdn.com/recipes/6503871160516608/751x532cq70/easy-my-melody-onigiri-for-charaben-decorative-bentos-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/6503871160516608/751x532cq70/easy-my-melody-onigiri-for-charaben-decorative-bentos-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/6503871160516608/751x532cq70/easy-my-melody-onigiri-for-charaben-decorative-bentos-recipe-main-photo.jpg
author: Mary Mitchell
ratingvalue: 5
reviewcount: 37456
recipeingredient:
- "1 Hot cooked white rice"
- "1 Colorful pink decofuri furikake"
- "1/2 slice Cheese"
- "1 dash Ham"
- "1 dash Nori seaweed"
- "1 dash A thin vegetable sheet sold in stores or a piece of thin omelette or cheese"
recipeinstructions:
- "Mix the "decofuri" furikake with the rice. Divide the rice into 3 portions - a large one for the face and 2 small portions for the ears. Form each portion into a ball."
- "Put the balls into a bento box. If the ears fall off, affix them to the head with pieces of long thin pasta."
- "Make an oval shape from kitchen parchment paper, and use it as a pattern to cut an oval shape from the cheese using a toothpick."
- "Make the facial features: The face...cheese; the mouth...nori seaweed; the nose...a piece of vegetable sheet, omelette or cheese. If you layer the cheese on top of a slice of ham, it will be more stable and not get too soft."
- "Put the facial features on, and it's done. Add hands and accessories to make it cute."
- "These are the special bento decorating tools I used."
- "For this version I added a bonnet made out of ham."
- "Please make your own My Melody variations."
categories:
- Recipe
tags:
- easy
- my
- melody
katakunci: easy my melody
nutrition: 205 calories
recipecuisine: American
preptime: "PT15M"
cooktime: "PT50M"
recipeyield: "2"
recipecategory: Lunch
---

Hey everyone, hope you are having an incredible day today. Today, I will show you a way to make a special dish, easy! my melody onigiri for charaben (decorative bentos). One of my favorites. For mine, I am going to make it a little bit unique. This is gonna smell and look delicious.
Easy! My Melody Onigiri For Charaben (Decorative Bentos) is one of the most popular of current trending foods on earth. It is easy, it is fast, it tastes yummy. It's appreciated by millions every day. They are nice and they look fantastic. Easy! My Melody Onigiri For Charaben (Decorative Bentos) is something which I have loved my whole life.
To begin with this particular recipe, we must first prepare a few ingredients. You can have easy! my melody onigiri for charaben (decorative bentos) using 6 ingredients and 8 steps. Here is how you can achieve that.
<!--inarticleads1-->
##### The ingredients needed to make Easy! My Melody Onigiri For Charaben (Decorative Bentos):
1. Get 1 Hot cooked white rice
1. Prepare 1 Colorful pink "decofuri" furikake
1. Prepare 1/2 slice Cheese
1. Take 1 dash Ham
1. Prepare 1 dash Nori seaweed
1. Take 1 dash A thin vegetable sheet (sold in stores; or a piece of thin omelette or cheese)
<!--inarticleads2-->
##### Instructions to make Easy! My Melody Onigiri For Charaben (Decorative Bentos):
1. Mix the "decofuri" furikake with the rice. Divide the rice into 3 portions - a large one for the face and 2 small portions for the ears. Form each portion into a ball.
1. Put the balls into a bento box. If the ears fall off, affix them to the head with pieces of long thin pasta.
1. Make an oval shape from kitchen parchment paper, and use it as a pattern to cut an oval shape from the cheese using a toothpick.
1. Make the facial features: The face...cheese; the mouth...nori seaweed; the nose...a piece of vegetable sheet, omelette or cheese. If you layer the cheese on top of a slice of ham, it will be more stable and not get too soft.
1. Put the facial features on, and it's done. Add hands and accessories to make it cute.
1. These are the special bento decorating tools I used.
1. For this version I added a bonnet made out of ham.
1. Please make your own My Melody variations.
So that's going to wrap this up with this exceptional food easy! my melody onigiri for charaben (decorative bentos) recipe. Thanks so much for your time. I'm sure you will make this at home. There's gonna be interesting food at home recipes coming up. Remember to save this page on your browser, and share it to your family, colleague and friends. Thank you for reading. Go on get cooking!
|
Java
|
UTF-8
| 807 | 3.703125 | 4 |
[] |
no_license
|
public class MethodOverloadingArrayAndMatrix {
public static void main(String[] args) {
int array[] = {2, 5, 6, 8, -5};
int matrix[][] = {{2, 3, 5, 6},
{4, 7, 8, 0}};
System.out.println("sum of the array is -> " + sum(array));
System.out.println("average of matrix is -> " + sum(matrix));
}
public static int sum(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
public static int sum(int[][] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
sum += arr[i][j];
}
}
return sum / (arr.length*arr[0].length);
}
}
|
PHP
|
UTF-8
| 20,057 | 2.78125 | 3 |
[] |
no_license
|
<?php
session_start();
include "databse_con.php";
include "helper.php";
$valid_form = false;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$response = [];
if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'image_update') {
$ext = pathinfo($_FILES["profileImage"]["name"], PATHINFO_EXTENSION);
$valid_ext = array("png", "jpg", "jpeg", "gif");
if(!in_array(strtolower($ext), $valid_ext)){
$response['message'] = "Invalid image file extension.";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
// for the database
$profileImageName = time() . '-' . $_FILES["profileImage"]["name"];
// For image upload
$target_dir = "../assets/images/profile/";
$target_file = $target_dir . basename($profileImageName);
// VALIDATION
// validate image size. Size is calculated in Bytes
if($_FILES['profileImage']['size'] > 2000000) {
$response['message'] = "Image size should not be greater than 2Mb";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
// check if file exists
if(file_exists($target_file)) {
$response['message'] = "File already exists";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
// Upload image only if no errors
if (empty($error)) {
if(move_uploaded_file($_FILES["profileImage"]["tmp_name"], $target_file)) {
$sql = "UPDATE bruker SET img_url='$profileImageName' WHERE id='".$_SESSION['user_id']."'";
if(mysqli_query($conn, $sql)){
$_SESSION['img_url'] = $profileImageName;
$response['img_url'] = $profileImageName;
$response['message'] = "Image uploaded and saved in the Database";
$response['status'] = 'SUCCESS';
echo json_encode($response);
exit();
} else {
$response['message'] = "There was an error in the database";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
}
else {
$response['message'] = "There was an error uploading the file";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
}
}
else if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'change_password') {
$valid_form = false;
if (isset($_POST['password']) && isset($_POST['re_password'])) {
$valid_form = true;
$pass = $_POST['password'];
$re_pass = $_POST['re_password'];
}
if (!$valid_form) {
$response['message'] = "Invalid request data.";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
if ($pass !== $re_pass) {
$response['message'] = "The confirmation password does not match.";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
// hashing the password using SHA1 with Salt
$pass = sha1($pass . $salt);
$sql = "SELECT * FROM bruker WHERE id='".$_SESSION['user_id']."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
if($row['passord'] == $pass){
$response['message'] = "You are not allowed to use the same password.";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
$sql = "UPDATE bruker SET passord='$pass' WHERE id='".$_SESSION['user_id']."'";
$result = mysqli_query($conn, $sql);
if ($result){
$response['message'] = "Your password has been created successfully changed.";
$response['status'] = 'SUCCESS';
echo json_encode($response);
exit();
}else {
$response['message'] = "Change password failed.";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
}
else {
$response['message'] = "Invalid account.";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
}
else if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'add_candidate') {
$valid_form = false;
if (isset($_FILES['profileImage']) && isset($_POST['fakultet']) && isset($_POST['institutt']) && isset($_POST['informasjon']) && isset($_POST['bruker']) && isset($_POST['bruker_epost'])) {
$valid_form = true;
}
$fakultet = validate($_POST['fakultet']);
$institutt = validate($_POST['institutt']);
$informasjon = validate($_POST['informasjon']);
$bruker = validate($_POST['bruker']);
$bruker_epost = validate($_POST['bruker_epost']);
$ext = pathinfo($_FILES["profileImage"]["name"], PATHINFO_EXTENSION);
$valid_ext = array("png", "jpg", "jpeg", "gif");
$error = true;
$error_mess = "";
if (empty($ext)) {
$error_mess = "Image is required";
} else if (empty($fakultet)) {
$error_mess = "Fakultet is required";
} else if (empty($institutt)) {
$error_mess = "Institutt is required";
} else if (empty($informasjon)) {
$error_mess = "Informasjon is required";
} else if (empty($bruker)) {
$error_mess = "Bruker is required";
} else if (empty($bruker_epost)) {
$error_mess = "Bruker epost is required";
} else {
$error = false;
}
if($error){
$response['message'] = $error_mess;
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
if(!in_array(strtolower($ext), $valid_ext)){
$response['message'] = "Invalid image file extension.";
$response['status'] = 'FAILED';
echo json_encode($ext);
exit();
}
// for the database
$profileImageName = time() . '-' . $_FILES["profileImage"]["name"];
// For image upload
$target_dir = "../assets/images/profile/";
$target_file = $target_dir . basename($profileImageName);
// VALIDATION
// validate image size. Size is calculated in Bytes
if($_FILES['profileImage']['size'] > 2000000) {
$response['message'] = "Image size should not be greater than 2Mb";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
// check if file exists
if(file_exists($target_file)) {
$response['message'] = "File already exists";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
$sql = "SELECT * FROM kandidat WHERE bruker_epost='$bruker_epost'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$response['message'] = $bruker_epost . ' is already existed in kandidat list.';
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
} else {
$kandidatcol = rand(1111111111,9999999999);
move_uploaded_file($_FILES["profileImage"]["tmp_name"], $target_file);
$sql2 = "INSERT INTO kandidat(fakultet, institutt, informasjon, kandidatcol, stemmer, bruker_epost, bruker, img_url) VALUES ('$fakultet', '$institutt', '$informasjon', '$kandidatcol', 0, '$bruker_epost', '$bruker', '$profileImageName')";
$result2 = mysqli_query($conn, $sql2);
if ($result2) {
$response['message'] = 'Your candidate has been created successfully';
$response['status'] = 'SUCCESS';
echo json_encode($response);
exit();
}else {
$response['message'] = 'unknown error occurred';
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
}
}
else if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'add_candidate_me') {
$valid_form = false;
if (isset($_POST['fakultet']) && isset($_POST['institutt']) && isset($_POST['informasjon'])) {
$valid_form = true;
}
$fakultet = validate($_POST['fakultet']);
$institutt = validate($_POST['institutt']);
$informasjon = validate($_POST['informasjon']);
$bruker = validate($_SESSION['fname'] . ' ' .$_SESSION['lname']);
$bruker_epost = validate($_SESSION['email']);
$error = true;
$error_mess = "";
if (empty($fakultet)) {
$error_mess = "Fakultet is required";
} else if (empty($institutt)) {
$error_mess = "Institutt is required";
} else if (empty($informasjon)) {
$error_mess = "Informasjon is required";
} else if (empty($bruker)) {
$error_mess = "Bruker is required";
} else if (empty($bruker_epost)) {
$error_mess = "Bruker epost is required";
} else {
$error = false;
}
if($error){
$response['message'] = $error_mess;
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
$profileImageName = $_SESSION['img_url'];
$sql = "SELECT * FROM kandidat WHERE bruker_epost='$bruker_epost'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$response['message'] = $bruker_epost . ' is already existed in kandidat list.';
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
} else {
$kandidatcol = rand(1111111111,9999999999);
$sql2 = "INSERT INTO kandidat(fakultet, institutt, informasjon, kandidatcol, stemmer, bruker_epost, bruker, img_url) VALUES ('$fakultet', '$institutt', '$informasjon', '$kandidatcol', 0, '$bruker_epost', '$bruker', '$profileImageName')";
$result2 = mysqli_query($conn, $sql2);
if ($result2) {
$response['message'] = 'Your candidate has been created successfully';
$response['status'] = 'SUCCESS';
echo json_encode($response);
exit();
}else {
$response['message'] = 'unknown error occurred';
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
}
}
else if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'get_candidate') {
$sql = "SELECT * FROM kandidat order by id desc";
$result = mysqli_query($conn, $sql);
$res = [];
$emparray = array();
if(mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_assoc($result)){
$row['allow_edit'] = false;
if(isset($_SESSION['email']) and $row['bruker_epost'] == $_SESSION['email']){
$row['allow_edit'] = true;
}
$emparray[] = $row;
}
$res['total_count'] = mysqli_num_rows($result);
$res['candidate_list'] = $emparray;
echo json_encode($res);
}
else{
$res['total_count'] = 0;
$res['candidate_list'] = [];
echo json_encode($res);
}
}
else if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'get_candidate_me') {
$sql = "SELECT * FROM kandidat WHERE bruker_epost = '". $_SESSION['email'] ."' order by id desc";
$result = mysqli_query($conn, $sql);
$res = [];
$emparray = array();
if(mysqli_num_rows($result) > 0) {
while($row =mysqli_fetch_assoc($result)){
$emparray[] = $row;
}
$res['total_count'] = mysqli_num_rows($result);
$res['candidate_list'] = $emparray;
echo json_encode($res);
}
else{
$res['total_count'] = 0;
$res['candidate_list'] = [];
echo json_encode($res);
}
}
else if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'update_candidate_me') {
$valid_form = false;
if (isset($_POST['fakultet']) && isset($_POST['institutt']) && isset($_POST['informasjon']) && isset($_POST['kandidat_id'])) {
$valid_form = true;
}
$fakultet = validate($_POST['fakultet']);
$institutt = validate($_POST['institutt']);
$informasjon = validate($_POST['informasjon']);
$kandidat_id = validate($_POST['kandidat_id']);
$error = true;
$error_mess = "";
if (empty($fakultet)) {
$error_mess = "Fakultet is required";
} else if (empty($institutt)) {
$error_mess = "Institutt is required";
} else if (empty($informasjon)) {
$error_mess = "Informasjon is required";
} else {
$error = false;
}
if($error){
$response['message'] = $error_mess;
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
$sql = "UPDATE kandidat SET fakultet='$fakultet',institutt='$institutt',informasjon='$informasjon' WHERE bruker_epost='".$_SESSION['email']."' and id='$kandidat_id'";
$result = mysqli_query($conn, $sql);
if ($result){
$response['message'] = "Your kandidat Informasjon is successfully updated.";
$response['status'] = 'SUCCESS';
echo json_encode($response);
exit();
}else {
$response['message'] = "Change password failed.";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
}
else if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'withdraw_candidate_me') {
$sql = "DELETE FROM kandidat WHERE bruker_epost = '". $_SESSION['email'] ."'";
$result = mysqli_query($conn, $sql);
if($result){
$response['message'] = "You successfully withraw from the candidacy";
$response['status'] = 'SUCCESS';
echo json_encode($response);
}
else{
$response['message'] = "You failed to withraw from the candidacy";
$response['status'] = 'FAILED';
echo json_encode($response);
}
} else if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'do_vote') {
$candidateid = validate($_POST['candidateid']);
$startforslag = validate($_POST['startforslag']);
$sluttforslag = validate($_POST['sluttforslag']);
$startvalg = validate($_POST['startvalg']);
$sluttvalg = validate($_POST['sluttvalg']);
$informasjon = validate($_POST['informasjon']);
$sql2 = "INSERT INTO valg(idvalg, candidateid, startforslag, sluttforslag, startvalg, sluttvalg, information, kontrollert) VALUES (0, '$candidateid', '$startforslag', '$sluttforslag', '$startvalg', '$sluttvalg', '$informasjon', '')";
$result = mysqli_query($conn, $sql2);
if($result){
$response['message'] = "You successfully voted this candidate";
$response['status'] = 'SUCCESS';
echo json_encode($response);
}
else{
$response['message'] = "You failed to vote";
$response['status'] = 'FAILED';
echo json_encode($response);
}
} else if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'get_users') {
$sql = "SELECT * FROM bruker where brukertype_id != 1 order by id desc";
$result = mysqli_query($conn, $sql);
$res = [];
$emparray = array();
if(mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_assoc($result)){
$emparray[] = $row;
}
$res['total_count'] = mysqli_num_rows($result);
$res['user_list'] = $emparray;
echo json_encode($res);
}
else{
$res['total_count'] = 0;
$res['user_list'] = [];
echo json_encode($res);
}
} else if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'update_userrole') {
$userid = validate($_POST['userid']);
$usertype_id = validate($_POST['usertype']);
$usertype = "";
if($usertype_id == "1") {
$usertype = "Administrator";
} else if ($usertype_id == "2") {
$usertype = "Candidates";
} else if ($usertype_id == "3") {
$usertype = "Voters";
} else {
$usertype = "Controllers";
}
$error = true;
$error_mess = "";
if (empty($userid)) {
$error_mess = "Bruker is required";
} else if (empty($usertype)) {
$error_mess = "User type is required";
} else {
$error = false;
}
if($error){
$response['message'] = $error_mess;
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
$sql = "UPDATE bruker SET brukertype_id='$usertype_id ',brukertype='$usertype' WHERE id='".$userid."'";
$result = mysqli_query($conn, $sql);
if ($result){
$response['message'] = "Your bruker type is successfully updated.";
$response['status'] = 'SUCCESS';
echo json_encode($response);
exit();
}else {
$response['message'] = "Change bruker type failed.";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
} else if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'get_valg') {
$sql = "SELECT * FROM valg INNER JOIN kandidat ON valg.candidateid = kandidat.id";
$result = mysqli_query($conn, $sql);
$res = [];
$emparray = array();
if(mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_assoc($result)){
$emparray[] = $row;
}
$res['total_count'] = mysqli_num_rows($result);
$res['valg_list'] = $emparray;
echo json_encode($res);
}
else{
$res['total_count'] = 0;
$res['valg_list'] = [];
echo json_encode($res);
}
exit;
} else if(isset($_POST['endpoint']) && $_POST['endpoint'] == 'add_election') {
$title = validate($_POST['title']);
$startvalg = validate($_POST['startvalg']);
$sluttvalg = validate($_POST['sluttvalg']);
$informasjon = validate($_POST['informasjon']);
$sql2 = "INSERT INTO duration(id,startvalg, sluttvalg, title, description) VALUES (0, '$startvalg', '$sluttvalg', '$title', '$informasjon')";
$result = mysqli_query($conn, $sql2);
if($result){
$response['message'] = "You successfully added election";
$response['status'] = 'SUCCESS';
echo json_encode($response);
}
else{
$response['message'] = "You failed to add election";
$response['status'] = 'FAILED';
echo json_encode($response);
}
exit;
} else if (isset($_POST['endpoint']) && $_POST['endpoint'] == 'get_election') {
$sql = "SELECT * FROM duration order by id desc";
$result = mysqli_query($conn, $sql);
$res = [];
$emparray = array();
if(mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_assoc($result)){
$emparray[] = $row;
}
$res['total_count'] = mysqli_num_rows($result);
$res['election_list'] = $emparray;
echo json_encode($res);
}
else{
$res['total_count'] = 0;
$res['election_list'] = [];
echo json_encode($res);
}
} else if(isset($_POST['endpoint']) && $_POST['endpoint'] == 'candidate_information') {
$id = $_POST['id'];
$info = $_POST['informasjon'];
$sql = "UPDATE kandidat SET informasjon='$info' WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if ($result){
$response['message'] = "Your kandidat Informasjon is successfully updated.";
$response['status'] = 'SUCCESS';
echo json_encode($response);
exit();
}else {
$response['message'] = "Failed.";
$response['status'] = 'FAILED';
echo json_encode($response);
exit();
}
} else if(isset($_POST['endpoint']) && $_POST['endpoint'] == 'get_vote') {
$sql = "SELECT valg.*, kandidat.* FROM valg JOIN kandidat ON valg.candidateid = kandidat.id";
$result = mysqli_query($conn, $sql);
$res = [];
$emparray = array();
if(mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_assoc($result)){
$emparray[] = $row;
}
$res['total_count'] = mysqli_num_rows($result);
$res['vote_list'] = $emparray;
echo json_encode($res);
}
else{
$res['total_count'] = 0;
$res['vote_list'] = [];
echo json_encode($res);
}
}
|
C#
|
UTF-8
| 1,189 | 3 | 3 |
[
"MIT"
] |
permissive
|
using System;
namespace ComponentTask.Internal
{
internal static class DelegateExtensions
{
/// <summary>
/// Get a diagnostic identifier that best describes this delegate.
/// </summary>
/// <remarks>
/// Only meant for diagnostic purposes, do NOT depend on output being in a specific format.
/// </remarks>
/// <param name="@delegate">Delegate to get an identifier for.</param>
/// <returns>Identifier best describing the given delegate.</returns>
public static string GetDiagIdentifier(this Delegate @delegate)
{
if (@delegate is null)
throw new ArgumentNullException(nameof(@delegate));
try
{
var method = @delegate.Method;
var owner = method.DeclaringType;
return $"{owner.Name}.{method.Name}";
}
catch (MemberAccessException)
{
if (!(@delegate.Target is null))
return $"{@delegate.Target.GetType().Name}.<private>";
return "<private>";
}
}
}
}
|
C++
|
UTF-8
| 4,483 | 2.78125 | 3 |
[] |
no_license
|
#include "proxy.hpp"
void accept_event_callback(struct ev_loop *loop, struct ev_io *watcher, int revents);
void read_event_callback(struct ev_loop *loop, struct ev_io *watcher, int revents);
void sql_line_detection_and_processing(char *str);
/*
*********************************** constructors ***************************************************
*/
Proxy::Proxy() { loop = ev_default_loop(0); }
Proxy::~Proxy() { };
/*
*********************************** proxy socket creation and initializatioin **********************
*/
void Proxy::create_proxy_socket(void)
{
if((proxy_socket_descriptor = socket(PF_INET, SOCK_STREAM, 0)) < 0)
perror("socket error");
bzero(&proxy_addr, sizeof(proxy_addr));
proxy_addr.sin_family = AF_INET;
proxy_addr.sin_port = htons(PROXY_PORT);
proxy_addr.sin_addr.s_addr = INADDR_ANY;
// Bind socket to the address
if (bind(proxy_socket_descriptor, (struct sockaddr*) &proxy_addr, sizeof(proxy_addr)) != 0)
perror("bind error");
// Start listing on the socket
if (listen(proxy_socket_descriptor, 2) < 0)
perror("listen error");
}
/*
************************* creation of the socket for the targeted connection ***********************
*/
void Proxy::create_connection_to_sql_server(void)
{
// Create client socket
if( (socket_for_connection_with_sql = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
perror("socket creation error");
bzero(&sql_addr, sizeof(sql_addr));
sql_addr.sin_family = AF_INET;
sql_addr.sin_port = htons(SQL_SERVER_PORT);
sql_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// Connect to server socket
if(connect(socket_for_connection_with_sql, (struct sockaddr *)&sql_addr, sizeof sql_addr) < 0)
perror("connection error");
w_accept_connection_to_proxy.sql_socket_descriptor = socket_for_connection_with_sql;
}
/*
************************* initialization of the libev_loop *****************************************
*/
void Proxy::init_and_start_watcher_for_the_client_connection_event(void)
{
// Initialize and start a watcher to accepts client requests to the proxy
ev_io_init(&w_accept_connection_to_proxy.io, accept_event_callback, proxy_socket_descriptor, EV_READ);
ev_io_start(loop, &w_accept_connection_to_proxy.io);
ev_loop(loop, 0);
}
/*
********************************* callbacks for the events *****************************************
/* Accept client requests */
void accept_event_callback(struct ev_loop *loop, struct ev_io *watcher, int revents)
{
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int client_sd;
struct my_io *w_client = (struct my_io *)malloc(sizeof(struct my_io));
struct my_io *ptr_to_get_sql_socket_descriptor = (struct my_io*)watcher;
w_client->sql_socket_descriptor = ptr_to_get_sql_socket_descriptor->sql_socket_descriptor;
if(EV_ERROR & revents)
{
// any invalid event;
perror("got invalid event");
return;
}
// Accept client request
client_sd = accept(watcher->fd, (struct sockaddr *)&client_addr, &client_len);
if (client_sd < 0)
{
// client has not been accepted;
perror("accept error");
return;
}
printf("Successfully connected with client.\n");
// Initialize and start watcher to read client requests
ev_io_init(&w_client->io, read_event_callback, client_sd, EV_READ);
ev_io_start(loop, &w_client->io);
}
/* Read client message */
void read_event_callback(struct ev_loop *loop, struct ev_io *watcher, int revents)
{
char buffer[BUFFER_SIZE];
ssize_t read; // <- read;
bzero(buffer, sizeof(buffer));
struct my_io *ptr_to_get_sql_socket_descriptor = (struct my_io*)watcher;
if(EV_ERROR & revents)
{
perror("got invalid event");
return;
}
// Receive message from client socket
read = recv(watcher->fd, buffer, BUFFER_SIZE, 0);
if(read < 0)
{
perror("read error");
return ;
}
if (read == 0)
{
// Stop and free watcher if client socket is closing
ev_io_stop(loop,watcher);
free(watcher);
perror("peer might closing");
return ;
}
auto future = std::async(std::launch::async, &sql_line_detection_and_processing, buffer);
send(ptr_to_get_sql_socket_descriptor->sql_socket_descriptor, buffer, read, 0);
}
void sql_line_detection_and_processing(char *str)
{
std::string s(str);
std::ofstream myfile;
std::smatch match;
const std::regex rgx("(SQL:)(\".*\")");
if (std::regex_match(s, match, rgx))
{
myfile.open("log.txt", std::ios::app);
myfile << match[2] << std::endl;
myfile.close();
}
}
|
Java
|
UTF-8
| 9,137 | 2.984375 | 3 |
[] |
no_license
|
package engine;
import engine.exceptions.OutOfBoardBoundariesException;
import engine.jaxb.schema.generated.Letter;
import javax.xml.soap.Node;
import java.awt.*;
import java.util.List;
import java.util.Random;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
public class Board {
static class Point{
private int x;
private int y;
Point(int _x, int _y){
x = _x;
y = _y;
}
public String printAsStr(){
return "( " + x + ", " + y + " )";
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public int hashCode() {
int hash = 17;
hash = 13 * hash + x + y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this){
return true;
}
if (!(obj instanceof Point)) {
return false;
}
final Point other = (Point) obj;
return this.x == other.x && this.y == other.y;
}
}
public class Cell{
boolean isShown;
String sign;
Cell(String _sign, boolean _isShown) {
isShown = _isShown;
sign = _sign;
}
}
private int leftCards;
private short size; // size of board
private List<GameDataFromXml.DataLetter> kupa = new ArrayList<>();
private Cell [][] board; // for priting
private Map <Letter,List<Point>> initLetters = new HashMap<>(); //for changes during the game
static final short MAX_SIZE = 50;
static final short MIN_SIZE = 5;
public char[][] getBoard_onlySigns() {
char[][] board = new char[size][size];
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
board[row][col] = this.board[row][col].isShown ? this.board[row][col].sign.toCharArray()[0] : ' ';
}
}
return board;
}
public Cell [][] getBoardFullDetails(){
return board;
}
public char [][] getBoardWithAllSignsShown(){
char[][] reSBoard = new char[size][size];
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
reSBoard[row][col] = this.board[row][col].sign.toCharArray()[0];
}
}
return reSBoard;
}
//C'tor
Board(short _size, List<GameDataFromXml.DataLetter> letters, int totalAmountLetters){
Letter toAdd;
Point p;
this.board = new Cell[_size][_size];
size = _size;
//(x,y) point in the board
//if equal amount letters to board size
leftCards = totalAmountLetters;
int numOfInsertions = 0;
while (numOfInsertions < size * size) {
for (GameDataFromXml.DataLetter letter : letters) {
if (numOfInsertions >= size * size) {
break;
}
if (letter.getAmount() > 0) {
toAdd = letter.getLetter();
if (!initLetters.containsKey(toAdd)) {
initLetters.put(toAdd, new ArrayList<>());
}
p = getRandomPoint();
initLetters.get(toAdd).add(p);
board[p.getY()][p.getX()] = new Cell(toAdd.getSign().get(0), false);
letter.setAmount(letter.getAmount() - 1);
leftCards--;
numOfInsertions++;
}
}
}
//build the kupa
kupa.addAll(letters);
}
public Map <Letter,List<Point>> getInitLetters(){return initLetters;}
private Point getRandomPoint() {
int x,y;
Random xy = new Random();
Point p;
boolean toContinue;
do {
toContinue = false;
x = xy.nextInt(size);
y = xy.nextInt(size);
p = new Point(x,y);
for (List<Point> listPoints : initLetters.values()){
if (listPoints.contains(p))
toContinue = true;
}
} while (toContinue);
return p;
}
List<GameDataFromXml.DataLetter> getKupa() {
return kupa;
}
int getKupaAmount(){
return leftCards;
}
void update(List<int[]> points) throws OutOfBoardBoundariesException {
//check valid point
for(int i = 0; i < points.size(); i++) {
Point point = new Point((points.get(i))[1], (points.get(i))[0]);
if (point.getX() > size || point.getX() < 1 || point.getY() > size || point.getY() < 1) {
throw new OutOfBoardBoundariesException();
}
}
for(int i = 0; i < points.size(); i++){
Point point = new Point((points.get(i))[1], (points.get(i))[0]);
board[point.getY()-1][point.getX()-1].isShown = true;
}
}
boolean hasChars(String word) {
for (Character c: word.toCharArray()) {
boolean hasChar = false;
for (Letter letter: initLetters.keySet()) {
if (letter.getSign().get(0).equals(c.toString())) {
for (Point point: initLetters.get(letter)) {
if (board[point.getY()][point.getX()].isShown) {
hasChar = true;
break;
}
}
if (!hasChar) {
return false;
}
}
if (hasChar) {
break;
}
}
}
return true;
}
short getBoardSize(){return size;}
void removeLettersFromBoard(String word) {
Random random = new Random();
List<String> chars = new ArrayList<>();
for (Character c: word.toCharArray()) {
chars.add(c.toString());
}
boolean stop = false;
for (int row = 0; row < size && !stop; row++) {
for (int col = 0; col < size && !stop; col++) {
if (!chars.isEmpty()) {
if (board[row][col].isShown && chars.contains(board[row][col].sign)) {
chars.remove(board[row][col].sign);
for (Letter letter: initLetters.keySet()) {
if (letter.getSign().get(0).equals(board[row][col].sign)) {
initLetters.get(letter).remove(new Point(col, row));
break;
}
}
// add new letter to the board
GameDataFromXml.DataLetter dataLetter;
do {
int letter = random.nextInt(initLetters.size());
dataLetter = kupa.get(letter);
} while(!(dataLetter.getAmount() > 0));
Letter letter = dataLetter.getLetter();
initLetters.get(letter).add(new Point(col, row));
dataLetter.setAmount(dataLetter.getAmount() - 1);
board[row][col].sign = letter.getSign().get(0);
board[row][col].isShown = false;
leftCards--;
}
}
else {
stop = true;
}
}
}
}
public void removePointsFromBoard(List<int[]> pointToRemove) {
List<java.awt.Point> points = new ArrayList<>();
for (int[] point: pointToRemove) {
points.add(new java.awt.Point(point[1], point[0]));
}
removeLettersFromBoard(points);
}
public void removeLettersFromBoard(List <java.awt.Point> pointsToRemove) {
Random random = new Random();
GameDataFromXml.DataLetter dataLetter;
for(java.awt.Point point : pointsToRemove){
int row = (int)point.getY() - 1;
int col = (int)point.getX() - 1;
for (Letter letter: initLetters.keySet()) {
if (letter.getSign().get(0).equals(board[row][col].sign)) {
initLetters.get(letter).remove(new Point(col, row));
break;
}
}
do {
int letter = random.nextInt(initLetters.size());
dataLetter = kupa.get(letter);
} while(!(dataLetter.getAmount() > 0));
Letter letter = dataLetter.getLetter();
initLetters.get(letter).add(new Point(col, row));
dataLetter.setAmount(dataLetter.getAmount() - 1);
board[row][col].sign = letter.getSign().get(0);
board[row][col].isShown = false;
leftCards--;
}
}
public Cell getCellByPos(int x, int y){
return board[y][x];
}
}
|
PHP
|
UTF-8
| 827 | 2.859375 | 3 |
[] |
no_license
|
<?php
class Member extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'members';
protected $fillable = array('id', 'username', 'password', 'nickname', 'email', 'create_at', 'update_at');
public $timestamps = true;
/**
* 获取用户头像 姓名 IP
*
* @param $ids array ID数组
*
* @return array
*/
public function byIds($ids) {
$ids = array_unique($ids);
$ids[] = 0;
$members = Member::whereRaw('id in (' . implode(',', $ids) . ')')
->get(['id', 'avatar', 'nickname', 'ip'])
->toArray();
$data = [];
foreach($members as $member) {
$data[$member['id']] = $member;
}
return $data;
}
}
|
JavaScript
|
UTF-8
| 5,196 | 2.734375 | 3 |
[
"Apache-2.0"
] |
permissive
|
// <<hpp_insert gen/TreeNode.js>>
/**
* Extend FilterCapableTreeNode by adding support for feedback cycle arrows and solvers.
* @typedef DmLinkageTreeNode
*/
class DmLinkageTreeNode extends FilterCapableNode {
constructor(origNode, attribNames, parent) {
super(origNode, attribNames, parent);
if ((this.isPhase() || this.isCondition()) && this.name == 'params' ) {
this.draw.minimized = true;
}
if (parent) { // Retain "highest warning" cell color when collapsed
// Only applies to trajectory parameters:
if (this.paramOpt == false) parent.paramOpt = false;
}
if (this.isPhase()) {
this.draw.varBoxDims = new Dimensions({'count': 0})
}
}
/** Temp fix to gen code reference */
get absPathName() { return this.path; }
/** Use a single filter instead of separate inputs and outputs */
addFilterChild(attribNames) {
if (this.isCondition()) {
this.filter = new FilterNode(this, attribNames, 'variables');
this.children.push(this.filter);
}
}
/** Add ourselves to the parental filter */
addSelfToFilter() { this.parent.filter.add(this); }
/** Remove ourselves from the parental filter */
removeSelfFromFilter() { this.parent.filter.del(this); }
getFilterList() { return [ this.filter ];}
wipeFilters() { this.filter.wipe(); }
addToFilter(node) { this.filter.add(node); }
isPhase() { return this.type == 'phase'; }
isCondition() { return this.type == 'condition'; }
isVariable() { return this.type == 'variable'; }
isTrajectory() { return this.type == 'root'; }
isParameter() { return this.isVariable() && this.class == 'parameter'; }
isTrajectoryParameter() {
return (this.isParameter() && this.parent.parent.isTrajectory()) ||
(this.name == 'params' && this.parent.isTrajectory()); // For the collapsed cell
}
isInputOrOutput() { return this.isVariable(); }
isGroup() { return super.isGroup() || this.isRoot(); }
isFixed() { return this.fixed; }
isLinked() { return this.linked; }
/**
* Determine the highest warning level for the node itself, or
* find the highest warning level of its children.
* @param {Object} colors A list of color definitions.
* @returns {Object} Property color is the chosen color, priority is used within
* this recursive function to help with selection.
*/
warningLevel(colors) {
let clr = colors.variableCell;
let priority = 0;
if (this.isVariable()) {
if (this.isTrajectoryParameter() && this.paramOpt === false) {
clr = colors.falseParamOpt;
priority = 1;
}
else if (this.isParameter()) {
if (this.isFixed()) {
if (this.isLinked()) {
clr = colors.fixedLinkedVariableCell;
priority = 2;
}
}
}
else if (this.isFixed()) {
if (this.isLinked()) {
clr = colors.fixedLinkedVariableCell;
priority = 2;
}
else {
clr = colors.fixedUnlinkedVariableCell;
priority = 1;
}
}
}
else if (this.hasChildren()) { // Must be a collapsed parent
clr = colors.collapsed;
for (const child of this.children) {
if ('warningLevel' in child) {
const level = child.warningLevel(colors);
if (level.priority > priority) {
clr = level.color;
priority = level.priority;
}
}
}
}
return { 'color': clr, 'priority': priority };
}
/**
* Determine if this node or any children are connected.
* @returns True if a connection is found.
*/
isConnected() {
if (this.isVariable()) return this.connected;
if (this.hasChildren()) {
for (const child of this.children) {
if ('isConnected' in child && child.isConnected()) return true;
}
}
return false;
}
/** In the matrix grid, draw a box around variables that share the same boxAncestor() */
boxAncestor(level = 2) {
if (level == 1) { // Return condition reference
if (this.isVariable()) return this.parent;
if (this.isCondition()) return this;
}
else if (level == 2) { // Return phase reference
if (this.isVariable() && this.parent.isPhase()) return this.parent;
if (this.isVariable()) return this.parent.parent;
if (this.isCondition()) return this.parent;
}
return null;
}
/** Not connectable if this is an input group or parents are minimized. */
isConnectable() {
if (this.isVariable() && !this.parent.draw.minimized) return true;
return this.draw.minimized;
}
}
|
Markdown
|
UTF-8
| 2,611 | 3.25 | 3 |
[] |
no_license
|
# pidarr_bot - A telegram bot to control Pidarr
This telegram bot is designed to be used with [Pidarr](https://github.com/AdrienCos/pidarr).
To build it, run `make` from the root of the repo.
To run it, start by settings the following environment variables:
| Variable | Contents | Default value |
| ---------------- | -------------------------------------------------------------------------------------------------------------- | ---------------- |
| `PIDARR_TOKEN` | Telegram bot token | None |
| `PIDARR_CHATID` | ID of the chat between the bot and yourself | None |
| `RADARR_TOKEN` | Radarr API token | None |
| `RADARR_HOST` | Host and path to your Radarr instance | `localhost:7878` |
| `RADARR_PATH` | Path where Radar should add newly added movies | `/movies` |
| `RADARR_QUALITY` | ID of the quality profile to use for newly added movies (query the `/profile` Radarr endpoint to get them all) | `4` (HD 1080p) |
You can then run the bot with `./pidarr_bot`.
## Using Docker
This project comes with a Dockerfile to build the bot in a dedicated image. To build it, simply run `docker build -t $IMAGE_NAME:$IMAGE_TAG .` from the root of the repo.
To run the container, first create a environment file containing the variables listed above, with the following structure:
```
PIDARR_TOKEN=$telegram_bot_token
PIDARR_CHATID=$telegram_chat_id
RADARR_TOKEN=$radarr_api_token
RADARR_HOST=$radarr_host
RADARR_PATH=$radarr_path
RADARR_QUALITY=$radarr_quality
```
You can then create a new container from your image and run it with:
```
docker run --env-file $ENV_FILENAME $IMAGE_NAME:$IMAGE_TAG
```
# How it works
Once the bot is running, you can ask it to search for movies by sending it a message in the form `/movies Movie Name`. The bot will then query the Radarr API to find a list of all movies that match that search term, and return you a list of options in the form an inline keyboard.
Find the movie(s) you want in the list and simply click them. The bot will then call Radarr again to have it add and search for the movies.
|
Shell
|
UTF-8
| 623 | 3.953125 | 4 |
[] |
no_license
|
#!/bin/sh
# Run this as root
if [ "$EUID" -ne 0 ]
then echo "Please run as the root user... exiting."
exit
fi
NETWORK="ansible_ovirt_demo_net"
##
# Check if the network already exist..if so? remove them
#
CHECK_NETWORK=`virsh net-list | grep ${NETWORK}`
if [ "${CHECK_NETWORK}" != "" ]; then
if [ "$1" = 'destroy' ] ; then
(set -x
virsh net-destroy ${NETWORK}
virsh net-undefine ${NETWORK}
)
fi
else
set -x
# define the network
virsh net-define ./${NETWORK}.xml
# start the network
virsh net-start ${NETWORK}
# restart the libvirtd service
systemctl restart libvirtd.service
fi
|
Python
|
UTF-8
| 706 | 3.984375 | 4 |
[] |
no_license
|
'''Q2 of Assignment 5: Vending machine change calculator
Patrick Boroughs
16 April 2014'''
cost = eval(input("Enter the cost (in cents):\n"))
payment=0
while cost>payment:
deposit=eval(input("Deposit a coin or note (in cents):\n"))
payment+=deposit
if payment>cost:
print("Your change is:")
change=payment-cost
if change//100>=1:
print(change//100,"x $1")
change=change%100
if change//25>=1:
print(change//25,"x 25c")
change=change%25
if change//10>=1:
print(change//10,"x 10c")
change=change%10
if change//5>=1:
print(change//5,"x 5c")
change=change%5
if change//1>=1:
print(change,"x 1c")
|
JavaScript
|
UTF-8
| 28,083 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
// DEPENDENCIES
var mysql = require("mysql");
const inquirer = require("inquirer");
const cTable = require("console.table");
const fs = require('fs');
//require("dotenv").config();
// CLASSES
const Employee = require("./lib/Employee");
// MYSQL SETUP
const connection = mysql.createConnection({
host: "localhost",
// Your port; if not 3306
port: 3306,
// Your username
user: "root",
//password: process.env.DB_PASS,
//database: process.env.DB_NAME
// Your password
password: "ENTER PASSWORD", //Please enter your database password here
database: "employeetracker_db"
});
// Connect to database
connection.connect(function (err) {
if (err) throw err;
console.log("connected as id " + connection.threadId);
init();
});
// Async Get Managers
async function getManagersAsync(array) {
let managers = [];
for (let i = 0; i < array.length; i++) {
await managers.push(array[i].manager);
}
return managers;
}
// Async Get Departments
async function getDepartmentsAsync(array) {
let departments = [];
for (let i = 0; i < array.length; i++) {
await departments.push(array[i].name);
}
return departments;
}
// Async Get Role
async function getRolesAsync(array) {
let roles = [];
for (let i = 0; i < array.length; i++) {
await roles.push(array[i].title);
}
return roles;
}
// Async Get Employees
async function getEmployeesAsync(array) {
let employeesArray = [];
for (let i = 0; i < array.length; i++) {
await employeesArray.push(`${array[i].name}`);
}
return employeesArray;
}
// Add Another?
function addAnother(returnTo) {
inquirer
.prompt({
name: "addAnother",
type: "list",
message: "Add another?",
choices: ["yes", "no"]
}).then(response => {
if (response.addAnother === "yes") {
if (returnTo === "addEmployee") {
addEmployee();
} else if (returnTo === "addDepartment") {
addDepartment();
} else if (returnTo === "addRole") {
addRole();
}
} else {
initMenu();
}
});
}
// Start Application
function init() {
console.log("------------------------------------------------------------------------------");
console.log("--------------------- WELCOME TO EMPLOYEE TRACKER ------------------------");
console.log("------------------------------------------------------------------------------");
initMenu();
};
// Main menu
function initMenu() {
inquirer
.prompt({
name: "initMenu",
type: "list",
message: "What would you like to do?",
choices: [
"View All Employees",
"View All Employees By Department",
"View All Employees By Manager",
"Add Employee",
"Remove Employee",
"Update Employee Title",
"Update Employee Manager",
new inquirer.Separator(),
"View All Departments",
"Add Department",
"Remove Department",
new inquirer.Separator(),
"View All Roles",
"Add Role",
"Remove Role",
new inquirer.Separator(),
"Total Utilized Budget By Department",
new inquirer.Separator(),
"Exit",
new inquirer.Separator()
]
}).then(response => {
switch (response.initMenu) {
case "View All Employees":
return queryEmployees("", "");
case "View All Employees By Department":
return employeeByDepartment();
case "View All Employees By Manager":
return employeeByManager();
case "Add Employee":
return addEmployee();
case "Remove Employee":
return removeEmployee();
case "Update Employee Title":
return updateEmployee("title");
case "Update Employee Manager":
return updateEmployee("manager");
case "View All Departments":
return viewDepartments();
case "Add Department":
return addDepartment();
case "Remove Department":
return removeDepartment();
case "View All Roles":
return viewRoles();
case "Add Role":
return addRole();
case "Remove Role":
return removeRole();
case "Total Utilized Budget By Department":
return totalBudgetDepartment();
case "Exit":
return connection.end();
}
});
}
// Query Employees
function queryEmployees(type, filter) {
let query = "SELECT e.id, e.first_name, e.last_name, title, name, salary, CONCAT_WS(' ', e2.first_name, e2.last_name) manager FROM employee e ";
query += "LEFT JOIN role ";
query += "ON role_id = role.id ";
query += "LEFT JOIN department ";
query += "ON role.department_id = department.id ";
query += "LEFT JOIN employee e2 ON e.manager_id = e2.id ";
if (type === "manager") {
query += "WHERE CONCAT_WS(' ', e2.first_name, e2.last_name) = ? ";
}
else if (type === "department") {
query += "WHERE name = ? ";
}
query += "ORDER BY e.id ASC";
connection.query(query, [filter], (err, res) => {
if (err) throw err;
let employeeArray = [];
res.forEach(employee => {
const newEmployee = new Employee(employee.id, employee.first_name, employee.last_name, employee.title, employee.name, employee.salary, employee.manager);
employeeArray.push(newEmployee);
});
console.table(employeeArray);
initMenu();
});
}
// Get Employee by Manager
function employeeByManager() {
let query = "SELECT DISTINCT CONCAT_WS(' ', e2.first_name, e2.last_name) manager FROM employee e ";
query += "INNER JOIN employee e2 ON e.manager_id = e2.id ";
query += "ORDER BY e.id ASC";
connection.query(query, (err, res) => {
if (err) throw err;
// Get managers asynchronously
getManagersAsync(res).then(result => {
inquirer
.prompt({
name: "selManager",
type: "list",
message: "Selected a manager to filter by:",
choices: result
}).then(response => {
queryEmployees("manager", response.selManager);
});
});
});
}
// Get Employee by Department
function employeeByDepartment() {
let query = "SELECT name FROM department ";
query += "ORDER BY id ASC";
connection.query(query, (err, res) => {
if (err) throw err;
// Get departments asynchronously
getDepartmentsAsync(res).then(result => {
inquirer
.prompt({
name: "selDepartment",
type: "list",
message: "Selected a department to filter by:",
choices: result
}).then(response => {
queryEmployees("department", response.selDepartment);
});
});
});
}
// Create Employee
function addEmployee() {
let query = "SELECT title FROM role ";
query += "ORDER BY id ASC";
connection.query(query, (err, res) => {
if (err) throw err;
// Get roles asynchronously
getRolesAsync(res).then(result => {
inquirer
.prompt([
{
type: "input",
message: "Enter employee first name:",
name: "firstName"
},
{
type: "input",
message: "Enter employee last name:",
name: "lastName"
},
{
type: "list",
message: "Select employee title:",
name: "selRole",
choices: result
}
]).then(response => {
if (response.firstName === "" || response.lastName === "") {
console.log("No employee added. Field(s) were blank.")
return initMenu();
}
let query = "SELECT id, CONCAT_WS(' ', first_name, last_name) name FROM employee ";
query += "ORDER BY id ASC";
connection.query(query, (err, res) => {
if (err) throw err;
getEmployeesAsync(res).then(result2 => {
result2.push(new inquirer.Separator(), "Null", new inquirer.Separator());
inquirer
.prompt([
{
type: "list",
message: "Select employee manager:",
name: "selManager",
choices: result2
}
]).then(response2 => {
let newEmployee = {};
if (response2.selManager === "Null") {
newEmployee = {
first_name: response.firstName,
last_name: response.lastName,
role_id: res[result.indexOf(response.selRole)].id
}
} else {
newEmployee = {
first_name: response.firstName,
last_name: response.lastName,
role_id: res[result.indexOf(response.selRole)].id,
manager_id: res[result2.indexOf(response2.selManager)].id
}
}
connection.query("INSERT INTO employee SET ?",
newEmployee,
(err, res) => {
if (err) throw err;
console.log(`${newEmployee.first_name} ${newEmployee.last_name} has been added.`);
addAnother("addEmployee");
});
});
});
});
});
});
});
}
// Remove Employee
function removeEmployee() {
let query = "SELECT id, CONCAT_WS(' ', first_name, last_name) name FROM employee ";
query += "ORDER BY id ASC";
connection.query(query, (err, res) => {
if (err) throw err;
getEmployeesAsync(res).then(result => {
result.push(new inquirer.Separator(), "Cancel", new inquirer.Separator());
inquirer
.prompt([
{
type: "list",
message: "Select employee to remove:",
name: "selEmployee",
choices: result
}
]).then(response => {
if (response.selEmployee === "Cancel") {
initMenu();
} else {
inquirer
.prompt([
{
type: "list",
message: `Are you sure you want to remove ${response.selEmployee}?`,
name: "areYouSure",
choices: ["yes", "no"]
}
]).then(response2 => {
if (response2.areYouSure === "yes") {
let employeeId = res[result.indexOf(response.selEmployee)].id;
//console.log(employeeId);
connection.query("DELETE FROM employee WHERE ?",
{
id: employeeId
},
(err, res) => {
if (err) throw err;
console.log(`${response.selEmployee} employee has been removed.`);
initMenu();
}
);
} else {
initMenu();
}
});
}
});
});
});
}
// Update Employee
function updateEmployee(type) {
let query = "SELECT id, CONCAT_WS(' ', first_name, last_name) name FROM employee ";
query += "ORDER BY id ASC";
connection.query(query, (err, res) => {
if (err) throw err;
getEmployeesAsync(res).then(result => {
result.push(new inquirer.Separator(), "Cancel", new inquirer.Separator());
inquirer
.prompt([
{
type: "list",
message: "Select employee to update title of:",
name: "selEmployee",
choices: result
}
]).then(response => {
if (response.selEmployee === "Cancel") {
initMenu();
} else {
// Update Title
if (type === "title") {
let query = "SELECT id, title FROM role ";
query += "ORDER BY id ASC";
connection.query(query, (err, res2) => {
if (err) throw err;
// Get roles asynchronously
getRolesAsync(res2).then(result2 => {
inquirer
.prompt([
{
type: "list",
message: "Select employee title:",
name: "selRole",
choices: result2
}
]).then(response2 => {
connection.query(
"UPDATE employee SET ? WHERE ?",
[
{
// set to
role_id: res2[result2.indexOf(response2.selRole)].id
},
{
// select
id: res[result.indexOf(response.selEmployee)].id
}
],
function (err, res) {
if (err) throw err;
console.log(`${response.selEmployee}'s title has been updated.`);
initMenu();
}
);
});
});
});
}
// Update Manager
if (type === "manager") {
let query = "SELECT id, CONCAT_WS(' ', first_name, last_name) name FROM employee ";
query += "ORDER BY id ASC";
connection.query(query, (err, res2) => {
if (err) throw err;
getEmployeesAsync(res2).then(result2 => {
result2.push(new inquirer.Separator(), "Null", new inquirer.Separator());
inquirer
.prompt([
{
type: "list",
message: "Select employee manager:",
name: "selManager",
choices: result2
}
]).then(response2 => {
let updateQuery = "";
let updateInputs = [];
if (response2.selManager === "Null") {
updateQuery = "UPDATE employee SET manager_id = NULL WHERE ?";
updateInputs = [
{
id: res[result.indexOf(response.selEmployee)].id
}
];
} else {
updateQuery = "UPDATE employee SET ? WHERE ?";
updateInputs = [
{
manager_id: res2[result2.indexOf(response2.selManager)].id
},
{
id: res[result.indexOf(response.selEmployee)].id
}
]
}
connection.query(
updateQuery,
updateInputs,
function (err, res) {
if (err) throw err;
console.log(`${response.selEmployee}'s manager has been updated.`);
initMenu();
}
);
});
});
});
}
}
});
});
});
}
// View All Departments
function viewDepartments() {
let query = "SELECT id, name FROM department ";
query += "ORDER BY id ASC";
connection.query(query, (err, res) => {
if (err) throw err;
departmentArray = [];
res.forEach(department => {
departmentArray.push({ id: department.id, department: department.name })
})
console.table(departmentArray);
initMenu();
});
}
// Add Department
function addDepartment() {
inquirer
.prompt([
{
type: "input",
message: "Enter name for new department:",
name: "depName"
}
]).then(response => {
if (response.depName == "") {
console.log("No department added. Name was blank.")
return initMenu();
}
connection.query("INSERT INTO department SET ?",
[{ name: response.depName }],
(err, res) => {
if (err) throw err;
console.log(`${response.depName} department has been added.`);
addAnother("addDepartment");
});
});
}
// Remove Department
function removeDepartment() {
let query = "SELECT id, name FROM department ";
query += "ORDER BY id ASC";
connection.query(query, (err, res) => {
if (err) throw err;
getDepartmentsAsync(res).then(result => {
inquirer
.prompt({
name: "selDepartment",
type: "list",
message: "Selected a department to remove:",
choices: result
}).then(response => {
inquirer
.prompt([
{
type: "list",
message: `Are you sure you want to remove ${response.selDepartment}?`,
name: "areYouSure",
choices: ["yes", "no"]
}
]).then(response2 => {
if (response2.areYouSure === "yes") {
let departmentId = res[result.indexOf(response.selDepartment)].id;
connection.query("DELETE FROM department WHERE ?",
{
id: departmentId
},
(err, res) => {
if (err) throw err;
console.log(`${response.selDepartment} department has been removed.`);
initMenu();
}
);
} else {
initMenu();
}
})
});
});
});
}
// View All Roles
function viewRoles() {
let query = "SELECT r.id, r.title, r.salary, d.name FROM role r ";
query += "LEFT JOIN department d ON r.department_id = d.id ";
query += "ORDER BY r.id ASC";
connection.query(query, (err, res) => {
if (err) throw err;
roleArray = [];
res.forEach(role => {
roleArray.push({ id: role.id, title: role.title, salary: role.salary, department: role.name })
});
console.table(roleArray);
initMenu();
});
}
// Add Role
function addRole() {
let query = "SELECT id, name FROM department ";
query += "ORDER BY id ASC";
connection.query(query, (err, res) => {
if (err) throw err;
getDepartmentsAsync(res).then(result => {
inquirer
.prompt({
name: "selDepartment",
type: "list",
message: "Selected a department to add a new role too:",
choices: result
}).then(response => {
let departmentId = res[result.indexOf(response.selDepartment)].id;
inquirer
.prompt([
{
type: "input",
message: "Enter title for new role:",
name: "roleTitle"
},
{
type: "input",
message: "Enter salary for new role:",
name: "roleSalary"
}
]).then(response => {
if (response.roleTitle == "" || response.roleSalary == "") {
console.log("No role added. Field(s) were blank.")
return initMenu();
}
connection.query("INSERT INTO role SET ?",
[{ title: response.roleTitle, salary: response.roleSalary, department_id: departmentId }],
(err, res) => {
if (err) throw err;
console.log(`${response.roleTitle} role has been added.`);
addAnother("addRole");
});
});
});
});
});
}
// Remove Role
function removeRole() {
let query = "SELECT id, title FROM role ";
query += "ORDER BY id ASC";
connection.query(query, (err, res) => {
if (err) throw err;
getRolesAsync(res).then(result => {
inquirer
.prompt({
name: "selRole",
type: "list",
message: "Selected a role to remove:",
choices: result
}).then(response => {
inquirer
.prompt([
{
type: "list",
message: `Are you sure you want to remove ${response.selRole}?`,
name: "areYouSure",
choices: ["yes", "no"]
}
]).then(response2 => {
if (response2.areYouSure === "yes") {
let roleId = res[result.indexOf(response.selRole)].id;
connection.query("DELETE FROM role WHERE ?",
{
id: roleId
},
(err, res) => {
if (err) throw err;
console.log(`${response.selRole} role has been removed.`);
initMenu();
}
);
} else {
initMenu();
}
})
});
});
});
}
// Total utilized budget by department
function totalBudgetDepartment() {
let query = "SELECT name department, SUM(salary) salaries FROM ( ";
query += "SELECT role_id, COUNT(*) ";
query += "FROM employee ";
query += "GROUP BY role_id ";
query += ") AS roleCount JOIN role ON role.id = roleCount.role_id ";
query += "LEFT JOIN department d ON department_id = d.id ";
query += "GROUP BY department_id";
connection.query(query, (err, res) => {
if (err) throw err;
console.table(res)
initMenu();
})
}
|
SQL
|
UTF-8
| 524 | 3.09375 | 3 |
[] |
no_license
|
database sysmaster;
drop database lportal;
create database lportal WITH LOG;
create procedure 'lportal'.isnull(test_string varchar)
returning boolean;
IF test_string IS NULL THEN
RETURN 't';
ELSE
RETURN 'f';
END IF
end procedure;
create table models_MobilePhone (
id_ int8 not null primary key,
name varchar(75),
brand varchar(75),
description varchar(255),
releaseDate datetime YEAR TO FRACTION,
price float
)
extent size 16 next size 16
lock mode row;
create index IX_6176737C on models_MobilePhone (name);
|
Java
|
UTF-8
| 785 | 1.804688 | 2 |
[
"MIT"
] |
permissive
|
package uk.gov.hmcts.ecm.common.model.helper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@Data
@AllArgsConstructor
@Builder
public class DefaultValues {
private String positionType;
private String claimantTypeOfClaimant;
private String tribunalCorrespondenceAddressLine1;
private String tribunalCorrespondenceAddressLine2;
private String tribunalCorrespondenceAddressLine3;
private String tribunalCorrespondenceTown;
private String tribunalCorrespondencePostCode;
private String tribunalCorrespondenceTelephone;
private String tribunalCorrespondenceFax;
private String tribunalCorrespondenceDX;
private String tribunalCorrespondenceEmail;
private String managingOffice;
private String caseType;
}
|
Java
|
UTF-8
| 1,291 | 2.28125 | 2 |
[] |
no_license
|
package hazelcast.com.sample;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.EntryListener;
import com.hazelcast.core.MapEvent;
public class MyMapEntryListener implements EntryListener<Long, Client> {
public void entryAdded(EntryEvent<Long, Client> event) {
System.out.println("Thread Name: "+Thread.currentThread().getName());
System.out.println("entryAdded:" + event);
}
public void entryRemoved(EntryEvent<Long, Client> event) {
System.out.println("Thread Name: "+Thread.currentThread().getName());
System.out.println("entryRemoved:" + event);
}
public void entryUpdated(EntryEvent<Long, Client> event) {
System.out.println("Thread Name: "+Thread.currentThread().getName());
System.out.println("entryUpdated:" + event);
}
public void entryEvicted(EntryEvent<Long, Client> event) {
System.out.println("Thread Name: "+Thread.currentThread().getName());
System.out.println("entryEvicted:" + event);
}
public void mapEvicted(MapEvent event) {
System.out.println("Thread Name: "+Thread.currentThread().getName());
System.out.println("mapEvicted:" + event);
}
public void mapCleared(MapEvent event) {
System.out.println("Thread Name: "+Thread.currentThread().getName());
System.out.println("mapCleared:" + event);
}
}
|
Java
|
UTF-8
| 532 | 2.6875 | 3 |
[] |
no_license
|
package com.Anukul.Vaccination.VaccinationApp.models;
public enum AgeLimit {
AGE0TO45(0,45),
AGE18TO45(18,45),
AGE45TO60(45,60),
AGE0TOABOVE(0,Integer.MAX_VALUE),
AGE60TOABOVE(60,Integer.MAX_VALUE),
AGE18TOABOVE(18,Integer.MAX_VALUE),
AGE45TOABOVE(45,Integer.MAX_VALUE);
Integer minAge;
Integer maxAge;
private AgeLimit(Integer minAge, Integer maxAge) {
this.minAge = minAge;
this.maxAge = maxAge;
}
public Integer getMinAge() {
return minAge;
}
public Integer getMaxAge() {
return maxAge;
}
}
|
PHP
|
UTF-8
| 2,251 | 2.625 | 3 |
[] |
no_license
|
<?php
//echo 1;die;
echo ini_get('max_input_time');
echo ini_get('upload_max_filesize');
include("config/config.php");
if(!isset($_SESSION['uinfoadmin'])) header("Location: login.php");
// Nếu người dùng click Upload
if (isset($_POST['submit']))
{
// Nếu người dùng có chọn file để upload
if (isset($_FILES['file']))
{
// Nếu file upload không bị lỗi,
// Tức là thuộc tính error > 0
if ($_FILES['file']['error'] > 0)
{
echo 'File Upload Bị Lỗi';
}
else{
$rootfolder= "uploads/file/";
$targetFolder = empty($_POST['path']) ? $rootfolder.date('Y/m/d') : ltrim($_POST['path'],'/') ; // Relative to the root
$targetFolder = rtrim($targetFolder,'/');
$fileParts = pathinfo($_FILES['file']['name']);
$tempFile = $_FILES['file']['tmp_name'];
$folder_name = '/';
if($_POST['create_folder_type'] == 'true'){
$folder_name = '/general/';
if(in_array($fileParts['extension'],array('jpg','jpeg','gif','png'))){
$folder_name = '/picture/';
}
if(in_array($fileParts['extension'],array('mp4','avi','mkv'))){
$folder_name = '/video/';
}
if(in_array($fileParts['extension'],array('mp3','m4a'))){
$folder_name = '/audio/';
}
}
$targetPath =$targetFolder . $folder_name;
if (!file_exists($targetPath)) mkdir($targetPath, 0777, true);
$targetFile = $targetPath . str_replace(" ","_",$file_name);
// Upload file
$rs = move_uploaded_file($tempFile, $targetPath);
if ($rs) {
$file_path = $targetFolder . $folder_name . $file_name;
echo 'Upload thành công: '.$file_path;
}else{
echo 'Upload thất bại.';
}
}
}
else{
echo 'Bạn chưa chọn file upload';
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="UPLOAD" name="submit">
</form>
|
PHP
|
UTF-8
| 336 | 3.3125 | 3 |
[] |
no_license
|
<?php
echo str_replace("ASP", "PHP", "I love ASP, ASP said");
echo "<br>";
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
$newstr = str_replace($order, $replace, $str);
echo $newstr;
?>
|
Shell
|
UTF-8
| 95 | 2.921875 | 3 |
[] |
no_license
|
#!/bin/bash
#
#check whether no is positve
#
if test $1 -ge 0
then
echo "Number is positu"
fi
|
C++
|
UTF-8
| 716 | 2.859375 | 3 |
[] |
no_license
|
/**
* Author: Lijing Wang
* Date: 5/7/2015
*/
#pragma once
#include "key.hpp"
namespace ndn {
class Verificator
{
public:
Verificator()
{
Name identity(IDENTITY_NAME);
Name keyName = m_keyChain.getDefaultKeyNameForIdentity(identity);
m_publicKey = m_keyChain.getPublicKey(keyName);
};
bool
onPacket(Consumer& c, const Data& data)
{
if (Validator::verifySignature(data, *m_publicKey))
{
// std::cout << "VERIFIED " << data.getName() << std::endl;
return true;
}
else
{
std::cout << "UNVERIFIED " << data.getName() << std::endl;
return false;
}
}
private:
KeyChain m_keyChain;
shared_ptr<PublicKey> m_publicKey;
};
} // namespace ndn
|
Python
|
UTF-8
| 1,965 | 3.140625 | 3 |
[] |
no_license
|
#!/usr/bin/python2
import re
def detail_file_extract(detail_fp):
"""
Given file pointer to detail file, extract information into form below:
return [{"detail":value, "detail":value, ...}, ...]
"""
######################
# Step 1) Build Legend
###
# Travel to the legend.
for line in detail_fp:
if line == "# Legend:\n": break
# Consume the legend.
details = []
for line in detail_fp:
if line == "\n": break
details.append(line.split(":")[-1].strip())
######################
# Step 2) Consume Organisms
###
orgs = {}
org_cnt = 0
for line in detail_fp:
org_dets = line.strip().split(" ")
org = {details[i].lower():org_dets[i] for i in range(0, len(org_dets))}
org_id = -1
if "genotype id" in org:
org_id = org["genotype id"]
else:
org_id = org_cnt
orgs[org_id] = org
org_cnt += 1
return orgs
def extract_lineage_from_detail_file(detail_fp):
"""
Given detail file pointer of a lineage, parse. Return as dictionary.
"""
# Find column labels
col_labels = []
lineage_details = []
for line in detail_fp:
if line.strip() == "# Legend:": break
# Collect column labels
for line in detail_fp:
if line.strip() == "": break
m = re.search(pattern = "#\s[0-9]+:\s([\w\s]+)", string = line)
col_labels.append(m.group(1).strip().lower())
# Collect ancestor details
for line in detail_fp:
ancestor_details = line.strip().split(" ")
lineage_details.append({col_labels[i]: ancestor_details[i] for i in range(0, len(ancestor_details))})
return lineage_details
def genome_from_genfile(gen_fp):
"""
Given a file pointer to a .gen (from avida analyze mode), return the genome as a list of instructions.
"""
return [line.strip() for line in gen_fp if (line.strip() != "") and (not "#" in line)]
|
Python
|
UTF-8
| 651 | 3.546875 | 4 |
[
"MIT"
] |
permissive
|
# Matrix generator module
import numpy as np
import random as rnd
def gen_random_matrix(n):
return np.array(np.random.random([n, n]))
def gen_diagonally_dominant_matrix(n):
matrix = gen_random_matrix(n)
sum = 0
for i in range(n):
for j in range(n):
if i != j:
sum += abs(matrix[i][j])
for i in range(n):
matrix[i][i] = rnd.uniform(sum, 10 * sum)
return matrix
def gen_hilbert_matrix(n):
res = []
for i in range(n):
row = []
for j in range(n):
e = 1.0 / (i + j + 1)
row.append(e)
res.append(row)
return np.array(res)
|
Markdown
|
UTF-8
| 3,607 | 3.6875 | 4 |
[
"MIT"
] |
permissive
|
# Day 8: I Heard You Like Registers
The crux of this problem is to be able to parse the instructions
and carry them out. The basic data structure used is a Dictionary
to hold the registers. The `Dictionary at: ifAbsent:` method is
very handy when it comes to incrementing and decrementing registers
that have not been seen before.
I used blocks to represent the increment/decrement operations as well as
the comparison operations. Then it was a matter of just invoking the
appropriate block when necessary.
The top level is to process the entire output:
```smalltalk
Day8Solver >> processInput: anInput
(anInput findTokens: String cr) do: [ :line | self processLine: line ]
```
A separate method is used to process each individual line:
```smalltalk
Day8Solver >> processLine: aLine
| tokens incReg incVal incOp predReg predOp predVal |
tokens := aLine findTokens: ' '.
incReg := tokens at: 1.
incVal := (tokens at: 3) asInteger.
incOp := (tokens at: 2) = 'inc'
ifTrue: [ [ self incrementRegister: incReg by: incVal ] ]
ifFalse: [ [ self decrementRegister: incReg by: incVal ] ].
predReg := tokens at: 5.
predVal := (tokens at: 7) asInteger.
predOp := [ (self predicateOperators at: (tokens at: 6)) value: (registers at: predReg ifAbsent: 0) value: predVal ].
predOp value
ifTrue: [ incOp value ]
```
Notice that this uses the Dictionary `predicateOperators` to determine which
block to use for the comparison. This Dictionary is initialized in the
`Day8Solver >> initialize` method.
```smalltalk
Day8Solver >> initialize
self registers: Dictionary new.
self highWaterMark: 0.
self
predicateOperators:
(Dictionary
newFromPairs:
{'=='.
[ :a :b | a = b ].
'!='.
[ :a :b | a ~= b ].
'<'.
[ :a :b | a < b ].
'>'.
[ :a :b | a > b ].
'<='.
[ :a :b | a <= b ].
'>='.
[ :a :b | a >= b ]})
```
Separate methods are used to increment/decrement the registers:
```smalltalk
Day8Solver >> incrementRegister: aRegister by: aValue
self registers at: aRegister put: (self registers at: aRegister ifAbsent: 0) + aValue.
self highWaterMark: (self highWaterMark max: (self registers at: aRegister))
```
```smalltalk
Day8Solver >> decrementRegister: aRegister by: aValue
self registers at: aRegister put: (self registers at: aRegister ifAbsent: 0) - aValue.
self highWaterMark: (self highWaterMark max: (self registers at: aRegister))
```
With the base formed we can move on to solving the puzzle.
## Solution to Part 1
The solution to part 1 is straightforward from here. After processing the
input, just ask for the maximum value in the registers:
```
Day8Solver >> solveA: anInput
self processInput: anInput.
^ self registers values max
```
## Solution to Part 2
The solution to part 2 requires that we kept track of the maximum value seen
when incrementing and decrementing the registers. I called this the
`highWaterMark` and you can see it in the last lines of the `decrementRegister:
by:` and the `incrementRegister: by:` methods.
```smalltalk
Day8Solver >> solveB: anInput
self processInput: anInput.
^ self highWaterMark
```
# Observations
I have noticed as I do each challenge that my programming style is changing. I
am using smaller methods that are individually tested. I know this is the
Smalltalk style but it happened organically, without my intention. I find that
interesting. One of the things I like most about solving competitive
programming problems in Python is the ability to unit test as I go. Smalltalk
is able to do that with far better facility. I find that very useful.
|
PHP
|
UTF-8
| 609 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
// Table Name
protected $table = 'transactions';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'qty',
'totalPrice',
'currencyCode',
'currencySymbol',
'product_id',
'sale_id'
];
public function rel_sale() {
return $this->belongsTo(Sale::class,'sale_id','id');
}
}
|
C#
|
UTF-8
| 3,700 | 2.65625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace DMCooking
{
public partial class Top5 : Form
{
public Top5()
{
InitializeComponent();
}
public string Requete(string requete)
{
string textResult = "Erreur dans la commande " + requete;
try
{
string connectionString = "SERVER=localhost;PORT=3306;DATABASE=Cooking;UID=root;PASSWORD=" + DataContainer.mdp + ";";
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = requete;
MySqlDataReader reader;
reader = command.ExecuteReader();
textResult = "";
while (reader.Read())
{
string currentRowAsString = "";
string valueAsString = "";
for (int i = 0; i < reader.FieldCount - 1; i++)
{
valueAsString = reader.GetValue(i).ToString();
currentRowAsString += valueAsString + ", ";
}
valueAsString = reader.GetValue(reader.FieldCount - 1).ToString();
currentRowAsString += valueAsString;
textResult += currentRowAsString + "\n";
}
//Enlever le dernier \n
textResult = textResult.Substring(0, textResult.Length - 1);
connection.Close();
}
catch { }
return textResult;
}
private void Top5_Load(object sender, EventArgs e)
{
string topfive = "select distinct r.nomRecette as Recette,r.typeRecette as Type,r.descRecette as Description,cl.nomClient as Cdr from recette r, contenu c, cdr cd, client cl where r.numTelClientCdr = cd.numTelClientCdr and r.nomRecette = c.nomRecette and cl.numTelClient = cd.numTelClientCdr group by c.nomRecette order by sum(c.quantite) desc limit 5";
string top5 = Requete(topfive);
string[] result = top5.Split('\n');
string[] recet = new string[5];
string[] type = new string[5];
string[] desc = new string[5];
string[] cdr = new string[5];
for (int i = 0; i < 5; i++)
{
string[] temp = result[i].Split(',');
recet[i] = temp[0];
type[i] = temp[1];
desc[i] = temp[2];
cdr[i] = temp[3];
}
label2.Text = "1. " + recet[0] + " (" + type[0] + "," + desc[0] + ") par" + cdr[0];
label3.Text = "2. " + recet[1] + " (" + type[1] + "," + desc[1] + ") par" + cdr[1];
label4.Text = "3. " + recet[2] + " (" + type[2] + "," + desc[2] + ") par" + cdr[2];
label5.Text = "4. " + recet[3] + " (" + type[3] + "," + desc[3] + ") par" + cdr[3];
label6.Text = "5. " + recet[4] + " (" + type[4] + "," + desc[4] + ") par" + cdr[4];
}
private void buttonRetour_Click(object sender, EventArgs e)
{
//retour au form précédent
TablBordGC formTablBord = new TablBordGC();
formTablBord.Show();
this.Close();
}
}
}
|
Markdown
|
UTF-8
| 504 | 2.53125 | 3 |
[] |
no_license
|
# Sound Distributor
A socket-based sound distributor
## How to use
```
$ npm install
$ node index.js
```
And point your browser to `http://localhost:3000`. Optionally specify
a port by supplying the `PORT` env variable.
## Features
Log multiple computers into the site and run the command `startPhase()` in the
browser console. Build and randomly generate arrangements of sound using the
`nextPhase()`, `bassPhase()`, and `pongPhase()` methods. End the arrangement
with the `endPhase()` command.
|
C++
|
UTF-8
| 777 | 3.359375 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
using namespace std;
class MatrixBoard
{
public:
int Matrix[443];
void setMatrix()
{
for(int i=0;i<21;i++)
for(int j=0;j<21;j++)
Matrix[i*21+j] = 0;
}
void modifiedMatrix(int row,int col,int type)//type = 0 noting 1 black 2 white
{
Matrix[row*21+col] = type+1;
}
void outputMatrix()//0 is noting,1 is black, 2 is white
{
ofstream file;
file.open("output.txt");
for(int i=0;i<21;i++)
for(int j=0;j<21;j++)
{
file<<Matrix[i*21+j];
file<<" ";
if(j == 20)
file<<"\n";
}
file.close();
}
void inputBoard()
{
ifstream ifs;
ifs.open ("output.txt", std::ifstream::in);
for(int i=0;i<21;i++)
for(int j=0;j<21;j++){
ifs>>Matrix[i*21+j];
}
ifs.close();
}
};
|
Markdown
|
UTF-8
| 2,597 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
+++
title = "Encryption"
weight = 3
+++
## Root Configuration
Class name: org.apache.shardingsphere.encrypt.api.config.EncryptRuleConfiguration
Attributes:
| *Name* | *DataType* | *Description* |
| -------------- | -------------------------------------------- | -------------------------------------- |
| encryptors (+) | Map\<String, EncryptorRuleConfiguration\> | Encryptor names and encryptors |
| tables (+) | Map\<String, EncryptTableRuleConfiguration\> | Encrypt table names and encrypt tables |
## Encrypt Table Configuration
Class name: org.apache.shardingsphere.encrypt.api.config.EncryptTableRuleConfiguration
Attributes:
| *Name* | *DataType* | *Description* |
| -------------- | --------------------------------------------- | -------------------------------- |
| columns (+) | Map\<String, EncryptColumnRuleConfiguration\> | Encrypt column names and columns |
### Encrypt Column Configuration
Class name: org.apache.shardingsphere.encrypt.api.config.EncryptColumnRuleConfiguration
Attributes:
| *Name* | *DataType* | *Description* |
| ----------------------- | ---------- | -------------------------- |
| plainColumn (?) | String | Plain column name |
| cipherColumn | String | Cipher column name |
| assistedQueryColumn (?) | String | Assisted query column name |
| encryptor | String | Encryptor type |
## Encryptor Configuration
Class name: org.apache.shardingsphere.encrypt.api.config.EncryptorRuleConfiguration
Attributes:
| *Name* | *DataType* | *Description* |
| ---------- | ---------- | --------------------- |
| type | String | Encryptor type |
| properties | Properties | Encryptor properties |
Apache ShardingSphere built-in implemented classes of Encryptor are:
### MD5 Encryptor
Class name: org.apache.shardingsphere.encrypt.strategy.impl.MD5Encryptor
Attributes: None
### AES Encryptor
Class name: org.apache.shardingsphere.encrypt.strategy.impl.AESEncryptor
Attributes:
| *Name* | *DataType* | *Description* |
| ------------- | ---------- | ------------- |
| aes.key.value | String | AES KEY |
### RC4 Encryptor
Class name: org.apache.shardingsphere.encrypt.strategy.impl.RC4Encryptor
Attributes:
| *Name* | *DataType* | *Description* |
| ------------- | ---------- | ------------- |
| rc4.key.value | String | RC4 KEY |
|
Java
|
UTF-8
| 743 | 2 | 2 |
[] |
no_license
|
package serviceI;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Component;
import model.BeanItemBudget;
import util.BaseException;
@Component
public interface IItemBudgetService {
public void addItemBudget( int budgetId, String itemName, int oItemId, float itemBudgetCost)throws BaseException;
public void modifryItemBudget(int itemBudgetId, float itemBudgetCost)throws BaseException;
public void DelItemBudget(int itemBudgetId)throws BaseException;
public BeanItemBudget SearchItemBudget(int itemBudgetId)throws BaseException;
public List<BeanItemBudget> LoadItemBudget()throws BaseException;
public List<BeanItemBudget> SearchItemBudgetbybudgetid(int budgetid)throws BaseException;
}
|
C++
|
UTF-8
| 1,137 | 3.203125 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include "armor.h"
Armor::Armor() : Item(false, 1, Point(0,0), "ARMADURA GENERICA"){
m_def = 1;
m_magic_def = 1;
m_durability_current = 100;
m_durability_max = 100;
m_weigth = 1;
}
Armor::Armor(bool inside, int size, Point pos, std::string id, int def, int mdef, Element elm, int dur, int w) :
Item(inside, size, pos, id){
m_def = def;
m_magic_def = mdef;
m_element = elm;
m_durability_current = dur;
m_durability_max = dur;
m_weigth = w;
}
int Armor::get_def() const{
return m_def;
}
int Armor::get_magic_def() const{
return m_magic_def;
}
int Armor::get_durability_max() const{
return m_durability_max;
}
int Armor::get_durability_current() const{
return m_durability_current;
}
Element Armor::get_element() const{
return m_element;
}
int Armor::get_weigth() const{
return m_weigth;
}
int Armor::use(){
if(m_durability_current == 0)
return 0;
m_durability_current--;
if(m_durability_current + 1 == m_durability_max)
return m_def;
return m_def * (m_durability_current + 1)/m_durability_max;
}
|
Python
|
UTF-8
| 7,263 | 2.609375 | 3 |
[] |
no_license
|
# adding and removal of cars after tracking (using iou)
# detect only vehicles
import cv2
import numpy as np
import copy
from imutils.video import FPS
net = cv2.dnn.readNet("../../yolov3.weights", "../../yolov3.cfg")
classes = []
with open("../../coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
colors = np.random.uniform(0, 255, size=(len(classes), 3))
def iou(boxA, boxB):
# determine the (x, y)-coordinates of the intersection rectangle
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
# compute the area of intersection rectangle
interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
# compute the area of both the prediction and ground-truth
# rectangles
boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
# compute the intersection over union by taking the intersection
# area and dividing it by the sum of prediction + ground-truth
# areas - the interesection area
# print(interArea, float(boxAArea + boxBArea - interArea))
iou = interArea / float(boxAArea + boxBArea - interArea)
# return the intersection over union value
return iou
# cap=cv2.VideoCapture(0)
cap=cv2.VideoCapture('../../videos/a.mp4')
cap.set(1,0)
# fourcc = cv2.VideoWriter_fourcc(*'XVID')
# out1 = cv2.VideoWriter('i.avi', fourcc, 3.0, (int(cap.get(3)),int(cap.get(4))))
fps = FPS().start()
prev_frame=[]
number=0
cot=0
while True:
_,img=cap.read()
cot=cot+1
height, width, channels = img.shape
# Detecting objects
blob = cv2.dnn.blobFromImage(img, 0.00392, (416,416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
# Showing informations on the screen
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
# print(classes[class_id])
if (classes[class_id]=='person' or classes[class_id]=='bicycle' or classes[class_id]=='car' or classes[class_id]=='motorbike' or classes[class_id]=='bus' or classes[class_id] =='truck'):
confidence = scores[class_id]
if confidence > 0.5:
# Object detected
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
# Rectangle coordinates
x = int(center_x - w / 2)
y = int(center_y - h / 2)
if (w*h >=1800):
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# print(indexes)
font = cv2.FONT_HERSHEY_PLAIN
change=[]
curr_frame=[]
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
# color = colors[i]
# cx,cy = (2*x + w)/2 , (2*y + h)/2
curr_frame.append([x,y,x+w,y+h,label])
# object tracking
curr , prev=copy.deepcopy(curr_frame) , copy.deepcopy(prev_frame)
display=[]
ll1,ll2,l1,l2=[],[],[],[]
ans=0
for i in range(max([len(prev_frame),len(curr_frame)])):
small=0
for curr_ind,curr_obj in enumerate(curr):
# x2 , y2 = curr_obj[4] , curr_obj[5]
l1 = [ curr_obj[0], curr_obj[1], curr_obj[2], curr_obj[3] ]
for prev_ind,prev_obj in enumerate(prev):
# x1 , y1 = prev_obj[0] , prev_obj[1]
l2 = [ prev_obj[0], prev_obj[1], prev_obj[2], prev_obj[3] ]
ans = iou( l1 , l2 )
# ans=((x2-x1)**2+(y2-y1)**2)**(1/2)
if ans > small:
small = ans
ll1,ll2=l1,l2
ind = prev_obj[4]
chct = prev_obj[5]
# aa,bb,cc,dd=x1,y1,x2,y2
pop1 , pop2 = curr_ind , prev_ind
new_list = [ curr_obj[0], curr_obj[1], curr_obj[2], curr_obj[3] , ind ]
disp=curr_obj
# print(small,aa,bb,cc,dd)
print(curr,prev)
print(small,ll1,ll2)
print(len(curr_frame) , len(prev_frame) , len(curr) , len(prev))
# print(min([len(prev_frame),len(curr_frame)]))
if small > 0.45: # decrease this if objects are small and their iou can change to a greater extent
display.append([disp,ind,chct])
curr.pop(pop1)
prev.pop(pop2)
change.append(new_list)
else:
break
print(len(change),len(display))
print('display curr',display,curr)
for i in display:
color=colors[i[1]%75]
x1,y1,x2,y2,label = i[0][0] , i[0][1] , i[0][2] , i[0][3] , i[0][4]
cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)
text=' '+str(i[1])
cv2.putText(img, text, (x1, y1 + 30), font, 3, color, 2)
for i in curr:
number=number+1
color=colors[number%75]
prev_frame.append([i[0], i[1], i[2], i[3], number,0])
x1, y1, x2, y2, label = i[0] , i[1] , i[2] , i[3] , i[4]
cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)
text=' '+str(number)
cv2.putText(img, text, (x1, y1 + 30), font, 3, color, 2)
if number==0:
for i in curr_frame:
number=number+1
color=colors[number%75]
xx1, yy1, xx2, yy2, label = i
prev_frame.append([xx1, yy1, xx2, yy2, number, 0])
cv2.rectangle(img, (xx1, yy1), (xx2, yy2), color, 2)
text=' '+str(number)
cv2.putText(img, text, (xx1, yy1 + 30), font, 3, color, 2)
# print(number , len(prev_frame),len(curr_frame))
print()
for ch in change:
find=ch[4]
for rr,ob in enumerate(prev_frame):
if ob[4]==find:
prev_frame[rr][0], prev_frame[rr][1], prev_frame[rr][2], prev_frame[rr][3], prev_frame[rr][5] = ch[0], ch[1], ch[2], ch[3], 0
break
index_note=[]
for rr,ob in enumerate(prev_frame):
prev_frame[rr][5]+=1
if prev_frame[rr][5]>=6:
index_note.append(rr)
print("prev_frame",prev_frame)
print(index_note)
lll=[]
for rr,ob in enumerate(prev_frame):
flag=0
for j in index_note:
if j==rr:
flag=1
break
if flag==0:
lll.append(ob)
prev_frame=lll
print('after pop',prev_frame)
cv2.imshow("version", img)
# out1.write(img)
key=cv2.waitKey(1)
fps.update()
if key & 0xFF == ord("q"):
break
# stop the timer and display FPS information
fps.stop()
print("[INFO] elasped time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
cap.release()
# out1.release()
cv2.destroyAllWindows()
|
Markdown
|
UTF-8
| 1,768 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
# JVC Camera Control Program
## Table of Contents
1. [Description](#Description)
2. [Developer Info](#Developer-Info)
1. [Pre-Requisites](#Pre-Requisites)
2. [API](#API)
3. [Future Work](#Future-Work)
4. [Miscellaneous](#Miscellaneous)
## Description
This program allow the user to control and receive information using a JVC GV-LS2 PTZ Camera. Current
## Developer Info
#### Pre-Requisites
Python Version:
* 3.5.x
Libraries used:
* Requests
Installation Instructions:
1. Create python virtual environment
```bash
Linux-
cd /path/to/your/Python/directory/Scripts/
./virtualenv /path/to/directory/the/virtual/environment/will/be/placed
Windows-
cd C:\Path\to\your\Python\Directory\Scripts\
.\virtualenv C:\path\to\directory\the\virtual\environment\will\be\placed
```
2. Activate environment
```bash
Linux-
cd /path/to/directory/where/the/virtual/environment/is/
cd ./Scripts
./activate
Windows-
cd C:\path\to\directory\where\the\virtual\environment\is\
cd .\Scripts
.\activate
```
3. Install requests library
```bash
Linux-
pip install requests
Windows-
pip install requests
```
4. Clone Gitlab repository
* __HTTP -__ [https://github.com/pinosjxp/JVC-Camera-Control.git](https://github.com/pinosjxp/JVC-Camera-Control.git) - Requires Username/Password
* __SSH -__ [git@toolsgit.labs.lenovo.com:jpinos/RedfishAutoPython.git](git@toolsgit.labs.lenovo.com:jpinos/RedfishAutoPython.git) - Requires SSH Keys
#### API
WIP...
## Future Work
* Access full streaming capabilities (Camera supposed to stream at Full HD; Currently only reading image snapshots)
## Miscellaneous
Contact Joshua Pinos ([pinosjxp@gmail.com](pinosjxp@gmail.com)) for additional inquiries.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.