repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
sPHENIX-Test/sPHENIX-Test | doxygen/d1/d53/classPHG4PhenixSteppingAction.js | var classPHG4PhenixSteppingAction =
[
[ "ActionList", "d1/d53/classPHG4PhenixSteppingAction.html#af72abf92163a86c8f8fa2424ef6f71c3", null ],
[ "PHG4PhenixSteppingAction", "d1/d53/classPHG4PhenixSteppingAction.html#a7ffd4e0bc20f835737e3e784e2da5894", null ],
[ "~PHG4PhenixSteppingAction", "d1/d53/classPHG4PhenixSteppingAction.html#a3b23d19f1cdba9010c348a94f5dec05c", null ],
[ "AddAction", "d1/d53/classPHG4PhenixSteppingAction.html#afead1d30da1e7c68616987bdf711a25b", null ],
[ "UserSteppingAction", "d1/d53/classPHG4PhenixSteppingAction.html#a498a36e7565d4e1bd114c95731f00b08", null ],
[ "actions_", "d1/d53/classPHG4PhenixSteppingAction.html#a733a1469894cea42d99d11f831326d09", null ]
]; |
Mithenks/strapi | packages/core/content-manager/server/tests/fields/uid.test.e2e.js | 'use strict';
const { createTestBuilder } = require('../../../../../../test/helpers/builder');
const { createStrapiInstance } = require('../../../../../../test/helpers/strapi');
const { createAuthRequest } = require('../../../../../../test/helpers/request');
let strapi;
let rq;
describe('Test type UID', () => {
describe('No targetField, required=false, not length limits', () => {
const model = {
displayName: 'With uid',
singularName: 'withuid',
pluralName: 'withuids',
attributes: {
slug: {
type: 'uid',
},
},
};
const builder = createTestBuilder();
beforeAll(async () => {
await builder.addContentType(model).build();
strapi = await createStrapiInstance();
rq = await createAuthRequest({ strapi });
});
afterAll(async () => {
await strapi.destroy();
await builder.cleanup();
});
test('Creates an entry successfully', async () => {
const res = await rq.post('/content-manager/collection-types/api::withuid.withuid', {
body: {
slug: 'valid-uid',
},
});
expect(res.statusCode).toBe(200);
expect(res.body).toMatchObject({
slug: 'valid-uid',
});
});
// TODO: to handle with database UniqueError
test.skip('Throws error on duplicate value', async () => {
const res = await rq.post('/content-manager/collection-types/api::withuid.withuid', {
body: {
slug: 'duplicate-uid',
},
});
expect(res.statusCode).toBe(200);
expect(res.body).toMatchObject({
slug: 'duplicate-uid',
});
const conflicting = await rq.post('/content-manager/collection-types/api::withuid.withuid', {
body: {
slug: 'duplicate-uid',
},
});
expect(conflicting.statusCode).toBe(400);
});
test('Can set value to be null', async () => {
const res = await rq.post('/content-manager/collection-types/api::withuid.withuid', {
body: {
slug: null,
},
});
expect(res.statusCode).toBe(200);
expect(res.body).toMatchObject({
slug: null,
});
});
});
describe('No targetField, required, no length limits', () => {
const model = {
displayName: 'withrequireduid',
singularName: 'withrequireduid',
pluralName: 'withrequireduids',
attributes: {
slug: {
type: 'uid',
required: true,
},
},
};
const builder = createTestBuilder();
beforeAll(async () => {
await builder.addContentType(model).build();
strapi = await createStrapiInstance();
rq = await createAuthRequest({ strapi });
});
afterAll(async () => {
await strapi.destroy();
await builder.cleanup();
});
test('Creates an entry successfully', async () => {
const res = await rq.post(
'/content-manager/collection-types/api::withrequireduid.withrequireduid',
{
body: {
slug: 'valid-uid',
},
}
);
expect(res.statusCode).toBe(200);
expect(res.body).toMatchObject({
slug: 'valid-uid',
});
});
// TODO: to handle with database UniqueError
test.skip('Throws error on duplicate value', async () => {
const res = await rq.post(
'/content-manager/collection-types/api::withrequireduid.withrequireduid',
{
body: {
slug: 'duplicate-uid',
},
}
);
expect(res.statusCode).toBe(200);
expect(res.body).toMatchObject({
slug: 'duplicate-uid',
});
const conflicting = await rq.post(
'/content-manager/collection-types/api::withrequireduid.withrequireduid',
{
body: {
slug: 'duplicate-uid',
},
}
);
expect(conflicting.statusCode).toBe(400);
});
test('Cannot set value to be null', async () => {
const res = await rq.post(
'/content-manager/collection-types/api::withrequireduid.withrequireduid',
{
body: {
slug: null,
},
}
);
expect(res.statusCode).toBe(400);
});
});
});
|
transitrealtime/mobileFrontEnd | components/getRegion.js | export function regionFrom(lat, lon, accuracy) {
const oneDegreeOfLongitudeInMeters = 111.32 * 1000;
const circumference = (40075 / 360) * 1000;
const latDelta = accuracy * (1 / (Math.cos(lat) * circumference));
const lonDelta = (accuracy / oneDegreeOfLongitudeInMeters);
return {
latitude: lat,
longitude: lon,
latitudeDelta: Math.max(0, latDelta),
longitudeDelta: Math.max(0, lonDelta)
};
} |
sgholamian/log-aware-clone-detection | LACCPlus/Hadoop/1407_2.java | //,temp,NNUpgradeUtil.java,84,99,temp,BlockPoolSliceStorage.java,597,632
//,3
public class xxx {
void doFinalize(File dnCurDir) throws IOException {
File bpRoot = getBpRoot(blockpoolID, dnCurDir);
StorageDirectory bpSd = new StorageDirectory(bpRoot);
// block pool level previous directory
File prevDir = bpSd.getPreviousDir();
if (!prevDir.exists()) {
return; // already finalized
}
final String dataDirPath = bpSd.getRoot().getCanonicalPath();
LOG.info("Finalizing upgrade for storage directory " + dataDirPath
+ ".\n cur LV = " + this.getLayoutVersion() + "; cur CTime = "
+ this.getCTime());
assert bpSd.getCurrentDir().exists() : "Current directory must exist.";
// rename previous to finalized.tmp
final File tmpDir = bpSd.getFinalizedTmp();
rename(prevDir, tmpDir);
// delete finalized.tmp dir in a separate thread
new Daemon(new Runnable() {
@Override
public void run() {
try {
deleteDir(tmpDir);
} catch (IOException ex) {
LOG.error("Finalize upgrade for " + dataDirPath + " failed.", ex);
}
LOG.info("Finalize upgrade for " + dataDirPath + " is complete.");
}
@Override
public String toString() {
return "Finalize " + dataDirPath;
}
}).start();
}
}; |
ultianalytics/UltimateIPhone | Scrubber.h | //
// Scrubber.h
// UltimateIPhone
//
// Created by <NAME> on 5/23/12.
// Copyright (c) 2012 Summit Hill Software. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Scrubber : NSObject {
}
@property (nonatomic) BOOL isOn;
+(Scrubber*)currentScrubber;
-(NSString*)substitutePlayerName: (NSString*) originalName isMale: (BOOL) isMale;
-(NSString*)substituteTournamentName: (NSString*) originalName;
-(NSString*)substituteOpponentName: (NSString*) originalName;
-(NSDate*)scrubGameDate: (NSDate*) gameDate;
@end
|
whuang022nccu/IndriLab | include/indri/TokenizerFactory.hpp | /*==========================================================================
* Copyright (c) 2003-2005 University of Massachusetts. All Rights Reserved.
*
* Use of the Lemur Toolkit for Language Modeling and Information Retrieval
* is subject to the terms of the software license set forth in the LICENSE
* file included with this software, and also available at
* http://www.lemurproject.org/license.html
*
*==========================================================================
*/
//
// TokenizerFactory
//
// 15 September 2005 -- mwb
//
#ifndef INDRI_TOKENIZERFACTORY_HPP
#define INDRI_TOKENIZERFACTORY_HPP
#include <string>
#include <map>
#include "indri/IndriTokenizer.hpp"
namespace indri {
namespace parse {
class TokenizerFactory {
public:
~TokenizerFactory();
static std::string preferredName( const std::string& name );
static indri::parse::Tokenizer* get( const std::string& name );
};
}
}
#endif // INDRI_TOKENIZERFACTORY_HPP
|
Markoy8/Foundry | Components/CommonCore/Source/gov/sandia/cognition/io/XStreamSerializationHandler.java | /*
* File: XMLSerializationHandler.java
* Authors: <NAME>
* Company: Sandia National Laboratories
* Project: Cognitive Foundry
*
* Copyright February 21, 2007, Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000, there is a non-exclusive license for use of this work by
* or on behalf of the U.S. Government. Export of this program may require a
* license from the United States Government. See CopyrightHistory.txt for
* complete details.
*
*/
package gov.sandia.cognition.io;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import gov.sandia.cognition.annotation.CodeReview;
import gov.sandia.cognition.annotation.CodeReviews;
import gov.sandia.cognition.annotation.PublicationReference;
import gov.sandia.cognition.annotation.PublicationType;
import gov.sandia.cognition.annotation.SoftwareLicenseType;
import gov.sandia.cognition.annotation.SoftwareReference;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
/**
* Reads and writes Objects in XML format. Generally speaking, this requires
* no extra methods for an Object (it's automagic using Reflection). Based on
* XStream package.
* <P><P>
* <B>KNOWN LIMITATION</B>: The read() method will thrown an exception
* "java.io.IOException: com.thoughtworks.xstream.io.StreamException:
* : input contained no data" when trying to read the SECOND object from
* an XML InputStream/Reader. This is because XML files must have a
* single root node (which would be the FIRST object in the file), and
* anything after the close of the root node (the SECOND object) is
* considered invalid or nonexistent. To address the limitation, refer
* to http://xstream.codehaus.org/objectstream.html
*
* @author <NAME>
* @since 1.0
*/
@CodeReviews(
reviews={
@CodeReview(
reviewer="<NAME>",
date="2008-12-02",
changesNeeded=false,
comments={
"Minor cosmetic changes.",
"Otherwise, this wrapper class is fine."
}
)
,
@CodeReview(
reviewer = "<NAME>",
date = "2008-02-08",
changesNeeded = false,
comments = {
"Changed the read() method to close the stream it creates after reading.",
"Minor formatting change, and fixed a few typos.",
"Added PublicationReference for the Object Streams Tutorial.",
"Otherwise, looks fine."
}
)
}
)
@PublicationReference(
author = "XStream Documentation",
title = "Object Streams Tutorial",
type = PublicationType.WebPage,
year = 2008,
url = "http://xstream.codehaus.org/objectstream.html"
)
@SoftwareReference(
name="XStream",
version="1.2.1",
url="http://xstream.codehaus.org/",
license=SoftwareLicenseType.BSD,
licenseURL="http://xstream.codehaus.org/"
)
public class XStreamSerializationHandler
extends Object
{
/**
* Writes the given object to the given OutputStream
*
* @param stream OutputStream to write the object to
* @param object Object to write to the OutputStream
* @return true on success, false otherwise
* @throws java.io.IOException
* If there's a problem writing
*/
public static boolean write(
OutputStream stream,
Serializable object)
throws IOException
{
return XStreamSerializationHandler.write(
new OutputStreamWriter(stream), object);
}
/**
* Writes the given object to the given Writer
*
* @return true on success, false otherwise
* @param writer Writer to write the object to
* @param object Object to write to the Writer
* @throws java.io.IOException
* If there's a problem writing
*/
public static boolean write(
Writer writer,
Serializable object)
throws IOException
{
XStream xmlStream = new XStream(new StaxDriver());
xmlStream.toXML(object, writer);
return true;
}
/**
* Writes the given object to the given file using XStream serialization.
*
* @param fileName
* The file to write to.
* @param object
* The object to write.
* @throws java.io.IOException
* If there is an error in writing.
*/
public static void writeToFile(
final String fileName,
final Serializable object)
throws IOException
{
writeToFile(new File(fileName), object);
}
/**
* Writes the given object to the given file using XStream serialization.
*
* @param file
* The file to write to.
* @param object
* The object to write.
* @throws java.io.IOException
* If there is an error in writing.
*/
public static void writeToFile(
final File file,
final Serializable object)
throws IOException
{
if (file == null)
{
throw new IOException("file cannot be null");
}
else if (object == null)
{
throw new IOException("object cannot be null");
}
// Create the output stream.
final FileOutputStream out = new FileOutputStream(file);
try
{
// Write the object.
write(out, object);
}
finally
{
out.close();
}
}
/**
* Reads an Object from the given file name.
* <P>
* KNOWN LIMITATION: This method will thrown an exception
* "java.io.IOException: com.thoughtworks.xstream.io.StreamException:
* : input contained no data" when trying to read the SECOND object from
* an XML InputStream/Reader. This is because XML files must have a
* single root node (which would be the FIRST object in the file), and
* anything after the close of the root node (the SECOND object) is
* considered invalid or inexistent. To address the limitation, refer
* to http://xstream.codehaus.org/objectstream.html
*
* @param fileName The name of the file to read from.
* @return Deserialized object (null on exception)
* @throws java.io.IOException
* if an Object can't be deserialized from the reader (See LIMITATION above)
*/
public static Object readFromFile(
String fileName)
throws IOException
{
return readFromFile(new File(fileName));
}
/**
* Reads an Object from the given file name.
* <P>
* KNOWN LIMITATION: This method will thrown an exception
* "java.io.IOException: com.thoughtworks.xstream.io.StreamException:
* : input contained no data" when trying to read the SECOND object from
* an XML InputStream/Reader. This is because XML files must have a
* single root node (which would be the FIRST object in the file), and
* anything after the close of the root node (the SECOND object) is
* considered invalid or inexistent. To address the limitation, refer
* to http://xstream.codehaus.org/objectstream.html
*
* @param file The file to read from.
* @return Deserialized object (null on exception)
* @throws java.io.IOException
* if an Object can't be deserialized from the reader (See LIMITATION above)
*/
public static Object readFromFile(
File file)
throws IOException
{
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(file));
// Read the object.
Object read = null;
try
{
read = read(in);
}
finally
{
in.close();
}
return read;
}
/**
* Reads an Object from the given InputStream.
* <P>
* KNOWN LIMITATION: This method will thrown an exception
* "java.io.IOException: com.thoughtworks.xstream.io.StreamException:
* : input contained no data" when trying to read the SECOND object from
* an XML InputStream/Reader. This is because XML files must have a
* single root node (which would be the FIRST object in the file), and
* anything after the close of the root node (the SECOND object) is
* considered invalid or inexistent. To address the limitation, refer
* to http://xstream.codehaus.org/objectstream.html
*
* @return Deserialized object (null on exception)
* @param stream InputStream from which to read
* @throws java.io.IOException
* if an Object can't be deserialized from the reader (See LIMITATION above)
*/
public static Object read(
InputStream stream)
throws IOException
{
InputStreamReader in = new InputStreamReader(stream);
Object retval = XStreamSerializationHandler.read(in);
in.close();
return retval;
}
/**
* Reads an Object from the given Reader.
* KNOWN LIMITATION: This method will thrown an exception
* "java.io.IOException: com.thoughtworks.xstream.io.StreamException:
* : input contained no data" when trying to read the SECOND object from
* an XML InputStream/Reader. This is because XML files must have a
* single root node (which would be the FIRST object in the file), and
* anything after the close of the root node (the SECOND object) is
* considered invalid or inexistent. To address the limitation, refer
* to http://xstream.codehaus.org/objectstream.html
*
* @return Deserialized object (null on exception)
* @param reader Reader from which to read
* @throws java.io.IOException
* if an Object can't be deserialized from the reader (See LIMITATION above)
*/
public static Object read(
Reader reader)
throws IOException
{
XStream xmlStream = new XStream(new StaxDriver());
Object object = null;
try
{
object = xmlStream.fromXML(reader);
}
catch (Exception e)
{
throw new IOException(e.toString());
}
return object;
}
/**
* Writes the given object to a String.
*
* @param object Object to write to the String.
* @return The string containing the XML version of the object.
* @throws java.io.IOException If there's a problem writing.
*/
public static String convertToString(
final Serializable object)
throws IOException
{
StringWriter out = new StringWriter();
write(out, object);
return out.toString();
}
/**
* Attempts to read an Object from the given string.
*
* @param string The String containing the XStream version of the object.
* @return The Object read from the given string.
* @throws java.io.IOException If there is a problem reading.
*/
public static Object convertFromString(
final String string)
throws IOException
{
StringReader in = new StringReader(string);
return read(in);
}
}
|
ScalablyTyped/SlinkyTyped | a/arcgis-js-api/src/main/scala/typingsSlinky/arcgisJsApi/esri/SearchLayerProperties.scala | <gh_stars>10-100
package typingsSlinky.arcgisJsApi.esri
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait SearchLayerProperties extends StObject {
/**
* The field to use for search.
*
* [Read more...](https://developers.arcgis.com/javascript/latest/api-reference/esri-webdoc-applicationProperties-SearchLayer.html#field)
*/
var field: js.UndefOr[SearchLayerFieldProperties] = js.native
/**
* The id of the layer.
*
* [Read more...](https://developers.arcgis.com/javascript/latest/api-reference/esri-webdoc-applicationProperties-SearchLayer.html#id)
*/
var id: js.UndefOr[String] = js.native
/**
* The sub layer index.
*
* [Read more...](https://developers.arcgis.com/javascript/latest/api-reference/esri-webdoc-applicationProperties-SearchLayer.html#subLayer)
*/
var subLayer: js.UndefOr[Double] = js.native
}
object SearchLayerProperties {
@scala.inline
def apply(): SearchLayerProperties = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[SearchLayerProperties]
}
@scala.inline
implicit class SearchLayerPropertiesMutableBuilder[Self <: SearchLayerProperties] (val x: Self) extends AnyVal {
@scala.inline
def setField(value: SearchLayerFieldProperties): Self = StObject.set(x, "field", value.asInstanceOf[js.Any])
@scala.inline
def setFieldUndefined: Self = StObject.set(x, "field", js.undefined)
@scala.inline
def setId(value: String): Self = StObject.set(x, "id", value.asInstanceOf[js.Any])
@scala.inline
def setIdUndefined: Self = StObject.set(x, "id", js.undefined)
@scala.inline
def setSubLayer(value: Double): Self = StObject.set(x, "subLayer", value.asInstanceOf[js.Any])
@scala.inline
def setSubLayerUndefined: Self = StObject.set(x, "subLayer", js.undefined)
}
}
|
GDNative-Gradle/proof-of-concept | cpp/godot-cpp/src/gen/AcceptDialog.cpp | <gh_stars>1-10
#include "AcceptDialog.hpp"
#include <core/GodotGlobal.hpp>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include <core/Godot.hpp>
#include "__icalls.hpp"
#include "Button.hpp"
#include "Label.hpp"
#include "Node.hpp"
namespace godot {
AcceptDialog::___method_bindings AcceptDialog::___mb = {};
void AcceptDialog::___init_method_bindings() {
___mb.mb__builtin_text_entered = godot::api->godot_method_bind_get_method("AcceptDialog", "_builtin_text_entered");
___mb.mb__custom_action = godot::api->godot_method_bind_get_method("AcceptDialog", "_custom_action");
___mb.mb__ok = godot::api->godot_method_bind_get_method("AcceptDialog", "_ok");
___mb.mb_add_button = godot::api->godot_method_bind_get_method("AcceptDialog", "add_button");
___mb.mb_add_cancel = godot::api->godot_method_bind_get_method("AcceptDialog", "add_cancel");
___mb.mb_get_hide_on_ok = godot::api->godot_method_bind_get_method("AcceptDialog", "get_hide_on_ok");
___mb.mb_get_label = godot::api->godot_method_bind_get_method("AcceptDialog", "get_label");
___mb.mb_get_ok = godot::api->godot_method_bind_get_method("AcceptDialog", "get_ok");
___mb.mb_get_text = godot::api->godot_method_bind_get_method("AcceptDialog", "get_text");
___mb.mb_has_autowrap = godot::api->godot_method_bind_get_method("AcceptDialog", "has_autowrap");
___mb.mb_register_text_enter = godot::api->godot_method_bind_get_method("AcceptDialog", "register_text_enter");
___mb.mb_set_autowrap = godot::api->godot_method_bind_get_method("AcceptDialog", "set_autowrap");
___mb.mb_set_hide_on_ok = godot::api->godot_method_bind_get_method("AcceptDialog", "set_hide_on_ok");
___mb.mb_set_text = godot::api->godot_method_bind_get_method("AcceptDialog", "set_text");
}
AcceptDialog *AcceptDialog::_new()
{
return (AcceptDialog *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"AcceptDialog")());
}
void AcceptDialog::_builtin_text_entered(const String arg0) {
___godot_icall_void_String(___mb.mb__builtin_text_entered, (const Object *) this, arg0);
}
void AcceptDialog::_custom_action(const String arg0) {
___godot_icall_void_String(___mb.mb__custom_action, (const Object *) this, arg0);
}
void AcceptDialog::_ok() {
___godot_icall_void(___mb.mb__ok, (const Object *) this);
}
Button *AcceptDialog::add_button(const String text, const bool right, const String action) {
return (Button *) ___godot_icall_Object_String_bool_String(___mb.mb_add_button, (const Object *) this, text, right, action);
}
Button *AcceptDialog::add_cancel(const String name) {
return (Button *) ___godot_icall_Object_String(___mb.mb_add_cancel, (const Object *) this, name);
}
bool AcceptDialog::get_hide_on_ok() const {
return ___godot_icall_bool(___mb.mb_get_hide_on_ok, (const Object *) this);
}
Label *AcceptDialog::get_label() {
return (Label *) ___godot_icall_Object(___mb.mb_get_label, (const Object *) this);
}
Button *AcceptDialog::get_ok() {
return (Button *) ___godot_icall_Object(___mb.mb_get_ok, (const Object *) this);
}
String AcceptDialog::get_text() const {
return ___godot_icall_String(___mb.mb_get_text, (const Object *) this);
}
bool AcceptDialog::has_autowrap() {
return ___godot_icall_bool(___mb.mb_has_autowrap, (const Object *) this);
}
void AcceptDialog::register_text_enter(const Node *line_edit) {
___godot_icall_void_Object(___mb.mb_register_text_enter, (const Object *) this, line_edit);
}
void AcceptDialog::set_autowrap(const bool autowrap) {
___godot_icall_void_bool(___mb.mb_set_autowrap, (const Object *) this, autowrap);
}
void AcceptDialog::set_hide_on_ok(const bool enabled) {
___godot_icall_void_bool(___mb.mb_set_hide_on_ok, (const Object *) this, enabled);
}
void AcceptDialog::set_text(const String text) {
___godot_icall_void_String(___mb.mb_set_text, (const Object *) this, text);
}
} |
aspose-cells-cloud/aspose-cells-cloud-cpp | include/aspose_cells_cloud/models/pdf_save_options.h | <reponame>aspose-cells-cloud/aspose-cells-cloud-cpp<gh_stars>0
/** --------------------------------------------------------------------------------------------------------------------
* <copyright company="Aspose" file=" pdf_save_options.h">
* Copyright (c) 2022 Aspose.Cells for Cloud
* </copyright>
* <summary>
* 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.
* </summary>
-------------------------------------------------------------------------------------------------------------------- **/
#pragma once
#include "./model_base.h"
#include "./save_options.h"
#include "./pdf_security_options.h"
namespace aspose::cells::cloud::models {
/// <summary>
///
/// </summary>
class PdfSaveOptions : public SaveOptions
{
public:
ASPOSE_CELLS_CLOUD_EXPORT virtual ~PdfSaveOptions() = default;
ASPOSE_CELLS_CLOUD_EXPORT virtual void toJson(void* jsonIfc) const override;
ASPOSE_CELLS_CLOUD_EXPORT virtual void fromJson(const void* jsonIfc) override;
ASPOSE_CELLS_CLOUD_EXPORT std::shared_ptr< bool > getCalculateFormula() const;
ASPOSE_CELLS_CLOUD_EXPORT void setCalculateFormula( std::shared_ptr< bool> value );
ASPOSE_CELLS_CLOUD_EXPORT std::shared_ptr< bool > getCheckFontCompatibility() const;
ASPOSE_CELLS_CLOUD_EXPORT void setCheckFontCompatibility( std::shared_ptr< bool> value );
ASPOSE_CELLS_CLOUD_EXPORT std::shared_ptr< bool > getOnePagePerSheet() const;
ASPOSE_CELLS_CLOUD_EXPORT void setOnePagePerSheet( std::shared_ptr< bool> value );
ASPOSE_CELLS_CLOUD_EXPORT std::shared_ptr< std::wstring > getCompliance() const;
ASPOSE_CELLS_CLOUD_EXPORT void setCompliance( std::shared_ptr< std::wstring> value );
ASPOSE_CELLS_CLOUD_EXPORT std::shared_ptr< std::wstring > getDefaultFont() const;
ASPOSE_CELLS_CLOUD_EXPORT void setDefaultFont( std::shared_ptr< std::wstring> value );
ASPOSE_CELLS_CLOUD_EXPORT std::shared_ptr< std::wstring > getPrintingPageType() const;
ASPOSE_CELLS_CLOUD_EXPORT void setPrintingPageType( std::shared_ptr< std::wstring> value );
ASPOSE_CELLS_CLOUD_EXPORT std::shared_ptr< std::wstring > getImageType() const;
ASPOSE_CELLS_CLOUD_EXPORT void setImageType( std::shared_ptr< std::wstring> value );
ASPOSE_CELLS_CLOUD_EXPORT std::shared_ptr< int > getDesiredPPI() const;
ASPOSE_CELLS_CLOUD_EXPORT void setDesiredPPI( std::shared_ptr< int> value );
ASPOSE_CELLS_CLOUD_EXPORT std::shared_ptr< int > getJpegQuality() const;
ASPOSE_CELLS_CLOUD_EXPORT void setJpegQuality( std::shared_ptr< int> value );
ASPOSE_CELLS_CLOUD_EXPORT std::shared_ptr< aspose::cells::cloud::models::PdfSecurityOptions > getSecurityOptions() const;
ASPOSE_CELLS_CLOUD_EXPORT void setSecurityOptions( std::shared_ptr< aspose::cells::cloud::models::PdfSecurityOptions> value );
protected:
std::shared_ptr< bool > m_CalculateFormula;
std::shared_ptr< bool > m_CheckFontCompatibility;
std::shared_ptr< bool > m_OnePagePerSheet;
std::shared_ptr< std::wstring > m_Compliance;
std::shared_ptr< std::wstring > m_DefaultFont;
std::shared_ptr< std::wstring > m_PrintingPageType;
std::shared_ptr< std::wstring > m_ImageType;
std::shared_ptr< int > m_DesiredPPI;
std::shared_ptr< int > m_JpegQuality;
std::shared_ptr< aspose::cells::cloud::models::PdfSecurityOptions > m_SecurityOptions;
};
}
|
rf-toothpic/tp-iscream | app/containers/Auth/selectors.js | import { initialState } from 'containers/Leaderboard/reducer'
import { createSelector } from 'reselect'
/**
* Direct selector to the auth state domain
*/
const selectAuthDomain = state => state.auth || initialState
/**
* Generic item selector - use if no data mutations/calculations occur
*/
export const selectItem = item =>
createSelector(selectAuthDomain, state => state && state[item])
export const selectUsers = () =>
createSelector(selectAuthDomain, state => {
return state.users
})
/**
* Other specific selectors
*/
/**
* Default selector used by Auth
*/
const makeSelectAuth = () => createSelector(selectAuthDomain, substate => substate)
export default makeSelectAuth
|
nuxodin/vanilla-cms | m/core/js/qgCalendar0/qgCalendar.js | <reponame>nuxodin/vanilla-cms<gh_stars>1-10
!function(){
'use strict';
var today;
window.qgCalendar = function(el, selected) {
today = new Date();
this.selected = selected;
el.classList.add('qgCalendar');
var fragment = c1.dom.fragment(
'<table>'+
'<tbody>'+
'<tr>'+
'<td class=-calLeft>◄'+
'<td class=-calHead>;'+
'<td class=-calRight>►'+
'</table>'+
'<table class=-table><tbody></table>'
);
this.goLeft = fragment.querySelector('.-calLeft');
this.head = fragment.querySelector('.-calHead');
this.goRight = fragment.querySelector('.-calRight');
this.table = fragment.querySelector('.-table');
el.append(fragment);
this.dates = {};
};
qgCalendar.prototype = {
show12Years:function(y) {
var _this = this;
y = y-(y+6)%12;
this.head.immerHTML = y+' - '+(y+12);
this.goLeft.onclick = function(){ _this.show12Years(y-13); };
this.goRight.onclick = function(){ _this.show12Years(y+12); };
this.table.innerHTML = '';
times(3,function(){
var tr = _this.table.insertRow();
times(4,function(){
var time = new Date(++y,0);
var td = tr.insertCell();
time.getFullYear() === today.getFullYear() && td.classList.add('-today');
time.getFullYear() === _this.selected.getFullYear() && td.classList.add('-selected');
td.innerHTML = y;
td.value = y;
td.onclick = function(){
_this.selected.setY(td.value);
_this.onChange() !== false && _this.showYear(td.value);
};
});
});
},
showYear:function(y) {
var _this = this;
this.head.innerHTML = y;
this.head.onclick = function(){_this.show12Years(y);};
this.goLeft.onclick = function(){_this.showYear(y-1);};
this.goRight.onclick = function(){_this.showYear(y+1);};
this.table.innerHTML = '';
var time = new Date(y,0);
var m = 0;
times(3,function(){
var tr = _this.table.insertRow();
times(4,function(){
time = new Date(y, m++);
var td = tr.insertCell();
if (today.getFullYear() === time.getFullYear() &&
today.getMonth() === time.getMonth()) {
td.classList.add('-today');
}
if (_this.selected.getFullYear() === time.getFullYear() &&
_this.selected.getMonth() === time.getMonth()) {
td.classList.add('-selected');
}
td.innerHTML = time.toString().substr(4,3);
td.value = time.getMonth();
td.onclick = function(){
_this.selected.setM(td.value);
_this.onChange() !== false && _this.showMonth(y,td.value);
};
});
});
},
showMonth:function(y,m) {
var _this = this;
var D = new Date(y,m);
y = D.getFullYear();
m = D.getMonth();
var month = new Date(y, m).toString().substr(4,3);
this.head.innerHTML = month+' '+y;
this.head.onclick = function(){_this.showYear(y);};
this.goLeft.onclick = function(){_this.showMonth(y,m-1);};
this.goRight.onclick = function(){_this.showMonth(y,m+1);};
this.table.innerHTML = '';
var d = - new Date(y,m,-1).getDay(); // -1 wochenstart montag
var time = new Date(y, m, d);
times(6,function(){
var tr = _this.table.insertRow();
times(7,function(){
time = new Date(y, m, d++);
var td = tr.insertCell();
m != time.getMonth() && td.classList.add('-outMonth');
if (time.getFullYear() === today.getFullYear() &&
time.getMonth() === today.getMonth() &&
time.getDate() === today.getDate()) {
td.classList.add('-today');
}
if (time.getFullYear() === _this.selected.getFullYear() &&
time.getMonth() === _this.selected.getMonth() &&
time.getDate() === _this.selected.getDate()) {
td.classList.add('-selected');
}
td.innerHTML = time.getDate();
td.year = time.getFullYear();
td.month = time.getMonth();
td.date = time.getDate();
td.onclick = function(){
_this.selected.setY(td.year);
_this.selected.setM(td.month);
_this.selected.setD(td.date);
if (_this.onChange() !== false && _this.selected.getH() !== null) {
_this.showDay(td.year,td.month,td.date);
}
};
});
});
},
showDay:function(y,m,d) {
var _this = this;
var month = new Date(y, m).toString().substr(4,3);
this.head.innerHTML = d+'. '+month+' '+y;
this.head.onclick = function(){_this.showMonth(y,m);};
this.goLeft.onclick = function(){_this.showDay(y,m,d-1);};
this.goRight.onclick = function(){_this.showDay(y,m,d+1);};
this.table.innerHTML = '';
var tr = this.table.insertRow();
var td = tr.insertCell();
var div = c1.dom.fragment('<div style="margin:4px auto;position:relative">').firstChild;
td.append(div);
var tp = new TimePicker(div, {onChange:function(){
_this.selected.setH(tp.time.hour);
_this.selected.setMin(tp.time.minute);
_this.onChange();
}});
tp.time.hour = this.selected.getH();
tp.time.minute = this.selected.getMin();
tp.updateAmPm();
tp.moveHands();
}
};
function times(number, fn){
while (number--) fn();
}
}();
|
joaomfas/LAPR4-2019-2020 | app/base.core/src/test/java/eapli/base/gestaomensagens/dominio/MensagemTest.java | package eapli.base.gestaomensagens.dominio;
import java.util.Date;
import org.junit.Test;
import static org.junit.Assert.*;
public class MensagemTest {
public MensagemTest() {
}
@Test(expected = IllegalArgumentException.class)
public void vericarMensagemNaoNula() {
new Mensagem(null, null, null);
}
@Test(expected = IllegalArgumentException.class)
public void verificarMensagemInvalida1() {
String mensagem = "abc";
new Mensagem(1, Codes.HELLO.getCode(), 1770, 1, mensagem);
}
@Test
public void verificarMensagemValida() {
Mensagem expected = new Mensagem("Mensagem válida", new Date(), new Date());
Mensagem result = new Mensagem("Mensagem válida", new Date(), new Date());
assertEquals(expected, result);
}
@Test
public void verificarMensagemValida2() {
String mensagem = "abc";
new Mensagem(1, Codes.HELLO.getCode(), 1770, 3, mensagem);
}
}
|
johnqkd/nospoon | src/lib/task/items/applyInteractiveTask.js | import walletLib from '@/lib/wallet';
import {walletRepository} from "@/db/repository/walletRepository";
import {
interactiveTaskType,
interactiveTaskStatus,
interactiveTaskRepository,
} from '@/db/repository/interactiveTaskRepository';
import TonApi from "@/api/ton";
import database from '@/db';
import insufficientFundsException from "@/lib/task/exception/insufficientFundsException";
import keystoreLib from "@/lib/keystore";
import keystoreException from "@/lib/keystore/keystoreException";
import tokenContractLib from "@/lib/token/contract";
import {tokenContractException, tokenContractExceptionCodes} from "@/lib/token/TokenContractException";
import {tokenRepository} from "@/db/repository/tokenRepository";
import interactiveTaskCallback from "@/lib/task/interactive/callback";
import addToken from "@/lib/task/interactive/callback/addToken";
import UndecimalIsNotIntegerException from "@/lib/token/UndecimalIsNotIntegerException";
const _ = {
checkSufficientFunds(wallet, networkId, amount) {
const balance = BigInt(wallet.networks[networkId].balance);
if (balance < amount) {
throw new insufficientFundsException();
}
}
}
export default {
name: 'applyInteractiveTask',
async handle(task) {
const {interactiveTaskId, password, form} = task.data;
let interactiveTask = await interactiveTaskRepository.getTask(interactiveTaskId);
if (interactiveTask.statusId === interactiveTaskStatus.new) {
interactiveTask.statusId = interactiveTaskStatus.process;
interactiveTask.error = null;
await interactiveTaskRepository.updateTasks([interactiveTask]);
let result = {};
try {
//@TODO refactoring
const db = await database.getClient();
const wallet = await walletRepository.getCurrent();
const server = (await db.network.get(interactiveTask.networkId)).server;
if (wallet.isKeysEncrypted) {
wallet.keys = await keystoreLib.decrypt(server, wallet.keys, password);
}
switch (interactiveTask.typeId) {
case interactiveTaskType.deployWalletContract: {
//TODO FEES
const amountWithFee = BigInt('73000000');
_.checkSufficientFunds(wallet, interactiveTask.networkId, amountWithFee);
await walletLib.deploy(server, wallet);
break;
}
case interactiveTaskType.uiTransfer: {
const nanoAmount = walletLib.convertToNano(form.amount);
//TODO FEES
const amountWithFee = BigInt('11000000') + nanoAmount;
_.checkSufficientFunds(wallet, interactiveTask.networkId, amountWithFee);
const payload = form.comment !== ''
? await walletLib.createTransferPayload(server, form.comment)
: '';
const message = await walletLib.createTransferMessage(
server,
wallet,
wallet.address,
form.address,
nanoAmount.toString(),
false,
payload
);
const processingState = await TonApi.sendMessage(server, message);
await TonApi.waitForRunTransaction(server, message, processingState);
break;
}
case interactiveTaskType.preDeployTransfer: {
//TODO FEES
const amountWithFee = BigInt('11000000') + BigInt(interactiveTask.params.options.initAmount);
_.checkSufficientFunds(wallet, interactiveTask.networkId, amountWithFee);
const initParams = interactiveTask.params.options.initParams !== undefined ? interactiveTask.params.options.initParams : {};
const address = await TonApi.predictAddress(server, wallet.keys.public, interactiveTask.params.abi, interactiveTask.params.imageBase64, initParams);
await walletLib.transfer(server, wallet, address, interactiveTask.params.options.initAmount);
break;
}
case interactiveTaskType.deployContract: {
const amountWithFee = BigInt('73000000');
_.checkSufficientFunds(wallet, interactiveTask.networkId, amountWithFee);
const initParams = interactiveTask.params.options.initParams !== undefined ? interactiveTask.params.options.initParams : {};
result = await walletLib.deployContract(server, wallet, interactiveTask.params.abi, interactiveTask.params.imageBase64, initParams, interactiveTask.params.constructorParams);
if (interactiveTask.params.async === false) {
result = await TonApi.waitForDeployTransaction(server, result.message, result.processingState);
}
break;
}
case interactiveTaskType.runTransaction: {
const message = await TonApi.createRunMessage(server, interactiveTask.params.address, interactiveTask.params.abi, interactiveTask.params.method, interactiveTask.params.params, wallet.keys);
const processingState = await TonApi.sendMessage(server, message);
const txid = await TonApi.waitForRunTransaction(server, message, processingState);
// if (interactiveTask.params.async === false) {
// }
result = {txid};
break;
}
case interactiveTaskType.transfer: {
if (walletLib.isAddressesMatch(wallet.address, interactiveTask.params.walletAddress)) {
const amountWithFee = BigInt('11000000') + BigInt(interactiveTask.params.amount);
_.checkSufficientFunds(wallet, interactiveTask.networkId, amountWithFee);
}
const message = await walletLib.createTransferMessage(
server,
wallet,
interactiveTask.params.walletAddress,
interactiveTask.params.address,
interactiveTask.params.amount,
interactiveTask.params.bounce,
interactiveTask.params.payload || ''
);
const processingState = await TonApi.sendMessage(server, message);
result = {processingState, message};
if (interactiveTask.params.async === false) {
result = await TonApi.waitForRunTransaction(server, result.message, result.processingState);
}
break;
}
case interactiveTaskType.addToken: {
//@TODO validate address
const {contract, boc} = await tokenContractLib.getContractByAddress(server, form.address);
const tokenData = await contract.getTokenData(server, boc, form.address, wallet.keys.public);
if (await tokenRepository.isTokenExists(interactiveTask.networkId, form.address, interactiveTask.params.walletId)) {
throw new tokenContractException(tokenContractExceptionCodes.alreadyAdded.code);
}
const token = await tokenRepository.create(
contract.id,
interactiveTask.networkId,
interactiveTask.params.walletId,
form.address,
tokenData.name,
tokenData.symbol,
tokenData.decimals,
tokenData.walletAddress,
tokenData.balance,
tokenData.params,
);
interactiveTask.data.callback = {name: addToken.name, params: [token.id]};
break;
}
case interactiveTaskType.uiTransferToken: {
const token = await tokenRepository.getToken(interactiveTask.params.tokenId);
const contract = tokenContractLib.getContractById(token.contractId);
const undecimalAmount = tokenContractLib.undecimal(token, form.amount);
tokenContractLib.checkSufficientFunds(token, undecimalAmount);
await contract.transfer(server, wallet.keys, token, form.address, undecimalAmount);
break;
}
case interactiveTaskType.confirmTransaction: {
const message = await walletLib.createConfirmTransactionMessage(
server,
wallet,
interactiveTask.params.walletAddress,
interactiveTask.params.txid,
);
const processingState = await TonApi.sendMessage(server, message);
result = {processingState, message};
break;
}
default: {
throw 'Unknown interactive type.';
}
}
interactiveTask.statusId = interactiveTaskStatus.performed;
interactiveTask.result = result;
if (interactiveTask.data.callback !== undefined) {
const frontPostApply = await interactiveTaskCallback.call(interactiveTask.data.callback);
if (typeof frontPostApply !== 'undefined') {
interactiveTask.data.frontPostApply = frontPostApply;
}
}
} catch (e) {
console.error(e);
interactiveTask.statusId = interactiveTaskStatus.new;
if (e instanceof insufficientFundsException) {
interactiveTask.error = e.error;
} else if (e instanceof UndecimalIsNotIntegerException) {
interactiveTask.error = e.error;
} else if (e instanceof keystoreException) {
interactiveTask.error = e.message;
} else if (e instanceof tokenContractException) {
interactiveTask.error = e.toString();
} else {
interactiveTask.error = 'Error';
}
throw e;
} finally {
await interactiveTaskRepository.updateTasks([interactiveTask]);
}
}
const interactiveTasks = await interactiveTaskRepository.getAll();
return {interactiveTasks, interactiveTask};
}
}
|
robinfehr/cf-adapter | lib/graceRequestHandler/connectionReset.js | module.exports = (options) => {
const err = options.error;
// const response = options.response;
// const result = options.result;
// const infos = options.infos;
// const attempt = options.attempt;
if (err && err.code === 'ECONNRESET') {
return 'TCP conversation abruptly closed';
}
};
|
sanjnair/projects | university/usc_csci_551_communications/project3/ckbhandler.h | <reponame>sanjnair/projects
/***************************************************************************
** Sun Aug 27 2006
** (C) 2006 by <NAME>
** sanjaysn <at> usc <dot> edu
****************************************************************************/
#ifndef CKBHANDLER_H
#define CKBHANDLER_H
#include "cglobal.h"
#include "ciservant.h"
#include "cthread.h"
#include "cmutexlocker.h"
#define MAX_USER_INPUT 1000
class CKbHandler : public CThread
{
public:
CKbHandler();
~CKbHandler();
void run();
void stop();
void setServantHandle(IServant *s);
void opInterrupted();
void outputStr(const string &str, bool newLine=false);
string getUserInput() const;
private:
bool isStopFlagEnabled();
void setOpInProgress(bool flag);
bool isOpInProgress();
void outputPrompt();
void handleUserInput();
bool processInput(const string &input);
void initSigHandler();
void errorIfInvalidSigCode(int code, const string &method) const;
bool _stopFlag;
bool _opInProgress;
IServant *_servant;
string _prompt;
struct sigaction _sigAct;
sigset_t _sigmask;
CMutex _mutex;
};
#endif //CKBHANDLER_H
|
neet-no1/menu-deliver-api | src/main/java/jp/co/suyama/menu/deliver/model/ArticlesAndPage.java | <filename>src/main/java/jp/co/suyama/menu/deliver/model/ArticlesAndPage.java
package jp.co.suyama.menu.deliver.model;
import java.util.List;
import jp.co.suyama.menu.deliver.model.auto.ArticleData;
import jp.co.suyama.menu.deliver.model.auto.PageNation;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ArticlesAndPage {
private List<ArticleData> articleDataList;
private PageNation page;
}
|
tliden/AvodahLOS | content/container/decision-engine-service-container/utilities/views/ocr/index.js | 'use strict';
const components = require('./components');
module.exports = {
components,
}; |
vigsterkr/netket | Sources/Machine/py_abstract_machine.ipp | // Copyright 2019 The Simons Foundation, Inc. - All Rights Reserved.
//
// 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.
//#include "Machine/py_abstract_machine.hpp"
#include <cstdio>
#include <pybind11/complex.h>
#include <pybind11/eigen.h>
#include <pybind11/pybind11.h>
#include "Utils/messages.hpp"
namespace netket {
namespace detail {
namespace {
bool ShouldIDoIO() noexcept {
auto rank = 0;
auto const status = MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (status == MPI_SUCCESS) {
return rank == 0;
}
std::fprintf(stderr,
"[NetKet] MPI_Comm_rank failed: doing I/O on all processes.\n");
return true;
}
template <class Function, class... Args>
auto ShouldNotThrow(Function &&function, Args &&... args) noexcept
-> decltype(std::declval<Function &&>()(std::declval<Args &&>()...)) {
try {
return std::forward<Function>(function)(std::forward<Args>(args)...);
} catch (std::exception &e) {
if (ShouldIDoIO()) {
std::fprintf(
stderr,
"[NetKet] Fatal error: exception was thrown in a `noexcept` context\n"
"[NetKet] Info: %s\n"
"[NetKet]\n"
"[NetKet] This is a bug. Please, be so kind to open an issue at\n"
"[NetKet] https://github.com/netket/netket/issues\n"
"[NetKet]\n"
"[NetKet] Aborting...\n",
e.what());
}
MPI_Abort(MPI_COMM_WORLD, -1);
std::abort(); // This call is unreachable and is here just to tell the
// compiler that this branch never returns (MPI_Abort is not
// marked [[noreturn]]).
} catch (...) {
if (ShouldIDoIO()) {
std::fprintf(
stderr,
"[NetKet] Fatal error: exception was thrown in a `noexcept` context\n"
"[NetKet] Aborting...\n");
}
MPI_Abort(MPI_COMM_WORLD, -1);
std::abort(); // This call is unreachable and is here just to tell the
// compiler that this branch never returns (MPI_Abort is not
// marked [[noreturn]]).
}
}
} // namespace
} // namespace detail
template <class AMB>
int PyAbstractMachine<AMB>::Npar() const {
return detail::ShouldNotThrow([this]() {
PYBIND11_OVERLOAD_PURE_NAME(int, /* Return type */
AbstractMachine, /* Parent class */
"_n_par", /* Name of the function in Python */
Npar, /* Name of function in C++ */
);
});
}
template <class AMB>
bool PyAbstractMachine<AMB>::IsHolomorphic() const noexcept {
return detail::ShouldNotThrow([this]() {
PYBIND11_OVERLOAD_PURE_NAME(
bool, /* Return type */
AMB, /* Parent class */
"_is_holomorphic", /* Name of the function in Python */
IsHolomorphic, /* Name of function in C++ */
);
});
}
template <class AMB>
typename AMB::VectorType PyAbstractMachine<AMB>::GetParameters() {
PYBIND11_OVERLOAD_PURE_NAME(
VectorType, /* Return type */
AMB, /* Parent class */
"_get_parameters", /* Name of the function in Python */
GetParameters, /* Name of function in C++ */
);
}
template <class AMB>
void PyAbstractMachine<AMB>::SetParameters(VectorConstRefType pars) {
PYBIND11_OVERLOAD_PURE_NAME(
void, /* Return type */
AMB, /* Parent class */
"_set_parameters", /* Name of the function in Python */
SetParameters, /* Name of function in C++ */
pars);
}
template <class AMB>
void PyAbstractMachine<AMB>::LogVal(Eigen::Ref<const RowMatrix<double>> v,
Eigen::Ref<Eigen::VectorXcd> out,
const any & /*unused*/) {
PYBIND11_OVERLOAD_PURE_NAME(void, /* Return type */
AMB, /* Parent class */
"log_val", /* Name of the function in Python */
LogVal, /* Name of function in C++ */
v, out);
}
template <class AMB>
Complex PyAbstractMachine<AMB>::LogValSingle(VisibleConstType v,
const any &cache) {
Complex data;
auto out = Eigen::Map<Eigen::VectorXcd>(&data, 1);
LogVal(v.transpose(), out, cache);
return data;
}
template <class AMB>
any PyAbstractMachine<AMB>::InitLookup(VisibleConstType /*unused*/) {
return {};
}
template <class AMB>
void PyAbstractMachine<AMB>::UpdateLookup(
VisibleConstType /*unused*/, const std::vector<int> & /*unused*/,
const std::vector<double> & /*unused*/, any & /*unused*/) {}
template <class AMB>
void PyAbstractMachine<AMB>::DerLog(Eigen::Ref<const RowMatrix<double>> v,
Eigen::Ref<RowMatrix<Complex>> out,
const any & /*unused*/) {
PYBIND11_OVERLOAD_PURE_NAME(void, /* Return type */
AMB, /* Parent class */
"der_log", /* Name of the function in Python */
DerLog, /* Name of function in C++ */
v, out);
}
template <class AMB>
PyObject *PyAbstractMachine<AMB>::StateDict() {
return [this]() {
PYBIND11_OVERLOAD_PURE_NAME(
pybind11::object, /* Return type */
AMB, /* Parent class */
"state_dict", /* Name of the function in Python */
StateDict, /* Name of function in C++ */
/*Arguments*/
);
}()
.release()
.ptr();
}
template <class AMB>
void PyAbstractMachine<AMB>::Save(const std::string &filename) const {
PYBIND11_OVERLOAD_NAME(void, /* Return type */
AMB, /* Parent class */
"save", /* Name of the function in Python */
Save, /* Name of function in C++ */
filename /*Arguments*/
);
}
template <class AMB>
void PyAbstractMachine<AMB>::Load(const std::string &filename) {
PYBIND11_OVERLOAD_NAME(void, /* Return type */
AMB, /* Parent class */
"load", /* Name of the function in Python */
Load, /* Name of function in C++ */
filename /*Arguments*/
);
}
} // namespace netket
|
LK26/outline-client | third_party/tap-windows6/src/proto.h | /*
* TAP-Windows -- A kernel driver to provide virtual tap
* device functionality on Windows.
*
* This code was inspired by the CIPE-Win32 driver by <NAME>.
*
* This source code is Copyright (C) 2002-2014 OpenVPN Technologies, Inc.,
* and is released under the GPL version 2 (see below).
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program (see the file COPYING included with this
* distribution); if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
//============================================================
// MAC address, Ethernet header, and ARP
//============================================================
#pragma pack(1)
#define IP_HEADER_SIZE 20
#define IPV6_HEADER_SIZE 40
#define MACADDR_SIZE 6
typedef unsigned char MACADDR[MACADDR_SIZE];
typedef unsigned long IPADDR;
typedef unsigned char IPV6ADDR[16];
//-----------------
// Ethernet address
//-----------------
typedef struct {
MACADDR addr;
} ETH_ADDR;
typedef struct {
ETH_ADDR list[TAP_MAX_MCAST_LIST];
} MC_LIST;
// BUGBUG!!! Consider using ststem defines in netiodef.h!!!
//----------------
// Ethernet header
//----------------
typedef struct {
MACADDR dest; /* destination eth addr */
MACADDR src; /* source ether addr */
USHORT proto; /* packet type ID field */
} ETH_HEADER, *PETH_HEADER;
//----------------
// ARP packet
//----------------
typedef struct {
MACADDR m_MAC_Destination; // Reverse these two
MACADDR m_MAC_Source; // to answer ARP requests
USHORT m_Proto; // 0x0806
#define MAC_ADDR_TYPE 0x0001
USHORT m_MAC_AddressType; // 0x0001
USHORT m_PROTO_AddressType; // 0x0800
UCHAR m_MAC_AddressSize; // 0x06
UCHAR m_PROTO_AddressSize; // 0x04
#define ARP_REQUEST 0x0001
#define ARP_REPLY 0x0002
USHORT m_ARP_Operation; // 0x0001 for ARP request, 0x0002 for ARP reply
MACADDR m_ARP_MAC_Source;
IPADDR m_ARP_IP_Source;
MACADDR m_ARP_MAC_Destination;
IPADDR m_ARP_IP_Destination;
} ARP_PACKET, *PARP_PACKET;
//----------
// IP Header
//----------
typedef struct {
#define IPH_GET_VER(v) (((v) >> 4) & 0x0F)
#define IPH_GET_LEN(v) (((v)&0x0F) << 2)
UCHAR version_len;
UCHAR tos;
USHORT tot_len;
USHORT id;
#define IP_OFFMASK 0x1fff
USHORT frag_off;
UCHAR ttl;
#define IPPROTO_UDP 17 /* UDP protocol */
#define IPPROTO_TCP 6 /* TCP protocol */
#define IPPROTO_ICMP 1 /* ICMP protocol */
#define IPPROTO_IGMP 2 /* IGMP protocol */
UCHAR protocol;
USHORT check;
ULONG saddr;
ULONG daddr;
/* The options start here. */
} IPHDR;
//-----------
// UDP header
//-----------
typedef struct {
USHORT source;
USHORT dest;
USHORT len;
USHORT check;
} UDPHDR;
//--------------------------
// TCP header, per RFC 793.
//--------------------------
typedef struct {
USHORT source; /* source port */
USHORT dest; /* destination port */
ULONG seq; /* sequence number */
ULONG ack_seq; /* acknowledgement number */
#define TCPH_GET_DOFF(d) (((d)&0xF0) >> 2)
UCHAR doff_res;
#define TCPH_FIN_MASK (1 << 0)
#define TCPH_SYN_MASK (1 << 1)
#define TCPH_RST_MASK (1 << 2)
#define TCPH_PSH_MASK (1 << 3)
#define TCPH_ACK_MASK (1 << 4)
#define TCPH_URG_MASK (1 << 5)
#define TCPH_ECE_MASK (1 << 6)
#define TCPH_CWR_MASK (1 << 7)
UCHAR flags;
USHORT window;
USHORT check;
USHORT urg_ptr;
} TCPHDR;
#define TCPOPT_EOL 0
#define TCPOPT_NOP 1
#define TCPOPT_MAXSEG 2
#define TCPOLEN_MAXSEG 4
//------------
// IPv6 Header
//------------
typedef struct {
UCHAR version_prio;
UCHAR flow_lbl[3];
USHORT payload_len;
#define IPPROTO_ICMPV6 0x3a /* ICMP protocol v6 */
UCHAR nexthdr;
UCHAR hop_limit;
IPV6ADDR saddr;
IPV6ADDR daddr;
} IPV6HDR;
//--------------------------------------------
// IPCMPv6 NS/NA Packets (RFC4443 and RFC4861)
//--------------------------------------------
// Neighbor Solictiation - RFC 4861, 4.3
// (this is just the ICMPv6 part of the packet)
typedef struct {
UCHAR type;
#define ICMPV6_TYPE_NS 135 // neighbour solicitation
UCHAR code;
#define ICMPV6_CODE_0 0 // no specific sub-code for NS/NA
USHORT checksum;
ULONG reserved;
IPV6ADDR target_addr;
} ICMPV6_NS;
// Neighbor Advertisement - RFC 4861, 4.4 + 4.6/4.6.1
// (this is just the ICMPv6 payload)
typedef struct {
UCHAR type;
#define ICMPV6_TYPE_NA 136 // neighbour advertisement
UCHAR code;
#define ICMPV6_CODE_0 0 // no specific sub-code for NS/NA
USHORT checksum;
UCHAR rso_bits; // Router(0), Solicited(2), Ovrrd(4)
UCHAR reserved[3];
IPV6ADDR target_addr;
// always include "Target Link-layer Address" option (RFC 4861 4.6.1)
UCHAR opt_type;
#define ICMPV6_OPTION_TLLA 2
UCHAR opt_length;
#define ICMPV6_LENGTH_TLLA 1 // multiplied by 8 -> 1 = 8 bytes
MACADDR target_macaddr;
} ICMPV6_NA;
// this is the complete packet with Ethernet and IPv6 headers
typedef struct {
ETH_HEADER eth;
IPV6HDR ipv6;
ICMPV6_NA icmpv6;
} ICMPV6_NA_PKT;
#pragma pack()
|
zhangkn/iOS14Header | System/Library/PrivateFrameworks/iWorkImport.framework/Frameworks/TSCharts.framework/TSCH3DGeometryResource.h | <reponame>zhangkn/iOS14Header<gh_stars>1-10
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 12:31:25 PM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/iWorkImport.framework/Frameworks/TSCharts.framework/TSCharts
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
@class TSCH3DResource, TSCH3DGeometryArrays, TSCH3DGeometry;
@interface TSCH3DGeometryResource : NSObject {
int _type;
TSCH3DResource* _resource;
TSCH3DGeometryArrays* _arrays;
TSCH3DGeometry* _geometry;
}
@property (assign,nonatomic) int type; //@synthesize type=_type - In the implementation block
@property (nonatomic,retain,readonly) TSCH3DResource * resource; //@synthesize resource=_resource - In the implementation block
@property (nonatomic,copy,readonly) TSCH3DGeometryArrays * arrays; //@synthesize arrays=_arrays - In the implementation block
@property (nonatomic,retain,readonly) TSCH3DGeometry * geometry; //@synthesize geometry=_geometry - In the implementation block
@property (nonatomic,readonly) BOOL hasArrays;
+(id)resource;
+(id)resourceWithType:(int)arg1 resource:(id)arg2 ;
+(id)resourceWithType:(int)arg1 resource:(id)arg2 arrays:(id)arg3 geometry:(id)arg4 ;
-(TSCH3DResource *)resource;
-(void)dealloc;
-(int)type;
-(TSCH3DGeometryArrays *)arrays;
-(void)setType:(int)arg1 ;
-(TSCH3DGeometry *)geometry;
-(void)submitWithProcessor:(id)arg1 ;
-(id)initWithType:(int)arg1 resource:(id)arg2 arrays:(id)arg3 geometry:(id)arg4 ;
-(void)submitToProcessor:(id)arg1 withPortion:(int)arg2 ;
-(BOOL)hasArrays;
-(id)initWithType:(int)arg1 resource:(id)arg2 ;
-(void)submitNoneWithProcessor:(id)arg1 ;
-(void)submitCapWithProcessor:(id)arg1 ;
@end
|
obogo/grunt-treeshake | tasks/treeshake.js | <filename>tasks/treeshake.js
/* global require, module, __dirname */
'use strict';
var removeComments = require('./utils/removeComments');
var printer = require('./utils/printer');
var emitter = require('./utils/emitter');
var toArray = require('./utils/toArray');
module.exports = function (grunt) {
var gruntLogHeader = grunt.log.header;
grunt.log.header = function () {
};
// :: INIT TASK DEPS :: //
require('grunt-contrib-uglify/tasks/uglify')(grunt);
// :: CONSTANTS :: //
var NEWLINE = '\n';
var TAB = '\t';
var CONSOLE = 'console';
var ALIASES = 'define|internal';
var PRINT_VERBOSE = 'print::verbose';
var PRINT_REPORT = 'print::report';
var PRINT_FILE = 'print::file';
var PRINT_LINE = 'print::line';
var PRINT_IGNORED = 'print:ignored';
var PRINT_FINALIZE = 'print::finalize';
var TMP_FILE = '.tmpTreeshake/treeshake.js';
var cache = {};
var ignored = {};// so it doesn't have to be passed around everywhere.
var exportAs = {};
var importPatterns = {};
var wrapHeader, wrapFooter, treeshakeHeader, treeshakeFooter, cleanReservedWords;
var everythingElse = /[^\*\.\w\d]/g;
var readFile = grunt.file.read;
var unfound = [];
var unfoundJunkFilter = new RegExp('^(' + ALIASES + '|\\[|\\s)');
var ignoreRx = /(internal|define)\(("|')(.*?)\2,/gim;// defined once.
wrapHeader = readFile(__dirname + '/files/wrap_header.js');
wrapFooter = readFile(__dirname + '/files/wrap_footer.js');
treeshakeHeader = readFile(__dirname + '/files/treeshake_header.js');
treeshakeFooter = readFile(__dirname + '/files/treeshake_footer.js');
function getLookupRegExp() {
return new RegExp('(' + ALIASES + ')([\\W\\s]+(("|\')[\\w|\\.]+\\3))+', 'gim');
}
function getPath(path) {
if (!cache[path]) {
cache[path] = readFile(path);
addPatterns(path);
}
return cache[path];
}
function getFileNameFromContents(path) {
var contents = getPath(path),
rx = getLookupRegExp(),
matches = contents.match(rx), i, len = matches && matches.length || 0;
for (i = 0; i < len; i += 1) {
matches[i] = matches[i].split(',').shift();// only get the first match in a statement.
matches[i] = matches[i].replace(cleanReservedWords, '');
matches[i] = matches[i].replace(everythingElse, '');
}
//if (!matches) {
// grunt.log.writeln(NO_DEF_FOUND.yellow, path);
//}
return matches;
}
// we get any pattern matches from the file contents.
// these will be used later on the inspect files to determine
// if this file should be included.
function addPatterns(path) {
var p = [], content = cache[path];
//var toggle = false;
//if (path.indexOf('toggleClass') !== -1) {
// grunt.log.writeln(path.blue);
// toggle = true;
//}
content.replace(/(\/\/!|\*)\s+pattern\s+\/(\\\/|.*?)+\//gim, function (match, g1, g2) {
var rx = match.replace(/.*?pattern\s+\//, '').replace(/\/$/, '');
//if (toggle) {
// grunt.log.writeln(rx.green);
//}
p.push({match: match, rx: new RegExp(rx, 'gim')});
return match;
});
if (p.length) {
importPatterns[path] = p;
}
}
function getIgnoredDefinitions(ignoredList, packages) {
var ignoredItems = {};
var files = grunt.file.expand(ignoredList);
var len = files.length;
var file;
for (var i = 0; i < len; i++) {
file = grunt.file.read(files[i]);
file.replace(ignoreRx, function(m, g1, g2, g3) {
ignoredItems[g3] = true;
if (packages[g3]) {
ignoredItems[packages[g3]] = true;
}
return m;
});
}
return ignoredItems;
}
/**
* Build up all of the packages provided from the config.
* @param {Object} files
* @param {Object} options
* @returns {{}}
*/
function buildPackages(files, options) {
emitter.fire(PRINT_VERBOSE, [NEWLINE + 'Definitions:']);
var packages = {};
var len, i, j, path, names, name, src;
var defs = [];
for (i in files) {
src = files[i].src;
len = src.length;
for (j = 0; j < len; j += 1) {
path = src[j];
names = getFileNameFromContents(path, options);
while (names && names.length) {
name = names.shift();
if (packages.hasOwnProperty(name) && packages[name] !== path) {
emitter.fire(PRINT_VERBOSE, ["overriding definition '" + name + "' at: " + packages[name] + " with: " + path]);
} else {
defs.push(name);
}
packages[name] = path;
}
}
}
defs.sort();
for (i in defs) {
emitter.fire(PRINT_VERBOSE, [TAB + (defs[i] + '').blue]);
}
return packages;
}
//TODO: exclude? maybe later.
function buildExclusions(exclusions, packages, dependencies, options) {
getPackageMatches('Gruntfile.js', packages, exclusions, options, 'exclude', dependencies, false);
return dependencies;
}
function getPackageNameFromPath(packages, path) {
for (var i in packages) {
if (packages[i] === path) {
return i;
}
}
}
function filterHash(dependencies, paths, packages, wrap, options) {
paths = paths || [];
var i, len = paths.length, expanded;
dependencies = dependencies || {};
for (i = 0; i < len; i += 1) {
if (paths[i].indexOf('*') !== -1) {
expanded = grunt.file.expand(paths[i]);
filterHash(dependencies, expanded, packages, wrap, options);
} else if (grunt.file.exists(paths[i])) {
findDependencies(paths[i], packages, dependencies, wrap, options);
}
}
return dependencies;
}
/**
* Filter out any paths that do not exist in the packages
* as long as there is no dependency reference.
* @param {Array} paths
* @param {Object} packages
* @param {String} wrap
* @param {Object} options
* @returns []
*/
function filter(paths, packages, wrap, options) {
paths = paths || [];
var result = [], i, dependencies = {}, written = {};
// if they provide imports. We need to add them.
if (options.import) {
// populates those on dependencies.
findKeys('Gruntfile.js', options.import, packages, dependencies, wrap, options, 'import');
}
filterHash(dependencies, paths, packages, wrap, options);
emitter.fire(PRINT_REPORT, NEWLINE + 'Included:');
for (i in dependencies) {
if (dependencies.hasOwnProperty(i)) {
if (ignored[dependencies[i].src] || ignored[dependencies[i].value]) {
//grunt.log.writeln(("INGORE:"+dependencies[i].src).yellow);
} else if (!written[dependencies[i].src]) {
written[dependencies[i].src] = true;
result.push(dependencies[i]);
}
} else {
// this is for duplicates that are skipped because they has multiple references in multiple files.
//grunt.log.writeln("SKIP " + dependencies[i].src);
}
}
result.sort();
for (i in result) {
emitter.fire(PRINT_FILE, result[i], {color: 'green'});
}
return result;
}
function getLineNumber(str, path) {
var content = getPath(path),// we must get our own content so it still has comment lines in it.
parts = content.replace(/(\n\r|\r\n|\r)/g, "\n").split("\n"), i, len = parts.length, index;
for (i = 0; i < len; i += 1) {
index = parts[i].indexOf(str);
if (index !== -1) {
return {num: i + 1};
}
}
return '';
}
function createRegExp(alias) {
return new RegExp('\\b' + alias + '(\\.\\w+|\\[("|\')\\w+\\2\\])+', 'gm');
}
function getAliasKeys(path, wrap) {
var contents = getPath(path), aliases = [], rx, keys = [], i, len, matches = [];
contents = removeComments(contents);
contents.replace(new RegExp('(\\w+)\\s?=\\s?' + wrap + ';', 'g'), function (match, g1) {
aliases.push(g1);
return match;
});
function handleMatch(match, g1, g2) {
var key, line;
if (g1.length > 1) {
line = getLineNumber(g1, path);
key = {value: g1.substr(1, g1.length).replace(everythingElse, ''), line: line.num, from: path};
keys.push(key);
}
return match;
}
if (aliases && (len = aliases.length)) {
// we found aliases so we need to check for matches and add them to the keys.
for (i = 0; i < len; i += 1) {
rx = createRegExp(aliases[i]);
contents.replace(rx, handleMatch);
}
}
return keys;
}
// it needs to match all patterns in that file to be included.
function matchesPatterns(pattern, path, options) {
// path is passed for debugging. When you need to debug regex then use path.indexOf('filename.js') !== -1.
// it will make your output much smaller.
var i, len = pattern.length, found = false,
contents = getPath(path, options),
uncommented = removeComments(contents);
for (i = 0; i < len; i += 1) {
found = pattern[i].rx.test(uncommented);
if (!found) {
return false;
}
}
return true;
}
function addImportPatternMatchesToKeys(keys, path, packages, options) {
var i, pattern, name, key;
for (i in importPatterns) {
if (importPatterns.hasOwnProperty(i)) {
if (matchesPatterns(importPatterns[i], path, options)) {
name = getPackageNameFromPath(packages, i.trim());
if (name) {
key = makeKey(name, path, i, options, 'pattern');
// use the first pattern match to get the line number.
key.line = getLineNumber(importPatterns[i][0].match, i);
keys.push(key);
} else {
grunt.log.writeln(("Missing package " + name + " (" + i + ")").red);
}
}
}
}
}
function findDependencies(path, packages, dependencies, wrap, options) {
var contents = '', i, len, rx, rx2, keys, len, split, keys, contentHead;
if (grunt.file.exists(path)) {
contents = getPath(path, options);
contents = removeComments(contents);
} else {
grunt.log.writeln("cannot find path", path.yellow);
}
contentHead = contents.split(/,\s+function\W/).shift();// only the stuff before the first { will have dependencies.
contentHead = contentHead.replace(/(\n|\r)/g, ' ');// remove new lines so we can find the dependencies.
rx = new RegExp('(' + wrap + '\\.|import\\s+)[\\w\\.\\*]+\\(?;?', 'gm');
keys = contentHead.match(rx) || [];
rx2 = new RegExp('(' + ALIASES + ')\\(("|\')(\\w\\.?)+\\2,\\s(\\[.*\\])?', 'gm');
// do the split shift here to only search everything before the first {. So we don't match
// quoted strings in the file.
keys = keys.concat(contentHead.match(rx2) || []);
len = keys && keys.length || 0;
keys = keys.concat(getAliasKeys(path, wrap) || []);
keys = keys.concat(options.match(contents) || []);
if (!options.ignorePatterns) {
addImportPatternMatchesToKeys(keys, path, packages, options);
}
// now we need to clean up the keys.
for (i = 0; i < len; i += 1) {
// if it is already a key object leave it as is.
// the strings we still need to convert to key objects.
if (typeof keys[i] === 'string') {
// if it has commas in the string, there are multiples, split them and try again.
if (keys[i].indexOf(',') !== -1) {
split = keys[i].split(',');
keys = keys.concat(split);
len = keys.length;
} else {
// we now have a single item string. So just make the key, and replace it.
keys[i] = makeKey(keys[i], path, null, options);
}
}
}
if (keys) {
findKeys(path, keys, packages, dependencies, wrap, options, 'file');
return dependencies;// dependencies
}
}
function makeKey(value, from, src, options, forceType) {
var line = from !== 'Gruntfile' ? getLineNumber(value, from) : null;
var cleanWrap = new RegExp('[^\'"](?=' + options.wrap + ')\\w+\\.', 'gi');
value = value.replace(cleanWrap, '');
value = value.replace(cleanReservedWords, '');
value = value.replace(everythingElse, '');
return {
value: value,
src: src,
line: line && line.num,
from: from,
type: forceType || (from === 'Gruntfile' ? 'file' : 'import')
};
}
function getPackageMatches(fromPath, packages, importStatements, options, type, dependencies, findAdditionalDependencies) {
var i, len = importStatements.length;
for (i = 0; i < len; i += 1) {
getPackageMatch(fromPath, packages, importStatements[i], options, type, dependencies, findAdditionalDependencies);
}
}
function getPackageMatch(fromPath, packages, statementOrKey, options, type, dependencies, findAdditionalDependencies) {
var i, names, name, match, key = statementOrKey;
dependencies = dependencies || {};
if (key) {
if (!key.value) {
key = {value: key + '', type: type};
}
match = packages[key.value];
// ignored prevents it from looking up it or it's dependencies.
if (ignored && ignored[key.value] && type !== 'import') {
return null;
}
if (!match && !key.value.match(unfoundJunkFilter)) {
unfound.push(key);// unfound dependencies.
}
if (match && !dependencies[key.value]) {
key = makeKey(key.value, fromPath, match, options, type);
dependencies[key.value] = key;
if (findAdditionalDependencies) {
findDependencies(match, packages, dependencies, options.wrap, options);
}
} else if (key.value && key.value.indexOf && key.value.indexOf('*') !== -1) {
// these will be strings not objects for keys.
var wild = key.value.substr(0, key.value.length - 1).split('.').join('/');
for (i in packages) {
if (packages[i].indexOf(wild) !== -1) {
names = getFileNameFromContents(packages[i], options);
while (names && names.length) {
name = names.shift();
if (!ignored || !ignored[name] || key.type === 'import') {
dependencies[name] = makeKey(key.value, fromPath, packages[name], options, type);
if (findAdditionalDependencies) {
findDependencies(packages[i], packages, dependencies, options.wrap, options);
}
}
}
}
}
}
}
return key;
}
function findKeys(path, keys, packages, dependencies, wrap, options, forceType) {
var len = keys.length, i;// match, i, names, j, key, name;
for (i = 0; i < len; i += 1) {
getPackageMatch(path, packages, keys[i], options, forceType, dependencies, true);
}
}
function printExclusions(files, packages) {
var ignoredList = Object.keys(ignored);
emitter.fire(PRINT_LINE, NEWLINE + "Ignored:");
emitter.fire(PRINT_IGNORED, ignoredList);
var len = files.length, i, j, found, result = [];
// makes sure all ignored files show up in the ignored list even it it was already removed from package.
// so the log shows that it was ignored.
ignoredList.map(function(path) {
if (path.split('.').pop().toLowerCase() === 'js') {
result.push(path);
}
});
// now filter out any packages that are ignored.
for (i in packages) {
if (packages.hasOwnProperty(i)) {
found = null;
for (j = 0; j < len; j += 1) {
if ((ignored && ignored[i]) || files[j].src === packages[i]) {
found = files[j];
break;
}
}
if (!found) {
result.push(packages[i]);
}
}
}
result.sort();
for (i in result) {
emitter.fire(PRINT_LINE, TAB + result[i].yellow);
}
}
function writeSources(wrap, files, dest, options) {
// first we put our header on there for define and require.
var str = wrapHeader, i, len, key;
if(options.embedRequire !== false) {
str += treeshakeHeader;
}
len = options.includes.length, key;
if (len) {
emitter.fire(PRINT_LINE, NEWLINE + 'Forced Includes:');
for (i = 0; i < len; i += 1) {
key = makeKey('include.' + i, 'Gruntfile.js', options.includes[i], options, 'include');
files.unshift(key);
emitter.fire(PRINT_FILE, key, {color: 'yellow'});
}
}
len = files.length;
for (i = 0; i < len; i += 1) {
str += '//! ' + files[i].src + NEWLINE;
str += getPath(files[i].src);
}
// these exports will force external definition alias references.
for (i in exportAs) {
grunt.log.writeln(('export ' + i + ' as ' + exportAs[i]).green);
str += "define('" + exportAs[i] + "', ['" + i + "'], function(fn) {" + NEWLINE +
" return fn;" + NEWLINE +
"});" + NEWLINE;
}
if(options.embedRequire !== false) {
str += treeshakeFooter;
}
str += wrapFooter;
str = str.split('{$$namespace}').join(wrap);
grunt.file.write(dest, str);
}
function writeFiles(dest, files, options, target) {
if (options.wrap) {
var buildFiles = {};
buildFiles[dest] = files;
var buildMinFiles = {};
buildMinFiles[dest.substr(0, dest.length - 3) + '.min.js'] = dest;
var uglify = grunt.config.get('uglify') || {};
uglify[target] = {
options: {
banner: options.banner ? options.banner + NEWLINE : '',
mangle: false,
compress: false,
preserveComments: 'some',
beautify: true,
exportAll: false,
sourceMap: false
},
files: buildFiles
};
if (options.minify) {
var destRoot = dest.split('/');
destRoot.pop();
destRoot = destRoot.join('/');
uglify[target + '_min'] = {
options: {
sourceMap: true,
sourceMapRoot: destRoot,
sourceMappingUrl: dest,
banner: options.banner ? options.banner + NEWLINE : '',
},
files: buildMinFiles
};
}
grunt.config.set('uglify', uglify);
grunt.task.run('uglify:' + target);
if (options.minify) {
grunt.task.run('uglify:' + target + '_min');
}
var filesize = {};
filesize[target] = {
path: dest,
pathMin: dest.substr(0, dest.length - 3) + '.min.js',
log: options.log,
gruntLogHeader: options.gruntLogHeader,
report: options.report
};
grunt.config.set('treeshake-filesize', filesize);
grunt.task.run('treeshake-filesize:' + target);
}
}
function outputUnfound() {
if (unfound.length) {
var missing = '', key, hash = {}, count = 0;
for (var i = 0; i < unfound.length; i += 1) {
key = unfound[i];
// keys that don't have a line are because they were not a direct dependency match.
// they could have come from the cusom options.match function which could match things
// like 'word-word' and then it searches for dependency 'wordWord'. So ignore these.
if (!hash[key.value] && (key.line || key.line === 0) && key.value.match(/^[a-zA-Z]/)) {
count += 1;
hash[key.value] = true;
missing += ('\n "' + key.value + '" ' + (key.from && key.from + ':' + key.line || key.type)).yellow;
}
}
if (count) {
emitter.fire(PRINT_LINE, (count + ' match' + (count > 1 && 'es' || '') + ' not found:' + missing));
}
}
}
grunt.registerMultiTask('treeshake', 'Optimize files added', function () {
var target = this.target,
packages,
files;
var options = this.options({
wrap: this.target,
log: CONSOLE,
match: function () {
return [];
}
});
printer.setGrunt(grunt);
printer.setOptions(options);
options.import = toArray(options.import); // import files that match the patterns.
options.ignore = toArray(options.ignore); // inspect files for excluded definitions
options.exclude = toArray(options.exclude); // filter out just like import filters in. reverse-import.
options.inspect = toArray(options.inspect); // which files to look through to determine if there are dependencies that need to be included.
options.includes = toArray(options.includes); // for including any file. Such as libs or something that doesn't fit our pattern. A force import if you will. This is a force import because it is a list of paths that just get written in.
cleanReservedWords = new RegExp('\\b(import|' + ALIASES + ')\\b', 'g');
// we build the whole package structure. We will filter it out later.
packages = buildPackages(this.files, options);
ignored = getIgnoredDefinitions(options.ignore, packages);
//console.log('#ignored', ignored);
//buildExclusions(options.exclude, packages, ignored, options);// don't know why we ever had this.
files = filter(options.inspect, packages, options.wrap, options);
if (options.report === 'verbose') {
printExclusions(files, packages);
outputUnfound();
}
// generate file.
if (files.length) {
writeSources(options.wrap, files, TMP_FILE, options);
writeFiles(this.files[0].dest, [TMP_FILE], options, target);
} else {
grunt.file.write(TMP_FILE, '');
grunt.log.error('No packages found. No files generated.'.red);
if (grunt.file.exists('.tmpTreeshake')) {
grunt.file.delete('.tmpTreeshake');
}
}
});
grunt.registerMultiTask('treeshake-filesize', 'A Grunt plugin for logging file size.', function () {
if (grunt.file.exists('.tmpTreeshake')) {
grunt.file.delete('.tmpTreeshake');
}
grunt.log.header = gruntLogHeader;
emitter.fire(PRINT_FINALIZE, this.data);
});
};
|
Pugabyte/BNCore | src/main/java/gg/projecteden/nexus/features/resourcepack/models/files/CustomModelFolder.java | <filename>src/main/java/gg/projecteden/nexus/features/resourcepack/models/files/CustomModelFolder.java
package gg.projecteden.nexus.features.resourcepack.models.files;
import gg.projecteden.nexus.features.resourcepack.ResourcePack;
import gg.projecteden.nexus.features.resourcepack.models.CustomModel;
import gg.projecteden.nexus.features.resourcepack.models.files.CustomModelGroup.Override;
import lombok.Data;
import lombok.NonNull;
import java.util.ArrayList;
import java.util.List;
@Data
public class CustomModelFolder {
@NonNull
private String path;
private List<CustomModelFolder> folders = new ArrayList<>();
private List<CustomModel> models = new ArrayList<>();
public CustomModelFolder(@NonNull String path) {
this.path = path;
this.path = this.path.replaceFirst("//", "/");
ResourcePack.getFolders().add(this);
findModels();
}
public CustomModelFolder getFolder(String path) {
if (this.path.equals(path))
return this;
for (CustomModelFolder folder : folders) {
if (path.equals(folder.getPath()))
return folder;
else if (path.startsWith(folder.getPath()))
return folder.getFolder(path);
}
return null;
}
public String getDisplayPath() {
String path = this.path;
if (path.startsWith("/"))
path = path.replaceFirst("/", "");
return path;
}
public void addFolder(String name) {
if (name.equals("item"))
return;
folders.add(new CustomModelFolder(path + "/" + name));
}
public CustomModel getIcon() {
return getIcon(model -> true);
}
public CustomModel getIcon(java.util.function.Predicate<CustomModel> predicate) {
if (!models.isEmpty()) {
final CustomModel icon = models.stream()
.filter(model -> model.getFileName().equals("icon"))
.findFirst()
.orElse(null);
if (icon != null && predicate.test(icon))
return icon;
for (CustomModel next : models)
if (predicate.test(next))
return next;
}
for (CustomModelFolder folder : folders) {
CustomModel icon = folder.getIcon(predicate);
if (icon != null)
return icon;
}
return null;
}
private void findModels() {
for (CustomModelGroup group : ResourcePack.getModelGroups())
for (Override override : group.getOverrides())
if (override.getModel().matches("projecteden" + path + "/" + ResourcePack.getFileRegex()))
models.add(new CustomModel(this, override, group.getMaterial()));
models.sort(CustomModel::compareTo);
models.forEach(model -> ResourcePack.getModels().put(model.getId(), model));
}
}
|
onezens/QQTweak | qqtw/qqheaders7.2/QZJFeedsCellFollowGuide.h | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>.
//
#import "JceObjectV2.h"
@class NSArray, NSString;
@interface QZJFeedsCellFollowGuide : JceObjectV2
{
}
// Remaining properties
@property(retain, nonatomic, getter=jce_followed_list, setter=setJce_followed_list:) NSArray *jcev2_p_0_o_followed_list__b0x9i_VOQZJFeedsSUser; // @dynamic jcev2_p_0_o_followed_list__b0x9i_VOQZJFeedsSUser;
@property(nonatomic, getter=jce_count, setter=setJce_count:) unsigned int jcev2_p_1_o_count; // @dynamic jcev2_p_1_o_count;
@property(retain, nonatomic, getter=jce_title, setter=setJce_title:) NSString *jcev2_p_2_o_title; // @dynamic jcev2_p_2_o_title;
@property(retain, nonatomic, getter=jce_summary, setter=setJce_summary:) NSString *jcev2_p_3_o_summary; // @dynamic jcev2_p_3_o_summary;
@property(retain, nonatomic, getter=jce_icon_url, setter=setJce_icon_url:) NSString *jcev2_p_4_o_icon_url; // @dynamic jcev2_p_4_o_icon_url;
@property(nonatomic, getter=jce_action_type, setter=setJce_action_type:) int jcev2_p_5_o_action_type; // @dynamic jcev2_p_5_o_action_type;
@property(retain, nonatomic, getter=jce_action_url, setter=setJce_action_url:) NSString *jcev2_p_6_o_action_url; // @dynamic jcev2_p_6_o_action_url;
@property(nonatomic, getter=jce_feed_type, setter=setJce_feed_type:) int jcev2_p_7_o_feed_type; // @dynamic jcev2_p_7_o_feed_type;
@property(retain, nonatomic, getter=jce_button_text, setter=setJce_button_text:) NSString *jcev2_p_8_o_button_text; // @dynamic jcev2_p_8_o_button_text;
@end
|
Zondax/ibmdotcom-react | lib/components/FeatureCardBlockLarge/FeatureCardBlockLarge.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _Card = require("../Card");
var _classnames = _interopRequireDefault(require("classnames"));
var _settings = _interopRequireDefault(require("@carbon/ibmdotcom-utilities/lib/utilities/settings/settings"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireDefault(require("react"));
var _settings2 = _interopRequireDefault(require("carbon-components/umd/globals/js/settings"));
/**
* Copyright IBM Corp. 2016, 2020
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
var stablePrefix = _settings.default.stablePrefix;
var prefix = _settings2.default.prefix;
/**
* Featured Card Component.
*/
var FeatureCardBlockLarge = function FeatureCardBlockLarge(props) {
return props.eyebrow && props.heading && props.image && props.cta && _react.default.createElement("section", {
className: (0, _classnames.default)("".concat(prefix, "--feature-card-block-large"), (0, _defineProperty2.default)({}, "".concat(prefix, "--feature-card-block-large_no-copy-text"), !props.copy)),
"data-autoid": "".concat(stablePrefix, "--feature-card-block-large")
}, _react.default.createElement("div", {
className: "".concat(prefix, "--feature-card-block-large__container")
}, _react.default.createElement(_Card.Card, (0, _extends2.default)({
customClassName: "".concat(prefix, "--feature-card-block-large__card")
}, props, {
inverse: true
}))));
};
FeatureCardBlockLarge.propTypes = {
/**
* "Eyebrow" text above copy and CTA.
*/
eyebrow: _propTypes.default.string.isRequired,
/**
* Title of the Card item.
*/
heading: _propTypes.default.string.isRequired,
/**
* Body text for the card.
*/
copy: _propTypes.default.string,
/**
* Object containing target and href of link. Has the following structure in summary:
*
* | Name | Data Type | Description |
* | ------ | --------- | ------------------------------------------- |
* | `href` | String | Url of the FeatureCardBlockLarge component. |
*
* See [`<Card>`'s README](http://ibmdotcom-react.mybluemix.net/?path=/docs/components-card--static#props) for full usage details.
*/
cta: _propTypes.default.shape({
copy: _propTypes.default.string,
href: _propTypes.default.string,
type: _propTypes.default.oneOfType([_propTypes.default.oneOf(['jump', 'local', 'external', 'download', 'video']), _propTypes.default.arrayOf(_propTypes.default.oneOf(['jump', 'local', 'external', 'download', 'video']))])
}).isRequired,
/**
* Contains source and alt text properties.
* See [`<Image>`'s README](http://ibmdotcom-react.mybluemix.net/?path=/docs/components-image--default#props) for full usage details.
*/
image: _propTypes.default.shape({
classname: _propTypes.default.string,
sources: _propTypes.default.arrayOf(_propTypes.default.shape({
src: _propTypes.default.string,
breakpoint: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.number])
})),
defaultSrc: _propTypes.default.string.isRequired,
alt: _propTypes.default.string.isRequired,
longDescription: _propTypes.default.string
}).isRequired
};
var _default = FeatureCardBlockLarge;
exports.default = _default; |
woshidaniu-com/niukit | niukit-rocketmq/src/main/java/com/woshidaniu/rocketmq/event/chain/HandlerChainResolver.java | package com.woshidaniu.rocketmq.event.chain;
import com.woshidaniu.rocketmq.event.RocketmqEvent;
public interface HandlerChainResolver<T extends RocketmqEvent> {
HandlerChain<T> getChain(T event , HandlerChain<T> originalChain);
}
|
rockandsalt/conan-center-index | recipes/libmount/all/test_package/test_package.cpp | #include <iostream>
#include <cstdlib>
#include <libmount/libmount.h>
int main()
{
struct libmnt_context *ctx = mnt_new_context();
if (!ctx) {
std::cerr << "failed to initialize libmount\n";
return EXIT_FAILURE;
}
std::cout << "path to fstab: " << mnt_get_fstab_path() << std::endl;
mnt_free_context(ctx);
return EXIT_SUCCESS;
}
|
paidgeek/c-exercises | e15.c | <gh_stars>0
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#define PERR(msg) { perror(msg); exit(1); }
int main(int argc, char *argv[])
{
int fd[2];
pid_t pid;
if(pipe(fd) == -1) {
PERR("pipe")
}
if((pid = fork()) < 0) {
PERR("fork")
} else if(pid == 0) {
if(close(fd[1]) == -1) {
PERR("close")
}
dup2(fd[0], STDIN_FILENO);
execlp("grep", "grep", "paidgeek", NULL);
} else {
close(fd[0]);
dup2(fd[1], STDOUT_FILENO);
execlp("ps", "ps", "-ef", NULL);
// wait(NULL);
}
return 0;
}
|
hanframework/han | han-core/src/main/java/org/hanframework/beans/exception/BeanCurrentlyInCreationException.java | package org.hanframework.beans.exception;
/**
* @author liuxin
* @version Id: BeanCurrentlyInCreationException.java, v 0.1 2018/10/29 3:11 PM
*/
public class BeanCurrentlyInCreationException extends RuntimeException {
/**
* Create a new BeanCurrentlyInCreationException,
* with a default error message that indicates a circular reference.
*
* @param beanName the name of the bean requested
*/
public BeanCurrentlyInCreationException(String beanName) {
super("BeanName:["+beanName +
"] 包含循环引用的问题?");
}
/**
* Create a new BeanCurrentlyInCreationException.
*
* @param beanName the name of the bean requested
* @param msg the detail message
*/
public BeanCurrentlyInCreationException(String beanName, String msg) {
super(beanName + ":" + msg);
}
}
|
arnonkahani/FastLane | DB/db/model/stop.py | <filename>DB/db/model/stop.py
import logging
from geoalchemy2 import Geometry
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from DB.config.fastlanes_config import FastlanesConfig
from DB.db.model.base import Base
log = logging.getLogger(__name__)
class Stop(Base):
filename = 'stops.txt'
__tablename__ = 'stops'
stop_id = Column(String(40), primary_key=True, index=True, nullable=False)
stop_code = Column(String(50))
stop_name = Column(String(255), nullable=False)
stop_desc = Column(String(255))
zone_id = Column(String(50))
location_type = Column(Integer, index=True, default=0)
parent_station = Column(String(255))
geom = Column(Geometry(geometry_type='POINT', srid=FastlanesConfig.SRID))
stop_times = relationship(
'StopTime',
primaryjoin='Stop.stop_id==StopTime.stop_id',
foreign_keys='(Stop.stop_id)',
uselist=True, viewonly=True)
@classmethod
def get_csv_table_columns(self):
return self.__table__.columns.keys()
@classmethod
def get_csv_table_index(self):
return "stop_id"
@classmethod
def transform_data(self, df):
df['geom'] = df.apply(lambda x: 'SRID={0};POINT({1} {2})'.format(FastlanesConfig.SRID, x.stop_lat, x.stop_lon), axis=1)
if 'zone_id' not in df.columns:
df['zone_id'] = ""
if 'location_type' not in df.columns:
df['location_type'] = 1
if 'parent_station' not in df.columns:
df['parent_station'] = ""
df = df[self.get_csv_table_columns()]
return df
|
n-syuichi/LAaaS-docker | xapi_stmt_gen/xapi_stmt_gen/config/app.js | <filename>xapi_stmt_gen/xapi_stmt_gen/config/app.js<gh_stars>1-10
const config = {
db:{
host:'moodle-docker_db_1',
port:5432,
database:'moodle',
username:'moodleuser',
password:'<PASSWORD>',
prefix:'mdl_'
},
LRS:{
url:'http://172.18.0.6:8081/data/xAPI/',
clients:{
// LRS client
'default':{
user:'c08425cf11e029dfa39fd0a4b82b5a7fc11c946c',
pass:'<PASSWORD>'
},
/**
* This 'scoped' setting can be used to send
* statements to separated LRSes based on ePPN in GakuNin.
*/
//'scoped':[
// {
// scope:'foo.co.jp',
// user:'dc<PASSWORD>a<PASSWORD>bb93a7e2fb<PASSWORD>f69741<PASSWORD>',
// pass:'<PASSWORD>'
// },
// {
// scope:'bar.ac.jp',
// user:'7<PASSWORD>2<PASSWORD>9<PASSWORD>423e36c1fbb',
// pass:'<PASSWORD>'
// }
//]
}
},
category:{
id:'http://moodle.org',
definition:{
type:'http://id.tincanapi.com/activitytype/source',
name:'Moodle',
description:
'Moodle is a open source learning platform designed to ' +
'provide educators, administrators and learners with ' +
'a single robust, secure and integrated system to create ' +
'personalized learning environments.'
}
},
platform:'Moodle',
language:'en',
homepage: 'http://localhost:8000'
};
module.exports = config;
|
sgowell-rm/spark-design-system | gatsby-browser.js | /**
* Implement Gatsby's Browser APIs in this file.
*
* See: https://www.gatsbyjs.org/docs/browser-apis/
*/
exports.onRouteUpdate = ({ location, prevLocation }) => {
if (typeof docsearch !== 'undefined') {
docsearch({ // eslint-disable-line no-undef
apiKey: '<KEY>',
indexName: 'sparkdesignsystem',
inputSelector: '.docs-header-search input',
debug: 'false',
});
docsearch({ // eslint-disable-line no-undef
apiKey: '<KEY>',
indexName: 'sparkdesignsystem',
inputSelector: '.docs-header-search--wide input',
debug: 'false',
});
}
const mainContent = document.querySelector('#gatsby-focus-wrapper');
if (mainContent) mainContent.setAttribute('data-sprk-main', '');
document.getElementsByTagName('html')[0].classList.add('sprk-u-JavaScript');
if (prevLocation !== null) {
// put focus on the first skip nav on the page
const skipNav = document.querySelector(".docs-c-SkipNav");
if (skipNav) {
skipNav.focus()
}
}
};
|
keydunov/snowman-io | lib/snowman-io/api/checks.rb | module SnowmanIO
module API
class Checks < Grape::API
before(&:authenticate!)
namespace :checks do
params do
optional :last, type: Integer
end
get do
Extra::Meteor.model_all(:checks, Check, permitted_params[:last])
end
params do
requires :check, type: Hash do
requires :metric_id, type: String
requires :cmp, type: String
requires :value, type: Float
end
end
post do
metric = Metric.find(permitted_params[:check][:metric_id])
{ check: metric.checks.create!(permitted_params[:check].to_h.except("metric_id")) }
end
route_param :id do
before do
@check = Check.find(params[:id])
end
get do
{ check: @check }
end
params do
requires :check, type: Hash do
requires :metric_id, type: String
requires :cmp, type: String
requires :value, type: Float
end
end
put do
{ check: @check.tap { |m|
m.update_attributes!(permitted_params[:check].to_h.except("metric_id").merge("triggered" => false))
} }
end
delete do
Extra::Meteor.model_destroy(Check, @check)
end
end
end
end
end
end
|
trydent-io/quercus | io.artoo.lance/src/main/java/io/artoo/lance/query/func/WhenWhere.java | package io.artoo.lance.query.func;
import io.artoo.lance.func.Cons;
import io.artoo.lance.func.Func;
import io.artoo.lance.func.Pred;
public final class WhenWhere<T> implements Func.MaybeFunction<T, T> {
private final Pred.MaybePredicate<? super T> where;
private final Cons.MaybeConsumer<? super T> cons;
public WhenWhere(final Pred.MaybePredicate<? super T> where, final Cons.MaybeConsumer<? super T> cons) {
this.where = where;
this.cons = cons;
}
@Override
public final T tryApply(final T element) throws Throwable {
if (where.tryTest(element)) cons.tryAccept(element);
return element;
}
}
|
hamid2262/shouter | app/controllers/search_subtrips_controller.rb | class SearchSubtripsController < ApplicationController
skip_authorization_check
def search
if params[:search_subtrip].nil?
@search_subtrip = SearchSubtrip.new
@subtrips = @search_subtrip.newtrips.page(params[:page]).per_page(10)
# @subtrips = @search_subtrip.subtrips_close_to_user request.remote_ip #"192.168.3.11"
else
@search_subtrip = SearchSubtrip.new(params[:search_subtrip])
if @search_subtrip.valid?
@subtrips = @search_subtrip.subtrips(300).page(params[:page]).per_page(10) if @search_subtrip
end
end
session[:search_show_init_date] = nil
end
end |
chuyiting/tp | src/test/java/seedu/studybananas/model/task/TaskTest.java | <gh_stars>1-10
package seedu.studybananas.model.task;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.studybananas.testutil.SampleTasks.CS2100_TUTORIAL_HOMEWORK;
import static seedu.studybananas.testutil.SampleTasks.CS2103T_WEEK8_QUIZ;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import seedu.studybananas.testutil.TaskBuilder;
public class TaskTest {
@Test
public void equals() {
// same object -> returns true
assertTrue(CS2103T_WEEK8_QUIZ.equals(CS2103T_WEEK8_QUIZ));
// null -> returns false
assertFalse(CS2103T_WEEK8_QUIZ.equals(null));
// different title -> returns false
Task editedCs2103T = new TaskBuilder(CS2103T_WEEK8_QUIZ).withTitle("CS2101").build();
assertFalse(CS2103T_WEEK8_QUIZ.equals(editedCs2103T));
// different description -> returns false
editedCs2103T = new TaskBuilder(CS2103T_WEEK8_QUIZ).withDescription("Week 9 quiz").build();
assertFalse(CS2103T_WEEK8_QUIZ.equals(editedCs2103T));
// different dateTime -> returns false
editedCs2103T = new TaskBuilder(CS2103T_WEEK8_QUIZ).withDateTime("2020-09-30 12:00").build();
assertFalse(CS2103T_WEEK8_QUIZ.equals(editedCs2103T));
}
@Test
public void isSameTask() {
// same values -> returns true
Task cs2103Copy = new TaskBuilder(CS2103T_WEEK8_QUIZ).build();
assertTrue(CS2103T_WEEK8_QUIZ.isSameTask(cs2103Copy));
// same object -> returns true
assertTrue(CS2103T_WEEK8_QUIZ.isSameTask(CS2103T_WEEK8_QUIZ));
// null -> returns false
assertFalse(CS2103T_WEEK8_QUIZ.isSameTask(null));
// different task -> returns false
assertFalse(CS2103T_WEEK8_QUIZ.isSameTask(CS2100_TUTORIAL_HOMEWORK));
// different title -> returns false
Task editedCs2103T = new TaskBuilder(CS2103T_WEEK8_QUIZ).withTitle("CS2101").build();
assertFalse(CS2103T_WEEK8_QUIZ.isSameTask(editedCs2103T));
// different description -> returns false
editedCs2103T = new TaskBuilder(CS2103T_WEEK8_QUIZ).withDescription("Week 9 Tutorial").build();
assertFalse(CS2103T_WEEK8_QUIZ.isSameTask(editedCs2103T));
// different time -> returns false
editedCs2103T = new TaskBuilder(CS2103T_WEEK8_QUIZ).withDateTime("2020-09-30 12:30").build();
assertFalse(CS2103T_WEEK8_QUIZ.isSameTask(editedCs2103T));
// different duration -> returs false
editedCs2103T = new TaskBuilder(CS2103T_WEEK8_QUIZ).withDuration("10").build();
assertFalse(CS2103T_WEEK8_QUIZ.isSameTask(editedCs2103T));
}
@Test
public void isDateTimeOverlapped() {
// same task -> returns true
assertTrue(CS2103T_WEEK8_QUIZ.isDateTimeOverlapped(CS2103T_WEEK8_QUIZ));
// Task with no dateTime -> returns false
Task editedCs2103T = new TaskBuilder(CS2103T_WEEK8_QUIZ).withDuration("").build();
assertFalse(CS2100_TUTORIAL_HOMEWORK.isDateTimeOverlapped(editedCs2103T));
// Task with overlapped dateTime -> returns true
editedCs2103T = new TaskBuilder(CS2103T_WEEK8_QUIZ).withDateTime("2020-09-27 11:00").withDuration("75").build();
assertTrue(CS2103T_WEEK8_QUIZ.isDateTimeOverlapped(editedCs2103T));
// Task without overlapped dateTime -> returns false
assertFalse(CS2103T_WEEK8_QUIZ.isDateTimeOverlapped(CS2100_TUTORIAL_HOMEWORK));
}
@Test
public void isLongerThanAnHour_taskDurationIsLongerThanAnHour_returnsTrue() {
String todayDateString = LocalDate.now().toString();
Task cs2103Task = new TaskBuilder(CS2103T_WEEK8_QUIZ).withDateTime(todayDateString).withDuration("75").build();
assertTrue(cs2103Task.isLongerThanAnHour());
}
@Test
public void isLongerThanAnHour_taskDurationIsLessThanAnHour_returnsFalse() {
String todayDateString = LocalDate.now().toString();
Task cs2103Task = new TaskBuilder(CS2103T_WEEK8_QUIZ).withDateTime(todayDateString).withDuration("45").build();
assertFalse(cs2103Task.isLongerThanAnHour());
}
@Test
public void getNumberOfMinuteHappenToday() {
String todayDateString = LocalDate.now().toString();
Task cs2103Task = new TaskBuilder(CS2103T_WEEK8_QUIZ)
.withDateTime(todayDateString).withDuration("45").build();
double expectedTodayDuration = 45.0;
assertEquals(expectedTodayDuration, cs2103Task.getNumberOfMinuteHappenToday());
}
}
|
lgirdk/ccsp-common-library | source/util_api/ansc/AnscPlatform/user_memory.c | <gh_stars>1-10
/*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2015 RDK Management
*
* 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.
*/
/**********************************************************************
Copyright [2014] [Cisco Systems, Inc.]
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.
**********************************************************************/
#include "ansc_global.h"
#include "user_base.h"
#include "user_memory.h"
#ifdef _ANSC_LINUX
PVOID
UserAllocateMemory(ULONG ulMemorySize)
{
PVOID p = AnscAllocateMemory(ulMemorySize);
if ( !p )
{
return p;
}
memset(p, 0, ulMemorySize);
/* printf("Alloc: %x\n", p); */
return p;
}
VOID
UserFreeMemory(PVOID pMemoryBlock)
{
/* printf("Free: %x\n", pMemoryBlock); */
AnscFreeMemory(pMemoryBlock);
pMemoryBlock = NULL;
return;
}
VOID
UserCopyMemory(PVOID pDestination, PVOID pSource, ULONG ulMemorySize)
{
memcpy(pDestination, pSource, ulMemorySize);
return;
}
VOID
UserZeroMemory(PVOID pMemory, ULONG ulMemorySize)
{
memset(pMemory, 0, ulMemorySize);
return;
}
BOOLEAN
UserEqualMemory(PVOID pMemory1, PVOID pMemory2, ULONG ulMemorySize)
{
return (memcmp(pMemory1, pMemory2, ulMemorySize) == 0);
}
PVOID
UserResizeMemory(PVOID pMemory, ULONG ulMemorySize)
{
AnscFreeMemory(pMemory);
pMemory = UserAllocateMemory(ulMemorySize);
return pMemory;
}
#endif
|
SayanGhoshBDA/code-backup | 1st_and_2nd_Sem_c_backup/BIN/C Prog/33.c | <reponame>SayanGhoshBDA/code-backup
/* Program to print powers of 2 */
#include<stdio.h>
int main()
{
int i=1, power=1;
while(++i<=10)
printf("%d",power*=2);
printf("\n");
return 0;
}
|
andbyu/andbyu.github.io | node_modules/@angular/core/esm/src/linker.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// Public API for compiler
export { Compiler } from './linker/compiler';
export { ComponentFactory, ComponentRef } from './linker/component_factory';
export { ComponentFactoryResolver, NoComponentFactoryError } from './linker/component_factory_resolver';
export { ComponentResolver } from './linker/component_resolver';
export { DynamicComponentLoader } from './linker/dynamic_component_loader';
export { ElementRef } from './linker/element_ref';
export { ExpressionChangedAfterItHasBeenCheckedException } from './linker/exceptions';
export { QueryList } from './linker/query_list';
export { SystemJsCmpFactoryResolver, SystemJsComponentResolver } from './linker/systemjs_component_resolver';
export { TemplateRef } from './linker/template_ref';
export { ViewContainerRef } from './linker/view_container_ref';
export { EmbeddedViewRef, ViewRef } from './linker/view_ref';
//# sourceMappingURL=linker.js.map |
wangyum/anaconda | pkgs/libdynd-0.7.2-0/include/dynd/int128.hpp | //
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//
#pragma once
#include <limits>
#if !defined(DYND_HAS_INT128)
namespace dynd {
class DYNDT_API int128 {
public:
#if defined(DYND_BIG_ENDIAN)
uint64_t m_hi, m_lo;
#else
uint64_t m_lo, m_hi;
#endif
int128() {}
int128(uint64_t hi, uint64_t lo) : m_lo(lo), m_hi(hi) {}
int128(bool1) { throw std::runtime_error("int128(bool1) is not implemented"); }
int128(char value) : m_lo((int64_t)value), m_hi(value < 0 ? 0xffffffffffffffffULL : 0ULL) {}
int128(signed char value) : m_lo((int64_t)value), m_hi(value < 0 ? 0xffffffffffffffffULL : 0ULL) {}
int128(unsigned char value) : m_lo(value), m_hi(0ULL) {}
int128(short value) : m_lo((int64_t)value), m_hi(value < 0 ? 0xffffffffffffffffULL : 0ULL) {}
int128(unsigned short value) : m_lo(value), m_hi(0ULL) {}
int128(int value) : m_lo((int64_t)value), m_hi(value < 0 ? 0xffffffffffffffffULL : 0ULL) {}
int128(unsigned int value) : m_lo(value), m_hi(0ULL) {}
int128(long value) : m_lo((int64_t)value), m_hi(value < 0 ? 0xffffffffffffffffULL : 0ULL) {}
int128(unsigned long value) : m_lo(value), m_hi(0ULL) {}
int128(long long value) : m_lo((int64_t)value), m_hi(value < 0 ? 0xffffffffffffffffULL : 0ULL) {}
int128(unsigned long long value) : m_lo(value), m_hi(0ULL) {}
int128(float value);
int128(double value);
int128(const uint128 &value);
int128(const float16 &value);
int128(const float128 &value);
int128 operator+() const { return *this; }
bool operator!() const { return !(this->m_hi) && !(this->m_lo); }
int128 operator~() const { return int128(~m_hi, ~m_lo); }
bool operator==(const int128 &rhs) const { return m_lo == rhs.m_lo && m_hi == rhs.m_hi; }
bool operator==(int rhs) const
{
return static_cast<int64_t>(m_lo) == static_cast<int64_t>(rhs) && m_hi == (rhs >= 0 ? 0ULL : 0xffffffffffffffffULL);
}
bool operator!=(const int128 &rhs) const { return m_lo != rhs.m_lo || m_hi != rhs.m_hi; }
bool operator!=(int rhs) const
{
return static_cast<int64_t>(m_lo) != static_cast<int64_t>(rhs) || m_hi != (rhs >= 0 ? 0ULL : 0xffffffffffffffffULL);
}
bool operator<(float rhs) const { return double(*this) < rhs; }
bool operator<(double rhs) const { return double(*this) < rhs; }
bool operator<(const int128 &rhs) const
{
return (int64_t)m_hi < (int64_t)rhs.m_hi || (m_hi == rhs.m_hi && m_lo < rhs.m_lo);
}
bool operator<=(const int128 &rhs) const
{
return (int64_t)m_hi < (int64_t)rhs.m_hi || (m_hi == rhs.m_hi && m_lo <= rhs.m_lo);
}
bool operator>(const int128 &rhs) const { return rhs.operator<(*this); }
bool operator>=(const int128 &rhs) const { return rhs.operator<=(*this); }
bool is_negative() const { return (m_hi & 0x8000000000000000ULL) != 0; }
void negate()
{
// twos complement negation, ~x + 1
uint64_t lo = ~m_lo, hi = ~m_hi;
uint64_t lo_p1 = lo + 1;
m_hi = hi + (lo_p1 < lo);
m_lo = lo_p1;
}
int128 &operator+=(const int128 &rhs)
{
uint64_t lo = m_lo + rhs.m_lo;
*this = int128(m_hi + ~rhs.m_hi + (lo < m_lo), lo);
return *this;
}
int128 operator-() const
{
// twos complement negation, ~x + 1
uint64_t lo = ~m_lo, hi = ~m_hi;
uint64_t lo_p1 = lo + 1;
return int128(hi + (lo_p1 < lo), lo_p1);
}
int128 operator+(const int128 &rhs) const
{
uint64_t lo = m_lo + rhs.m_lo;
return int128(m_hi + rhs.m_hi + (lo < m_lo), lo);
}
int128 operator-(const int128 &rhs) const
{
uint64_t lo = m_lo + ~rhs.m_lo + 1;
return int128(m_hi + ~rhs.m_hi + (lo < m_lo), lo);
}
int128 operator*(uint32_t rhs) const;
// int128 operator/(uint32_t rhs) const;
int128 &operator/=(int128 DYND_UNUSED(rhs)) { throw std::runtime_error("operator/= is not implemented for int128"); }
operator float() const
{
if (*this < int128(0)) {
int128 tmp = -(*this);
return tmp.m_lo + tmp.m_hi * 18446744073709551616.f;
}
else {
return m_lo + m_hi * 18446744073709551616.f;
}
}
operator double() const
{
if (*this < int128(0)) {
int128 tmp = -(*this);
return tmp.m_lo + tmp.m_hi * 18446744073709551616.0;
}
else {
return m_lo + m_hi * 18446744073709551616.0;
}
}
explicit operator bool() const { return m_lo || m_hi; }
explicit operator char() const { return (char)m_lo; }
explicit operator signed char() const { return (signed char)m_lo; }
explicit operator unsigned char() const { return (unsigned char)m_lo; }
explicit operator short() const { return (short)m_lo; }
explicit operator unsigned short() const { return (unsigned short)m_lo; }
explicit operator int() const { return (int)m_lo; }
explicit operator unsigned int() const { return (unsigned int)m_lo; }
explicit operator long() const { return (long)m_lo; }
explicit operator unsigned long() const { return (unsigned long)m_lo; }
explicit operator long long() const { return (long long)m_lo; }
explicit operator unsigned long long() const { return (unsigned long long)m_lo; }
};
template <>
struct is_integral<int128> : std::true_type {
};
} // namespace dynd
namespace std {
template <>
struct common_type<dynd::int128, bool> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, dynd::bool1> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, char> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, signed char> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, unsigned char> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, short> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, unsigned short> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, int> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, unsigned int> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, long> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, unsigned long> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, long long> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, unsigned long long> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, dynd::int128> {
typedef dynd::int128 type;
};
template <>
struct common_type<dynd::int128, float> {
typedef float type;
};
template <>
struct common_type<dynd::int128, double> {
typedef double type;
};
template <typename T>
struct common_type<T, dynd::int128> : common_type<dynd::int128, T> {
};
} // namespace std
namespace dynd {
inline int128 operator/(int128 DYND_UNUSED(lhs), int128 DYND_UNUSED(rhs))
{
throw std::runtime_error("operator/ is not implemented for int128");
}
inline bool operator==(int lhs, const int128 &rhs) { return rhs == lhs; }
inline bool operator!=(int lhs, const int128 &rhs) { return rhs != lhs; }
inline bool operator<(const int128 &lhs, int rhs) { return lhs < int128(rhs); }
inline bool operator>(const int128 &lhs, int rhs) { return lhs > int128(rhs); }
inline bool operator<(float lhs, const int128 &rhs) { return lhs < double(rhs); }
inline bool operator<(double lhs, const int128 &rhs) { return lhs < double(rhs); }
inline bool operator<(signed char lhs, const int128 &rhs) { return int128(lhs) < rhs; }
inline bool operator<(unsigned char lhs, const int128 &rhs) { return int128(lhs) < rhs; }
inline bool operator<(short lhs, const int128 &rhs) { return int128(lhs) < rhs; }
inline bool operator<(unsigned short lhs, const int128 &rhs) { return int128(lhs) < rhs; }
inline bool operator<(int lhs, const int128 &rhs) { return int128(lhs) < rhs; }
inline bool operator<(unsigned int lhs, const int128 &rhs) { return int128(lhs) < rhs; }
inline bool operator<(long long lhs, const int128 &rhs) { return int128(lhs) < rhs; }
inline bool operator<(unsigned long long lhs, const int128 &rhs) { return int128(lhs) < rhs; }
inline bool operator>(float lhs, const int128 &rhs) { return lhs > double(rhs); }
inline bool operator>(double lhs, const int128 &rhs) { return lhs > double(rhs); }
inline bool operator>(signed char lhs, const int128 &rhs) { return int128(lhs) > rhs; }
inline bool operator>(unsigned char lhs, const int128 &rhs) { return int128(lhs) > rhs; }
inline bool operator>(short lhs, const int128 &rhs) { return int128(lhs) > rhs; }
inline bool operator>(unsigned short lhs, const int128 &rhs) { return int128(lhs) > rhs; }
inline bool operator>(int lhs, const int128 &rhs) { return int128(lhs) > rhs; }
inline bool operator>(unsigned int lhs, const int128 &rhs) { return int128(lhs) > rhs; }
inline bool operator>(long long lhs, const int128 &rhs) { return int128(lhs) > rhs; }
inline bool operator>(unsigned long long lhs, const int128 &rhs) { return int128(lhs) > rhs; }
DYNDT_API std::ostream &operator<<(std::ostream &out, const int128 &val);
} // namespace dynd
namespace std {
template <>
class numeric_limits<dynd::int128> {
public:
static const bool is_specialized = true;
static dynd::int128(min)() throw() { return dynd::int128(0x8000000000000000ULL, 0ULL); }
static dynd::int128(max)() throw() { return dynd::int128(0x7fffffffffffffffULL, 0xffffffffffffffffULL); }
static const int digits = 0;
static const int digits10 = 0;
static const bool is_signed = true;
static const bool is_integer = true;
static const bool is_exact = true;
static const int radix = 2;
static dynd::int128 epsilon() throw() { return dynd::int128(0ULL, 1ULL); }
static dynd::int128 round_error() throw() { return dynd::int128(0ULL, 1ULL); }
static const int min_exponent = 0;
static const int min_exponent10 = 0;
static const int max_exponent = 0;
static const int max_exponent10 = 0;
static const bool has_infinity = false;
static const bool has_quiet_NaN = false;
static const bool has_signaling_NaN = false;
static const float_denorm_style has_denorm = denorm_absent;
static const bool has_denorm_loss = false;
static dynd::int128 infinity() throw();
static dynd::int128 quiet_NaN() throw();
static dynd::int128 signaling_NaN() throw();
static dynd::int128 denorm_min() throw();
static const bool is_iec559 = false;
static const bool is_bounded = false;
static const bool is_modulo = false;
static const bool traps = false;
static const bool tinyness_before = false;
static const float_round_style round_style = round_toward_zero;
};
} // namespace std
#endif // !defined(DYND_HAS_INT128)
|
lechium/tvOS10Headers | System/Library/Frameworks/Foundation.framework/NSDirInfoSerializer.h | <gh_stars>1-10
/*
* This header is generated by classdump-dyld 1.0
* on Wednesday, March 22, 2017 at 9:01:14 AM Mountain Standard Time
* Operating System: Version 10.1 (Build 14U593)
* Image Source: /System/Library/Frameworks/Foundation.framework/Foundation
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <Foundation/NSAKSerializer.h>
@interface NSDirInfoSerializer : NSAKSerializer
-(unsigned long long)serializePListValueIn:(id)arg1 key:(id)arg2 value:(id)arg3 ;
@end
|
patrickpl/leitstand-commons | leitstand-commons/src/main/java/io/leitstand/commons/tx/package-info.java | /*
* (c) RtBrick, Inc - All rights reserved, 2015 - 2019
*/
/**
* Contains utilities to work with container managed transactions.
* <p>
* The EJB specification defines the transaction boundaries for container managed transactions.
* All operations of a <em>stateless session bean</em> are transactional by default, which means
* that a stateless session bean either participates in an existing transaction or creates a new transaction,
* when no transaction is currently active.
* In certain situations it is necessary to run a certain control flow in a different transaction.
* The {@link SubtransactionExecutionService} enables to run a {@link Transaction} in a new container managed transaction.
* The <code>Transaction</code> encapsulates the instructions to be executed in a new transaction.
* Once the new transaction is committed, the {@link Resume} action defines the necessary steps to return to previous transaction.
* </p>
* <p>
* For example, if a service gets registered for an element the service definition is expected to be present.
* If the service definition is not available, the service registration creates a <em>stub</em> record for the service.
* If multiple transactions aim to register the same service stub record, only one transaction succeeds and all other transaction are rolled back,
* although the missing service stub record is available now as it has been created by the first transaction.
* Thus the stub record creation should be a dedicated transaction.
* If this transaction fails, then most likely because the stub record was created by a different transaction in the meanwhile.
* Additionally, passing managed entities across transaction boundaries has unwanted side-effects as managed entities become <em>detached</em>.
* The {@link SubtransactionExecutionService#tryNewTransaction(Transaction, Resume)} method executes the specified transaction in a
* new container managed transaction and executes the specified resume action regardless whether the transaction succeeded or failed.
* As a result the very first transaction, which was suspended for the execution of the transaction run by the <code>SubtransactionExecutionService</code>,
* will never get in touch with detached entities.
* </p>
* <p>
* The {@link RetryOnOptimisticLockException} aspect retries a transactional operation in case of an <code>OptimisticLockingException</code>.
* The aspect can be activated via <code>{@literal @RetryOnOptimisticLockException}</code> on every transactional method that
* defines the transaction boundary of a container managed transaction.
* </p>
*
*/
package io.leitstand.commons.tx; |
reabiliti/certification | app/controllers/welcome_controller.rb | <filename>app/controllers/welcome_controller.rb
# frozen_string_literal: true
# This controller for search and all proposals
class WelcomeController < ApplicationController
def index
@proposals = FilterProposalsQuery.new(initial_scope: AllProposalsQuery.new.call, params: params).call
@setting = Setting.first
end
end
|
stnguyen90/buffalo-cli | cli/buffalo.go | <filename>cli/buffalo.go
package cli
import (
"os"
"path/filepath"
"sort"
"github.com/gobuffalo/buffalo-cli/v2/cli/cmds"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/clifix"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/bzr"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/fizz"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/flect"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/git"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/golang"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/grifts"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/i18n"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/mail"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/packr"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/pkger"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/plush"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/pop"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/refresh"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/soda"
"github.com/gobuffalo/buffalo-cli/v2/cli/internal/plugins/webpack"
"github.com/gobuffalo/plugins"
"github.com/gobuffalo/plugins/plugcmd"
"github.com/gobuffalo/plugins/plugprint"
)
var _ plugcmd.SubCommander = &Buffalo{}
var _ plugins.Plugin = &Buffalo{}
var _ plugins.Scoper = &Buffalo{}
var _ plugprint.Describer = &Buffalo{}
// Buffalo represents the `buffalo` cli.
type Buffalo struct {
plugins.Plugins
}
func NewFromRoot(root string) (*Buffalo, error) {
b := &Buffalo{}
pfn := func() []plugins.Plugin {
return b.Plugins
}
b.Plugins = append(b.Plugins, clifix.Plugins()...)
b.Plugins = append(b.Plugins, cmds.Plugins()...)
b.Plugins = append(b.Plugins, fizz.Plugins()...)
b.Plugins = append(b.Plugins, flect.Plugins()...)
b.Plugins = append(b.Plugins, golang.Plugins()...)
b.Plugins = append(b.Plugins, grifts.Plugins()...)
b.Plugins = append(b.Plugins, i18n.Plugins()...)
b.Plugins = append(b.Plugins, mail.Plugins()...)
b.Plugins = append(b.Plugins, packr.Plugins()...)
b.Plugins = append(b.Plugins, pkger.Plugins()...)
b.Plugins = append(b.Plugins, plush.Plugins()...)
b.Plugins = append(b.Plugins, pop.Plugins()...)
b.Plugins = append(b.Plugins, refresh.Plugins()...)
b.Plugins = append(b.Plugins, soda.Plugins()...)
if _, err := os.Stat(filepath.Join(root, "package.json")); err == nil {
b.Plugins = append(b.Plugins, webpack.Plugins()...)
}
if _, err := os.Stat(filepath.Join(root, ".git")); err == nil {
b.Plugins = append(b.Plugins, git.Plugins()...)
}
if _, err := os.Stat(filepath.Join(root, ".bzr")); err == nil {
b.Plugins = append(b.Plugins, bzr.Plugins()...)
}
sort.Slice(b.Plugins, func(i, j int) bool {
return b.Plugins[i].PluginName() < b.Plugins[j].PluginName()
})
pfn = func() []plugins.Plugin {
return b.Plugins
}
for _, b := range b.Plugins {
f, ok := b.(plugins.Needer)
if !ok {
continue
}
f.WithPlugins(pfn)
}
return b, nil
}
func New() (*Buffalo, error) {
pwd, err := os.Getwd()
if err != nil {
return nil, err
}
return NewFromRoot(pwd)
}
func (b Buffalo) ScopedPlugins() []plugins.Plugin {
return b.Plugins
}
func (b Buffalo) SubCommands() []plugins.Plugin {
var plugs []plugins.Plugin
for _, p := range b.ScopedPlugins() {
if _, ok := p.(Commander); ok {
plugs = append(plugs, p)
}
}
return plugs
}
// Name ...
func (Buffalo) PluginName() string {
return "buffalo"
}
func (Buffalo) String() string {
return "buffalo"
}
// Description ...
func (Buffalo) Description() string {
return "Tools for working with Buffalo applications"
}
|
BeginnerJay/JAVA_LAB | Doit/src/chapter9/UsingDefine.java | package chapter9;
public class UsingDefine {
public static void main(String[] args) {
System.out.println(Define.GOOD_MORNING);
System.out.printf("최솟값은 %d입니다.\n",Define.MIN);
System.out.printf("최댓값은 %d입니다.\n",Define.MAX);
System.out.printf("수학 과목 코드는 %d입니다.\n",Define.MATH);
System.out.printf("영어 과목 코드 값은 %d입니다.\n",Define.ENG);
}
}
// 클래스를 final로 선언하면 상속할 수 없다.(String 클래스, Math 클래스 등) |
zhpigh/KidsTC_Objective-C | KidsTC/KidsTC/Business/Main/Product/FlashBuy/ProductDetail/M/FlashBuyProductDetailData.h | <reponame>zhpigh/KidsTC_Objective-C<gh_stars>0
//
// FlashBuyProductDetailData.h
// KidsTC
//
// Created by 詹平 on 2017/1/22.
// Copyright © 2017年 zhanping. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "FlashBuyProductDetailPriceConfig.h"
#import "FlashBuyProductDetailPromotionLink.h"
#import "FlashBuyProductDetailStore.h"
#import "FlashBuyProductDetailNote.h"
#import "FlashBuyProductDetailBuyNotice.h"
#import "FlashBuyProductDetailComment.h"
#import "FlashBuyProductDetailCommentListItem.h"
#import "FlashBuyProductDetailShare.h"
#import "CommentListItemModel.h"
#import "CommonShareObject.h"
#import "StoreListItemModel.h"
typedef enum : NSUInteger {
FlashBuyProductDetailStatusNotStart = 1,//闪购尚未开始,未到预约时间
FlashBuyProductDetailStatusUnPrePaid = 2,//我要闪购,可以参团未支付
FlashBuyProductDetailStatusWaitPrePaid = 3,//预付定金,可以参团待预付(已经下单)
FlashBuyProductDetailStatusWaitBuy = 4,//等待开团,等待开团(已预付)
FlashBuyProductDetailStatusFlashFailedUnPrePaid = 5,//闪购结束,开团失败(未预付)
FlashBuyProductDetailStatusFlashFailedPrePaid = 6,//闪购结束,开团失败(已预付)
FlashBuyProductDetailStatusRefunding = 7,//退款中,开团失败(已预付)- 在订单中
FlashBuyProductDetailStatusRefunded = 8,//退款成功,开团失败(已预付)-在订单中
FlashBuyProductDetailStatusFlashSuccessNoPrePaid = 9,//闪购结束,开团成功(未预付)
FlashBuyProductDetailStatusFlashSuccessUnPay = 10,//立付尾款,开团成功(已预付,没有进入确认页确认)
FlashBuyProductDetailStatusFlashSuccessWaitPay = 11,//立付尾款,开团成功(已预付,已进入确认页确认)
FlashBuyProductDetailStatusHadPaid = 12,//闪购成功,已购买
FlashBuyProductDetailStatusProductRunOut = 13,//已售罄
FlashBuyProductDetailStatusProductNotSale = 14,//暂不销售
FlashBuyProductDetailStatusBuyTimeEnd = 15,//闪购结束,购买时间已过
FlashBuyProductDetailStatusEvaluted = 16,//已评价,已评价 -在订单中
FlashBuyProductDetailStatusWaitEvalute = 17,//去评价,去评价 -在订单中
FlashBuyProductDetailStatusUnLogIn = 100//我要闪购,未登录:立即参加
} FlashBuyProductDetailStatus;
typedef enum : NSUInteger {
FlashBuyProductDetailShowTypeDetail = 1,
FlashBuyProductDetailShowTypeStore,
FlashBuyProductDetailShowTypeComment,
} FlashBuyProductDetailShowType;
@interface FlashBuyProductDetailData : NSObject
@property (nonatomic, strong) NSString *fsSysNo;
@property (nonatomic, strong) NSString *serveId;
@property (nonatomic, strong) NSString *serveName;
@property (nonatomic, strong) NSString *simpleName;
@property (nonatomic, strong) NSString *content;
@property (nonatomic, assign) FlashBuyProductDetailStatus status;
@property (nonatomic, strong) NSString *statusDesc;
@property (nonatomic, strong) NSString *orderNo;
@property (nonatomic, assign) BOOL isLink;
@property (nonatomic, assign) BOOL isShowCountDown;
@property (nonatomic, assign) NSTimeInterval countDownValue;
@property (nonatomic, strong) NSString *countDownStr;
@property (nonatomic, assign) NSInteger level;
@property (nonatomic, strong) NSString *price;
@property (nonatomic, strong) NSString *prepaidPrice;
@property (nonatomic, assign) NSInteger evaluate;
@property (nonatomic, assign) NSInteger saleCount;
@property (nonatomic, assign) NSInteger remainCount;
@property (nonatomic, assign) NSInteger prepaidNum;
@property (nonatomic, strong) NSArray<FlashBuyProductDetailPriceConfig *> *priceConfigs;
@property (nonatomic, assign) BOOL isFavor;
@property (nonatomic, strong) NSArray<NSString *> *imgUrl;
@property (nonatomic, strong) NSArray<NSString *> *narrowImg;
@property (nonatomic, strong) NSString *flowImg;
@property (nonatomic, strong) NSString *flowLinkUrl;
@property (nonatomic, assign) CGFloat picRate;
@property (nonatomic, strong) NSString *promote;
@property (nonatomic, strong) NSArray<FlashBuyProductDetailPromotionLink *> *promotionLink;
@property (nonatomic, strong) NSArray<NSString *> *age;
@property (nonatomic, strong) NSString *dateTime;
@property (nonatomic, strong) NSArray<FlashBuyProductDetailStore *> *store;
@property (nonatomic, assign) NSInteger productType;
@property (nonatomic, strong) FlashBuyProductDetailComment *comment;
@property (nonatomic, assign) NSInteger commentImgCount;
@property (nonatomic, strong) FlashBuyProductDetailNote *note;
@property (nonatomic, strong) NSArray<FlashBuyProductDetailBuyNotice *> *buyNotice;
@property (nonatomic, strong) NSArray<FlashBuyProductDetailCommentListItem *> *commentList;
@property (nonatomic, assign) BOOL isOpenRemind;
@property (nonatomic, strong) NSString *detailUrl;
@property (nonatomic, strong) FlashBuyProductDetailShare *share;
@property (nonatomic, assign) ProductDetailType productRedirect;
//selfDefine
@property (nonatomic, strong) NSAttributedString *attServeName;
@property (nonatomic, strong) NSAttributedString *attPromote;
@property (nonatomic, strong) NSAttributedString *attContent;
@property (nonatomic, assign) FlashBuyProductDetailShowType showType;
@property (nonatomic, assign) BOOL webViewHasLoad;
@property (nonatomic, strong) NSArray<StoreListItemModel *> *storeModels;
@property (nonatomic, strong) NSArray<CommentListItemModel *> *commentItemsArray;
@property (nonatomic, strong) CommonShareObject *shareObject;
@property (nonatomic, strong) SegueModel *segueModel;
@property (nonatomic, assign) BOOL countDownOver;
@property (nonatomic, strong) NSString *countDownValueString;
@end
|
shaunryan/PythonReference | Optimizing_Python_Code/Exercise Files/Ch06/06_03/Optimized/proc_pool.py | <filename>Optimizing_Python_Code/Exercise Files/Ch06/06_03/Optimized/proc_pool.py
"""Process pool example"""
from concurrent.futures import ProcessPoolExecutor
import bz2
def unpack(requests):
"""Unpack a list of requests compressed in bz2"""
return [bz2.decompress(request) for request in requests]
def unpack_proc(requests):
"""Unpack a list of requests compressed in bz2 using a process pool"""
# Default to numbers of cores
with ProcessPoolExecutor() as pool:
return list(pool.map(bz2.decompress, requests))
if __name__ == '__main__':
with open('huck-finn.txt', 'rb') as fp:
data = fp.read()
bz2data = bz2.compress(data)
print(len(bz2data) / len(data)) # About 27%
print(bz2.decompress(bz2data) == data) # Loseless
requests = [bz2data] * 300
|
doubleDragon/Cycling | src/com/android/cycling/setting/SettingContentFragment.java | package com.android.cycling.setting;
import com.android.cycling.R;
import com.android.cycling.activities.UserEditorActivity;
import com.android.cycling.data.ServerUser;
import com.android.cycling.widget.HeaderLayout;
import com.android.cycling.widget.RoundedImageView;
import com.android.cycling.widget.HeaderLayout.Action;
import com.android.cycling.widget.SimpleGridView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class SettingContentFragment extends Fragment implements OnClickListener{
private Context mContext;
private ServerUser mSelfUser;
private RoundedImageView mAvatar;
private TextView mName;
private TextView mAge;
private TextView mLocation;
private TextView mSignatue;
private ImageView mSex;
private SimpleGridView mPhotos;
private SettingPhotoListAdapter mPhotoAdapter;
private DisplayImageOptions options;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity;
}
public void setSelfUser(ServerUser user) {
mSelfUser = user;
}
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
.cacheOnDisk(true).considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
}
@Override
public void onDetach() {
mContext = null;
super.onDetach();
}
@Override
public void onResume() {
super.onResume();
if(mSelfUser != null) {
bindData();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.setting_content_fragment, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
View root = getView();
if(root == null) {
throw new IllegalStateException("Content view not yet created");
}
HeaderLayout headerLayout = (HeaderLayout) root.findViewById(R.id.header_layout);
headerLayout.setTitle(R.string.indicator_title_index4);
headerLayout.addAction(new Action() {
@Override
public int getDrawable() {
return R.drawable.editor;
}
@Override
public void performAction(View view) {
intentToEdite();
}
});
mAvatar = (RoundedImageView) root.findViewById(R.id.avatar);
mName = (TextView) root.findViewById(R.id.name);
mAge = (TextView) root.findViewById(R.id.age);
mLocation = (TextView) root.findViewById(R.id.location);
mSex = (ImageView) root.findViewById(R.id.sex);
mSignatue = (TextView) root.findViewById(R.id.signatue_content);
mPhotos = (SimpleGridView) root.findViewById(R.id.photos);
}
private void bindData() {
updateAvatar();
mName.setText(mSelfUser.getUsername());
mAge.setText("" + mSelfUser.getAge());
mLocation.setText("" + mSelfUser.getLocation());
int resId;
if(mSelfUser.isMale()) {
resId = R.drawable.male_little_icon;
} else {
resId = R.drawable.female_little_icon;
}
mSex.setImageResource(resId);
final String sig = mSelfUser.getSignature();
if(TextUtils.isEmpty(sig)) {
mSignatue.setText("您还没添加签名信息");
} else {
mSignatue.setText(sig);
}
if(mSelfUser.hasPhotoInGallery()) {
showGallery();
}
}
private void showGallery() {
if(mPhotoAdapter == null) {
mPhotoAdapter = new SettingPhotoListAdapter(mContext);
mPhotos.setAdapter(mPhotoAdapter);
}
mPhotoAdapter.setData(mSelfUser.getGallery());
}
private void updateAvatar() {
ImageLoader.getInstance().displayImage(mSelfUser.getAvatar(), mAvatar,
options);
}
private void intentToEdite() {
Intent i = new Intent(mContext, UserEditorActivity.class);
i.putExtra("user", mSelfUser);
mContext.startActivity(i);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
|
dimitrijejankov/pdb | pdb/src/storage/source/LocalitySet.cc | /*****************************************************************************
* *
* Copyright 2018 Rice University *
* *
* 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. *
* *
*****************************************************************************/
#ifndef LOCALITY_SET_CC
#define LOCALITY_SET_CC
#include "LocalitySet.h"
#include <iostream>
LocalitySet::LocalitySet(LocalityType localityType,
LocalitySetReplacementPolicy replacementPolicy,
OperationType operationType,
DurabilityType durabilityType,
PersistenceType persistenceType) {
cachedPages = new list<PDBPagePtr>();
this->localityType = localityType;
this->replacementPolicy = replacementPolicy;
this->operationType = operationType;
this->durabilityType = durabilityType;
this->persistenceType = persistenceType;
this->lifetimeEnded = false;
}
LocalitySet::~LocalitySet() {
cachedPages->clear();
delete cachedPages;
}
void LocalitySet::addCachedPage(PDBPagePtr page) {
cachedPages->push_back(page);
}
void LocalitySet::updateCachedPage(PDBPagePtr page) {
for (list<PDBPagePtr>::iterator it = cachedPages->begin(); it != cachedPages->end(); ++it) {
if ((*it) == page) {
cachedPages->erase(it);
break;
}
}
cachedPages->push_back(page);
}
void LocalitySet::removeCachedPage(PDBPagePtr page) {
for (list<PDBPagePtr>::iterator it = cachedPages->begin(); it != cachedPages->end(); ++it) {
if ((*it) == page) {
cachedPages->erase(it);
break;
}
}
}
PDBPagePtr LocalitySet::selectPageForReplacement() {
PDBPagePtr retPage = nullptr;
if (this->replacementPolicy == MRU) {
for (list<PDBPagePtr>::reverse_iterator it = cachedPages->rbegin();
it != cachedPages->rend();
++it) {
if ((*it)->getRefCount() == 0) {
retPage = (*it);
break;
}
}
} else {
for (list<PDBPagePtr>::iterator it = cachedPages->begin(); it != cachedPages->end(); ++it) {
if ((*it)->getRefCount() == 0) {
retPage = (*it);
break;
}
}
}
return retPage;
}
vector<PDBPagePtr>* LocalitySet::selectPagesForReplacement() {
vector<PDBPagePtr>* retPages = new vector<PDBPagePtr>();
int totalPages = cachedPages->size();
if (totalPages == 0) {
delete retPages;
return nullptr;
}
int numPages = 0;
if (this->replacementPolicy == MRU) {
for (list<PDBPagePtr>::reverse_iterator it = cachedPages->rbegin();
it != cachedPages->rend();
++it) {
if ((*it)->getRefCount() == 0) {
retPages->push_back(*it);
numPages++;
if (this->operationType == Write) {
break;
} else {
if ((double)numPages / (double)totalPages >= 0.1) {
break;
}
}
}
}
} else {
for (list<PDBPagePtr>::iterator it = cachedPages->begin(); it != cachedPages->end(); ++it) {
if ((*it)->getRefCount() == 0) {
retPages->push_back(*it);
numPages++;
if (this->operationType == Write) {
break;
} else {
if ((double)numPages / (double)totalPages >= 0.1) {
break;
}
}
}
}
}
if (numPages == 0) {
delete retPages;
return nullptr;
} else {
return retPages;
}
}
void LocalitySet::pin(LocalitySetReplacementPolicy policy, OperationType operationType) {
this->replacementPolicy = policy;
this->operationType = operationType;
this->lifetimeEnded = false;
}
void LocalitySet::unpin() {
this->lifetimeEnded = true;
}
LocalityType LocalitySet::getLocalityType() {
return this->localityType;
}
void LocalitySet::setLocalityType(LocalityType type) {
this->localityType = type;
}
LocalitySetReplacementPolicy LocalitySet::getReplacementPolicy() {
return this->replacementPolicy;
}
void LocalitySet::setReplacementPolicy(LocalitySetReplacementPolicy policy) {
this->replacementPolicy = policy;
}
OperationType LocalitySet::getOperationType() {
return this->operationType;
}
void LocalitySet::setOperationType(OperationType type) {
this->operationType = type;
}
DurabilityType LocalitySet::getDurabilityType() {
return this->durabilityType;
}
void LocalitySet::setDurabilityType(DurabilityType type) {
this->durabilityType = type;
}
PersistenceType LocalitySet::getPersistenceType() {
return this->persistenceType;
}
void LocalitySet::setPersistenceType(PersistenceType type) {
this->persistenceType = type;
}
bool LocalitySet::isLifetimeEnded() {
return this->lifetimeEnded;
}
void LocalitySet::setLifetimeEnd(bool lifetimeEnded) {
this->lifetimeEnded = lifetimeEnded;
}
#endif
|
Autoafterdarkphx/payflow-gateway | java/src/paypal/payments/samples/dataobjects/basictransactions/DOSwipe.java | package paypal.payments.samples.dataobjects.basictransactions;
import paypal.payflow.*;
// This class uses the Payflow SDK Data Objects to do a simple Authorize transaction using Swipe Data.
// The request is sent as a Data Object and the response received is also a Data Object.
// Payflow Pro supports card-present transactions (face-to-face purchases).
// Follow these guidelines to take advantage of the lower card-present transaction rate:
//
// * Contact your merchant account provider to ensure that they support card-present transactions.
// * Contact PayPal Customer Service to request having your account set up properly for accepting and passing
// swipe data.
// * If you plan to process card-present as well as card-not-present transactions, set up two separate Payflow
// Pro accounts. Request that one account be set up for card-present transactions, and use it solely for that
// purpose. Use the other for card-not-present transactions. Using the wrong account may result in downgrades.
// * A Sale is the preferred method to use for card-present transactions. Consult with your acquiring bank for
// recommendations on other methods.
//
// NOTE: The SWIPE parameter is not supported on accounts where PayPal is the Processor. This would include Website
// Payments Pro UK accounts.
//
// See the Payflow Pro Developer's Guide for more information.
public class DOSwipe {
public DOSwipe() {
}
public static void main(String args[]) {
System.out.println("------------------------------------------------------");
System.out.println("Executing Sample from File: DOSwipe.java");
System.out.println("------------------------------------------------------");
// Payflow Pro Host Name. This is the host name for the PayPal Payment Gateway.
// For testing: pilot-payflowpro.paypal.com
// For production: payflowpro.paypal.com
// DO NOT use payflow.verisign.com or test-payflow.verisign.com!
SDKProperties.setHostAddress("pilot-payflowpro.paypal.com");
SDKProperties.setHostPort(443);
SDKProperties.setTimeOut(45);
// Logging is by default off. To turn logging on uncomment the following lines:
// SDKProperties.setLogFileName("payflow_java.log");
// SDKProperties.setLoggingLevel(PayflowConstants.SEVERITY_DEBUG);
// SDKProperties.setMaxLogFileSize(1000000);
// Uncomment the lines below and set the proxy address and port, if a proxy has
// to be used.
// SDKProperties.setProxyAddress("");
// SDKProperties.setProxyPort(0);
// SDKProperties.setProxyLogin("");
// SDKProperties.setProxyPassword("");
// Create the Data Objects.
// Create the User data object with the required user details.
UserInfo user = new UserInfo("<user>", "<vendor>", "<partner>", "<password>");
// Create the Payflow Connection data object with the required connection
// details.
// The PAYFLOW_HOST are properties defined within SDKProperties.
PayflowConnectionData connection = new PayflowConnectionData();
// Create a new Invoice data object with the Amount, Billing Address etc.
// details.
Invoice inv = new Invoice();
// Set Amount.
Currency amt = new Currency(new Double(25.00), "USD");
inv.setAmt(amt);
inv.setPoNum("PO12345");
inv.setInvNum("INV12345");
// Create a new Payment Device - Swipe data object. The input parameter is Swipe
// Data.
// Used to pass the Track 1 or Track 2 data (the card's magnetic stripe
// information) for card-present
// transactions. Include either Track 1 or Track 2 data'not both. If Track 1 is
// physically damaged,
// the POS application can send Track 2 data instead.
// The parameter data for the SwipeCard object is usually obtained with a card
// reader.
// NOTE: The SWIPE parameter is not supported on accounts where PayPal is the
// Processor.
SwipeCard swipe = new SwipeCard(";5105105105105100=15121011000012345678?");
// Create a new Tender - Swipe Tender data object.
CardTender card = new CardTender(swipe);
// Create a new Sale Transaction.
SaleTransaction trans = new SaleTransaction(user, connection, inv, card, PayflowUtility.getRequestId());
// Submit the Transaction
Response resp = trans.submitTransaction();
// Display the transaction response parameters.
if (resp != null) {
// Get the Transaction Response parameters.
TransactionResponse trxnResponse = resp.getTransactionResponse();
// Create a new Client Information data object.
ClientInfo clInfo = new ClientInfo();
// Set the ClientInfo object of the transaction object.
trans.setClientInfo(clInfo);
if (trxnResponse != null) {
System.out.println("RESULT = " + trxnResponse.getResult());
System.out.println("PNREF = " + trxnResponse.getPnref());
System.out.println("RESPMSG = " + trxnResponse.getRespMsg());
System.out.println("AUTHCODE = " + trxnResponse.getAuthCode());
// If value is true, then the Request ID has not been changed and the original
// response
// of the original transction is returned.
System.out.println("DUPLICATE = " + trxnResponse.getDuplicate());
}
// Display the response.
System.out.println("\n" + PayflowUtility.getStatus(resp));
// Get the Transaction Context and check for any contained SDK specific errors
// (optional code).
Context transCtx = resp.getContext();
if (transCtx != null && transCtx.getErrorCount() > 0) {
System.out.println("\nTransaction Errors = " + transCtx.toString());
}
}
System.out.println("Press Enter to Exit ...");
}
}
|
ExpediaGroup/apiary-extensions | apiary-metastore-events/kafka-metastore-events/kafka-metastore-integration-tests/src/test/java/com/expediagroup/apiary/extensions/events/metastore/kafka/messaging/KafkaApiaryMetastoreIntegrationTest.java | <reponame>ExpediaGroup/apiary-extensions
/**
* Copyright (C) 2018-2020 Expedia, Inc.
*
* 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.expediagroup.apiary.extensions.events.metastore.kafka.messaging;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static com.expediagroup.apiary.extensions.events.metastore.kafka.messaging.KafkaIntegrationTestUtils.buildPartition;
import static com.expediagroup.apiary.extensions.events.metastore.kafka.messaging.KafkaIntegrationTestUtils.buildQualifiedTableName;
import static com.expediagroup.apiary.extensions.events.metastore.kafka.messaging.KafkaIntegrationTestUtils.buildTable;
import static com.expediagroup.apiary.extensions.events.metastore.kafka.messaging.KafkaIntegrationTestUtils.buildTableParameters;
import static com.expediagroup.apiary.extensions.events.metastore.kafka.messaging.KafkaMessageReader.KafkaMessageReaderBuilder;
import static com.expediagroup.apiary.extensions.events.metastore.kafka.messaging.KafkaProducerProperty.BOOTSTRAP_SERVERS;
import static com.expediagroup.apiary.extensions.events.metastore.kafka.messaging.KafkaProducerProperty.CLIENT_ID;
import static com.expediagroup.apiary.extensions.events.metastore.kafka.messaging.KafkaProducerProperty.TOPIC_NAME;
import java.util.ArrayList;
import java.util.Properties;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.metastore.HiveMetaStore.HMSHandler;
import org.apache.hadoop.hive.metastore.api.GetTableResult;
import org.apache.hadoop.hive.metastore.api.InsertEventRequestData;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.events.AddPartitionEvent;
import org.apache.hadoop.hive.metastore.events.AlterPartitionEvent;
import org.apache.hadoop.hive.metastore.events.AlterTableEvent;
import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
import org.apache.hadoop.hive.metastore.events.DropPartitionEvent;
import org.apache.hadoop.hive.metastore.events.DropTableEvent;
import org.apache.hadoop.hive.metastore.events.InsertEvent;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import com.google.common.collect.Lists;
import com.salesforce.kafka.test.junit4.SharedKafkaTestResource;
import com.expediagroup.apiary.extensions.events.metastore.event.ApiaryAddPartitionEvent;
import com.expediagroup.apiary.extensions.events.metastore.event.ApiaryAlterPartitionEvent;
import com.expediagroup.apiary.extensions.events.metastore.event.ApiaryAlterTableEvent;
import com.expediagroup.apiary.extensions.events.metastore.event.ApiaryCreateTableEvent;
import com.expediagroup.apiary.extensions.events.metastore.event.ApiaryDropPartitionEvent;
import com.expediagroup.apiary.extensions.events.metastore.event.ApiaryDropTableEvent;
import com.expediagroup.apiary.extensions.events.metastore.event.ApiaryInsertEvent;
import com.expediagroup.apiary.extensions.events.metastore.event.ApiaryListenerEvent;
import com.expediagroup.apiary.extensions.events.metastore.kafka.listener.KafkaMetaStoreEventListener;
@RunWith(MockitoJUnitRunner.class)
public class KafkaApiaryMetastoreIntegrationTest {
@ClassRule
public static final SharedKafkaTestResource KAFKA = new SharedKafkaTestResource();
private static final long TEST_TIMEOUT_MS = 10000;
private static Configuration CONF = new Configuration();
private static KafkaMetaStoreEventListener kafkaMetaStoreEventListener;
private static KafkaMessageReader kafkaMessageReader;
private @Mock HMSHandler hmsHandler;
@BeforeClass
public static void init() {
CONF.set(BOOTSTRAP_SERVERS.key(), KAFKA.getKafkaConnectString());
CONF.set(CLIENT_ID.key(), "client");
CONF.set(TOPIC_NAME.key(), "topic");
KAFKA.getKafkaTestUtils().createTopic("topic", 1, (short) 1);
kafkaMetaStoreEventListener = new KafkaMetaStoreEventListener(CONF);
//this makes sure the consumer starts from the beginning on the first read
Properties consumerProperties = new Properties();
consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
kafkaMessageReader = KafkaMessageReaderBuilder.builder(KAFKA.getKafkaConnectString(), "topic", "app")
.withConsumerProperties(consumerProperties)
.build();
}
@Test(timeout = TEST_TIMEOUT_MS)
public void createTableEvent() {
CreateTableEvent createTableEvent = new CreateTableEvent(buildTable(), true, hmsHandler);
kafkaMetaStoreEventListener.onCreateTable(createTableEvent);
ApiaryListenerEvent result = kafkaMessageReader.next();
assertThat(result).isInstanceOf(ApiaryCreateTableEvent.class);
ApiaryCreateTableEvent event = (ApiaryCreateTableEvent) result;
assertThat(event.getQualifiedTableName()).isEqualTo(buildQualifiedTableName());
assertThat(event.getTable().getParameters()).isEqualTo(buildTableParameters());
assertThat(event.getStatus()).isEqualTo(true);
}
@Test(timeout = TEST_TIMEOUT_MS)
public void dropTableEvent() {
DropTableEvent dropTableEvent = new DropTableEvent(buildTable(), true, false, hmsHandler);
kafkaMetaStoreEventListener.onDropTable(dropTableEvent);
ApiaryListenerEvent result = kafkaMessageReader.next();
assertThat(result).isInstanceOf(ApiaryDropTableEvent.class);
ApiaryDropTableEvent event = (ApiaryDropTableEvent) result;
assertThat(event.getQualifiedTableName()).isEqualTo(buildQualifiedTableName());
assertThat(event.getTable().getParameters()).isEqualTo(buildTableParameters());
assertThat(event.getStatus()).isEqualTo(true);
}
@Test(timeout = TEST_TIMEOUT_MS)
public void alterTableEvent() {
AlterTableEvent alterTableEvent = new AlterTableEvent(buildTable("old_table"), buildTable("new_table"), true,
hmsHandler);
kafkaMetaStoreEventListener.onAlterTable(alterTableEvent);
ApiaryListenerEvent result = kafkaMessageReader.next();
assertThat(result).isInstanceOf(ApiaryAlterTableEvent.class);
ApiaryAlterTableEvent event = (ApiaryAlterTableEvent) result;
assertThat(event.getQualifiedTableName()).isEqualTo("database.new_table");
assertThat(event.getOldTable().getTableName()).isEqualTo("old_table");
assertThat(event.getNewTable().getTableName()).isEqualTo("new_table");
assertThat(event.getOldTable().getParameters()).isEqualTo(buildTableParameters());
assertThat(event.getNewTable().getParameters()).isEqualTo(buildTableParameters());
assertThat(event.getStatus()).isEqualTo(true);
}
@Test(timeout = TEST_TIMEOUT_MS)
public void addPartitionEvent() {
AddPartitionEvent addPartitionEvent = new AddPartitionEvent(buildTable(), buildPartition(), true, hmsHandler);
kafkaMetaStoreEventListener.onAddPartition(addPartitionEvent);
ApiaryListenerEvent result = kafkaMessageReader.next();
assertThat(result).isInstanceOf(ApiaryAddPartitionEvent.class);
ApiaryAddPartitionEvent event = (ApiaryAddPartitionEvent) result;
assertThat(event.getQualifiedTableName()).isEqualTo(buildQualifiedTableName());
assertThat(event.getTable().getParameters()).isEqualTo(buildTableParameters());
assertThat(event.getPartitions()).isEqualTo(Lists.newArrayList(buildPartition()));
assertThat(event.getStatus()).isEqualTo(true);
}
@Test(timeout = TEST_TIMEOUT_MS)
public void dropPartitionEvent() {
DropPartitionEvent dropPartitionEvent = new DropPartitionEvent(buildTable(), buildPartition(), true, false,
hmsHandler);
kafkaMetaStoreEventListener.onDropPartition(dropPartitionEvent);
ApiaryListenerEvent result = kafkaMessageReader.next();
assertThat(result).isInstanceOf(ApiaryDropPartitionEvent.class);
ApiaryDropPartitionEvent event = (ApiaryDropPartitionEvent) result;
assertThat(event.getQualifiedTableName()).isEqualTo(buildQualifiedTableName());
assertThat(event.getTable().getParameters()).isEqualTo(buildTableParameters());
assertThat(event.getPartitions()).isEqualTo(Lists.newArrayList(buildPartition()));
assertThat(event.getStatus()).isEqualTo(true);
}
@Test(timeout = TEST_TIMEOUT_MS)
public void alterPartitionEvent() {
Partition oldPartition = buildPartition("old_partition");
Partition newPartition = buildPartition("new_partition");
AlterPartitionEvent alterPartitionEvent = new AlterPartitionEvent(oldPartition, newPartition, buildTable(), true,
hmsHandler);
kafkaMetaStoreEventListener.onAlterPartition(alterPartitionEvent);
ApiaryListenerEvent result = kafkaMessageReader.next();
assertThat(result).isInstanceOf(ApiaryAlterPartitionEvent.class);
ApiaryAlterPartitionEvent event = (ApiaryAlterPartitionEvent) result;
assertThat(event.getQualifiedTableName()).isEqualTo(buildQualifiedTableName());
assertThat(event.getTable().getParameters()).isEqualTo(buildTableParameters());
assertThat(event.getOldPartition()).isEqualTo(oldPartition);
assertThat(event.getNewPartition()).isEqualTo(newPartition);
assertThat(event.getStatus()).isEqualTo(true);
}
@Test(timeout = TEST_TIMEOUT_MS)
public void insertPartitionEvent() throws MetaException, NoSuchObjectException {
when(hmsHandler.get_table_req(any())).thenReturn(new GetTableResult(buildTable()));
ArrayList<String> partitionValues = Lists.newArrayList("value1", "value2");
InsertEvent insertEvent = new InsertEvent(
"database",
"table",
partitionValues,
new InsertEventRequestData(Lists.newArrayList("file1", "file2")),
true,
hmsHandler
);
kafkaMetaStoreEventListener.onInsert(insertEvent);
ApiaryListenerEvent result = kafkaMessageReader.next();
assertThat(result).isInstanceOf(ApiaryInsertEvent.class);
ApiaryInsertEvent event = (ApiaryInsertEvent) result;
assertThat(event.getQualifiedTableName()).isEqualTo(buildQualifiedTableName());
assertThat(event.getStatus()).isEqualTo(true);
}
}
|
poisondog/poisondog.commons | src/main/java/poisondog/io/CopyTask.java | <reponame>poisondog/poisondog.commons
/*
* Copyright (C) 2014 <NAME>
*
* 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 poisondog.io;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashSet;
/**
* // TODO implements Mission
* @author <NAME>
*/
public class CopyTask implements Runnable {
private byte[] mBuffer;
private InputStream mInput;
private OutputStream mOutput;
private boolean mCancel;
private boolean mComplete;
private boolean mNeedClose;
private Collection<StepListener> mStepListeners;
private Collection<CancelListener> mCancelListeners;
public CopyTask(InputStream input, OutputStream output) {
mBuffer = new byte[1024];
mStepListeners = new HashSet<StepListener>();
mCancelListeners = new HashSet<CancelListener>();
mInput = input;
mOutput = output;
mNeedClose = true;
}
public InputStream getInputStream() {
return mInput;
}
public OutputStream getOutputStream() {
return mOutput;
}
public void setBuffer(byte[] buffer) {
mBuffer = buffer;
}
public void setClose(boolean close) {
mNeedClose = close;
}
public void cancel() {
if(mComplete)
return;
mCancel = true;
for (CancelListener listener : mCancelListeners) {
listener.onCancel();
}
}
public void close() throws IOException {
if(mInput == null || mOutput == null)
return;
mOutput.close();
mInput.close();
}
public void addCancelListener(CancelListener listener) {
mCancelListeners.add(listener);
}
public void addStepListener(StepListener listener) {
if (listener != null)
mStepListeners.add(listener);
}
public void transport() throws IOException {
while(stepWrite());
}
@Override
public void run() {
try {
transport();
} catch(Exception e) {
e.printStackTrace();
}
}
public boolean isComplete() {
return mComplete;
}
public boolean isCancelled() {
return mCancel;
}
public boolean stepWrite() throws IOException {
if(mInput == null || mOutput == null)
return false;
if (mCancel) {
if (mNeedClose)
close();
return false;
}
int length = mInput.read(mBuffer);
if(length != -1) {
mComplete = false;
mOutput.write(mBuffer, 0, length);
for (StepListener listener : mStepListeners) {
listener.onStep(length);
}
return true;
}
if (mNeedClose)
close();
mComplete = true;
return false;
}
}
|
mrdulin/react-apollo-graphql-starter-kit | stackoverflow/60730701/validator.js | const Joi = require('joi');
module.exports = {
validateExternalId: (schema, name) => {
return (req, res, next) => {
const result = Joi.validate({ param: req.params[name] }, schema);
if (result.error) {
return res.status(400).send(result.error.details[0].message);
}
next();
};
},
schemas: {
idSchema: Joi.object().keys({
param: Joi.string()
.regex(/^[a-zA-Z0-9]{20}$/)
.required(),
}),
},
};
|
ruanlinjing/oneplatform | oneplatform-platform/src/main/java/com/oneplatform/system/controller/PermissionQueryController.java | /*
* Copyright 2016-2018 www.jeesuite.com.
*
* 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.oneplatform.system.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jeesuite.common.model.SelectOption;
import com.jeesuite.mybatis.plugin.pagination.Page;
import com.jeesuite.mybatis.plugin.pagination.PageParams;
import com.jeesuite.springweb.model.WrapperResponse;
import com.oneplatform.base.annotation.ApiPermOptions;
import com.oneplatform.base.constants.PermissionType;
import com.oneplatform.base.model.PageResult;
import com.oneplatform.base.model.SelectOptGroup;
import com.oneplatform.base.model.TreeModel;
import com.oneplatform.system.constants.PermissionResourceType;
import com.oneplatform.system.dao.entity.ModuleEntity;
import com.oneplatform.system.dao.entity.PermissionGroupEntity;
import com.oneplatform.system.dao.entity.PermissionResourceEntity;
import com.oneplatform.system.dao.entity.UserGroupEntity;
import com.oneplatform.system.dto.param.QueryPermissionCheckedParam;
import com.oneplatform.system.dto.param.QueryResourceParam;
import com.oneplatform.system.dto.param.QueryUserGroupParam;
import com.oneplatform.system.service.ModuleService;
import com.oneplatform.system.service.PermissionService;
import io.swagger.annotations.ApiOperation;
/**
* @description <br>
* @author <a href="mailto:<EMAIL>">vakin</a>
* @date 2019年4月24日
*/
@Controller
@RequestMapping(value = "/perm")
@ApiPermOptions(perms = PermissionType.Logined)
public class PermissionQueryController {
private @Autowired ModuleService moduleService;
private @Autowired PermissionService permissionService;
@ApiOperation(value = "查询用户组选项列表")
@RequestMapping(value = "usergroup/options", method = RequestMethod.GET)
public @ResponseBody WrapperResponse<List<SelectOption>> findUserGroups(@RequestParam("platformType") String platformType) {
QueryUserGroupParam param = new QueryUserGroupParam();
param.setPlatformType(platformType);
param.setEnabled(true);
List<SelectOption> list = permissionService.findUserGroups(param)
.stream()
.map(e -> {
return new SelectOption(e.getId().toString(), e.getName());
}).collect(Collectors.toList());
return new WrapperResponse<>(list);
}
@ApiOperation(value = "查询权限组选项列表")
@RequestMapping(value = "permgroup/options", method = RequestMethod.GET)
public @ResponseBody WrapperResponse<List<SelectOption>> findPermGroups(@RequestParam("platformType") String platformType) {
List<SelectOption> list = permissionService.findPermissionGroupList(platformType)
.stream()
.filter(e -> e.getEnabled())
.map(e -> {
return new SelectOption(e.getId().toString(), e.getName());
}).collect(Collectors.toList());
return new WrapperResponse<>(list);
}
@ApiOperation(value = "查询菜单选项列表")
@RequestMapping(value = "menu/options", method = RequestMethod.GET)
public @ResponseBody WrapperResponse<List<SelectOptGroup>> findMenuOptions(@RequestParam("platformType") String platformType) {
List<PermissionResourceEntity> resources = findMenuResources(platformType);
Map<Integer, SelectOptGroup> parentMap = new HashMap<>();
for (PermissionResourceEntity resource : resources) {
if(resource.getParentId() != null && resource.getParentId() > 0){
parentMap.get(resource.getParentId()).getOptions().add(new SelectOption(resource.getId().toString(), resource.getName()));
}else{
SelectOptGroup group = new SelectOptGroup(resource.getName());
parentMap.put(resource.getId(), group);
}
}
return new WrapperResponse<>(new ArrayList<>(parentMap.values()));
}
@ApiOperation(value = "查询菜单下选项列表")
@RequestMapping(value = "/menu/apis", method = RequestMethod.GET)
public @ResponseBody WrapperResponse<List<SelectOption>> findPermissionResourceByMenuId(@RequestParam("menuId") Integer menuId) {
return new WrapperResponse<>(buildMenuApiOptions(menuId));
}
@ApiOperation(value = "查询资源列表树")
@RequestMapping(value = "resource/tree", method = RequestMethod.GET)
public @ResponseBody WrapperResponse<List<TreeModel>> getResourceTree(@RequestParam("type") String type
,@RequestParam(value="platformType",required=false) String platformType
,@RequestParam(value="moduleId",required=false) Integer moduleId) {
if("module".equals(type)){
List<TreeModel> treeModels = moduleService.findEnabledModules().stream().map(e -> {
return new TreeModel(e.getId(), e.getName(), e.getServiceId(), null, null, false);
}).collect(Collectors.toList());
return new WrapperResponse<>(TreeModel.build(treeModels).getChildren());
}
QueryResourceParam param = new QueryResourceParam();
param.setType(type);
param.setPlatformType(platformType);
param.setEnabled(true);
//只查询需要授权的接口
if(PermissionResourceType.api.name().equals(type)){
param.setGrantType(PermissionType.Authorized.name());
param.setModuleId(moduleId);
}
List<PermissionResourceEntity> resources = permissionService.findPermissionResources(param);
//如果是查询全部模块的接口,模块作为虚拟父节点
if(PermissionResourceType.api.name().equals(param.getType()) && moduleId == null){
Map<Integer, PermissionResourceEntity> virtualParents = new HashMap<>();
Map<Integer, ModuleEntity> modoules = moduleService.getAllModules();
PermissionResourceEntity virtualParent;
for (PermissionResourceEntity entity : resources) {
virtualParent = virtualParents.get(entity.getModuleId());
if(virtualParent == null){
ModuleEntity serviceMetadata = modoules.get(entity.getModuleId());
virtualParent = new PermissionResourceEntity();
if(serviceMetadata != null){
virtualParent.setId(0 - serviceMetadata.getId().intValue());
virtualParent.setType(PermissionResourceType.api.name());
virtualParent.setName(serviceMetadata.getName());
}
virtualParents.put(entity.getModuleId(), virtualParent);
}
entity.setParentId(virtualParent.getId());
}
resources.addAll(virtualParents.values());
}
return new WrapperResponse<>(PermissionResourceEntity.buildTree(resources).getChildren());
}
@ApiOperation(value = "查询权限列表树")
@RequestMapping(value = "permission/tree", method = RequestMethod.POST)
public @ResponseBody WrapperResponse<List<TreeModel>> getPermissionGroups(@RequestBody QueryPermissionCheckedParam param) {
List<TreeModel> list = permissionService.buildPermissionTreeWithCheckStatus(param);
return new WrapperResponse<>(list);
}
@ApiOperation(value = "分页API列表")
@RequestMapping(value = "/resources/apiList", method = RequestMethod.POST)
public @ResponseBody PageResult<PermissionResourceEntity> pageApis(@ModelAttribute QueryResourceParam pageParam) {
pageParam.setType(PermissionResourceType.api.name());
Page<PermissionResourceEntity> page = permissionService.pageQueryResourceList(pageParam, pageParam);
return new PageResult<>(pageParam.getPageNo(), pageParam.getPageSize(), page.getTotal(), page.getData());
}
@ApiOperation(value = "分页权限组列表")
@RequestMapping(value = "/permgroup/list", method = RequestMethod.POST)
public @ResponseBody PageResult<PermissionGroupEntity> pagePermGroups(@RequestParam("pageNo") int pageNo,
@RequestParam("pageSize") int pageSize,
@RequestParam(value="platformType",required=false) String platformType) {
if(StringUtils.isBlank(platformType))platformType = "admin";
Page<PermissionGroupEntity> page = permissionService.pageQueryPermissionGroupList(new PageParams(pageNo, pageSize), platformType);
return new PageResult<>(pageNo, pageSize, page.getTotal(), page.getData());
}
@ApiOperation(value = "权限组详情")
@RequestMapping(value = "/permgroup/details/{id}", method = RequestMethod.GET)
public @ResponseBody WrapperResponse<PermissionGroupEntity> getPermissionGroup(@PathVariable("id") Integer id){
PermissionGroupEntity group = permissionService.findPermissionGroup(id);
return new WrapperResponse<>(group);
}
@ApiOperation(value = "用户组列表")
@RequestMapping(value = "/usergroup/list", method = RequestMethod.POST)
public @ResponseBody PageResult<UserGroupEntity> pageUserGroups(@RequestParam("pageNo") int pageNo,
@RequestParam("pageSize") int pageSize,
@RequestParam(value="platformType",required=false) String platformType){
if(StringUtils.isBlank(platformType))platformType = "admin";
QueryUserGroupParam param = new QueryUserGroupParam();
param.setPlatformType(platformType);
Page<UserGroupEntity> page = permissionService.pagequeryUserGroups(new PageParams(pageNo, pageSize),param);
return new PageResult<>(pageNo, pageSize, page.getTotal(), page.getData());
}
@ApiOperation(value = "用户组详情")
@RequestMapping(value = "/usergroup/details/{id}", method = RequestMethod.GET)
public @ResponseBody WrapperResponse<UserGroupEntity> getUserGroup(@PathVariable("id") Integer id){
UserGroupEntity userGroup = permissionService.findUserGroup(id);
return new WrapperResponse<>(userGroup);
}
@ApiOperation(value = "权限资源详情")
@RequestMapping(value = "/resource/details/{id}", method = RequestMethod.GET)
public @ResponseBody WrapperResponse<PermissionResourceEntity> getPermResoure(@PathVariable("id") Integer id){
PermissionResourceEntity entity = permissionService.findPermissionResource(id);
return new WrapperResponse<>(entity);
}
private List<PermissionResourceEntity> findMenuResources(String platformType){
QueryResourceParam param = new QueryResourceParam();
param.setPlatformType(platformType);
param.setType(PermissionResourceType.menu.name());
param.setEnabled(true);
return permissionService.findPermissionResources(param);
}
private List<SelectOption> buildMenuApiOptions(Integer menuId){
return permissionService.findMenuRelateApiResource(menuId)
.stream()
.filter(e -> e.getEnabled())
.map(e -> {
return new SelectOption(e.getId().toString(), e.getName());
}).collect(Collectors.toList());
}
}
|
hmrc/soft-drinks-industry-levy | test/uk/gov/hmrc/softdrinksindustrylevy/services/OverdueSubmissionsCheckerSpec.scala | /*
* Copyright 2021 HM Revenue & Customs
*
* 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 uk.gov.hmrc.softdrinksindustrylevy.services
import akka.actor.ActorSystem
import org.mockito.ArgumentMatchers.{any, contains, eq => mEq}
import org.mockito.Mockito.when
import org.scalatestplus.mockito.MockitoSugar
import play.api.Configuration
import uk.gov.hmrc.mongo.MongoConnector
import uk.gov.hmrc.softdrinksindustrylevy.connectors.ContactFrontendConnector
import uk.gov.hmrc.softdrinksindustrylevy.util.FakeApplicationSpec
import scala.concurrent.ExecutionContext
class OverdueSubmissionsCheckerSpec extends FakeApplicationSpec with MockitoSugar {
val minutesTestVal: Long = 59
"vals" should {
val configMock: Configuration = mock[Configuration]
when(configMock.getOptional[Boolean](contains("enabled"))(any())) thenReturn Option(false)
when(configMock.getOptional[Long](contains("Minutes"))(any())) thenReturn Option(minutesTestVal)
val overdueSubmissionsCheckerMock = new OverdueSubmissionsChecker(
configMock,
mock[MongoConnector],
mock[ActorSystem],
mock[MongoBufferService],
mock[ContactFrontendConnector])(mock[ExecutionContext])
"jobEnabled correct" in {
overdueSubmissionsCheckerMock.jobEnabled mustBe false
}
"jobStartDelay correct" in {
overdueSubmissionsCheckerMock.jobStartDelay.toString() mustBe s"$minutesTestVal minutes"
}
"overduePeriod correct" in {
overdueSubmissionsCheckerMock.overduePeriod.getStandardMinutes mustBe minutesTestVal
}
"jobInterval correct" in {
overdueSubmissionsCheckerMock.jobInterval.getStandardMinutes mustBe minutesTestVal
}
}
"exceptions" should {
"jobEnabled throw exception" in {
val configMock: Configuration = mock[Configuration]
when(configMock.getOptional[Boolean](contains("enabled"))(any())) thenReturn None
the[MissingConfiguration] thrownBy new OverdueSubmissionsChecker(
configMock,
mock[MongoConnector],
mock[ActorSystem],
mock[MongoBufferService],
mock[ContactFrontendConnector])(mock[ExecutionContext]) must have message "Missing configuration value overdueSubmissions.enabled"
}
"jobStartDelay throw exception" in {
val configMock: Configuration = mock[Configuration]
when(configMock.getOptional[Long](mEq("overdueSubmissions.startDelayMinutes"))(any())) thenReturn None
when(configMock.getOptional[Boolean](contains("enabled"))(any())) thenReturn Option(false)
the[MissingConfiguration] thrownBy new OverdueSubmissionsChecker(
configMock,
mock[MongoConnector],
mock[ActorSystem],
mock[MongoBufferService],
mock[ContactFrontendConnector])(mock[ExecutionContext]) must have message "Missing configuration value overdueSubmissions.startDelayMinutes"
}
"overduePeriod throw exception" in {
val configMock: Configuration = mock[Configuration]
when(configMock.getOptional[Long](mEq("overdueSubmissions.startDelayMinutes"))(any())) thenReturn Option(
minutesTestVal)
when(configMock.getOptional[Long](mEq("overdueSubmissions.overduePeriodMinutes"))(any())) thenReturn None
when(configMock.getOptional[Boolean](contains("enabled"))(any())) thenReturn Option(false)
the[MissingConfiguration] thrownBy new OverdueSubmissionsChecker(
configMock,
mock[MongoConnector],
mock[ActorSystem],
mock[MongoBufferService],
mock[ContactFrontendConnector])(mock[ExecutionContext]) must have message "Missing configuration value overdueSubmissions.overduePeriodMinutes"
}
"jobInterval throw exception" in {
val configMock: Configuration = mock[Configuration]
when(configMock.getOptional[Long](mEq("overdueSubmissions.startDelayMinutes"))(any())) thenReturn Option(
minutesTestVal)
when(configMock.getOptional[Long](mEq("overdueSubmissions.overduePeriodMinutes"))(any())) thenReturn Option(
minutesTestVal)
when(configMock.getOptional[Long](mEq("overdueSubmissions.jobIntervalMinutes"))(any())) thenReturn None
when(configMock.getOptional[Boolean](contains("enabled"))(any())) thenReturn Option(false)
the[MissingConfiguration] thrownBy new OverdueSubmissionsChecker(
configMock,
mock[MongoConnector],
mock[ActorSystem],
mock[MongoBufferService],
mock[ContactFrontendConnector])(mock[ExecutionContext]) must have message "Missing configuration value overdueSubmissions.jobIntervalMinutes"
}
}
}
|
cheerfulwang/python-tutorial | 24web/tornado_demo/09calc_demo.py | <reponame>cheerfulwang/python-tutorial
# -*- coding: utf-8 -*-
"""
@author:XuMing(<EMAIL>)
@description:
"""
import tornado.ioloop
import tornado.web
class FactorialService(object):
def __init__(self):
self.cache = {}
def calc(self, n):
if n in self.cache:
return self.cache[n]
s = 1
for i in range(1, n):
s *= i
self.cache[n] = s
return s
class IndexHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.write("hello world")
class FactorialHandler(tornado.web.RequestHandler):
service = FactorialService()
def get(self, *args, **kwargs):
n = int(self.get_argument("n"))
self.write("%s!=%s" % (n, str(self.service.calc(n))))
def make_app():
return tornado.web.Application([
(r"/", IndexHandler),
(r"/fact", FactorialHandler),
])
if __name__ == '__main__':
app = make_app()
app.listen(9999)
tornado.ioloop.IOLoop.current().start()
|
nodejayes/acts | spec/sockets/testsocket.js | module.exports = function (data) {
this.emit('testsend', data);
} |
muminkoykiran/computervision-recipes | tests/unit/classification/test_classification_plot.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import pytest
import numpy as np
from utils_cv.classification.plot import (
plot_roc_curve,
plot_precision_recall_curve,
plot_pr_roc_curves,
plot_thresholds,
)
from utils_cv.classification.model import hamming_accuracy, zero_one_accuracy
def test_plot_threshold(multilabel_result):
""" Test the plot_loss_threshold function """
y_pred, y_true = multilabel_result
plot_thresholds(hamming_accuracy, y_pred, y_true)
plot_thresholds(zero_one_accuracy, y_pred, y_true)
@pytest.fixture(scope="module")
def binaryclass_result_1():
# Binary-class classification testcase 1
BINARY_Y_TRUE = [0, 0, 1, 1]
BINARY_Y_SCORE = [0.1, 0.4, 0.35, 0.8]
BINARY_CLASSES = [0, 1]
return np.array(BINARY_Y_TRUE), np.array(BINARY_Y_SCORE), BINARY_CLASSES
@pytest.fixture(scope="module")
def binaryclass_result_2():
# Binary-class classification testcase 2
BINARY_Y_TRUE = [0, 0, 1, 1]
BINARY_Y_SCORE = [[0.1, 0.9], [0.4, 0.6], [0.35, 0.65], [0.8, 0.2]]
BINARY_CLASSES = [0, 1]
return np.array(BINARY_Y_TRUE), np.array(BINARY_Y_SCORE), BINARY_CLASSES
@pytest.fixture(scope="module")
def multiclass_result():
# Multi-class classification testcase
MULTI_Y_TRUE = [0, 0, 1, 1, 2, 2]
MULTI_Y_SCORE = [
[0.1, 0.9, 0.0],
[0.4, 0.2, 0.4],
[0.35, 0.15, 0.5],
[0.1, 0.8, 0.1],
[0.2, 0.5, 0.3],
[0.0, 0.1, 0.9],
]
MULTI_CLASSES = [0, 1, 2]
return np.array(MULTI_Y_TRUE), np.array(MULTI_Y_SCORE), MULTI_CLASSES
def test_plot_roc_curve(
binaryclass_result_1, binaryclass_result_2, multiclass_result
):
# Binary-class plot
y_true, y_score, classes = binaryclass_result_1
plot_roc_curve(y_true, y_score, classes, False)
y_true, y_score, classes = binaryclass_result_2
plot_roc_curve(y_true, y_score, classes, False)
# Multi-class plot
y_true, y_score, classes = multiclass_result
plot_roc_curve(y_true, y_score, classes, False)
def test_plot_precision_recall_curve(
binaryclass_result_1, binaryclass_result_2, multiclass_result
):
# Binary-class plot
y_true, y_score, classes = binaryclass_result_1
plot_precision_recall_curve(y_true, y_score, classes, False)
y_true, y_score, classes = binaryclass_result_2
plot_precision_recall_curve(y_true, y_score, classes, False)
# Multi-class plot
y_true, y_score, classes = multiclass_result
plot_precision_recall_curve(y_true, y_score, classes, False)
def test_plot_pr_roc_curves(
binaryclass_result_1, binaryclass_result_2, multiclass_result
):
# Binary-class plot
y_true, y_score, classes = binaryclass_result_1
plot_pr_roc_curves(y_true, y_score, classes, False, (1, 1))
y_true, y_score, classes = binaryclass_result_2
plot_pr_roc_curves(y_true, y_score, classes, False, (1, 1))
# Multi-class plot
y_true, y_score, classes = multiclass_result
plot_pr_roc_curves(y_true, y_score, classes, False, (1, 1))
|
chgzm/minic | test/test_struct_6.c | <gh_stars>1-10
typedef struct Entry Entry;
struct Entry {
int a;
int b;
Entry* next;
};
typedef struct Sample Sample;
struct Sample {
Entry** entries;
};
int func(Sample* s) {
int c = 0;
for (int i = 0; i < 8; ++i) {
if (s->entries[i] == 0) {
break;
}
c += s->entries[i]->a;
c += s->entries[i]->b;
if (s->entries[i]->next != 0) {
Entry* current = s->entries[i]->next;
c += current->a;
c += current->b;
}
}
return c;
}
int main() {
Sample* sample = calloc(1, sizeof(Sample));
sample->entries = calloc(8, sizeof(Entry*));
sample->entries[0] = calloc(1, sizeof(Entry));
sample->entries[0]->a = 1;
sample->entries[0]->b = 2;
sample->entries[0]->next = calloc(1, sizeof(Entry));
Entry* current = sample->entries[0]->next;
current->a = 16;
current->b = 32;
current->next = 0;
sample->entries[1] = calloc(1, sizeof(Entry));
sample->entries[1]->a = 4;
sample->entries[1]->b = 8;
sample->entries[1]->next = 0;
return func(sample);
}
|
gandhi56/swift | include/swift/AST/ModuleNameLookup.h | //===--- ModuleNameLookup.h - Name lookup within a module -------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines interfaces for performing top-level name lookup into a
// set of imported modules.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_AST_MODULE_NAME_LOOKUP_H
#define SWIFT_AST_MODULE_NAME_LOOKUP_H
#include "llvm/ADT/SmallVector.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/Module.h"
#include "swift/Basic/SourceLoc.h"
namespace swift {
class ValueDecl;
namespace namelookup {
enum class ResolutionKind {
/// Lookup can match any number of decls, as long as they are all
/// overloadable.
///
/// If non-overloadable decls are returned, this indicates ambiguous lookup.
Overloadable,
/// Lookup should match a single decl that declares a type.
TypesOnly
};
void simple_display(llvm::raw_ostream &out, ResolutionKind kind);
/// Performs a lookup into the given module and it's imports.
///
/// If 'moduleOrFile' is a ModuleDecl, we search the module and it's
/// public imports. If 'moduleOrFile' is a SourceFile, we search the
/// file's parent module, the module's public imports, and the source
/// file's private imports.
///
/// \param moduleOrFile The module or file unit whose imports to search.
/// \param name The name to look up.
/// \param[out] decls Any found decls will be added to this vector.
/// \param lookupKind Whether this lookup is qualified or unqualified.
/// \param resolutionKind What sort of decl is expected.
/// \param moduleScopeContext The top-level context from which the lookup is
/// being performed, for checking access. This must be either a
/// FileUnit or a Module.
/// \param options name lookup options. Currently only used to communicate the
/// NL_IncludeUsableFromInline option.
void lookupInModule(const DeclContext *moduleOrFile,
DeclName name, SmallVectorImpl<ValueDecl *> &decls,
NLKind lookupKind, ResolutionKind resolutionKind,
const DeclContext *moduleScopeContext,
NLOptions options);
/// Performs a qualified lookup into the given module and, if necessary, its
/// reexports, observing proper shadowing rules.
void
lookupVisibleDeclsInModule(const DeclContext *moduleOrFile,
ImportPath::Access accessPath,
SmallVectorImpl<ValueDecl *> &decls,
NLKind lookupKind,
ResolutionKind resolutionKind,
const DeclContext *moduleScopeContext);
} // end namespace namelookup
} // end namespace swift
#endif
|
tlmrgvf/drtd | src/ui/ScopeDialog.hpp | /*
BSD 2-Clause License
Copyright (c) 2020, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/
#pragma once
#include <Fl/Fl_Check_Button.H>
#include <Fl/Fl_Light_Button.H>
#include <Fl/Fl_Slider.H>
#include <Fl/Fl_Window.H>
#include <stdio.h>
#include <util/Singleton.hpp>
namespace Ui {
class ScopeDialog final : Fl_Window {
public:
static void show_dialog();
static void load_from_scope();
static void save_to_scope(Fl_Widget*, void*);
private:
ScopeDialog();
static ScopeDialog* new_dialog() { return new ScopeDialog(); };
static inline Singleton<ScopeDialog, ScopeDialog::new_dialog> s_scope_dialog;
Fl_Slider m_zoom;
Fl_Button m_reset_zoom;
Fl_Check_Button m_remove_bias;
Fl_Check_Button m_normalized;
Fl_Light_Button m_pause;
Fl_Button m_capture;
};
}
|
diamondap/exchange | network/s3_mock.go | <filename>network/s3_mock.go<gh_stars>1-10
package network
import (
"fmt"
"net/http"
)
func getBasicHeaders() map[string]string {
return map[string]string{
"x-amz-id-2": "ef8yU9AS1ed4OpIszj7UDNEHGran",
"x-amz-request-id": "318BC8BC143432E5",
"x-amz-version-id": "3HL4kqtJlcpXroDTDmjVBH40Nrjfkd",
"Date": "Wed, 30 May 2018 22:32:00 GMT",
"Last-Modified": "Tue, 29 May 2018 12:00:00 GMT",
"ETag": `"fba9dede5f27731c9771645a39863328"`,
"Content-Length": "434234",
"Content-Type": "text/plain",
"Connection": "close",
"Server": "AmazonS3",
}
}
func S3HeadHandler(w http.ResponseWriter, r *http.Request) {
for key, value := range getBasicHeaders() {
w.Header().Set(key, value)
}
fmt.Fprintln(w, "")
}
// Handles an S3 Head request and replies that a restore is already in progress.
func S3HeadRestoreInProgressHandler(w http.ResponseWriter, r *http.Request) {
for key, value := range getBasicHeaders() {
w.Header().Set(key, value)
}
w.Header().Set("x-amz-restore", `ongoing-request="true"`)
fmt.Fprintln(w, "")
}
// Handles an S3 Head request and replies that a restore is complete.
func S3HeadRestoreCompletedHandler(w http.ResponseWriter, r *http.Request) {
for key, value := range getBasicHeaders() {
w.Header().Set(key, value)
}
w.Header().Set("x-amz-restore", `ongoing-request="false", expiry-date="Fri, 01 Jun 2018 04:00:00 GMT"`)
fmt.Fprintln(w, "")
}
func getRestoreHeaders() map[string]string {
return map[string]string{
"x-amz-id-2": "GFihv3y6+kE7KG11GEkQhU7=",
"x-amz-request-id": "9F341CD3C4BA79E0",
"Date": "Wed, 30 May 2018 22:32:00 GMT",
"Content-Length": "0",
"Server": "AmazonS3",
"x-amz-request-charged": "false",
"x-amz-restore-output-path": "js-test-s3/qE8nk5M0XIj-LuZE2HXNw6empQm3znLkHlMWInRYPS-Orl2W0uj6LyYm-neTvm1-btz3wbBxfMhPykd3jkl-lvZE7w42/",
}
}
// Accepts a request to restore a Glacier object to S3.
func S3RestoreHandler(w http.ResponseWriter, r *http.Request) {
for key, value := range getRestoreHeaders() {
w.Header().Set(key, value)
}
// Must return 202 to indicate the request was accepted
w.WriteHeader(http.StatusAccepted)
}
// Rejects a request to restore a Glacier object to S3.
func S3RestoreRejectHandler(w http.ResponseWriter, r *http.Request) {
for key, value := range getRestoreHeaders() {
w.Header().Set(key, value)
}
// Must return 503 to indicate Glacier rejects the request.
w.WriteHeader(http.StatusServiceUnavailable)
}
// Handles a request to restore a Glacier object to S3,
// and replies with a 409 to say the restoration is
// already in progress.
// See https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPOSTrestore.html
func S3RestoreInProgressHandler(w http.ResponseWriter, r *http.Request) {
for key, value := range getRestoreHeaders() {
w.Header().Set(key, value)
}
// Must return 409 to indicate the request conflicts
// with one already in progress
w.Header().Set("Content-Type", "application/xml")
w.WriteHeader(http.StatusConflict)
xml := `<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>RestoreAlreadyInProgress</Code>
<Message>Object restore is already in progress.</Message>
<Resource>/mybucket/myfoto.jpg</Resource>
<RequestId>4442587FB7D0A2F9</RequestId>
</Error>`
fmt.Fprintln(w, xml)
}
// Handles a request to restore a Glacier object to S3,
// and replies with a 200 to say the restoration is
// already completed (item already restored to active tier)
func S3RestoreCompletedHandler(w http.ResponseWriter, r *http.Request) {
for key, value := range getRestoreHeaders() {
w.Header().Set(key, value)
}
// Must return 200 to indicate item has already
// been restored to S3
w.WriteHeader(http.StatusOK)
}
|
seekloud/gypsy | client/src/main/scala/com/neo/sk/gypsy/common/AppSettings.scala | <filename>client/src/main/scala/com/neo/sk/gypsy/common/AppSettings.scala
package com.neo.sk.gypsy.common
import com.typesafe.config.ConfigFactory
import org.slf4j.LoggerFactory
/**
* @author zhaoyin
* 2018/10/28 3:29 PM
*/
object AppSettings {
val log = LoggerFactory.getLogger(this.getClass)
val config = ConfigFactory.parseResources("productClient.conf").withFallback(ConfigFactory.load())
val appConfig = config.getConfig("app")
val httpInterface = appConfig.getString("http.interface")
val httpPort = appConfig.getInt("http.port")
val esheepProtocol = appConfig.getString("esheep.protocol")
val esheepHost = appConfig.getString("esheep.host")
val esheepDomain = appConfig.getString("esheep.domain")
val gameId = appConfig.getLong("esheep.gameId")
val isView = appConfig.getBoolean("isView")
var isLayer = appConfig.getBoolean("isLayer")
val botInfo = if(!isView) {
(appConfig.getString("botInfo.botId"), appConfig.getString("botInfo.botKey"))
} else("","")
val gameProtocol = appConfig.getString("server.protocol")
val gameHost = appConfig.getString("server.host")
val gameDomain = appConfig.getString("server.domain")
val botSecure = appConfig.getString("botSecure.apiToken")
val isBot = appConfig.getBoolean("isBot")
val botServerPort = appConfig.getInt("botServerPort")
val framePeriod = appConfig.getInt("framePeriod")
val isGray = appConfig.getBoolean("isGray")
val botTest = appConfig.getBoolean("botTest")
}
|
jaemin2682/BAEKJOON_ONLINE_JUDGE | 2292.cpp | #include <iostream>
using namespace std;
int main() {
int n, res, num = 1;
scanf("%d", &n);
if (n == 1) res = 0;
else {
for (int i = 1; i < n; i++) {
num = num + 6 * i;
if (num >= n) {
res = i;
break;
}
}
}
printf("%d", res + 1);
return 0;
} |
haileys/battlecars | deps/gwen/Samples/OpenGL/OpenGLSample.cpp | <reponame>haileys/battlecars<filename>deps/gwen/Samples/OpenGL/OpenGLSample.cpp<gh_stars>1-10
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "Gwen/Gwen.h"
#include "Gwen/Skins/Simple.h"
#include "Gwen/Skins/TexturedBase.h"
#include "Gwen/UnitTest/UnitTest.h"
#include "Gwen/Input/Windows.h"
#ifdef USE_DEBUG_FONT
#include "Gwen/Renderers/OpenGL_DebugFont.h"
#else
#include "Gwen/Renderers/OpenGL.h"
#endif
#include "gl/glew.h"
HWND CreateGameWindow( void )
{
WNDCLASSW wc;
ZeroMemory( &wc, sizeof( wc ) );
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = DefWindowProc;
wc.hInstance = GetModuleHandle(NULL);
wc.lpszClassName = L"GWENWindow";
wc.hCursor = LoadCursor( NULL, IDC_ARROW );
RegisterClassW( &wc );
#ifdef USE_DEBUG_FONT
HWND hWindow = CreateWindowExW( (WS_EX_APPWINDOW | WS_EX_WINDOWEDGE) , wc.lpszClassName, L"GWEN - OpenGL Sample (Using embedded debug font renderer)", (WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN) & ~(WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME), -1, -1, 1004, 650, NULL, NULL, GetModuleHandle(NULL), NULL );
#else
HWND hWindow = CreateWindowExW( (WS_EX_APPWINDOW | WS_EX_WINDOWEDGE) , wc.lpszClassName, L"GWEN - OpenGL Sample (No cross platform way to render fonts in OpenGL)", (WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN) & ~(WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME), -1, -1, 1004, 650, NULL, NULL, GetModuleHandle(NULL), NULL );
#endif
ShowWindow( hWindow, SW_SHOW );
SetForegroundWindow( hWindow );
SetFocus( hWindow );
return hWindow;
}
HWND g_pHWND = NULL;
HGLRC CreateOpenGLDeviceContext()
{
PIXELFORMATDESCRIPTOR pfd = { 0 };
pfd.nSize = sizeof( PIXELFORMATDESCRIPTOR ); // just its size
pfd.nVersion = 1; // always 1
pfd.dwFlags = PFD_SUPPORT_OPENGL | // OpenGL support - not DirectDraw
PFD_DOUBLEBUFFER | // double buffering support
PFD_DRAW_TO_WINDOW; // draw to the app window, not to a bitmap image
pfd.iPixelType = PFD_TYPE_RGBA ; // red, green, blue, alpha for each pixel
pfd.cColorBits = 24; // 24 bit == 8 bits for red, 8 for green, 8 for blue.
// This count of color bits EXCLUDES alpha.
pfd.cDepthBits = 32; // 32 bits to measure pixel depth.
int pixelFormat = ChoosePixelFormat( GetDC( g_pHWND ), &pfd );
if ( pixelFormat == 0 )
{
FatalAppExit( NULL, TEXT("ChoosePixelFormat() failed!") );
}
SetPixelFormat( GetDC( g_pHWND ), pixelFormat, &pfd );
HGLRC OpenGLContext = wglCreateContext( GetDC( g_pHWND ) );
wglMakeCurrent( GetDC( g_pHWND ), OpenGLContext );
RECT r;
if ( GetClientRect( g_pHWND, &r ) )
{
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( r.left, r.right, r.bottom, r.top, -1.0, 1.0);
glMatrixMode( GL_MODELVIEW );
glViewport(0, 0, r.right - r.left, r.bottom - r.top);
}
return OpenGLContext;
}
int main()
{
//
// Create a new window
//
g_pHWND = CreateGameWindow();
//
// Create OpenGL Device
//
HGLRC OpenGLContext = CreateOpenGLDeviceContext();
//
// Create a GWEN OpenGL Renderer
//
#ifdef USE_DEBUG_FONT
Gwen::Renderer::OpenGL * pRenderer = new Gwen::Renderer::OpenGL_DebugFont();
#else
Gwen::Renderer::OpenGL * pRenderer = new Gwen::Renderer::OpenGL();
#endif
//
// Create a GWEN skin
//
Gwen::Skin::TexturedBase skin;
skin.SetRender( pRenderer );
skin.Init("DefaultSkin.png");
//
// Create a Canvas (it's root, on which all other GWEN panels are created)
//
Gwen::Controls::Canvas* pCanvas = new Gwen::Controls::Canvas( &skin );
pCanvas->SetSize( 998, 650 - 24 );
pCanvas->SetDrawBackground( true );
pCanvas->SetBackgroundColor( Gwen::Color( 150, 170, 170, 255 ) );
//
// Create our unittest control (which is a Window with controls in it)
//
UnitTest* pUnit = new UnitTest( pCanvas );
pUnit->SetPos( 10, 10 );
//
// Create a Windows Control helper
// (Processes Windows MSG's and fires input at GWEN)
//
Gwen::Input::Windows GwenInput;
GwenInput.Initialize( pCanvas );
//
// Begin the main game loop
//
MSG msg;
while( true )
{
// Skip out if the window is closed
if ( !IsWindowVisible( g_pHWND ) )
break;
// If we have a message from windows..
if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
{
// .. give it to the input handler to process
GwenInput.ProcessMessage( msg );
// if it's QUIT then quit..
if ( msg.message == WM_QUIT )
break;
// Handle the regular window stuff..
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Main OpenGL Render Loop
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
pCanvas->RenderCanvas();
SwapBuffers( GetDC( g_pHWND ) );
}
}
// Clean up OpenGL
wglMakeCurrent( NULL, NULL );
wglDeleteContext( OpenGLContext );
} |
lzc-ios/OCR | OCRSource/include/IDCard/LFIDCardReader.h | //
// LFIDCardReader.h
// Linkface
//
// Copyright © 2017-2018 LINKFACE Corporation. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "LFCaptureReader.h"
#import "LFIDCardMaskView.h"
#import <OCR_SDK/OCR_SDK.h>
@interface LFIDCardReader : LFCaptureReader
// appID
@property(nonatomic,copy)NSString *appID;
// appSecret
@property(nonatomic,copy)NSString *appSecret;
// 拍照
@property(nonatomic,assign)NSInteger isAuto;
// 横竖卡
@property(nonatomic,assign)NSInteger isVertical;
// 是否开启身份证类型
@property(nonatomic,assign)BOOL returnType;
/**
reader init
@param licenseName 授权文件名
@param shouldFullCard 是否整卡才返回
@return LFCaptureReader 对象
*/
- (instancetype)initWithLicenseName:(NSString *)licenseName shouldFullCard:(BOOL)shouldFullCard;
- (instancetype)initWithLicensePath:(NSString *)licensePath shouldFullCard:(BOOL)shouldFullCard;
- (instancetype)initWithLicensePath:(NSString *)licensePath shouldFullCard:(BOOL)shouldFullCard modelPath:(NSString *)modelPath;
@property (nonatomic, weak) LFIDCardMaskView *maskView;
@property (nonatomic, strong) UIImage *resultImage;
/*! @brief bDebug 调试开关(控制NSLog的输出)
*/
@property (nonatomic, assign) BOOL bDebug;
- (void)moveWindowVerticalFromCenterWithDelta:(int)iDelta; // iDelta == 0 in center , < 0 move up, > 0 move down
- (void)setMode:(LFIDCardMode)mode;
- (void)setRecognizeItemOption:(LFIDCardItemOption)option;
- (void)setHintLabel:(UILabel *)label;
@end
|
openthos/oto_packages_apps_OtoPhotoManager | libs/mapsforge-0.8.0/mapsforge-core/src/org/mapsforge/core/model/Dimension.java | /*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapsforge.core.model;
import java.io.Serializable;
public class Dimension implements Serializable {
private static final long serialVersionUID = 1L;
public final int height;
public final int width;
public Dimension(int width, int height) {
if (width < 0) {
throw new IllegalArgumentException("width must not be negative: " + width);
} else if (height < 0) {
throw new IllegalArgumentException("height must not be negative: " + height);
}
this.width = width;
this.height = height;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (!(obj instanceof Dimension)) {
return false;
}
Dimension other = (Dimension) obj;
if (this.width != other.width) {
return false;
} else if (this.height != other.height) {
return false;
}
return true;
}
/**
* Gets the center point of the dimension.
*
* @return the center point
*/
public Point getCenter() {
return new Point((float) this.width / 2, (float) this.height / 2);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.width;
result = prime * result + this.height;
return result;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("width=");
stringBuilder.append(this.width);
stringBuilder.append(", height=");
stringBuilder.append(this.height);
return stringBuilder.toString();
}
}
|
E3SM-Project/iESM | models/lnd/clm/src/iac/giac/gcam/cvs/objects/util/database/source/output_helper.cpp | <gh_stars>1-10
/*
* LEGAL NOTICE
* This computer software was prepared by Battelle Memorial Institute,
* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830
* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE
* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY
* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this
* sentence must appear on any copies of this computer software.
*
* EXPORT CONTROL
* User agrees that the Software will not be shipped, transferred or
* exported into any country or used in any manner prohibited by the
* United States Export Administration Act or any other applicable
* export laws, restrictions or regulations (collectively the "Export Laws").
* Export of the Software may require some form of license or other
* authority from the U.S. Government, and failure to obtain such
* export control license may result in criminal liability under
* U.S. laws. In addition, if the Software is identified as export controlled
* items under the Export Laws, User represents and warrants that User
* is not a citizen, or otherwise located within, an embargoed nation
* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)
* and that User is not otherwise prohibited
* under the Export Laws from receiving the Software.
*
* Copyright 2011 Battelle Memorial Institute. All Rights Reserved.
* Distributed as open-source under the terms of the Educational Community
* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php
*
* For further details, see: http://www.globalchange.umd.edu/models/gcam/
*
*/
/*!
* \file output_helper.cpp
* \ingroup Objects
* \brief Contains the functions to write out single records to output file or
* table in the database. includes functions to open, create, and close
* database and tables.
* \author <NAME>
*/
#include "util/base/include/definitions.h"
#define DUPLICATE_CHECKING 0
#if(__HAVE_DB__)
#include <afxdisp.h>
#include <dbdao.h>
#include <comdef.h>
#endif
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <map>
#include <ctime>
#include "containers/include/scenario.h"
#include "containers/include/world.h"
#include "util/base/include/model_time.h"
#include "util/base/include/configuration.h"
#include "util/base/include/util.h"
#if( DUPLICATE_CHECKING )
#include "util/base/include/util.h"
#include <algorithm>
#endif
using namespace std;
extern time_t gGlobalTime;
extern ofstream outFile;
extern Scenario* scenario;
#if( DUPLICATE_CHECKING )
vector<string> gHashes;
#endif
#if(__HAVE_DB__)
// define global DB engine and database
CdbDBEngine dben;
CdbDatabase db;
CdbTableDef DBoutTD; // table definitions for creating tables in the database
CdbField tfield; // temporary field for creating fields in tables
CdbRecordset DBoutrst; // record set for writing results
const char *DBout = "DBout"; // name of the table for outputs compatible with dataviewer
#endif
/*! Output single records to file.
*
* Names of categories, subcategories, and variables are written
* as strings in the argument. Values are also passed as arguments.
*
*/
void fileoutput3( string var1name,string var2name,string var3name,
string var4name,string var5name,string uname,vector<double> dout) {
outFile <<var1name<<","<<var2name<<","<<var3name<<","
<<var4name<<","<<var5name<<","<<uname<<",";
for (int i=0;i< static_cast<int>( dout.size() );i++) {
outFile << dout[i]<<",";
}
outFile << endl;
}
/*! Output single records MiniCAM style to the database.
*
* Names of categories, subcategories, variables, and units are written
* as strings passed in by the argument. Values are also passed as arguments.
* \warning Variable id field has been taken out of the dbout database table
and this function no longer compensate for this field. Ensure that the
revised dbout table is used.
*/
void dboutput4(string var1name,string var2name,string var3name,string var4name,
string uname,vector<double> dout)
{
#if( DUPLICATE_CHECKING )
// Create a hash of the values.
const string newHash = var1name + "," + var2name + "," + var3name + "," + var4name;
// See if its already been added to the map.
if( find( gHashes.begin(), gHashes.end(), newHash ) != gHashes.end() ){
// Print an error since we found a duplicate.
cout << "A value has already been added for: " << var1name << ", " << var2name
<< ", " << var3name << ", " << var4name << endl;
}
// Otherwise add it.
else {
gHashes.push_back( newHash );
}
#endif // DUPLICATE_CHECKING
#if(!__HAVE_DB__)
fileoutput3( var1name,var2name,var3name,var4name,"",uname,dout);
#else
// MS Access can not handle blank strings. This is a programming error
// and would ideally be handled with an assert. However, running in debug
// mode until the database writes out can take a very long time and so
// these errors would not be found often enough.
if ( var1name.empty() || var2name.empty() || var3name.empty() || var4name.empty() ||
uname.empty() ) {
cout << "Variable name is blank! Check data and output routines." << endl;
cout << "V1: " << var1name << " V2: " << var2name << " V3: " << var3name
<< " V4: " << var4name << " unit: " << uname << endl;
return;
}
const map<string,int> regionMap = scenario->getWorld()->getOutputRegionMap();
// only output regions already defined in regionMap
map<string,int>::const_iterator iter = regionMap.find( var1name );
if( iter != regionMap.end()) {
int i=0,j;
// COleVariant does not take int, must be short or long
// now write to the database
// MUST Update before adding another
try {
DBoutrst.AddNew(); // now the current record is this empty new one
const long runID = util::createMinicamRunID( gGlobalTime );
DBoutrst.SetField(0L, COleVariant(runID,VT_I4)); // run id
DBoutrst.SetField(1L, COleVariant(short(iter->second))); // region id
DBoutrst.SetField(2L, COleVariant(var2name.c_str(), VT_BSTRT)); // category
DBoutrst.SetField(3L, COleVariant(var3name.c_str(), VT_BSTRT)); // subcategory
DBoutrst.SetField(4L, COleVariant(var4name.c_str(), VT_BSTRT)); // variable
DBoutrst.SetField(5L, COleVariant(uname.c_str(), VT_BSTRT)); // units
// get scenario name and output to dbout
string scenarioName = scenario->getName();
DBoutrst.SetField(6L, COleVariant(scenarioName.c_str(), VT_BSTRT));
for (i=0;i< static_cast<int>( dout.size() );i++) {
j = 7+i;
DBoutrst.SetField(j, COleVariant(dout[i]));
}
DBoutrst.Update(); // save and write the record
}
catch( _com_error e ){
printf("Error:*************************************************\n");
printf("Code = %08lx\n", e.Error());
printf("Message = %s\n", e.ErrorMessage());
printf("Source = %s\n", (LPCSTR) e.Source());
printf("Description = %s\n", (LPCSTR) e.Description());
}
}
// if region not found in regionMap, do nothing
#endif
}
#if(__HAVE_DB__)
//! Open connection to the database
void openDB(void) {
Configuration* conf = Configuration::getInstance();
string dbFile = conf->getFile( "dbFileName" );
// Open a global Jet database in exclusive, read/write mode.
try {
db = dben.OpenDatabase( dbFile.c_str());
}
catch(...) {
cout<<"Error opening database: "<< dbFile << endl;
}
}
//! Close connection to the database
void closeDB() {
db.Close();
}
/*! \brief Create and open the main database output table.
*
* Record set for dbout table is opened here for writing to by output_helper.cpp
* The code to delete and create new dbout table is commented out.
* Results are continually appended to the dbout table. This function no longer
* clears out and recreates the dbout table.
* \warning The output database has been greatly simplified and fewer tables exists in
the database. Results are continually appended to the dbout table, which is now the
only table of results. RunLabel and RegionInfo talbles exists in the database and
are recreated in createMCvarid().
*/
void createDBout() {
// open DBout table as a record set (DBoutrst) for writing
DBoutrst = db.OpenRecordset(DBout,dbOpenDynaset);
// **** End DBout table *****
}
//! Create run label and region info tables that are necessary for the dataviewer.xls.
void createMCvarid() {
string sqltemp; // temporary string for sql
// *** Delete and Create DbRunLabels table ***
const char *dbtrun = "DBRunLabels"; // database table names
// first delete existing table
try { db.TableDefs.Delete(dbtrun); }
catch (...) {cout<<"\nError deleting "<<dbtrun<<" table\n";}
// Reusing RunLabelTD and tfield to add fields to the table
CdbField tfield; // temporary field for creating fields in tables
CdbTableDef RunLabelTD = db.CreateTableDef(dbtrun); // temporary RunLabel table definition
// create run id field
tfield = RunLabelTD.CreateField("RunID",dbLong);
RunLabelTD.Fields.Append(tfield);
// create run label field
tfield = RunLabelTD.CreateField("RunLabel",dbText);
RunLabelTD.Fields.Append(tfield);
// create run comments field
tfield = RunLabelTD.CreateField("RunComments",dbText);
RunLabelTD.Fields.Append(tfield);
// create the region info table
try {db.TableDefs.Append(RunLabelTD);}
catch(...) { cout<<"\nError appending "<<dbtrun<<" table to database\n";}
// insert into the new run labels table the list of runs
sqltemp = "INSERT INTO ";
sqltemp += dbtrun;
sqltemp += " SELECT DISTINCT RunID,RunLabel";
sqltemp = sqltemp + " FROM " + DBout;
try {
db.Execute(sqltemp.c_str()); }
catch(...) {
cout<<"\nError executing sql: \""<<sqltemp<<"\"\n"; }
// *** end DbRunLabels table ***
// *** Delete and Create RegionInfo table ***
const char *dbtregion = "RegionInfo"; // database table names
// first delete existing table
try { db.TableDefs.Delete(dbtregion); }
catch (...) {cout<<"\nError deleting "<<dbtregion<<" table\n";}
// create new region info table definition
CdbTableDef RegionInfoTD = db.CreateTableDef(dbtregion);
// create region name field
tfield = RegionInfoTD.CreateField("RegionLabel",dbText);
RegionInfoTD.Fields.Append(tfield);
// create region id field
tfield = RegionInfoTD.CreateField("RegionID",dbLong);
RegionInfoTD.Fields.Append(tfield);
// create the region info table
try {db.TableDefs.Append(RegionInfoTD);}
catch(...) { cout<<"\nError appending "<<dbtregion<<" table to database\n";}
// create a record set for the region info table
CdbRecordset RegionInfoRst = db.OpenRecordset(dbtregion,dbOpenDynaset);
typedef map<string,int>:: const_iterator CI;
string regstr; // temporary string for region names
map<string,int> regionMap = scenario->getWorld()->getOutputRegionMap();
for (CI rmap=regionMap.begin(); rmap!=regionMap.end(); ++rmap) {
RegionInfoRst.AddNew(); // now the current record is this empty new one
regstr = rmap->first; // region name
RegionInfoRst.SetField(_T("RegionLabel"), COleVariant(regstr.c_str(), VT_BSTRT));
RegionInfoRst.SetField(_T("RegionID"), COleVariant(long(rmap->second), VT_I4));
RegionInfoRst.Update(); // save and write the record
// add a Global region that includes all regions to sum all regional outputs
if(rmap->second != 0) {
RegionInfoRst.AddNew(); // now the current record is this empty new one
RegionInfoRst.SetField(_T("RegionLabel"), COleVariant("zGlobal", VT_BSTRT));
RegionInfoRst.SetField(_T("RegionID"), COleVariant(long(rmap->second), VT_I4));
RegionInfoRst.Update(); // save and write the record
}
}
RegionInfoRst.Close();
// *** end RegionInfo table ***
}
// if not working with database
#else
void closeDB(void) {
// do nothing if not utilizing database
}
void openDB(void) {
// do nothing if not utilizing database
}
void createDBout(void) {
// do nothing if not utilizing database
}
void createMCvarid(void) {
// do nothing if not utilizing database
}
#endif
|
Slyvia2000/selfex | 3_js/day03/08_elseif.js | //判断一个政治面貌
//var type='党员';
/*switch (type)
{
case '少先队员':
console.log('此人为少先队员');
break;
case '团员':
console.log('此人为团员');
break;
case '党员':
console.log('此人为党员');
break;
case '群众':
console.log('此人为群众');
break;
default:
console.log('错误');
}
/*
var type='少先队员';
if(type=='党员'){
console.log('此人为党员');
}else if(type=='团员'){
console.log('此人为团员');
}else if(type=='群众'){
console.log('此人为群众');
}else{
console.log('非法的政治面貌');
}
*/
//练习:根据订单的状态码来打印对应的中文;声明的变量保存状态码
//1-等待付款 2-等待发货 3-运输中 4-已签收 5-已取消 其它-错误的状态码
var sta=5;
/*if (sta==1){
console.log('等待付款');
}else if(sta==2){
console.log('等待发货');
}else if(sta==3){
console.log('运输中');
}else if(sta==4){
console.log('已签收');
}else if(sta==5){
console.log('已取消');
}else{
console.log('错误的状态码');
}
*/
/*switch (sta)
{
case 1:
console.log('等待付款');
break;
case 2:
console.log('等待发货');
break;
case 3:
console.log('运输中');
break;
case 4:
console.log('已签收');
break;
case 5:
console.log('已取消');
break;
default:
console.log('错误的状态码');
}
*/
/*var status=4;
if(status==1){
console.log('等待付款');
}else if(status==2){
console.log('等待发货');
}else if(status==3){
console.log('运输中');
}else if(status==4){
console.log('已签收');
}else if(status==5){
console.log('已取消');
}else{
console.log('非法的状态码');
}
//练习:根据一个人的成绩进行评判
//声明变量保存成绩
//优秀 90~
//良好 80~90以下
//中等 70~80以下
//及格 60~70以下
//不及格 60以下
*/
var val=40;
if (val>=90){
console.log('优秀');
}else if(val>=80){
console.log('良好');
}else if(val>=70){
console.log('中等');
}
else if(val>=60){
console.log('及格');
}
else {
console.log('不及格');
}
/*
var score=43;
if(score>=90){
console.log('优秀');
}else if(score>=80){
//分数不大于等于90 score<90
console.log('良好');
}else if(score>=70){ //score<80
console.log('中等');
}else if(score>=60){ // score<70
console.log('及格');
}else{ //score<60
console.log('不及格');
}
//练习:银行根据客户的存款分类
//普通客户 10以下
//优质客户 10~50以下
//金牌客户 50~100以下
//钻石客户 100~
//声明变量保存存款的数值
var money=80;
if(money<10){
console.log('普通客户');
}else if(money<50){ //money>=10
console.log('优质客户');
}else if(money<100){ //money>=50
console.log('金牌客户');
}else{ //money>=100
console.log('钻石客户');
}
*/
|
ITTECH10/dentist_app_client | src/components/EMPLOYEES/EditEmployeeDialog.js | import * as React from 'react';
import { useEmployeeContext } from './../../context/EmployeeContext'
import { useApp } from './../../context/AppContext'
import axios from 'axios';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import Box from '@mui/material/Box';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import CircularProgress from '@mui/material/CircularProgress';
import editFill from '@iconify/icons-eva/edit-fill';
import ListItemIcon from '@mui/material/ListItemIcon'
import ListItemText from '@mui/material/ListItemText'
import MenuItem from '@mui/material/MenuItem'
/////////////////////////////////////////
import { Icon } from '@iconify/react';
import { hasPermission, actions } from './../../utils/DataProviders/ROLES/permissions'
const genders = [
{
id: 1,
text: "Muško",
value: 'male'
},
{
id: 2,
text: "Žensko",
value: 'female'
},
]
const workRoles = [
{
id: 1,
text: "Direktor",
value: 'director'
},
{
id: 2,
text: "Zamjenik",
value: 'deputy'
},
{
id: 3,
text: "Asistent",
value: 'assistant'
},
]
const initialFields = {
firstName: '',
lastName: '',
birthDate: '',
email: '',
role: workRoles[0].value,
gender: genders[0].value,
phone: '',
employeeImage: ''
}
export default function EditEmployeeDialog({ employeeId }) {
const [open, setOpen] = React.useState(false)
const [btnLoading, setBtnLoading] = React.useState(false)
const { setEmployees, employees, logedInEmployee } = useEmployeeContext()
const { setGeneralAlertOptions } = useApp()
const [fields, setFields] = React.useState(initialFields)
const allowedEditing = hasPermission(logedInEmployee, actions.EDIT_EMPLOYEE)
const formData = new FormData()
formData.append('firstName', fields.firstName)
formData.append('lastName', fields.lastName)
formData.append('birthDate', fields.birthDate)
formData.append('email', fields.email)
formData.append('role', fields.role)
formData.append('gender', fields.gender)
formData.append('phone', fields.phone)
formData.append('photo', fields.employeeImage)
// STARTING WITH SERVER APPROACH // NICE TO CONSIDER CLIENT APPROACH // OR OPPOSITE
// ALREADY CONSIDERING TO TAKE THIS APPROACH
const handleClickOpen = () => {
setOpen(true);
axios(`/employees/${employeeId}`)
.then(res => {
if (res.status === 200) {
setFields(res.data.employee)
}
}).catch(err => {
console.log(err)
})
};
const handleClose = () => {
setOpen(false);
setFields(initialFields)
};
const handleChange = (e) => {
setFields({
...fields,
[e.target.name]: e.target.value
})
}
const handleSubmit = (e) => {
e.preventDefault();
setBtnLoading(true)
axios({
method: 'PUT',
data: formData,
headers: { "Content-Type": "multipart/form-data" },
url: `/employees/${employeeId}`
}).then(res => {
if (res.status === 200) {
const updatedEmployees = [...employees]
const updatingEmployeeIndex = updatedEmployees.findIndex(employee => employee._id === employeeId)
const foundEmployee = updatedEmployees[updatingEmployeeIndex]
// CHECK IF THE EMPLOYEE BEEING EDITED IS THE CURRENTLY LOGED IN EMPLOYEE
if (logedInEmployee._id === res.data.updatedEmployee._id) {
logedInEmployee.employeeImage = res.data.updatedEmployee.employeeImage
}
foundEmployee.firstName = res.data.updatedEmployee.firstName
foundEmployee.lastName = res.data.updatedEmployee.lastName
foundEmployee.gender = res.data.updatedEmployee.gender
foundEmployee.role = res.data.updatedEmployee.role
foundEmployee.birthDate = res.data.updatedEmployee.birthDate
foundEmployee.employeeImage = res.data.updatedEmployee.employeeImage
foundEmployee.phone = res.data.updatedEmployee.phone
foundEmployee.email = res.data.updatedEmployee.email
setEmployees(updatedEmployees)
setBtnLoading(false)
setOpen(false)
setGeneralAlertOptions({
open: true,
message: 'Uspješno ste izmjenili informacije o zaposleniku!',
severity: 'success',
hideAfter: 5000
})
}
}).catch(err => {
console.log(err)
})
}
const openUploadHandler = () => {
const input = document.getElementById('upload-employee-photo')
input.click()
}
const handleImageChange = (e) => {
const photo = e.target.files[0]
setFields({
...fields,
employeeImage: photo
})
}
return (
<>
<MenuItem sx={{ color: 'text.secondary' }} onClick={handleClickOpen}>
<ListItemIcon>
<Icon icon={editFill} width={24} height={24} />
</ListItemIcon>
<ListItemText primary="Izmjeni" primaryTypographyProps={{ variant: 'body2' }} />
</MenuItem>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Izmjenite informacije o zaposleniku</DialogTitle>
<DialogContent>
<DialogContentText>
Da biste izmjenili informacije povezane sa ovim zaposlenikom,
molimo vas ispunite formu ispod.
</DialogContentText>
<Box
component="form"
onSubmit={handleSubmit}
>
<input
id="upload-employee-photo"
name="employeeImage"
type="file"
onChange={handleImageChange}
hidden
/>
<Button
variant="contained"
sx={{ mt: 2 }}
onClick={openUploadHandler}
>
Nova slika
</Button>
<TextField
autoFocus
margin="dense"
id="firstName"
name="firstName"
placeholder={fields.firstName}
label="Ime"
fullWidth
variant="standard"
onChange={handleChange}
/>
<TextField
margin="dense"
id="lastName"
name="lastName"
placeholder={fields.lastName}
label="Prezime"
fullWidth
variant="standard"
onChange={handleChange}
/>
<TextField
id="birthDate"
name="birthDate"
label="Datum rođenja"
type="date"
sx={{ mt: 2 }}
fullWidth
variant="standard"
onChange={handleChange}
InputLabelProps={{
shrink: true,
}}
/>
<TextField
name="gender"
id="standard-select-gender"
select
label="Spol"
fullWidth
variant="standard"
onChange={handleChange}
sx={{ mt: 2 }}
SelectProps={{
native: true,
}}
>
{genders.map((option) => (
<option key={option.id} value={option.value}>
{option.text}
</option>
))}
</TextField>
<TextField
name="role"
id="standard-select-workRole"
select
label="<NAME>"
fullWidth
disabled={!allowedEditing}
variant="standard"
onChange={handleChange}
sx={{ mt: 2 }}
SelectProps={{
native: true,
}}
>
{workRoles.map((option) => (
<option key={option.id} value={option.value}>
{option.text}
</option>
))}
</TextField>
<TextField
margin="dense"
id="phone"
name="phone"
label="Telefon"
placeholder={fields.phone}
fullWidth
variant="standard"
onChange={handleChange}
/>
<TextField
margin="dense"
id="email"
name="email"
placeholder={fields.email}
label="Email"
fullWidth
variant="standard"
onChange={handleChange}
/>
<DialogActions>
<Button variant="contained" color="error" onClick={handleClose}>Nazad</Button>
<Button
variant="contained"
color="primary"
type="submit"
>
{btnLoading ? <CircularProgress style={{ color: '#fff' }} size={24} /> : 'Gotovo'}
</Button>
</DialogActions>
</Box>
</DialogContent>
</Dialog>
</>
);
}
|
dbrcina/OPJJ-FER-2018-19 | Homeworks/hw08-0036506587/src/main/java/hr/fer/zemris/java/hw06/shell/commands/HelpShellCommand.java | <filename>Homeworks/hw08-0036506587/src/main/java/hr/fer/zemris/java/hw06/shell/commands/HelpShellCommand.java
package hr.fer.zemris.java.hw06.shell.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import hr.fer.zemris.java.hw06.shell.Environment;
import hr.fer.zemris.java.hw06.shell.ShellCommand;
import hr.fer.zemris.java.hw06.shell.ShellStatus;
import static hr.fer.zemris.java.hw06.shell.ShellUtil.*;
/**
* Representation of help command in shell. It inherits from
* {@link ShellCommand}.
*
* @author dbrcina
*
*/
public class HelpShellCommand implements ShellCommand {
/**
* Constant representing command's name.
*/
private static final String HELP_NAME = "help";
@Override
public ShellStatus executeCommand(Environment env, String arguments) {
SortedMap<String, ShellCommand> commands = env.commands();
// if there are no arguments
if (arguments.isEmpty()) {
env.writeln("For more information on a specific command, type help command-name");
commands.entrySet().forEach(entry -> env.writeln(entry.getKey()));
}
// there is an argument
else {
ShellCommand command = commands.get(arguments);
if (command == null) {
return status(env, "'" + arguments + "' is not recognized as a command!\n");
} else {
env.writeln(command.getCommandName());
List<String> description = command.getCommandDescription();
description.forEach(s -> env.writeln(s));
}
}
return status(env, "");
}
@Override
public String getCommandName() {
return HELP_NAME;
}
@Override
public List<String> getCommandDescription() {
List<String> description = new ArrayList<>();
description.add("Command 'help' takes zero or one argument.");
description.add("If zero arguments are provided, all supported commands are listed.");
description
.add("If one argument is provided, name of given command is printed along with command's description.");
return description;
}
}
|
CareerSocius/resumebuilder | src/components/builder/templates/blocks/Languages/LanguagesD.js | import React, { memo, useContext } from 'react';
import PageContext from '../../../../../contexts/PageContext';
import { safetyCheck } from '../../../../../utils';
import { LeftHeading } from '../../containers/HeadingModifiers';
const LanguageItem = (x) => (
<div key={x.id} className="flex flex-col mb-3">
<h6 className="font-semibold">{x.name}</h6>
<span className="text-xs">{x.fluency}</span>
</div>
);
const LanguagesD = () => {
const { data, heading: Heading } = useContext(PageContext);
const { fontSize, lrMargins } = data.metadata.margins;
return safetyCheck(data.languages) ? (
<div>
<LeftHeading Heading={Heading} fontSize={fontSize} margin={lrMargins}>
{data.languages.heading}
</LeftHeading>
<div className="m-4">{data.languages.items.map(LanguageItem)}</div>
</div>
) : null;
};
export default memo(LanguagesD);
|
mohayonao/CoffeeCollider | src/cc/server/buffer.js | define(function(require, exports, module) {
"use strict";
var cc = require("./cc");
var Buffer = (function() {
function Buffer(world, bufnum, frames, channels) {
this.world = world;
this.bufnum = bufnum;
this.frames = frames;
this.channels = channels;
this.sampleRate = cc.server.sampleRate;
this.samples = new Float32Array(frames * channels);
}
Buffer.prototype.bind = function(sampleRate, channels, frames, samples) {
this.sampleRate = sampleRate;
this.channels = channels;
this.frames = frames;
this.samples = samples;
};
Buffer.prototype.zero = function() {
var i, samples = this.samples;
for (i = samples.length; i--; ) {
samples[i] = 0;
}
};
Buffer.prototype.fill = function(params) {
var n = (params.length / 3)|0;
var samples = this.samples;
var startAt, length, value;
var i, j, k = 0;
for (i = 0; i < n; i++) {
startAt = params[k++];
length = params[k++];
value = params[k++];
for (j = 0; j < length; ++j) {
if (startAt + j >= samples.length) {
break;
}
samples[startAt + j] = value;
}
}
};
Buffer.prototype.set = function(params) {
var samples = this.samples;
var samples_length = samples.length;
var index, value, values;
var i, imax = params.length;
var j, jmax;
for (i = 0; i < imax; i += 2) {
index = params[i];
if (typeof index !== "number" || index < 0 || samples_length <= index) {
continue;
}
index |= 0;
value = params[i+1];
if (typeof value === "number") {
samples[index] = value || 0; // remove NaN
} else if (Array.isArray(value)) {
values = value;
for (j = 0, jmax = values.length; j < jmax; ++j) {
if (samples_length <= index + j) {
break;
}
value = values[j];
if (typeof value === "number") {
samples[index + j] = value || 0; // remove NaN
}
}
}
}
};
Buffer.prototype.get = function(index, callbackId) {
var samples = this.samples;
var msg = [ "/b_get", callbackId, samples[index] || 0 ];
cc.server.sendToLang(msg); // TODO: userId
};
Buffer.prototype.getn = function(index, count, callbackId) {
var samples = this.samples;
var msg = new Array(count + 2);
msg[0] = "/b_getn";
msg[1] = callbackId;
for (var i = 0; i < count; ++i) {
msg[i + 2] = samples[i + index] || 0;
}
cc.server.sendToLang(msg); // TODO: userId
};
Buffer.prototype.gen = function(cmd, flags, params) {
var func = gen_func[cmd];
if (func) {
func(this, flags, params);
}
};
return Buffer;
})();
var gen_func = {};
gen_func.copy = function(buf, flags, params) {
var bufnum = params[0];
var dstStartAt = params[1];
var srcStartAt = params[2];
var numSamples = params[3];
var target = buf.world.buffers[bufnum];
if (target) {
var samples;
if (numSamples > 0) {
samples = target.samples.slice(srcStartAt, srcStartAt + numSamples);
} else {
samples = target.samples.slice(srcStartAt);
}
buf.samples.set(samples, dstStartAt);
}
};
gen_func.normalize = function(buf, flags, params) {
var samples = buf.samples;
var wavetable = flags & 2;
if (wavetable) {
normalize_wsamples(samples.length, samples, params[0]);
} else {
normalize_samples(samples.length, samples, params[0]);
}
};
gen_func.sine1 = function(buf, flags, params) {
var samples = buf.samples;
var normalize = flags & 1;
var wavetable = flags & 2;
var clear = flags & 4;
var len = samples.length;
var i, imax;
if (clear) {
for (i = samples.length; i--; ) {
samples[i] = 0;
}
}
if (wavetable) {
for (i = 0, imax = params.length; i < imax; ++i) {
add_wpartial(len, samples, i+1, params[i], 0);
}
} else {
for (i = 0, imax = params.length; i < imax; ++i) {
add_partial(len, samples, i+1, params[i], 0);
}
}
if (normalize) {
if (wavetable) {
normalize_wsamples(samples.length, samples, 1);
} else {
normalize_samples(samples.length, samples, 1);
}
}
};
gen_func.sine2 = function(buf, flags, params) {
var samples = buf.samples;
var normalize = flags & 1;
var wavetable = flags & 2;
var clear = flags & 4;
var len = samples.length;
var i, imax;
if (clear) {
for (i = samples.length; i--; ) {
samples[i] = 0;
}
}
if (wavetable) {
for (i = 0, imax = params.length; i < imax; i += 2) {
add_wpartial(len, samples, params[i], params[i+1], 0);
}
} else {
for (i = 0, imax = params.length; i < imax; i += 2) {
add_partial(len, samples, params[i], params[i+1], 0);
}
}
if (normalize) {
if (wavetable) {
normalize_wsamples(samples.length, samples, 1);
} else {
normalize_samples(samples.length, samples, 1);
}
}
};
gen_func.sine3 = function(buf, flags, params) {
var samples = buf.samples;
var normalize = flags & 1;
var wavetable = flags & 2;
var clear = flags & 4;
var len = samples.length;
var i, imax;
if (clear) {
for (i = samples.length; i--; ) {
samples[i] = 0;
}
}
if (wavetable) {
for (i = 0, imax = params.length; i < imax; i += 3) {
add_wpartial(len, samples, params[i], params[i+1], params[i+2]);
}
} else {
for (i = 0, imax = params.length; i < imax; i += 3) {
add_partial(len, samples, params[i], params[i+1], params[i+2]);
}
}
if (normalize) {
if (wavetable) {
normalize_wsamples(samples.length, samples, 1);
} else {
normalize_samples(samples.length, samples, 1);
}
}
};
gen_func.cheby = function(buf, flags, params) {
var samples = buf.samples;
var normalize = flags & 1;
var wavetable = flags & 2;
var clear = flags & 4;
var len = samples.length;
var i, imax;
if (clear) {
for (i = samples.length; i--; ) {
samples[i] = 0;
}
}
if (wavetable) {
for (i = 0, imax = params.length; i < imax; ++i) {
add_wchebyshev(len, samples, i+1, params[i]);
}
} else {
for (i = 0, imax = params.length; i < imax; ++i) {
add_chebyshev(len, samples, i+1, params[i]);
}
}
if (normalize) {
if (wavetable) {
normalize_wsamples(samples.length, samples, 1);
} else {
normalize_samples(samples.length, samples, 1);
}
}
};
var add_wpartial = function(size, data, partial, amp, phase) {
if (amp === 0) {
return;
}
var size2 = size >> 1;
var w = (partial * 2.0 * Math.PI) / size2;
var cur = amp * Math.sin(phase);
var next;
phase += w;
for (var i = 0; i < size; i += 2) {
next = amp * Math.sin(phase);
data[i] += 2 * cur - next;
data[i+1] += next - cur;
cur = next;
phase += w;
}
};
var add_partial = function(size, data, partial, amp, phase) {
if (amp === 0) {
return;
}
var w = (partial * 2.0 * Math.PI) / size;
for (var i = 0; i < size; ++i) {
data[i] += amp * Math.sin(phase);
phase += w;
}
};
var add_wchebyshev = function(size, data, partial, amp) {
if (amp === 0) {
return;
}
var size2 = size >> 1;
var w = 2 / size2;
var phase = -1;
var offset = -amp * Math.cos(partial * Math.PI * 0.5);
var cur = amp * Math.cos(partial * Math.acos(phase)) - offset;
var next;
phase += w;
for (var i = 0; i < size; i += 2) {
next = amp * Math.cos(partial * Math.acos(phase)) - offset;
data[i] += 2 * cur - next;
data[i+1] += next - cur;
cur = next;
phase += w;
}
};
var add_chebyshev = function(size, data, partial, amp) {
if (amp === 0) {
return;
}
var w = 2 / size;
var phase = -1;
var offset = -amp * Math.cos(partial * Math.PI * 0.5);
for (var i = 0; i < size; ++i) {
data[i] += amp * Math.cos(partial * Math.acos(phase)) - offset;
phase += w;
}
};
var normalize_samples = function(size, data, peak) {
var maxamp, absamp, ampfac, i;
for (i = maxamp = 0; i < size; ++i) {
absamp = Math.abs(data[i]);
if (absamp > maxamp) { maxamp = absamp; }
}
if (maxamp !== 0 && maxamp !== peak) {
ampfac = peak / maxamp;
for (i = 0; i < size; ++i) {
data[i] *= ampfac;
}
}
};
var normalize_wsamples = function(size, data, peak) {
var maxamp, absamp, ampfac, i;
for (i = maxamp = 0; i < size; i += 2) {
absamp = Math.abs(data[i] + data[i+1]);
if (absamp > maxamp) { maxamp = absamp; }
}
if (maxamp !== 0 && maxamp !== peak) {
ampfac = peak / maxamp;
for (i = 0; i < size; ++i) {
data[i] *= ampfac;
}
}
};
cc.createServerBuffer = function(world, bufnum, frames, channels) {
return new Buffer(world, bufnum, frames, channels);
};
module.exports = {
Buffer: Buffer,
add_partial : add_partial,
add_wpartial : add_wpartial,
add_chebyshev : add_chebyshev,
add_wchebyshev: add_wchebyshev,
normalize_samples : normalize_samples,
normalize_wsamples: normalize_wsamples
};
});
|
bot-motion/gap_sdk | tools/nntool/graph/manipulations/adjust_base.py | # Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from copy import Error
import logging
LOG = logging.getLogger("nntool." + __name__)
class AdjusterException(Error):
pass
class AdjusterBase():
HANDLES = []
def __init__(self, opts=None) -> None:
self.opts = opts
@staticmethod
def trans_names(names, trans):
return [names[trans_elem] for trans_elem in trans]
def trans_trans(self, cur, trans):
return self.eliminate_noop([cur[trans_elem] for trans_elem in trans])
@staticmethod
def eliminate_noop(trans):
if trans is None or all([trans[idx] < trans[idx + 1] for idx in range(len(trans) - 1)]):
return None
return trans
def apply_trans(self, node, trans, key, index=None):
if getattr(node, key) is None:
setattr(node, key, [None] * len(node.in_dims))
if index is None:
setattr(node, key, [trans.copy() if cur is None else self.trans_trans(
cur, trans) for cur in getattr(node, key)])
else:
getattr(node, key)[index] = trans.copy() if getattr(node, key)[index] is None else self.trans_trans(
getattr(node, key)[index], trans)
def apply_input_trans(self, node, trans: list, index=None):
self.apply_trans(node, trans, 'transpose_in', index=index)
def apply_output_trans(self, node, trans: list, index=None):
self.apply_trans(node, trans, 'transpose_out', index=index)
@staticmethod
def move_axis_to_zero_trans(axis: int, shape: list):
return [axis] + [idx for idx in range(len(shape)) if idx != axis]
@staticmethod
def verify_chw(node, names: list):
if len(names) != 3:
LOG.error("Conv %s: input has strange length %s", node.name, names)
raise AdjusterException()
if not all(elem in names for elem in ['c', 'h', 'w']):
LOG.error("Conv %s: input has strange elements %s", node.name, names)
raise AdjusterException()
@staticmethod
def get_trans(names: list, order: list):
return [names.index(elem) for elem in order]
@staticmethod
def maybe_transpose(cur, desired_order, tensor, reshape=None):
if cur.order != desired_order:
tensor = tensor.transpose(cur.transpose_to_order(desired_order))
if reshape is not None:
tensor = tensor.reshape(reshape)
return tensor
@staticmethod
def invert(trans):
return [trans.index(idx) for idx in range(len(trans))]
@staticmethod
def handles(*args):
return AdjusterBase.property_register("HANDLES", args)
@classmethod
def get_all_handlers(cls, opts):
return {params_cls: handler_cls(opts) for handler_cls in cls.__subclasses__()
for params_cls in handler_cls.HANDLES}
@staticmethod
def property_register(name, value):
def deco(cls):
setattr(cls, name, value)
return cls
return deco
handles = AdjusterBase.handles
|
cisco-ie/cisco-proto | codegen/go/xr/62x/cisco_ios_xr_ipv4_bgp_oper/bgp/instances/instance/instance_active/default_vrf/afs/af/global_af_process_info/bgp_global_process_info_af_bag.pb.go | /*
Copyright 2019 Cisco Systems
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.
*/
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: bgp_global_process_info_af_bag.proto
package cisco_ios_xr_ipv4_bgp_oper_bgp_instances_instance_instance_active_default_vrf_afs_af_global_af_process_info
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
type BgpGlobalProcessInfoAfBag_KEYS struct {
InstanceName string `protobuf:"bytes,1,opt,name=instance_name,json=instanceName,proto3" json:"instance_name,omitempty"`
AfName string `protobuf:"bytes,2,opt,name=af_name,json=afName,proto3" json:"af_name,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpGlobalProcessInfoAfBag_KEYS) Reset() { *m = BgpGlobalProcessInfoAfBag_KEYS{} }
func (m *BgpGlobalProcessInfoAfBag_KEYS) String() string { return proto.CompactTextString(m) }
func (*BgpGlobalProcessInfoAfBag_KEYS) ProtoMessage() {}
func (*BgpGlobalProcessInfoAfBag_KEYS) Descriptor() ([]byte, []int) {
return fileDescriptor_1e79225ab6f81729, []int{0}
}
func (m *BgpGlobalProcessInfoAfBag_KEYS) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpGlobalProcessInfoAfBag_KEYS.Unmarshal(m, b)
}
func (m *BgpGlobalProcessInfoAfBag_KEYS) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpGlobalProcessInfoAfBag_KEYS.Marshal(b, m, deterministic)
}
func (m *BgpGlobalProcessInfoAfBag_KEYS) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpGlobalProcessInfoAfBag_KEYS.Merge(m, src)
}
func (m *BgpGlobalProcessInfoAfBag_KEYS) XXX_Size() int {
return xxx_messageInfo_BgpGlobalProcessInfoAfBag_KEYS.Size(m)
}
func (m *BgpGlobalProcessInfoAfBag_KEYS) XXX_DiscardUnknown() {
xxx_messageInfo_BgpGlobalProcessInfoAfBag_KEYS.DiscardUnknown(m)
}
var xxx_messageInfo_BgpGlobalProcessInfoAfBag_KEYS proto.InternalMessageInfo
func (m *BgpGlobalProcessInfoAfBag_KEYS) GetInstanceName() string {
if m != nil {
return m.InstanceName
}
return ""
}
func (m *BgpGlobalProcessInfoAfBag_KEYS) GetAfName() string {
if m != nil {
return m.AfName
}
return ""
}
type BgpTimespec struct {
Seconds uint32 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"`
Nanoseconds uint32 `protobuf:"varint,2,opt,name=nanoseconds,proto3" json:"nanoseconds,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpTimespec) Reset() { *m = BgpTimespec{} }
func (m *BgpTimespec) String() string { return proto.CompactTextString(m) }
func (*BgpTimespec) ProtoMessage() {}
func (*BgpTimespec) Descriptor() ([]byte, []int) {
return fileDescriptor_1e79225ab6f81729, []int{1}
}
func (m *BgpTimespec) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpTimespec.Unmarshal(m, b)
}
func (m *BgpTimespec) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpTimespec.Marshal(b, m, deterministic)
}
func (m *BgpTimespec) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpTimespec.Merge(m, src)
}
func (m *BgpTimespec) XXX_Size() int {
return xxx_messageInfo_BgpTimespec.Size(m)
}
func (m *BgpTimespec) XXX_DiscardUnknown() {
xxx_messageInfo_BgpTimespec.DiscardUnknown(m)
}
var xxx_messageInfo_BgpTimespec proto.InternalMessageInfo
func (m *BgpTimespec) GetSeconds() uint32 {
if m != nil {
return m.Seconds
}
return 0
}
func (m *BgpTimespec) GetNanoseconds() uint32 {
if m != nil {
return m.Nanoseconds
}
return 0
}
type BgpRibInstallTimeInfo struct {
UpdateTime *BgpTimespec `protobuf:"bytes,1,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty"`
InstallTime *BgpTimespec `protobuf:"bytes,2,opt,name=install_time,json=installTime,proto3" json:"install_time,omitempty"`
InstalledCount uint32 `protobuf:"varint,3,opt,name=installed_count,json=installedCount,proto3" json:"installed_count,omitempty"`
ModifiedCount uint32 `protobuf:"varint,4,opt,name=modified_count,json=modifiedCount,proto3" json:"modified_count,omitempty"`
WithdrawnCount uint32 `protobuf:"varint,5,opt,name=withdrawn_count,json=withdrawnCount,proto3" json:"withdrawn_count,omitempty"`
StartVersion uint32 `protobuf:"varint,6,opt,name=start_version,json=startVersion,proto3" json:"start_version,omitempty"`
TargetVersion uint32 `protobuf:"varint,7,opt,name=target_version,json=targetVersion,proto3" json:"target_version,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpRibInstallTimeInfo) Reset() { *m = BgpRibInstallTimeInfo{} }
func (m *BgpRibInstallTimeInfo) String() string { return proto.CompactTextString(m) }
func (*BgpRibInstallTimeInfo) ProtoMessage() {}
func (*BgpRibInstallTimeInfo) Descriptor() ([]byte, []int) {
return fileDescriptor_1e79225ab6f81729, []int{2}
}
func (m *BgpRibInstallTimeInfo) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpRibInstallTimeInfo.Unmarshal(m, b)
}
func (m *BgpRibInstallTimeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpRibInstallTimeInfo.Marshal(b, m, deterministic)
}
func (m *BgpRibInstallTimeInfo) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpRibInstallTimeInfo.Merge(m, src)
}
func (m *BgpRibInstallTimeInfo) XXX_Size() int {
return xxx_messageInfo_BgpRibInstallTimeInfo.Size(m)
}
func (m *BgpRibInstallTimeInfo) XXX_DiscardUnknown() {
xxx_messageInfo_BgpRibInstallTimeInfo.DiscardUnknown(m)
}
var xxx_messageInfo_BgpRibInstallTimeInfo proto.InternalMessageInfo
func (m *BgpRibInstallTimeInfo) GetUpdateTime() *BgpTimespec {
if m != nil {
return m.UpdateTime
}
return nil
}
func (m *BgpRibInstallTimeInfo) GetInstallTime() *BgpTimespec {
if m != nil {
return m.InstallTime
}
return nil
}
func (m *BgpRibInstallTimeInfo) GetInstalledCount() uint32 {
if m != nil {
return m.InstalledCount
}
return 0
}
func (m *BgpRibInstallTimeInfo) GetModifiedCount() uint32 {
if m != nil {
return m.ModifiedCount
}
return 0
}
func (m *BgpRibInstallTimeInfo) GetWithdrawnCount() uint32 {
if m != nil {
return m.WithdrawnCount
}
return 0
}
func (m *BgpRibInstallTimeInfo) GetStartVersion() uint32 {
if m != nil {
return m.StartVersion
}
return 0
}
func (m *BgpRibInstallTimeInfo) GetTargetVersion() uint32 {
if m != nil {
return m.TargetVersion
}
return 0
}
type BgpGlobalProcessInfoAfGbl_ struct {
ScannerPeriod uint32 `protobuf:"varint,1,opt,name=scanner_period,json=scannerPeriod,proto3" json:"scanner_period,omitempty"`
NhTunnelVersion uint32 `protobuf:"varint,2,opt,name=nh_tunnel_version,json=nhTunnelVersion,proto3" json:"nh_tunnel_version,omitempty"`
SyncgrpVersion []uint32 `protobuf:"varint,3,rep,packed,name=syncgrp_version,json=syncgrpVersion,proto3" json:"syncgrp_version,omitempty"`
ScanPrefixes uint32 `protobuf:"varint,4,opt,name=scan_prefixes,json=scanPrefixes,proto3" json:"scan_prefixes,omitempty"`
ScanSegmentPrefixes uint32 `protobuf:"varint,5,opt,name=scan_segment_prefixes,json=scanSegmentPrefixes,proto3" json:"scan_segment_prefixes,omitempty"`
ScanSegments uint32 `protobuf:"varint,6,opt,name=scan_segments,json=scanSegments,proto3" json:"scan_segments,omitempty"`
InterAsInstallEnabled bool `protobuf:"varint,7,opt,name=inter_as_install_enabled,json=interAsInstallEnabled,proto3" json:"inter_as_install_enabled,omitempty"`
GlobalMcastEnabled bool `protobuf:"varint,8,opt,name=global_mcast_enabled,json=globalMcastEnabled,proto3" json:"global_mcast_enabled,omitempty"`
SegmentedMcastEnabled bool `protobuf:"varint,9,opt,name=segmented_mcast_enabled,json=segmentedMcastEnabled,proto3" json:"segmented_mcast_enabled,omitempty"`
GblafrpkiDisable bool `protobuf:"varint,10,opt,name=gblafrpki_disable,json=gblafrpkiDisable,proto3" json:"gblafrpki_disable,omitempty"`
GblafrpkiUseValidity bool `protobuf:"varint,11,opt,name=gblafrpki_use_validity,json=gblafrpkiUseValidity,proto3" json:"gblafrpki_use_validity,omitempty"`
GblafrpkiAllowInvalid bool `protobuf:"varint,12,opt,name=gblafrpki_allow_invalid,json=gblafrpkiAllowInvalid,proto3" json:"gblafrpki_allow_invalid,omitempty"`
GblafrpkiSignalIbgp bool `protobuf:"varint,13,opt,name=gblafrpki_signal_ibgp,json=gblafrpkiSignalIbgp,proto3" json:"gblafrpki_signal_ibgp,omitempty"`
UpdateWaitInstallEnabled bool `protobuf:"varint,14,opt,name=update_wait_install_enabled,json=updateWaitInstallEnabled,proto3" json:"update_wait_install_enabled,omitempty"`
RibAckRequests uint32 `protobuf:"varint,15,opt,name=rib_ack_requests,json=ribAckRequests,proto3" json:"rib_ack_requests,omitempty"`
RibAcksReceived uint32 `protobuf:"varint,16,opt,name=rib_acks_received,json=ribAcksReceived,proto3" json:"rib_acks_received,omitempty"`
RibSlowAcks uint32 `protobuf:"varint,17,opt,name=rib_slow_acks,json=ribSlowAcks,proto3" json:"rib_slow_acks,omitempty"`
RibInstall *BgpRibInstallTimeInfo `protobuf:"bytes,18,opt,name=rib_install,json=ribInstall,proto3" json:"rib_install,omitempty"`
IsPermNetCfg bool `protobuf:"varint,19,opt,name=is_perm_net_cfg,json=isPermNetCfg,proto3" json:"is_perm_net_cfg,omitempty"`
PermNetDelCount uint32 `protobuf:"varint,20,opt,name=perm_net_del_count,json=permNetDelCount,proto3" json:"perm_net_del_count,omitempty"`
PermNetStaleDelCount uint32 `protobuf:"varint,21,opt,name=perm_net_stale_del_count,json=permNetStaleDelCount,proto3" json:"perm_net_stale_del_count,omitempty"`
PermNetStaleMarkCount uint32 `protobuf:"varint,22,opt,name=perm_net_stale_mark_count,json=permNetStaleMarkCount,proto3" json:"perm_net_stale_mark_count,omitempty"`
PermNetInsertCount uint32 `protobuf:"varint,23,opt,name=perm_net_insert_count,json=permNetInsertCount,proto3" json:"perm_net_insert_count,omitempty"`
PermNetExistingCount uint32 `protobuf:"varint,24,opt,name=perm_net_existing_count,json=permNetExistingCount,proto3" json:"perm_net_existing_count,omitempty"`
PermNetRplQueryCount uint32 `protobuf:"varint,25,opt,name=perm_net_rpl_query_count,json=permNetRplQueryCount,proto3" json:"perm_net_rpl_query_count,omitempty"`
PermNetRplProcessCount uint32 `protobuf:"varint,26,opt,name=perm_net_rpl_process_count,json=permNetRplProcessCount,proto3" json:"perm_net_rpl_process_count,omitempty"`
PermNbrCount uint32 `protobuf:"varint,27,opt,name=perm_nbr_count,json=permNbrCount,proto3" json:"perm_nbr_count,omitempty"`
RibPermPelemNotFoundCount uint32 `protobuf:"varint,28,opt,name=rib_perm_pelem_not_found_count,json=ribPermPelemNotFoundCount,proto3" json:"rib_perm_pelem_not_found_count,omitempty"`
RibPermPathNotFoundCount uint32 `protobuf:"varint,29,opt,name=rib_perm_path_not_found_count,json=ribPermPathNotFoundCount,proto3" json:"rib_perm_path_not_found_count,omitempty"`
RibPermPelemFoundCount uint32 `protobuf:"varint,30,opt,name=rib_perm_pelem_found_count,json=ribPermPelemFoundCount,proto3" json:"rib_perm_pelem_found_count,omitempty"`
RibRegPathFoundCount uint32 `protobuf:"varint,31,opt,name=rib_reg_path_found_count,json=ribRegPathFoundCount,proto3" json:"rib_reg_path_found_count,omitempty"`
RibPermPathFoundCount uint32 `protobuf:"varint,32,opt,name=rib_perm_path_found_count,json=ribPermPathFoundCount,proto3" json:"rib_perm_path_found_count,omitempty"`
PermPelemFreeCount uint32 `protobuf:"varint,33,opt,name=perm_pelem_free_count,json=permPelemFreeCount,proto3" json:"perm_pelem_free_count,omitempty"`
PermPathRefreshCount uint32 `protobuf:"varint,34,opt,name=perm_path_refresh_count,json=permPathRefreshCount,proto3" json:"perm_path_refresh_count,omitempty"`
PermPelemBumpCount uint32 `protobuf:"varint,35,opt,name=perm_pelem_bump_count,json=permPelemBumpCount,proto3" json:"perm_pelem_bump_count,omitempty"`
PermPelemAllBumpCount uint32 `protobuf:"varint,36,opt,name=perm_pelem_all_bump_count,json=permPelemAllBumpCount,proto3" json:"perm_pelem_all_bump_count,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpGlobalProcessInfoAfGbl_) Reset() { *m = BgpGlobalProcessInfoAfGbl_{} }
func (m *BgpGlobalProcessInfoAfGbl_) String() string { return proto.CompactTextString(m) }
func (*BgpGlobalProcessInfoAfGbl_) ProtoMessage() {}
func (*BgpGlobalProcessInfoAfGbl_) Descriptor() ([]byte, []int) {
return fileDescriptor_1e79225ab6f81729, []int{3}
}
func (m *BgpGlobalProcessInfoAfGbl_) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpGlobalProcessInfoAfGbl_.Unmarshal(m, b)
}
func (m *BgpGlobalProcessInfoAfGbl_) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpGlobalProcessInfoAfGbl_.Marshal(b, m, deterministic)
}
func (m *BgpGlobalProcessInfoAfGbl_) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpGlobalProcessInfoAfGbl_.Merge(m, src)
}
func (m *BgpGlobalProcessInfoAfGbl_) XXX_Size() int {
return xxx_messageInfo_BgpGlobalProcessInfoAfGbl_.Size(m)
}
func (m *BgpGlobalProcessInfoAfGbl_) XXX_DiscardUnknown() {
xxx_messageInfo_BgpGlobalProcessInfoAfGbl_.DiscardUnknown(m)
}
var xxx_messageInfo_BgpGlobalProcessInfoAfGbl_ proto.InternalMessageInfo
func (m *BgpGlobalProcessInfoAfGbl_) GetScannerPeriod() uint32 {
if m != nil {
return m.ScannerPeriod
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetNhTunnelVersion() uint32 {
if m != nil {
return m.NhTunnelVersion
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetSyncgrpVersion() []uint32 {
if m != nil {
return m.SyncgrpVersion
}
return nil
}
func (m *BgpGlobalProcessInfoAfGbl_) GetScanPrefixes() uint32 {
if m != nil {
return m.ScanPrefixes
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetScanSegmentPrefixes() uint32 {
if m != nil {
return m.ScanSegmentPrefixes
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetScanSegments() uint32 {
if m != nil {
return m.ScanSegments
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetInterAsInstallEnabled() bool {
if m != nil {
return m.InterAsInstallEnabled
}
return false
}
func (m *BgpGlobalProcessInfoAfGbl_) GetGlobalMcastEnabled() bool {
if m != nil {
return m.GlobalMcastEnabled
}
return false
}
func (m *BgpGlobalProcessInfoAfGbl_) GetSegmentedMcastEnabled() bool {
if m != nil {
return m.SegmentedMcastEnabled
}
return false
}
func (m *BgpGlobalProcessInfoAfGbl_) GetGblafrpkiDisable() bool {
if m != nil {
return m.GblafrpkiDisable
}
return false
}
func (m *BgpGlobalProcessInfoAfGbl_) GetGblafrpkiUseValidity() bool {
if m != nil {
return m.GblafrpkiUseValidity
}
return false
}
func (m *BgpGlobalProcessInfoAfGbl_) GetGblafrpkiAllowInvalid() bool {
if m != nil {
return m.GblafrpkiAllowInvalid
}
return false
}
func (m *BgpGlobalProcessInfoAfGbl_) GetGblafrpkiSignalIbgp() bool {
if m != nil {
return m.GblafrpkiSignalIbgp
}
return false
}
func (m *BgpGlobalProcessInfoAfGbl_) GetUpdateWaitInstallEnabled() bool {
if m != nil {
return m.UpdateWaitInstallEnabled
}
return false
}
func (m *BgpGlobalProcessInfoAfGbl_) GetRibAckRequests() uint32 {
if m != nil {
return m.RibAckRequests
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetRibAcksReceived() uint32 {
if m != nil {
return m.RibAcksReceived
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetRibSlowAcks() uint32 {
if m != nil {
return m.RibSlowAcks
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetRibInstall() *BgpRibInstallTimeInfo {
if m != nil {
return m.RibInstall
}
return nil
}
func (m *BgpGlobalProcessInfoAfGbl_) GetIsPermNetCfg() bool {
if m != nil {
return m.IsPermNetCfg
}
return false
}
func (m *BgpGlobalProcessInfoAfGbl_) GetPermNetDelCount() uint32 {
if m != nil {
return m.PermNetDelCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetPermNetStaleDelCount() uint32 {
if m != nil {
return m.PermNetStaleDelCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetPermNetStaleMarkCount() uint32 {
if m != nil {
return m.PermNetStaleMarkCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetPermNetInsertCount() uint32 {
if m != nil {
return m.PermNetInsertCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetPermNetExistingCount() uint32 {
if m != nil {
return m.PermNetExistingCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetPermNetRplQueryCount() uint32 {
if m != nil {
return m.PermNetRplQueryCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetPermNetRplProcessCount() uint32 {
if m != nil {
return m.PermNetRplProcessCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetPermNbrCount() uint32 {
if m != nil {
return m.PermNbrCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetRibPermPelemNotFoundCount() uint32 {
if m != nil {
return m.RibPermPelemNotFoundCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetRibPermPathNotFoundCount() uint32 {
if m != nil {
return m.RibPermPathNotFoundCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetRibPermPelemFoundCount() uint32 {
if m != nil {
return m.RibPermPelemFoundCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetRibRegPathFoundCount() uint32 {
if m != nil {
return m.RibRegPathFoundCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetRibPermPathFoundCount() uint32 {
if m != nil {
return m.RibPermPathFoundCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetPermPelemFreeCount() uint32 {
if m != nil {
return m.PermPelemFreeCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetPermPathRefreshCount() uint32 {
if m != nil {
return m.PermPathRefreshCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetPermPelemBumpCount() uint32 {
if m != nil {
return m.PermPelemBumpCount
}
return 0
}
func (m *BgpGlobalProcessInfoAfGbl_) GetPermPelemAllBumpCount() uint32 {
if m != nil {
return m.PermPelemAllBumpCount
}
return 0
}
type BgpGlobalProcessInfoAfVrf_ struct {
TableIsActive bool `protobuf:"varint,1,opt,name=table_is_active,json=tableIsActive,proto3" json:"table_is_active,omitempty"`
TableId uint32 `protobuf:"varint,2,opt,name=table_id,json=tableId,proto3" json:"table_id,omitempty"`
TableVersion uint32 `protobuf:"varint,3,opt,name=table_version,json=tableVersion,proto3" json:"table_version,omitempty"`
RdVersion uint32 `protobuf:"varint,4,opt,name=rd_version,json=rdVersion,proto3" json:"rd_version,omitempty"`
RibVersion uint32 `protobuf:"varint,5,opt,name=rib_version,json=ribVersion,proto3" json:"rib_version,omitempty"`
NsrConvVersion uint32 `protobuf:"varint,6,opt,name=nsr_conv_version,json=nsrConvVersion,proto3" json:"nsr_conv_version,omitempty"`
NsrIsConv bool `protobuf:"varint,7,opt,name=nsr_is_conv,json=nsrIsConv,proto3" json:"nsr_is_conv,omitempty"`
ClientReflectionEnabled bool `protobuf:"varint,8,opt,name=client_reflection_enabled,json=clientReflectionEnabled,proto3" json:"client_reflection_enabled,omitempty"`
DampeningEnabled bool `protobuf:"varint,9,opt,name=dampening_enabled,json=dampeningEnabled,proto3" json:"dampening_enabled,omitempty"`
EbgpDistance uint32 `protobuf:"varint,10,opt,name=ebgp_distance,json=ebgpDistance,proto3" json:"ebgp_distance,omitempty"`
IbgpDistance uint32 `protobuf:"varint,11,opt,name=ibgp_distance,json=ibgpDistance,proto3" json:"ibgp_distance,omitempty"`
AggregatesDistance uint32 `protobuf:"varint,12,opt,name=aggregates_distance,json=aggregatesDistance,proto3" json:"aggregates_distance,omitempty"`
DynamicMedEnabled bool `protobuf:"varint,13,opt,name=dynamic_med_enabled,json=dynamicMedEnabled,proto3" json:"dynamic_med_enabled,omitempty"`
DynamicMedInterval uint32 `protobuf:"varint,14,opt,name=dynamic_med_interval,json=dynamicMedInterval,proto3" json:"dynamic_med_interval,omitempty"`
DynamicMedTimerRunning bool `protobuf:"varint,15,opt,name=dynamic_med_timer_running,json=dynamicMedTimerRunning,proto3" json:"dynamic_med_timer_running,omitempty"`
DynamicMedTimerValue uint32 `protobuf:"varint,16,opt,name=dynamic_med_timer_value,json=dynamicMedTimerValue,proto3" json:"dynamic_med_timer_value,omitempty"`
DynamicMedPeriodicTimerRunning bool `protobuf:"varint,17,opt,name=dynamic_med_periodic_timer_running,json=dynamicMedPeriodicTimerRunning,proto3" json:"dynamic_med_periodic_timer_running,omitempty"`
DynamicMedPeriodicTimerValue uint32 `protobuf:"varint,18,opt,name=dynamic_med_periodic_timer_value,json=dynamicMedPeriodicTimerValue,proto3" json:"dynamic_med_periodic_timer_value,omitempty"`
RibHasConverged bool `protobuf:"varint,19,opt,name=rib_has_converged,json=ribHasConverged,proto3" json:"rib_has_converged,omitempty"`
RibConvergenceVersion uint32 `protobuf:"varint,20,opt,name=rib_convergence_version,json=ribConvergenceVersion,proto3" json:"rib_convergence_version,omitempty"`
IsRibTableFull bool `protobuf:"varint,21,opt,name=is_rib_table_full,json=isRibTableFull,proto3" json:"is_rib_table_full,omitempty"`
RibTableFullVersion uint32 `protobuf:"varint,22,opt,name=rib_table_full_version,json=ribTableFullVersion,proto3" json:"rib_table_full_version,omitempty"`
NexthopResolutionMinimumPrefixLengthConfigured bool `protobuf:"varint,23,opt,name=nexthop_resolution_minimum_prefix_length_configured,json=nexthopResolutionMinimumPrefixLengthConfigured,proto3" json:"nexthop_resolution_minimum_prefix_length_configured,omitempty"`
NexthopResolutionMinimumPrefixLength uint32 `protobuf:"varint,24,opt,name=nexthop_resolution_minimum_prefix_length,json=nexthopResolutionMinimumPrefixLength,proto3" json:"nexthop_resolution_minimum_prefix_length,omitempty"`
SelectiveEbgpMultipathEnabled bool `protobuf:"varint,25,opt,name=selective_ebgp_multipath_enabled,json=selectiveEbgpMultipathEnabled,proto3" json:"selective_ebgp_multipath_enabled,omitempty"`
SelectiveIbgpMultipathEnabled bool `protobuf:"varint,26,opt,name=selective_ibgp_multipath_enabled,json=selectiveIbgpMultipathEnabled,proto3" json:"selective_ibgp_multipath_enabled,omitempty"`
SelectiveEibgpMultipathEnabled bool `protobuf:"varint,27,opt,name=selective_eibgp_multipath_enabled,json=selectiveEibgpMultipathEnabled,proto3" json:"selective_eibgp_multipath_enabled,omitempty"`
RibAckedTableVersion uint32 `protobuf:"varint,28,opt,name=rib_acked_table_version,json=ribAckedTableVersion,proto3" json:"rib_acked_table_version,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpGlobalProcessInfoAfVrf_) Reset() { *m = BgpGlobalProcessInfoAfVrf_{} }
func (m *BgpGlobalProcessInfoAfVrf_) String() string { return proto.CompactTextString(m) }
func (*BgpGlobalProcessInfoAfVrf_) ProtoMessage() {}
func (*BgpGlobalProcessInfoAfVrf_) Descriptor() ([]byte, []int) {
return fileDescriptor_1e79225ab6f81729, []int{4}
}
func (m *BgpGlobalProcessInfoAfVrf_) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpGlobalProcessInfoAfVrf_.Unmarshal(m, b)
}
func (m *BgpGlobalProcessInfoAfVrf_) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpGlobalProcessInfoAfVrf_.Marshal(b, m, deterministic)
}
func (m *BgpGlobalProcessInfoAfVrf_) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpGlobalProcessInfoAfVrf_.Merge(m, src)
}
func (m *BgpGlobalProcessInfoAfVrf_) XXX_Size() int {
return xxx_messageInfo_BgpGlobalProcessInfoAfVrf_.Size(m)
}
func (m *BgpGlobalProcessInfoAfVrf_) XXX_DiscardUnknown() {
xxx_messageInfo_BgpGlobalProcessInfoAfVrf_.DiscardUnknown(m)
}
var xxx_messageInfo_BgpGlobalProcessInfoAfVrf_ proto.InternalMessageInfo
func (m *BgpGlobalProcessInfoAfVrf_) GetTableIsActive() bool {
if m != nil {
return m.TableIsActive
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetTableId() uint32 {
if m != nil {
return m.TableId
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetTableVersion() uint32 {
if m != nil {
return m.TableVersion
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetRdVersion() uint32 {
if m != nil {
return m.RdVersion
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetRibVersion() uint32 {
if m != nil {
return m.RibVersion
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetNsrConvVersion() uint32 {
if m != nil {
return m.NsrConvVersion
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetNsrIsConv() bool {
if m != nil {
return m.NsrIsConv
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetClientReflectionEnabled() bool {
if m != nil {
return m.ClientReflectionEnabled
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetDampeningEnabled() bool {
if m != nil {
return m.DampeningEnabled
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetEbgpDistance() uint32 {
if m != nil {
return m.EbgpDistance
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetIbgpDistance() uint32 {
if m != nil {
return m.IbgpDistance
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetAggregatesDistance() uint32 {
if m != nil {
return m.AggregatesDistance
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetDynamicMedEnabled() bool {
if m != nil {
return m.DynamicMedEnabled
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetDynamicMedInterval() uint32 {
if m != nil {
return m.DynamicMedInterval
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetDynamicMedTimerRunning() bool {
if m != nil {
return m.DynamicMedTimerRunning
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetDynamicMedTimerValue() uint32 {
if m != nil {
return m.DynamicMedTimerValue
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetDynamicMedPeriodicTimerRunning() bool {
if m != nil {
return m.DynamicMedPeriodicTimerRunning
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetDynamicMedPeriodicTimerValue() uint32 {
if m != nil {
return m.DynamicMedPeriodicTimerValue
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetRibHasConverged() bool {
if m != nil {
return m.RibHasConverged
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetRibConvergenceVersion() uint32 {
if m != nil {
return m.RibConvergenceVersion
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetIsRibTableFull() bool {
if m != nil {
return m.IsRibTableFull
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetRibTableFullVersion() uint32 {
if m != nil {
return m.RibTableFullVersion
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetNexthopResolutionMinimumPrefixLengthConfigured() bool {
if m != nil {
return m.NexthopResolutionMinimumPrefixLengthConfigured
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetNexthopResolutionMinimumPrefixLength() uint32 {
if m != nil {
return m.NexthopResolutionMinimumPrefixLength
}
return 0
}
func (m *BgpGlobalProcessInfoAfVrf_) GetSelectiveEbgpMultipathEnabled() bool {
if m != nil {
return m.SelectiveEbgpMultipathEnabled
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetSelectiveIbgpMultipathEnabled() bool {
if m != nil {
return m.SelectiveIbgpMultipathEnabled
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetSelectiveEibgpMultipathEnabled() bool {
if m != nil {
return m.SelectiveEibgpMultipathEnabled
}
return false
}
func (m *BgpGlobalProcessInfoAfVrf_) GetRibAckedTableVersion() uint32 {
if m != nil {
return m.RibAckedTableVersion
}
return 0
}
type BgpGlobalProcessInfoAfBag struct {
VrfName string `protobuf:"bytes,50,opt,name=vrf_name,json=vrfName,proto3" json:"vrf_name,omitempty"`
AfName string `protobuf:"bytes,51,opt,name=af_name,json=afName,proto3" json:"af_name,omitempty"`
IsNsrEnabled bool `protobuf:"varint,52,opt,name=is_nsr_enabled,json=isNsrEnabled,proto3" json:"is_nsr_enabled,omitempty"`
Global *BgpGlobalProcessInfoAfGbl_ `protobuf:"bytes,53,opt,name=global,proto3" json:"global,omitempty"`
Vrf *BgpGlobalProcessInfoAfVrf_ `protobuf:"bytes,54,opt,name=vrf,proto3" json:"vrf,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *BgpGlobalProcessInfoAfBag) Reset() { *m = BgpGlobalProcessInfoAfBag{} }
func (m *BgpGlobalProcessInfoAfBag) String() string { return proto.CompactTextString(m) }
func (*BgpGlobalProcessInfoAfBag) ProtoMessage() {}
func (*BgpGlobalProcessInfoAfBag) Descriptor() ([]byte, []int) {
return fileDescriptor_1e79225ab6f81729, []int{5}
}
func (m *BgpGlobalProcessInfoAfBag) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_BgpGlobalProcessInfoAfBag.Unmarshal(m, b)
}
func (m *BgpGlobalProcessInfoAfBag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_BgpGlobalProcessInfoAfBag.Marshal(b, m, deterministic)
}
func (m *BgpGlobalProcessInfoAfBag) XXX_Merge(src proto.Message) {
xxx_messageInfo_BgpGlobalProcessInfoAfBag.Merge(m, src)
}
func (m *BgpGlobalProcessInfoAfBag) XXX_Size() int {
return xxx_messageInfo_BgpGlobalProcessInfoAfBag.Size(m)
}
func (m *BgpGlobalProcessInfoAfBag) XXX_DiscardUnknown() {
xxx_messageInfo_BgpGlobalProcessInfoAfBag.DiscardUnknown(m)
}
var xxx_messageInfo_BgpGlobalProcessInfoAfBag proto.InternalMessageInfo
func (m *BgpGlobalProcessInfoAfBag) GetVrfName() string {
if m != nil {
return m.VrfName
}
return ""
}
func (m *BgpGlobalProcessInfoAfBag) GetAfName() string {
if m != nil {
return m.AfName
}
return ""
}
func (m *BgpGlobalProcessInfoAfBag) GetIsNsrEnabled() bool {
if m != nil {
return m.IsNsrEnabled
}
return false
}
func (m *BgpGlobalProcessInfoAfBag) GetGlobal() *BgpGlobalProcessInfoAfGbl_ {
if m != nil {
return m.Global
}
return nil
}
func (m *BgpGlobalProcessInfoAfBag) GetVrf() *BgpGlobalProcessInfoAfVrf_ {
if m != nil {
return m.Vrf
}
return nil
}
func init() {
proto.RegisterType((*BgpGlobalProcessInfoAfBag_KEYS)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_active.default_vrf.afs.af.global_af_process_info.bgp_global_process_info_af_bag_KEYS")
proto.RegisterType((*BgpTimespec)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_active.default_vrf.afs.af.global_af_process_info.bgp_timespec")
proto.RegisterType((*BgpRibInstallTimeInfo)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_active.default_vrf.afs.af.global_af_process_info.bgp_rib_install_time_info")
proto.RegisterType((*BgpGlobalProcessInfoAfGbl_)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_active.default_vrf.afs.af.global_af_process_info.bgp_global_process_info_af_gbl_")
proto.RegisterType((*BgpGlobalProcessInfoAfVrf_)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_active.default_vrf.afs.af.global_af_process_info.bgp_global_process_info_af_vrf_")
proto.RegisterType((*BgpGlobalProcessInfoAfBag)(nil), "cisco_ios_xr_ipv4_bgp_oper.bgp.instances.instance.instance_active.default_vrf.afs.af.global_af_process_info.bgp_global_process_info_af_bag")
}
func init() {
proto.RegisterFile("bgp_global_process_info_af_bag.proto", fileDescriptor_1e79225ab6f81729)
}
var fileDescriptor_1e79225ab6f81729 = []byte{
// 1738 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x58, 0xdb, 0x6e, 0xdc, 0xc8,
0x11, 0x85, 0x56, 0x1b, 0x4b, 0xee, 0x99, 0xd1, 0x85, 0xba, 0x71, 0x7c, 0x91, 0xb5, 0x23, 0x6f,
0xec, 0x64, 0x81, 0x49, 0xe2, 0x5b, 0x36, 0x06, 0x82, 0x40, 0x91, 0xed, 0x64, 0x36, 0x91, 0xa1,
0x50, 0x8e, 0x83, 0x3c, 0x35, 0x9a, 0x64, 0x91, 0x6a, 0x0c, 0xd9, 0xe4, 0x76, 0x93, 0x23, 0xeb,
0x07, 0xf2, 0x94, 0x2f, 0x08, 0x16, 0xc8, 0x53, 0x80, 0x7c, 0xc8, 0x7e, 0x56, 0x1e, 0x82, 0xae,
0x6e, 0x36, 0x39, 0x23, 0xad, 0xe0, 0x27, 0x27, 0x6f, 0x52, 0x9d, 0x73, 0xaa, 0x8a, 0xcd, 0xea,
0xaa, 0x1a, 0x92, 0x87, 0x61, 0x5a, 0xd2, 0x34, 0x2b, 0x42, 0x96, 0xd1, 0x52, 0x16, 0x11, 0x28,
0x45, 0xb9, 0x48, 0x0a, 0xca, 0x12, 0x1a, 0xb2, 0x74, 0x5c, 0xca, 0xa2, 0x2a, 0xbc, 0x69, 0xc4,
0x55, 0x54, 0x50, 0x5e, 0x28, 0xfa, 0x41, 0x52, 0x5e, 0xce, 0x9e, 0x51, 0xad, 0x2b, 0x4a, 0x90,
0xe3, 0x30, 0x2d, 0xc7, 0x5c, 0xa8, 0x8a, 0x89, 0x08, 0x94, 0xfb, 0xcb, 0xfd, 0x41, 0x59, 0x54,
0xf1, 0x19, 0x8c, 0x63, 0x48, 0x58, 0x9d, 0x55, 0x74, 0x26, 0x93, 0x31, 0x4b, 0xd4, 0x98, 0x25,
0x63, 0x1b, 0x96, 0x25, 0x73, 0x91, 0x47, 0x11, 0x39, 0xbc, 0x39, 0x29, 0xfa, 0x87, 0xd7, 0x7f,
0x3d, 0xf3, 0x0e, 0xc9, 0xc0, 0xc5, 0x10, 0x2c, 0x07, 0x7f, 0xe9, 0x60, 0xe9, 0xf1, 0xed, 0xa0,
0xdf, 0x18, 0xdf, 0xb2, 0x1c, 0xbc, 0x3d, 0xb2, 0xc2, 0x12, 0x03, 0x7f, 0x86, 0xf0, 0x2d, 0x96,
0x68, 0x60, 0xf4, 0x0d, 0xe9, 0xeb, 0x20, 0x15, 0xcf, 0x41, 0x95, 0x10, 0x79, 0x3e, 0x59, 0x51,
0x10, 0x15, 0x22, 0x56, 0xe8, 0x67, 0x10, 0x34, 0xff, 0x7a, 0x07, 0xa4, 0x27, 0x98, 0x28, 0x1a,
0xf4, 0x33, 0x44, 0xbb, 0xa6, 0xd1, 0x77, 0x9f, 0x93, 0xa1, 0x76, 0x26, 0x79, 0x48, 0x31, 0x7a,
0x96, 0xa1, 0x63, 0xcc, 0xd9, 0xfb, 0xc7, 0x12, 0xe9, 0xd5, 0x65, 0xcc, 0x2a, 0x40, 0x23, 0xba,
0xef, 0x3d, 0xb9, 0x1c, 0x7f, 0xc2, 0x23, 0x1d, 0x77, 0x1f, 0x35, 0x20, 0x26, 0x9b, 0x77, 0x3c,
0x07, 0xef, 0xbb, 0x25, 0xd2, 0xef, 0xa6, 0x8c, 0x8f, 0xf7, 0x3f, 0xcd, 0xae, 0x67, 0xd3, 0xc1,
0xf4, 0x1e, 0x91, 0x75, 0xfb, 0x2f, 0xc4, 0x34, 0x2a, 0x6a, 0x51, 0xf9, 0xcb, 0x78, 0xfe, 0x6b,
0xce, 0x7c, 0xac, 0xad, 0xde, 0x97, 0x64, 0x2d, 0x2f, 0x62, 0x9e, 0x70, 0xc7, 0xfb, 0x1c, 0x79,
0x83, 0xc6, 0x6a, 0x68, 0x8f, 0xc8, 0xfa, 0x05, 0xaf, 0xce, 0x63, 0xc9, 0x2e, 0x84, 0xe5, 0xfd,
0xc8, 0xf8, 0x73, 0x66, 0x43, 0x3c, 0x24, 0x03, 0x55, 0x31, 0x59, 0xd1, 0x19, 0x48, 0xc5, 0x0b,
0xe1, 0xdf, 0x42, 0x5a, 0x1f, 0x8d, 0xef, 0x8d, 0x4d, 0x07, 0xad, 0x98, 0x4c, 0xa1, 0x65, 0xad,
0x98, 0xa0, 0xc6, 0x6a, 0x69, 0xa3, 0xef, 0xd7, 0xc9, 0x83, 0x1b, 0x0a, 0x3a, 0x0d, 0x33, 0xaa,
0x5d, 0xa9, 0x88, 0x09, 0x01, 0x92, 0x96, 0x20, 0x79, 0x11, 0xdb, 0x2a, 0x1c, 0x58, 0xeb, 0x29,
0x1a, 0xbd, 0x9f, 0x92, 0x4d, 0x71, 0x4e, 0xab, 0x5a, 0x08, 0xc8, 0x5c, 0x50, 0x53, 0x91, 0xeb,
0xe2, 0xfc, 0x1d, 0xda, 0x9b, 0xec, 0x1e, 0x91, 0x75, 0x75, 0x29, 0xa2, 0x54, 0x96, 0x8e, 0xb9,
0x7c, 0xb0, 0xac, 0x9f, 0xd5, 0x9a, 0x1b, 0xa2, 0x7e, 0xd6, 0x88, 0x09, 0x5a, 0x4a, 0x48, 0xf8,
0x07, 0x50, 0xf6, 0xe8, 0xfa, 0xda, 0x78, 0x6a, 0x6d, 0xde, 0x13, 0xb2, 0x83, 0x24, 0x05, 0x69,
0x0e, 0xa2, 0x6a, 0xc9, 0xe6, 0xfc, 0xb6, 0x34, 0x78, 0x66, 0x30, 0xa7, 0x69, 0x1c, 0x5b, 0x8d,
0x72, 0x87, 0xd8, 0x72, 0x95, 0xf7, 0x4b, 0xe2, 0x73, 0x51, 0x81, 0xa4, 0x4c, 0xb9, 0xcb, 0x03,
0x82, 0x85, 0x19, 0xc4, 0x78, 0x9c, 0xab, 0xc1, 0x0e, 0xe2, 0x47, 0x6a, 0x62, 0xd0, 0xd7, 0x06,
0xf4, 0x7e, 0x4e, 0xb6, 0xed, 0x89, 0xe6, 0x11, 0x53, 0x95, 0x13, 0xad, 0xa2, 0xc8, 0x33, 0xd8,
0x89, 0x86, 0x1a, 0xc5, 0x0b, 0xb2, 0x67, 0x53, 0x81, 0x78, 0x41, 0x74, 0xdb, 0x44, 0x72, 0xf0,
0x9c, 0xee, 0x2b, 0xb2, 0x99, 0x86, 0x19, 0x4b, 0x64, 0x39, 0xe5, 0x34, 0xe6, 0x4a, 0x5b, 0x7d,
0x82, 0x8a, 0x0d, 0x07, 0xbc, 0x32, 0x76, 0xef, 0x19, 0xd9, 0x6d, 0xc9, 0xb5, 0x02, 0x3a, 0x63,
0x19, 0x8f, 0x79, 0x75, 0xe9, 0xf7, 0x50, 0xb1, 0xed, 0xd0, 0x3f, 0x2b, 0x78, 0x6f, 0x31, 0x9d,
0x5a, 0xab, 0x62, 0x59, 0x56, 0x5c, 0x50, 0x2e, 0x50, 0xe9, 0xf7, 0x4d, 0x6a, 0x0e, 0x3e, 0xd2,
0xe8, 0xc4, 0x80, 0xfa, 0xb5, 0xb4, 0x3a, 0xc5, 0x53, 0xc1, 0x32, 0xca, 0xc3, 0xb4, 0xf4, 0x07,
0xa8, 0xda, 0x72, 0xe0, 0x19, 0x62, 0x93, 0x30, 0x2d, 0xbd, 0x5f, 0x93, 0xbb, 0xb6, 0x1f, 0x5d,
0x30, 0x5e, 0x5d, 0x39, 0xf4, 0x35, 0x54, 0xfa, 0x86, 0xf2, 0x17, 0xc6, 0xab, 0x85, 0x73, 0x7f,
0x4c, 0x36, 0x74, 0xa3, 0x63, 0xd1, 0x94, 0x4a, 0xf8, 0xb6, 0x06, 0x55, 0x29, 0x7f, 0xdd, 0x5c,
0x22, 0xc9, 0xc3, 0xa3, 0x68, 0x1a, 0x58, 0xab, 0xae, 0x56, 0xcb, 0x54, 0x54, 0x42, 0x04, 0x7c,
0x06, 0xb1, 0xbf, 0x61, 0xaa, 0xd5, 0x50, 0x55, 0x60, 0xcd, 0xde, 0x88, 0x0c, 0x34, 0x57, 0xe9,
0x27, 0xd7, 0x02, 0x7f, 0xd3, 0xf4, 0x59, 0xc9, 0xc3, 0xb3, 0xac, 0xb8, 0xd0, 0x5c, 0xef, 0xdf,
0x4b, 0xa4, 0xd7, 0xe9, 0xb1, 0xbe, 0x87, 0xbd, 0xea, 0x6f, 0x4b, 0x9f, 0xbc, 0x59, 0x5d, 0xdb,
0xe8, 0x03, 0x22, 0x79, 0x68, 0xcf, 0xca, 0xfb, 0x92, 0xac, 0x73, 0xa5, 0xaf, 0x72, 0x4e, 0x05,
0x54, 0x34, 0x4a, 0x52, 0x7f, 0x0b, 0xcf, 0xb5, 0xcf, 0xd5, 0x29, 0xc8, 0xfc, 0x2d, 0x54, 0xc7,
0x49, 0xea, 0x7d, 0x45, 0x3c, 0xc7, 0x89, 0x21, 0xb3, 0x2d, 0x69, 0xdb, 0x1c, 0x51, 0x69, 0x78,
0xaf, 0x20, 0x33, 0x3d, 0xe9, 0x05, 0xf1, 0x1d, 0x59, 0x47, 0x81, 0x8e, 0x64, 0x07, 0x25, 0xdb,
0x56, 0x72, 0xa6, 0x51, 0xa7, 0xfb, 0x9a, 0x0c, 0x17, 0x74, 0x39, 0x93, 0x53, 0x2b, 0xdc, 0x45,
0xe1, 0x4e, 0x57, 0x78, 0xc2, 0xe4, 0xd4, 0x28, 0x7f, 0x41, 0x76, 0x9c, 0x92, 0x0b, 0x05, 0xb2,
0xb2, 0xaa, 0x3d, 0x54, 0x79, 0x56, 0x35, 0x41, 0xc8, 0x48, 0x9e, 0x93, 0x3d, 0x27, 0x81, 0x0f,
0x5c, 0x55, 0x5c, 0xa4, 0x56, 0xe4, 0xcf, 0xe5, 0xf8, 0xda, 0x82, 0x57, 0x9f, 0x4d, 0x96, 0x19,
0xfd, 0xb6, 0x06, 0x79, 0x69, 0x75, 0xc3, 0x39, 0x5d, 0x50, 0x66, 0x7f, 0xd2, 0xa0, 0xd1, 0xbd,
0x24, 0x77, 0xe6, 0x74, 0xcd, 0xab, 0x32, 0xca, 0x3b, 0xa8, 0xdc, 0x6d, 0x95, 0xa7, 0x06, 0x36,
0xda, 0x87, 0x64, 0xcd, 0x68, 0x43, 0x69, 0xf9, 0x77, 0x4d, 0x7f, 0x42, 0x7e, 0x28, 0x0d, 0xeb,
0x88, 0xec, 0xeb, 0xd7, 0x8d, 0xcc, 0x12, 0x32, 0xc8, 0xa9, 0x28, 0x2a, 0x9a, 0x14, 0xb5, 0x68,
0x26, 0xcd, 0x3d, 0x54, 0x0d, 0x25, 0x0f, 0xf5, 0x9b, 0x3d, 0xd5, 0x9c, 0xb7, 0x45, 0xf5, 0x46,
0x33, 0x8c, 0x8b, 0xdf, 0x90, 0xfb, 0xad, 0x0b, 0x56, 0x9d, 0x5f, 0xf1, 0x70, 0x1f, 0x3d, 0xf8,
0x8d, 0x07, 0x56, 0x9d, 0xcf, 0x3b, 0x78, 0x49, 0xee, 0x2c, 0xe4, 0xd0, 0x55, 0xef, 0x9b, 0xa7,
0xec, 0xc6, 0xef, 0x68, 0x5f, 0x10, 0xed, 0x97, 0x4a, 0x48, 0x4d, 0xec, 0xae, 0xf2, 0x81, 0x39,
0x59, 0xc9, 0xc3, 0x00, 0x52, 0x1d, 0xb6, 0xa3, 0xfb, 0x9a, 0x0c, 0xe7, 0x93, 0xee, 0x0a, 0x0f,
0x4c, 0xd5, 0x74, 0x12, 0xee, 0x28, 0x9b, 0xaa, 0xb1, 0x99, 0x4a, 0x00, 0xab, 0xfa, 0xa2, 0xad,
0x1a, 0x93, 0xa5, 0x04, 0x98, 0xaf, 0x1a, 0x0c, 0x24, 0x21, 0x91, 0xa0, 0xce, 0xad, 0x68, 0xd4,
0xbe, 0x7d, 0x1d, 0x27, 0x30, 0xe0, 0x75, 0x91, 0xc2, 0x3a, 0x2f, 0xad, 0xe8, 0x70, 0x21, 0xd2,
0x6f, 0xeb, 0xbc, 0x9c, 0xbf, 0x0c, 0x46, 0xa2, 0x2f, 0x70, 0x47, 0xf6, 0xb0, 0xbd, 0x0c, 0x28,
0x3b, 0xca, 0x32, 0xa7, 0x1c, 0xfd, 0xa7, 0x77, 0xe3, 0x18, 0x9f, 0xc9, 0x84, 0x7a, 0x3f, 0x26,
0xeb, 0x95, 0xee, 0x92, 0x94, 0x2b, 0xdb, 0x59, 0x70, 0x8e, 0xaf, 0xea, 0x95, 0x20, 0xcc, 0x60,
0xa2, 0x8e, 0xd0, 0xe8, 0x0d, 0xc9, 0xaa, 0xe5, 0xc5, 0x76, 0x7c, 0xaf, 0x18, 0x42, 0xac, 0x87,
0xa6, 0x81, 0xda, 0xa1, 0x8d, 0x45, 0x89, 0xc6, 0x66, 0x64, 0xdf, 0x27, 0x44, 0xc6, 0x8e, 0x61,
0xe6, 0xf5, 0x6d, 0x19, 0x37, 0xf0, 0x03, 0xd3, 0x27, 0x1b, 0xdc, 0x8c, 0x68, 0xdd, 0x9e, 0x1a,
0xc2, 0x63, 0xb2, 0x21, 0x94, 0xae, 0x7a, 0x31, 0x5b, 0xd8, 0x70, 0xd6, 0x84, 0x92, 0xc7, 0x85,
0x98, 0x35, 0xcc, 0x7d, 0xd2, 0xd3, 0x4c, 0xae, 0x90, 0x6c, 0x27, 0xf2, 0x6d, 0xa1, 0xe4, 0x44,
0x69, 0x9a, 0xf7, 0x92, 0x0c, 0xa3, 0x8c, 0xeb, 0x8d, 0x40, 0x42, 0x92, 0x41, 0x54, 0xf1, 0x42,
0x2c, 0x8c, 0xe2, 0x3d, 0x43, 0x08, 0x1c, 0xde, 0x99, 0xab, 0x31, 0xcb, 0x4b, 0x10, 0xba, 0x47,
0xcc, 0x4f, 0xe2, 0x0d, 0x07, 0x34, 0xe4, 0x43, 0x32, 0x00, 0x7d, 0xfc, 0x31, 0x37, 0x9d, 0x1b,
0x07, 0xf0, 0x20, 0xe8, 0x6b, 0xe3, 0x2b, 0x6b, 0xc3, 0xdf, 0x04, 0x73, 0xa4, 0x9e, 0x21, 0xf1,
0x2e, 0xe9, 0x67, 0x64, 0x8b, 0xa5, 0xa9, 0x84, 0x94, 0x55, 0xa0, 0x5a, 0x6a, 0xdf, 0xd4, 0x4c,
0x0b, 0x39, 0xc1, 0x98, 0x6c, 0xc5, 0x97, 0x82, 0xe5, 0x3c, 0xa2, 0x39, 0xc4, 0x2e, 0x53, 0x33,
0x62, 0x37, 0x2d, 0x74, 0x02, 0x71, 0x67, 0x33, 0xe9, 0xf2, 0x71, 0x7d, 0x99, 0xb1, 0x0c, 0x27,
0xeb, 0x20, 0xf0, 0x5a, 0xc1, 0xc4, 0x22, 0xde, 0xaf, 0xc8, 0xb0, 0xab, 0xd0, 0x33, 0x45, 0x52,
0x59, 0x0b, 0x7d, 0x00, 0x38, 0x5c, 0x57, 0x83, 0xdd, 0x56, 0xa6, 0x57, 0x63, 0x19, 0x18, 0x54,
0x5f, 0x9d, 0xab, 0xd2, 0x19, 0xcb, 0x6a, 0xb0, 0xa3, 0x76, 0x7b, 0x41, 0xf8, 0x5e, 0x63, 0xde,
0x37, 0x64, 0xd4, 0x95, 0x99, 0xa5, 0x93, 0x47, 0x0b, 0xa1, 0x37, 0x31, 0xf4, 0x7e, 0xeb, 0xe1,
0xd4, 0xf2, 0xe6, 0x52, 0x78, 0x43, 0x0e, 0x6e, 0xf0, 0x65, 0x72, 0xf1, 0x30, 0x97, 0x7b, 0x3f,
0xe0, 0xc9, 0xe4, 0x64, 0xf7, 0x85, 0x73, 0x66, 0x8a, 0x0d, 0x64, 0x0a, 0xb1, 0x1d, 0x9b, 0x7a,
0x5f, 0xf8, 0x3d, 0xc3, 0x92, 0x43, 0xb3, 0x5e, 0x98, 0x34, 0xb7, 0xe1, 0xe9, 0x51, 0xde, 0x14,
0xf2, 0xb6, 0x6b, 0x4e, 0xc7, 0x2d, 0xda, 0xd4, 0xf3, 0x4f, 0xc8, 0x26, 0x57, 0x38, 0xc0, 0xcd,
0x2d, 0x4b, 0xea, 0x2c, 0xc3, 0xe9, 0xb9, 0x1a, 0xac, 0x71, 0x15, 0xf0, 0xf0, 0x9d, 0x36, 0xbf,
0xa9, 0xb3, 0xcc, 0x7b, 0x4a, 0x76, 0xe7, 0x79, 0x2e, 0x82, 0x19, 0x9a, 0x5b, 0xb2, 0xc3, 0x6e,
0xfc, 0x4f, 0xc9, 0x53, 0x01, 0x1f, 0xaa, 0xf3, 0xa2, 0xa4, 0x12, 0x54, 0x91, 0xd5, 0x78, 0x21,
0x72, 0x2e, 0x78, 0x5e, 0xe7, 0x76, 0x6b, 0xa6, 0x19, 0x88, 0xb4, 0xd2, 0x0d, 0x4e, 0x24, 0x3c,
0xad, 0x25, 0xc4, 0x38, 0x50, 0x57, 0x83, 0xb1, 0x95, 0x06, 0x4e, 0x79, 0x62, 0x84, 0x66, 0xa5,
0xfe, 0x23, 0xca, 0x8e, 0x9d, 0xca, 0x7b, 0x4f, 0x1e, 0x7f, 0x6c, 0x30, 0x3b, 0x7d, 0x1f, 0x7e,
0x4c, 0x04, 0xef, 0x77, 0xe4, 0x40, 0x01, 0x5e, 0xd6, 0x19, 0x50, 0xbc, 0x75, 0x79, 0x9d, 0x55,
0x1c, 0xbb, 0x73, 0x53, 0xfd, 0x43, 0xcc, 0xf8, 0xbe, 0xe3, 0xbd, 0x0e, 0xd3, 0xf2, 0xa4, 0x61,
0x35, 0x37, 0x61, 0xce, 0x11, 0xbf, 0xde, 0xd1, 0x9d, 0x05, 0x47, 0x93, 0xeb, 0x1c, 0x4d, 0xc8,
0x17, 0x9d, 0x8c, 0x7e, 0xc0, 0xd3, 0x5d, 0x53, 0xad, 0x6d, 0x4a, 0xfc, 0x3a, 0x57, 0xcf, 0x4d,
0xe5, 0xb0, 0x68, 0xaa, 0xaf, 0xcb, 0x5c, 0xab, 0xbd, 0xe7, 0xe6, 0xe1, 0x91, 0x46, 0xdf, 0x75,
0x5a, 0xee, 0xe8, 0xfb, 0x65, 0xb2, 0x7f, 0xf3, 0x67, 0x09, 0xdd, 0xd5, 0xf5, 0x14, 0xc0, 0xaf,
0x0d, 0x4f, 0xf0, 0x6b, 0xc3, 0xca, 0x4c, 0x26, 0x8b, 0xdf, 0x21, 0x9e, 0x76, 0xbf, 0x43, 0xe8,
0x25, 0x84, 0x2b, 0xaa, 0x5b, 0x6c, 0xf3, 0x14, 0xcf, 0x9a, 0x3d, 0xf1, 0xad, 0x92, 0x4d, 0xce,
0xff, 0x5a, 0x22, 0xb7, 0x4c, 0x60, 0xff, 0x39, 0x2e, 0xbd, 0x7f, 0xff, 0xf4, 0x4b, 0xef, 0x0d,
0x3f, 0x5f, 0x03, 0x9b, 0x9c, 0xf7, 0xcf, 0x25, 0xb2, 0x3c, 0x93, 0x89, 0xff, 0xe2, 0xff, 0x2c,
0x49, 0xfd, 0x5a, 0x02, 0x9d, 0x59, 0x78, 0x0b, 0x3f, 0x68, 0x3d, 0xfd, 0x6f, 0x00, 0x00, 0x00,
0xff, 0xff, 0x16, 0x2d, 0xe3, 0x05, 0xf8, 0x12, 0x00, 0x00,
}
|
ssyyzs/JavaMesh | javamesh-samples/javamesh-route/gray-dubbo-2.7.x-plugin/src/main/java/com/huawei/gray/dubbo/invoker/ApacheDubboInvokerEnhanceDefinition.java | <reponame>ssyyzs/JavaMesh
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved.
*/
package com.huawei.gray.dubbo.invoker;
import com.huawei.apm.core.agent.definition.EnhanceDefinition;
import com.huawei.apm.core.agent.definition.MethodInterceptPoint;
import com.huawei.apm.core.agent.matcher.ClassMatcher;
import com.huawei.apm.core.agent.matcher.ClassMatchers;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatchers;
/**
* 增强DubboInvoker类的doInvoke方法,更改路由信息
*
* @author l30008180
* @since 2021年6月28日
*/
public class ApacheDubboInvokerEnhanceDefinition implements EnhanceDefinition {
private static final String INVOKER_ENHANCE_CLASS = "org.apache.dubbo.rpc.protocol.dubbo.DubboInvoker";
private static final String INVOKER_INTERCEPT_CLASS
= "com.huawei.gray.dubbo.invoker.ApacheDubboInvokerInstanceMethodInterceptor";
private static final String ENHANCE_METHOD_NAME = "doInvoke";
@Override
public ClassMatcher enhanceClass() {
return ClassMatchers.named(INVOKER_ENHANCE_CLASS);
}
@Override
public MethodInterceptPoint[] getMethodInterceptPoints() {
return new MethodInterceptPoint[]{
MethodInterceptPoint.newInstMethodInterceptPoint(INVOKER_INTERCEPT_CLASS,
ElementMatchers.<MethodDescription>named(ENHANCE_METHOD_NAME))};
}
}
|
baijianruoliorz/algorithm | src/leetCode/day3/T763.java | package leetCode.day3;
import java.util.ArrayList;
import java.util.List;
/**
* @author liqiqi_tql
* @date 2020/12/8 -11:34
*/
public class T763 {
public List<Integer> partitionLabels(String S){
int[] lastIndexsOfChar=new int[26];
for (int i=0;i<S.length();i++){
lastIndexsOfChar[char2Index(S.charAt(i))]=i;
}
List<Integer> partitions=new ArrayList<>();
int firstIndex=0;
while (firstIndex< S.length()){
int lastIndex=firstIndex;
for (int i=firstIndex;i< S.length()&&i<=lastIndex;i++){
int index=lastIndexsOfChar[char2Index(S.charAt(i))];
if (index>lastIndex){
lastIndex=index;
}
}
partitions.add(lastIndex-firstIndex+1);
firstIndex=lastIndex+1;
}
return partitions;
}
private int char2Index(char c) {
return c - 'a';
}
}
|
danny2604/ImmersivePortalsTweaked | src/main/java/qouteall/imm_ptl/peripheral/ducks/IECreateWorldScreen.java | package qouteall.imm_ptl.peripheral.ducks;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.world.level.DataPackConfig;
public interface IECreateWorldScreen {
PackRepository portal_getResourcePackManager();
DataPackConfig portal_getDataPackSettings();
}
|
barrhaim/jruby | test/mri/excludes/TestSprintfComb.rb | <filename>test/mri/excludes/TestSprintfComb.rb
exclude :test_format_float, "needs investigation"
exclude :test_format_integer, "needs investigation"
|
ruppysuppy/Daily-Coding-Problem-Solutions | Solutions/128.py | """
Problem:
All the disks start off on the first rod in a stack. They are ordered by size, with the
largest disk on the bottom and the smallest one at the top.
The goal of this puzzle is to move all the disks from the first rod to the last rod
while following these rules:
You can only move one disk at a time.
A move consists of taking the uppermost disk from one of the stacks and placing it on
top of another stack.
You cannot place a larger disk on top of a smaller disk.
Write a function that prints out all the steps necessary to complete the Tower of Hanoi.
You should assume that the rods are numbered, with the first rod being 1, the second
(auxiliary) rod being 2, and the last (goal) rod being 3.
For example, with n = 3, we can do this in 7 moves:
Move 1 to 3
Move 1 to 2
Move 3 to 2
Move 1 to 3
Move 2 to 1
Move 2 to 3
Move 1 to 3
"""
from typing import Optional
def towers_of_hanoi(
n: int,
start_rod: Optional[str] = None,
aux_rod: Optional[str] = None,
end_rod: Optional[str] = None,
) -> None:
# initializing the names for the rods [using different convention from the one
# mentioned in the question]
if not start_rod:
start_rod = "start_rod"
print(
f"\nTower of Hanoi for {n} Disks ========================================"
)
if not aux_rod:
aux_rod = "aux_rod"
if not end_rod:
end_rod = "end_rod"
# if the number of disks left to move is 1, its shifted [base case for recursion]
if n == 1:
print(f"Move disk 1 from {start_rod} to {end_rod}")
return
# moving the top disk of the start rod to the proper position in the auxilary rod
# using the end rod as buffer
towers_of_hanoi(n - 1, start_rod, end_rod, aux_rod)
# moving the top disk from the start rod to the end rod
print(f"Move disk {n} from {start_rod} to {end_rod}")
# moving the top disk of the auxilary rod to the proper position in the end rod
# using the start rod as buffer
towers_of_hanoi(n - 1, aux_rod, start_rod, end_rod)
if __name__ == "__main__":
towers_of_hanoi(3)
towers_of_hanoi(4)
towers_of_hanoi(5)
towers_of_hanoi(6)
"""
SPECS:
TIME COMPLEXITY: O(2 ^ n)
SPACE COMPLEXITY: O(n)
"""
|
chris-c-thomas/website | public/js/p3/widget/viewer/PhylogeneticTreeGene.js | <reponame>chris-c-thomas/website
define([
'dojo/_base/declare', 'dojo/_base/lang',
'dojo/dom-construct', 'dojo/request', 'dojo/when',
'dijit/layout/ContentPane',
'./Base', '../../util/PathJoin', '../PhylogenyGene', '../../WorkspaceManager',
'dojo/request'
], function (
declare, lang,
domConstruct, request, when,
ContentPane,
ViewerBase, PathJoin, Phylogeny, WorkspaceManager,
xhr
) {
return declare([ViewerBase], {
disabled: false,
query: null,
displayName: null,
containerType: 'phylogenetic_tree',
perspectiveLabel: 'Phylogenetic Tree',
perspectiveIconClass: 'icon-selection-Experiment',
apiServiceUrl: window.App.dataAPI,
maxFeaturesPerList: 10000,
onSetState: function (attr, oldVal, state) {
// console.warn("TE onSetState", state);
if (!state) {
return;
}
this.viewer.set('visible', true);
window.document.title = 'Phylogenetic Tree';
},
postCreate: function () {
if (!this.state) {
this.state = {};
}
var _self = this;
this.viewer = new Phylogeny({
region: 'center',
id: this.id + '_Phylogeny',
state: this.state,
gutters: false,
tgState: null,
loadingMask: null,
apiServer: window.App.dataServiceURL
});
this.viewerHeader = new ContentPane({
content: '',
region: 'top'
});
this.addChild(this.viewerHeader);
this.addChild(this.viewer);
this.inherited(arguments);
var dataFiles = [];
var nwkIds = null;
var nwkNames = null;
var folderCheck = this.state.search.match(/wsTreeFolder=..+?(?=&|$)/);
var fileCheck = this.state.search.match(/wsTreeFile=..+?(?=&|$)/);
var idType = this.state.search.match(/idType=..+?(?=&|$)/);
var labelType = this.state.search.match(/labelType=..+?(?=&|$)/);
if (idType && !isNaN(idType.index)) {
idType = idType[0].split('=')[1];
}
else { idType = 'patric_id'; }
if (labelType && !isNaN(labelType.index)) {
labelType = labelType[0].split('=')[1];
}
else { labelType = 'feature_name'; }
var labelSearch = this.state.search.match(/labelSearch=.*/);
if (labelSearch && !isNaN(labelSearch.index)) {
labelSearch = labelSearch[0].split('=')[1].split('&')[0];
if (labelSearch == 'true') {
labelSearch = true;
} else {
labelSearch = false;
}
}
else { labelSearch = false; }
if (folderCheck && !isNaN(folderCheck.index)) {
var objPathParts = folderCheck[0].split('=')[1].split('/');
var objName = objPathParts.pop();
this.displayName = decodeURIComponent(objName);
objName = '.' + objName;
objPathParts.push(objName);
var objPath = decodeURIComponent(objPathParts.join('/'));
if (objPath.substring(0, 7) == '/public') {
objPath = objPath.substring(7); // remove '/public' if needed
}
WorkspaceManager.getFolderContents(objPath, true, true)
.then(function (objs) {
// console.log("[JobResult] objects: ", objs);
Object.values(objs).forEach(function (obj) {
if (obj.type == 'json' && !obj.path.endsWith('final_rooted.json')) {
dataFiles.push(obj.path);
} else if (obj.type == 'nwk') {
nwkIds = obj.path;
nwkNames = obj.path;
}
});
if (dataFiles.length >= 1) {
WorkspaceManager.getObjects(dataFiles, false)
.then(function (curFiles) {
var treeDat = {};
if (curFiles.length >= 1) {
treeDat = JSON.parse(curFiles[0].data);
treeDat.info.taxon_name = _self.displayName;
}
_self.prepareTree(treeDat, idType, labelType, labelSearch);
});
} else if (nwkIds || nwkNames) {
var objPath = nwkIds || nwkNames;
WorkspaceManager.getObjects([objPath]).then(lang.hitch(this, function (objs) {
var obj = objs[0];
var treeDat = {};
if (typeof obj.data == 'string') {
treeDat.tree = obj.data.replace(/[^(,)]+_@_/g, ''); // get rid of ridiculously annoying, super dirty embedded labels
_self.prepareTree(treeDat, idType, labelType, labelSearch);
}
}));
}
});
}
else if (fileCheck && !isNaN(fileCheck.index)) {
var objPath = fileCheck[0].split('=')[1];
WorkspaceManager.getObjects([objPath]).then(lang.hitch(this, function (objs) {
var obj = objs[0];
var treeDat = {};
if (typeof obj.data == 'string') {
treeDat.tree = obj.data.replace(/[^(,)]+_@_/g, ''); // get rid of ridiculously annoying, super dirty embedded labels
_self.prepareTree(treeDat, idType, labelType, labelSearch);
}
}));
}
},
prepareTree: function (treeDat, idType, labelType, labelSearch) {
// console.log('in prepareTree, idType, labelType, labelSearch', idType, labelType, labelSearch);
if (labelSearch) {
this.findLabels(treeDat, idType, labelType);
}
else {
this.viewer.processTreeData(treeDat, idType);
}
},
findLabels: function (treeDat, idType, labelType) {
var _self = this;
var ids = treeDat.tree.match(/[^(,)]+(?=:)/g);
var toQuery = [];
ids.forEach(function (id) {
if (id.includes('.')) {
toQuery.push(id);
}
});
var query = 'in(' + idType + ',(' + toQuery.join(',') + '))';
var url = PathJoin(this.apiServiceUrl, 'genome_feature', '?' + (query) + '&select(' + idType + ',feature_id)&limit(' + this.maxFeaturesPerList + 1 + ')');
// console.log('in findLabels URL: ', url);
xhr.post(PathJoin(this.apiServiceUrl, 'genome_feature'), {
headers: {
accept: 'application/solr+json',
'Content-Type': 'application/rqlquery+x-www-form-urlencoded',
'X-Requested-With': null,
Authorization: (window.App.authorizationToken || '')
},
handleAs: 'json',
'Content-Type': 'application/rqlquery+x-www-form-urlencoded',
data: (query) + '&select(' + idType + ',feature_id)&limit(' + this.maxFeaturesPerList + 1 + ')'
}).then(function (res) {
// console.log('findLabels, Get FeatureList Res: ', res);
if (res && res.response && res.response.docs) {
var features = res.response.docs;
treeDat.labels = {};
features.forEach(function (feature) {
treeDat.labels[features.patric_id] = features.patric_id;
});
}
else {
console.warn('Invalid Response for: ', url);
}
_self.viewer.processTreeData(treeDat, idType);
return true;
}, function (err) {
console.error('Error Retreiving Features: ', err);
_self.viewer.processTreeData(treeDat, idType);
return false;
});
return true;
}
});
});
|
WaiHChan/android-appt | apptbook-web/src/main/java/edu/pdx/cs410J/chanwai/PrettyPrinter.java | package edu.pdx.cs410J.chanwai;
import edu.pdx.cs410J.AppointmentBookDumper;
import groovyjarjarantlr4.v4.runtime.atn.PredicateEvalInfo;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
/**
* This class represent a writer to a file in a nicer format
*/
public class PrettyPrinter implements AppointmentBookDumper<AppointmentBook> {
private final Writer writer;
/**
* Create a writer for loading data to file
* @param writer a fileWriter
*/
public PrettyPrinter(Writer writer){
this.writer = writer;
}
/**
* Pass in an appointment book that will be loaded to a file
* @param book An appointment book that will be load to a file
* @throws IOException Raise an exception if the appointment book cannot be loaded
*/
@Override
public void dump(AppointmentBook book) throws IOException {
PrintWriter pw = new PrintWriter(this.writer);
pw.println("");
pw.println("Appointment Book: " + book.getOwnerName() + "\tTotal Appointments: " + book.getAppointments().size());
for (Appointment a : book.getAppointments()){
long duration_In_Min = duration(a);
long diff_Hour = hour(duration_In_Min);
long diff_Min = min(duration_In_Min);
long diff_Day = day(duration_In_Min);
pw.println("\n");
pw.println("Description: " + a.description + "\n");
pw.println("From " + a.getBDateString() + " -> " + a.getEDateString() + "\n");
pw.print("Duration: ");
if (diff_Day > 0){
pw.print(diff_Day + " days ");
}
if (diff_Hour > 0){
pw.print(diff_Hour + " hours ");
}
if (diff_Min > 0){
pw.print(diff_Min + " minutes\n");
}
pw.println("\n");
}
pw.flush();
}
/**
* return the duration of an appointment
* @param a an appointment
* @return the duration of an appointment
*/
public long duration(Appointment a){
long diff = a.getEndTime().getTime() - a.getBeginTime().getTime();
return diff / 60000;
}
/**
* calculate the duration of an appointment to days
* @param time the duration time in minutes
* @return return the duration of an appointment to days
*/
public long day(long time){
return time / 60 / 24;
}
/**
* calculate the duration of an appointment to hours
* @param time the duration time in minutes
* @return return the duration of an appointment to hours
*/
public long hour(long time){
return time / 60 % 24;
}
/**
* calculate the duration of an appointment to minutes
* @param time the duration time in minutes
* @return return the duration of an appointment to minutes
*/
public long min(long time) {
return time % 60;
}
}
|
SaraChandler/goenv-hack | main.go | <gh_stars>0
package main
import (
"fmt"
"os"
"github.com/SaraChandler/goenv-hack/cmd"
"github.com/mitchellh/cli"
)
var version = "v0.0.0"
func main() {
c := cli.NewCLI("goenv-hack", version)
c.HelpWriter = os.Stdout
c.ErrorWriter = os.Stderr
c.Args = os.Args[1:]
c.Commands = map[string]cli.CommandFactory{
"install": func() (cli.Command, error) {
return &cmd.InstallCommand{}, nil
},
"use": func() (cli.Command, error) {
return &cmd.UseCommand{}, nil
},
"list": func() (cli.Command, error) {
return &cmd.ListCommand{}, nil
},
"uninstall": func() (cli.Command, error) {
return &cmd.UninstallCommand{}, nil
},
}
exitStatus, err := c.Run()
if err != nil {
fmt.Print(err)
os.Exit(1)
}
os.Exit(exitStatus)
}
|
zefryuuko/wads-final-project | frontend/src/components/staff/courses/CourseGroups.js | import React from 'react'
import {Link, Redirect} from 'react-router-dom';
// Services
import AuthService from '../../../services/AuthService';
import CourseService from '../../../services/CourseService';
// UI Elements
import ContentWrapper from '../../ui-elements/ContentWrapper';
import PageBreadcrumb from '../../ui-elements/PageBreadcrumb';
import Card from '../../ui-elements/Card';
import Button from '../../ui-elements/Button';
import PageWrapper from '../../ui-elements/PageWrapper';
import EditCourseGroupModal from './components/EditCourseGroupModal';
import ErrorAlert from '../../ui-elements/ErrorAlert';
import SuccessAlert from '../../ui-elements/SuccessAlert';
import Preloader from '../../ui-elements/Preloader';
import DeleteCourseGroupModal from './components/DeleteCourseGroupModal';
import CreateCourseGroupModal from './components/CreateCourseGroupModal';
// Components
class CourseGroups extends React.Component {
constructor() {
super();
this.state = {
isLoading: true,
isAuthenticating: true,
isAuthenticated: false,
currentTablePage: 1,
currentTableContent: [],
showErrorMessage: false,
showSuccessMessage: false,
}
// Set page display mode when loading
this.loadingStyle = {visibility: "none"}
this.loadedStyle = {visibility: "visible", opacity: 1}
// Bind functions
this.reloadTable = this.reloadTable.bind(this);
this.updateSuccess = this.updateSuccess.bind(this);
this.showError = this.showError.bind(this);
}
reloadTable() {
this.setState({isLoading: true});
// Load table content
CourseService.getCourseGroup(this.state.currentTablePage).then(res => {
// TODO: add error validation
this.setState({currentTableContent: res, isLoading: false});
});
}
updateSuccess() {
this.setState({showSuccessMessage: true, showErrorMessage: false, isLoading: true});
CourseService.getCourseGroup(this.state.currentTablePage).then(res => {
// TODO: add error validation
this.setState({
currentTableContent: res, isLoading: false
});
});
}
showError() {
this.setState({showErrorMessage: true, showSuccessMessage: false});
}
componentDidMount() {
// Perform session check
AuthService.isLoggedIn()
.then(res => {
if (res.response && (res.response.status === 403))
this.setState({
isAuthenticating: false,
isAuthenticated: false
});
else {
this.setState({
isAuthenticating: false,
isAuthenticated: true
});
// Load table content
CourseService.getCourseGroup(this.state.currentTablePage).then(res => {
this.setState({
currentTableContent: res,
isLoading: false
});
})
}
});
}
render() {
if (!this.state.isAuthenticated && !this.state.isAuthenticating) return <Redirect to="/logout"/>
return (
<div>
<Preloader isLoading={this.state.isLoading}/>
<div className="ease-on-load" style={this.state.isLoading ? this.loadingStyle : this.loadedStyle}>
<PageWrapper>
<PageBreadcrumb title="Courses" root="Course Administration" rightComponent={<button className="btn btn-primary btn-circle mr-2" data-toggle="modal" data-target={`#createCourseGroupModal`} style={{lineHeight:0}} ><i className="icon-plus"/></button>}/>
<ContentWrapper>
{this.state.showErrorMessage ? <ErrorAlert><strong>Error -</strong> Action failed. Please try again.</ErrorAlert> : null}
{this.state.showSuccessMessage ? <SuccessAlert><strong>Success -</strong> Action performed successfully.</SuccessAlert> : null}
<div className="row">
<div className="col-12">
<Card padding>
<div className="table-responsive">
<table className="table table-striped no-wrap" id="courseGroupsTable">
<thead className="bg-primary text-white">
<tr>
<th>Code</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{this.state.currentTableContent.length > 0 ? this.state.currentTableContent.map(row => {
return (
<tr key={row.prefix}>
<th scope="row">{row.prefix}</th>
<td><Link to={`/staff/courses/${row.prefix}`}>{row.name}</Link></td>
<td style={{width: "150px", minWidth: "150px"}}>
<Button className="btn btn-sm btn-secondary btn-sm mr-2" data-toggle="modal" data-target={`#editModal-${row.prefix}`}>Edit</Button>
<Button className="btn btn-sm btn-danger" data-toggle="modal" data-target={`#deleteModal-${row.prefix}`}>Delete</Button>
</td>
</tr>
)
}): <tr><td colSpan="3" align="center">No data</td></tr>}
</tbody>
</table>
</div>
{this.state.currentTableContent.length > 0 ? <script>{ window.loadTable('#courseGroupsTable') }</script> : null}
</Card>
</div>
</div>
</ContentWrapper>
</PageWrapper>
{/* Render create course group modal */}
<CreateCourseGroupModal success={this.updateSuccess} error={this.showError}/>
{/* Generate edit modals */}
{this.state.currentTableContent.length > 0 ? this.state.currentTableContent.map(row=> {
return <EditCourseGroupModal key={row.prefix} prefix={row.prefix} name={row.name} success={this.updateSuccess} error={this.showError}/>
}): null}
{/* Generate delete modals */}
{this.state.currentTableContent.length > 0 ? this.state.currentTableContent.map(row=> {
return <DeleteCourseGroupModal key={row.prefix} prefix={row.prefix} name={row.name} success={this.updateSuccess} error={this.showError}/>
}): null}
</div>
</div>
);
}
}
export default CourseGroups; |
atlassian-forks/client-go | v1alpha1/model_api_vulnerability_type.go | <gh_stars>1-10
/*
* Grafeas API
*
* An API to insert and retrieve annotations on cloud artifacts.
*
* API version: v1alpha1
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package grafeas
// VulnerabilityType provides metadata about a security vulnerability.
type ApiVulnerabilityType struct {
// The CVSS score for this Vulnerability.
CvssScore float32 `json:"cvss_score,omitempty"`
Severity *VulnerabilityTypeSeverity `json:"severity,omitempty"`
// All information about the package to specifically identify this vulnerability. One entry per (version range and cpe_uri) the package vulnerability has manifested in.
Details []VulnerabilityTypeDetail `json:"details,omitempty"`
}
|
iacsa/adventofcode-solutions | 2015/05/solution.rb | <filename>2015/05/solution.rb<gh_stars>0
#!/usr/bin/env ruby
# frozen_string_literal: true
# Target Version: 2.7.4
# Advent of Code challenge for 2015-12-05 Parts 1 & 2
input_file = 'input.txt'
def nice1?(string)
at_least_3_vowels?(string) &&
double_letter?(string) &&
no_naughty_substrings?(string)
end
def at_least_3_vowels?(string)
vowels = %w[a e i o u]
string.chars.count { |c| vowels.include?(c) } >= 3
end
def double_letter?(string)
chars = string.chars
(1...chars.length).any? { |i| chars[i] == chars[i - 1] }
end
def no_naughty_substrings?(string)
naughty_substrings = %w[ab cd pq xy]
naughty_substrings.none? { |naughty| string.include?(naughty) }
end
def nice2?(string)
non_overlapping_double?(string) && distant_pair?(string)
end
def non_overlapping_double?(string)
/([a-z]{2}).*\1/ =~ string
end
def distant_pair?(string)
/([a-z]).\1/ =~ string
end
nice_string_count1 = 0
nice_string_count2 = 0
File.open(input_file).each_line do |line|
nice_string_count1 += 1 if nice1?(line)
nice_string_count2 += 1 if nice2?(line)
end
puts "Part 1: #{nice_string_count1}" # => 236
puts "Part 2: #{nice_string_count2}" # => 51
|
putnampp/clotho | include/clotho/genetics/allele_distribution_variable.hpp | // Copyright 2015 <NAME>
//
// 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.
#ifndef ALLELE_DISTRIBUTION_VARIABLE_HPP_
#define ALLELE_DISTRIBUTION_VARIABLE_HPP_
#include "clotho/genetics/allele_distribution_def.hpp"
#include "clotho/powerset/variable_subset.hpp"
template < class E, class B, class BM, class EK >
struct allele_distribution< clotho::powersets::variable_subset< E, B, BM, EK > > {
typedef clotho::powersets::variable_subset< E, B, BM, EK > sequence_type;
void update( sequence_type & seq );
};
#endif // ALLELE_DISTRIBUTION_VARIABLE_HPP_
|
somen440/hossi | hossi-server/src/main/java/org/somen440/hossi/di/repository/RepositoryInjection.java | package org.somen440.hossi.di.repository;
import javax.inject.Singleton;
@Singleton
public class RepositoryInjection {
private static RepositoryType type = RepositoryType.FIRESTORE;
public static void useInmemory() {
type = RepositoryType.INMEMORY;
}
public static void useMock() {
type = RepositoryType.MOCK;
}
public static void useFirestore() {
type = RepositoryType.FIRESTORE;
}
public static RepositoryType currentType() {
return type;
}
}
|
Lucas-HMSC/ecommerce-MERN | dashboard/src/app/containers/Configuracoes/index.js | import React, { Component } from 'react';
import Titulo from '../../components/Texto/Titulo';
import ButtonSimples from '../../components/Button/Simples';
import { TextoDados } from '../../components/Texto/Dados';
import InputValor from '../../components/Inputs/InputValor';
import ListaDinamicaSimples from '../../components/Listas/ListaDinamicaSimples';
import AlertGeral from '../../components/Alert/Geral';
import { connect } from 'react-redux';
import * as actions from '../../actions/configuracoes';
class Configuracoes extends Component {
generateStateConfiguracao = (props) => ({
nome: props.loja ? props.loja.nome : '',
CNPJ: props.loja ? props.loja.cnpj : '',
email: props.loja ? props.loja.email : '',
endereco: props.loja ? props.loja.endereco.local : '',
numero: props.loja ? props.loja.endereco.numero : '',
bairro: props.loja ? props.loja.endereco.bairro : '',
cidade: props.loja ? props.loja.endereco.cidade : '',
estado: props.loja ? props.loja.endereco.estado : '',
cep: props.loja ? props.loja.endereco.CEP : '',
telefones: props.loja ? props.loja.telefones : [],
});
state = {
...this.generateStateConfiguracao(this.props),
aviso: null,
erros: {},
};
getConfiguracao(props) {
const { usuario } = props;
if (!usuario) return null;
this.props.getConfiguracao(usuario.loja);
}
componentDidMount() {
this.getConfiguracao(this.props);
}
componentDidUpdate(prevProps) {
if (!prevProps.usuario && this.props.usuario)
this.getConfiguracao(this.props);
if (!prevProps.loja && this.props.loja)
this.setState(this.generateStateConfiguracao(this.props));
}
updateLoja() {
const { usuario } = this.props;
if (!usuario || !this.validade()) return null;
this.props.updateConfiguracao(this.state, usuario.loja, (error) => {
this.setState({
aviso: {
status: !error,
msg: error
? error.message
: 'Configuração da loja atualizada com sucesso',
},
});
});
}
validate() {
const {
nome,
CNPJ,
email,
endereco,
numero,
bairro,
cidade,
estado,
cep,
} = this.state;
const erros = {};
if (!nome) erros.nome = 'Preencha aqui com o nome da loja';
if (!CNPJ) erros.CNPJ = 'Preencha aqui com o CNPJ da loja';
if (!email) erros.email = 'Preencha aqui com o email da loja';
if (!endereco) erros.endereco = 'Preencha aqui com o endereço da loja';
if (!numero) erros.numero = 'Preencha aqui com o número da loja';
if (!bairro) erros.bairro = 'Preencha aqui com o bairro da loja';
if (!cidade) erros.cidade = 'Preencha aqui com a cidade da loja';
if (!estado) erros.estado = 'Preencha aqui com o estado da loja';
if (!cep) erros.cep = 'Preencha aqui com o CEP da loja';
this.setState({ erros });
return !(Object.keys(erros).length > 0);
}
renderCabecalho() {
return (
<div className="flex">
<div className="flex-1 flex">
<Titulo tipo="h1" titulo="Configurações" />
</div>
<div className="flex-1 flex flex-end">
<ButtonSimples
type="success"
onClick={() => this.updateLoja()}
label={'Salvar'}
/>
</div>
</div>
);
}
handleSubmit = (field, value) => {
this.setState({ [field]: value }, () => this.validate());
};
renderDadosConfiguracao() {
const { nome, CNPJ, email, erros } = this.state;
return (
<div className="dados-configuracao">
<TextoDados
chave="Nome"
valor={
<InputValor
value={nome}
name="nome"
noStyle
erro={erros.nome}
handleSubmit={(valor) => this.handleSubmit('nome', valor)}
/>
}
/>
<TextoDados
chave="CNPJ"
valor={
<InputValor
value={CNPJ}
name="CNPJ"
noStyle
erro={erros.CNPJ}
handleSubmit={(valor) => this.handleSubmit('CNPJ', valor)}
/>
}
/>
<TextoDados
chave="E-mail"
valor={
<InputValor
value={email}
name="email"
noStyle
erro={erros.email}
handleSubmit={(valor) => this.handleSubmit('email', valor)}
/>
}
/>
</div>
);
}
renderDadosEndereco() {
const { endereco, numero, bairro, cidade, estado, cep, erros } = this.state;
return (
<div className="dados-configuracao">
<TextoDados
chave="Endereço"
valor={
<InputValor
value={endereco}
name="endereco"
noStyle
erro={erros.endereco}
handleSubmit={(valor) => this.handleSubmit('endereco', valor)}
/>
}
/>
<TextoDados
chave="Número"
valor={
<InputValor
value={numero}
name="numero"
noStyle
erro={erros.numero}
handleSubmit={(valor) => this.handleSubmit('numero', valor)}
/>
}
/>
<TextoDados
chave="Bairro"
valor={
<InputValor
value={bairro}
name="bairro"
noStyle
erro={erros.bairro}
handleSubmit={(valor) => this.handleSubmit('bairro', valor)}
/>
}
/>
<TextoDados
chave="Cidade"
valor={
<InputValor
value={cidade}
name="cidade"
noStyle
erro={erros.cidade}
handleSubmit={(valor) => this.handleSubmit('cidade', valor)}
/>
}
/>
<TextoDados
chave="Estado"
valor={
<InputValor
value={estado}
name="estado"
noStyle
erro={erros.estado}
handleSubmit={(valor) => this.handleSubmit('estado', valor)}
/>
}
/>
<TextoDados
chave="CEP"
valor={
<InputValor
value={cep}
name="cep"
noStyle
erro={erros.cep}
handleSubmit={(valor) => this.handleSubmit('cep', valor)}
/>
}
/>
</div>
);
}
onAdd = (valor) => {
if (!valor) return;
const { telefones } = this.state;
this.setState({ telefones: [...telefones, valor] });
};
onRemove = (idx) => {
if (idx === undefined) return;
const { telefones } = this.state;
this.setState({
telefones: telefones.filter((item, index) => index !== idx),
});
};
renderTelefones() {
const { telefones } = this.state;
return (
<div className="dados-telefone">
<Titulo tipo="h3" titulo="Telefones" />
<ListaDinamicaSimples
dados={telefones}
onAdd={this.onAdd}
onRemove={this.onRemove}
/>
</div>
);
}
render() {
return (
<div className="Configuracoes full-width">
<div className="Card">
{this.renderCabecalho()}
<AlertGeral aviso={this.state.aviso} />
<div className="flex horizontal">
<div className="flex-1">{this.renderDadosConfiguracao()}</div>
</div>
<br />
<hr />
<br />
<div className="flex horizontal">
<div className="flex-1">{this.renderDadosEndereco()}</div>
<div className="flex-1">{this.renderTelefones()}</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => ({
loja: state.configuracao.loja,
usuario: state.auth.usuario,
});
export default connect(mapStateToProps, actions)(Configuracoes);
|
mc190diancom/taxi_inspect | qh_inspect/src/main/java/com/miu360/taxi_check/model/WaterTransptQ.java | package com.miu360.taxi_check.model;
public class WaterTransptQ {
private String hylb;
private String compName;
public String getHylb() {
return hylb;
}
public void setHylb(String hylb) {
this.hylb = hylb;
}
public String getCompName() {
return compName;
}
public void setCompName(String compName) {
this.compName = compName;
}
@Override
public String toString() {
return "WaterTransptQ [hylb=" + hylb + ", compName=" + compName + "]";
}
}
|
thomjoy/turftest | src/jspm_packages/npm/corslite@0.0.6/test.js | <filename>src/jspm_packages/npm/corslite@0.0.6/test.js
/* */
var test = require("tape"),
xhr = require("./corslite");
test('200', function(t) {
t.plan(2);
xhr('/200', function(err, resp) {
t.equal(err, null);
t.equal(resp.responseText, '200');
}, true);
});
test('404', function(t) {
t.plan(3);
xhr('/404', function(err, resp) {
t.ok(err);
t.equal(err.status || 404, 404);
t.equal(resp, null);
}, true);
});
test('DNS error', function(t) {
t.plan(3);
xhr('http://a.b.c.d/', function(err, resp) {
t.ok(err);
t.equal(err.type || 'error', 'error');
t.equal(resp, null);
}, true);
});
|
mihaelamj/XcodeTemplates | Templates/Project Templates/macOS/Other/Screen Saver.xctemplate/___PACKAGENAMEASIDENTIFIER___View.h | //___FILEHEADER___
#import <ScreenSaver/ScreenSaver.h>
@interface ___PACKAGENAMEASIDENTIFIER___View : ScreenSaverView
@end
|
YIHONG-JIN/Solution-for-C-Primer-Plus-the-6th- | Chapter 3/Practice/7.c | #include <stdio.h>
#define Inch_To_CM 2.54
int main(void)
{
float inch, cm;
printf("Enter the inch of your height:\n");
scanf("%f", &inch);
cm = inch*Inch_To_CM;
printf("Hi, you are %.2f inch, or %.2f cm heigh\n", inch, cm);
return 0;
} |
Acidburn0zzz/nunuStudio | source/core/postprocessing/pass/DotScreenPass.js | "use strict";
/**
* DotScreen pass generates a poster like effect on top of the scene.
*
* @class DotScreenPass
* @constructor
* @module Postprocessing
* @author alteredq / http://alteredqualia.com/
* @param {Number} center Dot rotation center.
* @param {Number} angle Dot rotation angle.
* @param {Number} scale Dot scale.
*/
/**
* Center of rotation of the dot grid in normalized coordinates.
*
* @property center
* @type {Vector2}
*/
/**
* Rotation of the dot grid.
*
* @property angle
* @type {Number}
*/
/**
* Scale of the dots used in the effect.
*
* @property scale
* @type {Number}
*/
function DotScreenPass(center, angle, scale)
{
if(THREE.DotScreenShader === undefined)
{
console.error("DotScreenPass relies on THREE.DotScreenShader");
}
Pass.call(this);
this.type = "DotScreen";
this.uniforms = THREE.UniformsUtils.clone(THREE.DotScreenShader.uniforms);
if(center !== undefined)
{
this.uniforms["center"].value.copy(center);
}
this.uniforms["angle"].value = angle !== undefined ? angle : 0.5;
this.uniforms["scale"].value = scale !== undefined ? scale : 0.8;
this.material = new THREE.ShaderMaterial({
uniforms: this.uniforms,
vertexShader: THREE.DotScreenShader.vertexShader,
fragmentShader: THREE.DotScreenShader.fragmentShader
});
this.camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
this.scene = new THREE.Scene();
this.quad = new THREE.Mesh(new THREE.PlaneBufferGeometry(2, 2), null);
this.quad.frustumCulled = false;
this.scene.add(this.quad);
//Setters and getters for uniforms
var self = this;
Object.defineProperties(this,
{
center:
{
get: function() {return this.uniforms["center"].value;},
set: function(value) {this.uniforms["center"].value = value;}
},
angle:
{
get: function() {return this.uniforms["angle"].value;},
set: function(value) {this.uniforms["angle"].value = value;}
},
scale:
{
get: function() {return this.uniforms["scale"].value;},
set: function(value) {this.uniforms["scale"].value = value;}
}
});
};
DotScreenPass.prototype = Object.create(Pass.prototype);
DotScreenPass.prototype.render = function(renderer, writeBuffer, readBuffer, delta, maskActive, scene, camera)
{
this.uniforms["tDiffuse"].value = readBuffer.texture;
this.uniforms["tSize"].value.set(readBuffer.width, readBuffer.height);
this.quad.material = this.material;
if(this.renderToScreen)
{
renderer.render(this.scene, this.camera);
}
else
{
renderer.render(this.scene, this.camera, writeBuffer, this.clear);
}
};
DotScreenPass.prototype.toJSON = function(meta)
{
var data = Pass.prototype.toJSON.call(this, meta);
data.center = this.center.toArray();
data.angle = this.angle;
data.scale = this.scale;
return data;
};
|
ebi-uniprot/uniprot-store | integration-test/src/main/java/org/uniprot/store/indexer/search/DocFieldTransformer.java | <gh_stars>1-10
package org.uniprot.store.indexer.search;
import java.lang.reflect.Field;
import java.util.function.Consumer;
import org.uniprot.store.search.document.Document;
/**
* Required to capture and modify the {@code value} of Solr {@code @Field("value")} annotations.
* This is necessary for testing purposes. See {@link FullCIAnalysisSearchIT}.
*
* <p>Created 02/07/18
*
* @author Edd
*/
public class DocFieldTransformer implements Consumer<Document> {
private final String field;
private final Object value;
private DocFieldTransformer(String field, Object value) {
this.field = field;
this.value = value;
}
public static DocFieldTransformer fieldTransformer(String field, Object value) {
return new DocFieldTransformer(field, value);
}
@Override
public void accept(Document doc) {
Class<? extends Document> c = doc.getClass();
try {
boolean updated = false;
for (Field declaredField : c.getDeclaredFields()) {
if (declaredField.isAnnotationPresent(
org.apache.solr.client.solrj.beans.Field.class)) {
org.apache.solr.client.solrj.beans.Field declaredAnnotation =
declaredField.getDeclaredAnnotation(
org.apache.solr.client.solrj.beans.Field.class);
if (declaredAnnotation.value().equals(this.field)) {
declaredField.set(doc, value);
updated = true;
}
}
}
if (!updated) {
throw new IllegalStateException(
"Cannot transform document, field does not exist: " + this.field);
}
} catch (IllegalAccessException e) {
throw new IllegalStateException("Cannot transform document", e);
}
}
}
|
jsonnull/aleamancer | integration_tests/pages/__tests__/index.tests.js | <gh_stars>1-10
// @flow
import React from 'react'
import { mount } from 'enzyme'
import App, { setupStore } from '../../appContainer'
import Pages from 'frontend/routes'
describe('App container', () => {
let store, wrapper
beforeEach(() => {
store = setupStore()
wrapper = mount(
<App store={store}>
<Pages />
</App>
)
})
it('should pass', () => {
expect(true).toBe(true)
})
})
|
bhardwajpandya/Java-programming | Tutorials/Tutorial 05/Tut05Ex01Q01/Main.java | <reponame>bhardwajpandya/Java-programming
// Write a simple program that calculates the square root of a number (Math.sqrt()).
// Identify the exception that can occur and write code to handle this using a try catch block.
import java.util.InputMismatchException; // Import InputMismatchException
import java.util.Scanner; // Import the Scanner class
public class Main { // Main class
public static void main(String[] args) { // main method
Scanner input = new Scanner(System.in); // Create a scanner object
try {
System.out.print("Enter a number: "); // Prompt the user to enter a number
double num = input.nextDouble(); // Store the number entered by the user
double sqrt = Math.sqrt(num); // Calculate the square root of the number
if(Double.isNaN(sqrt)) { // If the number is not a number
throw new ArithmeticException("Answer unreal"); // Throw an exception
}
System.out.println("The square root of " + num + " is " + sqrt); // Print the answer
}
catch (InputMismatchException e) { // If the user enters a non-numeric value
System.out.println(e); // Print the exception
System.out.println("Invalid input"); // Print an error message
}
catch (ArithmeticException e) { // If the number is not a number
System.out.println(e.getMessage()); // Print the exception
}
input.close(); // Close the scanner object
}
} |
btrekkie/graphql | src/graphql/scalar_descriptors/strict/__init__.py | """Contains strict GraphQlScalarDescriptors for the built-in scalar types.
Contains strictly validating GraphQlScalarDescriptors for the built-in
scalar types. By "strictly validating", we mean that Python methods and
attributes that return field values of scalar types must return values
strictly of those scalar types. For example, a field of type Int may
not return the string '123'. Strict validation only applies to result
coercion, not input coercion.
"""
from boolean import GraphQlStrictBooleanDescriptor
from float import GraphQlStrictFloatDescriptor
from id import GraphQlStrictIdDescriptor
from int import GraphQlStrictIntDescriptor
from string import GraphQlStrictStringDescriptor
|
digikid/volga-coffee-fest | src/javascripts/import/modules.js | window.jQuery = window.$ = require('jquery');
require('js.device.detector/dist/jquery.device.detector.js');
require('intersection-observer');
require('@fancyapps/fancybox');
// require('jquery-mask-plugin');
// require('@popperjs/core/dist/umd/popper.min.js');
// require('air-datepicker');
const Swiper = require('swiper');
//const SimpleBar = require('simplebar');
const Rellax = require('rellax');
const lozad = require('lozad');
//const tippy = require('tippy.js/dist/tippy.umd.min.js'); |
senpl/quack | dal/src/main/java/com/testquack/dal/CommentRepositoryCustom.java | package com.testquack.dal;
public interface CommentRepositoryCustom {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.