identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/tt9133github/Skyperious/blob/master/skyperious/__init__.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Skyperious
|
tt9133github
|
Python
|
Code
| 8
| 20
|
import conf
__version__ = conf.Version
__VERSION__ = conf.Version
| 15,457
|
https://github.com/halotroop2288/consulo/blob/master/modules/desktop-awt/desktop-ui-impl/src/main/java/com/mxgraph/util/png/mxPngSuggestedPaletteEntry.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
consulo
|
halotroop2288
|
Java
|
Code
| 453
| 810
|
/*
* $Id: mxPngSuggestedPaletteEntry.java,v 1.1 2012/11/15 13:26:39 gaudenz Exp $
* Copyright (c) 2001 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed,licensed or intended for use in
* the design, construction, operation or maintenance of any nuclear facility.
*/
package com.mxgraph.util.png;
import java.io.Serializable;
/**
* A class representing the fields of a PNG suggested palette entry.
* <p/>
* <p><b> This class is not a committed part of the JAI API. It may
* be removed or changed in future releases of JAI.</b>
*
* @version $Id: mxPngSuggestedPaletteEntry.java,v 1.1 2012/11/15 13:26:39 gaudenz Exp $
*/
public class mxPngSuggestedPaletteEntry implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8711686482529372447L;
/**
* The name of the entry.
*/
public String name;
/**
* The depth of the color samples.
*/
public int sampleDepth;
/**
* The red color value of the entry.
*/
public int red;
/**
* The green color value of the entry.
*/
public int green;
/**
* The blue color value of the entry.
*/
public int blue;
/**
* The alpha opacity value of the entry.
*/
public int alpha;
/**
* The probable frequency of the color in the image.
*/
public int frequency;
}
| 37,569
|
https://github.com/vyashole/bookshelf/blob/master/src/components/BookShelf.js
|
Github Open Source
|
Open Source
|
MIT
| null |
bookshelf
|
vyashole
|
JavaScript
|
Code
| 107
| 359
|
import React, { Component } from 'react'
import { TouchableOpacity } from 'react-native-gesture-handler';
import { StyleSheet, FlatList } from 'react-native'
import BookItem from './BookItem';
import { Text } from '@ui-kitten/components';
export default class BookShelf extends Component {
renderItem = ({ item }) => (
<TouchableOpacity onPress={() => this.props.bookPressHandler(item)} style={styles.item}>
<BookItem book={item} appearance='small' />
</TouchableOpacity>
)
keyExtractor = (book) => book.id.toString()
render() {
return (
<FlatList
data={this.props.books}
numColumns={2}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
contentContainerStyle={styles.container}
onRefresh={this.props.onRefresh}
refreshing={false}
ListEmptyComponent={<Text style={{ textAlign: "center", padding: 20 }} category='p1'>No books found!</Text>}
/>
)
}
}
const styles = StyleSheet.create({
item: {
flex: 1,
paddingHorizontal: 8,
maxWidth: 200
},
container: {
alignSelf: "stretch",
justifyContent: "space-around"
}
})
| 23,511
|
https://github.com/polosecki/ton_rfmri_repo/blob/master/fcd_tools/extras/plot_stability.m
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,019
|
ton_rfmri_repo
|
polosecki
|
MATLAB
|
Code
| 182
| 1,162
|
function inter = plot_stability(cd,fid)
% cd - classifier descriptor
alg = cd.alg; K=cd.top_K; method = cd.method;
lambda1 = cd.lambda1; lambda2 = cd.lambda2;
sel_type = cd.sel_type; thresh = cd.thresh;
infname = cd.fnm;
s_lambda1 = ''; s_lambda2='';
if cd.lambda1
s_lambda1=sprintf('_lam1_%.3f',lambda1);
end
if cd.lambda2
s_lambda2=sprintf('_lam2_%.3f_',lambda2);
end
outfig_all = sprintf('Figures/%s_%s%s%strain_%s.fig',alg,method,s_lambda1,s_lambda2,sel_type);
outeps_all = sprintf('Figures/%s_%s%s%strain_%s.eps',alg,method,s_lambda1,s_lambda2,sel_type);
plot_sym = {'bo-';'b--';'bs-';'m-';'k--';'r--';'g--';'ro-';'gv-'};
folds = cd.folds;
outfig = sprintf('stability_frac_%s_%s.fig',sel_type,infname{1});
outeps = sprintf('stability_frac_%s_%s.eps',sel_type,infname{1});
% outfig1 = sprintf('stability_frac_300%s%d.fig',sel_type,K(length(K)));
% outeps1 = sprintf('stability_frac_300%s%d.eps',sel_type,K(length(K)));
%
% outfig2 = sprintf('stability_frac_1000%s%d.fig',sel_type,K(length(K)));
% outeps2 = sprintf('stability_frac_1000%s%d.eps',sel_type,K(length(K)));
inter = zeros(length(infname),length(K));
for i = 1:size(infname,1)
infname{i}
fnm = infname{i};
fnm(strfind(fnm,'_')) = '-';
for tf = 1:size(K,2)
top_features = K(tf);
fold=1;
if thresh
rank_fnm = sprintf('ranking/%s%.2f_fold%d_out_%d_%s',sel_type,thresh,fold,folds,infname{i});
else
rank_fnm = sprintf('ranking/%s_fold%d_out_%d_%s',sel_type,fold,folds,infname{i});
end
load(rank_fnm);
common_features = ranked_features(1:top_features);
clear ranked_features;
for fold=2:folds
if thresh
rank_fnm = sprintf('ranking/%s%.2f_fold%d_out_%d_%s',sel_type,thresh,fold,folds,infname{i});
else
rank_fnm = sprintf('ranking/%s_fold%d_out_%d_%s',sel_type,fold,folds,infname{i});
end
load(rank_fnm);
common_features = intersect(common_features,ranked_features(1:top_features));
clear ranked_features;
end
inter(i,tf) = size(common_features,2);
end
figure(fid);
plot(K, inter(i,:)./K, plot_sym{i});
hold on;
ylabel('% features in common','FontSize',12); xlabel('top voxels','FontSize',12);
[s,e]=sprintf('Common features over %d CV folds: \n %s', folds, fnm);
title(s,'fontsize',12);
end
legend(cd.legend);
saveas(gcf,outfig,'fig');
saveas(gcf,outeps,'psc2');
% xlim([0 300]);
% saveas(gcf,outfig1,'fig');
% saveas(gcf,outeps1,'psc2');
%
% xlim([0 1000]);
% saveas(gcf,outfig2,'fig');
% saveas(gcf,outeps2,'psc2');
%%%%%%%
| 19,500
|
https://github.com/DScheglov/ur2mr-cli/blob/master/lib/condition.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
ur2mr-cli
|
DScheglov
|
JavaScript
|
Code
| 148
| 338
|
const { fixAction, line } = require('./utils');
const IsFileCond = ({ input, negate, ignoreCase }) => ({
input: fixAction(input),
pattern: negate === 'true' ? '!-f' : '-f',
flags: ncFlag(ignoreCase),
});
const IsDirCond = ({ input, negate, ignoreCase }) => ({
input: fixAction(input),
pattern: negate === 'true' ? '!-d' : '-d',
flags: ncFlag(ignoreCase),
});
const ncFlag = ignoreCase => (
ignoreCase === 'true' ? '[NC]' : ''
);
const PatternCond = ({ input, pattern, ignoreCase, negate }) => ({
input: fixAction(input),
pattern: negate === 'true' ? `!${pattern}` : pattern,
flags: ncFlag(ignoreCase),
});
const Condition = ({ input, matchType, negate, pattern, ignoreCase }) => (
matchType === 'IsFile' ? IsFileCond({ input, negate }) :
matchType === 'IsDirectory' ? IsDirCond({ input, negate }) :
PatternCond({ input, negate, pattern, ignoreCase })
);
Condition.toString = operator => ({ input, pattern, flags }) => line(
'RewriteCond', input, pattern, flags, operator
);
module.exports = Condition;
| 37,697
|
https://github.com/gradle/gradle/blob/master/subprojects/workers/src/main/java/org/gradle/workers/WorkerExecutor.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause, LGPL-2.1-or-later, LicenseRef-scancode-mit-old-style, EPL-2.0, CDDL-1.0, MIT, LGPL-2.1-only, Apache-2.0, MPL-2.0, EPL-1.0
| 2,023
|
gradle
|
gradle
|
Java
|
Code
| 558
| 1,046
|
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.workers;
import org.gradle.api.Action;
import org.gradle.internal.service.scopes.Scopes;
import org.gradle.internal.service.scopes.ServiceScope;
/**
* Allows work to be submitted for asynchronous execution. This api allows for safe, concurrent execution of work items and enables:
*
* <ul>
* <li>Parallel execution of work items within a single task</li>
* <li>Execution in isolated contexts such as an isolated classloader or even a separate process</li>
* <li>Safe execution of multiple tasks in parallel</li>
* </ul>
*
* <p>Work should be submitted with a {@link WorkAction} class representing the implementation of the unit of work
* and an action to configure the parameters of the unit of work (via {@link WorkParameters}).
*
* <pre>
* workerExecutor.noIsolation().submit(MyWorkActionImpl.class) { MyWorkParameters parameters ->
* parameters.inputFile = project.file('foo')
* parameters.outputFile = project.layout.buildDirectory.file('bar')
* }
* </pre>
*
* <p>
* An instance of the executor can be injected into a task by annotating a public constructor or property getter method with {@code javax.inject.Inject}.
*
* @since 3.5
*/
@ServiceScope(Scopes.Project.class)
public interface WorkerExecutor {
/**
* Creates a {@link WorkQueue} to submit work for asynchronous execution with no isolation.
*
* @since 5.6
*/
WorkQueue noIsolation();
/**
* Creates a {@link WorkQueue} to submit work for asynchronous execution with an isolated classloader.
*
* @since 5.6
*/
WorkQueue classLoaderIsolation();
/**
* Creates a {@link WorkQueue} to submit work for asynchronous execution in a daemon process.
*
* Work will execute in an idle daemon, if available. If no idle daemons are available, a new daemon will be started.
*
* @since 5.6
*/
WorkQueue processIsolation();
/**
* Creates a {@link WorkQueue} to submit work for asynchronous execution with no isolation and the requirements specified in the supplied {@link WorkerSpec}.
*
* @since 5.6
*/
WorkQueue noIsolation(Action<? super WorkerSpec> action);
/**
* Creates a {@link WorkQueue} to submit work for asynchronous execution with an isolated classloader and the requirements specified in the supplied {@link ClassLoaderWorkerSpec}.
*
* @since 5.6
*/
WorkQueue classLoaderIsolation(Action<? super ClassLoaderWorkerSpec> action);
/**
* Creates a {@link WorkQueue} to submit work for asynchronous execution in a daemon process.
*
* Work will execute in an idle daemon matching the requirements specified in the supplied {@link ProcessWorkerSpec}, if available. If no idle daemons are available, a new daemon will be started.
*
* @since 5.6
*/
WorkQueue processIsolation(Action<? super ProcessWorkerSpec> action);
/**
* Blocks until all work associated with the current build operation is complete. Note that when using this method inside
* a task action, it will block completion of the task action until all submitted work is complete. This means that other
* tasks from the same project cannot be run in parallel while the task action is still executing.
*
* @throws WorkerExecutionException when a failure occurs while executing the work.
*/
void await() throws WorkerExecutionException;
}
| 50,293
|
https://github.com/mneira10/SistransI2/blob/master/java-server-master/src/tm/RotondAndesTM.java
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
SistransI2
|
mneira10
|
Java
|
Code
| 5,390
| 23,935
|
package tm;
import dao.DAOTablaCarritos;
import dao.DAOTablaHistorial;
import dao.DAOTablaIngredientes;
import dao.DAOTablaItems;
import dao.DAOTablaMenus;
import dao.DAOTablaMenusProductoIndividual;
import dao.DAOTablaProductos;
import dao.DAOTablaProductosIndividuales;
import dao.DAOTablaProductosPreferidos;
import dao.DAOTablaRestaurante;
import dao.DAOTablaUsuarios;
import dao.DAOTablaUsuariosRegistrados;
import dao.DAOTablaZonaPreferida;
import vos.*;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import dao.DAOTablaZonas;
import dtm.RotondAndesDistributed;
public class RotondAndesTM {
/**
* Atributo estatico que contiene el path relativo del archivo que tiene los datos de la conexion
*/
private static final String CONNECTION_DATA_FILE_NAME_REMOTE = "/conexion.properties";
/**
* Atributo estatico que contiene el path absoluto del archivo que tiene los datos de la conexion
*/
private String connectionDataPath;
/**
* Atributo que guarda el usuario que se va a usar para conectarse a la base de datos.
*/
private String user;
/**
* Atributo que guarda la clave que se va a usar para conectarse a la base de datos.
*/
private String password;
/**
* Atributo que guarda el URL que se va a usar para conectarse a la base de datos.
*/
private String url;
/**
* Atributo que guarda el driver que se va a usar para conectarse a la base de datos.
*/
private String driver;
/**
* conexion a la base de datos
*/
private Connection conn;
private RotondAndesDistributed dtm;
public RotondAndesTM(String contextPathP) {
connectionDataPath = contextPathP + CONNECTION_DATA_FILE_NAME_REMOTE;
initConnectionData();
System.out.println("A");
dtm=RotondAndesDistributed.getInstance(this);
System.out.println("B");
}
private void initConnectionData() {
try {
File arch = new File(this.connectionDataPath);
Properties prop = new Properties();
FileInputStream in = new FileInputStream(arch);
prop.load(in);
in.close();
this.url = prop.getProperty("url");
this.user = prop.getProperty("usuario");
this.password = prop.getProperty("clave");
this.driver = prop.getProperty("driver");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
private Connection darConexion() throws SQLException {
System.out.println("Connecting to: " + url + " With user: " + user);
return DriverManager.getConnection(url, user, password);
}
public Zona buscarZonaPorNombre(String name) throws SQLException,Exception {
List<Zona> zonas;
DAOTablaZonas daoZonas = new DAOTablaZonas();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarZonasPorName(name);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas.get(0);
}
public void addZona(Zona zona) throws Exception {
DAOTablaZonas daoZonas = new DAOTablaZonas();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.addZona(zona);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void addCarrito(Carrito carrito) throws Exception {
DAOTablaCarritos daoCarritos = new DAOTablaCarritos();
try
{
//////transaccion
this.conn = darConexion();
daoCarritos.setConn(conn);
daoCarritos.addCarrito(carrito);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoCarritos.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public List<Zona> darZonas() throws Exception {
List<Zona> zonas;
DAOTablaZonas daoZonas = new DAOTablaZonas();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darZonas();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public void updateZona(Zona zona) throws Exception {
DAOTablaZonas daoZona = new DAOTablaZonas();
try
{
//////transaccion
this.conn = darConexion();
daoZona.setConn(conn);
daoZona.updateZona(zona);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZona.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void deleteZona(Zona zona) throws Exception {
DAOTablaZonas daoZona = new DAOTablaZonas();
try
{
//////transaccion
this.conn = darConexion();
daoZona.setConn(conn);
daoZona.deleteZona(zona);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZona.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public List<Usuario> darUsuarios() throws Exception{
List<Usuario> usuarios;
DAOTablaUsuarios daoUsuarios = new DAOTablaUsuarios();
try
{
//////transaccion
this.conn = darConexion();
daoUsuarios.setConn(conn);
usuarios = daoUsuarios.darUsuarios();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoUsuarios.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return usuarios;
}
public Usuario darUsuariosPorID(Long id) throws Exception{
Usuario usuario;
DAOTablaUsuarios daoUsuario= new DAOTablaUsuarios();
try
{
//////transaccion
this.conn = darConexion();
daoUsuario.setConn(conn);
usuario = daoUsuario.buscarUsuariosPorId(id);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoUsuario.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return usuario;
}
public void addUsuario(Usuario usuario) throws Exception {
DAOTablaUsuarios daoUsuarios = new DAOTablaUsuarios();
try
{
//////transaccion
this.conn = darConexion();
daoUsuarios.setConn(conn);
daoUsuarios.addUsuario(usuario);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoUsuarios.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void updateUsuario(Usuario usuario) throws Exception {
DAOTablaUsuarios daoUsuarios = new DAOTablaUsuarios();
try
{
//////transaccion
this.conn = darConexion();
daoUsuarios.setConn(conn);
daoUsuarios.updateUsuario(usuario);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoUsuarios.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void deleteUsuario(Usuario usuario) throws Exception {
DAOTablaUsuarios daoUsuario = new DAOTablaUsuarios();
try
{
//////transaccion
this.conn = darConexion();
daoUsuario.setConn(conn);
daoUsuario.deleteUsuario(usuario);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoUsuario.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public List<ZonaPreferida> darZonasPreferidas() throws Exception {
List<ZonaPreferida> zonas;
DAOTablaZonaPreferida daoZonas = new DAOTablaZonaPreferida();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darZonasPreferidas();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<ZonaPreferida> buscarZonaPreferidaPorId(Long id) throws Exception{
List<ZonaPreferida> zonas;
DAOTablaZonaPreferida daoZonas = new DAOTablaZonaPreferida();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarZonaPreferidaPorIdUsuarioRegistrado(id);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<ZonaPreferida> buscarZonaPreferidaPorNombre(String nombre) throws Exception {
List<ZonaPreferida> zonas;
DAOTablaZonaPreferida daoZonas = new DAOTablaZonaPreferida();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarHistorialPorNombreZona(nombre);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public void addZonaPreferida(ZonaPreferida zona) throws Exception {
DAOTablaZonaPreferida daoZonas = new DAOTablaZonaPreferida();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.addZonaPreferida(zona);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void deleteZonaPreferida(ZonaPreferida zona) throws Exception {
DAOTablaZonaPreferida daoZonas = new DAOTablaZonaPreferida();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.deleteZonaPreferida(zona);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public List<UsuarioRegistrado> darUsuariosRegistrados() throws Exception {
List<UsuarioRegistrado> zonas;
DAOTablaUsuariosRegistrados daoZonas = new DAOTablaUsuariosRegistrados();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darUsuarioRegistrados();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public UsuarioRegistrado buscarUsuarioRegistradoporId(Long id) throws Exception {
UsuarioRegistrado zonas;
DAOTablaUsuariosRegistrados daoZonas = new DAOTablaUsuariosRegistrados();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarUsuarioRegistradosPorID(id);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public UsuarioRegistrado buscarUsuarioRegistradoporLogin(String login) throws Exception {
UsuarioRegistrado zonas;
DAOTablaUsuariosRegistrados daoZonas = new DAOTablaUsuariosRegistrados();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarUsuarioRegistradosPorLogin(login);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public void addUsuarioRegistrado(UsuarioRegistrado usuarioRegistrado) throws Exception {
DAOTablaUsuariosRegistrados daoZonas = new DAOTablaUsuariosRegistrados();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.addUsuarioRegistrado(usuarioRegistrado);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void updateUsuarioRegistrado(UsuarioRegistrado user2) throws Exception {
DAOTablaUsuariosRegistrados daoZonas = new DAOTablaUsuariosRegistrados();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.updateUsuarioRegistrado(user2);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void deleteUsuarioRegistrado(UsuarioRegistrado user2) throws Exception {
DAOTablaUsuariosRegistrados daoZonas = new DAOTablaUsuariosRegistrados();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.deleteUsuarioRegistrado(user2);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public List<Restaurante> darRestaurantes() throws Exception {
List<Restaurante> zonas;
DAOTablaRestaurante daoZonas = new DAOTablaRestaurante();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darRestaurantes();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<Restaurante> buscarRestaurantePorId(Long id) throws Exception {
List<Restaurante> zonas;
DAOTablaRestaurante daoZonas = new DAOTablaRestaurante();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarRestaurantesPorID(id);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<Restaurante> buscarRestaurantesPorZona(String zona) throws Exception {
List<Restaurante> zonas;
DAOTablaRestaurante daoZonas = new DAOTablaRestaurante();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarRestaurantesPorZona(zona);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public void addRestaurante(Restaurante rest) throws Exception {
DAOTablaRestaurante daoZonas = new DAOTablaRestaurante();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.addRestaurante(rest);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void updateRestaurante(Restaurante rest) throws Exception {
DAOTablaRestaurante daoZonas = new DAOTablaRestaurante();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.updateRestaurante(rest);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void deleteRestaurante(Restaurante rest) throws Exception {
DAOTablaRestaurante daoZonas = new DAOTablaRestaurante();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.deleteRestaurante(rest);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public List<Producto> darProductos() throws Exception {
List<Producto> zonas;
DAOTablaProductos daoZonas = new DAOTablaProductos();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darProductos();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public Producto buscarProductoPorId(Long id) throws Exception {
Producto zonas;
DAOTablaProductos daoZonas = new DAOTablaProductos();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarProductosPorId(id);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<ProductoPreferido> buscarPreferenciaPorProductoUsuario(Long idProd, Long idUsuario) throws Exception {
List<ProductoPreferido> zonas;
DAOTablaProductosPreferidos daoZonas = new DAOTablaProductosPreferidos();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarProductosPreferidosPorIDUsrIdProd(idUsuario, idProd);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<ProductoPreferido> buscarPreferenciaPorProducto(Long idProd) throws Exception {
List<ProductoPreferido> zonas;
DAOTablaProductosPreferidos daoZonas = new DAOTablaProductosPreferidos();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarProductosPreferidosPorIDProd(idProd);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public void addProdPreferido(ProductoPreferido prod) throws Exception {
DAOTablaProductosPreferidos daoZonas = new DAOTablaProductosPreferidos();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.addProductoPreferido(prod);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public List<ProductoPreferido> buscarPreferenciaPorUsuario(Long idUsuario) throws Exception {
List<ProductoPreferido> zonas;
DAOTablaProductosPreferidos daoZonas = new DAOTablaProductosPreferidos();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarProductosPreferidosPorIDUsr(idUsuario);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public void deleteProductoPreferido(ProductoPreferido zona) throws Exception {
DAOTablaProductosPreferidos daoZonas = new DAOTablaProductosPreferidos();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.deleteProductoPreferido(zona);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public boolean verificarCredencialesRestaurante(String loginAdmin, String passAdmin) throws Exception {
DAOTablaUsuariosRegistrados daoUsuarios= new DAOTablaUsuariosRegistrados();
return daoUsuarios.confirmarAdmin(loginAdmin, passAdmin);
}
public boolean verificarCredencialesAdmin(String loginAdmin, String passAdmin) throws Exception {
DAOTablaUsuariosRegistrados daoUsuarios= new DAOTablaUsuariosRegistrados();
return daoUsuarios.confirmarRestaurante(loginAdmin, passAdmin);
}
public void addIngrediente(Ingrediente ingrediente) throws Exception {
DAOTablaIngredientes daoZonas = new DAOTablaIngredientes();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.addIngrediente(ingrediente);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void addMenu(Menu menu) throws Exception {
DAOTablaMenus daoMenus = new DAOTablaMenus();
try
{
//////transaccion
this.conn = darConexion();
daoMenus.setConn(conn);
daoMenus.addMenu(menu);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoMenus.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void addProducto(Producto producto) throws Exception {
DAOTablaProductos daoZonas = new DAOTablaProductos();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.addProducto(producto);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void addProductoInd(ProductoIndividual prodInd) throws Exception {
DAOTablaProductosIndividuales daoProdInd= new DAOTablaProductosIndividuales();
DAOTablaProductos daoTablaProductos = new DAOTablaProductos();
try
{
//////transaccion
this.conn = darConexion();
daoProdInd.setConn(conn);
daoTablaProductos.addProducto(prodInd);
daoTablaProductos.setConn(conn);
daoProdInd.addProductoIndividual(prodInd);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoProdInd.cerrarRecursos();
daoTablaProductos.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public List<ZonaPreferida> buscarZonaPreferidaPorIdNombre(Long id, String nombre) throws Exception {
List<ZonaPreferida> zonas;
DAOTablaZonaPreferida daoZonas = new DAOTablaZonaPreferida();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarZonaPreferidaPorId(nombre, id);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<MenuProductoIndividual> darMenuProdInd() {
// TODO Auto-generated method stub
return null;
}
public List<Producto> buscarProductosRestaurante(Long idRestaurante) throws SQLException {
List<Producto> productos;
DAOTablaProductos daoProductos = new DAOTablaProductos();
try
{
//////transaccion
this.conn = darConexion();
daoProductos.setConn(conn);
productos = daoProductos.buscarProductosRestaurante(idRestaurante);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoProductos.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return productos;
}
public List<Producto> buscarProductosRangoPrecios(Double rangoMinimo, Double rangoMaximo) throws SQLException {
List<Producto> productos;
DAOTablaProductos daoProductos = new DAOTablaProductos();
try
{
//////transaccion
this.conn = darConexion();
daoProductos.setConn(conn);
productos = daoProductos.buscarProductosRangoPrecios(rangoMinimo, rangoMaximo);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoProductos.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return productos;
}
public List<Producto> buscarProductosCategoria(String categoria) throws SQLException {
List<Producto> productos;
DAOTablaProductos daoProductos = new DAOTablaProductos();
try
{
//////transaccion
this.conn = darConexion();
daoProductos.setConn(conn);
productos = daoProductos.buscarProductosCategoria(categoria);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoProductos.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return productos;
}
public void addMenuProductoIndividual(MenuProductoIndividual menuProductoIndividual) {
// TODO Auto-generated method stub
}
public List<Carrito> darCarritos() throws Exception{
List<Carrito> zonas;
DAOTablaCarritos daoZonas = new DAOTablaCarritos();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darCarritos();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<Carrito> buscarCarritoPorId(Long id) throws Exception {
List<Carrito> carritos;
DAOTablaCarritos daoZonas = new DAOTablaCarritos();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
carritos = daoZonas.buscarCarritosPorId(id);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return carritos;
}
public void updateCarrito(Carrito zona) throws Exception {
DAOTablaCarritos daoZonas = new DAOTablaCarritos();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.updateCarrito(zona);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void deleteCarrito(Carrito zona) throws Exception {
DAOTablaCarritos daoZonas = new DAOTablaCarritos();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
daoZonas.deleteCarrito(zona);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public List<Menu> darMenus() throws Exception {
List<Menu> zonas;
DAOTablaMenus daoZonas = new DAOTablaMenus();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darMenus();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<Producto> darProductosMenu(Long id) throws Exception {
List<MenuProductoIndividual> menusProdInd;
List<Producto> productos=new ArrayList<>();
DAOTablaMenusProductoIndividual daoProductos = new DAOTablaMenusProductoIndividual();
try
{
//////transaccion
this.conn = darConexion();
daoProductos.setConn(conn);
menusProdInd = daoProductos.buscarProductosPreferidosPorIDMenu(id);
for(MenuProductoIndividual menu: menusProdInd) {
Producto p=buscarProductoPorId(menu.getId_prod_individual());
productos.add(p);
}
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoProductos.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return productos;
}
public List<Menu> buscarMenuPorId(Long id) throws Exception {
List<Menu> zonas;
DAOTablaMenus daoZonas = new DAOTablaMenus();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarMenusPorID(id);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<Item> buscarItemsCarrito(Long idCarrito) throws Exception{
List<Item> zonas;
DAOTablaItems daoZonas = new DAOTablaItems();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.buscarItemsPorIDCarrito(idCarrito);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public void addItemHistorial(Long idCarrito) throws Exception {
DAOTablaHistorial daoZonas = new DAOTablaHistorial();
DAOTablaProductosIndividuales daoItems = new DAOTablaProductosIndividuales();
try
{
List<Item> itemsCarrito=buscarItemsCarrito(idCarrito);
Carrito carrito= buscarCarritoPorId(idCarrito).get(0);
for (Item item: itemsCarrito) {
List<Menu> esMenu= buscarMenuPorId(item.getProductoId());
if(esMenu.size()==0) {
this.conn = darConexion();
daoZonas.setConn(conn);
Historial hist= new Historial(item.getProductoId(), carrito.getUsuarioId(),new Date());
daoZonas.addHistorial(hist);
daoZonas.cerrarRecursos();
daoItems.setConn(conn);
daoItems.venderProductoIndividual(item.getProductoId());
daoItems.cerrarRecursos();
}
else {
List<Producto> lista=darProductosMenu(esMenu.get(0).getId());
for(Producto prod: lista) {
this.conn = darConexion();
daoZonas.setConn(conn);
Historial hist= new Historial(prod.getId(), carrito.getUsuarioId(),new Date());
daoZonas.addHistorial(hist);
daoZonas.cerrarRecursos();
daoItems.setConn(conn);
daoItems.venderProductoIndividual(prod.getId());
daoItems.cerrarRecursos();
}
}
}
}
catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
daoItems.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void addItem(Item item) throws Exception {
DAOTablaItems daoMenus = new DAOTablaItems();
try
{
//////transaccion
this.conn = darConexion();
daoMenus.setConn(conn);
daoMenus.addItem(item);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoMenus.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public void deleteItem(Item item) {
//TODO RF17
}
public void surtirRestaurante(Restaurante restaurante) throws Exception{
DAOTablaProductos daoProductos = new DAOTablaProductos();
DAOTablaProductosIndividuales daoTablaProductosIndividuales = new DAOTablaProductosIndividuales();
try
{
//////transaccion
this.conn = darConexion();
List<Producto> productosDeRestaurante = daoProductos.buscarProductosRestaurante(restaurante.getId());
for(Producto prod : productosDeRestaurante){
daoTablaProductosIndividuales.surtirProducto(prod.getId());
}
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoProductos.cerrarRecursos();
daoTablaProductosIndividuales.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public List<ProductoIndividual> buscarProductoMasOfrecidos() throws Exception{
List<ProductoIndividual> zonas;
DAOTablaProductosIndividuales daoZonas = new DAOTablaProductosIndividuales();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darProductosMasUtilizadoMenu();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<Producto> buscarProductoMasVendidos() {
// TODO RFC6
return null;
}
public List<Producto> darPedidosRestaurante(UsuarioRegistrado usuarioRegistrado) throws Exception{
List<Producto> productos = new ArrayList<>();
DAOTablaHistorial daoHistorial= new DAOTablaHistorial();
try
{
//////transaccion
this.conn = darConexion();
daoHistorial.setConn(conn);
List<Historial> historial = daoHistorial.buscarHistorialPorIdUsuarioRegistrado(usuarioRegistrado.getUsuario_id());
for(Historial historia : historial){
productos.add(buscarProductoPorId(historia.getIdProducto()));
}
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoHistorial.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
}
catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return productos;
}
public List<Producto> datTotPedidos() throws Exception {
List<Producto> productos = new ArrayList<>();
DAOTablaHistorial daoHistorial= new DAOTablaHistorial();
try
{
//////transaccion
this.conn = darConexion();
daoHistorial.setConn(conn);
List<Historial> historial = daoHistorial.darHistorial();
for(Historial historia : historial){
productos.add(buscarProductoPorId(historia.getIdProducto()));
}
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoHistorial.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
}
catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return productos;
}
public List<Historial> darHistorialUsuario(Long usuario_id) throws Exception{
List<Historial> historials = new ArrayList<>();
DAOTablaHistorial daoHistorial= new DAOTablaHistorial();
try
{
//////transaccion
this.conn = darConexion();
daoHistorial.setConn(conn);
historials = daoHistorial.buscarHistorialPorIdUsuarioRegistrado(usuario_id);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoHistorial.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
}
catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return historials;
}
public List<ProductoFacturado> datTotProductosFacturados(Date fechaInicio,Date fechaFin) throws Exception{
List<ProductoFacturado> productos = new ArrayList<>();
DAOTablaHistorial daoHistorial= new DAOTablaHistorial();
try
{
//////transaccion
this.conn = darConexion();
daoHistorial.setConn(conn);
productos = daoHistorial.darTotProductosFacturados( fechaInicio,fechaFin);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoHistorial.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
}
catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return productos;
}
public List<ProductoFacturado> darProductosFacturadosRestaurante(Long usuario_id,Date fechaInicio,Date fechaFin) throws Exception {
List<ProductoFacturado> productos = new ArrayList<>();
DAOTablaHistorial daoHistorial= new DAOTablaHistorial();
try
{
//////transaccion
this.conn = darConexion();
daoHistorial.setConn(conn);
productos = daoHistorial.darProductosFactoradosRestaurante(usuario_id,fechaInicio, fechaFin);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoHistorial.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
}
catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return productos;
}
public List<ProductoMasVendido> darMasVendidos() throws Exception{
List<ProductoMasVendido> productos = new ArrayList<>();
DAOTablaHistorial daoHistorial= new DAOTablaHistorial();
try
{
//////transaccion
this.conn = darConexion();
daoHistorial.setConn(conn);
productos = daoHistorial.darProductosMasVendidos();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoHistorial.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
}
catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return productos;
}
public void cancelarPedido(Long id) throws Exception {
DAOTablaCarritos daoTablaCarritos= new DAOTablaCarritos();
try
{
//////transaccion
this.conn = darConexion();
daoTablaCarritos.setConn(conn);
daoTablaCarritos.cancelarPedido(id);
conn.commit();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoTablaCarritos.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
}
catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
}
public List<RespuestaRequerimiento11> diasMayorConsumo() throws Exception {
List<RespuestaRequerimiento11> zonas;
DAOTablaHistorial daoZonas = new DAOTablaHistorial();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darInformacionDiaMasConsumido();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<RespuestaRequerimiento11> diasMenorConsumo() throws Exception {
List<RespuestaRequerimiento11> zonas;
DAOTablaHistorial daoZonas = new DAOTablaHistorial();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darInformacionDiaMenosConsumido();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<UsuarioRegistrado> buscarBuenosClientes() throws Exception{
List<UsuarioRegistrado> zonas;
DAOTablaUsuariosRegistrados daoZonas = new DAOTablaUsuariosRegistrados();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darBuenosClientes();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<UsuarioRegistrado> darUsuariosReq9(Long idRestaurante, Date fecha1, Date fecha2) throws Exception{
List<UsuarioRegistrado> zonas;
DAOTablaUsuariosRegistrados daoZonas = new DAOTablaUsuariosRegistrados();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.requerimiento9(idRestaurante, fecha1, fecha2);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<UsuarioRegistrado> darUsuariosReq10(Long idRestaurante, Date fecha1, Date fecha2) throws Exception {
List<UsuarioRegistrado> zonas;
DAOTablaUsuariosRegistrados daoZonas = new DAOTablaUsuariosRegistrados();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.requerimiento10(idRestaurante, fecha1, fecha2);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<RespuestaRequerimiento11A> diasMenorFrecuencia() throws Exception {
List<RespuestaRequerimiento11A> zonas;
DAOTablaHistorial daoZonas = new DAOTablaHistorial();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darInformacionDiaMenosFrecuentado();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<RespuestaRequerimiento11A> diasMayorFrecuencia() throws Exception{
List<RespuestaRequerimiento11A> zonas;
DAOTablaHistorial daoZonas = new DAOTablaHistorial();
try
{
//////transaccion
this.conn = darConexion();
daoZonas.setConn(conn);
zonas = daoZonas.darInformacionDiaMasFrecuentado();
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoZonas.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return zonas;
}
public List<Producto> buscarProductosGenerales(Long idRestaurante, String categoria, Double rangoMinimo,
Double rangoMaximo, String[] criterios) throws Exception {
List<Producto> productos;
DAOTablaProductos daoProductos = new DAOTablaProductos();
try
{
//////transaccion
this.conn = darConexion();
daoProductos.setConn(conn);
productos = daoProductos.buscarProductosGenerales(idRestaurante, categoria, rangoMinimo, rangoMaximo, criterios);
} catch (SQLException e) {
System.err.println("SQLException:" + e.getMessage());
e.printStackTrace();
throw e;
} catch (Exception e) {
System.err.println("GeneralException:" + e.getMessage());
e.printStackTrace();
throw e;
} finally {
try {
daoProductos.cerrarRecursos();
if(this.conn!=null)
this.conn.close();
} catch (SQLException exception) {
System.err.println("SQLException closing resources:" + exception.getMessage());
exception.printStackTrace();
throw exception;
}
}
return productos;
}
}
| 42,037
|
https://github.com/114snehasish/spring-security-series/blob/master/spring-security-02/src/main/java/com/snehasish/ssc2/service/DBUserDetailsService.java
|
Github Open Source
|
Open Source
|
MIT
| null |
spring-security-series
|
114snehasish
|
Java
|
Code
| 103
| 384
|
package com.snehasish.ssc2.service;
import com.snehasish.ssc2.dao.UserRepository;
import com.snehasish.ssc2.model.User;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import javax.transaction.Transactional;
import java.util.Optional;
@RequiredArgsConstructor
public class DBUserDetailsService implements UserDetailsManager {
private final UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
Optional<User> userOptional = userRepository.findByUserName(userName);
User u = userOptional.orElseThrow(() -> new UsernameNotFoundException("Error::: username " + userName + " not found."));
return new SecurityUser(u);
}
@Override
@Transactional
public void createUser(UserDetails userDetails) {
userRepository.save(((SecurityUser) userDetails).getUser());
}
@Override
public void updateUser(UserDetails userDetails) {
}
@Override
public void deleteUser(String s) {
}
@Override
public void changePassword(String s, String s1) {
}
@Override
public boolean userExists(String s) {
return false;
}
}
| 5,119
|
https://github.com/JosephChataignon/pyclustering/blob/master/ccore/src/container/kdnode.cpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
pyclustering
|
JosephChataignon
|
C++
|
Code
| 451
| 1,516
|
/*!
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
*/
#include <pyclustering/container/kdnode.hpp>
namespace pyclustering {
namespace container {
kdnode::kdnode(const std::vector<double> & p_data, void * p_payload, const kdnode::ptr & p_left, const kdnode::ptr & p_right, const kdnode::ptr & p_parent, const std::size_t p_desc) :
m_data(p_data),
m_payload(p_payload),
m_left(p_left),
m_right(p_right),
m_parent(p_parent),
m_discriminator(p_desc)
{ }
void kdnode::set_left(const kdnode::ptr & p_node) {
m_left = p_node;
}
void kdnode::set_right(const kdnode::ptr & p_node) {
m_right = p_node;
}
void kdnode::set_parent(const kdnode::ptr & p_node) {
m_parent = p_node;
}
void kdnode::set_data(const point & p_data) {
m_data = p_data;
}
void kdnode::set_payload(void * p_payload) {
m_payload = p_payload;
}
void kdnode::set_discriminator(const std::size_t disc) {
m_discriminator = disc;
}
kdnode::ptr kdnode::get_left() const {
return m_left;
}
kdnode::ptr kdnode::get_right() const {
return m_right;
}
kdnode::ptr kdnode::get_parent() const {
return m_parent.lock();
}
void * kdnode::get_payload() const {
return m_payload;
}
kdnode::ptr kdnode::find_node(const point & p_point) {
search_node_rule rule = [&p_point](const kdnode & p_node) {
return p_point == p_node.get_data();
};
return find_node(p_point, rule);
}
kdnode::ptr kdnode::find_node(const point & p_point, const search_node_rule & p_rule) {
kdnode::ptr cur_node = shared_from_this();
while (cur_node != nullptr) {
if (*cur_node <= p_point) {
if (p_rule(*cur_node)) { /* Less or equal - check if equal. */
return cur_node;
}
cur_node = cur_node->get_right();
}
else {
cur_node = cur_node->get_left();
}
}
return nullptr;
}
const std::vector<double> & kdnode::get_data() const {
return m_data;
}
std::vector<double> & kdnode::get_data() {
return m_data;
}
double kdnode::get_value() const {
return m_data[m_discriminator];
}
double kdnode::get_value(const std::size_t p_descr) const {
return m_data[p_descr];
}
std::size_t kdnode::get_discriminator() const {
return m_discriminator;
}
std::size_t kdnode::get_dimension() const {
return m_data.size();
}
void kdnode::get_children(std::vector<kdnode::ptr> & p_children) {
p_children.clear();
if (m_left != nullptr) {
p_children.push_back(m_left);
}
if (m_right != nullptr) {
p_children.push_back(m_right);
}
}
bool operator < (const kdnode & node, const std::vector<double> & point) {
return node.get_value() < point[node.get_discriminator()];
}
bool operator < (const std::vector<double> & point, const kdnode & node) {
return point[node.get_discriminator()] < node.get_value();
}
bool operator > (const kdnode & node, const std::vector<double> & point) {
return point[node.get_discriminator()] < node.get_value();
}
bool operator > (const std::vector<double> & point, const kdnode & node) {
return node.get_value() < point[node.get_discriminator()];
}
bool operator <= (const kdnode & node, const std::vector<double> & point) {
return !(node.get_value() > point[node.get_discriminator()]);
}
bool operator <= (const std::vector<double> & point, const kdnode & node) {
return !(point[node.get_discriminator()] > node.get_value());
}
bool operator >= (const kdnode & node, const std::vector<double> & point) {
return !(node.get_value() < point[node.get_discriminator()]);
}
bool operator >= (const std::vector<double> & point, const kdnode & node) {
return !(point[node.get_discriminator()] < node.get_value());
}
bool operator == (const kdnode & node, const std::vector<double> & point) {
return node.get_value() == point[node.get_discriminator()];
}
bool operator == (const std::vector<double> & point, const kdnode & node) {
return node == point;
}
}
}
| 20,507
|
https://github.com/c-yan/yukicoder/blob/master/yc313/1673.py
|
Github Open Source
|
Open Source
|
MIT
| null |
yukicoder
|
c-yan
|
Python
|
Code
| 64
| 153
|
from sys import stdin
readline = stdin.readline
N, Q = map(int, readline().split())
c = 0
t = [0] * (N + 1)
result = []
for _ in range(Q):
L, R = map(int, readline().split())
for i in range(L - 1, R):
if t[i] == 0:
c += 1
t[i] = 1
elif t[i] == 1:
c -= 1
t[i] = 0
result.append(c)
print(*result, sep='\n')
| 49,798
|
https://github.com/cats-oss/android-license-sample/blob/master/app/src/main/java/com/github/aakira/license/view/RoadView.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
android-license-sample
|
cats-oss
|
Kotlin
|
Code
| 360
| 1,272
|
package com.github.aakira.license.view
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewTreeObserver
import androidx.constraintlayout.widget.ConstraintLayout
import kotlinx.android.synthetic.main.view_road.view.*
import kotlin.properties.Delegates
class RoadView : ConstraintLayout {
companion object {
private const val LINE_OFFSET = 2000
// graph of factor
// When x reaches the height of the screen, it seeks y is 1
// https://docs.google.com/spreadsheets/d/19MNZnu5E56emzYd1NAsaBBy4eDTrPvMvSqkmJ9gzR-o/edit?usp=sharing
private const val SCALE_FACTOR = 3.5
private const val Y_FACTOR = 7.5
}
// line movement amount
private var dy: Float by Delegates.notNull()
// margin of lines
private var marginLine: Float by Delegates.notNull()
init {
LayoutInflater.from(context).inflate(com.github.aakira.license.R.layout.view_road, this, true)
}
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
super(context, attrs, defStyleAttr) {
rootView.viewTreeObserver.addOnGlobalLayoutListener(
object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
rootView.viewTreeObserver.removeOnGlobalLayoutListener(this)
line1.pivotX = line1.measuredWidth.toFloat() / 2
line1.pivotY = 0f
line2.pivotX = line2.measuredWidth.toFloat() / 2
line2.pivotY = 0f
line3.pivotX = line3.measuredWidth.toFloat() / 2
line3.pivotY = 0f
line4.pivotX = line4.measuredWidth.toFloat() / 2
line4.pivotY = 0f
val positionY = height / 2f - line1.height
line1.marginY(positionY.toInt())
line2.marginY(positionY.toInt())
line3.marginY(positionY.toInt())
line4.marginY(positionY.toInt())
dy = height / 2f
marginLine = (dy - line1.height * 2) / 2 // height = line height*2 + margin*2
position(0, LINE_OFFSET)
}
})
}
/**
* y current position
* dy total movement (half the height of screen)
* scaleFactor factor for scale
* yFactor factor for dy
*
* y=(1 / h^n) * x^n
* https://docs.google.com/spreadsheets/d/18L7ELAOvYFlnyRuj-T_5yDBZDgzLFjkvj8rHRkcF230/edit#gid=0
*/
private fun View.linePosition(y: Int, dy: Float, scaleFactor: Double, yFactor: Double) {
// (1 / h^n) * x^n
(Math.pow(y.toDouble(), scaleFactor) / Math.pow(dy.toDouble(), scaleFactor)).toFloat().let {
scaleX = it
scaleY = it
}
translationY = y * (Math.pow(y.toDouble(), yFactor) / Math.pow(dy.toDouble(), yFactor)).toFloat()
}
fun position(y: Int, offset: Int = LINE_OFFSET) {
val position = y + offset
val firstY = Math.max(0f, position % dy)
line1.linePosition(firstY.toInt(), dy, SCALE_FACTOR, Y_FACTOR)
val secondY = Math.max(0f, (position + marginLine) % dy)
line2.linePosition(secondY.toInt(), dy, SCALE_FACTOR, Y_FACTOR)
val thirdY = Math.max(0f, (position + marginLine * 2) % dy)
line3.linePosition(thirdY.toInt(), dy, SCALE_FACTOR, Y_FACTOR)
val forthY = Math.max(0f, (position + marginLine * 3) % dy)
line4.linePosition(forthY.toInt(), dy, SCALE_FACTOR, Y_FACTOR)
}
private fun View.marginY(margin: Int) {
val marginLayoutParams = layoutParams as ConstraintLayout.LayoutParams
marginLayoutParams.setMargins(
marginLayoutParams.leftMargin, marginLayoutParams.topMargin,
marginLayoutParams.rightMargin, margin
)
layoutParams = marginLayoutParams
}
}
| 39,320
|
https://github.com/MatteCarra/kahoot_loudness_meter_app/blob/master/app/src/main/java/mattecarra/loudnessmeter/protocol/PacketProtocol.kt
|
Github Open Source
|
Open Source
|
MIT
| null |
kahoot_loudness_meter_app
|
MatteCarra
|
Kotlin
|
Code
| 176
| 502
|
package mattecarra.loudnessmeter.protocol
import android.util.SparseArray
import androidx.core.util.contains
import mattecarra.loudnessmeter.packet.Packet
import java.util.HashMap
class PacketProtocol {
private val incoming = SparseArray<Class<out Packet>>()
private val outgoing = HashMap<Class<out Packet>, Int>()
fun registerOutgoing(id: Int, packet: Class<out Packet>) {
this.outgoing[packet] = id
}
fun registerIncoming(id: Int, packet: Class<out Packet>) {
this.incoming.put(id, packet)
}
fun createIncomingPacket(id: Int): Packet {
val packet: Class<out Packet>
if (id < 0 || !this.incoming.contains(id) || this.incoming.get(id) == null) {
throw IllegalArgumentException("Invalid packet id: $id")
} else {
packet = this.incoming.get(id)
}
try {
val constructor = packet.getDeclaredConstructor()
if (!constructor.isAccessible) {
constructor.isAccessible = true
}
return constructor.newInstance()
} catch (e: NoSuchMethodError) {
throw IllegalStateException("Packet \"" + id + ", " + packet.name + "\" does not have a no-params constructor for instantiation.")
} catch (e: Exception) {
throw IllegalStateException("Failed to instantiate packet \"" + id + ", " + packet.name + "\".", e)
}
}
fun getOutgoingId(packet: Class<out Packet>): Int {
val res: Int?
if (this.outgoing.containsKey(packet)) {
res = this.outgoing[packet]
if (res != null) {
return res
}
}
throw IllegalArgumentException("Unregistered outgoing packet class: " + packet.name)
}
}
| 14,648
|
https://github.com/jkfierce/leadlearn/blob/master/leadlearn/app/views/tables.blade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,013
|
leadlearn
|
jkfierce
|
Blade
|
Code
| 90
| 546
|
@extends('layouts.base')
@section('content')
<div class="row-fluid">
<div class="span8">
<div class="scroll">
<table class="table">
<tr>
<th>Child ID</th>
<th>Child</th>
<th>Classroom</th>
<th>Program</th>
<th>Missed Days</th>
</tr>
<tr>
<td>847204</td>
<td>John Smith</td>
<td>#202</td>
<td>Program 2</td>
<td>3 days</td>
</tr>
<tr>
<td>847204</td>
<td>John Smith</td>
<td>#202</td>
<td>Program 2</td>
<td>3 days</td>
</tr>
<tr>
<td>847204</td>
<td>John Smith</td>
<td>#202</td>
<td>Program 2</td>
<td>3 days</td>
</tr>
<tr>
<td>847204</td>
<td>John Smith</td>
<td>#202</td>
<td>Program 2</td>
<td>3 days</td>
</tr>
</table>
</div>
<ul class="nav nav-pills">
<li>
<a href="#">General Table</a>
</li>
<li>
<a href="#">Absences</a>
</li>
<li>
<a href="#">Attendance Patterns</a>
</li>
</ul>
</div>
<div class="span4">
<h3>Sidebar</h3>
<p>For Links and Information</p>
</div>
</div>
@stop
| 43,352
|
https://github.com/querylayer/presidio/blob/master/presidio-analyzer/presidio_analyzer/predefined_recognizers/text_analytics_dal.py
|
Github Open Source
|
Open Source
|
MIT
| null |
presidio
|
querylayer
|
Python
|
Code
| 217
| 721
|
import os
import requests
class TextAnalyticsDal: # pylint: disable=too-many-instance-attributes
def __init__(self, logger, tolerate_errors=True):
"""
Create a new instance of TextAnalyticsDal.
:param logger: A logger.
:param tolerate_errors: When set to True (default),
the analyzer will complete initialization.
When False, exception is thrown if required data
is missing.
"""
self.logger = logger
self.tolerate_errors = tolerate_errors
self.endpoint = os.environ.get('TEXT_ANALYTICS_ENDPOINT')
self.key = os.environ.get('TEXT_ANALYTICS_KEY')
self.api_path = '/text/analytics/v3.0-preview.1/entities/recognition/'
self.api_classes = ['general', 'pii'] # request both general data and pii data
self.failed_to_load = False
error_message = 'TextAnalyticsRecognizer cannot work without {}.'
if not self.endpoint:
self.failed_to_load = True
self.logger.error(error_message.format('an endpoint'))
if not self.tolerate_errors:
raise ValueError(error_message.format('an endpoint'))
if not self.key:
self.failed_to_load = True
self.logger.error(error_message.format('a key'))
if not self.tolerate_errors:
raise ValueError(error_message.format('a key'))
self.headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': self.key,
}
def analyze_pii_data(self, text):
"""
Analyze the text using TextAnalytics PII service
:param text: The text to be analyzed
:return: json string
"""
if self.failed_to_load:
return None
body = {
"Documents": [
{
"Language": "en",
"Id": "0",
"Text": text
},
]
}
params = {
'model-version': '2020-04-01'
}
data = None
try:
for c in self.api_classes:
req = requests.post(
self.endpoint+self.api_path+c,
json=body, headers=self.headers, params=params
)
d = req.json()
if data is None:
data = d
else:
entities = data['documents'][0]['entities']
entities.extend(d['documents'][0]['entities'])
except Exception as e: # pylint: disable=broad-except
self.logger.error("Could not request Text Analytics service", e)
return data
| 42,692
|
https://github.com/n1ck3dcydoom/learning-note/blob/master/practise-learning/src/main/java/daimasuixianglu/_4_string/_2_ReverseStringII.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
learning-note
|
n1ck3dcydoom
|
Java
|
Code
| 140
| 382
|
package daimasuixianglu._4_string;
public class _2_ReverseStringII {
public static void main(String[] args) {
String s = "abcdefg";
System.out.println(reverseStr(s, 2));
}
public static String reverseStr(String s, int k) {
int n = s.length();
char[] cs = s.toCharArray();
for (int i = 0; i < n; i += 2 * k) {
// 1.剩余数量大于2K个,反转前k个数
if (n - i >= 2 * k) {
reverse(cs, i, i + k - 1);
}
// 2.剩余数量小于2k但是大于等于k,反转前k个数
else if (n - i < 2 * k && n - i >= k) {
reverse(cs, i, i + k - 1);
}
// 3. 剩余数量小于k个,反转剩下的所有字符
else {
reverse(cs, i, n - 1);
}
}
return new String(cs);
}
private static void reverse(char[] cs, int s, int e) {
while (s < e) {
char c = cs[s];
cs[s] = cs[e];
cs[e] = c;
s++;
e--;
}
}
}
| 29,892
|
https://github.com/gitbunsin/cms-e-learning/blob/master/public/fonts/lib/config.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
cms-e-learning
|
gitbunsin
|
PHP
|
Code
| 104
| 583
|
<?php
//configure constants
$directory = realpath(dirname(__FILE__));
$document_root = realpath($_SERVER['DOCUMENT_ROOT']);
$base_url = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' .
$_SERVER['HTTP_HOST'];
if(strpos($directory, $document_root)===0) {
$base_url .= str_replace(DIRECTORY_SEPARATOR, '/', substr($directory, strlen($document_root)));
}
defined("APP_URL") ? null : define("APP_URL", str_replace("/lib", "", $base_url));
//Assets URL, location of your css, img, js, etc. files
defined("ASSETS_URL") ? null : define("ASSETS_URL", APP_URL);
//require library files
//require_once("util.php");
require_once("func.global.php");
require_once("smartui/class.smartutil.php");
require_once("smartui/class.smartui.php");
// smart pages plugins
require_once("smartui/class.smartui-widget.php");
require_once("smartui/class.smartui-datatable.php");
require_once("smartui/class.smartui-button.php");
require_once("smartui/class.smartui-tab.php");
require_once("smartui/class.smartui-accordion.php");
require_once("smartui/class.smartui-carousel.php");
require_once("smartui/class.smartui-smartform.php");
require_once("smartui/class.smartui-nav.php");
SmartUI::$icon_source = 'fa';
// register our pages plugins
SmartUI::register('widget', 'Widget');
SmartUI::register('datatable', 'DataTable');
SmartUI::register('button', 'Button');
SmartUI::register('tab', 'Tab');
SmartUI::register('accordion', 'Accordion');
SmartUI::register('carousel', 'Carousel');
SmartUI::register('smartform', 'SmartForm');
SmartUI::register('nav', 'Nav');
require_once("class.html-indent.php");
require_once("class.parsedown.php");
?>
| 9,609
|
https://github.com/metthal/ccool/blob/master/src/ccoold/device_detector.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
ccool
|
metthal
|
C++
|
Code
| 78
| 330
|
#include <spdlog/spdlog.h>
#include "device_detector.hpp"
#include "devices/all.hpp"
#include "logging.hpp"
namespace ccool {
std::unique_ptr<BaseDevice> DeviceDetector::detect_device(const std::string& interface_name)
{
spdlog::info("Detecting devices using interface '{}'...", interface_name);
_interface = Interface::create(interface_name);
if (!_interface)
return nullptr;
std::unique_ptr<BaseDevice> result;
auto device_ifs = _interface->get_device_interfaces();
for (auto&& device_if : device_ifs)
{
auto vendor_id = device_if->get_vendor_id();
auto product_id = device_if->get_product_id();
LOG->debug(" - {:#06x}:{:#06x}", vendor_id, product_id);
result = check_known_devices(vendor_id, product_id, std::move(device_if));
if (result)
{
LOG->debug(" - known device '{}'", result->get_name());
break;
}
}
return result;
}
} // namespace ccool
| 37,357
|
https://github.com/djmarafi/ikasan/blob/master/ikasaneip/visualisation/dashboard/src/main/java/org/ikasan/dashboard/ui/visualisation/component/StatusPanel.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
ikasan
|
djmarafi
|
Java
|
Code
| 462
| 2,525
|
package org.ikasan.dashboard.ui.visualisation.component;
import com.vaadin.componentfactory.Tooltip;
import com.vaadin.flow.component.*;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.shared.Registration;
import org.ikasan.dashboard.broadcast.FlowState;
import org.ikasan.dashboard.broadcast.State;
import org.ikasan.dashboard.cache.CacheStateBroadcaster;
import org.ikasan.dashboard.cache.FlowStateCache;
import org.ikasan.dashboard.ui.general.component.TooltipHelper;
import org.ikasan.dashboard.ui.visualisation.event.GraphViewChangeEvent;
import org.ikasan.dashboard.ui.visualisation.event.GraphViewChangeListener;
import org.ikasan.dashboard.ui.visualisation.model.flow.Flow;
import org.ikasan.dashboard.ui.visualisation.model.flow.Module;
import org.ikasan.rest.client.ModuleControlRestServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StatusPanel extends HorizontalLayout implements GraphViewChangeListener
{
private Logger logger = LoggerFactory.getLogger(StatusPanel.class);
private Button runningButton;
private Button stoppedButton;
private Button stoppedInErrorButton;
private Button recoveringButton;
private Button pauseButton;
private Module currentModule;
private Flow currentFlow;
private Registration broadcasterRegistration;
private ModuleControlRestServiceImpl moduleControlRestService;
private Tooltip runningButtonTooltip;
private Tooltip stoppedButtonTooltip;
private Tooltip stoppedInErrorButtonTooltip;
private Tooltip recoveringButtonTooltip;
private Tooltip pauseButtonTooltip;
public StatusPanel(ModuleControlRestServiceImpl moduleControlRestService)
{
this.moduleControlRestService = moduleControlRestService;
init();
}
protected void init()
{
Label runningLabel = new Label(getTranslation("status-label.running", UI.getCurrent().getLocale()));
runningLabel.getStyle().set("font-size", "8pt");
Label stoppedLabel = new Label(getTranslation("status-label.stopped", UI.getCurrent().getLocale()));
stoppedLabel.getStyle().set("font-size", "8pt");
Label stoppedInErrorLabel = new Label(getTranslation("status-label.stopped-in-error", UI.getCurrent().getLocale()));
stoppedInErrorLabel.getStyle().set("font-size", "8pt");
Label recoveringLabel = new Label(getTranslation("status-label.recovering", UI.getCurrent().getLocale()));
recoveringLabel.getStyle().set("font-size", "8pt");
Label pausedLabel = new Label(getTranslation("status-label.paused", UI.getCurrent().getLocale()));
pausedLabel.getStyle().set("font-size", "8pt");
runningButton = this.createStatusButton();
runningButton.setText("0");
runningButtonTooltip = TooltipHelper.getTooltipForComponentBottom(runningButton, getTranslation("status.click-for-module-status", UI.getCurrent().getLocale()));
VerticalLayout runningButtonLayout = this.createStatusButtonLayout(runningButton, runningLabel);
runningButtonLayout.add(runningButtonTooltip);
stoppedButton = this.createStatusButton();
stoppedButton.setText("0");
stoppedButtonTooltip = TooltipHelper.getTooltipForComponentBottom(stoppedButton, getTranslation("status.click-for-module-status", UI.getCurrent().getLocale()));
VerticalLayout stoppedButtonLayout = this.createStatusButtonLayout(stoppedButton, stoppedLabel);
stoppedButtonLayout.add(stoppedButtonTooltip);
stoppedInErrorButton = this.createStatusButton();
stoppedInErrorButton.setText("0");
stoppedInErrorButtonTooltip = TooltipHelper.getTooltipForComponentBottom(stoppedInErrorButton, getTranslation("status.click-for-module-status", UI.getCurrent().getLocale()));
VerticalLayout stoppedInErrorButtonLayout = this.createStatusButtonLayout(stoppedInErrorButton, stoppedInErrorLabel);
stoppedInErrorButtonLayout.add(stoppedInErrorButtonTooltip);
recoveringButton = this.createStatusButton();
recoveringButton.setText("0");
recoveringButtonTooltip = TooltipHelper.getTooltipForComponentBottom(recoveringButton, getTranslation("status.click-for-module-status", UI.getCurrent().getLocale()));
VerticalLayout recoveringButtonLayout = this.createStatusButtonLayout(recoveringButton, recoveringLabel);
recoveringButtonLayout.add(recoveringButtonTooltip);
pauseButton = this.createStatusButton();
pauseButton.setText("0");
pauseButtonTooltip = TooltipHelper.getTooltipForComponentBottom(pauseButton, getTranslation("status.click-for-module-status", UI.getCurrent().getLocale()));
VerticalLayout pauseButtonLayout = this.createStatusButtonLayout(pauseButton, pausedLabel);
pauseButtonLayout.add(pauseButtonTooltip);
this.setSpacing(false);
this.setMargin(false);
this.expand(runningButtonLayout, stoppedButtonLayout, stoppedInErrorButtonLayout, recoveringButtonLayout, pauseButtonLayout);
this.add(runningButtonLayout, stoppedButtonLayout, stoppedInErrorButtonLayout, recoveringButtonLayout, pauseButtonLayout);
this.setVerticalComponentAlignment(FlexComponent.Alignment.BASELINE, runningButtonLayout, stoppedButtonLayout, stoppedInErrorButtonLayout, recoveringButtonLayout, pauseButtonLayout);
}
private Button createStatusButton()
{
Button statusButton = new Button();
statusButton.getStyle().set("color", "rgb(0,0,0)");
statusButton.getStyle().set("font-weight", "bold");
statusButton.getStyle().set("font-size", "14pt");
statusButton.getStyle().set("border", "solid 2px");
statusButton.getStyle().set("border-color", "rgb(241,90,35)");
statusButton.setHeight("35px");
statusButton.setWidth("35px");
statusButton.setEnabled(true);
statusButton.addClickListener((ComponentEventListener<ClickEvent<Button>>) buttonClickEvent ->
{
ModuleStatusDialog moduleStatusDialog = new ModuleStatusDialog(currentModule
, this.moduleControlRestService);
moduleStatusDialog.open();
});
return statusButton;
}
/**
* Create the button layout
*
* @param button
* @param label
* @return
*/
private VerticalLayout createStatusButtonLayout(Button button, Label label)
{
VerticalLayout buttonLayout = new VerticalLayout();
buttonLayout.setMargin(false);
buttonLayout.setSpacing(false);
label.setHeight("10px");
buttonLayout.add(button, label);
buttonLayout.setHorizontalComponentAlignment(Alignment.CENTER, button);
buttonLayout.setHorizontalComponentAlignment(Alignment.CENTER, label);
buttonLayout.setFlexGrow(4.0, button);
buttonLayout.setFlexGrow(1.0, label);
return buttonLayout;
}
@Override
protected void onAttach(AttachEvent attachEvent)
{
UI ui = attachEvent.getUI();
broadcasterRegistration = CacheStateBroadcaster.register(flowState ->
{
ui.access(() ->
{
// do something interesting here.
logger.info("Received flow state: " + flowState);
calculateStatus();
});
});
this.stoppedButtonTooltip.attachToComponent(stoppedButton);
this.recoveringButtonTooltip.attachToComponent(recoveringButton);
this.runningButtonTooltip.attachToComponent(runningButton);
this.stoppedInErrorButtonTooltip.attachToComponent(stoppedInErrorButton);
this.pauseButtonTooltip.attachToComponent(pauseButton);
}
protected void calculateStatus()
{
int running = 0;
int stopped = 0;
int inError = 0;
int recovering = 0;
int paused = 0;
for(Flow flow: currentModule.getFlows())
{
FlowState flowState = FlowStateCache.instance().get(currentModule, flow);
if(flowState == null)
{
continue;
}
else if(flowState.getState().equals(State.RUNNING_STATE))
{
running++;
}
else if(flowState.getState().equals(State.STOPPED_STATE))
{
stopped++;
}
else if(flowState.getState().equals(State.RECOVERING_STATE))
{
recovering++;
}
else if(flowState.getState().equals(State.PAUSED_STATE))
{
paused++;
}
else if(flowState.getState().equals(State.STOPPED_IN_ERROR_STATE))
{
inError++;
}
}
this.recoveringButton.setText(Integer.toString(recovering));
this.stoppedButton.setText(Integer.toString(stopped));
this.runningButton.setText(Integer.toString(running));
this.pauseButton.setText(Integer.toString(paused));
this.stoppedInErrorButton.setText(Integer.toString(inError));
}
@Override
protected void onDetach(DetachEvent detachEvent)
{
broadcasterRegistration.remove();
broadcasterRegistration = null;
}
@Override
public void onChange(GraphViewChangeEvent event)
{
this.currentModule = event.getModule();
this.currentFlow = event.getFlow();
calculateStatus();
}
}
| 27,491
|
https://github.com/b1ackc4t/pan/blob/master/src/controller/PublicShare.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
pan
|
b1ackc4t
|
Java
|
Code
| 339
| 1,490
|
package controller;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import service.UserService;
import service.impl.UserServiceImpl;
import java.util.ArrayList;
import java.util.Date;
import util.FileUtil;
@MultipartConfig //使用MultipartConfig注解标注改servlet能够接受文件上传的请求
public class PublicShare extends HttpServlet {
UserService userService = new UserServiceImpl();
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
res.setContentType("text/html;charset=utf-8");
String method = (req.getParameter("method")!=null)?req.getParameter("method"):"";
switch (method) {
case "upload":
uploadPage(req, res);
break;
default:
mainPage(req, res);
break;
}
}
private void uploadPage(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session = req.getSession();
String name = null;
String sep = System.getProperty("file.separator");
String dir = null;
if (req.getParameter("dir")==null || req.getParameter("dir").equals("")) {
dir = sep;
} else {
dir = (String)req.getParameter("dir");
}
if(!session.isNew() && session.getAttribute("name") != null){
name = (String)session.getAttribute("name");
} else {
res.sendRedirect("./Login");
return;
}
String userpath = "." + sep + "publicshare" + dir;
req.setAttribute("username", name);
req.setAttribute("path", dir);
req.setAttribute("uploadpath", userpath);
req.setAttribute("part", req.getPart("uploadfile"));
req.getRequestDispatcher("/Upload").forward(req, res);
}
private void mainPage(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
String name = null;
String sep = System.getProperty("file.separator");
String dir = null;
if (req.getParameter("dir")==null || req.getParameter("dir").equals("")) {
dir = sep;
} else {
dir = (String)req.getParameter("dir");
}
if(!session.isNew() && session.getAttribute("name") != null){
name = (String)session.getAttribute("name");
} else {
res.sendRedirect("./Login");
return;
}
String userpath = "." + sep + "publicshare" + dir;
ArrayList<ArrayList> dirtotal = new ArrayList(); //存放用户目录下的目录信息列表
ArrayList<ArrayList> filetotal = new ArrayList(); //存放用户目录下的文件信息列表
for (String i:FileUtil.getFiles(userpath)) {
ArrayList<String> info = new ArrayList();
File f = new File(i);
String n = f.getName();
Double size = f.length()/1024.0;
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
info.add(n);
info.add(userService.getOwner(dir, n));
info.add(dateFormat.format(new Date(f.lastModified())));
if (size < 1024) {
info.add(String.format("%.2fKB", size));
} else {
info.add(String.format("%.2fMB", size/1024.0));
}
info.add(FileUtil.ext(i));
filetotal.add(info);
}
for (String i:FileUtil.getDirs(userpath)) {
ArrayList<String> info = new ArrayList();
File f = new File(i);
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
long size = FileUtil.getTotalSizeOfFilesInDir(f)/1024;
info.add(f.getName());
info.add(dateFormat.format(new Date(f.lastModified())));
if (size < 1024) {
info.add(String.format("%dKB", size));
} else {
info.add(String.format("%.2fMB", size/1024.0));
}
info.add("DIR");
dirtotal.add(info);
}
req.setAttribute("filetotal", filetotal);
req.setAttribute("dirtotal", dirtotal);
req.setAttribute("dir", dir);
req.setAttribute("name", name);
req.getRequestDispatcher("/PublicShareView").forward(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
this.doGet(req, res);
}
}
| 15,430
|
https://github.com/roth1002/mordred/blob/master/packages/mordred/src/webpack.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
mordred
|
roth1002
|
TypeScript
|
Code
| 139
| 387
|
import { Compiler } from 'webpack'
import JoyCon from 'joycon'
import { Mordred } from './'
type PluginConfigObject = {
resolve: string
options?: any
}
type MordredConfigPlugins = PluginConfigObject[]
export type MordredConfig = {
plugins?: MordredConfigPlugins
}
let initialized = false
export class MordredWebpackPlugin {
loadConfig(cwd: string): MordredConfig {
const joycon = new JoyCon()
const { path, data } = joycon.loadSync(['mordred.config.js'], cwd)
if (!path) {
throw new Error(`Cannot find mordred.config.js in your project`)
}
return data || {}
}
apply(compiler: Compiler) {
if (initialized) {
return
}
initialized = true
const webpackContext = compiler.context || process.cwd()
const config = this.loadConfig(webpackContext)
const mordred = new Mordred(config, {
cwd: webpackContext,
})
let started = false
compiler.hooks.watchRun.tapPromise('mordred', async () => {
if (started) {
return
}
started = true
await mordred.init()
})
compiler.hooks.run.tapPromise('mordred', async () => {
await mordred.init()
})
}
}
| 14,664
|
https://github.com/gopherd/gonum/blob/master/mat/diagonal.go
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
gonum
|
gopherd
|
Go
|
Code
| 1,285
| 3,182
|
// Copyright ©2018 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mat
import (
"math"
"github.com/gopherd/gonum/blas"
"github.com/gopherd/gonum/blas/blas64"
)
var (
diagDense *DiagDense
_ Matrix = diagDense
_ allMatrix = diagDense
_ denseMatrix = diagDense
_ Diagonal = diagDense
_ MutableDiagonal = diagDense
_ Triangular = diagDense
_ TriBanded = diagDense
_ Symmetric = diagDense
_ SymBanded = diagDense
_ Banded = diagDense
_ RawBander = diagDense
_ RawSymBander = diagDense
diag Diagonal
_ Matrix = diag
_ Diagonal = diag
_ Triangular = diag
_ TriBanded = diag
_ Symmetric = diag
_ SymBanded = diag
_ Banded = diag
)
// Diagonal represents a diagonal matrix, that is a square matrix that only
// has non-zero terms on the diagonal.
type Diagonal interface {
Matrix
// Diag returns the number of rows/columns in the matrix.
Diag() int
// The following interfaces are included in the Diagonal
// interface to allow the use of Diagonal types in
// functions operating on these types.
Banded
SymBanded
Symmetric
Triangular
TriBanded
}
// MutableDiagonal is a Diagonal matrix whose elements can be set.
type MutableDiagonal interface {
Diagonal
SetDiag(i int, v float64)
}
// DiagDense represents a diagonal matrix in dense storage format.
type DiagDense struct {
mat blas64.Vector
}
// NewDiagDense creates a new Diagonal matrix with n rows and n columns.
// The length of data must be n or data must be nil, otherwise NewDiagDense
// will panic. NewDiagDense will panic if n is zero.
func NewDiagDense(n int, data []float64) *DiagDense {
if n <= 0 {
if n == 0 {
panic(ErrZeroLength)
}
panic("mat: negative dimension")
}
if data == nil {
data = make([]float64, n)
}
if len(data) != n {
panic(ErrShape)
}
return &DiagDense{
mat: blas64.Vector{N: n, Data: data, Inc: 1},
}
}
// Diag returns the dimension of the receiver.
func (d *DiagDense) Diag() int {
return d.mat.N
}
// Dims returns the dimensions of the matrix.
func (d *DiagDense) Dims() (r, c int) {
return d.mat.N, d.mat.N
}
// T returns the transpose of the matrix.
func (d *DiagDense) T() Matrix {
return d
}
// TTri returns the transpose of the matrix. Note that Diagonal matrices are
// Upper by default.
func (d *DiagDense) TTri() Triangular {
return TransposeTri{d}
}
// TBand performs an implicit transpose by returning the receiver inside a
// TransposeBand.
func (d *DiagDense) TBand() Banded {
return TransposeBand{d}
}
// TTriBand performs an implicit transpose by returning the receiver inside a
// TransposeTriBand. Note that Diagonal matrices are Upper by default.
func (d *DiagDense) TTriBand() TriBanded {
return TransposeTriBand{d}
}
// Bandwidth returns the upper and lower bandwidths of the matrix.
// These values are always zero for diagonal matrices.
func (d *DiagDense) Bandwidth() (kl, ku int) {
return 0, 0
}
// SymmetricDim implements the Symmetric interface.
func (d *DiagDense) SymmetricDim() int {
return d.mat.N
}
// SymBand returns the number of rows/columns in the matrix, and the size of
// the bandwidth.
func (d *DiagDense) SymBand() (n, k int) {
return d.mat.N, 0
}
// Triangle implements the Triangular interface.
func (d *DiagDense) Triangle() (int, TriKind) {
return d.mat.N, Upper
}
// TriBand returns the number of rows/columns in the matrix, the
// size of the bandwidth, and the orientation. Note that Diagonal matrices are
// Upper by default.
func (d *DiagDense) TriBand() (n, k int, kind TriKind) {
return d.mat.N, 0, Upper
}
// Reset empties the matrix so that it can be reused as the
// receiver of a dimensionally restricted operation.
//
// Reset should not be used when the matrix shares backing data.
// See the Reseter interface for more information.
func (d *DiagDense) Reset() {
// No change of Inc or n to 0 may be
// made unless both are set to 0.
d.mat.Inc = 0
d.mat.N = 0
d.mat.Data = d.mat.Data[:0]
}
// Zero sets all of the matrix elements to zero.
func (d *DiagDense) Zero() {
for i := 0; i < d.mat.N; i++ {
d.mat.Data[d.mat.Inc*i] = 0
}
}
// DiagView returns the diagonal as a matrix backed by the original data.
func (d *DiagDense) DiagView() Diagonal {
return d
}
// DiagFrom copies the diagonal of m into the receiver. The receiver must
// be min(r, c) long or empty, otherwise DiagFrom will panic.
func (d *DiagDense) DiagFrom(m Matrix) {
n := min(m.Dims())
d.reuseAsNonZeroed(n)
var vec blas64.Vector
switch r := m.(type) {
case *DiagDense:
vec = r.mat
case RawBander:
mat := r.RawBand()
vec = blas64.Vector{
N: n,
Inc: mat.Stride,
Data: mat.Data[mat.KL : (n-1)*mat.Stride+mat.KL+1],
}
case RawMatrixer:
mat := r.RawMatrix()
vec = blas64.Vector{
N: n,
Inc: mat.Stride + 1,
Data: mat.Data[:(n-1)*mat.Stride+n],
}
case RawSymBander:
mat := r.RawSymBand()
vec = blas64.Vector{
N: n,
Inc: mat.Stride,
Data: mat.Data[:(n-1)*mat.Stride+1],
}
case RawSymmetricer:
mat := r.RawSymmetric()
vec = blas64.Vector{
N: n,
Inc: mat.Stride + 1,
Data: mat.Data[:(n-1)*mat.Stride+n],
}
case RawTriBander:
mat := r.RawTriBand()
data := mat.Data
if mat.Uplo == blas.Lower {
data = data[mat.K:]
}
vec = blas64.Vector{
N: n,
Inc: mat.Stride,
Data: data[:(n-1)*mat.Stride+1],
}
case RawTriangular:
mat := r.RawTriangular()
if mat.Diag == blas.Unit {
for i := 0; i < n; i += d.mat.Inc {
d.mat.Data[i] = 1
}
return
}
vec = blas64.Vector{
N: n,
Inc: mat.Stride + 1,
Data: mat.Data[:(n-1)*mat.Stride+n],
}
case RawVectorer:
d.mat.Data[0] = r.RawVector().Data[0]
return
default:
for i := 0; i < n; i++ {
d.setDiag(i, m.At(i, i))
}
return
}
blas64.Copy(vec, d.mat)
}
// RawBand returns the underlying data used by the receiver represented
// as a blas64.Band.
// Changes to elements in the receiver following the call will be reflected
// in returned blas64.Band.
func (d *DiagDense) RawBand() blas64.Band {
return blas64.Band{
Rows: d.mat.N,
Cols: d.mat.N,
KL: 0,
KU: 0,
Stride: d.mat.Inc,
Data: d.mat.Data,
}
}
// RawSymBand returns the underlying data used by the receiver represented
// as a blas64.SymmetricBand.
// Changes to elements in the receiver following the call will be reflected
// in returned blas64.Band.
func (d *DiagDense) RawSymBand() blas64.SymmetricBand {
return blas64.SymmetricBand{
N: d.mat.N,
K: 0,
Stride: d.mat.Inc,
Uplo: blas.Upper,
Data: d.mat.Data,
}
}
// reuseAsNonZeroed resizes an empty diagonal to a r×r diagonal,
// or checks that a non-empty matrix is r×r.
func (d *DiagDense) reuseAsNonZeroed(r int) {
if r == 0 {
panic(ErrZeroLength)
}
if d.IsEmpty() {
d.mat = blas64.Vector{
Inc: 1,
Data: use(d.mat.Data, r),
}
d.mat.N = r
return
}
if r != d.mat.N {
panic(ErrShape)
}
}
// IsEmpty returns whether the receiver is empty. Empty matrices can be the
// receiver for size-restricted operations. The receiver can be emptied using
// Reset.
func (d *DiagDense) IsEmpty() bool {
// It must be the case that d.Dims() returns
// zeros in this case. See comment in Reset().
return d.mat.Inc == 0
}
// Trace returns the trace of the matrix.
//
// Trace will panic with ErrZeroLength if the matrix has zero size.
func (d *DiagDense) Trace() float64 {
if d.IsEmpty() {
panic(ErrZeroLength)
}
rb := d.RawBand()
var tr float64
for i := 0; i < rb.Rows; i++ {
tr += rb.Data[rb.KL+i*rb.Stride]
}
return tr
}
// Norm returns the specified norm of the receiver. Valid norms are:
// 1 or Inf - The maximum diagonal element magnitude
// 2 - The Frobenius norm, the square root of the sum of the squares of
// the diagonal elements
//
// Norm will panic with ErrNormOrder if an illegal norm is specified and with
// ErrZeroLength if the receiver has zero size.
func (d *DiagDense) Norm(norm float64) float64 {
if d.IsEmpty() {
panic(ErrZeroLength)
}
switch norm {
default:
panic(ErrNormOrder)
case 1, math.Inf(1):
imax := blas64.Iamax(d.mat)
return math.Abs(d.at(imax, imax))
case 2:
return blas64.Nrm2(d.mat)
}
}
| 44,152
|
https://github.com/vatbub/hangman-solver/blob/master/src/main/resources/mergedLanguages/wn-merged-syc.tab
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-public-domain, CC-BY-SA-3.0, Apache-2.0
| 2,021
|
hangman-solver
|
vatbub
|
SQL
|
Code
| 180
| 1,165
|
# Wiktionary syc http://wiktionary.org/ CC BY-SA
00631391-a syc:lemma ܬܪܨ
01677433-a syc:lemma ܪܒܐ
00219012-n syc:lemma ܩܛܠ
01015310-n syc:lemma ܚܨܕܐ
01726692-n syc:lemma ܚܘܝܐ
01726692-n syc:lemma ܚܘܘܝܬܐ
01887623-n syc:lemma ܬܘܪܐ
02083672-n syc:lemma ܟܠܒܬܐ
02129604-n syc:lemma ܛܝܓܪܝܣ
03986704-n syc:lemma ܐܙܓܐ
03986704-n syc:lemma ܐܣܛܘܐ
05819453-n syc:lemma ܩܘܫܬܐ
06000644-n syc:lemma ܡܢܝܘܬܐ
06724066-n syc:lemma ܩܘܫܬܐ
07445480-n syc:lemma ܩܘܡ
07541053-n syc:lemma ܣܒܪܐ
08276720-n syc:lemma ܡܕܪܫܬܐ
08438533-n syc:lemma ܥܒܐ
08855505-n syc:lemma ܩܘܪܝܛܝܒܐ
08918944-n syc:lemma ܐܬܘܪ
09274739-n syc:lemma ܦܪܬ
09328904-n syc:lemma ܝܡܬܐ
11091706-n syc:lemma ܝܘܣܦ
11091863-n syc:lemma ܝܘܣܦ
11231157-n syc:lemma ܦܛܪܘܣ
11281555-n syc:lemma ܣܪܐ
13969700-n syc:lemma ܫܝܢܐ
13970236-n syc:lemma ܫܠܡܐ
14024882-n syc:lemma ܫܢܬܐ
15167027-n syc:lemma ܠܠܝܐ
00063172-r syc:lemma ܚܠܦ
00014742-v syc:lemma ܕܡܟ
00031820-v syc:lemma ܓܚܟ
00066191-v syc:lemma ܒܟܐ
00354845-v syc:lemma ܡܬ
00628491-v syc:lemma ܚܫܒ
00948071-v syc:lemma ܡܢܐ
00948853-v syc:lemma ܡܢܐ
01009240-v syc:lemma ܐܡܪ
01090335-v syc:lemma ܟܬܫ
01170052-v syc:lemma ܫܬܐ
01189427-v syc:lemma ܨܡ
01214265-v syc:lemma ܐܚܕ
01311103-v syc:lemma ܚܦܪ
01414467-v syc:lemma ܢܩܫ
01535246-v syc:lemma ܣܚܐ
01543123-v syc:lemma ܝܬܒ
01546111-v syc:lemma ܩܘܡ
01729431-v syc:lemma ܙܡܪ
01780202-v syc:lemma ܕܚܠ
01796582-v syc:lemma ܬܘܐ
01904930-v syc:lemma ܗܠܟ
01940403-v syc:lemma ܦܪܚ
01960911-v syc:lemma ܣܚܐ
01972298-v syc:lemma ܢܦܠ
02096167-v syc:lemma ܦܢܐ
02199590-v syc:lemma ܝܗܒ
02418686-v syc:lemma ܫܥܐ
| 11,476
|
https://github.com/Ashwanigupta9125/code-DS-ALGO/blob/master/Problems in Java/Lecture/L20/L20/PriorityQueue.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
code-DS-ALGO
|
Ashwanigupta9125
|
Java
|
Code
| 222
| 742
|
package L20;
import java.util.ArrayList;
public class PriorityQueue {
ArrayList<Integer> heap;
public PriorityQueue() {
heap = new ArrayList<Integer>();
heap.add(null);
}
public int getSize() {
return heap.size() - 1;
}
public boolean isEmpty() {
return (getSize() == 0);
}
public int min() {
if(isEmpty()) {
// PQ empty Exception
}
return heap.get(1);
}
public void insert(int priority) {
heap.add(priority);
int childIndex = heap.size() - 1;
int parentIndex = childIndex / 2;
while(childIndex > 1) {
int child = heap.get(childIndex);
int parent = heap.get(parentIndex);
if(child > parent) {
return;
}
int temp = child;
heap.set(childIndex, parent);
heap.set(parentIndex, temp);
childIndex = parentIndex;
parentIndex = childIndex / 2;
}
}
public int removeMin() {
if(isEmpty()) {
// PQ empty Exception
}
int min = heap.get(1);
int lastIndex = heap.size()-1;
heap.set(1, heap.get(lastIndex));
heap.remove(lastIndex);
int parentIndex = 1;
int leftChildIndex = 2*parentIndex;
int rightChildIndex = leftChildIndex + 1;
while(parentIndex <= heap.size()-1) {
int minIndex = parentIndex;
int minValue = heap.get(minIndex);
if(leftChildIndex <= heap.size()-1) {
int leftChild = heap.get(leftChildIndex);
if(leftChild < minValue) {
minIndex = leftChildIndex;
minValue = heap.get(minIndex);
}
}
if(rightChildIndex <= heap.size()-1) {
int rightChild = heap.get(rightChildIndex);
if(rightChild < minValue) {
minIndex = rightChildIndex;
minValue = heap.get(minIndex);
}
}
if(parentIndex == minIndex) {
break;
}
else {
heap.set(minIndex, heap.get(parentIndex));
heap.set(parentIndex, minValue);
}
parentIndex = minIndex;
leftChildIndex = 2*parentIndex;
rightChildIndex = leftChildIndex + 1;
}
return min;
}
}
| 38,827
|
https://github.com/jpcima/ADLplug/blob/master/sources/opn2/adl/player.cc
|
Github Open Source
|
Open Source
|
BSL-1.0, LicenseRef-scancode-unknown-license-reference
| 2,021
|
ADLplug
|
jpcima
|
C++
|
Code
| 257
| 886
|
// Copyright Jean Pierre Cimalando 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "player.h"
#include <stdexcept>
void Player::init(unsigned sample_rate)
{
OPN2_MIDIPlayer *pl = opn2_init(sample_rate);
if (!pl)
throw std::runtime_error("cannot initialize player");
player_.reset(pl);
}
void Player::play_midi(const uint8_t *msg, unsigned len)
{
OPN2_MIDIPlayer *pl = player_.get();
if (len <= 0)
return;
uint8_t status = msg[0];
if ((status & 0xf0) == 0xf0)
return;
uint8_t channel = status & 0x0f;
switch (status >> 4) {
case 0b1001:
if (len < 3) break;
if (msg[2] != 0) {
opn2_rt_noteOn(pl, channel, msg[1], msg[2]);
break;
}
case 0b1000:
if (len < 3) break;
opn2_rt_noteOff(pl, channel, msg[1]);
break;
case 0b1010:
if (len < 3) break;
opn2_rt_noteAfterTouch(pl, channel, msg[1], msg[2]);
break;
case 0b1101:
if (len < 2) break;
opn2_rt_channelAfterTouch(pl, channel, msg[1]);
break;
case 0b1011:
if (len < 3) break;
opn2_rt_controllerChange(pl, channel, msg[1], msg[2]);
break;
case 0b1100:
if (len < 2) break;
opn2_rt_patchChange(pl, channel, msg[1]);
break;
case 0b1110:
if (len < 3) break;
opn2_rt_pitchBendML(pl, channel, msg[2], msg[1]);
break;
}
}
void Player::generate(float *left, float *right, unsigned nframes, unsigned stride)
{
OPNMIDI_AudioFormat format;
format.type = OPNMIDI_SampleType_F32;
format.containerSize = sizeof(float);
format.sampleOffset = stride * sizeof(float);
opn2_generateFormat(
player_.get(), 2 * nframes, (uint8_t *)left, (uint8_t *)right, &format);
}
std::vector<std::string> Player::enumerate_emulators()
{
std::unique_ptr<OPN2_MIDIPlayer, Player_Deleter> pl(opn2_init(44100));
if (!pl)
throw std::runtime_error("cannot initialize player");
std::vector<std::string> names(32);
size_t count = 0;
for (unsigned i = 0, n = (unsigned)names.size(); i < n; ++i) {
if (opn2_switchEmulator(pl.get(), i) == 0) {
names[i] = opn2_chipEmulatorName(pl.get());
count = i + 1;
}
}
names.resize(count);
return names;
}
| 21,865
|
https://github.com/hispindia/MAHARASHTRA-2.13/blob/master/dhis-2/dhis-services/dhis-service-datamart-default/src/test/java/org/hisp/dhis/datamart/crosstab/CrossTabServiceTest.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
MAHARASHTRA-2.13
|
hispindia
|
Java
|
Code
| 834
| 2,516
|
package org.hisp.dhis.datamart.crosstab;
/*
* Copyright (c) 2004-2013, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.amplecode.quick.BatchHandler;
import org.amplecode.quick.BatchHandlerFactory;
import org.apache.commons.lang.RandomStringUtils;
import org.hisp.dhis.DhisTest;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementCategory;
import org.hisp.dhis.dataelement.DataElementCategoryCombo;
import org.hisp.dhis.dataelement.DataElementCategoryOption;
import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
import org.hisp.dhis.dataelement.DataElementCategoryService;
import org.hisp.dhis.dataelement.DataElementOperand;
import org.hisp.dhis.dataelement.DataElementService;
import org.hisp.dhis.datamart.CrossTabDataValue;
import org.hisp.dhis.datamart.crosstab.jdbc.CrossTabStore;
import org.hisp.dhis.datavalue.DataValueService;
import org.hisp.dhis.jdbc.batchhandler.GenericBatchHandler;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.period.MonthlyPeriodType;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodService;
import org.hisp.dhis.period.WeeklyPeriodType;
import org.junit.Test;
/**
* @author Lars Helge Overland
* @version $Id: CrossTabServiceTest.java 6217 2008-11-06 18:53:04Z larshelg $
*/
public class CrossTabServiceTest
extends DhisTest
{
private CrossTabService crossTabService;
private BatchHandlerFactory batchHandlerFactory;
private Iterator<Period> generatedPeriods;
private List<DataElementOperand> operands;
private Collection<Integer> periodIds;
private Collection<Integer> organisationUnitIds;
// -------------------------------------------------------------------------
// Fixture
// -------------------------------------------------------------------------
@Override
public void setUpTest()
{
crossTabService = (CrossTabService) getBean( CrossTabService.ID );
batchHandlerFactory = (BatchHandlerFactory) getBean( "inMemoryBatchHandlerFactory" );
categoryService = (DataElementCategoryService) getBean( DataElementCategoryService.ID );
dataElementService = (DataElementService) getBean( DataElementService.ID );
periodService = (PeriodService) getBean( PeriodService.ID );
organisationUnitService = (OrganisationUnitService) getBean( OrganisationUnitService.ID );
dataValueService = (DataValueService) getBean( DataValueService.ID );
Calendar calendar = Calendar.getInstance();
calendar.set( 2007, 0, 1 );
WeeklyPeriodType periodType = (WeeklyPeriodType) periodService.getPeriodTypeByName( WeeklyPeriodType.NAME );
Period period = createPeriod( periodType, calendar.getTime(), calendar.getTime() );
generatedPeriods = periodType.generatePeriods( period ).iterator();
setUpTestData();
}
@Override
public boolean emptyDatabaseAfterTest()
{
return true;
}
private void setUpTestData()
{
DataElementCategoryOption categoryOptionA = new DataElementCategoryOption( "Male" );
DataElementCategoryOption categoryOptionB = new DataElementCategoryOption( "Female" );
categoryService.addDataElementCategoryOption( categoryOptionA );
categoryService.addDataElementCategoryOption( categoryOptionB );
DataElementCategory categoryA = new DataElementCategory( "Gender" );
categoryA.getCategoryOptions().add( categoryOptionA );
categoryA.getCategoryOptions().add( categoryOptionB );
categoryService.addDataElementCategory( categoryA );
DataElementCategoryCombo categoryComboA = new DataElementCategoryCombo( "Gender" );
categoryComboA.getCategories().add( categoryA );
categoryService.addDataElementCategoryCombo( categoryComboA );
categoryService.generateOptionCombos( categoryComboA );
Collection<DataElementCategoryOptionCombo> categoryOptionCombos = categoryService.getAllDataElementCategoryOptionCombos();
Character[] characters = { 'A', 'B', 'C', 'D', 'E' };
periodIds = new HashSet<Integer>();
organisationUnitIds = new HashSet<Integer>();
Collection<DataElement> dataElements = new HashSet<DataElement>();
Collection<Period> periods = new HashSet<Period>();
Collection<OrganisationUnit> organisationUnits = new HashSet<OrganisationUnit>();
for ( Character character : characters )
{
DataElement dataElement = createDataElement( character, categoryComboA );
Period period = generatedPeriods.next();
OrganisationUnit organisationUnit = createOrganisationUnit( character );
dataElements.add( dataElement );
periods.add( period );
organisationUnits.add( organisationUnit );
dataElementService.addDataElement( dataElement );
periodIds.add( periodService.addPeriod( period ) );
organisationUnitIds.add( organisationUnitService.addOrganisationUnit( organisationUnit ) );
}
operands = new ArrayList<DataElementOperand>( categoryService.getOperands( dataElements ) );
for ( DataElement dataElement : dataElements )
{
for ( DataElementCategoryOptionCombo categoryOptionCombo : categoryOptionCombos )
{
for ( Period period : periods )
{
for ( OrganisationUnit organisationUnit : organisationUnits )
{
dataValueService.addDataValue( createDataValue( dataElement, period, organisationUnit, "10", categoryOptionCombo ) );
}
}
}
}
}
// -------------------------------------------------------------------------
// Tests
// -------------------------------------------------------------------------
@Test
public void testPopulateCrossTabValue()
throws Exception
{
String key = crossTabService.createCrossTabTable( operands );
crossTabService.populateCrossTabTable( operands, periodIds, organisationUnitIds, key ).get();
Collection<CrossTabDataValue> values = crossTabService.getCrossTabDataValues( operands, periodIds, organisationUnitIds, key );
assertNotNull( values );
assertEquals( 25, values.size() );
for ( CrossTabDataValue crossTabValue : values )
{
assertTrue( crossTabValue.getPeriodId() != 0 );
assertTrue( crossTabValue.getSourceId() != 0 );
assertNotNull( crossTabValue.getValueMap() );
assertEquals( 10, crossTabValue.getValueMap().size() );
for ( String value : crossTabValue.getValueMap().values() )
{
assertEquals( "10", value );
}
}
}
@Test
public void testPopulateAggregatedDataCache()
{
String key = RandomStringUtils.randomAlphanumeric( 8 );
Period period = new MonthlyPeriodType().createPeriod();
period.setId( 1 );
OrganisationUnit unit = createOrganisationUnit( 'A' );
unit.setId( 1 );
crossTabService.createAggregatedDataCache( operands, key );
BatchHandler<Object> batchHandler = batchHandlerFactory.createBatchHandler( GenericBatchHandler.class ).
setTableName( CrossTabStore.AGGREGATEDDATA_CACHE_PREFIX + key ).init();
List<Object> valueList = new ArrayList<Object>( operands.size() + 2 );
valueList.add( 1 );
valueList.add( 1 );
for ( int i = 0; i < operands.size(); i++ )
{
valueList.add( 10.0 );
}
batchHandler.addObject( valueList );
batchHandler.flush();
Map<DataElementOperand, Double> valueMap = crossTabService.getAggregatedDataCacheValue( operands, period, unit, null, key );
for ( DataElementOperand operand : valueMap.keySet() )
{
assertNotNull( valueMap.get( operand ) );
assertEquals( 10.0, valueMap.get( operand ), DELTA );
}
}
}
| 50,760
|
https://github.com/modux4s/modux/blob/master/modules/plugin/src/main/java/modux/plugin/classutils/FileTool.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
modux
|
modux4s
|
Java
|
Code
| 148
| 545
|
package modux.plugin.classutils;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Set;
public class FileTool {
static public void unzip(File fileIn, File dir, boolean isLinux) throws IOException {
TarArchiveInputStream tarIn = new TarArchiveInputStream(
new GzipCompressorInputStream(
new BufferedInputStream(
new FileInputStream(fileIn)
)
)
);
byte[] b = new byte[4096];
TarArchiveEntry tarEntry;
Set<PosixFilePermission> perms = new HashSet<>();
perms.add(PosixFilePermission.OWNER_EXECUTE);
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
while ((tarEntry = tarIn.getNextTarEntry()) != null) {
final File file = new File(dir, tarEntry.getName());
if (tarEntry.isDirectory()) {
if (!file.mkdirs()) {
throw new IOException("Unable to create folder " + file.getAbsolutePath());
}
} else {
final File parent = file.getParentFile();
if (!parent.exists()) {
if (!parent.mkdirs()) {
throw new IOException("Unable to create folder " + parent.getAbsolutePath());
}
}
try (FileOutputStream fos = new FileOutputStream(file)) {
int r;
while ((r = tarIn.read(b)) != -1) {
fos.write(b, 0, r);
}
fos.flush();
}
if (isLinux) Files.setPosixFilePermissions(file.toPath(), perms);
}
}
}
}
| 24,997
|
https://github.com/hotrush/laravel-signer/blob/master/tests/SignatureTest.php
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
laravel-signer
|
hotrush
|
PHP
|
Code
| 182
| 833
|
<?php
declare(strict_types=1);
namespace Hotrush\Signer\Tests;
use Hotrush\Signer\Signature;
use Illuminate\Foundation\Testing\WithFaker;
class SignatureTest extends TestCase
{
use WithFaker;
public function test_encoding(): void
{
$hash = $this->faker->uuid();
$expiresAt = now()->addHour();
$payload = ['email' => $this->faker->email()];
$signature = (string) new Signature($hash, $expiresAt, $payload);
$this->assertNotEmpty($signature);
$signatureDecoded = Signature::decode($signature);
$this->assertInstanceOf(Signature::class, $signatureDecoded);
$this->assertEquals($hash, $signatureDecoded->hash);
$this->assertEquals($expiresAt->toAtomString(), $signatureDecoded->expiresAt->toAtomString());
$this->assertEquals($payload, $signatureDecoded->payload);
}
public function test_encoding_without_expiration(): void
{
$hash = $this->faker->uuid();
$expiresAt = null;
$payload = ['email' => $this->faker->email()];
$signature = (string) new Signature($hash, $expiresAt, $payload);
$this->assertNotEmpty($signature);
$signatureDecoded = Signature::decode($signature);
$this->assertInstanceOf(Signature::class, $signatureDecoded);
$this->assertEquals($hash, $signatureDecoded->hash);
$this->assertEquals(null, $signatureDecoded->expiresAt);
$this->assertEquals($payload, $signatureDecoded->payload);
}
/**
* @dataProvider decoding_errors_data
*/
public function test_decoding_errors(string $signature, string $exception, string $exceptionMessage): void
{
$this->expectException($exception);
$this->expectExceptionMessage($exceptionMessage);
Signature::decode($signature);
}
public function decoding_errors_data(): array
{
return [
['invalid', \InvalidArgumentException::class, 'Can not decode signature'],
[
base64_encode(json_encode(['foo' => 'bar'])),
\InvalidArgumentException::class,
'Signature is invalid',
],
[
base64_encode(json_encode(['hash' => 'qwerty'])),
\InvalidArgumentException::class,
'Signature is invalid',
],
[
base64_encode(json_encode(['hash' => 'qwerty', 'expires_at' => null])),
\InvalidArgumentException::class,
'Signature is invalid',
],
[
base64_encode(json_encode(['hash' => 'qwerty', 'expires_at' => '2022-11-23T16:33:52.000000+0000', 'payload' => 'foo'])),
\InvalidArgumentException::class,
'Signature is invalid',
],
[
base64_encode(json_encode(['hash' => 'qwerty', 'expires_at' => '-11-23T16:33:52.000000+0000', 'payload' => []])),
\InvalidArgumentException::class,
'Could not parse',
],
];
}
}
| 23,753
|
https://github.com/MattDowens/bootstrap/blob/master/pycftboot/revised-ising-gap.py
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
bootstrap
|
MattDowens
|
Python
|
Code
| 820
| 2,590
|
import bootstrap
import matplotlib.pyplot as plt
import time
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
class Grid(object):
def __init__(self, dim, kmax, lmax, mmax, nmax, allowed_points, disallowed_points):
self.dim = dim
self.kmax = kmax
self.lmax = lmax
self.mmax = mmax
self.nmax = nmax
self.allowed_points = allowed_points
self.disallowed_points = disallowed_points
class IsingGap(object):
bootstrap.cutoff=1e-10
def __init__(self, from_file = False, file_name = 'name', gap = 3, sig_values = np.arange(0.5,0.85,0.05).tolist(), eps_values = np.arange(1.0,2.2,0.2).tolist()):
if from_file == True:
self.recover_table(file_name)
else:
self.default_inputs = {'dim': 3, 'kmax': 7, 'lmax': 7, 'mmax': 2, 'nmax': 4}
self.inputs = self.default_inputs
self.gap = gap
self.sig_values = sig_values
self.eps_values = eps_values
self.table = []
def determine_grid(self):
#key = [self.inputs['dim'], self.inputs['kmax'], self.inputs['lmax'], self.inputs['mmax'], self.inputs['nmax']]
key = list(self.inputs.values())
tab1 = bootstrap.ConformalBlockTable(*key)
tab2 = bootstrap.ConvolvedBlockTable(tab1)
# Instantiate a Grid object with appropriate input values.
grid=Grid(*key, [], [])
for sig in self.sig_values:
for eps in self.eps_values:
sdp = bootstrap.SDP(sig,tab2)
sdp.set_bound(0,float(self.gap))
sdp.add_point(0,eps)
result = sdp.iterate()
if result:
grid.allowed_points.append((sig, eps))
else:
grid.disallowed_points.append((sig,eps))
# Now append this grid object to the IsingGap table.
# Note we will need to implement a look up table to retrieve desired data.
self.table.append(grid)
def iterate_parameter(self, par, par_range):
if type(par_range) == int:
par_range = [par_range]
for x in par_range:
self.inputs[par] = x
if self.get_grid_index(*list(self.inputs.values())) != -1:
continue
self.determine_grid()
self.inputs = self.default_inputs
def save_to_file(self, name):
with open(name + ".py", 'w') as file:
#file.write("self.default_inputs = " + self.default_inputs.__str__() + "\n")
#file.write("self.inputs = " + self.inputs.__str__() + "\n")
file.write("self.gap = " + self.gap.__str__() + "\n")
file.write("self.sig_values = " + self.sig_values.__str__() + "\n")
file.write("self.eps_values = " + self.eps_values.__str__() + "\n")
file.write("self.table = []\n")
for grid in self.table:
file.write("dim = " + str(grid.dim) + "\n")
file.write("kmax = " + str(grid.kmax) + "\n")
file.write("lmax = " + str(grid.lmax) + "\n")
file.write("mmax = " + str(grid.mmax) + "\n")
file.write("nmax = " + str(grid.nmax) + "\n")
file.write("allowed_points = " + str(grid.allowed_points) + "\n")
file.write("disallowed_points = " + str(grid.disallowed_points) + "\n")
file.write("self.table.append(Grid(dim, kmax, lmax, mmax, nmax, allowed_points, disallowed_points))" + "\n")
#file.write("self.table = table")
def recover_table(self, file_name):
exec(open(file_name + ".py").read())
# Searches table of grids for index matching input parameters. Returns -1 if not found.
def get_grid_index(self, dim, kmax, lmax, mmax, nmax):
for i in range(0, len(self.table)):
if self.table[i].dim == dim and self.table[i].kmax == kmax and self.table[i].lmax == lmax and self.table[i].mmax == mmax and self.table[i].nmax == nmax:
return i
return -1
# Note, imputs will be a list of grid objects, as found in the table attribute.
def plot_grids(dim_values, kmax_values, lmax_values, mmax_values, nmax_values):
table = self.generate_table(dim_values, kmax_values, lmax_values, mmax_values, nmax_values)
pdf_pages = PdfPages('grids.pdf')
# Define the number of plots per page and the size of the grid board.
nb_plots = len(table)
nb_plots_per_page = 6
nb_pages = int(np.ceil(nb_plots / float(nb_plots_per_page)))
grid_size=(3,2)
# This will define which row of the grid we are on.
row_index = 0
# We go through each 'grid' in 'table', generating a plot for each.
for i in range(nb_plots):
# To begin, declare a new figure / page if we have exceeded limit of the last page.
if i % nb_plots_per_page == 0:
fig = plt.figure(figsize=(8.27, 11.69), dpi=100)
# Now, add a plot for the current grid on the grid board.
plt.subplot2grid(grid_size, (row_index, i % grid_size[1]))
if i % grid_size[1] == 1:
row_index += 1
# Handle our data. Retrieve isolated points for plotting from out input table of Grid objects.
allowed_sig = [points[0] for points in table[i].allowed_points]
allowed_eps = [points[1] for points in table[i].allowed_points]
disallowed_sig = [points[0] for points in table[i].disallowed_points]
disallowed_eps = [points[1] for points in table[i].disallowed_points]
# Plot a grid.
plt.plot(allowed_sig, allowed_eps, 'r+')
plt.plot(disallowed_sig, disallowed_eps, 'b+')
plt.title('kmax : ' + table[i].kmax.__str__() + " " +
'lmax : ' + table[i].lmax.__str__() + " " +
'mmax : ' + table[i].mmax.__str__() + " " +
'nmax : ' + table[i].nmax.__str__())
# If we have filled a page, or have reached the end of our plots, tight-pack and save the page.
if (i + 1) % nb_plots_per_page == 0 or (i + 1) == nb_plots:
plt.tight_layout()
pdf_pages.savefig(fig)
row_index = 0
pdf_pages.close()
# Generates a table of already determined grids, specified by lists of points of input parameters.
def generate_table(dim_range, kmax_range, lmax_range, mmax_range, nmax_range):
# table to store the resulting grids.
table = []
if type(dim_range) == int:
dim_range = [dim_range]
if type(kmax_range) == int:
kmax_range = [kmax_range]
if type(lmax_range) == int:
lmax_range = [lmax_range]
if type(mmax_range) == int:
mmax_range = [mmax_range]
if type(nmax_range) == int:
nmax_range = [nmax_range]
# Generates a list of unique keys, giving a warning message if a grid isn't found.
keys = []
for dim in dim_range:
for kmax in kmax_range:
for lmax in lmax_range:
for mmax in mmax_range:
for nmax in nmax_range:
key = [dim, kmax, lmax, mmax, nmax]
if self.get_grid_index(*key) == -1:
print("Grid at dim = " + str(key[0]) + ", " +
"kmax = " + str(key[1]) + ", " +
"lmax = " + str(key[2]) + ", " +
"mmax = " + str(key[3]) + ", " +
"nmax = " + str(key[4]) + " does not exist.")
else:
table.append(self.table[self.get_grid_index(*key)])
return table
| 8,307
|
https://github.com/xie-wenjie/AndroidBaseApplicationSourse/blob/master/apps/QuickSearchBox/src/com/android/quicksearchbox/google/GoogleSuggestionProvider.java
|
Github Open Source
|
Open Source
|
MIT
| null |
AndroidBaseApplicationSourse
|
xie-wenjie
|
Java
|
Code
| 392
| 1,119
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.quicksearchbox.google;
import com.android.quicksearchbox.QsbApplication;
import com.android.quicksearchbox.SuggestionCursorBackedCursor;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
/**
* A suggestion provider which provides content from Genie, a service that offers
* a superset of the content provided by Google Suggest.
*/
public class GoogleSuggestionProvider extends ContentProvider {
// UriMatcher constants
private static final int SEARCH_SUGGEST = 0;
private static final int SEARCH_SHORTCUT = 1;
private UriMatcher mUriMatcher;
private GoogleSource mSource;
@Override
public boolean onCreate() {
mSource = QsbApplication.get(getContext()).getGoogleSource();
mUriMatcher = buildUriMatcher(getContext());
return true;
}
/**
* This will always return {@link SearchManager#SUGGEST_MIME_TYPE} as this
* provider is purely to provide suggestions.
*/
@Override
public String getType(Uri uri) {
return SearchManager.SUGGEST_MIME_TYPE;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
int match = mUriMatcher.match(uri);
if (match == SEARCH_SUGGEST) {
String query = getQuery(uri);
return new SuggestionCursorBackedCursor(mSource.getSuggestionsExternal(query));
} else if (match == SEARCH_SHORTCUT) {
String shortcutId = getQuery(uri);
String extraData =
uri.getQueryParameter(SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);
return new SuggestionCursorBackedCursor(mSource.refreshShortcut(shortcutId, extraData));
} else {
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
/**
* Gets the search text from a uri.
*/
private String getQuery(Uri uri) {
if (uri.getPathSegments().size() > 1) {
return uri.getLastPathSegment();
} else {
return "";
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException();
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
throw new UnsupportedOperationException();
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
private UriMatcher buildUriMatcher(Context context) {
String authority = getAuthority(context);
UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY,
SEARCH_SUGGEST);
matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY + "/*",
SEARCH_SUGGEST);
matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_SHORTCUT,
SEARCH_SHORTCUT);
matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*",
SEARCH_SHORTCUT);
return matcher;
}
protected String getAuthority(Context context) {
return context.getPackageName() + ".google";
}
}
| 24,532
|
https://github.com/Screaming-Onion/CSharp-API-Project/blob/master/src/App/App.Dto/Logs/LogErrorInfo.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
CSharp-API-Project
|
Screaming-Onion
|
C#
|
Code
| 49
| 121
|
namespace App.Dto.Logs
{
public class LogErrorInfo
{
public string ErrorMessage { get; }
public System.Exception Exception { get; }
public bool IsException { get; }
public LogErrorInfo(string errorMessage)
{
ErrorMessage = errorMessage;
IsException = false;
}
public LogErrorInfo(System.Exception exception)
{
Exception = exception;
IsException = true;
}
}
}
| 8,658
|
https://github.com/lehnenb/examples/blob/master/upload/main.go
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
examples
|
lehnenb
|
Go
|
Code
| 255
| 881
|
// Command upload is a chromedp example demonstrating how to upload a file on a
// form.
package main
import (
"context"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/chromedp/chromedp"
)
var flagPort = flag.Int("port", 8544, "port")
func main() {
flag.Parse()
// get wd
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
filepath := wd + "/main.go"
// get some info about the file
fi, err := os.Stat(filepath)
if err != nil {
log.Fatal(err)
}
// start upload server
result := make(chan int, 1)
go uploadServer(fmt.Sprintf(":%d", *flagPort), result)
// create context
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// run task list
var sz string
err = chromedp.Run(ctx, upload(filepath, &sz))
if err != nil {
log.Fatal(err)
}
log.Printf("original size: %d, upload size: %d", fi.Size(), <-result)
}
func upload(filepath string, sz *string) chromedp.Tasks {
return chromedp.Tasks{
chromedp.Navigate(fmt.Sprintf("http://localhost:%d", *flagPort)),
chromedp.SendKeys(`input[name="upload"]`, filepath, chromedp.NodeVisible),
chromedp.Click(`input[name="submit"]`),
chromedp.Text(`#result`, sz, chromedp.ByID, chromedp.NodeVisible),
}
}
func uploadServer(addr string, result chan int) error {
// create http server and result channel
mux := http.NewServeMux()
mux.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
fmt.Fprintf(res, uploadHTML)
})
mux.HandleFunc("/upload", func(res http.ResponseWriter, req *http.Request) {
f, _, err := req.FormFile("upload")
if err != nil {
http.Error(res, err.Error(), http.StatusBadRequest)
return
}
defer f.Close()
buf, err := ioutil.ReadAll(f)
if err != nil {
http.Error(res, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(res, resultHTML, len(buf))
result <- len(buf)
})
return http.ListenAndServe(addr, mux)
}
const (
uploadHTML = `<!doctype html>
<html>
<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input name="upload" type="file"/>
<input name="submit" type="submit"/>
</form>
</body>
</html>`
resultHTML = `<!doctype html>
<html>
<body>
<div id="result">%d</div>
</body>
</html>`
)
| 7,111
|
https://github.com/evergreen-ci/spruce/blob/master/src/pages/task/taskTabs/buildBaronAndAnnotations/AddIssueModal/AddIssueModal.test.tsx
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
spruce
|
evergreen-ci
|
TSX
|
Code
| 358
| 1,550
|
import { MockedProvider } from "@apollo/client/testing";
import { RenderFakeToastContext } from "context/toast/__mocks__";
import {
AddAnnotationIssueMutation,
AddAnnotationIssueMutationVariables,
} from "gql/generated/types";
import { getSpruceConfigMock } from "gql/mocks/getSpruceConfig";
import { ADD_ANNOTATION } from "gql/mutations";
import {
renderWithRouterMatch as render,
screen,
userEvent,
waitFor,
} from "test_utils";
import { ApolloMock } from "types/gql";
import { AddIssueModal as AddIssueModalToTest } from ".";
const AddIssueModal = (
props: Omit<
React.ComponentProps<typeof AddIssueModalToTest>,
"execution" | "taskId" | "visible"
>
) => (
<MockedProvider mocks={[getSpruceConfigMock, addAnnotationMock]}>
<AddIssueModalToTest
taskId="1"
execution={0}
visible
data-cy="add-issue-modal"
{...props}
/>
</MockedProvider>
);
describe("addIssueModal", () => {
it("should have submit disabled by default when all the fields are empty", async () => {
const { Component } = RenderFakeToastContext(
<AddIssueModal
closeModal={jest.fn()}
setSelectedRowKey={jest.fn()}
isIssue
/>
);
render(<Component />);
await waitFor(() => {
checkModalVisibility();
});
expect(screen.queryByDataCy("issue-url")).toHaveValue("");
expect(
screen.getByRole("button", {
name: "Add issue",
})
).toHaveAttribute("aria-disabled", "true");
});
it("entering values should enable the submit button", async () => {
const { Component } = RenderFakeToastContext(
<AddIssueModal
closeModal={jest.fn()}
setSelectedRowKey={jest.fn()}
isIssue
/>
);
render(<Component />);
await waitFor(() => {
checkModalVisibility();
});
expect(screen.queryByDataCy("issue-url")).toHaveValue("");
userEvent.type(
screen.queryByDataCy("issue-url"),
"https://jira.mongodb.org/browse/EVG-123"
);
expect(
screen.getByRole("button", {
name: "Add issue",
})
).not.toHaveAttribute("aria-disabled", "true");
});
it("entering an invalid confidence score should disable the submit button", async () => {
const { Component } = RenderFakeToastContext(
<AddIssueModal
closeModal={jest.fn()}
setSelectedRowKey={jest.fn()}
isIssue
/>
);
render(<Component />);
await waitFor(() => {
checkModalVisibility();
});
expect(screen.queryByDataCy("issue-url")).toHaveValue("");
userEvent.type(
screen.queryByDataCy("issue-url"),
"https://jira.mongodb.org/browse/EVG-123"
);
const confirmButton = screen.getByRole("button", {
name: "Add issue",
});
userEvent.type(screen.queryByDataCy("confidence-level"), "not a number");
expect(confirmButton).toHaveAttribute("aria-disabled", "true");
userEvent.clear(screen.queryByDataCy("confidence-level"));
userEvent.type(screen.queryByDataCy("confidence-level"), "110");
expect(confirmButton).toHaveAttribute("aria-disabled", "true");
userEvent.clear(screen.queryByDataCy("confidence-level"));
userEvent.type(screen.queryByDataCy("confidence-level"), "80");
expect(confirmButton).not.toHaveAttribute("aria-disabled", "true");
});
it("should be able to successfully add annotation", async () => {
const setSelectedRowKey = jest.fn();
const { Component, dispatchToast } = RenderFakeToastContext(
<AddIssueModal
closeModal={jest.fn()}
setSelectedRowKey={setSelectedRowKey}
isIssue
/>
);
render(<Component />);
await waitFor(() => {
checkModalVisibility();
});
userEvent.type(
screen.queryByDataCy("issue-url"),
"https://jira.mongodb.org/browse/EVG-123"
);
userEvent.type(screen.queryByDataCy("confidence-level"), "12");
const confirmButton = screen.getByRole("button", {
name: "Add issue",
});
expect(confirmButton).not.toHaveAttribute("aria-disabled", "true");
userEvent.click(confirmButton);
await waitFor(() => expect(dispatchToast.success).toHaveBeenCalledTimes(1));
expect(setSelectedRowKey).toHaveBeenCalledWith("EVG-123");
});
});
const checkModalVisibility = () => {
expect(screen.getByDataCy("add-issue-modal")).toBeVisible();
expect(screen.getByDataCy("issue-url")).toBeVisible();
expect(screen.getByDataCy("confidence-level")).toBeVisible();
};
const addAnnotationMock: ApolloMock<
AddAnnotationIssueMutation,
AddAnnotationIssueMutationVariables
> = {
request: {
query: ADD_ANNOTATION,
variables: {
taskId: "1",
execution: 0,
apiIssue: {
url: "https://jira.mongodb.org/browse/EVG-123",
issueKey: "EVG-123",
confidenceScore: 0.12,
},
isIssue: true,
},
},
result: {
data: {
addAnnotationIssue: true,
},
},
};
| 47,895
|
https://github.com/wuchunfu/EngineX/blob/master/jar-enginex-manager/src/main/java/com/risk/riskmanage/datamanage/model/Field.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
EngineX
|
wuchunfu
|
Java
|
Code
| 1,039
| 3,184
|
package com.risk.riskmanage.datamanage.model;
import com.risk.riskmanage.common.model.BasePage;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class Field extends BasePage implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
* */
private Long id;
/**
* 字段英文名
* */
private String fieldEn;
/**
* 字段中文名
* */
private String fieldCn;
/**
* 字段类型编号
* */
private Long fieldTypeId;
/**
* 字段类型名
* */
private String fieldType;
/**
* 字段存值类型
* */
private Integer valueType;
/**
* 字段存值类型中文
* */
private String valueTypeName;
/**
* 字段约束范围
* */
private String valueScope;
/**
* 是否衍生字段
* */
private Integer isDerivative;
/**
* 是否衍生字段
* */
private String isDerivativeName;
/**
* 是否输出字段
* */
private Integer isOutput;
/**
* 是否输出字段
* */
private String isOutputName;
/**
* 是否组织定义的通用字段
* */
private Integer isCommon;
/**
* 衍生字段公式
* */
private String formula;
/**
* 衍生字段公式回显信息
* */
private String formulaShow;
/**
* 衍生字段引用的字段id
* */
private String usedFieldId;
/**
* 衍生字段引用的原生字段id
* */
private String origFieldId;
/**
* 创建人
* */
private Long author;
/**
* 创建人昵称
* */
private String nickName;
/**
* 创建时间
* */
private Date created;
/**
* 归属的引擎ID
* */
private Long engineId;
/**
* 归属的引擎名称
* */
private String engineName;
/**
* 字段状态(启用、停用、删除、未知)
* */
private String status;
/**
* 字段条件设置集合
* */
private List<FieldCond> fieldCondList;
/**
* 字段用户关系编号
* */
private Long fieldRelId;
/**
* 是否使用sql获取指标
*/
private Boolean isUseSql;
/**
* 使用sql获取指标时对应的数据源
*/
private Integer dataSourceId;
/**
* 使用sql获取指标时对应的sql语句
*/
private String sqlStatement;
/**
* sql变量配置
*/
private String sqlVariable;
//是否使用接口
private Boolean isInterface;
//接口id
private Integer interfaceId;
//接口解析指标
private String interfaceParseField;
//json类型对应的json值
private String jsonValue;
//字典变量如:日期字符串
private String dictVariable;
public String getDictVariable() {
return dictVariable;
}
public void setDictVariable(String dicVariable) {
this.dictVariable = dicVariable;
}
/**
* 该字段归属的组织编号
* */
private Long organId;
public String getInterfaceParseField() {
return interfaceParseField;
}
public void setInterfaceParseField(String interfaceParseField) {
this.interfaceParseField = interfaceParseField;
}
public String getJsonValue() {
return jsonValue;
}
public void setJsonValue(String jsonValue) {
this.jsonValue = jsonValue;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFieldEn() {
return fieldEn;
}
public void setFieldEn(String fieldEn) {
this.fieldEn = fieldEn;
}
public String getFieldCn() {
return fieldCn;
}
public void setFieldCn(String fieldCn) {
this.fieldCn = fieldCn;
}
public Long getFieldTypeId() {
return fieldTypeId;
}
public void setFieldTypeId(Long fieldTypeId) {
this.fieldTypeId = fieldTypeId;
}
public Integer getValueType() {
return valueType;
}
public void setValueType(Integer valueType) {
this.valueType = valueType;
}
public String getValueScope() {
return valueScope;
}
public void setValueScope(String valueScope) {
this.valueScope = valueScope;
}
public Integer getIsDerivative() {
return isDerivative;
}
public void setIsDerivative(Integer isDerivative) {
this.isDerivative = isDerivative;
}
public Integer getIsOutput() {
return isOutput;
}
public void setIsOutput(Integer isOutput) {
this.isOutput = isOutput;
}
public Integer getIsCommon() {
return isCommon;
}
public void setIsCommon(Integer isCommon) {
this.isCommon = isCommon;
}
public String getFormula() {
return formula;
}
public void setFormula(String formula) {
this.formula = formula;
}
public String getFormulaShow() {
return formulaShow;
}
public void setFormulaShow(String formulaShow) {
this.formulaShow = formulaShow;
}
public String getUsedFieldId() {
return usedFieldId;
}
public void setUsedFieldId(String usedFieldId) {
this.usedFieldId = usedFieldId;
}
public String getOrigFieldId() {
return origFieldId;
}
public void setOrigFieldId(String origFieldId) {
this.origFieldId = origFieldId;
}
public Long getAuthor() {
return author;
}
public void setAuthor(Long author) {
this.author = author;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Long getEngineId() {
return engineId;
}
public void setEngineId(Long engineId) {
this.engineId = engineId;
}
public String getFieldType() {
return fieldType;
}
public void setFieldType(String fieldType) {
this.fieldType = fieldType;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Long getFieldRelId() {
return fieldRelId;
}
public void setFieldRelId(Long fieldRelId) {
this.fieldRelId = fieldRelId;
}
public List<FieldCond> getFieldCondList() {
return fieldCondList;
}
public void setFieldCondList(List<FieldCond> fieldCondList) {
this.fieldCondList = fieldCondList;
}
public String getEngineName() {
return engineName;
}
public void setEngineName(String engineName) {
this.engineName = engineName;
}
public String getValueTypeName() {
return valueTypeName;
}
public void setValueTypeName(String valueTypeName) {
this.valueTypeName = valueTypeName;
}
public String getIsDerivativeName() {
return isDerivativeName;
}
public void setIsDerivativeName(String isDerivativeName) {
this.isDerivativeName = isDerivativeName;
}
public String getIsOutputName() {
return isOutputName;
}
public void setIsOutputName(String isOutputName) {
this.isOutputName = isOutputName;
}
public Boolean getUseSql() {
return isUseSql;
}
public void setUseSql(Boolean useSql) {
isUseSql = useSql;
}
public Integer getDataSourceId() {
return dataSourceId;
}
public void setDataSourceId(Integer dataSourceId) {
this.dataSourceId = dataSourceId;
}
public String getSqlStatement() {
return sqlStatement;
}
public void setSqlStatement(String sqlStatement) {
this.sqlStatement = sqlStatement;
}
@Override
public String toString() {
return "Field{" +
"id=" + id +
", fieldEn='" + fieldEn + '\'' +
", fieldCn='" + fieldCn + '\'' +
", fieldTypeId=" + fieldTypeId +
", fieldType='" + fieldType + '\'' +
", valueType=" + valueType +
", valueTypeName='" + valueTypeName + '\'' +
", valueScope='" + valueScope + '\'' +
", isDerivative=" + isDerivative +
", isDerivativeName='" + isDerivativeName + '\'' +
", isOutput=" + isOutput +
", isOutputName='" + isOutputName + '\'' +
", isCommon=" + isCommon +
", formula='" + formula + '\'' +
", formulaShow='" + formulaShow + '\'' +
", usedFieldId='" + usedFieldId + '\'' +
", origFieldId='" + origFieldId + '\'' +
", author=" + author +
", nickName='" + nickName + '\'' +
", created=" + created +
", engineId=" + engineId +
", engineName='" + engineName + '\'' +
", status='" + status + '\'' +
", fieldCondList=" + fieldCondList +
", fieldRelId=" + fieldRelId +
", isUseSql=" + isUseSql +
", dataSourceId=" + dataSourceId +
", sqlStatement='" + sqlStatement + '\'' +
", isInterface=" + isInterface +
", interfaceId=" + interfaceId +
'}';
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public Boolean getInterface() {
return isInterface;
}
public void setInterface(Boolean anInterface) {
isInterface = anInterface;
}
public Integer getInterfaceId() {
return interfaceId;
}
public void setInterfaceId(Integer interfaceId) {
this.interfaceId = interfaceId;
}
public String getSqlVariable() {
return sqlVariable;
}
public void setSqlVariable(String sqlVariable) {
this.sqlVariable = sqlVariable;
}
public Long getOrganId() {
return organId;
}
public void setOrganId(Long organId) {
this.organId = organId;
}
}
| 25,399
|
https://github.com/GI-Backyard/BasicRayTracing/blob/master/BasicRayTracing/sphere.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
BasicRayTracing
|
GI-Backyard
|
C++
|
Code
| 205
| 509
|
//
// sphere.cpp
// BasicRayTracing
//
// Created by huabingxu on 2019/3/28.
// Copyright © 2019 harrisonxu. All rights reserved.
//
#include "sphere.hpp"
#include "material.h"
Sphere::~Sphere() {
delete mtl;
}
bool Sphere::hit(const Ray& r, float tMin, float tMax, HitRecord& rec) const {
Vec3 ac = r.origin() - center;
// a * t *t + b * t + c = 0;
float a = dot(r.direction(), r.direction());
float b = dot(r.direction(), ac);
float c = dot(ac, ac) - radius * radius;
float discriminant = b * b - a * c;
if(discriminant < 0) return false;
float t1 = (- b - sqrt(discriminant))/ a;
if(t1 >= tMin && t1 <= tMax) {
rec.t = t1;
rec.p = r.getPoint(t1);
rec.normal = (rec.p - center) / radius;
rec.mtl = this->mtl;
rec.obj = this;
return true;
}
float t2 = (- b + sqrt(discriminant))/ a;
if(t2 >= tMin && t2 <= tMax) {
rec.t = t2;
rec.p = r.getPoint(t2);
rec.normal = (rec.p - center) / radius;
rec.mtl = this->mtl;
rec.obj = this;
return true;
}
// exceeds tMin and tMax, return false
return false;
}
bool Sphere::bounding_box(float t0, float t1, AABB& bb) const {
bb = AABB(this->center - Vec3(radius, radius, radius), this->center + Vec3(radius, radius, radius));
return true;
}
| 27,053
|
https://github.com/mikangogo/JRTrainPack/blob/master/Rock_On/Train/JR/Plugin/ATS_East/signal_pattern.nut
|
Github Open Source
|
Open Source
|
Condor-1.1
| 2,022
|
JRTrainPack
|
mikangogo
|
Squirrel
|
Code
| 6,124
| 26,876
|
function get_brake_pattern_offset(limit_speed)
{
return 0;
}
function get_incoming_pattern_offset(limit_speed)
{
return 0;
}
function lookup_brake_pattern(limit_speed, accum_distance, target_distance, offset_distance)
{
local brake_pattern_table =
{
[0] = 10.0,
[1] = 10.0,
[2] = 10.0,
[3] = 10.0,
[4] = 10.0,
[5] = 10.73312629,
[6] = 11.75755077,
[7] = 12.69960629,
[8] = 13.5764502,
[9] = 14.4,
[10] = 15.17893277,
[11] = 15.91979899,
[12] = 16.62768775,
[13] = 17.30664612,
[14] = 17.95995546,
[15] = 18.59032006,
[16] = 19.2,
[17] = 19.790907,
[18] = 20.3646753,
[19] = 20.92271493,
[20] = 21.46625258,
[21] = 21.99636334,
[22] = 22.51399565,
[23] = 23.01999131,
[24] = 23.51510153,
[25] = 24,
[26] = 24.47529367,
[27] = 24.94153163,
[28] = 25.39921259,
[29] = 25.84879107,
[30] = 26.29068276,
[31] = 26.72526894,
[32] = 27.1529004,
[33] = 27.5739007,
[34] = 27.9885691,
[35] = 28.39718296,
[36] = 28.8,
[37] = 29.19726015,
[38] = 29.58918721,
[39] = 29.97599039,
[40] = 30.35786554,
[41] = 30.73499634,
[42] = 31.10755535,
[43] = 31.47570492,
[44] = 31.83959799,
[45] = 32.19937888,
[46] = 32.55518392,
[47] = 32.90714208,
[48] = 33.25537551,
[49] = 33.6,
[50] = 33.9411255,
[51] = 34.27885646,
[52] = 34.61329224,
[53] = 34.94452747,
[54] = 35.2726523,
[55] = 35.59775274,
[56] = 35.91991091,
[57] = 36.23920529,
[58] = 36.55571091,
[59] = 36.86949959,
[60] = 37.18064012,
[61] = 37.48919844,
[62] = 37.7952378,
[63] = 38.09881888,
[64] = 38.4,
[65] = 38.69883719,
[66] = 38.99538434,
[67] = 39.2896933,
[68] = 39.58181401,
[69] = 39.87179454,
[70] = 40.15968127,
[71] = 40.44551891,
[72] = 40.7293506,
[73] = 41.01121798,
[74] = 41.29116128,
[75] = 41.56921938,
[76] = 41.84542986,
[77] = 42.11982906,
[78] = 42.39245216,
[79] = 42.6633332,
[80] = 42.93250517,
[81] = 43.2,
[82] = 43.46584866,
[83] = 43.73008118,
[84] = 43.99272667,
[85] = 44.2538134,
[86] = 44.51336878,
[87] = 44.77141945,
[88] = 45.02799129,
[89] = 45.28310943,
[90] = 45.53679831,
[91] = 45.78908167,
[92] = 46.03998262,
[93] = 46.28952365,
[94] = 46.53772663,
[95] = 46.78461286,
[96] = 47.03020306,
[97] = 47.27451745,
[98] = 47.5175757,
[99] = 47.75939698,
[100] = 48,
[101] = 48.23940298,
[102] = 48.4776237,
[103] = 48.71467951,
[104] = 48.95058733,
[105] = 49.18536368,
[106] = 49.41902468,
[107] = 49.65158608,
[108] = 49.88306326,
[109] = 50.11347124,
[110] = 50.34282471,
[111] = 50.57113801,
[112] = 50.79842517,
[113] = 51.0246999,
[114] = 51.24997561,
[115] = 51.47426541,
[116] = 51.69758215,
[117] = 51.91993837,
[118] = 52.14134636,
[119] = 52.36181815,
[120] = 52.58136552,
[121] = 52.8,
[122] = 53.01773288,
[123] = 53.23457523,
[124] = 53.45053788,
[125] = 53.66563146,
[126] = 53.87986637,
[127] = 54.09325281,
[128] = 54.3058008,
[129] = 54.51752012,
[130] = 54.7284204,
[131] = 54.93851108,
[132] = 55.14780141,
[133] = 55.35630045,
[134] = 55.56401713,
[135] = 55.77096019,
[136] = 55.97713819,
[137] = 56.18255957,
[138] = 56.3872326,
[139] = 56.59116539,
[140] = 56.79436592,
[141] = 56.99684202,
[142] = 57.19860138,
[143] = 57.39965157,
[144] = 57.6,
[145] = 57.79965398,
[146] = 57.99862067,
[147] = 58.19690713,
[148] = 58.39452029,
[149] = 58.59146696,
[150] = 58.78775383,
[151] = 58.98338749,
[152] = 59.17837443,
[153] = 59.37272101,
[154] = 59.5664335,
[155] = 59.75951807,
[156] = 59.95198078,
[157] = 60.14382761,
[158] = 60.33506443,
[159] = 60.52569702,
[160] = 60.71573108,
[161] = 60.90517219,
[162] = 61.09402589,
[163] = 61.28229761,
[164] = 61.46999268,
[165] = 61.65711638,
[166] = 61.84367389,
[167] = 62.02967032,
[168] = 62.2151107,
[169] = 62.4,
[170] = 62.58434309,
[171] = 62.76814479,
[172] = 62.95140983,
[173] = 63.1341429,
[174] = 63.3163486,
[175] = 63.49803147,
[176] = 63.67919597,
[177] = 63.85984654,
[178] = 64.03998751,
[179] = 64.21962317,
[180] = 64.39875775,
[181] = 64.57739543,
[182] = 64.7555403,
[183] = 64.93319644,
[184] = 65.11036784,
[185] = 65.28705844,
[186] = 65.46327215,
[187] = 65.63901279,
[188] = 65.81428416,
[189] = 65.98909001,
[190] = 66.16343401,
[191] = 66.33731981,
[192] = 66.51075101,
[193] = 66.68373115,
[194] = 66.85626373,
[195] = 67.02835221,
[196] = 67.2,
[197] = 67.37121047,
[198] = 67.54198694,
[199] = 67.7123327,
[200] = 67.88225099,
[201] = 68.05174502,
[202] = 68.22081794,
[203] = 68.38947287,
[204] = 68.55771291,
[205] = 68.7255411,
[206] = 68.89296045,
[207] = 69.05997394,
[208] = 69.22658449,
[209] = 69.39279502,
[210] = 69.55860838,
[211] = 69.72402742,
[212] = 69.88905494,
[213] = 70.05369369,
[214] = 70.21794642,
[215] = 70.38181583,
[216] = 70.54530459,
[217] = 70.70841534,
[218] = 70.87115069,
[219] = 71.03351322,
[220] = 71.19550548,
[221] = 71.35712999,
[222] = 71.51838924,
[223] = 71.67928571,
[224] = 71.83982183,
[225] = 72,
[226] = 72.15982262,
[227] = 72.31929203,
[228] = 72.47841058,
[229] = 72.63718056,
[230] = 72.79560426,
[231] = 72.95368394,
[232] = 73.11142182,
[233] = 73.26882011,
[234] = 73.425881,
[235] = 73.58260664,
[236] = 73.73899918,
[237] = 73.89506073,
[238] = 74.05079338,
[239] = 74.2061992,
[240] = 74.36128025,
[241] = 74.51603854,
[242] = 74.67047609,
[243] = 74.82459489,
[244] = 74.97839689,
[245] = 75.13188404,
[246] = 75.28505828,
[247] = 75.4379215,
[248] = 75.59047559,
[249] = 75.74272242,
[250] = 75.89466384,
[251] = 76.04630169,
[252] = 76.19763776,
[253] = 76.34867386,
[254] = 76.49941176,
[255] = 76.64985323,
[256] = 76.8,
[257] = 76.9498538,
[258] = 77.09941634,
[259] = 77.24868931,
[260] = 77.39767438,
[261] = 77.54637322,
[262] = 77.69478747,
[263] = 77.84291875,
[264] = 77.99076868,
[265] = 78.13833886,
[266] = 78.28563087,
[267] = 78.43264626,
[268] = 78.57938661,
[269] = 78.72585344,
[270] = 78.87204828,
[271] = 79.01797264,
[272] = 79.16362801,
[273] = 79.30901588,
[274] = 79.45413771,
[275] = 79.59899497,
[276] = 79.74358908,
[277] = 79.88792149,
[278] = 80.0319936,
[279] = 80.17580682,
[280] = 80.31936255,
[281] = 80.46266215,
[282] = 80.60570699,
[283] = 80.74849844,
[284] = 80.89103782,
[285] = 81.03332648,
[286] = 81.17536572,
[287] = 81.31715686,
[288] = 81.45870119,
[289] = 81.6,
[290] = 81.74105456,
[291] = 81.88186612,
[292] = 82.02243596,
[293] = 82.16276529,
[294] = 82.30285536,
[295] = 82.44270738,
[296] = 82.58232256,
[297] = 82.72170211,
[298] = 82.86084721,
[299] = 82.99975904,
[300] = 83.13843876,
[301] = 83.27688755,
[302] = 83.41510655,
[303] = 83.55309689,
[304] = 83.69085972,
[305] = 83.82839614,
[306] = 83.96570729,
[307] = 84.10279425,
[308] = 84.23965812,
[309] = 84.37629999,
[310] = 84.51272094,
[311] = 84.64892203,
[312] = 84.78490432,
[313] = 84.92066886,
[314] = 85.0562167,
[315] = 85.19154888,
[316] = 85.32666641,
[317] = 85.46157031,
[318] = 85.5962616,
[319] = 85.73074128,
[320] = 85.86501034,
[321] = 85.99906976,
[322] = 86.13292054,
[323] = 86.26656363,
[324] = 86.4,
[325] = 86.53323061,
[326] = 86.66625641,
[327] = 86.79907834,
[328] = 86.93169733,
[329] = 87.06411431,
[330] = 87.1963302,
[331] = 87.32834591,
[332] = 87.46016236,
[333] = 87.59178044,
[334] = 87.72320104,
[335] = 87.85442505,
[336] = 87.98545334,
[337] = 88.1162868,
[338] = 88.24692629,
[339] = 88.37737267,
[340] = 88.50762679,
[341] = 88.6376895,
[342] = 88.76756164,
[343] = 88.89724405,
[344] = 89.02673756,
[345] = 89.15604298,
[346] = 89.28516114,
[347] = 89.41409285,
[348] = 89.54283891,
[349] = 89.67140012,
[350] = 89.79977728,
[351] = 89.92797118,
[352] = 90.05598259,
[353] = 90.18381229,
[354] = 90.31146107,
[355] = 90.43892967,
[356] = 90.56621887,
[357] = 90.69332941,
[358] = 90.82026206,
[359] = 90.94701754,
[360] = 91.07359661,
[361] = 91.2,
[362] = 91.32622843,
[363] = 91.45228264,
[364] = 91.57816334,
[365] = 91.70387124,
[366] = 91.82940705,
[367] = 91.95477149,
[368] = 92.07996525,
[369] = 92.20498902,
[370] = 92.3298435,
[371] = 92.45452936,
[372] = 92.57904731,
[373] = 92.703398,
[374] = 92.82758211,
[375] = 92.95160031,
[376] = 93.07545326,
[377] = 93.19914163,
[378] = 93.32266606,
[379] = 93.4460272,
[380] = 93.56922571,
[381] = 93.69226222,
[382] = 93.81513737,
[383] = 93.9378518,
[384] = 94.06040612,
[385] = 94.18280098,
[386] = 94.30503698,
[387] = 94.42711475,
[388] = 94.5490349,
[389] = 94.67079803,
[390] = 94.79240476,
[391] = 94.91385568,
[392] = 95.03515139,
[393] = 95.15629249,
[394] = 95.27727956,
[395] = 95.39811319,
[396] = 95.51879396,
[397] = 95.63932246,
[398] = 95.75969925,
[399] = 95.87992491,
[400] = 96,
[401] = 96.11992509,
[402] = 96.23970075,
[403] = 96.35932752,
[404] = 96.47880596,
[405] = 96.59813663,
[406] = 96.71732006,
[407] = 96.83635681,
[408] = 96.95524741,
[409] = 97.0739924,
[410] = 97.19259231,
[411] = 97.31104768,
[412] = 97.42935902,
[413] = 97.54752688,
[414] = 97.66555176,
[415] = 97.78343418,
[416] = 97.90117466,
[417] = 98.01877371,
[418] = 98.13623184,
[419] = 98.25354955,
[420] = 98.37072735,
[421] = 98.48776574,
[422] = 98.6046652,
[423] = 98.72142625,
[424] = 98.83804935,
[425] = 98.95453501,
[426] = 99.07088371,
[427] = 99.18709593,
[428] = 99.30317215,
[429] = 99.41911285,
[430] = 99.5349185,
[431] = 99.65058956,
[432] = 99.76612652,
[433] = 99.88152982,
[434] = 99.99679995,
[435] = 100.1119374,
[436] = 100.2269425,
[437] = 100.3418158,
[438] = 100.4565578,
[439] = 100.5711688,
[440] = 100.6856494,
[441] = 100.8,
[442] = 100.914221,
[443] = 101.0283129,
[444] = 101.142276,
[445] = 101.2561109,
[446] = 101.369818,
[447] = 101.4833977,
[448] = 101.5968503,
[449] = 101.7101765,
[450] = 101.8233765,
[451] = 101.9364508,
[452] = 102.0493998,
[453] = 102.1622239,
[454] = 102.2749236,
[455] = 102.3874992,
[456] = 102.4999512,
[457] = 102.61228,
[458] = 102.7244859,
[459] = 102.8365694,
[460] = 102.9485308,
[461] = 103.0603707,
[462] = 103.1720892,
[463] = 103.283687,
[464] = 103.3951643,
[465] = 103.5065215,
[466] = 103.6177591,
[467] = 103.7288774,
[468] = 103.8398767,
[469] = 103.9507576,
[470] = 104.0615203,
[471] = 104.1721652,
[472] = 104.2826927,
[473] = 104.3931032,
[474] = 104.5033971,
[475] = 104.6135746,
[476] = 104.7236363,
[477] = 104.8335824,
[478] = 104.9434133,
[479] = 105.0531294,
[480] = 105.162731,
[481] = 105.2722186,
[482] = 105.3815923,
[483] = 105.4908527,
[484] = 105.6,
[485] = 105.7090346,
[486] = 105.8179569,
[487] = 105.9267672,
[488] = 106.0354658,
[489] = 106.1440531,
[490] = 106.2525294,
[491] = 106.3608951,
[492] = 106.4691505,
[493] = 106.5772959,
[494] = 106.6853317,
[495] = 106.7932582,
[496] = 106.9010758,
[497] = 107.0087847,
[498] = 107.1163853,
[499] = 107.2238779,
[500] = 107.3312629,
[501] = 107.4385406,
[502] = 107.5457112,
[503] = 107.6527752,
[504] = 107.7597327,
[505] = 107.8665843,
[506] = 107.97333,
[507] = 108.0799704,
[508] = 108.1865056,
[509] = 108.2929361,
[510] = 108.399262,
[511] = 108.5054837,
[512] = 108.6116016,
[513] = 108.7176159,
[514] = 108.8235269,
[515] = 108.9293349,
[516] = 109.0350402,
[517] = 109.1406432,
[518] = 109.2461441,
[519] = 109.3515432,
[520] = 109.4568408,
[521] = 109.5620372,
[522] = 109.6671327,
[523] = 109.7721276,
[524] = 109.8770222,
[525] = 109.9818167,
[526] = 110.0865114,
[527] = 110.1911067,
[528] = 110.2956028,
[529] = 110.4,
[530] = 110.5042986,
[531] = 110.6084988,
[532] = 110.7126009,
[533] = 110.8166053,
[534] = 110.9205121,
[535] = 111.0243217,
[536] = 111.1280343,
[537] = 111.2316502,
[538] = 111.3351696,
[539] = 111.438593,
[540] = 111.5419204,
[541] = 111.6451522,
[542] = 111.7482886,
[543] = 111.8513299,
[544] = 111.9542764,
[545] = 112.0571283,
[546] = 112.1598859,
[547] = 112.2625494,
[548] = 112.3651191,
[549] = 112.4675953,
[550] = 112.5699782,
[551] = 112.6722681,
[552] = 112.7744652,
[553] = 112.8765698,
[554] = 112.978582,
[555] = 113.0805023,
[556] = 113.1823308,
[557] = 113.2840677,
[558] = 113.3857134,
[559] = 113.487268,
[560] = 113.5887318,
[561] = 113.6901051,
[562] = 113.7913881,
[563] = 113.892581,
[564] = 113.993684,
[565] = 114.0946975,
[566] = 114.1956216,
[567] = 114.2964566,
[568] = 114.3972028,
[569] = 114.4978602,
[570] = 114.5984293,
[571] = 114.6989102,
[572] = 114.7993031,
[573] = 114.8996084,
[574] = 114.9998261,
[575] = 115.0999566,
[576] = 115.2,
[577] = 115.2999566,
[578] = 115.3998267,
[579] = 115.4996104,
[580] = 115.599308,
[581] = 115.6989196,
[582] = 115.7984456,
[583] = 115.8978861,
[584] = 115.9972413,
[585] = 116.0965116,
[586] = 116.195697,
[587] = 116.2947978,
[588] = 116.3938143,
[589] = 116.4927466,
[590] = 116.5915949,
[591] = 116.6903595,
[592] = 116.7890406,
[593] = 116.8876384,
[594] = 116.986153,
[595] = 117.0845848,
[596] = 117.1829339,
[597] = 117.2812005,
[598] = 117.3793849,
[599] = 117.4774872,
[600] = 117.5755077,
[601] = 117.6734465,
[602] = 117.7713038,
[603] = 117.8690799,
[604] = 117.966775,
[605] = 118.0643892,
[606] = 118.1619228,
[607] = 118.2593759,
[608] = 118.3567489,
[609] = 118.4540417,
[610] = 118.5512547,
[611] = 118.6483881,
[612] = 118.745442,
[613] = 118.8424167,
[614] = 118.9393123,
[615] = 119.036129,
[616] = 119.132867,
[617] = 119.2295265,
[618] = 119.3261078,
[619] = 119.4226109,
[620] = 119.5190361,
[621] = 119.6153836,
[622] = 119.7116536,
[623] = 119.8078462,
[624] = 119.9039616,
[625] = 120,
[626] = 120.0959616,
[627] = 120.1918466,
[628] = 120.2876552,
[629] = 120.3833876,
[630] = 120.4790438,
[631] = 120.5746242,
[632] = 120.6701289,
[633] = 120.765558,
[634] = 120.8609118,
[635] = 120.9561904,
[636] = 121.051394,
[637] = 121.1465229,
[638] = 121.241577,
[639] = 121.3365567,
[640] = 121.4314622,
[641] = 121.5262935,
[642] = 121.6210508,
[643] = 121.7157344,
[644] = 121.8103444,
[645] = 121.904881,
[646] = 121.9993443,
[647] = 122.0937345,
[648] = 122.1880518,
[649] = 122.2822963,
[650] = 122.3764683,
[651] = 122.4705679,
[652] = 122.5645952,
[653] = 122.6585505,
[654] = 122.7524338,
[655] = 122.8462454,
[656] = 122.9399854,
[657] = 123.0336539,
[658] = 123.1272512,
[659] = 123.2207775,
[660] = 123.3142328,
[661] = 123.4076173,
[662] = 123.5009312,
[663] = 123.5941746,
[664] = 123.6873478,
[665] = 123.7804508,
[666] = 123.8734838,
[667] = 123.9664471,
[668] = 124.0593406,
[669] = 124.1521647,
[670] = 124.2449194,
[671] = 124.3376049,
[672] = 124.4302214,
[673] = 124.522769,
[674] = 124.6152479,
[675] = 124.7076581,
[676] = 124.8,
[677] = 124.8922736,
[678] = 124.984479,
[679] = 125.0766165,
[680] = 125.1686862,
[681] = 125.2606882,
[682] = 125.3526226,
[683] = 125.4444897,
[684] = 125.5362896,
[685] = 125.6280224,
[686] = 125.7196882,
[687] = 125.8112873,
[688] = 125.9028197,
[689] = 125.9942856,
[690] = 126.0856852,
[691] = 126.1770185,
[692] = 126.2682858,
[693] = 126.3594872,
[694] = 126.4506228,
[695] = 126.5416927,
[696] = 126.6326972,
[697] = 126.7236363,
[698] = 126.8145102,
[699] = 126.905319,
[700] = 126.9960629,
[701] = 127.086742,
[702] = 127.1773565,
[703] = 127.2679064,
[704] = 127.3583919,
[705] = 127.4488133,
[706] = 127.5391705,
[707] = 127.6294637,
[708] = 127.7196931,
[709] = 127.8098588,
[710] = 127.8999609,
[711] = 127.9899996,
[712] = 128.079975,
[713] = 128.1698873,
[714] = 128.2597365,
[715] = 128.3495228,
[716] = 128.4392463,
[717] = 128.5289073,
[718] = 128.6185057,
[719] = 128.7080417,
[720] = 128.7975155,
[721] = 128.8869272,
[722] = 128.9762769,
[723] = 129.0655647,
[724] = 129.1547909,
[725] = 129.2439554,
[726] = 129.3330584,
[727] = 129.4221001,
[728] = 129.5110806,
[729] = 129.6,
[730] = 129.6888584,
[731] = 129.777656,
[732] = 129.8663929,
[733] = 129.9550692,
[734] = 130.043685,
[735] = 130.1322404,
[736] = 130.2207357,
[737] = 130.3091708,
[738] = 130.397546,
[739] = 130.4858613,
[740] = 130.5741169,
[741] = 130.6623129,
[742] = 130.7504493,
[743] = 130.8385264,
[744] = 130.9265443,
[745] = 131.014503,
[746] = 131.1024027,
[747] = 131.1902435,
[748] = 131.2780256,
[749] = 131.365749,
[750] = 131.4534138,
[751] = 131.5410202,
[752] = 131.6285683,
[753] = 131.7160582,
[754] = 131.8034901,
[755] = 131.890864,
[756] = 131.97818,
[757] = 132.0654383,
[758] = 132.152639,
[759] = 132.2397822,
[760] = 132.326868,
[761] = 132.4138966,
[762] = 132.5008679,
[763] = 132.5877822,
[764] = 132.6746396,
[765] = 132.7614402,
[766] = 132.848184,
[767] = 132.9348713,
[768] = 133.021502,
[769] = 133.1080764,
[770] = 133.1945945,
[771] = 133.2810564,
[772] = 133.3674623,
[773] = 133.4538122,
[774] = 133.5401063,
[775] = 133.6263447,
[776] = 133.7125275,
[777] = 133.7986547,
[778] = 133.8847265,
[779] = 133.9707431,
[780] = 134.0567044,
[781] = 134.1426107,
[782] = 134.228462,
[783] = 134.3142584,
[784] = 134.4,
[785] = 134.485687,
[786] = 134.5713194,
[787] = 134.6568973,
[788] = 134.7424209,
[789] = 134.8278903,
[790] = 134.9133055,
[791] = 134.9986667,
[792] = 135.0839739,
[793] = 135.1692273,
[794] = 135.2544269,
[795] = 135.3395729,
[796] = 135.4246654,
[797] = 135.5097044,
[798] = 135.5946902,
[799] = 135.6796226,
[800] = 135.764502,
[801] = 135.8493283,
[802] = 135.9341017,
[803] = 136.0188222,
[804] = 136.10349,
[805] = 136.1881052,
[806] = 136.2726678,
[807] = 136.357178,
[808] = 136.4416359,
[809] = 136.5260415,
[810] = 136.6103949,
[811] = 136.6946963,
[812] = 136.7789457,
[813] = 136.8631433,
[814] = 136.9472891,
[815] = 137.0313833,
[816] = 137.1154258,
[817] = 137.1994169,
[818] = 137.2833566,
[819] = 137.367245,
[820] = 137.4510822,
[821] = 137.5348683,
[822] = 137.6186034,
[823] = 137.7022876,
[824] = 137.7859209,
[825] = 137.8695035,
[826] = 137.9530355,
[827] = 138.0365169,
[828] = 138.1199479,
[829] = 138.2033285,
[830] = 138.2866588,
[831] = 138.3699389,
[832] = 138.453169,
[833] = 138.536349,
[834] = 138.6194792,
[835] = 138.7025595,
[836] = 138.78559,
[837] = 138.868571,
[838] = 138.9515023,
[839] = 139.0343842,
[840] = 139.1172168,
[841] = 139.2,
[842] = 139.282734,
[843] = 139.365419,
[844] = 139.4480548,
[845] = 139.5306418,
[846] = 139.6131799,
[847] = 139.6956692,
[848] = 139.7781099,
[849] = 139.8605019,
[850] = 139.9428455,
[851] = 140.0251406,
[852] = 140.1073874,
[853] = 140.1895859,
[854] = 140.2717363,
[855] = 140.3538386,
[856] = 140.4358928,
[857] = 140.5178992,
[858] = 140.5998578,
[859] = 140.6817685,
[860] = 140.7636317,
[861] = 140.8454472,
[862] = 140.9272153,
[863] = 141.0089359,
[864] = 141.0906092,
[865] = 141.1722352,
[866] = 141.2538141,
[867] = 141.3353459,
[868] = 141.4168307,
[869] = 141.4982685,
[870] = 141.5796596,
[871] = 141.6610038,
[872] = 141.7423014,
[873] = 141.8235523,
[874] = 141.9047568,
[875] = 141.9859148,
[876] = 142.0670264,
[877] = 142.1480918,
[878] = 142.2291109,
[879] = 142.310084,
[880] = 142.391011,
[881] = 142.471892,
[882] = 142.5527271,
[883] = 142.6335164,
[884] = 142.71426,
[885] = 142.7949579,
[886] = 142.8756102,
[887] = 142.9562171,
[888] = 143.0367785,
[889] = 143.1172946,
[890] = 143.1977653,
[891] = 143.2781909,
[892] = 143.3585714,
[893] = 143.4389069,
[894] = 143.5191973,
[895] = 143.5994429,
[896] = 143.6796437,
[897] = 143.7597997,
[898] = 143.839911,
[899] = 143.9199778,
[900] = 144,
[901] = 144.0799778,
[902] = 144.1599112,
[903] = 144.2398003,
[904] = 144.3196452,
[905] = 144.399446,
[906] = 144.4792027,
[907] = 144.5589153,
[908] = 144.6385841,
[909] = 144.7182089,
[910] = 144.79779,
[911] = 144.8773274,
[912] = 144.9568212,
[913] = 145.0362713,
[914] = 145.115678,
[915] = 145.1950412,
[916] = 145.2743611,
[917] = 145.3536377,
[918] = 145.4328711,
[919] = 145.5120614,
[920] = 145.5912085,
[921] = 145.6703127,
[922] = 145.7493739,
[923] = 145.8283923,
[924] = 145.9073679,
[925] = 145.9863007,
[926] = 146.0651909,
[927] = 146.1440385,
[928] = 146.2228436,
[929] = 146.3016063,
[930] = 146.3803265,
[931] = 146.4590045,
[932] = 146.5376402,
[933] = 146.6162338,
[934] = 146.6947852,
[935] = 146.7732946,
[936] = 146.851762,
[937] = 146.9301875,
[938] = 147.0085712,
[939] = 147.0869131,
[940] = 147.1652133,
[941] = 147.2434718,
[942] = 147.3216888,
[943] = 147.3998643,
[944] = 147.4779984,
[945] = 147.556091,
[946] = 147.6341424,
[947] = 147.7121525,
[948] = 147.7901215,
[949] = 147.8680493,
[950] = 147.9459361,
[951] = 148.0237819,
[952] = 148.1015868,
[953] = 148.1793508,
[954] = 148.257074,
[955] = 148.3347565,
[956] = 148.4123984,
[957] = 148.4899997,
[958] = 148.5675604,
[959] = 148.6450806,
[960] = 148.7225605,
[961] = 148.8,
[962] = 148.8773992,
[963] = 148.9547582,
[964] = 149.0320771,
[965] = 149.1093558,
[966] = 149.1865946,
[967] = 149.2637933,
[968] = 149.3409522,
[969] = 149.4180712,
[970] = 149.4951504,
[971] = 149.5721899,
[972] = 149.6491898,
[973] = 149.72615,
[974] = 149.8030707,
[975] = 149.879952,
[976] = 149.9567938,
[977] = 150.0335962,
[978] = 150.1103594,
[979] = 150.1870833,
[980] = 150.2637681,
[981] = 150.3404137,
[982] = 150.4170203,
[983] = 150.4935879,
[984] = 150.5701166,
[985] = 150.6466063,
[986] = 150.7230573,
[987] = 150.7994695,
[988] = 150.875843,
[989] = 150.9521779,
[990] = 151.0284741,
[991] = 151.1047319,
[992] = 151.1809512,
[993] = 151.2571321,
[994] = 151.3332746,
[995] = 151.4093788,
[996] = 151.4854448,
[997] = 151.5614727,
[998] = 151.6374624,
[999] = 151.713414,
[1000] = 151.7893277,
};
local true_idx = (target_distance - accum_distance);
if (true_idx <= 0)
{
return 15.0;
}
else if (true_idx > 1000)
{
return brake_pattern_table[1000];
}
else
{
return brake_pattern_table[true_idx.tointeger()];
}
}
function lookup_incoming_pattern(limit_speed, accum_distance, target_distance, offset_distance)
{
local incoming_pattern_table =
{
[0] = 5.0,
[1] = 5.0,
[2] = 5.0,
[3] = 5.0,
[4] = 5.0,
[5] = 5.305338422,
[6] = 6.288932633,
[7] = 7.19344086,
[8] = 8.035336589,
[9] = 8.826062346,
[10] = 9.573949362,
[11] = 10.28528704,
[12] = 10.96496163,
[13] = 11.61685891,
[14] = 12.24412944,
[15] = 12.84936974,
[16] = 13.43474979,
[17] = 14.00210515,
[18] = 14.55300488,
[19] = 15.08880285,
[20] = 15.61067684,
[21] = 16.11965909,
[22] = 16.61666024,
[23] = 17.10248855,
[24] = 17.57786527,
[25] = 18.04343724,
[26] = 18.49978723,
[27] = 18.94744245,
[28] = 19.38688172,
[29] = 19.81854146,
[30] = 20.24282076,
[31] = 20.66008574,
[32] = 21.07067318,
[33] = 21.47489377,
[34] = 21.87303481,
[35] = 22.26536264,
[36] = 22.65212469,
[37] = 23.03355133,
[38] = 23.40985744,
[39] = 23.78124389,
[40] = 24.14789872,
[41] = 24.50999831,
[42] = 24.86770832,
[43] = 25.22118462,
[44] = 25.57057409,
[45] = 25.91601527,
[46] = 26.25763907,
[47] = 26.59556931,
[48] = 26.92992327,
[49] = 27.26081214,
[50] = 27.58834147,
[51] = 27.91261156,
[52] = 28.23371782,
[53] = 28.55175107,
[54] = 28.8667979,
[55] = 29.17894088,
[56] = 29.48825887,
[57] = 29.7948272,
[58] = 30.09871793,
[59] = 30.4,
[60] = 30.69873947,
[61] = 30.99499965,
[62] = 31.28884126,
[63] = 31.58032258,
[64] = 31.86949959,
[65] = 32.15642609,
[66] = 32.44115383,
[67] = 32.72373258,
[68] = 33.00421029,
[69] = 33.28263314,
[70] = 33.55904563,
[71] = 33.8334907,
[72] = 34.10600977,
[73] = 34.37664282,
[74] = 34.64542849,
[75] = 34.91240409,
[76] = 35.1776057,
[77] = 35.44106824,
[78] = 35.70282545,
[79] = 35.96291005,
[80] = 36.22135369,
[81] = 36.47818704,
[82] = 36.73343983,
[83] = 36.98714089,
[84] = 37.23931818,
[85] = 37.48999882,
[86] = 37.73920916,
[87] = 37.98697477,
[88] = 38.23332048,
[89] = 38.47827043,
[90] = 38.72184809,
[91] = 38.96407624,
[92] = 39.2049771,
[93] = 39.44457222,
[94] = 39.68288263,
[95] = 39.91992876,
[96] = 40.15573053,
[97] = 40.39030734,
[98] = 40.62367806,
[99] = 40.85586113,
[100] = 41.08687449,
[101] = 41.31673564,
[102] = 41.54546165,
[103] = 41.77306917,
[104] = 41.99957447,
[105] = 42.22499338,
[106] = 42.44934141,
[107] = 42.67263366,
[108] = 42.8948849,
[109] = 43.11610957,
[110] = 43.33632175,
[111] = 43.55553521,
[112] = 43.77376344,
[113] = 43.99101959,
[114] = 44.20731653,
[115] = 44.42266686,
[116] = 44.63708291,
[117] = 44.85057673,
[118] = 45.06316011,
[119] = 45.2748446,
[120] = 45.48564152,
[121] = 45.69556194,
[122] = 45.90461669,
[123] = 46.1128164,
[124] = 46.32017147,
[125] = 46.52669211,
[126] = 46.73238831,
[127] = 46.93726986,
[128] = 47.14134636,
[129] = 47.34462723,
[130] = 47.54712171,
[131] = 47.74883885,
[132] = 47.94978753,
[133] = 48.14997648,
[134] = 48.34941424,
[135] = 48.54810921,
[136] = 48.74606962,
[137] = 48.94330357,
[138] = 49.13981899,
[139] = 49.33562367,
[140] = 49.53072528,
[141] = 49.72513134,
[142] = 49.91884922,
[143] = 50.1118862,
[144] = 50.30424938,
[145] = 50.4959458,
[146] = 50.68698232,
[147] = 50.87736572,
[148] = 51.06710265,
[149] = 51.25619966,
[150] = 51.44466317,
[151] = 51.6324995,
[152] = 51.81971489,
[153] = 52.00631544,
[154] = 52.19230718,
[155] = 52.37769602,
[156] = 52.56248779,
[157] = 52.74668822,
[158] = 52.93030295,
[159] = 53.11333754,
[160] = 53.29579745,
[161] = 53.47768805,
[162] = 53.65901465,
[163] = 53.83978246,
[164] = 54.01999661,
[165] = 54.19966216,
[166] = 54.37878409,
[167] = 54.5573673,
[168] = 54.73541663,
[169] = 54.91293683,
[170] = 55.0899326,
[171] = 55.26640855,
[172] = 55.44236925,
[173] = 55.61781916,
[174] = 55.79276273,
[175] = 55.9672043,
[176] = 56.14114817,
[177] = 56.31459859,
[178] = 56.48755972,
[179] = 56.66003568,
[180] = 56.83203053,
[181] = 57.00354829,
[182] = 57.17459288,
[183] = 57.34516822,
[184] = 57.51527813,
[185] = 57.68492642,
[186] = 57.85411681,
[187] = 58.022853,
[188] = 58.19113862,
[189] = 58.35897726,
[190] = 58.52637248,
[191] = 58.69332775,
[192] = 58.85984654,
[193] = 59.02593225,
[194] = 59.19158823,
[195] = 59.35681782,
[196] = 59.52162428,
[197] = 59.68601085,
[198] = 59.84998072,
[199] = 60.01353705,
[200] = 60.17668295,
[201] = 60.33942149,
[202] = 60.5017557,
[203] = 60.6636886,
[204] = 60.82522313,
[205] = 60.98636223,
[206] = 61.14710878,
[207] = 61.30746564,
[208] = 61.46743564,
[209] = 61.62702155,
[210] = 61.78622612,
[211] = 61.94505209,
[212] = 62.10350214,
[213] = 62.26157893,
[214] = 62.41928507,
[215] = 62.57662318,
[216] = 62.7335958,
[217] = 62.89020548,
[218] = 63.04645472,
[219] = 63.202346,
[220] = 63.35788177,
[221] = 63.51306445,
[222] = 63.66789643,
[223] = 63.82238008,
[224] = 63.97651774,
[225] = 64.13031173,
[226] = 64.28376433,
[227] = 64.43687781,
[228] = 64.5896544,
[229] = 64.74209633,
[230] = 64.89420577,
[231] = 65.0459849,
[232] = 65.19743585,
[233] = 65.34856075,
[234] = 65.4993617,
[235] = 65.64984076,
[236] = 65.8,
[237] = 65.94984144,
[238] = 66.09936709,
[239] = 66.24857893,
[240] = 66.39747895,
[241] = 66.54606907,
[242] = 66.69435124,
[243] = 66.84232736,
[244] = 66.98999931,
[245] = 67.13736896,
[246] = 67.28443816,
[247] = 67.43120874,
[248] = 67.57768252,
[249] = 67.72386128,
[250] = 67.86974681,
[251] = 68.01534085,
[252] = 68.16064516,
[253] = 68.30566145,
[254] = 68.45039142,
[255] = 68.59483678,
[256] = 68.73899918,
[257] = 68.88288029,
[258] = 69.02648175,
[259] = 69.16980518,
[260] = 69.31285219,
[261] = 69.45562437,
[262] = 69.5981233,
[263] = 69.74035055,
[264] = 69.88230766,
[265] = 70.02399616,
[266] = 70.16541758,
[267] = 70.30657342,
[268] = 70.44746517,
[269] = 70.5880943,
[270] = 70.72846228,
[271] = 70.86857057,
[272] = 71.00842059,
[273] = 71.14801376,
[274] = 71.28735151,
[275] = 71.42643522,
[276] = 71.56526628,
[277] = 71.70384606,
[278] = 71.84217592,
[279] = 71.98025721,
[280] = 72.11809126,
[281] = 72.2556794,
[282] = 72.39302294,
[283] = 72.53012318,
[284] = 72.6669814,
[285] = 72.80359889,
[286] = 72.93997691,
[287] = 73.07611671,
[288] = 73.21201954,
[289] = 73.34768663,
[290] = 73.4831192,
[291] = 73.61831848,
[292] = 73.75328565,
[293] = 73.8880219,
[294] = 74.02252843,
[295] = 74.1568064,
[296] = 74.29085698,
[297] = 74.4246813,
[298] = 74.55828052,
[299] = 74.69165577,
[300] = 74.82480817,
[301] = 74.95773884,
[302] = 75.09044887,
[303] = 75.22293936,
[304] = 75.35521141,
[305] = 75.48726607,
[306] = 75.61910444,
[307] = 75.75072755,
[308] = 75.88213647,
[309] = 76.01333224,
[310] = 76.14431588,
[311] = 76.27508843,
[312] = 76.40565091,
[313] = 76.53600432,
[314] = 76.66614966,
[315] = 76.79608793,
[316] = 76.92582011,
[317] = 77.05534717,
[318] = 77.1846701,
[319] = 77.31378985,
[320] = 77.44270738,
[321] = 77.57142363,
[322] = 77.69993954,
[323] = 77.82825605,
[324] = 77.95637408,
[325] = 78.08429454,
[326] = 78.21201836,
[327] = 78.33954644,
[328] = 78.46687966,
[329] = 78.59401892,
[330] = 78.72096512,
[331] = 78.84771911,
[332] = 78.97428178,
[333] = 79.10065398,
[334] = 79.22683658,
[335] = 79.35283042,
[336] = 79.47863635,
[337] = 79.60425521,
[338] = 79.72968783,
[339] = 79.85493504,
[340] = 79.97999765,
[341] = 80.10487648,
[342] = 80.22957233,
[343] = 80.35408602,
[344] = 80.47841833,
[345] = 80.60257005,
[346] = 80.72654198,
[347] = 80.85033489,
[348] = 80.97394954,
[349] = 81.09738672,
[350] = 81.22064718,
[351] = 81.34373168,
[352] = 81.46664097,
[353] = 81.58937579,
[354] = 81.71193689,
[355] = 81.83432501,
[356] = 81.95654087,
[357] = 82.0785852,
[358] = 82.20045871,
[359] = 82.32216214,
[360] = 82.44369617,
[361] = 82.56506153,
[362] = 82.6862589,
[363] = 82.80728899,
[364] = 82.92815249,
[365] = 83.04885008,
[366] = 83.16938244,
[367] = 83.28975025,
[368] = 83.40995419,
[369] = 83.52999492,
[370] = 83.6498731,
[371] = 83.76958939,
[372] = 83.88914444,
[373] = 84.00853892,
[374] = 84.12777345,
[375] = 84.24684868,
[376] = 84.36576526,
[377] = 84.4845238,
[378] = 84.60312495,
[379] = 84.72156931,
[380] = 84.83985752,
[381] = 84.9579902,
[382] = 85.07596794,
[383] = 85.19379136,
[384] = 85.31146107,
[385] = 85.42897766,
[386] = 85.54634173,
[387] = 85.66355387,
[388] = 85.78061467,
[389] = 85.89752472,
[390] = 86.01428459,
[391] = 86.13089487,
[392] = 86.24735613,
[393] = 86.36366893,
[394] = 86.47983384,
[395] = 86.59585143,
[396] = 86.71172226,
[397] = 86.82744688,
[398] = 86.94302584,
[399] = 87.05845969,
[400] = 87.17374897,
[401] = 87.28889424,
[402] = 87.40389602,
[403] = 87.51875486,
[404] = 87.63347127,
[405] = 87.7480458,
[406] = 87.86247897,
[407] = 87.97677129,
[408] = 88.0909233,
[409] = 88.20493549,
[410] = 88.31880839,
[411] = 88.43254251,
[412] = 88.54613835,
[413] = 88.65959641,
[414] = 88.7729172,
[415] = 88.88610121,
[416] = 88.99914893,
[417] = 89.11206086,
[418] = 89.22483749,
[419] = 89.3374793,
[420] = 89.44998677,
[421] = 89.56236038,
[422] = 89.67460061,
[423] = 89.78670793,
[424] = 89.89868281,
[425] = 90.01052573,
[426] = 90.12223715,
[427] = 90.23381752,
[428] = 90.34526732,
[429] = 90.45658699,
[430] = 90.567777,
[431] = 90.67883779,
[432] = 90.78976981,
[433] = 90.90057351,
[434] = 91.01124934,
[435] = 91.12179774,
[436] = 91.23221914,
[437] = 91.34251398,
[438] = 91.4526827,
[439] = 91.56272573,
[440] = 91.67264349,
[441] = 91.78243642,
[442] = 91.89210494,
[443] = 92.00164947,
[444] = 92.11107043,
[445] = 92.22036824,
[446] = 92.32954331,
[447] = 92.43859605,
[448] = 92.54752688,
[449] = 92.6563362,
[450] = 92.76502442,
[451] = 92.87359194,
[452] = 92.98203917,
[453] = 93.0903665,
[454] = 93.19857433,
[455] = 93.30666305,
[456] = 93.41463306,
[457] = 93.52248474,
[458] = 93.63021849,
[459] = 93.73783469,
[460] = 93.84533373,
[461] = 93.95271598,
[462] = 94.05998183,
[463] = 94.16713165,
[464] = 94.27416582,
[465] = 94.38108472,
[466] = 94.48788871,
[467] = 94.59457817,
[468] = 94.70115345,
[469] = 94.80761494,
[470] = 94.91396299,
[471] = 95.02019796,
[472] = 95.12632022,
[473] = 95.23233011,
[474] = 95.33822801,
[475] = 95.44401426,
[476] = 95.54968921,
[477] = 95.65525322,
[478] = 95.76070663,
[479] = 95.86604979,
[480] = 95.97128305,
[481] = 96.07640674,
[482] = 96.18142122,
[483] = 96.28632682,
[484] = 96.39112387,
[485] = 96.49581272,
[486] = 96.6003937,
[487] = 96.70486714,
[488] = 96.80923337,
[489] = 96.91349273,
[490] = 97.01764553,
[491] = 97.12169211,
[492] = 97.22563279,
[493] = 97.3294679,
[494] = 97.43319774,
[495] = 97.53682265,
[496] = 97.64034295,
[497] = 97.74375893,
[498] = 97.84707094,
[499] = 97.95027926,
[500] = 98.05338422,
[501] = 98.15638613,
[502] = 98.2592853,
[503] = 98.36208202,
[504] = 98.46477662,
[505] = 98.56736938,
[506] = 98.66986062,
[507] = 98.77225063,
[508] = 98.87453971,
[509] = 98.97672817,
[510] = 99.07881629,
[511] = 99.18080437,
[512] = 99.28269272,
[513] = 99.38448161,
[514] = 99.48617133,
[515] = 99.58776219,
[516] = 99.68925446,
[517] = 99.79064844,
[518] = 99.8919444,
[519] = 99.99314263,
[520] = 100.0942434,
[521] = 100.195247,
[522] = 100.2961538,
[523] = 100.3969639,
[524] = 100.4976777,
[525] = 100.5982954,
[526] = 100.6988174,
[527] = 100.7992439,
[528] = 100.8995751,
[529] = 100.9998113,
[530] = 101.0999529,
[531] = 101.2,
[532] = 101.299953,
[533] = 101.399812,
[534] = 101.4995775,
[535] = 101.5992495,
[536] = 101.6988285,
[537] = 101.7983146,
[538] = 101.8977081,
[539] = 101.9970093,
[540] = 102.0962184,
[541] = 102.1953357,
[542] = 102.2943615,
[543] = 102.3932959,
[544] = 102.4921392,
[545] = 102.5908918,
[546] = 102.6895538,
[547] = 102.7881255,
[548] = 102.8866071,
[549] = 102.984999,
[550] = 103.0833012,
[551] = 103.1815141,
[552] = 103.279638,
[553] = 103.377673,
[554] = 103.4756194,
[555] = 103.5734774,
[556] = 103.6712473,
[557] = 103.7689294,
[558] = 103.8665238,
[559] = 103.9640308,
[560] = 104.0614506,
[561] = 104.1587834,
[562] = 104.2560296,
[563] = 104.3531893,
[564] = 104.4502627,
[565] = 104.5472501,
[566] = 104.6441517,
[567] = 104.7409677,
[568] = 104.8376984,
[569] = 104.934344,
[570] = 105.0309047,
[571] = 105.1273808,
[572] = 105.2237724,
[573] = 105.3200798,
[574] = 105.4163031,
[575] = 105.5124427,
[576] = 105.6084988,
[577] = 105.7044715,
[578] = 105.800361,
[579] = 105.8961677,
[580] = 105.9918916,
[581] = 106.0875331,
[582] = 106.1830922,
[583] = 106.2785694,
[584] = 106.3739646,
[585] = 106.4692783,
[586] = 106.5645105,
[587] = 106.6596615,
[588] = 106.7547314,
[589] = 106.8497206,
[590] = 106.9446292,
[591] = 107.0394573,
[592] = 107.1342053,
[593] = 107.2288733,
[594] = 107.3234615,
[595] = 107.4179701,
[596] = 107.5123993,
[597] = 107.6067494,
[598] = 107.7010204,
[599] = 107.7952127,
[600] = 107.8893263,
[601] = 107.9833616,
[602] = 108.0773187,
[603] = 108.1711977,
[604] = 108.264999,
[605] = 108.3587226,
[606] = 108.4523689,
[607] = 108.5459378,
[608] = 108.6394298,
[609] = 108.7328449,
[610] = 108.8261833,
[611] = 108.9194452,
[612] = 109.0126309,
[613] = 109.1057404,
[614] = 109.1987741,
[615] = 109.291732,
[616] = 109.3846144,
[617] = 109.4774214,
[618] = 109.5701532,
[619] = 109.66281,
[620] = 109.755392,
[621] = 109.8478994,
[622] = 109.9403323,
[623] = 110.032691,
[624] = 110.1249756,
[625] = 110.2171862,
[626] = 110.3093231,
[627] = 110.4013865,
[628] = 110.4933764,
[629] = 110.5852932,
[630] = 110.6771369,
[631] = 110.7689077,
[632] = 110.8606059,
[633] = 110.9522315,
[634] = 111.0437848,
[635] = 111.135266,
[636] = 111.2266751,
[637] = 111.3180124,
[638] = 111.409278,
[639] = 111.5004721,
[640] = 111.5915949,
[641] = 111.6826465,
[642] = 111.7736272,
[643] = 111.864537,
[644] = 111.9553761,
[645] = 112.0461447,
[646] = 112.1368431,
[647] = 112.2274712,
[648] = 112.3180293,
[649] = 112.4085176,
[650] = 112.4989362,
[651] = 112.5892852,
[652] = 112.6795649,
[653] = 112.7697754,
[654] = 112.8599169,
[655] = 112.9499894,
[656] = 113.0399932,
[657] = 113.1299285,
[658] = 113.2197953,
[659] = 113.3095939,
[660] = 113.3993243,
[661] = 113.4889868,
[662] = 113.5785815,
[663] = 113.6681086,
[664] = 113.7575682,
[665] = 113.8469604,
[666] = 113.9362855,
[667] = 114.0255435,
[668] = 114.1147346,
[669] = 114.203859,
[670] = 114.2929168,
[671] = 114.3819082,
[672] = 114.4708333,
[673] = 114.5596922,
[674] = 114.6484852,
[675] = 114.7372123,
[676] = 114.8258737,
[677] = 114.9144695,
[678] = 115.003,
[679] = 115.0914651,
[680] = 115.1798652,
[681] = 115.2682003,
[682] = 115.3564705,
[683] = 115.4446761,
[684] = 115.5328171,
[685] = 115.6208937,
[686] = 115.7089061,
[687] = 115.7968543,
[688] = 115.8847385,
[689] = 115.9725589,
[690] = 116.0603155,
[691] = 116.1480087,
[692] = 116.2356383,
[693] = 116.3232047,
[694] = 116.4107079,
[695] = 116.4981481,
[696] = 116.5855255,
[697] = 116.67284,
[698] = 116.760092,
[699] = 116.8472815,
[700] = 116.9344086,
[701] = 117.0214735,
[702] = 117.1084764,
[703] = 117.1954173,
[704] = 117.2822963,
[705] = 117.3691138,
[706] = 117.4558696,
[707] = 117.542564,
[708] = 117.6291972,
[709] = 117.7157692,
[710] = 117.8022801,
[711] = 117.8887302,
[712] = 117.9751194,
[713] = 118.0614481,
[714] = 118.1477162,
[715] = 118.2339239,
[716] = 118.3200714,
[717] = 118.4061587,
[718] = 118.492186,
[719] = 118.5781534,
[720] = 118.6640611,
[721] = 118.7499091,
[722] = 118.8356976,
[723] = 118.9214267,
[724] = 119.0070966,
[725] = 119.0927073,
[726] = 119.178259,
[727] = 119.2637518,
[728] = 119.3491858,
[729] = 119.4345611,
[730] = 119.5198779,
[731] = 119.6051363,
[732] = 119.6903364,
[733] = 119.7754784,
[734] = 119.8605622,
[735] = 119.9455882,
[736] = 120.0305563,
[737] = 120.1154667,
[738] = 120.2003195,
[739] = 120.2851148,
[740] = 120.3698528,
[741] = 120.4545336,
[742] = 120.5391572,
[743] = 120.6237239,
[744] = 120.7082336,
[745] = 120.7926866,
[746] = 120.8770829,
[747] = 120.9614227,
[748] = 121.045706,
[749] = 121.129933,
[750] = 121.2141038,
[751] = 121.2982185,
[752] = 121.3822772,
[753] = 121.4662801,
[754] = 121.5502272,
[755] = 121.6341186,
[756] = 121.7179545,
[757] = 121.801735,
[758] = 121.8854602,
[759] = 121.9691301,
[760] = 122.052745,
[761] = 122.1363048,
[762] = 122.2198098,
[763] = 122.30326,
[764] = 122.3866555,
[765] = 122.4699965,
[766] = 122.553283,
[767] = 122.6365152,
[768] = 122.7196931,
[769] = 122.8028169,
[770] = 122.8858866,
[771] = 122.9689025,
[772] = 123.0518645,
[773] = 123.1347728,
[774] = 123.2176275,
[775] = 123.3004287,
[776] = 123.3831765,
[777] = 123.465871,
[778] = 123.5485122,
[779] = 123.6311004,
[780] = 123.7136356,
[781] = 123.796118,
[782] = 123.8785475,
[783] = 123.9609243,
[784] = 124.0432486,
[785] = 124.1255203,
[786] = 124.2077397,
[787] = 124.2899068,
[788] = 124.3720217,
[789] = 124.4540845,
[790] = 124.5360954,
[791] = 124.6180543,
[792] = 124.6999614,
[793] = 124.7818169,
[794] = 124.8636208,
[795] = 124.9453731,
[796] = 125.0270741,
[797] = 125.1087238,
[798] = 125.1903222,
[799] = 125.2718696,
[800] = 125.3533659,
[801] = 125.4348113,
[802] = 125.5162059,
[803] = 125.5975497,
[804] = 125.678843,
[805] = 125.7600857,
[806] = 125.8412779,
[807] = 125.9224198,
[808] = 126.0035114,
[809] = 126.0845529,
[810] = 126.1655443,
[811] = 126.2464857,
[812] = 126.3273772,
[813] = 126.4082189,
[814] = 126.4890109,
[815] = 126.5697534,
[816] = 126.6504463,
[817] = 126.7310897,
[818] = 126.8116839,
[819] = 126.8922287,
[820] = 126.9727245,
[821] = 127.0531711,
[822] = 127.1335688,
[823] = 127.2139176,
[824] = 127.2942176,
[825] = 127.3744688,
[826] = 127.4546715,
[827] = 127.5348256,
[828] = 127.6149313,
[829] = 127.6949886,
[830] = 127.7749976,
[831] = 127.8549585,
[832] = 127.9348713,
[833] = 128.014736,
[834] = 128.0945529,
[835] = 128.1743218,
[836] = 128.2540431,
[837] = 128.3337167,
[838] = 128.4133427,
[839] = 128.4929212,
[840] = 128.5724522,
[841] = 128.651936,
[842] = 128.7313725,
[843] = 128.8107619,
[844] = 128.8901042,
[845] = 128.9693995,
[846] = 129.0486479,
[847] = 129.1278495,
[848] = 129.2070043,
[849] = 129.2861125,
[850] = 129.3651741,
[851] = 129.4441892,
[852] = 129.5231579,
[853] = 129.6020802,
[854] = 129.6809563,
[855] = 129.7597863,
[856] = 129.8385701,
[857] = 129.917308,
[858] = 129.9959999,
[859] = 130.074646,
[860] = 130.1532464,
[861] = 130.231801,
[862] = 130.31031,
[863] = 130.3887735,
[864] = 130.4671916,
[865] = 130.5455643,
[866] = 130.6238917,
[867] = 130.7021739,
[868] = 130.780411,
[869] = 130.858603,
[870] = 130.93675,
[871] = 131.0148521,
[872] = 131.0929094,
[873] = 131.170922,
[874] = 131.2488899,
[875] = 131.3268132,
[876] = 131.404692,
[877] = 131.4825264,
[878] = 131.5603163,
[879] = 131.638062,
[880] = 131.7157635,
[881] = 131.7934209,
[882] = 131.8710342,
[883] = 131.9486035,
[884] = 132.0261289,
[885] = 132.1036105,
[886] = 132.1810483,
[887] = 132.2584424,
[888] = 132.3357929,
[889] = 132.4130998,
[890] = 132.4903633,
[891] = 132.5675834,
[892] = 132.6447602,
[893] = 132.7218937,
[894] = 132.798984,
[895] = 132.8760313,
[896] = 132.9530355,
[897] = 133.0299967,
[898] = 133.1069151,
[899] = 133.1837907,
[900] = 133.2606235,
[901] = 133.3374136,
[902] = 133.4141611,
[903] = 133.4908661,
[904] = 133.5675287,
[905] = 133.6441488,
[906] = 133.7207266,
[907] = 133.7972622,
[908] = 133.8737556,
[909] = 133.9502069,
[910] = 134.0266162,
[911] = 134.1029834,
[912] = 134.1793088,
[913] = 134.2555923,
[914] = 134.3318341,
[915] = 134.4080342,
[916] = 134.4841927,
[917] = 134.5603095,
[918] = 134.6363849,
[919] = 134.7124189,
[920] = 134.7884115,
[921] = 134.8643629,
[922] = 134.940273,
[923] = 135.0161419,
[924] = 135.0919698,
[925] = 135.1677566,
[926] = 135.2435025,
[927] = 135.3192075,
[928] = 135.3948717,
[929] = 135.4704951,
[930] = 135.5460779,
[931] = 135.62162,
[932] = 135.6971215,
[933] = 135.7725826,
[934] = 135.8480032,
[935] = 135.9233834,
[936] = 135.9987234,
[937] = 136.0740231,
[938] = 136.1492827,
[939] = 136.2245021,
[940] = 136.2996815,
[941] = 136.374821,
[942] = 136.4499205,
[943] = 136.5249801,
[944] = 136.6,
[945] = 136.6749801,
[946] = 136.7499206,
[947] = 136.8248215,
[948] = 136.8996829,
[949] = 136.9745048,
[950] = 137.0492872,
[951] = 137.1240303,
[952] = 137.1987342,
[953] = 137.2733988,
[954] = 137.3480242,
[955] = 137.4226106,
[956] = 137.4971579,
[957] = 137.5716662,
[958] = 137.6461356,
[959] = 137.7205661,
[960] = 137.7949579,
[961] = 137.8693109,
[962] = 137.9436253,
[963] = 138.017901,
[964] = 138.0921381,
[965] = 138.1663368,
[966] = 138.2404971,
[967] = 138.3146189,
[968] = 138.3887025,
[969] = 138.4627478,
[970] = 138.5367549,
[971] = 138.6107238,
[972] = 138.6846547,
[973] = 138.7585476,
[974] = 138.8324025,
[975] = 138.9062195,
[976] = 138.9799986,
[977] = 139.05374,
[978] = 139.1274436,
[979] = 139.2011096,
[980] = 139.2747379,
[981] = 139.3483287,
[982] = 139.421882,
[983] = 139.4953979,
[984] = 139.5688763,
[985] = 139.6423175,
[986] = 139.7157213,
[987] = 139.789088,
[988] = 139.8624175,
[989] = 139.9357099,
[990] = 140.0089652,
[991] = 140.0821836,
[992] = 140.155365,
[993] = 140.2285096,
[994] = 140.3016173,
[995] = 140.3746883,
[996] = 140.4477226,
[997] = 140.5207202,
[998] = 140.5936812,
[999] = 140.6666056,
[1000] = 140.7394936,
}
local true_idx = (target_distance - accum_distance);
if (true_idx <= 0)
{
return 10.0;
}
else if (true_idx > 1000)
{
return incoming_pattern_table[1000];
}
else
{
return incoming_pattern_table[true_idx.tointeger()];
}
}
function self_erase(accum_distance, target_distance)
{
if ((target_distance - accum_distance) <= -50.0)
{
return true;
}
else
{
return false;
}
}
function pattern_type(param)
{
return 0;
}
| 39,067
|
https://github.com/qrvd/discord-unix-bot/blob/master/bin/pick
|
Github Open Source
|
Open Source
|
BSL-1.0
| 2,020
|
discord-unix-bot
|
qrvd
|
Shell
|
Code
| 186
| 532
|
#!/bin/bash
set -ueo pipefail
et="$(cat var/drop/event-type)"
if [ "$et" != 'drop' ] && [ "$et" != 'xpdrop' ]; then
# wrong event
exit 10
elif [ -e var/drop/has-picked ]; then
# already picked
exit 50
elif [ "$SRCID" != "$(cat var/drop/stream)" ]; then
# wrong stream
exit 100
fi
userid="$AUTHORID"
sid="$SRCID"
amt="$(cat var/drop/amount)"
# announce it
if [ "$et" == 'drop' ]; then
printf '**%s** picked the %s!\n' \
"$(sbin/mention "$userid")" "$(sbin/printcash "$amt")" | sbin/say "$sid"
elif [ "$et" == 'xpdrop' ]; then
printf '**%s** earned the **%sXP**!\n' \
"$(sbin/mention "$userid")" "$amt" | sbin/say "$sid"
else
printf 'Unknown drop type %s\n' "$et" 1>&2
exit 1
fi
# disable the drop
touch var/drop/has-picked
# log the event
sbin/event "$userid" PICK
# get the reward
if [ "$et" == 'drop' ]; then
sbin/transfer-balance "$BOTID" "$userid" "$amt"
elif [ "$et" == 'xpdrop' ]; then
# add xp
sbin/modify-xp "$AUTHORID" "$amt"
if sbin/update-level "$AUTHORID"; then
sbin/on-levelup "$lnauth" "$betstream"
fi
else
printf 'Unknown drop type %s\n' "$et" 1>&2
exit 1
fi
if [ "$userid" == "$(cat var/bot/pawn.id)" ]; then
touch var/drop/lucky-picked
fi
# Remove the old message
# sbin/delmsg "$(cat var/drop/drop.message-id)"
| 22,081
|
https://github.com/balena-io/balena-cli/blob/master/tests/test-data/projects/docker-compose/basic/.dockerignore
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
balena-cli
|
balena-io
|
Ignore List
|
Code
| 2
| 15
|
service1/test-ignore*
**/.dockerignore
| 47,893
|
https://github.com/octoblu/nanocyte-component-function/blob/master/test/function-spec.coffee
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
nanocyte-component-function
|
octoblu
|
CoffeeScript
|
Code
| 225
| 696
|
child_process = require 'child_process'
CallbackComponent = require 'nanocyte-component-callback'
Function = require '../src/function'
describe 'Function', ->
beforeEach ->
@envelope = thanks: "ERIK"
@childObject =
on: sinon.stub()
send: sinon.spy()
kill: sinon.spy()
@child_process =
fork: sinon.stub().returns @childObject
@sut = new Function {}, child_process: @child_process
it 'should exist', ->
expect(@sut).to.be.an.instanceOf CallbackComponent
describe '->onEnvelope', ->
describe 'when given an envelope from the engine', ->
beforeEach ->
@sut.onEnvelope @envelope, =>
it "should send the envelope it received to the child", ->
expect(@childObject.send).to.have.been.calledWith @envelope
describe 'when the child responds with a new message', ->
beforeEach (done) ->
@childMessage =
type: 'envelope'
envelope:
message:
youAre: 'WELCOME'
@sut.onEnvelope @envelope, (@error, @message) => done()
@childObject.on.yield type: 'ready'
@childObject.on.yield @childMessage
it 'should call the callback with that message', ->
expect(@message.envelope).to.deep.equal @childMessage.message
it 'should violently kill all the children', ->
expect(@childObject.kill).to.have.been.calledWith 'SIGKILL'
describe 'when the child process takes longer than 100ms', ->
beforeEach (done) ->
@sut.onEnvelope @envelope, (@error, @message) => done()
@childObject.on.yield type: 'ready'
it 'should call the callback with error', ->
expect(@error).to.be.an.instanceof Error
it 'should violently kill all the children', ->
expect(@childObject.kill).to.have.been.calledWith 'SIGKILL'
describe 'when the child process returns, but later throws an error', ->
beforeEach (done) ->
@sut.onEnvelope @envelope, (@error, @message) => done()
@childObject.on.yield type: 'ready'
it 'should call the callback with error', ->
expect(@error).to.be.an.instanceof Error
it 'should violently kill all the children', ->
expect(@childObject.kill).to.have.been.calledWith 'SIGKILL'
# it 'should call the callback with an error'
| 11,952
|
https://github.com/alonisser/knesset-data-pipelines/blob/master/datapackage_pipelines_knesset/common/db.py
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
knesset-data-pipelines
|
alonisser
|
Python
|
Code
| 75
| 306
|
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, MetaData
import os, logging
def get_engine(connection_string=None):
if not connection_string:
connection_string = os.environ["DPP_DB_ENGINE"]
if connection_string.startswith("sqlite:///../"):
relpath = connection_string.replace("sqlite:///../", "")
abspath = os.path.join(os.path.dirname(__file__), "..", "..", relpath)
connection_string = "sqlite:///{}".format(abspath)
return create_engine(connection_string)
def get_session(engine=None, connection_string=None):
if not engine:
engine = get_engine(connection_string)
return sessionmaker(bind=engine)()
def get_connection(session=None, engine=None, connection_string=None):
if not session:
session = get_session(engine, connection_string)
return session.connection()
def get_reflect_metadata(bind=None):
if not bind:
bind = get_connection()
metadata = MetaData(bind=bind)
metadata.reflect()
return metadata
| 20,275
|
https://github.com/uccser/cs-unplugged/blob/master/csunplugged/general/management/__init__.py
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-secret-labs-2011, MIT, OFL-1.1, LGPL-2.0-or-later, AGPL-3.0-only, CC-BY-4.0, Apache-2.0, BSD-3-Clause, CC-BY-SA-4.0, LicenseRef-scancode-public-domain, LicenseRef-scancode-other-copyleft, LicenseRef-scancode-unknown-license-reference
| 2,023
|
cs-unplugged
|
uccser
|
Python
|
Code
| 8
| 12
|
"""Module for the management of the general application."""
| 38,655
|
https://github.com/KristenWegner/sec_mem/blob/master/checksum.h
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
sec_mem
|
KristenWegner
|
C
|
Code
| 226
| 731
|
// checksum.h
#include "config.h"
#ifndef INCLUDE_CHECKSUM_H
#define INCLUDE_CHECKSUM_H 1
#define CRCPOLY 0xEDB88320
#define CRCINIT 0xFFFFFFFF
void sec_crc_initialize(void *restrict s)
{
register uint32_t i, x, j, c;
register uint32_t* p = (uint32_t*)s;
for (i = UINT32_C(0); i <= UINT32_C(0xFF); ++i)
{
x = i;
for (j = 0; j < UINT32_C(8); ++j)
x = (x >> 1) ^ (UINT32_C(0xEDB88320) & (-(int32_t)(x & UINT32_C(1))));
p[(0 * 256) + i] = x;
}
for (i = UINT32_C(0); i <= UINT32_C(0xFF); ++i)
{
c = p[(0 * 256) + i];
for (j = 1; j < UINT32_C(4); ++j)
{
c = p[(0 * 256) + (c & UINT32_C(0xFF))] ^ (c >> 8);
p[(j * 256) + i] = c;
}
}
}
uint32_t sec_crc_compute(const void *restrict s, const uint8_t *restrict v, size_t n)
{
uint32_t r = UINT32_C(0xFFFFFFFF);
uint32_t i = (uint32_t)(n / sizeof(uint32_t));
uint32_t c;
for (; i; i--)
{
r ^= *(uint32_t*)v;
r =
g_crc_precalc[3][(r) & 0xFF] ^
g_crc_precalc[2][(r >> 8) & 0xFF] ^
g_crc_precalc[1][(r >> 16) & 0xFF] ^
g_crc_precalc[0][(r >> 24) & 0xFF];
v += sizeof(uint32_t);
}
if (n & sizeof(uint16_t))
{
c = r ^ *(uint16_t*)v;
r = g_crc_precalc[1][(c) & 0xFF] ^
g_crc_precalc[0][(c >> 8) & 0xFF] ^ (r >> 16);
v += sizeof(uint16_t);
}
if (n & 1)
r = g_crc_precalc[0][(r ^ *v) & 0xFF] ^ (r >> 8);
return ~r;
}
#endif //
| 49,075
|
https://github.com/VEASTARK/jMetal/blob/master/resources/weightVectorFiles/mombi2/weight_05D.sld
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
jMetal
|
VEASTARK
|
Scheme
|
Code
| 1,053
| 7,579
|
# 210 5
1.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00
8.333333e-01 1.666667e-01 0.000000e+00 0.000000e+00 0.000000e+00
8.333333e-01 0.000000e+00 1.666667e-01 0.000000e+00 0.000000e+00
8.333333e-01 0.000000e+00 0.000000e+00 1.666667e-01 0.000000e+00
8.333333e-01 0.000000e+00 0.000000e+00 0.000000e+00 1.666667e-01
6.666667e-01 3.333333e-01 0.000000e+00 0.000000e+00 0.000000e+00
6.666667e-01 1.666667e-01 1.666667e-01 0.000000e+00 0.000000e+00
6.666667e-01 1.666667e-01 0.000000e+00 1.666667e-01 0.000000e+00
6.666667e-01 1.666667e-01 0.000000e+00 0.000000e+00 1.666667e-01
6.666667e-01 0.000000e+00 3.333333e-01 0.000000e+00 0.000000e+00
6.666667e-01 0.000000e+00 1.666667e-01 1.666667e-01 0.000000e+00
6.666667e-01 0.000000e+00 1.666667e-01 0.000000e+00 1.666667e-01
6.666667e-01 0.000000e+00 0.000000e+00 3.333333e-01 0.000000e+00
6.666667e-01 0.000000e+00 0.000000e+00 1.666667e-01 1.666667e-01
6.666667e-01 0.000000e+00 0.000000e+00 0.000000e+00 3.333333e-01
5.000000e-01 5.000000e-01 0.000000e+00 0.000000e+00 0.000000e+00
5.000000e-01 3.333333e-01 1.666667e-01 0.000000e+00 0.000000e+00
5.000000e-01 3.333333e-01 0.000000e+00 1.666667e-01 0.000000e+00
5.000000e-01 3.333333e-01 0.000000e+00 0.000000e+00 1.666667e-01
5.000000e-01 1.666667e-01 3.333333e-01 0.000000e+00 0.000000e+00
5.000000e-01 1.666667e-01 1.666667e-01 1.666667e-01 0.000000e+00
5.000000e-01 1.666667e-01 1.666667e-01 0.000000e+00 1.666667e-01
5.000000e-01 1.666667e-01 0.000000e+00 3.333333e-01 0.000000e+00
5.000000e-01 1.666667e-01 0.000000e+00 1.666667e-01 1.666667e-01
5.000000e-01 1.666667e-01 0.000000e+00 0.000000e+00 3.333333e-01
5.000000e-01 0.000000e+00 5.000000e-01 0.000000e+00 0.000000e+00
5.000000e-01 0.000000e+00 3.333333e-01 1.666667e-01 0.000000e+00
5.000000e-01 0.000000e+00 3.333333e-01 0.000000e+00 1.666667e-01
5.000000e-01 0.000000e+00 1.666667e-01 3.333333e-01 0.000000e+00
5.000000e-01 0.000000e+00 1.666667e-01 1.666667e-01 1.666667e-01
5.000000e-01 0.000000e+00 1.666667e-01 0.000000e+00 3.333333e-01
5.000000e-01 0.000000e+00 0.000000e+00 5.000000e-01 0.000000e+00
5.000000e-01 0.000000e+00 0.000000e+00 3.333333e-01 1.666667e-01
5.000000e-01 0.000000e+00 0.000000e+00 1.666667e-01 3.333333e-01
5.000000e-01 0.000000e+00 0.000000e+00 0.000000e+00 5.000000e-01
3.333333e-01 6.666667e-01 0.000000e+00 0.000000e+00 0.000000e+00
3.333333e-01 5.000000e-01 1.666667e-01 0.000000e+00 0.000000e+00
3.333333e-01 5.000000e-01 0.000000e+00 1.666667e-01 0.000000e+00
3.333333e-01 5.000000e-01 0.000000e+00 0.000000e+00 1.666667e-01
3.333333e-01 3.333333e-01 3.333333e-01 0.000000e+00 0.000000e+00
3.333333e-01 3.333333e-01 1.666667e-01 1.666667e-01 0.000000e+00
3.333333e-01 3.333333e-01 1.666667e-01 0.000000e+00 1.666667e-01
3.333333e-01 3.333333e-01 0.000000e+00 3.333333e-01 0.000000e+00
3.333333e-01 3.333333e-01 0.000000e+00 1.666667e-01 1.666667e-01
3.333333e-01 3.333333e-01 0.000000e+00 0.000000e+00 3.333333e-01
3.333333e-01 1.666667e-01 5.000000e-01 0.000000e+00 0.000000e+00
3.333333e-01 1.666667e-01 3.333333e-01 1.666667e-01 0.000000e+00
3.333333e-01 1.666667e-01 3.333333e-01 0.000000e+00 1.666667e-01
3.333333e-01 1.666667e-01 1.666667e-01 3.333333e-01 0.000000e+00
3.333333e-01 1.666667e-01 1.666667e-01 1.666667e-01 1.666667e-01
3.333333e-01 1.666667e-01 1.666667e-01 0.000000e+00 3.333333e-01
3.333333e-01 1.666667e-01 0.000000e+00 5.000000e-01 0.000000e+00
3.333333e-01 1.666667e-01 0.000000e+00 3.333333e-01 1.666667e-01
3.333333e-01 1.666667e-01 0.000000e+00 1.666667e-01 3.333333e-01
3.333333e-01 1.666667e-01 0.000000e+00 0.000000e+00 5.000000e-01
3.333333e-01 0.000000e+00 6.666667e-01 0.000000e+00 0.000000e+00
3.333333e-01 0.000000e+00 5.000000e-01 1.666667e-01 0.000000e+00
3.333333e-01 0.000000e+00 5.000000e-01 0.000000e+00 1.666667e-01
3.333333e-01 0.000000e+00 3.333333e-01 3.333333e-01 0.000000e+00
3.333333e-01 0.000000e+00 3.333333e-01 1.666667e-01 1.666667e-01
3.333333e-01 0.000000e+00 3.333333e-01 0.000000e+00 3.333333e-01
3.333333e-01 0.000000e+00 1.666667e-01 5.000000e-01 0.000000e+00
3.333333e-01 0.000000e+00 1.666667e-01 3.333333e-01 1.666667e-01
3.333333e-01 0.000000e+00 1.666667e-01 1.666667e-01 3.333333e-01
3.333333e-01 0.000000e+00 1.666667e-01 0.000000e+00 5.000000e-01
3.333333e-01 0.000000e+00 0.000000e+00 6.666667e-01 0.000000e+00
3.333333e-01 0.000000e+00 0.000000e+00 5.000000e-01 1.666667e-01
3.333333e-01 0.000000e+00 0.000000e+00 3.333333e-01 3.333333e-01
3.333333e-01 0.000000e+00 0.000000e+00 1.666667e-01 5.000000e-01
3.333333e-01 0.000000e+00 0.000000e+00 0.000000e+00 6.666667e-01
1.666667e-01 8.333333e-01 0.000000e+00 0.000000e+00 0.000000e+00
1.666667e-01 6.666667e-01 1.666667e-01 0.000000e+00 0.000000e+00
1.666667e-01 6.666667e-01 0.000000e+00 1.666667e-01 0.000000e+00
1.666667e-01 6.666667e-01 0.000000e+00 0.000000e+00 1.666667e-01
1.666667e-01 5.000000e-01 3.333333e-01 0.000000e+00 0.000000e+00
1.666667e-01 5.000000e-01 1.666667e-01 1.666667e-01 0.000000e+00
1.666667e-01 5.000000e-01 1.666667e-01 0.000000e+00 1.666667e-01
1.666667e-01 5.000000e-01 0.000000e+00 3.333333e-01 0.000000e+00
1.666667e-01 5.000000e-01 0.000000e+00 1.666667e-01 1.666667e-01
1.666667e-01 5.000000e-01 0.000000e+00 0.000000e+00 3.333333e-01
1.666667e-01 3.333333e-01 5.000000e-01 0.000000e+00 0.000000e+00
1.666667e-01 3.333333e-01 3.333333e-01 1.666667e-01 0.000000e+00
1.666667e-01 3.333333e-01 3.333333e-01 0.000000e+00 1.666667e-01
1.666667e-01 3.333333e-01 1.666667e-01 3.333333e-01 0.000000e+00
1.666667e-01 3.333333e-01 1.666667e-01 1.666667e-01 1.666667e-01
1.666667e-01 3.333333e-01 1.666667e-01 0.000000e+00 3.333333e-01
1.666667e-01 3.333333e-01 0.000000e+00 5.000000e-01 0.000000e+00
1.666667e-01 3.333333e-01 0.000000e+00 3.333333e-01 1.666667e-01
1.666667e-01 3.333333e-01 0.000000e+00 1.666667e-01 3.333333e-01
1.666667e-01 3.333333e-01 0.000000e+00 0.000000e+00 5.000000e-01
1.666667e-01 1.666667e-01 6.666667e-01 0.000000e+00 0.000000e+00
1.666667e-01 1.666667e-01 5.000000e-01 1.666667e-01 0.000000e+00
1.666667e-01 1.666667e-01 5.000000e-01 0.000000e+00 1.666667e-01
1.666667e-01 1.666667e-01 3.333333e-01 3.333333e-01 0.000000e+00
1.666667e-01 1.666667e-01 3.333333e-01 1.666667e-01 1.666667e-01
1.666667e-01 1.666667e-01 3.333333e-01 0.000000e+00 3.333333e-01
1.666667e-01 1.666667e-01 1.666667e-01 5.000000e-01 0.000000e+00
1.666667e-01 1.666667e-01 1.666667e-01 3.333333e-01 1.666667e-01
1.666667e-01 1.666667e-01 1.666667e-01 1.666667e-01 3.333333e-01
1.666667e-01 1.666667e-01 1.666667e-01 0.000000e+00 5.000000e-01
1.666667e-01 1.666667e-01 0.000000e+00 6.666667e-01 0.000000e+00
1.666667e-01 1.666667e-01 0.000000e+00 5.000000e-01 1.666667e-01
1.666667e-01 1.666667e-01 0.000000e+00 3.333333e-01 3.333333e-01
1.666667e-01 1.666667e-01 0.000000e+00 1.666667e-01 5.000000e-01
1.666667e-01 1.666667e-01 0.000000e+00 0.000000e+00 6.666667e-01
1.666667e-01 0.000000e+00 8.333333e-01 0.000000e+00 0.000000e+00
1.666667e-01 0.000000e+00 6.666667e-01 1.666667e-01 0.000000e+00
1.666667e-01 0.000000e+00 6.666667e-01 0.000000e+00 1.666667e-01
1.666667e-01 0.000000e+00 5.000000e-01 3.333333e-01 0.000000e+00
1.666667e-01 0.000000e+00 5.000000e-01 1.666667e-01 1.666667e-01
1.666667e-01 0.000000e+00 5.000000e-01 0.000000e+00 3.333333e-01
1.666667e-01 0.000000e+00 3.333333e-01 5.000000e-01 0.000000e+00
1.666667e-01 0.000000e+00 3.333333e-01 3.333333e-01 1.666667e-01
1.666667e-01 0.000000e+00 3.333333e-01 1.666667e-01 3.333333e-01
1.666667e-01 0.000000e+00 3.333333e-01 0.000000e+00 5.000000e-01
1.666667e-01 0.000000e+00 1.666667e-01 6.666667e-01 0.000000e+00
1.666667e-01 0.000000e+00 1.666667e-01 5.000000e-01 1.666667e-01
1.666667e-01 0.000000e+00 1.666667e-01 3.333333e-01 3.333333e-01
1.666667e-01 0.000000e+00 1.666667e-01 1.666667e-01 5.000000e-01
1.666667e-01 0.000000e+00 1.666667e-01 0.000000e+00 6.666667e-01
1.666667e-01 0.000000e+00 0.000000e+00 8.333333e-01 0.000000e+00
1.666667e-01 0.000000e+00 0.000000e+00 6.666667e-01 1.666667e-01
1.666667e-01 0.000000e+00 0.000000e+00 5.000000e-01 3.333333e-01
1.666667e-01 0.000000e+00 0.000000e+00 3.333333e-01 5.000000e-01
1.666667e-01 0.000000e+00 0.000000e+00 1.666667e-01 6.666667e-01
1.666667e-01 0.000000e+00 0.000000e+00 0.000000e+00 8.333333e-01
0.000000e+00 1.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00
0.000000e+00 8.333333e-01 1.666667e-01 0.000000e+00 0.000000e+00
0.000000e+00 8.333333e-01 0.000000e+00 1.666667e-01 0.000000e+00
0.000000e+00 8.333333e-01 0.000000e+00 0.000000e+00 1.666667e-01
0.000000e+00 6.666667e-01 3.333333e-01 0.000000e+00 0.000000e+00
0.000000e+00 6.666667e-01 1.666667e-01 1.666667e-01 0.000000e+00
0.000000e+00 6.666667e-01 1.666667e-01 0.000000e+00 1.666667e-01
0.000000e+00 6.666667e-01 0.000000e+00 3.333333e-01 0.000000e+00
0.000000e+00 6.666667e-01 0.000000e+00 1.666667e-01 1.666667e-01
0.000000e+00 6.666667e-01 0.000000e+00 0.000000e+00 3.333333e-01
0.000000e+00 5.000000e-01 5.000000e-01 0.000000e+00 0.000000e+00
0.000000e+00 5.000000e-01 3.333333e-01 1.666667e-01 0.000000e+00
0.000000e+00 5.000000e-01 3.333333e-01 0.000000e+00 1.666667e-01
0.000000e+00 5.000000e-01 1.666667e-01 3.333333e-01 0.000000e+00
0.000000e+00 5.000000e-01 1.666667e-01 1.666667e-01 1.666667e-01
0.000000e+00 5.000000e-01 1.666667e-01 0.000000e+00 3.333333e-01
0.000000e+00 5.000000e-01 0.000000e+00 5.000000e-01 0.000000e+00
0.000000e+00 5.000000e-01 0.000000e+00 3.333333e-01 1.666667e-01
0.000000e+00 5.000000e-01 0.000000e+00 1.666667e-01 3.333333e-01
0.000000e+00 5.000000e-01 0.000000e+00 0.000000e+00 5.000000e-01
0.000000e+00 3.333333e-01 6.666667e-01 0.000000e+00 0.000000e+00
0.000000e+00 3.333333e-01 5.000000e-01 1.666667e-01 0.000000e+00
0.000000e+00 3.333333e-01 5.000000e-01 0.000000e+00 1.666667e-01
0.000000e+00 3.333333e-01 3.333333e-01 3.333333e-01 0.000000e+00
0.000000e+00 3.333333e-01 3.333333e-01 1.666667e-01 1.666667e-01
0.000000e+00 3.333333e-01 3.333333e-01 0.000000e+00 3.333333e-01
0.000000e+00 3.333333e-01 1.666667e-01 5.000000e-01 0.000000e+00
0.000000e+00 3.333333e-01 1.666667e-01 3.333333e-01 1.666667e-01
0.000000e+00 3.333333e-01 1.666667e-01 1.666667e-01 3.333333e-01
0.000000e+00 3.333333e-01 1.666667e-01 0.000000e+00 5.000000e-01
0.000000e+00 3.333333e-01 0.000000e+00 6.666667e-01 0.000000e+00
0.000000e+00 3.333333e-01 0.000000e+00 5.000000e-01 1.666667e-01
0.000000e+00 3.333333e-01 0.000000e+00 3.333333e-01 3.333333e-01
0.000000e+00 3.333333e-01 0.000000e+00 1.666667e-01 5.000000e-01
0.000000e+00 3.333333e-01 0.000000e+00 0.000000e+00 6.666667e-01
0.000000e+00 1.666667e-01 8.333333e-01 0.000000e+00 0.000000e+00
0.000000e+00 1.666667e-01 6.666667e-01 1.666667e-01 0.000000e+00
0.000000e+00 1.666667e-01 6.666667e-01 0.000000e+00 1.666667e-01
0.000000e+00 1.666667e-01 5.000000e-01 3.333333e-01 0.000000e+00
0.000000e+00 1.666667e-01 5.000000e-01 1.666667e-01 1.666667e-01
0.000000e+00 1.666667e-01 5.000000e-01 0.000000e+00 3.333333e-01
0.000000e+00 1.666667e-01 3.333333e-01 5.000000e-01 0.000000e+00
0.000000e+00 1.666667e-01 3.333333e-01 3.333333e-01 1.666667e-01
0.000000e+00 1.666667e-01 3.333333e-01 1.666667e-01 3.333333e-01
0.000000e+00 1.666667e-01 3.333333e-01 0.000000e+00 5.000000e-01
0.000000e+00 1.666667e-01 1.666667e-01 6.666667e-01 0.000000e+00
0.000000e+00 1.666667e-01 1.666667e-01 5.000000e-01 1.666667e-01
0.000000e+00 1.666667e-01 1.666667e-01 3.333333e-01 3.333333e-01
0.000000e+00 1.666667e-01 1.666667e-01 1.666667e-01 5.000000e-01
0.000000e+00 1.666667e-01 1.666667e-01 0.000000e+00 6.666667e-01
0.000000e+00 1.666667e-01 0.000000e+00 8.333333e-01 0.000000e+00
0.000000e+00 1.666667e-01 0.000000e+00 6.666667e-01 1.666667e-01
0.000000e+00 1.666667e-01 0.000000e+00 5.000000e-01 3.333333e-01
0.000000e+00 1.666667e-01 0.000000e+00 3.333333e-01 5.000000e-01
0.000000e+00 1.666667e-01 0.000000e+00 1.666667e-01 6.666667e-01
0.000000e+00 1.666667e-01 0.000000e+00 0.000000e+00 8.333333e-01
0.000000e+00 0.000000e+00 1.000000e+00 0.000000e+00 0.000000e+00
0.000000e+00 0.000000e+00 8.333333e-01 1.666667e-01 0.000000e+00
0.000000e+00 0.000000e+00 8.333333e-01 0.000000e+00 1.666667e-01
0.000000e+00 0.000000e+00 6.666667e-01 3.333333e-01 0.000000e+00
0.000000e+00 0.000000e+00 6.666667e-01 1.666667e-01 1.666667e-01
0.000000e+00 0.000000e+00 6.666667e-01 0.000000e+00 3.333333e-01
0.000000e+00 0.000000e+00 5.000000e-01 5.000000e-01 0.000000e+00
0.000000e+00 0.000000e+00 5.000000e-01 3.333333e-01 1.666667e-01
0.000000e+00 0.000000e+00 5.000000e-01 1.666667e-01 3.333333e-01
0.000000e+00 0.000000e+00 5.000000e-01 0.000000e+00 5.000000e-01
0.000000e+00 0.000000e+00 3.333333e-01 6.666667e-01 0.000000e+00
0.000000e+00 0.000000e+00 3.333333e-01 5.000000e-01 1.666667e-01
0.000000e+00 0.000000e+00 3.333333e-01 3.333333e-01 3.333333e-01
0.000000e+00 0.000000e+00 3.333333e-01 1.666667e-01 5.000000e-01
0.000000e+00 0.000000e+00 3.333333e-01 0.000000e+00 6.666667e-01
0.000000e+00 0.000000e+00 1.666667e-01 8.333333e-01 0.000000e+00
0.000000e+00 0.000000e+00 1.666667e-01 6.666667e-01 1.666667e-01
0.000000e+00 0.000000e+00 1.666667e-01 5.000000e-01 3.333333e-01
0.000000e+00 0.000000e+00 1.666667e-01 3.333333e-01 5.000000e-01
0.000000e+00 0.000000e+00 1.666667e-01 1.666667e-01 6.666667e-01
0.000000e+00 0.000000e+00 1.666667e-01 0.000000e+00 8.333333e-01
0.000000e+00 0.000000e+00 0.000000e+00 1.000000e+00 0.000000e+00
0.000000e+00 0.000000e+00 0.000000e+00 8.333333e-01 1.666667e-01
0.000000e+00 0.000000e+00 0.000000e+00 6.666667e-01 3.333333e-01
0.000000e+00 0.000000e+00 0.000000e+00 5.000000e-01 5.000000e-01
0.000000e+00 0.000000e+00 0.000000e+00 3.333333e-01 6.666667e-01
0.000000e+00 0.000000e+00 0.000000e+00 1.666667e-01 8.333333e-01
0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 1.000000e+00
| 32,142
|
https://github.com/mdecourse/simExtMTB/blob/master/CMakeLists.txt
|
Github Open Source
|
Open Source
|
BSD-3-Clause, LicenseRef-scancode-unknown-license-reference
| 2,021
|
simExtMTB
|
mdecourse
|
CMake
|
Code
| 35
| 303
|
cmake_minimum_required(VERSION 3.15)
project(simExtMTB)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_MACOSX_RPATH 1)
find_package(Boost REQUIRED)
if(NOT LIBPLUGIN_DIR)
if(DEFINED ENV{COPPELIASIM_ROOT_DIR})
set(LIBPLUGIN_DIR $ENV{COPPELIASIM_ROOT_DIR}/programming/libPlugin)
else()
set(LIBPLUGIN_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../libPlugin)
endif()
endif()
list(APPEND CMAKE_MODULE_PATH ${LIBPLUGIN_DIR}/cmake)
find_package(CoppeliaSim 4.1.0.0 REQUIRED)
coppeliasim_add_plugin(
simExtMTB
LEGACY
SOURCES
simExtMTB.cpp
${COPPELIASIM_COMMON_DIR}/socketOutConnection.cpp
${COPPELIASIM_COMMON_DIR}/scriptFunctionData.cpp
${COPPELIASIM_COMMON_DIR}/scriptFunctionDataItem.cpp
)
| 1,525
|
https://github.com/pyDebugger/Cells/blob/master/core/src/ch/crowdev/cells/Cells.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Cells
|
pyDebugger
|
Java
|
Code
| 417
| 1,251
|
package ch.crowdev.cells;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import java.util.HashMap;
public class Cells extends ApplicationAdapter {
private OrthographicCamera camera;
private SpriteBatch spriteBatch;
private String[] cellTypes = {"", "empty cell", "dead cell", "living cell", "rotator"};
public TextureAtlas spritesheet;
public HashMap<String, Sprite> sprites = new HashMap<String, Sprite>();
public Cell[][] grid = new Cell[21][12];
@Override
public void create() {
spritesheet = new TextureAtlas("sprites.atlas");
sprites.put("empty cell", spritesheet.createSprite("empty_cell"));
sprites.put("dead cell", spritesheet.createSprite("dead_cell"));
sprites.put("living cell", spritesheet.createSprite("living_cell"));
sprites.put("rotator", spritesheet.createSprite("rotator_cell"));
spriteBatch = new SpriteBatch();
camera = new OrthographicCamera();
camera.setToOrtho(false, 1260, 720);
for (int x = 0; x < 1260; x += 60) {
for (int y = 0; y < 720; y += 60) {
grid[x / 60][y / 60] = new Cell(x / 60, y / 60, 1, 1);
}
}
grid[9][6] = new Cell(9, 6, 1, 4);
grid[10][6] = new Cell(10, 6, 1, 3);
grid[8][5] = new Cell(8, 5, 1, 2);
}
@Override
public void render() {
Gdx.gl.glClearColor(0.8f, 0.8f, 0.8f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
spriteBatch.begin();
for (int x = 0; x < 1260; x += 60) {
for (int y = 0; y < 720; y += 60) {
Sprite tmp = sprites.get(cellTypes[grid[x / 60][y / 60].getType()]);
tmp.setRotation(grid[x / 60][y / 60].getRotation());
spriteBatch.draw(tmp, x, y);
}
}
spriteBatch.end();
if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) {
behavior();
}
camera.update();
}
@Override
public void dispose () {
spriteBatch.dispose();
spritesheet.dispose();
}
public void behavior() {
for (int x = 0; x < 1260; x += 60) {
for (int y = 0; y < 720; y += 60) {
switch (grid[x / 60][y / 60].getType()) {
case 3:
if (x / 60 < 19) {
switch (grid[x / 60][y / 60].direction) {
case 1:
grid[(x + 60) / 60][y / 60] = new Cell((x + 60) / 60, y / 60, 1, 3);
break;
case 2:
grid[x / 60][(y - 60) / 60] = new Cell((x + 60) / 60, y / 60, 2, 3);
break;
case 3:
grid[(x - 60) / 60][y / 60] = new Cell((x + 60) / 60, y / 60, 3, 3);
break;
case 4:
grid[x / 60][(y + 60) / 60] = new Cell((x + 60) / 60, y / 60, 4, 3);
break;
}
} else {
grid[x / 60][y / 60] = new Cell(x / 60, y / 60, 1, 2);
}
grid[x / 60][y / 60] = new Cell(x / 60, y / 60, 1, 1);
x += 60;
break;
case 4:
Cell temp = grid[x / 60][y / 60];
}
}
}
}
}
| 44,596
|
https://github.com/cjellick/auth/blob/master/tokens/api_server.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
auth
|
cjellick
|
Go
|
Code
| 867
| 2,976
|
package tokens
import (
"context"
"fmt"
log "github.com/sirupsen/logrus"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/rancher/types/config"
)
const (
defaultSecret = "secret"
defaultTokenTTL = "57600000"
defaultRefreshTokenTTL = "7200000"
)
type tokenAPIServer struct {
ctx context.Context
client *config.ManagementContext
tokensClient v3.TokenInterface
}
func newTokenAPIServer(ctx context.Context, mgmtCtx *config.ManagementContext) (*tokenAPIServer, error) {
if mgmtCtx == nil {
return nil, fmt.Errorf("Failed to build tokenAPIHandler, nil ManagementContext")
}
apiServer := &tokenAPIServer{
ctx: ctx,
client: mgmtCtx,
tokensClient: mgmtCtx.Management.Tokens(""),
}
return apiServer, nil
}
//CreateLoginToken will authenticate with provider and create a jwt token
func (s *tokenAPIServer) createLoginToken(jsonInput v3.LoginInput) (v3.Token, int, error) {
log.Info("Create Token Invoked %v", jsonInput)
authenticated := true
/* Authenticate User
if provider != nil {
token, status, err := provider.GenerateToken(json)
if err != nil {
return model.TokenOutput{}, status, err
}
}*/
if authenticated {
if s.client != nil {
key, err := generateKey()
if err != nil {
log.Info("Failed to generate token key: %v", err)
return v3.Token{}, 0, fmt.Errorf("Failed to generate token key")
}
//check that there is no token with this key.
payload := make(map[string]interface{})
tokenValue, err := createTokenWithPayload(payload, defaultSecret)
if err != nil {
log.Info("Failed to generate token value: %v", err)
return v3.Token{}, 0, fmt.Errorf("Failed to generate token value")
}
ttl := jsonInput.TTLMillis
refreshTTL := jsonInput.IdentityRefreshTTLMillis
if ttl == "" {
ttl = defaultTokenTTL //16 hrs
refreshTTL = defaultRefreshTokenTTL //2 hrs
}
k8sToken := &v3.Token{
TokenID: key,
TokenValue: tokenValue, //signed jwt containing user details
IsDerived: false,
TTLMillis: ttl,
IdentityRefreshTTLMillis: refreshTTL,
User: "dummy",
ExternalID: "github_12346",
AuthProvider: "github",
}
rToken, err := s.createK8sTokenCR(k8sToken)
return rToken, 0, err
}
log.Info("Client nil %v", s.client)
return v3.Token{}, 500, fmt.Errorf("No k8s Client configured")
}
return v3.Token{}, 0, fmt.Errorf("No auth provider configured")
}
//CreateDerivedToken will create a jwt token for the authenticated user
func (s *tokenAPIServer) createDerivedToken(jsonInput v3.Token, tokenID string) (v3.Token, int, error) {
log.Info("Create Derived Token Invoked")
token, err := s.getK8sTokenCR(tokenID)
if err != nil {
return v3.Token{}, 401, err
}
if s.client != nil {
key, err := generateKey()
if err != nil {
log.Info("Failed to generate token key: %v", err)
return v3.Token{}, 0, fmt.Errorf("Failed to generate token key")
}
ttl := jsonInput.TTLMillis
refreshTTL := jsonInput.IdentityRefreshTTLMillis
if ttl == "" {
ttl = defaultTokenTTL //16 hrs
refreshTTL = defaultRefreshTokenTTL //2 hrs
}
k8sToken := &v3.Token{
TokenID: key,
TokenValue: token.TokenValue, //signed jwt containing user details
IsDerived: true,
TTLMillis: ttl,
IdentityRefreshTTLMillis: refreshTTL,
User: token.User,
ExternalID: token.ExternalID,
AuthProvider: token.AuthProvider,
}
rToken, err := s.createK8sTokenCR(k8sToken)
return rToken, 0, err
}
log.Info("Client nil %v", s.client)
return v3.Token{}, 500, fmt.Errorf("No k8s Client configured")
}
func (s *tokenAPIServer) createK8sTokenCR(k8sToken *v3.Token) (v3.Token, error) {
if s.client != nil {
labels := make(map[string]string)
labels["io.cattle.token.field.externalID"] = k8sToken.ExternalID
k8sToken.APIVersion = "management.cattle.io/v3"
k8sToken.Kind = "Token"
k8sToken.ObjectMeta = metav1.ObjectMeta{
Name: strings.ToLower(k8sToken.TokenID),
Labels: labels,
}
createdToken, err := s.tokensClient.Create(k8sToken)
if err != nil {
log.Info("Failed to create token resource: %v", err)
return v3.Token{}, err
}
log.Info("Created Token %v", createdToken)
return *createdToken, nil
}
return v3.Token{}, fmt.Errorf("No k8s Client configured")
}
func (s *tokenAPIServer) getK8sTokenCR(tokenID string) (*v3.Token, error) {
if s.client != nil {
storedToken, err := s.tokensClient.Get(strings.ToLower(tokenID), metav1.GetOptions{})
if err != nil {
log.Info("Failed to get token resource: %v", err)
return nil, fmt.Errorf("Failed to retrieve auth token")
}
log.Info("storedToken token resource: %v", storedToken)
return storedToken, nil
}
return nil, fmt.Errorf("No k8s Client configured")
}
//GetTokens will list all tokens of the authenticated user - login and derived
func (s *tokenAPIServer) getTokens(tokenID string) ([]v3.Token, int, error) {
log.Info("GET Token Invoked")
var tokens []v3.Token
if s.client != nil {
storedToken, err := s.tokensClient.Get(strings.ToLower(tokenID), metav1.GetOptions{})
if err != nil {
log.Info("Failed to get token resource: %v", err)
return tokens, 401, fmt.Errorf("Failed to retrieve auth token")
}
log.Info("storedToken token resource: %v", storedToken)
externalID := storedToken.ExternalID
set := labels.Set(map[string]string{"io.cattle.token.field.externalID": externalID})
tokenList, err := s.tokensClient.List(metav1.ListOptions{LabelSelector: set.AsSelector().String()})
if err != nil {
return tokens, 0, fmt.Errorf("Error getting tokens for user: %v selector: %v err: %v", externalID, set.AsSelector().String(), err)
}
for _, t := range tokenList.Items {
log.Info("List token resource: %v", t)
tokens = append(tokens, t)
}
return tokens, 0, nil
}
log.Info("Client nil %v", s.client)
return tokens, 500, fmt.Errorf("No k8s Client configured")
}
func (s *tokenAPIServer) deleteToken(tokenKey string) (int, error) {
log.Info("DELETE Token Invoked")
if s.client != nil {
err := s.tokensClient.Delete(strings.ToLower(tokenKey), &metav1.DeleteOptions{})
if err != nil {
return 500, fmt.Errorf("Failed to delete token")
}
log.Info("Deleted Token")
return 0, nil
}
log.Info("Client nil %v", s.client)
return 500, fmt.Errorf("No k8s Client configured")
}
func (s *tokenAPIServer) getIdentities(tokenKey string) ([]v3.Identity, int, error) {
var identities []v3.Identity
/*token, status, err := GetToken(tokenKey)
if err != nil {
return identities, 401, err
} else {
identities = append(identities, token.UserIdentity)
identities = append(identities, token.GroupIdentities...)
return identities, status, nil
}*/
identities = append(identities, getUserIdentity())
identities = append(identities, getGroupIdentities()...)
return identities, 0, nil
}
func getUserIdentity() v3.Identity {
identity := v3.Identity{
LoginName: "dummy",
DisplayName: "Dummy User",
ProfilePicture: "",
ProfileURL: "",
Kind: "user",
Me: true,
MemberOf: false,
}
identity.ObjectMeta = metav1.ObjectMeta{
Name: "ldap_cn=dummy,dc=tad,dc=rancher,dc=io",
}
return identity
}
func getGroupIdentities() []v3.Identity {
var identities []v3.Identity
identity1 := v3.Identity{
DisplayName: "Admin group",
LoginName: "Administrators",
ProfilePicture: "",
ProfileURL: "",
Kind: "group",
Me: false,
MemberOf: true,
}
identity1.ObjectMeta = metav1.ObjectMeta{
Name: "ldap_cn=group1,dc=tad,dc=rancher,dc=io",
}
identity2 := v3.Identity{
DisplayName: "Dev group",
LoginName: "Developers",
ProfilePicture: "",
ProfileURL: "",
Kind: "group",
Me: false,
MemberOf: true,
}
identity2.ObjectMeta = metav1.ObjectMeta{
Name: "ldap_cn=group2,dc=tad,dc=rancher,dc=io",
}
identities = append(identities, identity1)
identities = append(identities, identity2)
return identities
}
| 2,105
|
https://github.com/openid-certification/-conformance-suite/blob/master/src/main/java/net/openid/conformance/condition/as/EnsureRedirectUriInRequestObjectMatchesOneOfClientRedirectUris.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
-conformance-suite
|
openid-certification
|
Java
|
Code
| 102
| 435
|
package net.openid.conformance.condition.as;
import com.google.common.base.Strings;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import net.openid.conformance.condition.AbstractCondition;
import net.openid.conformance.condition.PostEnvironment;
import net.openid.conformance.condition.PreEnvironment;
import net.openid.conformance.testmodule.Environment;
import net.openid.conformance.testmodule.OIDFJSON;
public class EnsureRedirectUriInRequestObjectMatchesOneOfClientRedirectUris extends AbstractCondition {
@Override
@PreEnvironment(required = { "client", "authorization_request_object" })
@PostEnvironment(strings = {"authorization_endpoint_request_redirect_uri"})
public Environment evaluate(Environment env) {
// get the client ID from the configuration
JsonArray redirectUris = env.getElementFromObject("client", "redirect_uris").getAsJsonArray();
String actual = env.getString("authorization_request_object", "claims.redirect_uri");
for(JsonElement redirUri : redirectUris) {
String uriString = OIDFJSON.getString(redirUri);
if(actual.equals(uriString)) {
env.putString("authorization_endpoint_request_redirect_uri", actual);
logSuccess("Redirect URI matched one of client redirect_uris",
args("actual", Strings.nullToEmpty(actual)));
return env;
}
}
throw error("Redirect URI is not one of the registered ones for the client",
args("expected", redirectUris, "actual", Strings.nullToEmpty(actual)));
}
}
| 49,971
|
https://github.com/curry684/tipctl/blob/master/src/Command/Domain/Dns/AddDnsEntry.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
tipctl
|
curry684
|
PHP
|
Code
| 95
| 586
|
<?php
namespace Transip\Api\CLI\Command\Domain\Dns;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Transip\Api\CLI\Command\AbstractCommand;
use Transip\Api\CLI\Command\Field;
use Transip\Api\Library\Entity\Domain\DnsEntry;
class AddDnsEntry extends AbstractCommand
{
protected function configure(): void
{
$this->setName('domain:dns:adddnsentry')
->setDescription('Add a dns entry to the domain DNS entries')
->setHelp('Provide DNS Record information to add to the DNS entries')
->addArgument(Field::DOMAIN_NAME, InputArgument::REQUIRED, Field::DOMAIN_NAME__DESC)
->addArgument(Field::DNS_ENTRY_NAME, InputArgument::REQUIRED, Field::DNS_ENTRY_NAME__DESC)
->addArgument(Field::DNS_ENTRY_EXPIRE, InputArgument::REQUIRED, Field::DNS_ENTRY_EXPIRE__DESC)
->addArgument(Field::DNS_ENTRY_TYPE, InputArgument::REQUIRED, Field::DNS_ENTRY_TYPE__DESC)
->addArgument(Field::DNS_ENTRY_CONTENT, InputArgument::REQUIRED, Field::DNS_ENTRY_CONTENT__DESC);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$domainName = $input->getArgument(Field::DOMAIN_NAME);
$name = $input->getArgument(Field::DNS_ENTRY_NAME);
$expire = $input->getArgument(Field::DNS_ENTRY_EXPIRE);
$type = $input->getArgument(Field::DNS_ENTRY_TYPE);
$content = $input->getArgument(Field::DNS_ENTRY_CONTENT);
$dnsEntry = new DnsEntry();
$dnsEntry->setName($name);
$dnsEntry->setExpire($expire);
$dnsEntry->setType($type);
$dnsEntry->setContent($content);
$this->getTransipApi()->domainDns()->addDnsEntryToDomain($domainName, $dnsEntry);
}
}
| 4,573
|
https://github.com/lunaris-studios/neptune/blob/master/packages/protocol/src/bin/_theme.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
neptune
|
lunaris-studios
|
TypeScript
|
Code
| 134
| 442
|
import * as Constants from "~/constants";
export interface Binds {
/**
* Used to identify the current client window size.
* @default Breakpoint.DESKTOP
*/
device: Constants.Device;
/**
* Used to indicate the global color scheme for the client.
* @default Scheme.LIGHT
*/
scheme: Constants.Scheme;
}
export interface Theme {
binds: Binds;
alignments: typeof Constants.Alignment;
boundaries: typeof Constants.Boundary;
breakpoints: typeof Constants.Breakpoint;
colors: typeof Constants.Color;
devices: typeof Constants.Device;
elevations: typeof Constants.Elevation;
intents: typeof Constants.Intent;
keys: typeof Constants.Key;
positions: typeof Constants.Position;
schemes: typeof Constants.Scheme;
sizes: typeof Constants.Size;
spaces: typeof Constants.Space;
}
/** Default theme values for root `styled-compoents` <ThemeProvider> */
export const Theme = Object.freeze<Theme>({
binds: {
device: Constants.Device.DESKTOP,
scheme: Constants.Scheme.DARK,
},
alignments: Constants.Alignment,
boundaries: Constants.Boundary,
breakpoints: Constants.Breakpoint,
colors: Constants.Color,
devices: Constants.Device,
elevations: Constants.Elevation,
intents: Constants.Intent,
keys: Constants.Key,
positions: Constants.Position,
schemes: Constants.Scheme,
sizes: Constants.Size,
spaces: Constants.Space,
});
| 40,333
|
https://github.com/filippopov/JavaScript-Advanced/blob/master/Task JavaScript Advance/JavaScript Advanced cod/JavaScript Advance/SearchInList/search.js
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
JavaScript-Advanced
|
filippopov
|
JavaScript
|
Code
| 22
| 95
|
function search() {
let patern = $('#searchText').val();
$('#towns li').css('font-weight', 'normal');
let li = $(`#towns li:contains(${patern})`);
$('#searchText').val('');
li.css('font-weight', 'bold');
$('#result').text(`${li.length} matches found.`);
}
| 6,793
|
https://github.com/phprojects/thinksns-plus/blob/master/packages/zhiyicx-plus-pc/resources/views/account/index.blade.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
thinksns-plus
|
phprojects
|
PHP
|
Code
| 848
| 3,629
|
@section('title')
基本资料
@endsection
@php
use function Zhiyi\Component\ZhiyiPlus\PlusComponentPc\getAvatar;
@endphp
@extends('pcview::layouts.default')
@section('styles')
<link rel="stylesheet" href="{{ asset('assets/pc/css/account.css')}}"/>
<link rel="stylesheet" href="{{ asset('assets/pc/cropper/cropper.min.css')}}">
@endsection
@section('content')
<div class="account_container">
@include('pcview::account.sidebar')
<div class="account_r">
<div class="account_c_c">
<div class="account_tab" id="J-input">
<div class="perfect_title">
<p>基本资料</p>
</div>
<div class="perfect_row mb30">
<div class="account_heder">
<div class="header">
<img id="J-image-preview" src="{{ getAvatar($user, 100) }}">
<input id="task_id" name="storage_task_id" type="hidden"/>
</div>
<a class="perfect_btn" id="J-file-upload-btn" href="javascript:;">更改头像</a>
</div>
</div>
<div class="perfect_row mb30">
<form action="#">
<div class="account_form_row">
<label for="name">昵称</label>
<input id="name" name="name" type="text" value="{{$user['name'] }}" maxlength="8" />
</div>
<div class="account_form_row">
<label for="bio">简介</label>
<input id="bio" name="bio" type="text" value="{{$user['bio'] ?? ''}}" />
</div>
<div class="account_form_row">
<label>性别</label>
<div class="input">
<span>
<input @if($user['sex'] == 1) checked="checked" @endif id="male" name="sex" type="radio" value="1" />
<label for="male">男</label>
</span>
<span>
<input @if($user['sex'] == 2) checked="checked" @endif id="female" name="sex" type="radio" value="2" />
<label for="female">女</label>
</span>
<span>
<input @if($user['sex'] == 0) checked="checked" @endif id="secret" name="sex" type="radio" value="0" />
<label for="secret">不方便透露</label>
</span>
</div>
</div>
<div class="account_form_row" style="position:relative">
<label for="area">地区</label>
<input id="location" name="location" type="text" value="{{$user['location'] ?? ''}}" placeholder="请输入地区搜索(例如:成都)" />
<div class="area_searching">
</div>
</div>
</form>
</div>
<div class="perfect_btns">
<a href="javascript:;" class="perfect_btn save" id="J-user-info">保存</a>
</div>
</div>
</div>
</div>
</div>
@endsection
@section('scripts')
<script src="{{ asset('assets/pc/cropper/cropper.min.js')}}"></script>
<script src="{{ asset('assets/pc/js/module.account.js')}}"></script>
<script src="{{ asset('assets/pc/js/md5.min.js')}}"></script>
<script>
// 地区搜索
var last;
$("#location").keyup(function(event){
//利用event的timeStamp来标记时间,这样每次的keyup事件都会修改last的值
last = event.timeStamp;
setTimeout(function(){
if(last - event.timeStamp == 0){
location_search();
}
}, 500);
});
$("#location").focus(function() {
var val = $.trim($("#location").val());
if (val.length >= 1) {
location_search();
}
});
$('.area_searching').on('click', 'a', function() {
$('#location').val($(this).text());
$('.area_searching').hide();
});
function location_search(event)
{
var val = $.trim($("#location").val());
var area_searching = $(".area_searching");
area_searching.html('').hide();
if (!val || val == "") { return; }
axios.get('/api/v2/locations/search', { params: {name:val} })
.then(function (response) {
if (response.data.length > 0) {
$.each(response.data, function(key, value) {
if (key < 3) {
var text = tree(value.tree);
var html = '<div><a>' + text + '</a></div>';
area_searching.append(html);
}
});
area_searching.show();
}
})
.catch(function (error) {
showError(error.response.data);
});
}
function tree(obj)
{
var text = '';
if (obj.parent != null) {
text = tree(obj.parent) + ' ' + obj.name;
} else {
text = obj.name;
}
return text;
}
var username = "{{$user['name'] }}";
var locate = "{{$user['location'] }}";
$('#J-image-preview, #J-file-upload-btn').on('click',function(){
var html = '<div id="model">'
+ '<div class="avatar-container" id="crop-avatar">'
+ '<div class="avatar-upload">'
+ '<input type="hidden" class="avatar-src" name="avatar_src">'
+ '<input type="file" class="avatar-input" id="avatarInput" name="avatar_file">'
+ '<label class="avatar-file" for="avatarInput">选择图片</label>'
+ '</div>'
+ '<div class="avatar-wrapper"></div>'
+ '<div class="save-btn"><span>上传完成记得点击保存按钮</span><button type="button" class="btn btn-primary avatar-save">完成</button></div>'
+ '</div></div>';
ly.loadHtml(html, '上传头像', '600px', '500px;');
$(function () {
'use strict';
var console = window.console || { log: function () {} };
function CropAvatar($element) {
this.$container = $element;
this.$avatarInput = this.$container.find('.avatar-input');
this.$avatarWrapper = this.$container.find('.avatar-wrapper');
this.$avatarPreview = this.$container.find('.avatar-preview');
this.$avatarSave = this.$container.find('.avatar-save');
this.init();
}
// base64
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
// get round avater
function getRoundedCanvas(sourceCanvas) {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var width = sourceCanvas.width;
var height = sourceCanvas.height;
canvas.width = width;
canvas.height = height;
context.beginPath();
context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI);
context.strokeStyle = 'rgba(0,0,0,0)';
context.stroke();
context.clip();
context.drawImage(sourceCanvas, 0, 0, width, height);
return canvas;
}
CropAvatar.prototype = {
constructor: CropAvatar,
support: {
fileList: !!$('<input type="file">').prop('files'),
blobURLs: !!window.URL && URL.createObjectURL,
formData: !!window.FormData
},
init: function () {
this.support.datauri = this.support.fileList && this.support.blobURLs;
this.fileUpload = {};
this.addListener();
},
addListener: function () {
this.$avatarInput.on('change', $.proxy(this.change, this));
this.$avatarSave.on('click', $.proxy(this.click, this));
},
click: function () {
if (this.fileUpload.mime_type) {
// 默认宽高 160
var croppedCanvas = this.$img.cropper('getCroppedCanvas');
var roundedCanvas = getRoundedCanvas(croppedCanvas); // 获取圆形头像
var dataurl = roundedCanvas.toDataURL('image/png');
var blob = dataURLtoBlob(dataurl);
/*blob.name = this.fileUpload.origin_filename;
this.$avatarSave.text('上传中...');
fileUpload.init(blob, updateImg);*/
this.upload(blob, dataurl);
} else {
ly.error('请选择上传文件', false);
}
},
upload: function(blob, url) {
var _this = this;
var reader = new FileReader();
reader.onload = function(e) {
var base64 = e.target.result;
var hash = md5(base64);
_this.$avatarSave.text('上传中...');
var params = {
filename: md5(_this.fileUpload.origin_filename) + '.' + _this.fileUpload.origin_filename.split('.').splice(-1),
hash: hash,
size: blob.size,
mime_type: 'image/png',
storage: { channel: 'public' },
}
axios.post('/api/v2/storage', params).then(function(res) {
var result = res.data;
var node = result.node;
var instance = axios.create();
instance.request({
method: result.method,
url: result.uri,
headers: result.headers,
data: blob,
}).then(function(res) {
// 头像上传成功后,更新用户头像
axios.patch('/api/v2/user', {avatar: node}).then(function () {
_this.insert(url);
}).catch(function (error) {
showError(error.response.data);
})
}).catch(function (error) {
showError(error.response.data);
})
}).catch(function (error) {
showError(error.response.data);
})
}
var file = new File([blob], _this.fileUpload.origin_filename, {
type: 'image/png',
lastModified: new Date()
})
reader.readAsArrayBuffer(file);
},
insert: function(src) {
$('#J-image-preview').attr('src', src);
layer.closeAll();
noticebox('修改头像成功', 1);
},
change: function () {
var files,file;
if (this.support.datauri) {
files = this.$avatarInput.prop('files');
if (files.length > 0) {
file = files[0];
this.fileUpload.mime_type = file.type;
this.fileUpload.origin_filename = file.name;
if (this.isImageFile(file)) {
if (this.url) {
URL.revokeObjectURL(this.url); // Revoke the old one
}
this.url = URL.createObjectURL(file);
this.startCropper();
}
}
} else {
file = this.$avatarInput.val();
if (this.isImageFile(file)) {
this.syncUpload();
}
}
},
startCropper: function () {
var _this = this;
if (this.active) {
this.$img.cropper('replace', this.url);
} else {
this.$img = $('<img src="' + this.url + '">');
this.$avatarWrapper.empty().html(this.$img);
this.$img.cropper({
aspectRatio: 1, //设置剪裁容器的比例
viewMode: 1,
preview: this.$avatarPreview.selector, //添加额外的元素(容器)的预览
});
this.active = true;
}
},
stopCropper: function () {
if (this.active) {
this.$img.cropper('destroy');
this.$img.remove();
this.active = false;
}
},
isImageFile: function (file) {
if (file.type) {
return /^image\/\w+$/.test(file.type);
} else {
return /\.(jpg|jpeg|png|gif)$/.test(file);
}
}
};
return new CropAvatar($('#crop-avatar'));
});
});
</script>
@endsection
| 28,632
|
https://github.com/dsp-testing/isis/blob/master/antora/components/refguide-index/modules/applib/pages/index/services/xmlsnapshot/hooks/XmlSnapshotService_020-examples-and-usage.adoc
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
isis
|
dsp-testing
|
AsciiDoc
|
Code
| 742
| 1,434
|
:Notice: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at. http://www.apache.org/licenses/LICENSE-2.0 . Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
== Usage
The most straight-forward usage of this service is simply:
[source,java]
----
XmlSnapshot snapshot = xmlsnapshotService.snapshotFor(customer);
Element customerAsXml = snapshot.getXmlElement();
----
This will return an XML (document) element that contains the names and values of each of the customer's value properties, along with the titles of reference properties, and also the number of items in collections.
As well as obtaining the XML snapshot, it is also possible to obtain an XSD schema that the XML snapshot conforms to.
[source]
----
XmlSnapshot snapshot = ...;
Element customerAsXml = snapshot.getXmlElement();
Element customerXsd = snapshot.getXsdElement();
----
This can be useful for some tools.
For example, link:http://www.altova.com/stylevision.html[Altova Stylevision] can use the XML and XSD to transform into reports.
Please note that this link does not imply endorsement (nor even a recommendation that this is a good design).
== Builder API
The contents of the snapshot can be adjusted by including "paths" to other references or collections.
To do this, the builder is used.
The API for this is:
[source,java]
----
public interface XmlSnapshotService {
...
public interface Builder {
void includePath(final String path);
void includePathAndAnnotation(String path, String annotation);
XmlSnapshotService.Snapshot build();
}
@Programmatic
public XmlSnapshotService.Builder builderFor(Object domainObject);
}
----
We start by obtaining a builder:
[source,java]
----
XmlSnapshot.Builder builder = xmlsnapshotService.builderFor(customer);
----
Suppose now that we want the snapshot to also include details of the customer's address, where `address` in this case is a reference property to an instance of the `Address` class.
We can "walk-the-graph" by including these references within the builder.
[source,java]
----
builder.includePath("address");
----
We could then go further and include details of every order in the customer's `orders` collection, and details of every product of every order:
[source,java]
----
builder.includePath("orders/product");
----
When all paths are included, then the builder can build the snapshot:
[source,java]
----
XmlSnapshot snapshot = builder.build();
Element customerAsXml = snapshot.getXmlElement();
----
All of this can be strung together in a fluent API:
[source,java]
----
Element customerAsXml = xmlsnapshotService.builderFor(customer)
.includePath("address")
.includePath("orders/product")
.build()
.getXmlElement();
----
As you might imagine, the resultant XML document can get quite large very quickly with only a few "include"s.
[NOTE]
====
If an XSD schema is beng generated (using `snapshot.getXsdElement()` then note that for the XSD to be correct, the object being snapshotted must have non-null values for the paths that are `include()`'d. If this isn't done then the XSD will not be correct reflect for another snapshotted object that does have non-null values.
====
== Automatic inclusions
If the domain object being snapshotted implements the `SnapshottableWithInclusions` interace, then this moves the responsibility for determining what is included within the snapshot from the caller to the snapshottable object itself:
[source]
----
public interface SnapshottableWithInclusions extends Snapshottable {
List<String> snapshotInclusions();
}
----
If necessary, both approaches can be combined.
[TIP]
====
As an alternative to using `include()`, you might consider building a view model domain object which can reference only the relevant information required for the snapshot.
For example, if only the 5 most recent Orders for a Customer were required, a `CustomerAndRecentOrders` view model could hold a collection of just those 5 ``Order``s.
Typically such view models would implement `SnapshottableWithInclusions`.
One reason for doing this is to provide a stable API between the domain model and whatever it is that might be consuming the XML. With a view model you can refactor the domain entities but still preserve a view model such that the XML is the same.
====
== See Also
* xref:refguide:applib:index/services/xmlsnapshot/XmlSnapshotService~Snapshot.adoc[Snapshot]
** xref:refguide:applib:index/services/xmlsnapshot/XmlSnapshotService~Snapshot~Builder.adoc[Snapshot.Builder]
* xref:refguide:applib:index/services/bookmark/BookmarkService.adoc[BookmarkService]
+
provides a mechanism for obtaining a string representations of a single domain object.
* xref:refguide:applib:index/services/jaxb/JaxbService.adoc[JaxbService]
+
is a simple wrapper around standard JAXB functionality for generating both XMLs and XSDs from JAXB-annotated classes.
+
Note that there is built-in support for JAXB classes (ie annotated with
xref:refguide:applib-ant:XmlRootElement.adoc[@XmlRootElement]) to be used as view models.
| 15,657
|
https://github.com/TanHaoran/NurseService1.0/blob/master/cn.jpush.api/schedule/trigger/Single.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
NurseService1.0
|
TanHaoran
|
C#
|
Code
| 55
| 190
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using cn.jpush.api.util;
using Newtonsoft.Json;
namespace cn.jpush.api.schedule
{
public class Single
{
[JsonProperty]
private string time;
public void setTime(string time)
{
Preconditions.checkArgument(!String.IsNullOrEmpty(time), "The time must not be empty.");
Preconditions.checkArgument(StringUtil.IsDateTime(time),"the time is not valid");
this.time = time;
}
public string getTime()
{
return this.time;
}
}
}
| 42,423
|
https://github.com/admariner/OCR4all/blob/master/src/main/java/de/uniwue/batch/BatchWorkflow.java
|
Github Open Source
|
Open Source
|
MIT
| null |
OCR4all
|
admariner
|
Java
|
Code
| 3,267
| 9,439
|
/**
* File: BatchWorkflow.java
* Package: de.uniwue.batch
*
* Author: Herbert Baier
* Date: 21.09.2020
*/
package de.uniwue.batch;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;
import java.util.UUID;
import org.apache.commons.io.FilenameUtils;
import de.uniwue.batch.process.AdjustmentType;
import de.uniwue.batch.process.ResultGenerationStrategy;
import de.uniwue.batch.process.ResultGenerationType;
import de.uniwue.batch.report.BatchProcessOverview;
import de.uniwue.batch.report.BatchWorkflowDetail;
import de.uniwue.config.ProjectConfiguration;
import de.uniwue.feature.ProcessHandler;
import de.uniwue.feature.ProcessStateCollector;
import de.uniwue.helper.LineSegmentationHelper;
import de.uniwue.helper.OverviewHelper;
import de.uniwue.helper.PreprocessingHelper;
import de.uniwue.helper.RecognitionHelper;
import de.uniwue.helper.ResultGenerationHelper;
import de.uniwue.helper.SegmentationDummyHelper;
/**
* Defines batch workflows.
*
* @author Herbert Baier
* @version 1.0
* @since 1.8
*/
public class BatchWorkflow {
/**
* The source image extension.
*/
public static final String sourceImageExtension = "png";
/**
* The source image extension.
*/
private static final String segmentationImageType = "Binary";
/**
* The preserve empty lines argument for result generation.
*/
public static final String resultGenerationPreserveEmptyLinesArgument = "--preserve-empty-lines";
/**
* The addPageDelimiter argument for result generation
*/
public static final String resultGenerationAddPageDelimiter = "--add-page-delimiter";
/**
* The backup argument for adjustment.
*/
public static final String adjustmentBackupArgument = "--backup";
/**
* The ignore blank pages for adjustment.
*/
public static final String adjustmentIgnoreBlankPagesArgument = "--ignore-blank-pages";
/**
* The dpi argument for adjustment.
*/
public static final String adjustmentDpiArgument = "--dpi";
/**
* Defines workflow states.
*
* @author Herbert Baier
* @version 1.0
* @since 1.8
*/
public enum State {
scheduled, running, completed, canceled, interrupted
}
/**
* Defines project folders.
*
* @author Herbert Baier
* @version 1.0
* @since 1.8
*/
public enum ProjectFolder {
input, processing, results
}
/**
* The id.
*/
private final String id = UUID.randomUUID().toString();
/**
* The state. The initial state is scheduled.
*/
private State state = State.scheduled;
/**
* The configuration.
*/
private final WorkflowConfiguration configuration;
/**
* The workflow process configurations. The key is the process identifier.
*/
private final Hashtable<String, WorkflowConfiguration.ProcessConfiguration> processConfigurations = new Hashtable<>();
/**
* The project folder.
*/
private final String projectFolder;
/**
* The page ids.
*/
private final List<String> pageIds = new ArrayList<String>();
/**
* The collector for current state of processes.
*/
private final ProcessStateCollector processStateCollector;
/**
* The process workers.
*/
private final LinkedList<ProcessWorker> processWorkers = new LinkedList<>();
/**
* True if the workflow was canceled.
*/
private boolean isCanceled = false;
/**
* The created time.
*/
private final Date created = new Date();
/**
* The start time.
*/
private Date start = null;
/**
* The finish time.
*/
private Date finish = null;
/**
* Creates a batch workflow.
*
* @param configuration The configuration.
* @throws IllegalArgumentException Throws on workflow configuration troubles.
* @throws IllegalStateException Throws if the input folder of project does
* not exist.
* @since 1.8
*/
public BatchWorkflow(WorkflowConfiguration configuration) throws IllegalArgumentException, IllegalStateException {
super();
WorkflowConfiguration.validate(configuration);
String projectFolder = OverviewHelper.listProjects().get(configuration.getProject());
this.projectFolder = projectFolder + (projectFolder.endsWith(File.separator) ? "" : File.separator);
this.configuration = configuration;
for (WorkflowConfiguration.ProcessConfiguration processConfiguration : this.configuration.getProcesses())
processConfigurations.put(processConfiguration.getId(), processConfiguration);
processStateCollector = new ProcessStateCollector(new ProjectConfiguration(this.projectFolder),
this.configuration.getType().name());
initialize(new File(this.projectFolder));
}
/**
* Initializes the batch workflow.
*
* @param projectFolder The project folder.
* @throws IllegalStateException Throws if the input folder of project does not
* exist.
* @since 1.8
*/
private void initialize(File projectFolder) throws IllegalStateException {
loadPageIds(projectFolder);
// create processing folder if required
File processingFolder = new File(projectFolder, ProjectFolder.processing.name());
if (!processingFolder.exists())
processingFolder.mkdir();
}
/**
* Loads the page ids from project input folder if batch configuration requires
* all pages, this means, its pages field is null. Furthermore, cross check if
* the project input folder is available. The pages ids will be sorted
* lexicographically, ignoring case differences.
*
* @param projectFolder The project folder.
* @throws IllegalStateException Throws if the input folder of project does not
* exist.
* @since 1.8
*/
private void loadPageIds(File projectFolder) throws IllegalStateException {
File inputFolder = new File(projectFolder, ProjectFolder.input.name());
if (inputFolder.exists()) {
pageIds.clear();
if (configuration.getPages() == null) {
for (File fileEntry : inputFolder.listFiles())
if (fileEntry.isFile()
&& FilenameUtils.getExtension(fileEntry.getName()).equals(sourceImageExtension))
pageIds.add(FilenameUtils.removeExtension(fileEntry.getName()));
} else
for (String page : configuration.getPages())
pageIds.add(page);
} else
throw new IllegalStateException(
"the input folder of project '" + configuration.getProject() + "' does not exist.");
Collections.sort(pageIds, String::compareToIgnoreCase);
}
/**
* Returns the id.
*
* @return The id.
* @since 1.8
*/
public String getId() {
return id;
}
/**
* Returns the state.
*
* @return The state.
* @since 1.8
*/
public State getState() {
return state;
}
/**
* Returns true if the process is done.
*
* @return True if the process is done.
* @since 1.8
*/
public boolean isDone() {
switch (state) {
case canceled:
case completed:
case interrupted:
return true;
case running:
case scheduled:
default:
return false;
}
}
/**
* Returns true if the workflow was canceled.
*
* @return True if the workflow was canceled.
* @since 1.8
*/
public boolean isCanceled() {
return isCanceled;
}
/**
* Returns the created time.
*
* @return The created time.
* @since 1.8
*/
public Date getCreated() {
return created;
}
/**
* Returns the start time.
*
* @return The start time.
* @since 1.8
*/
public Date getStart() {
return start;
}
/**
* Returns the finish time.
*
* @return The finish time.
* @since 1.8
*/
public Date getFinish() {
return finish;
}
/**
* Returns the configuration.
*
* @return The configuration.
* @since 1.8
*/
public WorkflowConfiguration getConfiguration() {
return configuration;
}
/**
* Returns the page ids.
*
* @return The page ids.
* @since 1.8
*/
public List<String> getPageIds() {
return pageIds;
}
/**
* Returns the running step. 0 if not started.
*
* @return The running step.
* @since 1.8
*/
public int getStep() {
return processWorkers.size();
}
/**
* Returns the number of steps.
*
* @return The number of steps.
* @since 1.8
*/
public int getStepNumber() {
return configuration.getWorkflow().size();
}
/**
* Returns the batch workflow details.
*
* @return The batch workflow details.
* @since 1.8
*/
public BatchWorkflowDetail getDetails() {
BatchWorkflowDetail details = new BatchWorkflowDetail(this);
synchronized (processWorkers) {
int step = 0;
for (ProcessWorker processWorker : processWorkers)
details.getSteps().add(new BatchProcessOverview(++step, processWorker));
}
return details;
}
/**
* Starts the workflow in a new thread if it is in scheduled state.
*
* @param callback The callback method when the batch workflow finishes. If
* null, no callback is performed.
* @since 1.8
*/
public synchronized void start(Callback callback) {
if (State.scheduled.equals(state)) {
state = State.running;
start = new Date();
new Thread(new Runnable() {
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
// Perform workflow
for (String workflow : configuration.getWorkflow()) {
WorkflowConfiguration.ProcessConfiguration processConfiguration = processConfigurations
.get(workflow);
switch (processConfiguration.getProcess()) {
case adjustment:
adjustment(processConfiguration);
break;
case preprocessing:
preprocessing(processConfiguration);
break;
case segmentationDummy:
segmentationDummy(processConfiguration);
break;
case lineSegmentation:
lineSegmentation(processConfiguration);
break;
case recognition:
recognition(processConfiguration);
break;
case resultGeneration:
resultGeneration(processConfiguration);
break;
}
if (isCanceled || !State.running.equals(state))
break;
}
if (State.running.equals(state)) {
if (isCanceled)
state = State.canceled;
else
state = State.completed;
}
finish = new Date();
if (callback != null)
callback.finish(BatchWorkflow.this);
}
}).start();
}
}
/**
* Cancels the workflow if it is in scheduled or running state.
*
* @since 1.8
*/
public synchronized void cancel() {
if (!isCanceled && !isDone()) {
isCanceled = true;
switch (state) {
case scheduled:
state = State.canceled;
finish = new Date();
break;
case running:
synchronized (processWorkers) {
if (!processWorkers.isEmpty())
processWorkers.getLast().getWrapper().cancelProcess();
}
break;
default:
break;
}
}
}
/**
* Performs the workflow adjustment.
*
* @param processConfiguration The process configuration.
* @since 1.8
*/
private void adjustment(WorkflowConfiguration.ProcessConfiguration processConfiguration) {
final OverviewHelper helper;
final ProcessWorker worker;
synchronized (processWorkers) {
if (isCanceled)
return;
helper = new OverviewHelper(projectFolder, configuration.getType().name());
// there are no page restrictions
worker = new ProcessWorker(processConfiguration, (id) -> true, new ProcessWrapper() {
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#getHandler()
*/
@Override
public ProcessHandler getHandler() {
return null;
}
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#getProgress()
*/
@Override
public float getProgress() {
try {
int progress = helper.getProgress();
return progress < 0 ? 0 : progress / 100F;
} catch (Exception e) {
return 0;
}
}
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#cancelProcess()
*/
@Override
public void cancelProcess() {
try {
helper.cancelProcess();
} catch (Exception e) {
// Nothing to do
}
}
});
processWorkers.add(worker);
}
execute(worker, () -> {
List<String> arguments = processConfiguration.getArguments();
AdjustmentType type;
int index = arguments.indexOf(AdjustmentType.argument);
if (index >= 0 && index < arguments.size() - 1)
try {
type = AdjustmentType.valueOf(arguments.get(index + 1));
} catch (Exception e) {
throw new IllegalArgumentException("unknown adjustment type \"" + arguments.get(index + 1) + "\"");
}
else
throw new IllegalArgumentException("missed adjustment type");
boolean isFlag = false;
switch (type) {
case pdf:
isFlag = arguments.contains(adjustmentIgnoreBlankPagesArgument);
index = arguments.indexOf(adjustmentDpiArgument);
if (index >= 0 && index < arguments.size() - 1)
try {
helper.setDPI(Integer.parseInt(arguments.get(index + 1)));
} catch (Exception e) {
throw new IllegalArgumentException("invalid adjustment dpi value \"" + arguments.get(index + 1)
+ "\" - " + e.getMessage());
}
else
throw new IllegalArgumentException("missed adjustment dpi");
break;
case image:
isFlag = arguments.contains(adjustmentBackupArgument);
break;
}
helper.execute(isFlag, AdjustmentType.pdf.equals(type));
// update the page ids
loadPageIds(new File(projectFolder));
});
}
/**
* Performs the workflow preprocessing.
*
* @param processConfiguration The process configuration.
* @since 1.8
*/
private void preprocessing(WorkflowConfiguration.ProcessConfiguration processConfiguration) {
final PreprocessingHelper helper;
final ProcessWorker worker;
synchronized (processWorkers) {
if (isCanceled)
return;
helper = new PreprocessingHelper(projectFolder, configuration.getType().name());
worker = new ProcessWorker(processConfiguration, null, new ProcessWrapper() {
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#getHandler()
*/
@Override
public ProcessHandler getHandler() {
return helper.getProcessHandler();
}
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#getProgress()
*/
@Override
public float getProgress() {
return helper.getProgress() / 100F;
}
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#cancelProcess()
*/
@Override
public void cancelProcess() {
try {
helper.cancelProcess();
} catch (Exception e) {
// Nothing to do
}
}
});
processWorkers.add(worker);
}
execute(worker, () -> helper.execute(worker.getAvailablePageIds(), processConfiguration.getArguments()));
}
/**
* Performs the workflow dummy segmentation.
*
* @param processConfiguration The process configuration.
* @since 1.8
*/
private void segmentationDummy(WorkflowConfiguration.ProcessConfiguration processConfiguration) {
final SegmentationDummyHelper helper;
final ProcessWorker worker;
synchronized (processWorkers) {
if (isCanceled)
return;
helper = new SegmentationDummyHelper(projectFolder, configuration.getType().name());
worker = new ProcessWorker(processConfiguration, (id) -> processStateCollector.preprocessingState(id),
new ProcessWrapper() {
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#getHandler()
*/
@Override
public ProcessHandler getHandler() {
return null;
}
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#getProgress()
*/
@Override
public float getProgress() {
return helper.getProgress() / 100F;
}
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#cancelProcess()
*/
@Override
public void cancelProcess() {
try {
helper.cancelProcess();
} catch (Exception e) {
// Nothing to do
}
}
});
processWorkers.add(worker);
}
execute(worker, () -> helper.execute(worker.getAvailablePageIds(), segmentationImageType));
}
/**
* Performs the workflow line segmentation.
*
* @param processConfiguration The process configuration.
* @since 1.8
*/
private void lineSegmentation(WorkflowConfiguration.ProcessConfiguration processConfiguration) {
final LineSegmentationHelper helper;
final ProcessWorker worker;
synchronized (processWorkers) {
if (isCanceled)
return;
helper = new LineSegmentationHelper(projectFolder, configuration.getType().name());
worker = new ProcessWorker(processConfiguration, (id) -> processStateCollector.segmentationState(id),
new ProcessWrapper() {
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#getHandler()
*/
@Override
public ProcessHandler getHandler() {
return helper.getProcessHandler();
}
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#getProgress()
*/
@Override
public float getProgress() {
try {
int progress = helper.getProgress();
return progress < 0 ? 0 : progress / 100F;
} catch (Exception e) {
return 0;
}
}
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#cancelProcess()
*/
@Override
public void cancelProcess() {
try {
helper.cancelProcess();
} catch (Exception e) {
// Nothing to do
}
}
});
processWorkers.add(worker);
}
execute(worker, () -> helper.execute(worker.getAvailablePageIds(), processConfiguration.getArguments()));
}
/**
* Performs the workflow recognition.
*
* @param processConfiguration The process configuration.
* @since 1.8
*/
private void recognition(WorkflowConfiguration.ProcessConfiguration processConfiguration) {
final RecognitionHelper helper;
final ProcessWorker worker;
synchronized (processWorkers) {
if (isCanceled)
return;
helper = new RecognitionHelper(projectFolder, configuration.getType().name());
worker = new ProcessWorker(processConfiguration, (id) -> processStateCollector.lineSegmentationState(id),
new ProcessWrapper() {
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#getHandler()
*/
@Override
public ProcessHandler getHandler() {
return helper.getProcessHandler();
}
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#getProgress()
*/
@Override
public float getProgress() {
try {
int progress = helper.getProgress();
return progress < 0 ? 0 : progress / 100F;
} catch (Exception e) {
return 0;
}
}
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#cancelProcess()
*/
@Override
public void cancelProcess() {
try {
helper.cancelProcess();
} catch (Exception e) {
// Nothing to do
}
}
});
processWorkers.add(worker);
}
execute(worker, () -> {
TreeMap<String, String> models = RecognitionHelper.listModels();
/*
* Set the models in format required by the recognition helper
*/
List<String> arguments = new ArrayList<>();
StringBuffer buffer = null;
for (String argument : processConfiguration.getArguments()) {
/*
* If the buffer is non null, then we are currently scanning models.
*/
if (buffer != null) {
// Ends model list
if (argument.startsWith("--")) {
if (buffer.length() == 0)
throw new IllegalArgumentException("the argmuent --checkpoint requires at least one model");
arguments.add(buffer.toString());
buffer = null;
} else {
String model = models.get(argument);
if (model == null)
throw new IllegalArgumentException("unknown model \"" + argument + "\"");
if (buffer.length() > 0)
buffer.append(" ");
buffer.append(model);
}
}
if (buffer == null) {
arguments.add(argument);
if ("--checkpoint".equals(argument))
buffer = new StringBuffer();
}
}
if (buffer != null) {
if (buffer.length() == 0)
throw new IllegalArgumentException("the argmuent --checkpoint requires at least one model");
arguments.add(buffer.toString());
}
helper.execute(worker.getAvailablePageIds(), arguments);
});
}
/**
* Performs the workflow result generation.
*
* @param processConfiguration The process configuration.
* @since 1.8
*/
private void resultGeneration(WorkflowConfiguration.ProcessConfiguration processConfiguration) {
final ResultGenerationHelper helper;
final ProcessWorker worker;
synchronized (processWorkers) {
if (isCanceled)
return;
helper = new ResultGenerationHelper(projectFolder, configuration.getType().name());
// only the txt type uses a validor, the xml take all pages with extension xml
worker = new ProcessWorker(processConfiguration, (id) -> processStateCollector.recognitionState(id),
new ProcessWrapper() {
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#getHandler()
*/
@Override
public ProcessHandler getHandler() {
return null;
}
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#getProgress()
*/
@Override
public float getProgress() {
try {
int progress = helper.getProgress();
return progress < 0 ? 0 : progress / 100F;
} catch (Exception e) {
return 0;
}
}
/*
* (non-Javadoc)
*
* @see de.uniwue.batch.BatchWorkflow.ProcessWrapper#cancelProcess()
*/
@Override
public void cancelProcess() {
try {
helper.cancelProcess();
} catch (Exception e) {
// Nothing to do
}
}
});
processWorkers.add(worker);
}
execute(worker, () -> {
List<String> arguments = processConfiguration.getArguments();
ResultGenerationType type;
int index = arguments.indexOf(ResultGenerationType.argument);
if (index >= 0 && index < arguments.size() - 1)
try {
type = ResultGenerationType.valueOf(arguments.get(index + 1));
} catch (Exception e) {
throw new IllegalArgumentException(
"unknown result generation type \"" + arguments.get(index + 1) + "\"");
}
else
throw new IllegalArgumentException("missed result generation type");
// strategy and preserve empty lines are only required for txt type
ResultGenerationStrategy strategy = ResultGenerationStrategy.defaultStrategy;
boolean isPreserveEmptyLines = false;
boolean isAddPageDelimiter = true;
if (ResultGenerationType.txt.equals(type)) {
index = arguments.indexOf(ResultGenerationStrategy.argument);
if (index >= 0) {
if (index < arguments.size() - 1)
try {
strategy = ResultGenerationStrategy.valueOf(arguments.get(index + 1));
} catch (Exception e) {
throw new IllegalArgumentException(
"unknown result generation strategy \"" + arguments.get(index + 1) + "\"");
}
else
throw new IllegalArgumentException("missed result generation strategy");
}
isPreserveEmptyLines = arguments.contains(resultGenerationPreserveEmptyLinesArgument);
isAddPageDelimiter = arguments.contains(resultGenerationAddPageDelimiter);
}
helper.executeProcess(worker.getAvailablePageIds(), type.name(), strategy.getProcessName(),
isPreserveEmptyLines, isAddPageDelimiter, "###");
});
}
/**
* Executes the process.
*
* @author Herbert Baier
* @version 1.0
* @since 1.8
*/
@FunctionalInterface
private interface ExecuteProcess {
/**
* Executes the process.
*
* @throws Exception Throws on execution troubles.
* @since 1.8
*/
public void execute() throws Exception;
}
/**
* Executes the process for given worker.
*
* @param worker The process worker.
* @param executeProcess The process to execute.
* @since 1.8
*/
private void execute(ProcessWorker worker, ExecuteProcess executeProcess) {
try {
executeProcess.execute();
if (isCanceled)
worker.cancel();
else if (worker.getWrapper().getProgress() < 1F) {
worker.finish(true);
worker.setMessage("only " + (int) (worker.getWrapper().getProgress() * 100F)
+ "% of the complete process was performed");
state = State.interrupted;
} else
worker.finish();
} catch (Exception e) {
state = State.interrupted;
worker.setMessage(e.getMessage());
worker.finish(true);
e.printStackTrace();
}
}
/**
* Defines callback.
*
* @author Herbert Baier
* @version 1.0
* @since 1.8
*/
@FunctionalInterface
public interface Callback {
/**
* Callback method when the batch workflow finishes.
*
* @param batchWorkflow The batch workflow that finish.
* @since 1.8
*/
public void finish(BatchWorkflow batchWorkflow);
}
/**
* Defines process page validators
*
* @author Herbert Baier
* @version 1.0
* @since 1.8
*/
@FunctionalInterface
private interface ProcessPageValidator {
/**
* Returns true if the page is available for the process.
*
* @param id The page id.
* @return True if the page is available for the process.
* @since 1.8
*/
public boolean isAvailable(String id);
}
/**
* Defines process wrappers.
*
* @author Herbert Baier
* @version 1.0
* @since 1.8
*/
public interface ProcessWrapper {
/**
* Returns the handler. Null if not available.
*
* @return The handler.
* @since 1.8
*/
public ProcessHandler getHandler();
/**
* Returns the progress. This is a value between 0 and 1 inclusive.
*
* @return The progress.
* @since 1.8
*/
public float getProgress();
/**
* Cancels the process.
*
* @since 1.8
*/
public void cancelProcess();
}
/**
* Defines process workers.
*
* @author Herbert Baier
* @version 1.0
* @since 1.8
*/
public class ProcessWorker {
/**
* The configuration.
*/
private final WorkflowConfiguration.ProcessConfiguration configuration;
/**
* The available page ids.
*/
private final List<String> availablePageIds = new ArrayList<>();
/**
* The wrapper.
*/
private final ProcessWrapper wrapper;
/**
* The process begin time.
*/
private final Date begin = new Date();
/**
* The process end time. Null if running.
*/
private Date end = null;
/**
* The message.
*/
private String message = null;
/**
* True if process worker was canceled.
*/
private boolean isCanceled = false;
/**
* True if there exist troubles performing process worker.
*/
private boolean isTrouble = false;
/**
* Creates a process worker.
*
* @param configuration The configuration.
* @param validator The page validator.
* @param wrapper The wrapper.
* @since 1.8
*/
public ProcessWorker(WorkflowConfiguration.ProcessConfiguration configuration, ProcessPageValidator validator,
ProcessWrapper wrapper) {
super();
this.configuration = configuration;
this.wrapper = wrapper;
for (String pageId : BatchWorkflow.this.getPageIds())
if (validator == null || validator.isAvailable(pageId))
availablePageIds.add(pageId);
}
/**
* Returns the configuration.
*
* @return The configuration.
* @since 1.8
*/
public WorkflowConfiguration.ProcessConfiguration getConfiguration() {
return configuration;
}
/**
* Returns the available page ids.
*
* @return The available page ids.
* @since 1.8
*/
public List<String> getAvailablePageIds() {
return availablePageIds;
}
/**
* Returns the wrapper.
*
* @return The wrapper.
* @since 1.8
*/
public ProcessWrapper getWrapper() {
return wrapper;
}
/**
* Returns the process begin time.
*
* @return The process begin time.
* @since 1.8
*/
public Date getBegin() {
return begin;
}
/**
* Returns the process end time. Null if running.
*
* @return The process end time.
* @since 1.8
*/
public Date getEnd() {
return end;
}
/**
* Returns true if there exist troubles performing this worker.
*
* @return True if there exist troubles performing this worker.
* @since 1.8
*/
public boolean isTrouble() {
return isTrouble;
}
/**
* Returns true if process worker was canceled.
*
* @return True if process worker was canceled.
* @since 1.8
*/
public boolean isCanceled() {
return isCanceled;
}
/**
* Cancels the process worker.
*
* @since 1.8
*/
public void cancel() {
isCanceled = true;
finish();
}
/**
* Finishes the process worker without troubles.
*
* @since 1.8
*/
public void finish() {
finish(false);
}
/**
* Finishes the process worker.
*
* @param isTrouble True if there exist troubles performing this worker.
* @since 1.8
*/
public void finish(boolean isTrouble) {
if (isRunning()) {
end = new Date();
this.isTrouble = isTrouble;
}
}
/**
* Returns true if the process worker is running.
*
* @return True if the process worker is running.
* @since 1.8
*/
public boolean isRunning() {
return end == null;
}
/**
* Returns the message.
*
* @return The message.
* @since 1.8
*/
public String getMessage() {
return message;
}
/**
* Set the message.
*
* @param message The message to set.
* @since 1.8
*/
public void setMessage(String message) {
this.message = message;
}
}
}
| 11,992
|
https://github.com/radtriste-bot-account/kogito-cloud-operator/blob/master/pkg/controller/kogitoapp/resource/infinispan.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
kogito-cloud-operator
|
radtriste-bot-account
|
Go
|
Code
| 253
| 934
|
// Copyright 2020 Red Hat, Inc. and/or its affiliates
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package resource
import (
"github.com/kiegroup/kogito-cloud-operator/pkg/apis/app/v1alpha1"
"github.com/kiegroup/kogito-cloud-operator/pkg/client"
"github.com/kiegroup/kogito-cloud-operator/pkg/infrastructure"
"github.com/kiegroup/kogito-cloud-operator/pkg/infrastructure/services"
corev1 "k8s.io/api/core/v1"
)
const (
defaultInfinispanSaslMechanism = v1alpha1.SASLPlain
)
// CreateInfinispanProperties creates Infinispan properties by reading information from the KogitoInfra
func CreateInfinispanProperties(cli *client.Client, kogitoInfra *v1alpha1.KogitoInfra, kogitoApp *v1alpha1.KogitoApp) (envs []corev1.EnvVar, appProps map[string]string, err error) {
if kogitoApp != nil &&
(kogitoInfra != nil &&
(len(kogitoInfra.Status.Infinispan.Name) > 0 ||
len(kogitoInfra.Status.Infinispan.Service) > 0)) {
uri, err := infrastructure.GetInfinispanServiceURI(cli, kogitoInfra)
if err != nil {
return nil, nil, err
}
secret, err := infrastructure.GetInfinispanCredentialsSecret(cli, kogitoInfra)
if err != nil {
return nil, nil, err
}
appProps = map[string]string{}
// inject credentials
vars := services.PropertiesInfinispanQuarkus
if kogitoApp.Spec.Runtime == v1alpha1.SpringbootRuntimeType {
vars = services.PropertiesInfinispanSpring
}
appProps[vars[services.AppPropInfinispanUseAuth]] = "true"
appProps[vars[services.AppPropInfinispanServerList]] = uri
appProps[vars[services.AppPropInfinispanSaslMechanism]] = string(defaultInfinispanSaslMechanism)
envs = append(envs, corev1.EnvVar{Name: vars[services.EnvVarInfinispanUser], ValueFrom: &corev1.EnvVarSource{
SecretKeyRef: &corev1.SecretKeySelector{
LocalObjectReference: corev1.LocalObjectReference{Name: secret.Name},
Key: infrastructure.InfinispanSecretUsernameKey,
},
}})
envs = append(envs, corev1.EnvVar{Name: vars[services.EnvVarInfinispanPassword], ValueFrom: &corev1.EnvVarSource{
SecretKeyRef: &corev1.SecretKeySelector{
LocalObjectReference: corev1.LocalObjectReference{Name: secret.Name},
Key: infrastructure.InfinispanSecretPasswordKey,
},
}})
}
return envs, appProps, nil
}
| 24,129
|
https://github.com/flaviogf/courses/blob/master/udemy/curso_python_com_kivy/src/006_kivylanguage/estudo1.kv
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
courses
|
flaviogf
|
Kvlang
|
Code
| 11
| 70
|
<MeuBotao@Button>:
text: "botao"
<Tela1@BoxLayout>:
MeuBotao:
MeuBotao:
BoxLayout:
Tela1:
Tela1:
orientation: "vertical"
| 48,631
|
https://github.com/abdeltiflouardi/CMSsf/blob/master/src/App/WebBundle/Resources/views/Partials/pagination.html.twig
|
Github Open Source
|
Open Source
|
MIT
| null |
CMSsf
|
abdeltiflouardi
|
Twig
|
Code
| 3
| 13
|
{{ knp_pagination_render(posts) }}
| 14,324
|
https://github.com/simplifiedrobot/git/blob/master/mobilesafe/src/utils/dao_addressToast.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
git
|
simplifiedrobot
|
Java
|
Code
| 20
| 88
|
package utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.example.mobilesafe.R;
public class dao_addressToast{
}
| 39,510
|
https://github.com/zitelog/mrsign/blob/master/serverstore.go
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
mrsign
|
zitelog
|
Go
|
Code
| 266
| 458
|
/*
* File: serverStore.go
* Project: mrsign
* Created Date: Tuesday, October 19th 2021, 12:16:54 pm
* Authors: Marcello Russo, Fabio Zito
* -----
* Last Modified:
* Modified By:
* -----
* MIT License
*
* Copyright (c) 2021 MR&&Z
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* -----
* HISTORY:
* Date By Comments
* ---------- --- ----------------------------------------------------------
*/
package main
const ServerStoreFile = "zserver.store"
type ServerStore struct {
Key string `json:"key"`
User string `json:"user"`
HostName string `json:"hostName"`
Path string `json:"path"`
Timestamp string `json:"timestamp"`
ServerChallenge string `json:"serverChallenge"`
Result []byte `json:"result"`
}
| 816
|
https://github.com/maxmind/GeoIP2-python/blob/master/tests/models_test.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
GeoIP2-python
|
maxmind
|
Python
|
Code
| 996
| 4,518
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
from typing import Dict
import unittest
sys.path.append("..")
import geoip2.models
class TestModels(unittest.TestCase):
def test_insights_full(self) -> None:
raw = {
"city": {
"confidence": 76,
"geoname_id": 9876,
"names": {"en": "Minneapolis"},
},
"continent": {
"code": "NA",
"geoname_id": 42,
"names": {"en": "North America"},
},
"country": {
"confidence": 99,
"geoname_id": 1,
"iso_code": "US",
"names": {"en": "United States of America"},
},
"location": {
"average_income": 24626,
"accuracy_radius": 1500,
"latitude": 44.98,
"longitude": 93.2636,
"metro_code": 765,
"population_density": 1341,
"time_zone": "America/Chicago",
},
"postal": {
"code": "55401",
"confidence": 33,
},
"subdivisions": [
{
"confidence": 88,
"geoname_id": 574635,
"iso_code": "MN",
"names": {"en": "Minnesota"},
},
{
"geoname_id": 123,
"iso_code": "HP",
"names": {"en": "Hennepin"},
},
],
"registered_country": {
"geoname_id": 2,
"iso_code": "CA",
"names": {"en": "Canada"},
},
"represented_country": {
"geoname_id": 3,
"is_in_european_union": True,
"iso_code": "GB",
"names": {"en": "United Kingdom"},
"type": "military",
},
"traits": {
"autonomous_system_number": 1234,
"autonomous_system_organization": "AS Organization",
"domain": "example.com",
"ip_address": "1.2.3.4",
"is_anonymous": True,
"is_anonymous_proxy": True,
"is_anonymous_vpn": True,
"is_hosting_provider": True,
"is_public_proxy": True,
"is_residential_proxy": True,
"is_satellite_provider": True,
"is_tor_exit_node": True,
"isp": "Comcast",
"network_speed": "cable/DSL",
"organization": "Blorg",
"static_ip_score": 1.3,
"user_count": 2,
"user_type": "college",
},
}
model = geoip2.models.Insights(raw)
self.assertEqual(
type(model), geoip2.models.Insights, "geoip2.models.Insights object"
)
self.assertEqual(
type(model.city), geoip2.records.City, "geoip2.records.City object"
)
self.assertEqual(
type(model.continent),
geoip2.records.Continent,
"geoip2.records.Continent object",
)
self.assertEqual(
type(model.country), geoip2.records.Country, "geoip2.records.Country object"
)
self.assertEqual(
type(model.registered_country),
geoip2.records.Country,
"geoip2.records.Country object",
)
self.assertEqual(
type(model.represented_country),
geoip2.records.RepresentedCountry,
"geoip2.records.RepresentedCountry object",
)
self.assertEqual(
type(model.location),
geoip2.records.Location,
"geoip2.records.Location object",
)
self.assertEqual(
type(model.subdivisions[0]),
geoip2.records.Subdivision,
"geoip2.records.Subdivision object",
)
self.assertEqual(
type(model.traits), geoip2.records.Traits, "geoip2.records.Traits object"
)
self.assertEqual(model.raw, raw, "raw method returns raw input")
self.assertEqual(
model.subdivisions[0].iso_code, "MN", "div 1 has correct iso_code"
)
self.assertEqual(
model.subdivisions[0].confidence, 88, "div 1 has correct confidence"
)
self.assertEqual(
model.subdivisions[0].geoname_id, 574635, "div 1 has correct geoname_id"
)
self.assertEqual(
model.subdivisions[0].names, {"en": "Minnesota"}, "div 1 names are correct"
)
self.assertEqual(
model.subdivisions[1].name, "Hennepin", "div 2 has correct name"
)
self.assertEqual(
model.subdivisions.most_specific.iso_code,
"HP",
"subdivisions.most_specific returns HP",
)
self.assertEqual(
model.represented_country.name,
"United Kingdom",
"represented_country name is correct",
)
self.assertEqual(
model.represented_country.type,
"military",
"represented_country type is correct",
)
self.assertEqual(model.location.average_income, 24626, "correct average_income")
self.assertEqual(model.location.latitude, 44.98, "correct latitude")
self.assertEqual(model.location.longitude, 93.2636, "correct longitude")
self.assertEqual(model.location.metro_code, 765, "correct metro_code")
self.assertEqual(
model.location.population_density, 1341, "correct population_density"
)
self.assertRegex(
str(model),
r"^geoip2.models.Insights\(\{.*geoname_id.*\}, \[.*en.*\]\)",
"Insights str representation looks reasonable",
)
self.assertEqual(model, eval(repr(model)), "Insights repr can be eval'd")
self.assertRegex(
str(model.location),
r"^geoip2.records.Location\(.*longitude=.*\)",
"Location str representation is reasonable",
)
self.assertEqual(
model.location, eval(repr(model.location)), "Location repr can be eval'd"
)
self.assertIs(model.country.is_in_european_union, False)
self.assertIs(model.registered_country.is_in_european_union, False)
self.assertIs(model.represented_country.is_in_european_union, True)
self.assertIs(model.traits.is_anonymous, True)
self.assertIs(model.traits.is_anonymous_proxy, True)
self.assertIs(model.traits.is_anonymous_vpn, True)
self.assertIs(model.traits.is_hosting_provider, True)
self.assertIs(model.traits.is_public_proxy, True)
self.assertIs(model.traits.is_residential_proxy, True)
self.assertIs(model.traits.is_satellite_provider, True)
self.assertIs(model.traits.is_tor_exit_node, True)
self.assertEqual(model.traits.user_count, 2)
self.assertEqual(model.traits.static_ip_score, 1.3)
def test_insights_min(self) -> None:
model = geoip2.models.Insights({"traits": {"ip_address": "5.6.7.8"}})
self.assertEqual(
type(model), geoip2.models.Insights, "geoip2.models.Insights object"
)
self.assertEqual(
type(model.city), geoip2.records.City, "geoip2.records.City object"
)
self.assertEqual(
type(model.continent),
geoip2.records.Continent,
"geoip2.records.Continent object",
)
self.assertEqual(
type(model.country), geoip2.records.Country, "geoip2.records.Country object"
)
self.assertEqual(
type(model.registered_country),
geoip2.records.Country,
"geoip2.records.Country object",
)
self.assertEqual(
type(model.location),
geoip2.records.Location,
"geoip2.records.Location object",
)
self.assertEqual(
type(model.traits), geoip2.records.Traits, "geoip2.records.Traits object"
)
self.assertEqual(
type(model.subdivisions.most_specific),
geoip2.records.Subdivision,
"geoip2.records.Subdivision object returned even"
"when none are available.",
)
self.assertEqual(
model.subdivisions.most_specific.names, {}, "Empty names hash returned"
)
def test_city_full(self) -> None:
raw = {
"continent": {
"code": "NA",
"geoname_id": 42,
"names": {"en": "North America"},
},
"country": {
"geoname_id": 1,
"iso_code": "US",
"names": {"en": "United States of America"},
},
"registered_country": {
"geoname_id": 2,
"iso_code": "CA",
"names": {"en": "Canada"},
},
"traits": {
"ip_address": "1.2.3.4",
"is_satellite_provider": True,
},
}
model = geoip2.models.City(raw)
self.assertEqual(type(model), geoip2.models.City, "geoip2.models.City object")
self.assertEqual(
type(model.city), geoip2.records.City, "geoip2.records.City object"
)
self.assertEqual(
type(model.continent),
geoip2.records.Continent,
"geoip2.records.Continent object",
)
self.assertEqual(
type(model.country), geoip2.records.Country, "geoip2.records.Country object"
)
self.assertEqual(
type(model.registered_country),
geoip2.records.Country,
"geoip2.records.Country object",
)
self.assertEqual(
type(model.location),
geoip2.records.Location,
"geoip2.records.Location object",
)
self.assertEqual(
type(model.traits), geoip2.records.Traits, "geoip2.records.Traits object"
)
self.assertEqual(model.raw, raw, "raw method returns raw input")
self.assertEqual(model.continent.geoname_id, 42, "continent geoname_id is 42")
self.assertEqual(model.continent.code, "NA", "continent code is NA")
self.assertEqual(
model.continent.names, {"en": "North America"}, "continent names is correct"
)
self.assertEqual(
model.continent.name, "North America", "continent name is correct"
)
self.assertEqual(model.country.geoname_id, 1, "country geoname_id is 1")
self.assertEqual(model.country.iso_code, "US", "country iso_code is US")
self.assertEqual(
model.country.names,
{"en": "United States of America"},
"country names is correct",
)
self.assertEqual(
model.country.name, "United States of America", "country name is correct"
)
self.assertEqual(model.country.confidence, None, "country confidence is None")
self.assertEqual(
model.registered_country.iso_code, "CA", "registered_country iso_code is CA"
)
self.assertEqual(
model.registered_country.names,
{"en": "Canada"},
"registered_country names is correct",
)
self.assertEqual(
model.registered_country.name,
"Canada",
"registered_country name is correct",
)
self.assertEqual(
model.traits.is_anonymous_proxy,
False,
"traits is_anonymous_proxy returns False by default",
)
self.assertEqual(
model.traits.is_satellite_provider,
True,
"traits is_setellite_provider is True",
)
self.assertEqual(model.raw, raw, "raw method produces raw output")
self.assertRegex(
str(model), r"^geoip2.models.City\(\{.*geoname_id.*\}, \[.*en.*\]\)"
)
self.assertFalse(model == True, "__eq__ does not blow up on weird input")
def test_unknown_keys(self) -> None:
model = geoip2.models.City(
{
"city": {"invalid": 0},
"continent": {
"invalid": 0,
"names": {"invalid": 0},
},
"country": {
"invalid": 0,
"names": {"invalid": 0},
},
"location": {"invalid": 0},
"postal": {"invalid": 0},
"subdivisions": [
{
"invalid": 0,
"names": {
"invalid": 0,
},
},
],
"registered_country": {
"invalid": 0,
"names": {
"invalid": 0,
},
},
"represented_country": {
"invalid": 0,
"names": {
"invalid": 0,
},
},
"traits": {"ip_address": "1.2.3.4", "invalid": "blah"},
"unk_base": {"blah": 1},
}
)
with self.assertRaises(AttributeError):
model.unk_base # type: ignore
with self.assertRaises(AttributeError):
model.traits.invalid # type: ignore
self.assertEqual(model.traits.ip_address, "1.2.3.4", "correct ip")
class TestNames(unittest.TestCase):
raw: Dict = {
"continent": {
"code": "NA",
"geoname_id": 42,
"names": {
"de": "Nordamerika",
"en": "North America",
"es": "América del Norte",
"ja": "北アメリカ",
"pt-BR": "América do Norte",
"ru": "Северная Америка",
"zh-CN": "北美洲",
},
},
"country": {
"geoname_id": 1,
"iso_code": "US",
"names": {
"en": "United States of America",
"fr": "États-Unis",
"zh-CN": "美国",
},
},
"traits": {
"ip_address": "1.2.3.4",
},
}
def test_names(self) -> None:
model = geoip2.models.Country(self.raw, locales=["sq", "ar"])
self.assertEqual(
model.continent.names,
self.raw["continent"]["names"],
"Correct names dict for continent",
)
self.assertEqual(
model.country.names,
self.raw["country"]["names"],
"Correct names dict for country",
)
def test_three_locales(self) -> None:
model = geoip2.models.Country(self.raw, locales=["fr", "zh-CN", "en"])
self.assertEqual(
model.continent.name,
"北美洲",
"continent name is in Chinese (no French available)",
)
self.assertEqual(model.country.name, "États-Unis", "country name is in French")
def test_two_locales(self) -> None:
model = geoip2.models.Country(self.raw, locales=["ak", "fr"])
self.assertEqual(
model.continent.name,
None,
"continent name is undef (no Akan or French " "available)",
)
self.assertEqual(model.country.name, "États-Unis", "country name is in French")
def test_unknown_locale(self) -> None:
model = geoip2.models.Country(self.raw, locales=["aa"])
self.assertEqual(
model.continent.name, None, "continent name is undef (no Afar available)"
)
self.assertEqual(
model.country.name, None, "country name is in None (no Afar available)"
)
def test_german(self) -> None:
model = geoip2.models.Country(self.raw, locales=["de"])
self.assertEqual(
model.continent.name, "Nordamerika", "Correct german name for continent"
)
if __name__ == "__main__":
unittest.main()
| 44,917
|
https://github.com/znuznu/randemon/blob/master/api/src/domain/models/generation.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
randemon
|
znuznu
|
TypeScript
|
Code
| 31
| 69
|
enum Generation {
I = 'I',
II = 'II',
III = 'III',
IV = 'IV',
V = 'V',
VI = 'VI',
VII = 'VII',
VIII = 'VIII'
}
export default Generation;
| 32,208
|
https://github.com/rgr19/MpiNonBlockingProtocol/blob/master/extern_libs/tbb-2019-u4/html/a00169.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
MpiNonBlockingProtocol
|
rgr19
|
JavaScript
|
Code
| 225
| 1,709
|
var a00169 =
[
[ "helper", "a00331.html", "a00331" ],
[ "internal_segments_table", "a00388.html", "a00388" ],
[ "segment_allocated", "a00692.html", null ],
[ "segment_allocation_failed", "a00693.html", null ],
[ "segment_not_used", "a00694.html", null ],
[ "segment_t", "a00696.html", "a00696" ],
[ "segment_value_t", "a00697.html", "a00697" ],
[ "internal_array_op1", "a00169.html#ad7c52f713ea60b5771a0de1bdde7e7a9", null ],
[ "internal_array_op2", "a00169.html#a4da4a55fd0545d1b669ca5cc49cd5308", null ],
[ "segment_index_t", "a00169.html#a537b5a463d9131c3777e71d05fa3a81b", null ],
[ "size_type", "a00169.html#a0c92dcfc62079e447c41d2b772cdd133", null ],
[ "default_initial_segments", "a00169.html#abbb8fe2e97a84e53773124c2c0616977affd2c6f15c2e2b031fb7846d15a1fbc4", null ],
[ "pointers_per_short_table", "a00169.html#abbb8fe2e97a84e53773124c2c0616977a55596bdb0c771a285e87ab3645b78e23", null ],
[ "pointers_per_long_table", "a00169.html#abbb8fe2e97a84e53773124c2c0616977a66806961c962fd17c06f0a7d8b7fa6a9", null ],
[ "concurrent_vector_base_v3", "a00169.html#a76e573e95d96877edbac7c02eaa08601", null ],
[ "~concurrent_vector_base_v3", "a00169.html#ad01734e9de5b19fa4521cae624508b1a", null ],
[ "internal_assign", "a00169.html#a2de722203d5e6cb6a18075e451417664", null ],
[ "internal_capacity", "a00169.html#aa358b781e8b59f324feba96f76f05757", null ],
[ "internal_clear", "a00169.html#aa8ab12f2be0114336e7bb0c291e611a2", null ],
[ "internal_compact", "a00169.html#a01aa29982c8e7708d413f1d30c5953e6", null ],
[ "internal_copy", "a00169.html#af0dff324e332e7b4df6dd933f0af0fb2", null ],
[ "internal_grow", "a00169.html#a62c8c2a7341dc8ea7a612341e27cb24e", null ],
[ "internal_grow_by", "a00169.html#a9334b74e81786c565f413134cf28b559", null ],
[ "internal_grow_to_at_least", "a00169.html#ae9d25fbe67e3ac09ab5c05bfb9963854", null ],
[ "internal_grow_to_at_least_with_result", "a00169.html#a558417c6b3314944dfa6182db71841e3", null ],
[ "internal_push_back", "a00169.html#a4bd7a3ced949af1191abe1ef5786f4f3", null ],
[ "internal_reserve", "a00169.html#ae07413aa0de51aeb5ec1ec35bbc0095f", null ],
[ "internal_resize", "a00169.html#a57151343a7f7c09dfc70bad5f149c417", null ],
[ "internal_swap", "a00169.html#a5913c17dffae92a75f8c1c3caaa7ecf6", null ],
[ "internal_throw_exception", "a00169.html#a20bd255e3a4b2baa7ed51f6fe7ba0ece", null ],
[ "is_first_element_in_segment", "a00169.html#a2b3d3fb0f6d82bccdce60828b271744b", null ],
[ "segment_base", "a00169.html#a95ddd84ac42ff56a1b390cc0eec513ea", null ],
[ "segment_base_index_of", "a00169.html#ac55fb14b17ddb920eaf50596446b9963", null ],
[ "segment_index_of", "a00169.html#a151f683d14625c45aeccddba8ee72109", null ],
[ "segment_size", "a00169.html#a68c3e198aae8f0a1128cf629c740988b", null ],
[ "enforce_segment_allocated", "a00169.html#ad9829790b45c37c2af2ea85c1c804eb1", null ],
[ "helper", "a00169.html#aabac8c5bc6a911e547e967a70f3fd282", null ],
[ "swap", "a00169.html#a3c2b97b5b407bea00c3d8c5829066542", null ],
[ "vector_iterator", "a00169.html#a212fe2fa401ecddf19d71155c214e9f9", null ],
[ "my_early_size", "a00169.html#a1f3773deae9ac723547700419690b043", null ],
[ "my_first_block", "a00169.html#ad9d3103757a1ef6a70a597d6b174d5c7", null ],
[ "my_segment", "a00169.html#acc5232333cf13be4c77bdfe7282f7e14", null ],
[ "my_storage", "a00169.html#adb52d25144f5cecc228e171f476cf91d", null ],
[ "vector_allocator_ptr", "a00169.html#a21eea9a9f25b8d2345f9c5dd112ab7bd", null ]
];
| 47,408
|
https://github.com/nicolaferraro/fanta-ng/blob/master/services/fanta-league/src/main/java/net/fantamiglia/league/core/LeagueService.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
fanta-ng
|
nicolaferraro
|
Java
|
Code
| 67
| 260
|
package net.fantamiglia.league.core;
import org.apache.camel.Body;
import org.apache.camel.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class LeagueService {
@Autowired
private LeagueRepository repo;
public League insertLeague(League league) {
repo.insert(league);
return league;
}
public League findOneLeague(String id) {
return repo.findOne(id);
}
public League saveLeague(String id, League league) {
league.setId(id);
repo.save(league);
return league;
}
public List<League> findAllLeagues() {
return repo.findAll();
}
public boolean deleteLeague(String leagueId) {
repo.delete(leagueId);
return true;
}
}
| 19,240
|
https://github.com/splitio/qos-runner/blob/master/src/main/java/io/split/testrunner/TestRunner.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
qos-runner
|
splitio
|
Java
|
Code
| 367
| 1,492
|
package io.split.testrunner;
import com.google.common.collect.Lists;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import io.split.qos.server.QOSServerApplication;
import io.split.qos.server.QOSServerConfiguration;
import io.split.qos.server.QOSServerState;
import io.split.qos.server.failcondition.FailWith;
import io.split.qos.server.failcondition.SimpleFailCondition;
import io.split.qos.server.integrations.datadog.DatadogBroadcaster;
import io.split.qos.server.integrations.pagerduty.PagerDutyBroadcaster;
import io.split.qos.server.integrations.slack.SlackSessionProvider;
import io.split.qos.server.modules.QOSCommonModule;
import io.split.qos.server.modules.QOSFailWithModule;
import io.split.qos.server.stories.QOSStories;
import io.split.testrunner.guice.ExtraModules;
import io.split.testrunner.guice.GuiceModules;
import io.split.testrunner.util.GuiceInitializator;
import io.split.testrunner.util.PropertiesConfig;
import io.split.testrunner.util.TestsFinder;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
/**
* The base class should use @RunWith with this Runners
*/
public class TestRunner extends BlockJUnit4ClassRunner {
private final transient Injector injector;
/**
* Constructor.
*
* @param clazz The in test.
* @throws InitializationError If something goes wrong.
*/
public TestRunner(final Class<?> clazz) throws InitializationError {
super(clazz);
// This is for running tests from the IDE.
// Basically you can set the annotation @QOSConfig and that will be used as properties file.
// If it is not already set, meaning the server didn't set it.
if (GuiceInitializator.getPaths().isEmpty() && clazz.isAnnotationPresent(PropertiesConfig.class)) {
PropertiesConfig annotation = clazz.getAnnotation(PropertiesConfig.class);
Arrays.asList(annotation.value())
.stream()
.forEach(path -> GuiceInitializator.addPath(Paths.get(path)));
}
this.injector = this.createInjectorFor(clazz);
}
@Override
public final Object createTest() throws Exception {
final Object obj = super.createTest();
this.injector.injectMembers(obj);
return obj;
}
/**
* Create a Guice Injector for the class under test.
*
* @return A Guice Injector instance.
* @throws InitializationError If couldn't instantiate a module.
*/
private Injector createInjectorFor(Class<?> theClass) throws InitializationError {
List<AbstractModule> modules = Lists.newArrayList();
for(Class<? extends AbstractModule> clazz : getGuiceModulesFor(theClass)) {
try {
modules.add(clazz.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
for(Class<? extends AbstractModule> clazz : getExtraModulesFor(theClass)) {
try {
modules.add(clazz.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
if (GuiceInitializator.isQos()) {
if (QOSServerApplication.injector != null) {
modules.add(new QOSCommonModule(
QOSServerApplication.injector.getInstance(SlackSessionProvider.class),
QOSServerApplication.injector.getInstance(QOSServerState.class),
QOSServerApplication.injector.getInstance(QOSStories.class),
QOSServerApplication.injector.getInstance(TestsFinder.class),
QOSServerApplication.injector.getInstance(PagerDutyBroadcaster.class),
QOSServerApplication.injector.getInstance(QOSServerConfiguration.class),
QOSServerApplication.injector.getInstance(DatadogBroadcaster.class)));
}
}
modules.add(getFailCondition(theClass));
return Guice.createInjector(modules);
}
private List<Class<? extends AbstractModule>> getGuiceModulesFor(final Class<?> clazz) throws InitializationError {
final GuiceModules annotation = clazz.getAnnotation(GuiceModules.class);
if (annotation == null) {
final String message = String.format("Missing @GuiceModules annotation for unit test '%s'", clazz.getName());
throw new InitializationError(message);
}
return Lists.newArrayList(annotation.value());
}
private List<Class<? extends AbstractModule>> getExtraModulesFor(final Class<?> clazz) throws InitializationError {
ExtraModules annotation = clazz.getAnnotation(ExtraModules.class);
return annotation == null ? Lists.newArrayList() : Lists.newArrayList(annotation.value());
}
private AbstractModule getFailCondition(Class<?> clazz) throws InitializationError {
FailWith failWith = clazz.getAnnotation(FailWith.class);
if (failWith == null) {
return new QOSFailWithModule(SimpleFailCondition.class);
}
return new QOSFailWithModule(failWith.value());
}
}
| 49,143
|
https://github.com/whelantm/VendingMachine/blob/master/CoffeeService/Implementation/CoffeeService.cs
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
VendingMachine
|
whelantm
|
C#
|
Code
| 244
| 847
|
using System;
using System.Collections.Generic;
using Model;
namespace Service
{
public class CoffeeService : ICoffeeService
{
private readonly IApplicationSettingsService _appSettings;
private readonly ICondimentServiceFactory _condimentServiceFactory;
private IList<CoffeeOrder> _orders;
private CoffeeOrder _currentCup;
private IPaymentService _paymentService;
public CoffeeService(ICondimentServiceFactory condimentServiceFactory, IPaymentService paymentService, IApplicationSettingsService appSettings)
{
_condimentServiceFactory = condimentServiceFactory;
_paymentService = paymentService;
_appSettings = appSettings;
_orders = new List<CoffeeOrder>();
}
public void CancelOrder()
{
_orders = new List<CoffeeOrder>();
}
public void CancelCurrentCup()
{
_currentCup = null;
}
public bool CompleteCup()
{
if (_currentCup == null)
return false;
_orders.Add(_currentCup);
_currentCup = null;
return true;
}
public CoffeeOrder ReviewCurrentCup()
{
return _currentCup;
}
public IEnumerable<CoffeeOrder> CurrentOrder()
{
return _orders;
}
public void OrderCoffee(CupSize size)
{
if (_currentCup == null)
{
_currentCup = new CoffeeOrder();
}
_currentCup.Coffee = new Coffee()
{
Size = size,
Price = CoffeePrice(size)
};
}
public bool OrderCondiment(CondimentType condimentType, int quantity)
{
if (_currentCup == null)
return false;
ICondimentService service = _condimentServiceFactory.Create(condimentType);
if (!service.IsCondimentValid(quantity))
{
return false;
}
if (_currentCup.Condiments.ContainsKey(condimentType))
{
_currentCup.Condiments.Remove(condimentType);
}
var condiment = service.OrderCondiment(quantity);
_currentCup.Condiments.Add(condimentType, condiment);
return true;
}
public decimal Total()
{
decimal price = 0;
foreach(var order in _orders)
{
price = price + order.Price();
}
return price;
}
private decimal CoffeePrice(CupSize size)
{
switch(size)
{
case CupSize.Small:
return _appSettings.SmallCoffeePrice;
case CupSize.Medium:
return _appSettings.MediumCoffeePrice;
case CupSize.Large:
return _appSettings.LargeCoffeePrice;
default:
throw new ArgumentOutOfRangeException("Invalid coffee size");
}
}
public PaymentResult CompleteOrderAndPay(decimal payment)
{
var result = _paymentService.RemitPayment(Total(), payment);
if (result.PaymentStatus == PaymentStatus.Success)
{
_orders = new List<CoffeeOrder>();
_currentCup = null;
}
return result;
}
}
}
| 31,402
|
https://github.com/IHTSDO/OTF-Mapping-Service/blob/master/jpa-services/src/main/java/org/ihtsdo/otf/mapping/jpa/algo/ICD10NODownloadAlgorithm.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
OTF-Mapping-Service
|
IHTSDO
|
Java
|
Code
| 618
| 2,203
|
package org.ihtsdo.otf.mapping.jpa.algo;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status.Family;
import org.apache.log4j.Logger;
import org.ihtsdo.otf.mapping.algo.Algorithm;
import org.ihtsdo.otf.mapping.helpers.LocalException;
import org.ihtsdo.otf.mapping.jpa.services.RootServiceJpa;
import org.ihtsdo.otf.mapping.services.helpers.ConfigUtility;
import org.ihtsdo.otf.mapping.services.helpers.ProgressListener;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ICD10NODownloadAlgorithm extends RootServiceJpa implements Algorithm {
/** Listeners. */
private List<ProgressListener> listeners = new ArrayList<>();
/** The request cancel flag. */
private boolean requestCancel = false;
/**
* Instantiates an empty {@link ICD10NODownloadAlgorithm}.
*
* @throws Exception the exception
*/
public ICD10NODownloadAlgorithm() throws Exception {
super();
}
/* see superclass */
@SuppressWarnings("rawtypes")
@Override
public void compute() throws Exception {
Logger.getLogger(getClass()).info("Checking ICD10NO API for recent terminologies");
//Example data from API
// {
// "data": [
// {
// "codeValue": "A00",
// "nameNorwegian": "Kolera (cholera)",
// "compactCode": "A00",
// "parentCode": "A00-A09",
// "active": true,
// "statusChangedDate": "1998-12-31T23:00:00.000+00:00"
// },
// {
// "codeValue": "A00-A09",
// "nameNorwegian": "Infeksiøse tarmsykdommer",
// "compactCode": "A00-A09",
// "parentCode": "I",
// "active": true,
// "statusChangedDate": "1998-12-31T23:00:00.000+00:00"
// },
// ...
// ],
// "succeeded": true,
// "pageNumber": 1,
// "pageSize": 100,
// "totalPages": 216,
// "totalRecords": 21526
// }
// Set up parent-correction map
final Map<String,String> parentCorrectionsMap = new HashMap<>();
final String parentCorrectionsList = ConfigUtility.getConfigProperties().getProperty("icd10noAPI.parentCorrections");
for (final String correctionPair : parentCorrectionsList.split(";")) {
String[] values = correctionPair.split("\\|");
final String fatCode = values[0];
final String correctCode = values[1];
parentCorrectionsMap.put(fatCode, correctCode);
}
// Pull ATC codes from API
final String url = ConfigUtility.getConfigProperties().getProperty("icd10noAPI.url");
final Client client = ClientBuilder.newClient();
final String accept = "*/*";
int pageNumber = 1;
final ObjectMapper mapper = new ObjectMapper();
//housekeeping for creating folder later
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy_MM_dd");
LocalDateTime now = LocalDateTime.now();
String dateFormat = dtf.format(now);
String parentChild = "";
String conceptDesc = "";
Set<String> conceptsMap = new HashSet<String>();
Set<String> parentsMap = new HashSet<String>();
File folder = new File(ConfigUtility.getConfigProperties().getProperty("icd10noAPI.dir") + "/" + dateFormat);
while (true) {
String targetUri = url + "?PageNumber="+pageNumber+"&PageSize=1000";
WebTarget target = client.target(targetUri);
target = client.target(targetUri);
Logger.getLogger(getClass()).info(targetUri);
Response response =
target.request(accept)
.get();
String resultString = response.readEntity(String.class);
if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
// n/a
} else {
throw new LocalException(
"Unexpected terminology server failure. Message = " + resultString);
}
final JsonNode doc = mapper.readTree(resultString);
// create folder if necessary
if(doc.size() > 0 && !folder.exists()) {
folder.mkdir();
}
// get total amount
// Get concepts returned in this call (up to 1000)
for (final JsonNode conceptNode : doc.get("data")) {
JsonNode codeActive = conceptNode.get("active");
//Only load in active codes
if(!codeActive.asText().equals("true")) {
continue;
}
JsonNode icd10noTerm = conceptNode.get("nameNorwegian");
JsonNode icd10noKode = conceptNode.get("codeValue");
JsonNode icd10noParent = conceptNode.get("parentCode");
if(icd10noKode != null && icd10noTerm != null && icd10noParent != null) {
//There are some parent codes specified on the fat server which incorrectly reference non-existent codes.
String icd10noParentKode = icd10noParent.asText();
if(parentCorrectionsMap.containsKey(icd10noParentKode)) {
icd10noParentKode = parentCorrectionsMap.get(icd10noParentKode);
}
//Additionally, the ICD-10 node has itself as its parent, which is incompatible with this tool.
//Update to root to resolve this.
if(icd10noKode.asText().equals("ICD-10")) {
icd10noParentKode = "root";
}
conceptDesc += icd10noKode.asText() + "|" + icd10noTerm.asText() + System.lineSeparator();
parentChild += icd10noParentKode + "|" + icd10noKode.asText() + System.lineSeparator();
conceptsMap.add(icd10noKode.asText());
parentsMap.add(icd10noParentKode);
}
}
pageNumber+=1;
if(pageNumber > Long.parseLong(doc.get("totalPages").asText())) // if we've processed the final page
break;
}
//Check for invalid parent codes
for(String parentCode : parentsMap) {
if(!conceptsMap.contains(parentCode) && parentCode != "root") {
Logger.getLogger(getClass()).error("No concept code found for specified parent: " + parentCode + "");
}
}
BufferedWriter writer = new BufferedWriter(new FileWriter(folder + "/parent-child.txt"));
writer.write(parentChild);
writer.close();
writer = new BufferedWriter(new FileWriter(folder + "/concepts.txt"));
writer.write(conceptDesc);
writer.close();
}
@Override
public void addProgressListener(ProgressListener l) {
listeners.add(l);
}
@Override
public void removeProgressListener(ProgressListener l) {
listeners.remove(l);
}
@Override
public void reset() throws Exception {
// n/a
}
@Override
public void checkPreconditions() throws Exception {
// n/a
}
@Override
public void cancel() throws Exception {
requestCancel = true;
}
}
| 28,134
|
https://github.com/sboron/godot4-fast-paced-network-fps-tps/blob/master/Example/Game/Shared/Components/PlayerAnimationComponent.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
godot4-fast-paced-network-fps-tps
|
sboron
|
C#
|
Code
| 192
| 643
|
using Framework;
using Framework.Network;
using Framework.Physics;
using Godot;
using Framework.Game;
using Framework.Input;
namespace Shooter.Shared.Components
{
public partial class PlayerAnimationComponent : Node, IPlayerComponent
{
public short NetworkId { get; set; } = 4;
[Export]
public bool IsEnabled { get; set; } = false;
[Export]
public NodePath AnimationTreePath { get; set; }
[Export]
public NodePath InputPath { get; set; }
[Export]
public NodePath CameraPath { get; set; }
private AnimationTree AnimTree { get; set; }
private CharacterCamera Camera { get; set; }
public Framework.Game.NetworkCharacter BaseComponent { get; set; }
public Framework.Game.NetworkInput Input { get; set; }
public override void _EnterTree()
{
base._EnterTree();
this.AnimTree = this.GetNode<AnimationTree>(this.AnimationTreePath);
this.Camera = this.GetNode<CharacterCamera>(this.CameraPath);
this.Input = this.GetNode<Framework.Game.NetworkInput>(this.InputPath);
this.AnimTree.Active = true;
}
public void Tick(float delta)
{
}
public override void _Process(float delta)
{
base._Process(delta);
var factor = (this.BaseComponent as MyPlayer).AnimationMoveSpeed;
var blendPosition = (this.BaseComponent as MyPlayer).AnimationBlendPosition;
if (!this.IsPuppet())
{
if (Input == null || Camera == null)
{
return;
}
var rotX = Mathf.Clamp(Mathf.Rad2Deg(Input.LastInput.ViewDirection.y), -90f, 90f) / 90f;
var rotY = Mathf.Clamp(Mathf.Rad2Deg(Input.LastInput.ViewDirection.x), -90f, 90f) / 90f;
this.AnimTree.Set("parameters/ShoulderMovement/add_amount", rotX * -1);
this.AnimTree.Set("parameters/ShoulderMiovementUp/add_amount", rotY);
}
this.AnimTree.Set("parameters/MoveVec/blend_position", blendPosition);
this.AnimTree.Set("parameters/MoveSpeed/scale", 1f + factor);
this.AnimTree.Set("parameters/MoveState/current", factor > 0 ? 1 : 0);
}
}
}
| 35,967
|
https://github.com/emencia/emencia-cmsplugin-xinnia/blob/master/cmsplugin_zinnia/__init__.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
emencia-cmsplugin-xinnia
|
emencia
|
Python
|
Code
| 17
| 84
|
"""cmsplugin_zinnia"""
__version__ = '0.9.1'
__license__ = 'BSD License'
__author__ = 'Emencia'
__email__ = 'support@emencia.com'
__url__ = 'https://github.com/emencia/emencia-cmsplugin-xinnia'
| 24,044
|
https://github.com/amandra1988/saarc/blob/master/web/assets/angular/Camion/app.js
|
Github Open Source
|
Open Source
|
MIT
| null |
saarc
|
amandra1988
|
JavaScript
|
Code
| 58
| 310
|
(function(angular){
angular.module('admin-camiones', [ 'ui.router','ngResource','ui.bootstrap'])
.constant('urlBase', saConstants.urlBase)
.constant('urlBaseImg', saConstants.urlBaseImg)
.constant('urlBaseApi', saConstants.urlBaseApi)
.constant('urlBasePartials', saConstants.urlBaseTmp)
.constant('apiKey', saConstants.apiKey)
.constant('idEmpresa', saConstants.idEmpresa)
.run(['$http', 'apiKey', function($http, apiKey) {
$http.defaults.headers.common = {'apikey': apiKey};
}])
.config( ['$stateProvider', '$urlRouterProvider', 'urlBasePartials',
function ($stateProvider , $urlRouterProvider , urlBasePartials) {
var listaDeRutas = {
name: 'lista_camiones',
url: '/',
controller: 'CamionesController',
templateUrl: urlBasePartials + 'lista_camiones.html'
};
$stateProvider.state(listaDeRutas);
$urlRouterProvider.when('', '/');
}
]);
})(angular);
| 31,974
|
https://github.com/Camyul/Modul_2_CSharp/blob/master/Databases/Workshop/01. XML-and-JSON/CarsProject - Flash Solution/CarsTask/Models/Query.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
Modul_2_CSharp
|
Camyul
|
C#
|
Code
| 54
| 154
|
using CarsTask.Models.Interfaces;
using System.Collections.Generic;
namespace CarsTask.Models
{
public class Query : IQuery
{
public Query(string outputName, string orderParameter, IList<IWhereClause> whereClauses)
{
this.OutputName = outputName;
this.OrderParameter = orderParameter;
this.WhereClauses = whereClauses;
}
public string OutputName { get; set; }
public string OrderParameter { get; set; }
public IList<IWhereClause> WhereClauses { get; set; }
}
}
| 27,939
|
https://github.com/NewLifeX/X_NET20/blob/master/NewLife.Net/Dhcp/DhcpOption.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
X_NET20
|
NewLifeX
|
C#
|
Code
| 411
| 1,408
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using NewLife.Serialization;
namespace NewLife.Net.Dhcp
{
/// <summary>DHCP选项类型</summary>
public enum DhcpOptions : byte
{
/// <summary></summary>
Mask = 1,
/// <summary></summary>
Router = 3,
/// <summary></summary>
TimeServer = 4,
/// <summary></summary>
NameServer = 5,
/// <summary></summary>
DNSServer = 6,
/// <summary></summary>
LOGServer = 7,
/// <summary></summary>
HostName = 12,
/// <summary></summary>
MTU = 26, // 0x1A
/// <summary></summary>
StaticRout = 33, // 0x21
/// <summary></summary>
ARPCacheTimeout = 35, // 0x23
/// <summary></summary>
NTPServer = 42, // 0x2A
/// <summary></summary>
RequestedIP = 50, // 0x32
/// <summary></summary>
IPLeaseTime = 51, // 0x33
/// <summary></summary>
MessageType = 53, // 0x35
/// <summary></summary>
DHCPServer = 54, // 0x36
/// <summary></summary>
ParameterList = 55, // 0x37
/// <summary></summary>
Message = 56, // 0x38
/// <summary></summary>
MaxMessageSize = 57, // 0x39
/// <summary></summary>
Vendor = 60, // 0x3C
/// <summary></summary>
ClientIdentifier = 61, // 0x3D
/// <summary></summary>
End = 255
}
/// <summary>DHCP可选项</summary>
public class DhcpOption
{
#region 属性
private DhcpOptions _Option;
/// <summary>选项类型</summary>
public DhcpOptions Option { get { return _Option; } set { _Option = value; } }
private Byte _Length;
/// <summary>长度</summary>
public Byte Length { get { return _Length; } set { _Length = value; } }
[FieldSize("_Length")]
private Byte[] _Data;
/// <summary>数据部分</summary>
public Byte[] Data { get { return _Data; } set { _Data = value; } }
#endregion
#region 方法
/// <summary>设置类型</summary>
/// <param name="kind"></param>
/// <returns></returns>
public DhcpOption SetType(DhcpMessageType kind)
{
Option = DhcpOptions.MessageType;
Length = 1;
Data = new Byte[] { (Byte)kind };
return this;
}
/// <summary>设置客户端标识</summary>
/// <param name="clientid"></param>
public void SetClientId(Byte[] clientid)
{
Option = DhcpOptions.ClientIdentifier;
Length = (Byte)(1 + clientid.Length);
Data = new Byte[Length];
Data[0] = 1;
Data.Write(1, clientid);
}
/// <summary>设置参数</summary>
/// <param name="kind"></param>
/// <param name="data"></param>
public void SetData(DhcpOptions kind, Byte[] data)
{
Option = kind;
Length = (Byte)data.Length;
Data = data.ReadBytes();
}
#endregion
#region 辅助
/// <summary>转为字符串标识</summary>
/// <returns></returns>
public String ToStr()
{
switch (Option)
{
case DhcpOptions.Router:
case DhcpOptions.Mask:
case DhcpOptions.DNSServer:
case DhcpOptions.DHCPServer:
case DhcpOptions.RequestedIP:
case DhcpOptions.NTPServer:
case DhcpOptions.TimeServer:
case DhcpOptions.NameServer:
case DhcpOptions.LOGServer:
return new IPAddress(Data.ToInt()).ToString();
case DhcpOptions.HostName:
case DhcpOptions.Vendor:
return Data.ToStr();
case DhcpOptions.MTU:
break;
case DhcpOptions.StaticRout:
break;
case DhcpOptions.ARPCacheTimeout:
break;
case DhcpOptions.IPLeaseTime:
break;
case DhcpOptions.MessageType:
case DhcpOptions.Message:
return ((DhcpMessageType)Data[0]).ToString();
case DhcpOptions.ParameterList:
break;
case DhcpOptions.MaxMessageSize:
break;
case DhcpOptions.ClientIdentifier:
return Data.ReadBytes(1, 6).ToHex(":");
case DhcpOptions.End:
return "";
default:
break;
}
return Data.ToHex();
}
/// <summary>已重载。</summary>
/// <returns></returns>
public override string ToString()
{
return Option + " " + ToStr();
}
#endregion
}
}
| 10,800
|
https://github.com/kanadaj/sentry-dotnet/blob/master/test/Sentry.Tests/Internals/SentryStackTraceFactoryTests.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
sentry-dotnet
|
kanadaj
|
C#
|
Code
| 413
| 1,673
|
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using FluentAssertions;
using Sentry;
using Sentry.Extensibility;
using Xunit;
// ReSharper disable once CheckNamespace
// Stack trace filters out Sentry frames by namespace
namespace Other.Tests.Internals
{
public class SentryStackTraceFactoryTests
{
private class Fixture
{
public SentryOptions SentryOptions { get; set; } = new();
public SentryStackTraceFactory GetSut() => new(SentryOptions);
}
private readonly Fixture _fixture = new();
[Fact]
public void Create_NoExceptionAndDefaultAttachStackTraceOption_NullResult()
{
var sut = _fixture.GetSut();
Assert.Null(sut.Create());
}
[Fact]
public void Create_NoExceptionAndAttachStackTraceOptionOnWithOriginalMode_CurrentStackTrace()
{
_fixture.SentryOptions.AttachStacktrace = true;
_fixture.SentryOptions.StackTraceMode = StackTraceMode.Original;
var sut = _fixture.GetSut();
var stackTrace = sut.Create();
Assert.NotNull(stackTrace);
Assert.Equal(
nameof(Create_NoExceptionAndAttachStackTraceOptionOnWithOriginalMode_CurrentStackTrace),
stackTrace.Frames.Last().Function);
Assert.DoesNotContain(stackTrace.Frames, p =>
p.Function?.StartsWith(
nameof(SentryStackTraceFactory.CreateFrame) + '(',
StringComparison.Ordinal
) == true);
}
[Fact]
public void Create_NoExceptionAndAttachStackTraceOptionOnWithEnhancedMode_CurrentStackTrace()
{
_fixture.SentryOptions.AttachStacktrace = true;
_fixture.SentryOptions.StackTraceMode = StackTraceMode.Enhanced;
var sut = _fixture.GetSut();
var stackTrace = sut.Create();
Assert.NotNull(stackTrace);
Assert.Equal(
$"void " +
$"{GetType().Name}" +
$".{nameof(Create_NoExceptionAndAttachStackTraceOptionOnWithEnhancedMode_CurrentStackTrace)}" +
"()",
stackTrace.Frames.Last().Function);
Assert.DoesNotContain(stackTrace.Frames, p =>
p.Function?.StartsWith(
nameof(SentryStackTraceFactory.CreateFrame) + '(',
StringComparison.Ordinal
) == true);
}
[Fact]
public void Create_WithExceptionAndDefaultAttachStackTraceOption_HasStackTrace()
{
var sut = _fixture.GetSut();
Exception exception;
try
{
Throw();
void Throw() => throw null;
}
catch (Exception e) { exception = e; }
Assert.NotNull(sut.Create(exception));
}
[Fact]
public void Create_WithExceptionAndAttachStackTraceOptionOn_HasStackTrace()
{
_fixture.SentryOptions.AttachStacktrace = true;
var sut = _fixture.GetSut();
Exception exception;
try
{
Throw();
void Throw() => throw null;
}
catch (Exception e) { exception = e; }
var stackTrace = sut.Create(exception);
Assert.Equal(new StackTrace(exception, true).FrameCount, stackTrace?.Frames.Count);
}
[Theory]
[InlineData(StackTraceMode.Original, "ByRefMethodThatThrows")]
[InlineData(StackTraceMode.Enhanced, "(Fixture f, int b) SentryStackTraceFactoryTests.ByRefMethodThatThrows(int value, in int valueIn, ref int valueRef, out int valueOut)")]
public void Create_InlineCase_IncludesAmpersandAfterParameterType(StackTraceMode mode, string method)
{
_fixture.SentryOptions.StackTraceMode = mode;
// Arrange
var i = 5;
var exception = Record.Exception(() => ByRefMethodThatThrows(i, in i, ref i, out i));
_fixture.SentryOptions.AttachStacktrace = true;
var factory = _fixture.GetSut();
// Act
var stackTrace = factory.Create(exception);
// Assert
var frame = stackTrace!.Frames.Last();
frame.Function.Should().Be(method);
}
[Fact]
public void CreateSentryStackFrame_AppNamespace_InAppFrame()
{
var frame = new StackFrame();
var sut = _fixture.GetSut();
var actual = sut.CreateFrame(frame);
Assert.True(actual.InApp);
}
[Fact]
public void CreateSentryStackFrame_AppNamespaceExcluded_NotInAppFrame()
{
_fixture.SentryOptions.AddInAppExclude(GetType().Namespace);
var sut = _fixture.GetSut();
var frame = new StackFrame();
var actual = sut.CreateFrame(frame);
Assert.False(actual.InApp);
}
[Fact]
public void CreateSentryStackFrame_NamespaceIncludedAndExcluded_IncludesTakesPrecedence()
{
_fixture.SentryOptions.AddInAppExclude(GetType().Namespace);
_fixture.SentryOptions.AddInAppInclude(GetType().Namespace);
var sut = _fixture.GetSut();
var frame = new StackFrame();
var actual = sut.CreateFrame(frame);
Assert.True(actual.InApp);
}
// https://github.com/getsentry/sentry-dotnet/issues/64
[Fact]
public void DemangleAnonymousFunction_NullFunction_ContinuesNull()
{
var stackFrame = new SentryStackFrame
{
Function = null
};
SentryStackTraceFactory.DemangleAnonymousFunction(stackFrame);
Assert.Null(stackFrame.Function);
}
[Fact]
public void DemangleAsyncFunctionName_NullModule_ContinuesNull()
{
var stackFrame = new SentryStackFrame
{
Module = null
};
SentryStackTraceFactory.DemangleAnonymousFunction(stackFrame);
Assert.Null(stackFrame.Module);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static (Fixture f, int b) ByRefMethodThatThrows(int value, in int valueIn, ref int valueRef, out int valueOut) =>
throw new Exception();
}
}
| 33,236
|
https://github.com/Dekier/game/blob/master/node_modules/troisjs/src/App.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
game
|
Dekier
|
Vue
|
Code
| 139
| 397
|
<template>
<Renderer :params="{ }" ref="renderer" antialias :orbit-ctrl="{ enableDamping: true }" resize="window" :pixel-ratio="pixelRatio">
<Camera :position="{ z: 10 }" />
<Scene>
<PointLight :position="{ y: 50, z: 50 }" />
<Box :size="1" ref="box" :rotation="{ y: Math.PI / 4, z: Math.PI / 4 }">
<LambertMaterial><Texture src="" /></LambertMaterial>
</Box >
</Scene>
</Renderer>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { Box, Camera, LambertMaterial, MeshPublicInterface, PointLight, Renderer, RendererPublicInterface, Scene, Texture } from './export'
export default defineComponent({
components: { Box, Camera, LambertMaterial, PointLight, Renderer, Scene, Texture },
data () {
return {
pixelRatio: window.devicePixelRatio,
}
},
mounted() {
const renderer = this.$refs.renderer as RendererPublicInterface
const mesh = (this.$refs.box as MeshPublicInterface).mesh
if (renderer && mesh) {
renderer.onBeforeRender(() => {
mesh.rotation.x += 0.01
})
}
},
})
</script>
<style>
body, html {
margin: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
}
</style>
| 9,766
|
https://github.com/mmewen/MT09-numerical-analysis/blob/master/TP3/lanccalcg.sce
|
Github Open Source
|
Open Source
|
MIT
| null |
MT09-numerical-analysis
|
mmewen
|
Scilab
|
Code
| 46
| 90
|
clear
exec("calcg.sci", -1);
T = [ 1 3 4.5 5 6 ]';
cc = [ 1 0 1 0; 5 0 -8/9 0 ; 3 0 16 0 ; 7 0 -8 0 ];
z = calcg(3, T, cc);
disp(z)
z = calcg(5, T, cc);
disp(z)
| 44,566
|
https://github.com/metauro/fastify-plus/blob/master/packages/swagger/lib/document.builder.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
fastify-plus
|
metauro
|
TypeScript
|
Code
| 375
| 1,299
|
import fastifySwagger from 'fastify-swagger';
import expressSwagger from 'swagger-ui-express';
import yaml from 'js-yaml';
import { defaults, merge } from 'lodash';
import { Application } from '@sojs/core';
import { Info, OpenApi, OpenApiScanner, Responses } from '@sojs/openapi';
import { LoggerService, ObjectTool } from '@sojs/common';
import { FastifyApplicationAdapter } from '@sojs/platform-fastify';
import { ExpressApplicationAdapter } from '@sojs/platform-express';
export class DocumentBuilder {
private static logger = new LoggerService(`swagger ${DocumentBuilder.name}`);
static create(app: Application) {
return new DocumentBuilder(app);
}
protected document: OpenApi & {
host: string;
basePath: string;
schemes: string[];
} = {
openapi: '',
info: {
title: '',
version: '',
},
components: {},
paths: {},
host: '',
basePath: '',
schemes: ['http', 'https'],
};
protected hasGlobalResponses = false;
constructor(protected readonly app: Application) {
const { klasses } = app.getContext();
merge(this.document, OpenApiScanner.scan(klasses));
this.resetNonsupportFormat();
}
private resetNonsupportFormat() {
const nonsupportFormats = [
'time',
'uri',
'uri-reference',
'uri-template',
'email',
'hostname',
'ipv4',
'ipv6',
'regex',
'uuid',
'json-pointer',
'relative-json-pointer',
];
ObjectTool.walk(this.document, (key, val, obj) => {
if (key === 'format' && nonsupportFormats.includes(val)) {
delete obj[key];
}
});
}
setInfo(info: Info) {
merge(this.document, info);
return this;
}
setHost(host: string) {
this.document.host = host;
return this;
}
setBasePath(basePath: string) {
this.document.basePath = basePath;
return this;
}
setSchemes(schemes: Array<'http' | 'https' | string>) {
this.document.schemes = schemes;
return this;
}
setGlobalResponses(responses: Responses) {
this.hasGlobalResponses = true;
Object.keys(this.document.paths).forEach(path => {
const pathItem = this.document.paths[path];
Object.keys(pathItem).forEach(method => {
const operation = pathItem[method];
defaults(operation.responses, responses);
});
});
return this;
}
build() {
if (!this.hasGlobalResponses) {
this.setGlobalResponses({
'404': {
description: 'Resource Not Found',
},
'405': {
description: 'Method Not Allow',
},
});
}
const docsPath = '/api-docs';
const jsonPath = '/api-json';
const yamlPath = '/api-yaml';
const jsonDoc = this.document;
const yamlDoc = yaml.dump(this.document);
const { adapter } = this.app.getContext();
DocumentBuilder.logger.info(`map swagger document to ${docsPath}`);
DocumentBuilder.logger.info(`map swagger json to ${jsonPath}`);
DocumentBuilder.logger.info(`map swagger yaml to ${yamlPath}`);
if (adapter instanceof FastifyApplicationAdapter) {
adapter.server.register(fastifySwagger as any, {
mode: 'static',
specification: {
document: this.document,
},
exposeRoute: true,
routePrefix: docsPath,
});
adapter.server.route({
method: 'GET',
url: jsonPath,
handler: (req, reply) => {
reply.header('Content-Type', 'application/json').send(jsonDoc);
},
});
adapter.server.route({
method: 'GET',
url: yamlPath,
handler: (req, reply) => {
reply.header('Content-Type', 'text/x-yaml').send(yamlDoc);
},
});
} else if (adapter instanceof ExpressApplicationAdapter) {
adapter.server.use(
docsPath,
expressSwagger.serve,
expressSwagger.setup(this.document),
);
adapter.server.get(jsonPath, (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(jsonDoc);
});
adapter.server.get(yamlPath, (req, res) => {
res.setHeader('Content-Type', 'text/x-yaml');
res.send(yamlDoc);
});
}
}
}
| 11,657
|
https://github.com/SpartanJ/restafari/blob/master/restafari/src/main/java/com/ensoft/restafari/database/annotations/DbForeignKey.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
restafari
|
SpartanJ
|
Java
|
Code
| 62
| 224
|
package com.ensoft.restafari.database.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import androidx.annotation.IntDef;
@Retention( RetentionPolicy.RUNTIME)
@Target( ElementType.FIELD)
public @interface DbForeignKey
{
String value();
@Action int onUpdate() default NO_ACTION;
@Action int onDelete() default NO_ACTION;
int NO_ACTION = 1;
int RESTRICT = 2;
int SET_NULL = 3;
int SET_DEFAULT = 4;
int CASCADE = 5;
@IntDef({NO_ACTION, RESTRICT, SET_NULL, SET_DEFAULT, CASCADE})
@interface Action {
}
}
| 21,179
|
https://github.com/lodrantl/fetch-mock/blob/master/test/specs/responses.test.js
|
Github Open Source
|
Open Source
|
MIT
| null |
fetch-mock
|
lodrantl
|
JavaScript
|
Code
| 1,216
| 4,671
|
const chai = require('chai');
const expect = chai.expect;
module.exports = (fetchMock) => {
describe('responses', () => {
let fm;
before(() => {
fm = fetchMock.createInstance();
fm.config.warnOnUnmatched = false;
});
afterEach(() => fm.restore());
describe('response building', () => {
it('respond with a status', async () => {
fm.mock('http://it.at.there/', 300);
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(300);
expect(res.statusText).to.equal('Multiple Choices');
});
it('should error on invalid statuses', async () => {
fm.mock('http://foo.com/', { status: 'not number' });
try {
await fm.fetchHandler('http://foo.com');
expect(true).to.be.false;
} catch (err) {
expect(err.message).to.match(
/Invalid status not number passed on response object/
);
}
});
it('respond with a string', async () => {
fm.mock('http://it.at.there/', 'a string');
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(200);
expect(res.statusText).to.equal('OK');
expect(await res.text()).to.equal('a string');
});
it('respond with an empty string', async () => {
fm.mock('http://it.at.there/', '');
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(200);
expect(res.statusText).to.equal('OK');
expect(await res.text()).to.equal('');
});
describe('json responses', () => {
it('respond with a json', async () => {
fm.mock('http://it.at.there/', { an: 'object' });
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(200);
expect(res.statusText).to.equal('OK');
expect(res.headers.get('content-type')).to.equal('application/json');
expect(await res.json()).to.eql({ an: 'object' });
});
it('convert body properties to json', async () => {
fm.mock('http://it.at.there/', {
body: { an: 'object' },
});
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.headers.get('content-type')).to.equal('application/json');
expect(await res.json()).to.eql({ an: 'object' });
});
it('not overide existing content-type-header', async () => {
fm.mock('http://it.at.there/', {
body: { an: 'object' },
headers: {
'content-type': 'text/html',
},
});
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.headers.get('content-type')).to.equal('text/html');
expect(await res.json()).to.eql({ an: 'object' });
});
it('not convert if `body` property exists', async () => {
fm.mock('http://it.at.there/', { body: 'exists' });
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.headers.get('content-type')).not.to.equal(
'application/json'
);
});
it('not convert if `headers` property exists', async () => {
fm.mock('http://it.at.there/', { headers: {} });
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.headers.get('content-type')).not.to.exist;
});
it('not convert if `status` property exists', async () => {
fm.mock('http://it.at.there/', { status: 300 });
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.headers.get('content-type')).not.to.exist;
});
// in the browser the fetch spec disallows invoking res.headers on an
// object that inherits from a response, thus breaking the ability to
// read headers of a fake redirected response.
if (typeof window === 'undefined') {
it('not convert if `redirectUrl` property exists', async () => {
fm.mock('http://it.at.there/', {
redirectUrl: 'http://url.to.hit',
});
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.headers.get('content-type')).not.to.exist;
});
}
it('convert if non-whitelisted property exists', async () => {
fm.mock('http://it.at.there/', { status: 300, weird: true });
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.headers.get('content-type')).to.equal('application/json');
});
});
it('respond with a complex response, including headers', async () => {
fm.mock('http://it.at.there/', {
status: 202,
body: { an: 'object' },
headers: {
header: 'val',
},
});
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(202);
expect(res.headers.get('header')).to.equal('val');
expect(await res.json()).to.eql({ an: 'object' });
});
// The fetch spec does not allow for manual url setting
// However node-fetch does, so we only run this test on the server
if (typeof window === 'undefined') {
it('should set the url property on responses', async () => {
fm.mock('begin:http://foo.com', 200);
const res = await fm.fetchHandler('http://foo.com/path?query=string');
expect(res.url).to.equal('http://foo.com/path?query=string');
});
it('should set the url property on responses when called with Request', async () => {
fm.mock('begin:http://foo.com', 200);
const res = await fm.fetchHandler(
new fm.config.Request('http://foo.com/path?query=string')
);
expect(res.url).to.equal('http://foo.com/path?query=string');
});
}
it('respond with a redirected response', async () => {
fm.mock('http://it.at.there/', {
redirectUrl: 'http://it.at.there/destination',
body: 'I am a redirect',
});
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.redirected).to.equal(true);
expect(res.url).to.equal('http://it.at.there/destination');
expect(await res.text()).to.equal('I am a redirect');
});
it('construct a response based on the request', async () => {
fm.mock(
'http://it.at.there/',
(url, opts) => url + opts.headers.header
);
const res = await fm.fetchHandler('http://it.at.there/', {
headers: { header: 'val' },
});
expect(res.status).to.equal(200);
expect(await res.text()).to.equal('http://it.at.there/val');
});
it('construct a response based on a Request instance', async () => {
fm.mock('http://it.at.there/path', (url, opts, request) =>
request.json().then(({ greeting }) => greeting)
);
const res = await fm.fetchHandler(
new fm.config.Request('http://it.at.there/path', {
body: JSON.stringify({ greeting: 'hi' }),
method: 'post',
})
);
expect(res.status).to.equal(200);
expect(await res.text()).to.equal('hi');
});
describe('content-length', () => {
it('should work on body of type string', async () => {
fm.mock('http://it.at.there/', 'Fetch-Mock rocks');
const res = await fetch('http://it.at.there/');
expect(res.headers.get('content-length')).to.equal('16');
});
it('should work on body of type object', async () => {
fm.mock('http://it.at.there/', { hello: 'world' });
const res = await fetch('http://it.at.there/');
expect(res.headers.get('content-length')).to.equal('17');
});
it('should not overrule explicit mocked content-length header', async () => {
fm.mock('http://it.at.there/', {
body: {
hello: 'world',
},
headers: {
'Content-Length': '100',
},
});
const res = await fetch('http://it.at.there/');
expect(res.headers.get('content-length')).to.equal('100');
});
it('should be case-insensitive when checking for explicit content-length header', async () => {
fm.mock('http://it.at.there/', {
body: {
hello: 'world',
},
headers: {
'CoNtEnT-LeNgTh': '100',
},
});
const res = await fetch('http://it.at.there/');
expect(res.headers.get('content-length')).to.equal('100');
});
});
});
describe('response negotiation', () => {
it('function', async () => {
fm.mock('http://it.at.there/', (url) => url);
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(200);
expect(await res.text()).to.equal('http://it.at.there/');
});
it('Promise', async () => {
fm.mock('http://it.at.there/', Promise.resolve(200));
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(200);
});
it('function that returns a Promise', async () => {
fm.mock('http://it.at.there/', (url) =>
Promise.resolve('test: ' + url)
);
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(200);
expect(await res.text()).to.equal('test: http://it.at.there/');
});
it('Promise for a function that returns a response', async () => {
fm.mock(
'http://it.at.there/',
Promise.resolve((url) => 'test: ' + url)
);
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(200);
expect(await res.text()).to.equal('test: http://it.at.there/');
});
it('delay', async () => {
fm.mock('http://it.at.there/', 200, { delay: 20 });
const req = fm.fetchHandler('http://it.at.there/');
let resolved = false;
req.then(() => (resolved = true));
await new Promise((res) => setTimeout(res, 10));
expect(resolved).to.be.false;
await new Promise((res) => setTimeout(res, 11));
expect(resolved).to.be.true;
const res = await req;
expect(res.status).to.equal(200);
});
it("delay a function response's execution", async () => {
const startTimestamp = new Date().getTime();
fm.mock(
'http://it.at.there/',
() => ({ timestamp: new Date().getTime() }),
{ delay: 20 }
);
const req = fm.fetchHandler('http://it.at.there/');
let resolved = false;
req.then(() => (resolved = true));
await new Promise((res) => setTimeout(res, 10));
expect(resolved).to.be.false;
await new Promise((res) => setTimeout(res, 11));
expect(resolved).to.be.true;
const res = await req;
expect(res.status).to.equal(200);
const responseTimestamp = (await res.json()).timestamp;
expect(responseTimestamp - startTimestamp).to.be.within(20, 25);
});
it('pass values to delayed function', async () => {
fm.mock('http://it.at.there/', (url) => `delayed: ${url}`, {
delay: 10,
});
const req = fm.fetchHandler('http://it.at.there/');
await new Promise((res) => setTimeout(res, 11));
const res = await req;
expect(res.status).to.equal(200);
expect(await res.text()).to.equal('delayed: http://it.at.there/');
});
it('call delayed response multiple times, each with the same delay', async () => {
fm.mock('http://it.at.there/', 200, { delay: 20 });
const req1 = fm.fetchHandler('http://it.at.there/');
let resolved = false;
req1.then(() => (resolved = true));
await new Promise((res) => setTimeout(res, 10));
expect(resolved).to.be.false;
await new Promise((res) => setTimeout(res, 11));
expect(resolved).to.be.true;
const res1 = await req1;
expect(res1.status).to.equal(200);
const req2 = fm.fetchHandler('http://it.at.there/');
resolved = false;
req2.then(() => (resolved = true));
await new Promise((res) => setTimeout(res, 10));
expect(resolved).to.be.false;
await new Promise((res) => setTimeout(res, 11));
expect(resolved).to.be.true;
const res2 = await req2;
expect(res2.status).to.equal(200);
});
it('Response', async () => {
fm.mock(
'http://it.at.there/',
new fm.config.Response('http://it.at.there/', { status: 200 })
);
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(200);
});
it('function that returns a Response', async () => {
fm.mock(
'http://it.at.there/',
() => new fm.config.Response('http://it.at.there/', { status: 200 })
);
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(200);
});
it('Promise that returns a Response', async () => {
fm.mock(
'http://it.at.there/',
Promise.resolve(
new fm.config.Response('http://it.at.there/', { status: 200 })
)
);
const res = await fm.fetchHandler('http://it.at.there/');
expect(res.status).to.equal(200);
});
describe('rejecting', () => {
it('reject if object with `throws` property', async () => {
fm.mock('http://it.at.there/', { throws: 'as expected' });
return fm
.fetchHandler('http://it.at.there/')
.then(() => {
throw 'not as expected';
})
.catch((err) => {
expect(err).to.equal('as expected');
});
});
it('reject if function that returns object with `throws` property', async () => {
fm.mock('http://it.at.there/', () => ({ throws: 'as expected' }));
return fm
.fetchHandler('http://it.at.there/')
.then(() => {
throw 'not as expected';
})
.catch((err) => {
expect(err).to.equal('as expected');
});
});
});
});
});
};
| 46,901
|
https://github.com/ibhelmer/TcpServerSocket/blob/master/src/wireless/module_frames.h
|
Github Open Source
|
Open Source
|
MIT
| null |
TcpServerSocket
|
ibhelmer
|
C
|
Code
| 1,826
| 3,484
|
// This software is part of OpenMono, see http://developer.openmono.com
// and is available under the MIT license, see LICENSE.txt
#ifndef __mono_redpine__module_frames__
#define __mono_redpine__module_frames__
#include <mbed.h>
#include <queue.h>
namespace mono { namespace redpine {
/**
* Management Frame structure as sent from/to the module
* This frame type deliver commands and status information to and from
* the module.
*/
typedef struct __attribute__((packed))
{
uint16_t LengthType; /**< LSB is the frame data length, MSB is always 0x40 */
uint16_t CommandId; /**< LSB is the frames Command Id */
uint8_t reserved[8]; /**< Reserved for future use */
uint16_t status; /**< An integer status of the frame */
uint8_t reserved2[2]; /**< Reserved for future use */
} mgmtFrameRaw;
/**
* Data Frame for transferring data related to a command, as sent to/from
* the module.
*
* The first 16-bit word is the length bit 0-11, and the frame type
* bit 12-15.
*/
typedef struct __attribute__((packed))
{
uint16_t LengthType; /**< LSB is the frame data length, MSB is always 0x50 */
uint8_t DataType; /**< Always 0x00 */
uint8_t reserved[13]; /**< Reserved for future use */
} dataFrameRaw;
/**
* A generic frame that is used to communicate which the module
* Subclasses of this will represent data or management frames.
*/
class ModuleFrame : public IQueueItem
{
public:
/** List of frame direction, sent og received */
enum FrameDirection
{
TX_FRAME, /**< The frame is a request to the module */
RX_FRAME /**< The frame is a response from module */
};
/** List of request commands id's */
enum RxTxCommandIds
{
SendData = 0x00, /**< Frame is data frame */
SetOperatingMode = 0x10, /**< */
Band = 0x11, /**< */
Init = 0x12, /**< */
Scan = 0x13, /**< */
Join = 0x14, /**< */
PowerSaveMode = 0x15, /**< */
SleepTimer = 0x16, /**< */
SetMacAddress = 0x17, /**< */
QueryNetworkParams = 0x18, /**< */
Disconnect = 0x19, /**< */
AntennaSelect = 0x1B, /**< */
SoftReset = 0x1C, /**< */
SetRegion = 0x1D, /**< */
ConfigSave = 0x20, /**< */
ConfigEnable = 0x21, /**< */
ConfigGet = 0x22, /**< */
UserStoreConfig = 0x23, /**< */
APConfig = 0x24, /**< */
SetWEPKeys = 0x25, /**< */
DebugPrintUART2 = 0x26, /**< */
PingCommand = 0x29, /**< */
RSSIQuery = 0x3A, /**< */
MulticastAddrFilter = 0x40, /**< */
SetIPParameters = 0x41, /**< */
SocketCreate = 0x42, /**< */
SocketClose = 0x43, /**< */
DnsResolution = 0x44, /**< DNS Resolution lookup command */
HttpGet = 0x51, /**< HTTP Client, GET request */
HttpPost = 0x52, /**< HTTP Client, POST request */
WakeFromSleep = 0xCD,
PowerSaveACK = 0xDE
};
/** List of response command Id's */
enum RxCommandIds
{
AsyncConnAcceptReq = 0x30, /**< Async connection accept request from remote wfd device */
CardReady = 0x89 /**< Card Ready command, when module is initialized and ready */
};
/** Indicate if the frame is request or response */
FrameDirection direction;
/** This is the payload data length */
uint16_t length;
/** Either a RxTxCommandId or a TxCommand id */
uint8_t commandId;
/** The size of frame in raw format */
static const uint8_t size = sizeof(mgmtFrameRaw);
///** If this object sits in a queue, this is the pointer the next in the queue */
//ModuleFrame *queueNextPointer;
/**
* Construct an empty frame with no properties set.
* The frame will not represent any data or any command
*/
ModuleFrame();
/**
* Dealloc the frame if its subclass contains resources that should
* be removed gracefully.
*/
virtual ~ModuleFrame();
};
class ManagementFrame : public ModuleFrame
{
public:
/**
* The datastructure provided by the Management Frames async completion
* handler.
*
* You should use the member variable `Context` to reference any frame
* response data. You should expect the frame to be deallocated right after
* you callback handler functions returns.
*
* **Note**: You type safety you can check the frames `CommandId` before
* downcasting the `Context` pointer to a specific frame subclass.
*/
typedef struct {
bool Success; /**< See if the request was successfull */
ManagementFrame *Context; /**< A pointer to the request frame object */
} FrameCompletionData;
/** Management response status */
uint16_t status;
/** The length of this frames payload data, differs for every subclass. */
//int dataPayloadLength;
/**
* Frames can handle responses from the module themselves
* This `bool` indicates that a frame subclass can handle a resposne
* frame and data payload.
*
* Normally the (@ref commit) method handles and parses a frames response,
* but when there is a payload, it needs a _response payload handler_
*
* This you set this property to `true` in your subclass, when you must
* overload the method (@ref responsePayloadHandler).
*
* The default value for this property is `false`
* @default `false`
*/
bool responsePayload;
/**
* @brief As long as this property is `false` the frame will continue
* to process reponses.
*
* Some commands gets multiple reponses from the module.
* Say you use the HTTP GET command or a socket receive command,
* the received data arrive in chunks of different lengths.
*
* Set this protoperty to `false` and the @ref commit method will know,
* it whould parse multiple responses for the command.
*
* If you set this property to `false`, the method
* @ref reposnePayloadHandler will be called multiple times.
*
* Finally, when you know the module will not sent any further response
* frames, you must indicate this by setting this property to `true`
*
* If a command frame takes only one response, your subclass can ignore
* this property.
*
* @default `true`
*/
bool lastResponseParsed;
/**
* The module handle class (@ref Module) should dealloc this object when
* it has parsed the last chunk of response data.
*/
bool autoReleaseWhenParsed;
/**
* @brief The handler called when @ref commit finishes
*
* To handle frame request and responses asynchronously, this handler
* is triggered when the frame is committed.
*/
mbed::FunctionPointerArg1<void, FrameCompletionData*> completionHandler;
/** A reference to the completion handler context object */
void *handlerContextObject;
/**
* Construct an empty (uninitialized) management frame
* This is used when you need to allocate memory on the stack for a
* frame, and pass it to another function.
*/
ManagementFrame();
/**
* Construct a management frame from reponse data
*
* The contructed object will not reference the raw data in any way.
*
* @param rawFrame A pointer to the raw frame data structure
*/
ManagementFrame(mgmtFrameRaw *rawFrame);
/**
* Construct a outgoing management frame, having the TX_FRAME direction
* parameter set.
* No other frame parameters are initailzed
*
* @param commandId The TX command id
*/
ManagementFrame(RxTxCommandIds commandId);
ManagementFrame(const ManagementFrame &other);
ManagementFrame &operator=(const ManagementFrame &other);
/**
* If this frame is of type TX_FRAME this method will sent it to the
* module.
*
* When the command frame is sent, the method will wait for a response
* and then check the response against the request. If the property
* @ref responsePayload is set to `true`, the method @ref responsePayloadHandler
* is called automatically.
*
* If the command takes multiple responses, like TCP data receive on
* sockets, you should see the @ref lastResponseParsed property.
*
* When the method returns, the frame response (with payload data) is
* expected to be present.
*
* @return `true` on success, false otherwise
*/
virtual bool commit();
/**
* @brief Send a TX_FRAME to the module asynchronous
*
* Same as @ref commit, but but asynchronous and return immediately. You
* should set the completion callback handler (@ref setCompletionCallback)
* before calling this method.
*
*
*
* @see commit
* @see setCompletionCallback
*/
virtual void commitAsync();
/**
* If the frame is pending, it is aborted and removed from the to-be-sent
* request queue.
* If the frame has already been sent to the module, the abort is ignored.
*
* Still the completion callback handler if removed, to avoid calling
* freed objects.
*
* @brief Abort the execution (commit) of the frame
*/
virtual void abort();
/**
* Internal method used by @ref commitAsync method to send the frame to
* the module, inside the async function handler.
*
* You should not call this directly.
*/
virtual bool writeFrame();
/**
* Internal method to trigger the completion handler callback - if any
* This method should only be used by the @ref Module member method
* `moduleEventHandler`.
*/
virtual void triggerCompletionHandler();
/**
* Gets the frames raw data format for transfer via the communication
* channel.
* This format is only the frame itself, not any data payload
*
* @param data A pointer to the raw frame structure were the data is written to.
* @return raw data struct
*/
virtual void rawFrameFormat(mgmtFrameRaw *data);
/**
* Get the byte length of the data payload for this management frame
* The payload length varys for every subclass.
* @return payload data byte length
*/
virtual int payloadLength();
/**
* Write the payload data for the frame into the provided buffer.
* The payload data is dependent on the specific management frame
* subclass.
*
* If the managament frame subclass does not have any payload data, this
* method not do anything. The target buffer will be left untouched.
* Before you call this method, you should check if payload data exists
* using the [payloadLength](@ref ManagementFrame::payloadLength) method.
*
* The data returned to ready to be transferred to the module, it is
* 4-byte aligned as required. It is you responsibility to ensure the
* provided data buffer is large enought to contain the needed bytes.
*
* @param dataBuffer A pointer to the target buffer, where the payload data is written.
*/
virtual void dataPayload(uint8_t *dataBuffer);
/**
* When frames need to parse or react to response payloads, there are
* received after a call to @ref commit.
*
* You must overload this method in your subclass and handle the parsing
* of the response payload. This parsing should set object properties
* that can later be accessed by outside objects.
*
* This mehod is called internally by the @ref commit method, only if
* property @ref responsePayload is set to `true`.
*
* @param payloadBuffer A pointer to the raw payload data buffer
*/
virtual void responsePayloadHandler(uint8_t *payloadBuffer);
/**
* @brief Set the frame completion callback handler
*
* The member function you provide is called when the frame is successfully
* committed. This means it has been sent to the module, and a response has
* been received.
*
* The callback function must accept an input parameter:
* @code
* void functionName(ManagementFrame::FrameCompletionData *);
* @endcode
*
* @param obj The member functions context pointer (the `this` pointer)
* @param memPtr A pointer to the member function on the class
*/
template <typename Owner>
void setCompletionCallback(Owner *obj, void(Owner::*memPtr)(FrameCompletionData*))
{
completionHandler.attach<Owner>(obj, memPtr);
handlerContextObject = obj;
}
};
}}
#endif /* defined(__mono_redpine__module_frames__) */
| 30,916
|
https://github.com/StepaTa/vkbottle/blob/master/examples/tests/user/shuffle_tokens.py
|
Github Open Source
|
Open Source
|
MIT
| null |
vkbottle
|
StepaTa
|
Python
|
Code
| 77
| 222
|
from vkbottle.user import User, Message
from vkbottle.api.token import LimitedTokenGenerator
import os
token_1 = os.environ["token_1"]
token_2 = os.environ["token_2"]
token_3 = os.environ["token_3"]
token_4 = os.environ["token_4"]
# Use ConsistentTokenGenerator if you are confident about the load of your polling
# LimitedTokenGenerator is the best choice to find out the problem of limit error at the start
generator = LimitedTokenGenerator([token_1, token_2, token_3, token_4])
user = User(token_1)
user.api.token_generator = generator
@user.on.message_handler()
async def new_message(ans: Message):
if ans.from_id == user.user_id:
await ans(ans.text)
user.run_polling()
| 45,713
|
https://github.com/matoruru/purescript-react-material-ui-svgicon/blob/master/src/MaterialUI/SVGIcon/Icon/FlightTakeoff.purs
|
Github Open Source
|
Open Source
|
MIT
| null |
purescript-react-material-ui-svgicon
|
matoruru
|
PureScript
|
Code
| 45
| 148
|
module MaterialUI.SVGIcon.Icon.FlightTakeoff
( flightTakeoff
, flightTakeoff_
) where
import Prelude (flip)
import MaterialUI.SVGIcon.Type (SVGIcon, SVGIcon_)
import React (unsafeCreateElement, ReactClass) as R
foreign import flightTakeoffImpl :: forall a. R.ReactClass a
flightTakeoff :: SVGIcon
flightTakeoff = flip (R.unsafeCreateElement flightTakeoffImpl) []
flightTakeoff_ :: SVGIcon_
flightTakeoff_ = flightTakeoff {}
| 24,277
|
https://github.com/HarryStevens/geometric/blob/master/src/angles/angleToRadians.js
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
geometric
|
HarryStevens
|
JavaScript
|
Code
| 15
| 33
|
// Converts degrees to radians.
export function angleToRadians(angle){
return angle / 180 * Math.PI;
}
| 41,493
|
https://github.com/odooht/odoo-rpc/blob/master/examples/erp/src/layouts/FormItemLayout.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
odoo-rpc
|
odooht
|
JavaScript
|
Code
| 39
| 83
|
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 7 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 12 },
md: { span: 10 },
},
};
export default formItemLayout;
| 31,963
|
https://github.com/asgerMe/Deep-Earth-/blob/master/run.py
|
Github Open Source
|
Open Source
|
MIT
| null |
Deep-Earth-
|
asgerMe
|
Python
|
Code
| 439
| 1,495
|
import argparse
import config
import train
import os
import util
import inference
parser = argparse.ArgumentParser()
parser.add_argument("input_dir", help="path to training fields / See ... for Houdini based data generator")
parser.add_argument("-od", "--output_dir", default='', help="path to training fields / See ... for Houdini based data generator")
parser.add_argument("-mg", "--meta graph_dir", default='', help="graph saving directory")
parser.add_argument("-t", "--train", help="train the network", action='store_true')
parser.add_argument("-lss", "--latent_state_size", type=int, help= "size of the latent state space. Should be 2^n", default=8, choices=[8, 16, 32, 64, 128])
parser.add_argument("-sb", "--small_blocks", help="number of small convolutional blocks in the network. ~1-4 should work well.", default=4, type=int, choices=[1,2,3,4,5,6,7])
parser.add_argument("-f", "--filters", help="number of filters in each convolution", default=128, type=int)
parser.add_argument("-ti", "--train_integrator", help="train the network", action='store_true')
parser.add_argument("-seq", "--sequence_length", help= "sequence length at inference time. How long a sequence should the networks generate ?", default=30, type=int)
parser.add_argument('-sg', '--graph_saving_freq', help= "save meta graph every n frame. no saves when set to zero", default=5000, type=int)
parser.add_argument('-tb', '--tensorboard_saving_freq', help= "save tensorboard plot every n frame. no saves when set to zero", default=5, type=int)
parser.add_argument('-pd', '--prediction_length', help = "Number of frames to predict", default=30, type=int)
parser.add_argument('-dp', '--deploy_path', default='', help="Alternative dir for inference data")
parser.add_argument('-lr_min', '--min_learn_rate', type=float, default=0.0000025, help="Minimum learning rate attained during cosine annealing")
parser.add_argument('-lr_max', '--max_learn_rate', type=float, default=0.0001, help="Maximum learning rate attained during cosine annealing")
parser.add_argument('-ep', '--period', default=2500, help="period of cosine annealing")
parser.add_argument('-tri', '--trilinear', action='store_true', help="use tri-linear interpolation for resampling and not nearest neighbour")
parser.add_argument('-mlp', '--encoder_mlp_layers', default = 1, type = int, help="MLP layers to use on each side of the latent state projection")
parser.add_argument('-sdf', '--sdf_state_size', default = 8, type = int, help="size of the boundary conditions encoding")
parser.add_argument('-gif', '--gif_saver_f', default = 5000, type = int, help="Frequency for saving gifs")
parser.add_argument('-b', '--batch_size', default = 1, type=int, help='Batch size for training')
parser.add_argument('-fem', '--use_differential_kernels', action='store_true', help="use fem layers")
parser.add_argument('-cv', '--convolution', action='store_true', help="use convolutions all the way through the autoencoder")
parser.add_argument('-fem_loss', '--fem_difference', action='store_true', help="use the fem differentials as loss metric")
parser.add_argument('-clear', '--clear', action='store_true', help="clear graphs and test fields in native dirs")
parser.add_argument('-inf', '--iframe', default=-1, help="display frame during inference")
parser.add_argument('-g', '--grid_path', default ='', help='Path to grid dictionary')
args = parser.parse_args()
config.data_path = args.input_dir
if os.path.isdir(config.data_path):
util.create_dirs(args.clear)
else:
print('Input dir is not valid')
if not os.path.isdir(config.output_dir):
print('WARNING - output dir is not valid. Meta graphs are not saved')
exit()
config.resample = args.trilinear
config.param_state_size = args.latent_state_size
config.n_filters = args.filters
config.output_dir = args.output_dir
config.save_freq = args.graph_saving_freq
config.f_tensorboard = args.tensorboard_saving_freq
config.sb_blocks = args.small_blocks
config.batch_size = args.batch_size
config.sequence_length = args.sequence_length
config.alt_dir = args.deploy_path
config.lr_max = args.max_learn_rate
config.lr_min = args.min_learn_rate
config.period = args.period
config.encoder_mlp_layers = args.encoder_mlp_layers
config.sdf_state = args.sdf_state_size
config.save_gif = args.gif_saver_f
if os.path.isdir(args.grid_path):
config.grid_dir = args.grid_path
config.use_fem = args.use_differential_kernels
config.fem_loss = args.fem_difference
config.conv = args.convolution
if args.train:
train.train_network()
elif args.train_integrator:
train.train_integrator()
else:
print('Inference AE with random field')
inference.restore_ae(data=config.data_path, graph_path=config.path_e, grid=config.grid_dir, frame=args.iframe)
| 40,660
|
https://github.com/TimMurphy/Casper/blob/master/tests/Casper.Data.Git.Specifications/Helpers/SpecFlowServiceLocator.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
Casper
|
TimMurphy
|
C#
|
Code
| 95
| 295
|
using System;
using System.Collections.Generic;
using BoDi;
using Microsoft.Practices.ServiceLocation;
namespace Casper.Data.Git.Specifications.Helpers
{
public class SpecFlowServiceLocator : ServiceLocatorImplBase
{
private readonly IObjectContainer _objectContainer;
public SpecFlowServiceLocator(IObjectContainer objectContainer)
{
_objectContainer = objectContainer;
}
protected override object DoGetInstance(Type serviceType, string key)
{
if (!string.IsNullOrWhiteSpace(key))
{
throw new NotImplementedException("DoGetInstance when key has a value has not been implemented.");
}
try
{
var value = _objectContainer.Resolve(serviceType);
return value;
}
catch (Exception exception)
{
throw new Exception(string.Format("{0} has not been registered with IObjectContainer. See {1}.BeforeScenario().", serviceType, typeof (SetupSteps)), exception);
}
}
protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
{
throw new NotSupportedException();
}
}
}
| 32,385
|
https://github.com/mpellicer/sakai/blob/master/mneme-project/ambrosia/ambrosia-api/api/src/java/org/etudes/ambrosia/api/Controller.java
|
Github Open Source
|
Open Source
|
ECL-2.0
| 2,020
|
sakai
|
mpellicer
|
Java
|
Code
| 324
| 656
|
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2008 Etudes, Inc.
*
* Portions completed before September 1, 2008
* Copyright (c) 2007, 2008 The Regents of the University of Michigan & Foothill College, ETUDES Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.etudes.ambrosia.api;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.sakaiproject.i18n.InternationalizedMessages;
/**
* Controller handles a view.
*/
public interface Controller
{
/**
* Handle GET
*
* @param req
* Servlet request
* @param res
* Servlet response
* @param context
* Ambrosia context
* @param params
* request path, split by "/"
*/
void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params) throws IOException;
/**
* Get the content hosting path for embedded media in the UI.
*
* @return The content hosting path for embedded media in the UI.
*/
String getDocsPath();
/**
* Get the messages.
*
* @return The messages.
*/
InternationalizedMessages getMessages();
/**
* Access the URL path that addresses this view.
*
* @return The URL path.
*/
String getPath();
/**
* Get the shared messages used by this controller.
*
* @return The shared messages used by this controller.
*/
InternationalizedMessages getSharedMessages();
/**
* Handle POST
*
* @param req
* Servlet request
* @param res
* Servlet response
* @param context
* Ambrosia context
* @param params
* request path, split by "/"
*/
void post(HttpServletRequest req, HttpServletResponse res, Context context, String[] params) throws IOException;
}
| 18,692
|
https://github.com/fightx/userJS/blob/master/祭奠百度/祭奠百度.user.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
userJS
|
fightx
|
TypeScript
|
Code
| 103
| 440
|
// ==UserScript==
// @name 祭奠百度
// @namespace http://tampermonkey.net/
// @version 1.39
// @description 或许未来只有一片精致的灰 !
// @author 崮生 2234839456@qq.com
// @match *
// @include *
// @connect shenzilong.cn
// @grant GM.setValue
// @grant GM.getValue
// ==/UserScript==
(() => {
function main() {
const style_el = document.createElement("style");
const gray = `-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: grayscale(100%);
filter: gray;`;
style_el.innerHTML = `
${pan_contained([
/** 百度 */
"baidu",
/** 百度静态资源 */
"bdstatic",
/** */
"bdimg",
])},
/** https://pan.baidu.com/buy/checkoutcounter?from=non&vip=1 */
.cashier-page-logo
{${gray}}
`;
function pan_contained(selector: string[]) {
return selector
.map(
(s) => `[src*=${s}],
[style*=${s}]`,
)
.join(",");
}
document.body.insertBefore(style_el, document.querySelector("body *"));
}
main();
})();
| 48,614
|
https://github.com/thewindev/CryBot/blob/master/CryBot.UnitTests/Services/BittrexApi/OrdersTests.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
CryBot
|
thewindev
|
C#
|
Code
| 205
| 1,145
|
using Bittrex.Net.Objects;
using Bittrex.Net.Interfaces;
using CryptoExchange.Net;
using FluentAssertions;
using Moq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Xunit;
namespace CryBot.UnitTests.Services.BittrexApi
{
public class OrdersTests
{
private readonly Mock<IBittrexClient> _bittrexClientMock;
private readonly Core.Exchange.BittrexApi _bittrexApi;
public OrdersTests()
{
_bittrexClientMock = new Mock<IBittrexClient>();
_bittrexApi = new Core.Exchange.BittrexApi(_bittrexClientMock.Object);
_bittrexClientMock.Setup(b => b.GetOpenOrdersAsync(It.IsAny<string>())).ReturnsAsync(()
=> CreateOpenOrdersResponse(new List<BittrexOpenOrdersOrder> { new BittrexOpenOrdersOrder() }, null));
}
[Fact]
public async Task GetOpenOrders_Should_ReturnListOfOrders()
{
var ordersResponse = await _bittrexApi.GetOpenOrdersAsync();
ordersResponse.Content.Should().NotBeNull();
}
[Fact]
public async Task SuccessfulCall_Should_ReturnListOfOrders()
{
var ordersResponse = await _bittrexApi.GetOpenOrdersAsync();
ordersResponse.Content.Count.Should().Be(1);
}
[Fact]
public async Task FailedCallForOrders_Should_ReturnFailedResponse()
{
_bittrexClientMock.Setup(b => b.GetOpenOrdersAsync(It.IsAny<string>()))
.ReturnsAsync(CreateOpenOrdersResponse(new List<BittrexOpenOrdersOrder>(), new ServerError("test")));
var ordersResponse = await _bittrexApi.GetOpenOrdersAsync();
ordersResponse.ErrorMessage.Should().NotBeNullOrWhiteSpace();
ordersResponse.IsSuccessful.Should().BeFalse();
}
[Fact]
public async Task SuccessfulOrderCall_ShouldReturn_CryptoOrders()
{
_bittrexClientMock.Setup(b => b.GetOrderHistoryAsync(It.IsAny<string>()))
.ReturnsAsync(() => CreateCompletedOrdersResponse(new List<BittrexOrderHistoryOrder>(), null));
var ordersResponse = await _bittrexApi.GetCompletedOrdersAsync();
ordersResponse.IsSuccessful.Should().BeTrue();
}
[Fact]
public async Task FailedHistoryCall_ShouldReturn_ErrorResponse()
{
_bittrexClientMock.Setup(b => b.GetOrderHistoryAsync(It.IsAny<string>()))
.ReturnsAsync(() => CreateCompletedOrdersResponse(null, new ServerError("test")));
var ordersResponse = await _bittrexApi.GetCompletedOrdersAsync();
ordersResponse.IsSuccessful.Should().BeFalse();
ordersResponse.ErrorMessage.Should().NotBeNullOrWhiteSpace();
}
[Fact]
public async Task SuccessfulHistoryCall_ShouldReturn_ConvertedOrders()
{
_bittrexClientMock.Setup(b => b.GetOrderHistoryAsync(It.IsAny<string>()))
.ReturnsAsync(() => CreateCompletedOrdersResponse(new List<BittrexOrderHistoryOrder>
{
new BittrexOrderHistoryOrder
{
Exchange = "BTC-XLM"
}
}, null));
var ordersResponse = await _bittrexApi.GetCompletedOrdersAsync();
ordersResponse.Content.Count.Should().Be(1);
ordersResponse.Content[0].Market.Should().Be("BTC-XLM");
}
private static CallResult<BittrexOrderHistoryOrder[]> CreateCompletedOrdersResponse(
List<BittrexOrderHistoryOrder> bittrexOrders,
Error serverError)
{
return new CallResult<BittrexOrderHistoryOrder[]>(bittrexOrders?.ToArray(), serverError);
}
private static CallResult<BittrexOpenOrdersOrder[]> CreateOpenOrdersResponse(
List<BittrexOpenOrdersOrder> bittrexOpenOrders,
Error serverError)
{
return new CallResult<BittrexOpenOrdersOrder[]>(bittrexOpenOrders?.ToArray(), serverError);
}
}
}
| 28,484
|
https://github.com/neuronit/pfa/blob/master/neuronit/tutorial/static/tutorial/js/test.js
|
Github Open Source
|
Open Source
|
MIT
| null |
pfa
|
neuronit
|
JavaScript
|
Code
| 17
| 69
|
function modif(val) {
var ava = document.getElementById("avancement");
if((ava.value+val)<=ava.max && (ava.value+val)>0) {
ava.value += val;
}
avancement();
}
| 48,510
|
https://github.com/smurawczik/assap-challenge/blob/master/app/components/Input/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
assap-challenge
|
smurawczik
|
JavaScript
|
Code
| 42
| 125
|
import React from 'react';
const Input = ({ className, value, onChange, onKeyDown, placeholder }) => {
return <input
className={`${className}`}
value={value}
onKeyDown={e => onKeyDown(e)}
onChange={e => onChange(e.target.value)}
placeholder={placeholder}
/>;
}
Input.defaultProps = {
className: 'input',
placeholder: 'Write your message',
};
export default Input;
| 38,189
|
https://github.com/zhaoge1991/oa-front/blob/master/src/app/pages/setting/erpsetting/erpconfig/components/edit.component.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
oa-front
|
zhaoge1991
|
TypeScript
|
Code
| 108
| 486
|
import {Component,OnInit,ViewChild} from '@angular/core';
import { ActivatedRoute, Params,Router } from '@angular/router';
import {GridOptions} from "ag-grid/main";
import {CommonActionBarConfig} from "../../../../../models/config/commonActionBarConfig";
import {Project} from "../../../../../models/group/project";
import {AppconfigService} from "../../../../../services/core/appConfigService/appConfigService";
@Component({
selector: 'setting-erpconfig-edit',
templateUrl: './edit.html',
styleUrls: ['./edit.scss']
})
export class EditComponent {
private progridOptions: GridOptions;
private costgridOptions: GridOptions;
private id:number;
private sub:any;
private olddata: any;
private data;
private isEdit:boolean;
private commonActionBarConfig: CommonActionBarConfig;
constructor(
private router:Router,
private route:ActivatedRoute,
private erpconfigservice: AppconfigService
){
this.commonActionBarConfig = new CommonActionBarConfig();
this.commonActionBarConfig.saveUrl = 'pages/setting/erpsetting/erpconfig/edit';
}
ngOnInit(){
this.sub = this.route.params.subscribe(params=>{
this.id = params['id'];
this.isEdit = !!this.id;
})
this.setData();
}
setData(){
this.data = this.erpconfigservice.get();
//保存原始数据
this.olddata = JSON.parse(JSON.stringify(this.data));
}
//保存
save(){
this.erpconfigservice.put(this.data).subscribe();
// this.olddata = this.data;
}
ngOnDestroy(){this.sub.unsubscribe();}
}
| 18,290
|
https://github.com/lxthien/symfonysms/blob/master/app/Resources/views/news/components/pagination.html.twig
|
Github Open Source
|
Open Source
|
MIT
| null |
symfonysms
|
lxthien
|
Twig
|
Code
| 6
| 27
|
<div class="navigation">
{{ knp_pagination_render(pagination) }}
</div>
| 38,910
|
https://github.com/rapid7/insightconnect-plugins/blob/master/plugins/rpm/Dockerfile
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
insightconnect-plugins
|
rapid7
|
Dockerfile
|
Code
| 113
| 283
|
FROM komand/python-3-plugin:2
# The three supported python parent images are:
# - komand/python-2-plugin
# - komand/python-3-plugin
# - komand/python-pypy3-plugin
#
LABEL organization=komand
# Add any custom package dependencies here
# NOTE: Add pip packages to requirements.txt
RUN apt-get clean
RUN apt-get update -y
RUN apt-get upgrade -y --fix-missing
RUN apt-get update && apt-get install -y apt-utils rpm yum yum-utils
# End package dependencies
# Add source code
WORKDIR /python/src
ADD ./plugin.spec.yaml /plugin.spec.yaml
ADD . /python/src
ADD ./repos/* /etc/yum.repos.d/
RUN mkdir /rpm-gpg
ADD ./rpm-gpg/* /rpm-gpg/
# Install pip dependencies
RUN if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
# Install plugin
RUN python setup.py build && python setup.py install
ENTRYPOINT ["/usr/local/bin/komand_rpm"]
| 17,942
|
https://github.com/xcheng85/node-express-di-experiment/blob/master/src/middlewares/custom-error-handler.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
node-express-di-experiment
|
xcheng85
|
TypeScript
|
Code
| 89
| 232
|
import * as express from 'express';
import * as util from 'util';
import {
StatusCodes,
} from 'http-status-codes';
import logger from '../utils/logger';
import HttpError from '../utils/error';
const customErrorHandler = (
err: Error,
req: express.Request,
res: express.Response,
next: express.NextFunction,
): void => {
if (err instanceof HttpError) {
let body: any = {
message: err.message || 'An error occurred during the request.',
name: err.name,
status: err.statusCode,
stack: err.stack,
};
res.status(err.statusCode).json(body);
}else{
res.sendStatus(StatusCodes.INTERNAL_SERVER_ERROR)
}
// since err's type is Error, it caught all the errors
// next();
};
export default customErrorHandler;
| 20,676
|
https://github.com/sroebuck/datahelix/blob/master/orchestrator/src/main/java/com/scottlogic/deg/orchestrator/violate/ViolateExecute.java
|
Github Open Source
|
Open Source
|
Apache-2.0, CC0-1.0
| 2,019
|
datahelix
|
sroebuck
|
Java
|
Code
| 252
| 1,145
|
package com.scottlogic.deg.orchestrator.violate;
import com.google.inject.Inject;
import com.scottlogic.deg.common.ValidationException;
import com.scottlogic.deg.common.profile.Profile;
import com.scottlogic.deg.generator.generation.DataGenerator;
import com.scottlogic.deg.common.output.GeneratedObject;
import com.scottlogic.deg.output.FileUtilsImpl;
import com.scottlogic.deg.output.manifest.ManifestWriter;
import com.scottlogic.deg.common.profile.ViolatedProfile;
import com.scottlogic.deg.output.writer.DataSetWriter;
import com.scottlogic.deg.output.outputtarget.SingleDatasetOutputTarget;
import com.scottlogic.deg.orchestrator.guice.AllConfigSource;
import com.scottlogic.deg.generator.inputs.profileviolation.ProfileViolator;
import com.scottlogic.deg.generator.inputs.validation.ProfileValidator;
import com.scottlogic.deg.output.outputtarget.OutputTargetFactory;
import com.scottlogic.deg.output.FileUtils;
import com.scottlogic.deg.generator.validators.ErrorReporter;
import com.scottlogic.deg.orchestrator.validator.ConfigValidator;
import com.scottlogic.deg.profile.reader.ProfileReader;
import com.scottlogic.deg.profile.v0_1.ProfileSchemaValidator;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.stream.Stream;
public class ViolateExecute {
private final ErrorReporter errorReporter;
private final AllConfigSource configSource;
private final ConfigValidator configValidator;
private final OutputTargetFactory outputTargetFactory;
private final ProfileReader profileReader;
private final ProfileValidator profileValidator;
private final ProfileSchemaValidator profileSchemaValidator;
private final ProfileViolator profileViolator;
private final DataGenerator dataGenerator;
private final ViolateOutputValidator violateOutputValidator;
private final ManifestWriter manifestWriter;
@Inject
ViolateExecute(
ProfileReader profileReader,
AllConfigSource configSource,
OutputTargetFactory outputTargetFactory,
ConfigValidator configValidator,
ErrorReporter errorReporter,
ProfileValidator profileValidator,
ProfileSchemaValidator profileSchemaValidator,
ProfileViolator profileViolator,
DataGenerator dataGenerator,
ViolateOutputValidator violateOutputValidator,
ManifestWriter manifestWriter) {
this.profileReader = profileReader;
this.configSource = configSource;
this.outputTargetFactory = outputTargetFactory;
this.configValidator = configValidator;
this.profileSchemaValidator = profileSchemaValidator;
this.errorReporter = errorReporter;
this.profileValidator = profileValidator;
this.profileViolator = profileViolator;
this.dataGenerator = dataGenerator;
this.violateOutputValidator = violateOutputValidator;
this.manifestWriter = manifestWriter;
}
public void execute() throws IOException {
configValidator.preProfileChecks(configSource);
profileSchemaValidator.validateProfile(configSource.getProfileFile());
Profile profile = profileReader.read(configSource.getProfileFile().toPath());
profileValidator.validate(profile);
violateOutputValidator.validate(profile);
doGeneration(profile);
}
private void doGeneration(Profile profile) throws IOException {
List<ViolatedProfile> violatedProfiles = profileViolator.violate(profile);
if (violatedProfiles.isEmpty()) {
return;
}
manifestWriter.writeManifest(violatedProfiles);
DecimalFormat intFormatter = FileUtilsImpl.getDecimalFormat(violatedProfiles.size());
int filename = 1;
for (Profile violatedProfile : violatedProfiles) {
SingleDatasetOutputTarget outputTarget =
outputTargetFactory.create(intFormatter.format(filename++));
Stream<GeneratedObject> generatedObjectStream = dataGenerator.generateData(violatedProfile);
outputData(profile, generatedObjectStream, outputTarget);
}
}
private void outputData(
Profile profile,
Stream<GeneratedObject> generatedDataItems,
SingleDatasetOutputTarget outputTarget) throws IOException
{
try (DataSetWriter writer = outputTarget.openWriter(profile.getFields())) {
generatedDataItems.forEach(row -> {
try {
writer.writeRow(row);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
}
| 46,166
|
https://github.com/ThatDevCompany/ngx-component-mixins/blob/master/src/Base.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
ngx-component-mixins
|
ThatDevCompany
|
TypeScript
|
Code
| 38
| 59
|
/**
* An empty class to form the base of all Mixins
*/
export class Base {}
/**
* A Typescript definition of a constructor function
*/
export type Constructor<T = {}> = new (...args: any[]) => T
| 37,189
|
https://github.com/KonradSchieban/stanza/blob/master/cmd/stanza/offsets.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
stanza
|
KonradSchieban
|
Go
|
Code
| 342
| 1,166
|
package main
import (
"fmt"
"io"
"os"
"github.com/observiq/stanza/database"
"github.com/observiq/stanza/operator/helper"
"github.com/spf13/cobra"
"go.etcd.io/bbolt"
)
var stdout io.Writer = os.Stdout
// NewOffsetsCmd returns the root command for managing offsets
func NewOffsetsCmd(rootFlags *RootFlags) *cobra.Command {
offsets := &cobra.Command{
Use: "offsets",
Short: "Manage input operator offsets",
Args: cobra.NoArgs,
Run: func(command *cobra.Command, args []string) {
stdout.Write([]byte("No offsets subcommand specified. See `stanza offsets help` for details\n"))
},
}
offsets.AddCommand(NewOffsetsClearCmd(rootFlags))
offsets.AddCommand(NewOffsetsListCmd(rootFlags))
return offsets
}
// NewOffsetsClearCmd returns the command for clearing offsets
func NewOffsetsClearCmd(rootFlags *RootFlags) *cobra.Command {
var all bool
offsetsClear := &cobra.Command{
Use: "clear [flags] [operator_ids]",
Short: "Clear persisted offsets from the database",
Args: cobra.ArbitraryArgs,
Run: func(command *cobra.Command, args []string) {
db, err := database.OpenDatabase(rootFlags.DatabaseFile)
exitOnErr("Failed to open database", err)
defer db.Close()
defer func() { _ = db.Sync() }()
if all {
if len(args) != 0 {
stdout.Write([]byte("Providing a list of operator IDs does nothing with the --all flag\n"))
}
err := db.Update(func(tx *bbolt.Tx) error {
offsetsBucket := tx.Bucket(helper.OffsetsBucket)
if offsetsBucket != nil {
return tx.DeleteBucket(helper.OffsetsBucket)
}
return nil
})
exitOnErr("Failed to delete offsets", err)
} else {
if len(args) == 0 {
stdout.Write([]byte("Must either specify a list of operators or the --all flag\n"))
os.Exit(1)
}
for _, operatorID := range args {
err = db.Update(func(tx *bbolt.Tx) error {
offsetBucket := tx.Bucket(helper.OffsetsBucket)
if offsetBucket == nil {
return nil
}
return offsetBucket.DeleteBucket([]byte(operatorID))
})
exitOnErr("Failed to delete offsets", err)
}
}
},
}
offsetsClear.Flags().BoolVar(&all, "all", false, "clear offsets for all inputs")
return offsetsClear
}
// NewOffsetsListCmd returns the command for listing offsets
func NewOffsetsListCmd(rootFlags *RootFlags) *cobra.Command {
offsetsList := &cobra.Command{
Use: "list",
Short: "List operators with persisted offsets",
Args: cobra.NoArgs,
Run: func(command *cobra.Command, args []string) {
db, err := database.OpenDatabase(rootFlags.DatabaseFile)
exitOnErr("Failed to open database", err)
defer db.Close()
err = db.View(func(tx *bbolt.Tx) error {
offsetBucket := tx.Bucket(helper.OffsetsBucket)
if offsetBucket == nil {
return nil
}
return offsetBucket.ForEach(func(key, value []byte) error {
stdout.Write(append(key, '\n'))
return nil
})
})
if err != nil {
exitOnErr("Failed to read database", err)
}
},
}
return offsetsList
}
func exitOnErr(msg string, err error) {
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("%s: %s\n", msg, err))
os.Exit(1)
}
}
| 32,531
|
https://github.com/cmdprompt/dcf/blob/master/scss/elements/_elements.small.scss
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,020
|
dcf
|
cmdprompt
|
SCSS
|
Code
| 44
| 78
|
//////////////////////////
// CORE / ELEMENTS / SMALL
//////////////////////////
small {
@include txt-base;
// The small element is intended for inline text meant to be treated as fine print.
// It does not change the font-size. Use font-size utilities to size text as needed.
}
| 16,065
|
https://github.com/boralt/EmbeddedAI/blob/master/api/html/search/all_f.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
EmbeddedAI
|
boralt
|
JavaScript
|
Code
| 6
| 126
|
var searchData=
[
['remove',['Remove',['../classbayeslib_1_1_var_set.html#a7f55569c4ecf8f907a2918f467888237',1,'bayeslib::VarSet']]],
['removevars',['RemoveVars',['../classbayeslib_1_1_factor_set.html#ab201e3c8164d926b3442ecf4ecfc89b4',1,'bayeslib::FactorSet']]]
];
| 8,488
|
https://github.com/duongdpq/timtro/blob/master/fmlaravel/app/Motel.php
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
timtro
|
duongdpq
|
PHP
|
Code
| 58
| 239
|
<?php
namespace App;
use App\User;
use App\Admin;
use App\Ward;
use Illuminate\Database\Eloquent\Model;
class Motel extends Model
{
protected $table = 'motels';
protected $fillable = [
'name', 'number_room', 'area','price','price_water','price_electric','image','description','address','phone','lat','lng','mezzanine','internet','status','ward_id','user_id','admin_id',
];
public $timestamps = true;
public function user(){
return $this->belongTo('App\User');
}
public function admin(){
return $this->belongTo('App\Admin');
}
public function ward(){
return $this->belongTo('App\Ward');
}
public function motelimages(){
return $this-> hasMany('App\MotelImages');
}
}
| 21,808
|
https://github.com/salihzeki12000/hirespace-static/blob/master/css/src/mixins/_box-shadow.sass
|
Github Open Source
|
Open Source
|
MIT
| null |
hirespace-static
|
salihzeki12000
|
Sass
|
Code
| 7
| 40
|
=box-shadow($style)
-webkit-box-shadow: $style
-moz-box-shadow: $style
box-shadow: $style
| 50,885
|
https://github.com/mantyr/images-imagick/blob/master/struct.go
|
Github Open Source
|
Open Source
|
MIT
| null |
images-imagick
|
mantyr
|
Go
|
Code
| 26
| 72
|
package images
import (
mag "github.com/mantyr/golang-magick"
)
type Image struct {
Image *mag.Image
Address string
Format string
Quality int
width int
height int
Error error
}
| 2,695
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.