repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
infopark-customers/bima-shark-sdk
|
lib/shark/form_service/form/text_field.rb
|
<filename>lib/shark/form_service/form/text_field.rb
# frozen_string_literal: true
module Shark
module FormService
module Form
class TextField < Element
def pre_text
attribute_definition('pre_text')['value']
end
def post_text
attribute_definition('post_text')['value']
end
end
end
end
end
|
ron4fun/IntXLib4CPP
|
IntXLib/src/Dividers/IDivider.h
|
#pragma once
#ifndef IDIVIDER_H
#define IDIVIDER_H
// data types
typedef unsigned long long UInt64;
typedef unsigned int UInt32;
#include "../IntX.h"
// Divider class interface.
class IDivider
{
public:
/// <summary>
/// Divides one <see cref="IntX" /> by another.
/// </summary>
/// <param name="int1">First big integer.</param>
/// <param name="int2">Second big integer.</param>
/// <param name="modRes">Remainder big integer.</param>
/// <param name="resultFlags">Which operation results to return.</param>
/// <returns>Divident big integer.</returns>
virtual IntX DivMod(const IntX &int1, const IntX &int2, IntX &modRes, DivModResultFlags resultFlags) = 0;
/// <summary>
/// Divides two big integers.
/// Also modifies <paramref name="digitsPtr1" /> and <paramref name="length1"/> (it will contain remainder).
/// </summary>
/// <param name="digitsPtr1">First big integer digits.</param>
/// <param name="digitsBufferPtr1">Buffer for first big integer digits. May also contain remainder.</param>
/// <param name="length1">First big integer length.</param>
/// <param name="digitsPtr2">Second big integer digits.</param>
/// <param name="digitsBufferPtr2">Buffer for second big integer digits. Only temporarily used.</param>
/// <param name="length2">Second big integer length.</param>
/// <param name="digitsResPtr">Resulting big integer digits.</param>
/// <param name="resultFlags">Which operation results to return.</param>
/// <param name="cmpResult">Big integers comparsion result (pass -2 if omitted).</param>
/// <returns>Resulting big integer length.</returns>
virtual UInt32 DivMod(
UInt32* digitsPtr1,
UInt32* digitsBufferPtr1,
UInt32 &length1,
UInt32* digitsPtr2,
UInt32* digitsBufferPtr2,
UInt32 length2,
UInt32* digitsResPtr,
DivModResultFlags resultFlags,
int cmpResult) = 0;
virtual UInt32 DivMod(
vector<UInt32> &digits1,
vector<UInt32> &digitsBuffer1,
UInt32 &length1,
vector<UInt32> &digits2,
vector<UInt32> &digitsBuffer2,
UInt32 length2,
vector<UInt32> &digitsRes,
DivModResultFlags resultFlags,
int cmpResult) = 0;
}; // end class IDivider
#endif // !IDIVIDER_H
|
chm-dev/amazfitGTSwatchfaceBundle
|
src/utils/pythonSrc/watchFaceParser/models/elements/status/unlockedElement.py
|
from watchFaceParser.models.elements.common.switchElement import SwitchElement
class UnlockedElement(SwitchElement):
def __init__(self, parameter, parent, name = None):
super(UnlockedElement, self).__init__(parameter = parameter, parent = parent, name = name)
def switchState(self, state):
return state.getUnlocked()
|
atelechev/astrocadre
|
tools/data-import/src/test/java/fr/atelechev/astrocadre/tools/dataimport/model/SegmentFactoryTest.java
|
package fr.atelechev.astrocadre.tools.dataimport.model;
import fr.atelechev.astrocadre.tools.dataimport.AbstractTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.Assert.assertEquals;
public class SegmentFactoryTest extends AbstractTest {
@Autowired
private SegmentFactory factory;
@Test
public void fromCsvRow_ReturnsExpectedSegment() {
final String csv = "1,ORI,4.830833,6.950000,4.843611,8.900000";
final Segment segment = factory.fromCsvRow(csv);
final Segment expected = segment(4.830833, 6.95,4.843611,8.9);
assertEquals(expected, segment);
}
private Segment segment(double ra0, double dec0, double ra1, double dec1) {
final Segment segment = new Segment();
segment.setRa0(ra0);
segment.setRa1(ra1);
segment.setDecl0(dec0);
segment.setDecl1(dec1);
return segment;
}
}
|
luyl1017713252/python
|
orm2.0/app02/models.py
|
<filename>orm2.0/app02/models.py<gh_stars>0
from django.db import models
# Create your models here.
class Foo(models.Model):
title=models.CharField(max_length=32)
|
john-breton/OOPDesign-MobileServiceManagement
|
src/main/java/reportingservice/ReportingService.java
|
<filename>src/main/java/reportingservice/ReportingService.java<gh_stars>0
package reportingservice;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import static reportingservice.PropertyNameStrings.*;
/**
* This is a concrete implementation of the Reporting Service. It is both an
* observer and observable. It fulfills the automatic reports requirement.
* <p>
* The class listens for changes in the management classes, and will respond by
* sending out commands to the management classes in order to have them print
* out information.
* <p>
* This class adds/removes observers (PropertyChangeListeners) who listen for
* its commands. For the midterm, these listeners would be the management
* services.
* <p>
* In order to expand this class, PropertyChangeEvent propertyNames must meet
* the required formatting:
* <p>
* propertyNames from Management classes should be in the format of:
* <p>
* "ManagementType::DetailType"
* <p>
* e.g. "Account::New" propertyNames
*
* @author <NAME>
* @version December 31, 2020
* @since December 30, 2020
*/
public class ReportingService extends AbstractReportingService {
private static final ReportingService UNIQUE_INSTANCE = new ReportingService();
private PropertyChangeSupport support;
/**
* Constructor for ReportingService.
*/
private ReportingService() {
support = new PropertyChangeSupport(this);
}
/**
* getInstance method to ensure this class is a singleton
*/
public static ReportingService getInstance() {
return UNIQUE_INSTANCE;
}
/**
* Adds listeners to this class.
*
* @param pcl a property change listener
*/
public void addPropertyChangeListener(PropertyChangeListener pcl) {
support.addPropertyChangeListener(pcl);
}
/**
* Removes listeners to this class.
*
* @param pcl a property change listener
*/
public void removePropertyChangeListener(PropertyChangeListener pcl) {
support.removePropertyChangeListener(pcl);
}
/**
* This method is called whenever a management service has a special change
* (e.g. new account, updating user, new bundle)
* <p>
* It will respond by sending out the corresponding command to its listeners
*
* @param event an event from the management classes indicating the change
*/
@Override
public void propertyChange(PropertyChangeEvent event) {
// property should be in format of "ManagementType::DetailType"
// e.g. "Account::New"
String property = event.getPropertyName();
String managementType = property.substring(0, property.indexOf(PROPERTY_CHANGE_SCOPE_DELIMITER));
String detailType = property.substring(
property.indexOf(PROPERTY_CHANGE_SCOPE_DELIMITER) + PROPERTY_CHANGE_SCOPE_DELIMITER.length());
switch (managementType) {
case ACCOUNT:
switch (detailType) {
case NEW:
support.firePropertyChange(PRINT_ACCOUNT_ADDED, event.getOldValue(), event.getNewValue());
break;
case UPDATING:
case UPDATED:
support.firePropertyChange(PRINT_ACCOUNT_DETAILS, event.getOldValue(), event.getNewValue());
break;
case DELETE:
// The below check is wild... apparently if we don't convert to string before comparing 'SPECIAL' != 'SPECIAL'
if (event.getOldValue().toString().equals(Events.SPECIAL.getDesc())) {
support.firePropertyChange(DELETE_USER, event.getOldValue(), event.getNewValue());
} else {
support.firePropertyChange(PRINT_ACCOUNT_DELETED, event.getOldValue(), event.getNewValue());
}
break;
case DISPLAY:
if (event.getNewValue().equals(USER)) {
support.firePropertyChange(PRINT_USER_DETAILS, Events.SUCCESS.getDesc(), event.getOldValue());
} else if (event.getNewValue().equals(BUNDLE)) {
support.firePropertyChange(PRINT_BUNDLE_DETAILS, event.getOldValue(), Events.SINGLE.getDesc());
} else if (event.getNewValue().toString().equals(ACCOUNT)) {
support.firePropertyChange(PRINT_ACCOUNT_DETAILS, Events.SUCCESS.getDesc(), event.getOldValue());
} else {
support.firePropertyChange(PRINT_ACCOUNT_DETAILS, Events.FAILURE.getDesc(), event.getOldValue());
}
break;
case FIND:
if (event.getOldValue().equals(Events.SUCCESS.getDesc())) {
support.firePropertyChange(GET_ACCOUNT, event.getOldValue(), event.getNewValue());
} else if (event.getOldValue().equals(Events.SPECIAL.getDesc())) {
support.firePropertyChange(FIND_ACCOUNTS, event.getOldValue(), event.getNewValue());
}
break;
case LIST:
if (event.getOldValue().equals(Events.SUCCESS.getDesc())) {
support.firePropertyChange(GET_ACCOUNT_FEES, event.getOldValue(), event.getNewValue());
} else if (event.getOldValue().equals(Events.SPECIAL.getDesc())) {
support.firePropertyChange(FIND_ACCOUNTS_FEES, event.getOldValue(), event.getNewValue());
}
break;
default:
break;
}
break;
case USER:
switch (detailType) {
case NEW:
support.firePropertyChange(PRINT_USER_ADDED, event.getOldValue(), event.getNewValue());
break;
case UPDATING:
support.firePropertyChange(PRINT_USER_UPDATING, event.getOldValue(), event.getNewValue());
break;
case UPDATED:
support.firePropertyChange(PRINT_USER_UPDATED, event.getOldValue(), event.getNewValue());
break;
case DELETE:
if (event.getOldValue().equals(Events.SUCCESS.getDesc())) {
support.firePropertyChange(DELETE_ACCOUNT, event.getOldValue(), event.getNewValue());
}
support.firePropertyChange(PRINT_USER_DELETED, event.getOldValue(), event.getNewValue());
break;
case DISPLAY:
if (event.getNewValue() == null) {
support.firePropertyChange(PRINT_USER_LIST, event.getOldValue(), event.getNewValue());
} else {
support.firePropertyChange(PRINT_USER_DETAILS, event.getOldValue(), event.getNewValue());
}
break;
default:
break;
}
break;
case BUNDLE:
switch (detailType) {
case NEW:
support.firePropertyChange(PRINT_BUNDLE_ADDED, event.getOldValue(), event.getNewValue());
break;
case DISPLAY:
support.firePropertyChange(PRINT_BUNDLE_DETAILS, event.getOldValue(), event.getNewValue());
break;
default:
break;
}
break;
}
}
}
|
daoxuantungframgia/Chicken
|
src/routes/ProductDetailPage/components/Promotions/Promotions.js
|
<filename>src/routes/ProductDetailPage/components/Promotions/Promotions.js
import React from 'react'
import PropTypes from 'prop-types'
const Promotions = ({ promotions }) => (
<ul>
{ promotions && promotions.map((promotion) => (
<li key={promotion.promDetailId}>
{(() => {
if (promotion.promType === 0) {
return 'ฦฐu ฤรฃi chรญnh'
} else {
const fromString = `Nแบฟu bแบกn mua tแปซ ${promotion.fromQuantity} `
const toString = promotion.toQuantity ? `ฤแบฟn ${promotion.toQuantity}` : ''
return `${fromString}${toString} sแบฃn phแบฉm bแบกn sแบฝ ฤฦฐแปฃc ฦฐu ฤรฃi thรชm ${promotion.value}%`
}
})()}
</li>
)) }
</ul>
)
Promotions.propTypes = {
promotions: PropTypes.array
}
export default Promotions
|
Loks-/competitions
|
timus/main.cpp
|
#include "common/proxy_run_main.h"
#include <iostream>
#include <string>
int main(int nargs, char **pargs) {
std::string solution_name;
if (nargs >= 2) {
solution_name = pargs[1];
} else {
std::cout << "Input timus solution to run:" << std::endl;
std::cin >> solution_name;
}
return ProxyAuto(solution_name, (nargs > 2) ? pargs[2] : "",
(nargs > 3) ? pargs[3] : "");
}
|
bnguyen82/stuff-projects
|
design/src/abstractfactory/restaurant/VNPizzaRestaurant.java
|
<gh_stars>0
package abstractfactory.restaurant;
import abstractfactory.product.Beverage;
import abstractfactory.product.Pizza;
import abstractfactory.product.vn.VNBeverage;
import abstractfactory.product.vn.VNPizza;
public class VNPizzaRestaurant extends PizzaRestaurant {
@Override
public Beverage deliverBeverage() {
return new VNBeverage();
}
@Override
public Pizza deliverPizza() {
return new VNPizza();
}
}
|
adamlwgriffiths/Razorback
|
razorback/input/mouse.py
|
'''
Created on 28/06/2011
@author: adam
'''
import numpy
from pyglet.gl import *
import pyglet.window.mouse
from analog import Analog
class Mouse( object ):
x = 0
y = 1
# allow access to pyglet.window.mouse
buttons = pyglet.window.mouse
def __init__( self, window, name = 'mouse' ):
super( Mouse, self ).__init__()
self.name = name
self.window = window
self.axis = [
Analog( self.name, 'x' ),
Analog( self.name, 'y' )
]
self.window.push_handlers(
on_mouse_motion = self.on_mouse_motion
)
def __del__( self ):
if self.window != None:
self.window.remove_handlers( self, self )
def on_mouse_motion( self, x, y, dx, dy ):
self.axis[ Mouse.x ].value_changed( x, dx )
self.axis[ Mouse.y ].value_changed( y, dy )
def clear_delta( self ):
for axis in self.axis:
axis.clear_delta()
def axis_x( self ):
return self.axis[ Mouse.x ]
def axis_y( self ):
return self.axis[ Mouse.y ]
@property
def absolute_position( self ):
return [
self.axis[ Mouse.x ].value,
self.axis[ Mouse.y ].value
]
@property
def relative_position( self ):
return [
self.axis[ Mouse.x ].delta,
self.axis[ Mouse.y ].delta
]
if __name__ == '__main__':
from pyglet.gl import *
window = pyglet.window.Window( fullscreen = False )
mouse = Mouse( window )
"""
def update( dt ):
global mouse
print mouse.absolute_position
global window
window.close()
pyglet.clock.schedule_interval( update, (1.0 / 60.0) )
"""
def update( analog, value ):
global mouse
print "[%s] %s: absolute: %f relative: %f" % (
analog.device,
analog.axis,
value[ 0 ],
value[ 1 ]
)
window.close()
mouse.axis_x().push_handlers( on_analog_input = update )
pyglet.app.run()
|
Reiex/SplayLibrary
|
include/SplayLibrary/3D/types.hpp
|
#pragma once
#include <SplayLibrary/Core/Core.hpp>
#include <Diskon/Diskon.hpp>
namespace spl
{
class Transformable3D;
class PerspectiveCamera;
struct VertexBase;
struct DefaultVertex;
template<typename VertexType> class Mesh;
}
|
ActionAnalytics/mds
|
microservices/nris_api/backend/tests/constants.py
|
from app.nris.utils.access_decorators import NRIS_VIEW #, NRIS_CREATE, NRIS_CREATE, MINESPACE_PROPONENT
# Auth Constants
TOKEN_HEADER = {"alg": "RS256", "typ": "JWT", "kid": "flask-jwt-oidc-test-client"}
BASE_AUTH_CLAIMS = {
"iss": "test_issuer",
"sub": "43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc",
"aud": "test_audience",
"exp": 21531718745,
"iat": 1531718745,
"jti": "flask-jwt-oidc-test-support",
"typ": "Bearer",
"username": "test-user",
"realm_access": {
"roles": ["idir"]
}
}
FULL_AUTH_CLAIMS = {
"iss": "test_issuer",
"sub": "43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc",
"aud": "test_audience",
"exp": 21531718745,
"iat": 1531718745,
"jti": "flask-jwt-oidc-test-support",
"typ": "Bearer",
"username": "test-user",
"preferred_username": "test-user",
"email": "test-email",
"given_name": "test-given-name",
"realm_access": {
"roles": [NRIS_VIEW, "idir"]
#"roles": [NRIS_VIEW, NRIS_CREATE, NRIS_ADMIN, "idir"]
}
}
NRIS_VIEW_ONLY_AUTH_CLAIMS = {
"iss": "test_issuer",
"sub": "43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc",
"aud": "test_audience",
"exp": 21531718745,
"iat": 1531718745,
"jti": "flask-jwt-oidc-test-support",
"typ": "Bearer",
"username": "test-user",
"email": "test-email",
"realm_access": {
"roles": [NRIS_VIEW, "idir"]
}
}
# CREATE_ONLY_AUTH_CLAIMS = {
# "iss": "test_issuer",
# "sub": "43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc",
# "aud": "test_audience",
# "exp": 21531718745,
# "iat": 1531718745,
# "jti": "flask-jwt-oidc-test-support",
# "typ": "Bearer",
# "username": "test-user",
# "realm_access": {
# "roles": [NRIS_CREATE, "idir"]
# }
# }
# ADMIN_ONLY_AUTH_CLAIMS = {
# "iss": "test_issuer",
# "sub": "43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc",
# "aud": "test_audience",
# "exp": 21531718745,
# "iat": 1531718745,
# "jti": "flask-jwt-oidc-test-support",
# "typ": "Bearer",
# "username": "test-user",
# "realm_access": {
# "roles": [NRIS_ADMIN, "idir"]
# }
# }
# PROPONENT_ONLY_AUTH_CLAIMS = {
# "iss": "test_issuer",
# "sub": "43e6a245-0bf7-4ccf-9bd0-e7fb85fd18cc",
# "aud": "test_audience",
# "exp": 21531718745,
# "iat": 1531718745,
# "jti": "flask-jwt-oidc-test-support",
# "typ": "Bearer",
# "username": "test-proponent",
# "email": "<EMAIL>",
# "realm_access": {
# "roles": [MINESPACE_PROPONENT]
# }
# }
|
mehrdad-shokri/cartodb
|
app/models/client_application.rb
|
require 'oauth'
class DomainPatcherRequestProxy < OAuth::RequestProxy::RackRequest
def uri
super.sub('carto.com', 'cartodb.com')
end
end
class ClientApplication < Sequel::Model
extend CartoDB::ConfigUtils
one_to_many :tokens, :class_name => :OauthToken
one_to_many :access_tokens
one_to_many :oauth_tokens
plugin :association_dependencies
add_association_dependencies :oauth_tokens => :destroy
attr_accessor :token_callback_url
def self.find_token(token_key)
return nil if token_key.nil?
token = ::RequestToken.first(:token => token_key) || ::AccessToken.first(:token => token_key)
token && token.authorized? ? token : nil
end
def self.find_by_key(key)
first(:key => key)
end
def user
::User[user_id]
end
def user=(value)
set(:user_id => value.id)
end
def self.verify_request(request, options = {}, &block)
value = OAuth::Signature.build(request, options, &block).verify
if !value && !cartodb_com_hosted?
# Validation failed, try to see if it has been signed for cartodb.com
cartodb_request = DomainPatcherRequestProxy.new(request, options)
value = OAuth::Signature.build(cartodb_request, options, &block).verify
end
value
rescue OAuth::Signature::UnknownSignatureMethod
false
end
def oauth_server
@oauth_server ||= OAuth::Server.new("http://your.site")
end
def credentials
@oauth_client ||= OAuth::Consumer.new(key, secret)
end
# If your application requires passing in extra parameters handle it here
def create_request_token(params={})
RequestToken.create :client_application => self, :callback_url=>self.token_callback_url
end
def before_create
self.key = OAuth::Helper.generate_key(40)[0,40]
self.secret = OAuth::Helper.generate_key(40)[0,40]
self.created_at = Time.now
end
def before_save
self.updated_at = Time.now
end
end
|
zhaoq0103/zhaoq0103.github.io
|
architect/code/springdemos/springdemo-aop/src/main/java/com/zhaoq/aop02/MyAroundAdvice.java
|
package com.zhaoq.aop02;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* ๅขๅผบ็็ฑป:
* ไฝฟ็จ็ๆฏ็ฏ็ปๅขๅผบ
*
*/
public class MyAroundAdvice implements MethodInterceptor{
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("็ฏ็ปๅๅขๅผบ...");
Object result = methodInvocation.proceed();// ๆง่ก็ฎๆ ๅฏน่ฑก็ๆนๆณ
System.out.println("็ฏ็ปๅๅขๅผบ...");
return result;
}
}
|
tie/Valkyrien-Skies
|
src/main/java/org/valkyrienskies/mod/common/physmanagement/shipdata/IBlockPosSet.java
|
<filename>src/main/java/org/valkyrienskies/mod/common/physmanagement/shipdata/IBlockPosSet.java<gh_stars>0
package org.valkyrienskies.mod.common.physmanagement.shipdata;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Nonnull;
import net.minecraft.util.math.BlockPos;
public interface IBlockPosSet extends Set<BlockPos> {
boolean add(int x, int y, int z);
boolean remove(int x, int y, int z);
boolean contains(int x, int y, int z);
boolean canStore(int x, int y, int z);
void clear();
default boolean add(BlockPos pos) {
return add(pos.getX(), pos.getY(), pos.getZ());
}
default boolean remove(BlockPos pos) {
return remove(pos.getX(), pos.getY(), pos.getZ());
}
default boolean contains(BlockPos pos) {
return contains(pos.getX(), pos.getY(), pos.getZ());
}
default boolean canStore(BlockPos pos) {
return canStore(pos.getX(), pos.getY(), pos.getZ());
}
default boolean containsAll(Collection<?> c) {
for (Object o : c) {
if (!contains(o)) {
return false;
}
}
return true;
}
default boolean addAll(Collection<? extends BlockPos> c) {
boolean modified = false;
for (BlockPos pos : c) {
modified |= add(pos);
}
return modified;
}
default boolean removeAll(Collection<?> c) {
boolean modified = false;
for (Object o : c) {
modified |= remove(o);
}
return modified;
}
default boolean retainAll(@Nonnull Collection<?> c) {
boolean modified = false;
for (BlockPos pos : this) {
if (!c.contains(pos)) {
remove(pos);
modified = true;
}
}
return modified;
}
default boolean isEmpty() {
return size() == 0;
}
default boolean remove(Object o) {
if (o instanceof BlockPos) {
return remove((BlockPos) o);
} else {
return false;
}
}
default boolean contains(Object o) {
if (o instanceof BlockPos) {
return contains((BlockPos) o);
} else {
return false;
}
}
@Nonnull
default Object[] toArray() {
BlockPos[] arr = new BlockPos[size()];
Iterator<BlockPos> iter = iterator();
for (int i = 0; i < size(); i++) {
arr[i] = iter.next();
}
return arr;
}
@Nonnull
@Override
@SuppressWarnings("unchecked")
default <T> T[] toArray(@Nonnull T[] a) {
return (T[]) toArray();
}
}
|
dannycho7/RTP_Latest
|
src/archive_lucene/archive_lucene/src/org/apache/lucene/search/ReqOptSumScorer.java
|
package org.apache.lucene.search;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
/** A Scorer for queries with a required part and an optional part.
* Delays skipTo() on the optional part until a score() is needed.
* <br>
* This <code>Scorer</code> implements {@link Scorer#skipTo(int)}.
*/
class ReqOptSumScorer extends Scorer {
/** The scorers passed from the constructor.
* These are set to null as soon as their next() or skipTo() returns false.
*/
private Scorer reqScorer;
private Scorer optScorer;
/** Construct a <code>ReqOptScorer</code>.
* @param reqScorer The required scorer. This must match.
* @param optScorer The optional scorer. This is used for scoring only.
*/
public ReqOptSumScorer(
Scorer reqScorer,
Scorer optScorer)
{
super(null); // No similarity used.
this.reqScorer = reqScorer;
this.optScorer = optScorer;
}
@Override
public int nextDoc() throws IOException {
return reqScorer.nextDoc();
}
@Override
public int advance(int target) throws IOException {
return reqScorer.advance(target);
}
@Override
public int docID() {
return reqScorer.docID();
}
/** Returns the score of the current document matching the query.
* Initially invalid, until {@link #next()} is called the first time.
* @return The score of the required scorer, eventually increased by the score
* of the optional scorer when it also matches the current document.
*/
@Override
public float score() throws IOException {
int curDoc = reqScorer.docID();
float reqScore = reqScorer.score();
if (optScorer == null) {
return reqScore;
}
int optScorerDoc = optScorer.docID();
if (optScorerDoc < curDoc && (optScorerDoc = optScorer.advance(curDoc)) == NO_MORE_DOCS) {
optScorer = null;
return reqScore;
}
return optScorerDoc == curDoc ? reqScore + optScorer.score() : reqScore;
}
}
|
venkyvb/OpenUnison
|
unison/unison-lastmile-sdk/src/main/java/com/tremolosecurity/lastmile/custom/CustomLastMile.java
|
/*
Copyright 2015 Tremolo Security, 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.tremolosecurity.lastmile.custom;
import javax.servlet.FilterConfig;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tremolosecurity.lastmile.LastMile;
public interface CustomLastMile {
public void postValidate(HttpServletRequest request,HttpServletResponse response,LastMile lastMile) throws Exception;
public void afterInit(FilterConfig config) throws ServletException;
}
|
stas-vilchik/bdd-ml
|
data/11710.js
|
<gh_stars>0
{
if (depth === 1 && currentBlock) {
currentBlock.end = start;
var text = deindent(content.slice(currentBlock.start, currentBlock.end));
if (currentBlock.type !== "template" && options.pad) {
text = padContent(currentBlock, options.pad) + text;
}
currentBlock.content = text;
currentBlock = null;
}
depth--;
}
|
rodrigojv/thisvui
|
src/mixins/columns.js
|
import utils from "../utils/utils";
import CssArchitect from "../utils/css-architect";
export default {
props: {
isThreeQuarters: {
type: [String, Boolean]
},
isTwoThirds: {
type: [String, Boolean]
},
isHalf: {
type: [String, Boolean]
},
isOneThird: {
type: [String, Boolean]
},
isOneQuarter: {
type: [String, Boolean]
},
isFourFifths: {
type: [String, Boolean]
},
isThreeFifths: {
type: [String, Boolean]
},
isTwoFifths: {
type: [String, Boolean]
},
isOneFifth: {
type: [String, Boolean]
},
isOffset: {
type: String
},
isNarrow: {
type: [String, Boolean]
},
isNarrowMobile: {
type: [String, Boolean]
},
isNarrowTablet: {
type: [String, Boolean]
},
isNarrowTouch: {
type: [String, Boolean]
},
isNarrowDesktop: {
type: [String, Boolean]
},
isNarrowWidescreen: {
type: [String, Boolean]
},
isNarrowFullhd: {
type: [String, Boolean]
}
},
computed: {
/**
* Dynamically adds the modifiers css classes based on mixin props
* @returns { A String with the chained css classes }
*/
getColumnModifiers: function() {
const cssArchitect = new CssArchitect();
cssArchitect.addClass(
"is-three-quarters",
utils.convert.stringToBoolean(this.isThreeQuarters)
);
cssArchitect.addClass(
"is-two-thirds",
utils.convert.stringToBoolean(this.isTwoThirds)
);
cssArchitect.addClass(
"is-half",
utils.convert.stringToBoolean(this.isHalf)
);
cssArchitect.addClass(
"is-one-third",
utils.convert.stringToBoolean(this.isOneThird)
);
cssArchitect.addClass(
"is-one-quarter",
utils.convert.stringToBoolean(this.isOneQuarter)
);
cssArchitect.addClass(
"is-four-fifths",
utils.convert.stringToBoolean(this.isFourFifths)
);
cssArchitect.addClass(
"is-three-fifths",
utils.convert.stringToBoolean(this.isThreeFifths)
);
cssArchitect.addClass(
"is-two-fifths",
utils.convert.stringToBoolean(this.isTwoFifths)
);
cssArchitect.addClass(
"is-one-fifth",
utils.convert.stringToBoolean(this.isOneFifth)
);
cssArchitect.addClass(
"is-narrow",
utils.convert.stringToBoolean(this.isNarrow)
);
cssArchitect.addClass(
"is-narrow-mobile",
utils.convert.stringToBoolean(this.isNarrowMobile)
);
cssArchitect.addClass(
"is-narrow-tablet",
utils.convert.stringToBoolean(this.isNarrowTablet)
);
cssArchitect.addClass(
"is-narrow-touch",
utils.convert.stringToBoolean(this.isNarrowTouch)
);
cssArchitect.addClass(
"is-narrow-desktop",
utils.convert.stringToBoolean(this.isNarrowDesktop)
);
cssArchitect.addClass(
"is-narrow-widescreen",
utils.convert.stringToBoolean(this.isNarrowWidescreen)
);
cssArchitect.addClass(
"is-narrow-fullhd",
utils.convert.stringToBoolean(this.isNarrowFullhd)
);
cssArchitect.addClass(
`is-offset-${this.isOffset}`,
this.isOffset !== undefined
);
return cssArchitect.getClasses();
}
}
};
|
sasa42/MeshSyncDCCPlugin
|
External/blender-2.79/include/blenkernel/BKE_tracking.h
|
/*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2011 Blender Foundation.
* All rights reserved.
*
* Contributor(s): Blender Foundation,
* <NAME>
*
* ***** END GPL LICENSE BLOCK *****
*/
#ifndef __BKE_TRACKING_H__
#define __BKE_TRACKING_H__
/** \file BKE_tracking.h
* \ingroup bke
* \author <NAME>
*/
struct bGPDlayer;
struct ImBuf;
struct ListBase;
struct MovieReconstructContext;
struct MovieTrackingTrack;
struct MovieTrackingMarker;
struct MovieTrackingPlaneTrack;
struct MovieTrackingPlaneMarker;
struct MovieTracking;
struct MovieTrackingObject;
struct MovieClipUser;
struct MovieDistortion;
struct Camera;
struct Object;
struct Scene;
struct rcti;
/* **** Common functions **** */
void BKE_tracking_free(struct MovieTracking *tracking);
void BKE_tracking_copy(struct MovieTracking *tracking_dst, const struct MovieTracking *tracking_src);
void BKE_tracking_settings_init(struct MovieTracking *tracking);
struct ListBase *BKE_tracking_get_active_tracks(struct MovieTracking *tracking);
struct ListBase *BKE_tracking_get_active_plane_tracks(struct MovieTracking *tracking);
struct MovieTrackingReconstruction *BKE_tracking_get_active_reconstruction(struct MovieTracking *tracking);
/* matrices for constraints and drawing */
void BKE_tracking_get_camera_object_matrix(struct Scene *scene, struct Object *ob, float mat[4][4]);
void BKE_tracking_get_projection_matrix(struct MovieTracking *tracking, struct MovieTrackingObject *object,
int framenr, int winx, int winy, float mat[4][4]);
/* **** Clipboard **** */
void BKE_tracking_clipboard_free(void);
void BKE_tracking_clipboard_copy_tracks(struct MovieTracking *tracking, struct MovieTrackingObject *object);
bool BKE_tracking_clipboard_has_tracks(void);
void BKE_tracking_clipboard_paste_tracks(struct MovieTracking *tracking, struct MovieTrackingObject *object);
/* **** Track **** */
struct MovieTrackingTrack *BKE_tracking_track_add(struct MovieTracking *tracking, struct ListBase *tracksbase,
float x, float y, int framenr, int width, int height);
struct MovieTrackingTrack *BKE_tracking_track_duplicate(struct MovieTrackingTrack *track);
void BKE_tracking_track_unique_name(struct ListBase *tracksbase, struct MovieTrackingTrack *track);
void BKE_tracking_track_free(struct MovieTrackingTrack *track);
void BKE_tracking_track_flag_set(struct MovieTrackingTrack *track, int area, int flag);
void BKE_tracking_track_flag_clear(struct MovieTrackingTrack *track, int area, int flag);
bool BKE_tracking_track_has_marker_at_frame(struct MovieTrackingTrack *track, int framenr);
bool BKE_tracking_track_has_enabled_marker_at_frame(struct MovieTrackingTrack *track, int framenr);
void BKE_tracking_track_path_clear(struct MovieTrackingTrack *track, int ref_frame, int action);
void BKE_tracking_tracks_join(struct MovieTracking *tracking, struct MovieTrackingTrack *dst_track, struct MovieTrackingTrack *src_track);
struct MovieTrackingTrack *BKE_tracking_track_get_named(struct MovieTracking *tracking,
struct MovieTrackingObject *object,
const char *name);
struct MovieTrackingTrack *BKE_tracking_track_get_indexed(struct MovieTracking *tracking, int tracknr,
struct ListBase **r_tracksbase);
struct MovieTrackingTrack *BKE_tracking_track_get_active(struct MovieTracking *tracking);
float *BKE_tracking_track_get_mask(int frame_width, int frame_height, struct MovieTrackingTrack *track,
struct MovieTrackingMarker *marker);
float BKE_tracking_track_get_weight_for_marker(struct MovieClip *clip, struct MovieTrackingTrack *track, struct MovieTrackingMarker *marker);
/* selection */
void BKE_tracking_track_select(struct ListBase *tracksbase, struct MovieTrackingTrack *track, int area, bool extend);
void BKE_tracking_track_deselect(struct MovieTrackingTrack *track, int area);
void BKE_tracking_tracks_deselect_all(struct ListBase *tracksbase);
/* **** Marker **** */
struct MovieTrackingMarker *BKE_tracking_marker_insert(struct MovieTrackingTrack *track,
struct MovieTrackingMarker *marker);
void BKE_tracking_marker_delete(struct MovieTrackingTrack *track, int framenr);
void BKE_tracking_marker_clamp(struct MovieTrackingMarker *marker, int event);
struct MovieTrackingMarker *BKE_tracking_marker_get(struct MovieTrackingTrack *track, int framenr);
struct MovieTrackingMarker *BKE_tracking_marker_get_exact(struct MovieTrackingTrack *track, int framenr);
struct MovieTrackingMarker *BKE_tracking_marker_ensure(struct MovieTrackingTrack *track, int framenr);
void BKE_tracking_marker_pattern_minmax(const struct MovieTrackingMarker *marker, float min[2], float max[2]);
void BKE_tracking_marker_get_subframe_position(struct MovieTrackingTrack *track, float framenr, float pos[2]);
/* **** Plane Track **** */
struct MovieTrackingPlaneTrack *BKE_tracking_plane_track_add(struct MovieTracking *tracking, struct ListBase *plane_tracks_base,
struct ListBase *tracks, int framenr);
void BKE_tracking_plane_track_unique_name(struct ListBase *plane_tracks_base, struct MovieTrackingPlaneTrack *plane_track);
void BKE_tracking_plane_track_free(struct MovieTrackingPlaneTrack *plane_track);
bool BKE_tracking_plane_track_has_marker_at_frame(struct MovieTrackingPlaneTrack *plane_track, int framenr);
bool BKE_tracking_plane_track_has_enabled_marker_at_frame(struct MovieTrackingPlaneTrack *plane_track, int framenr);
struct MovieTrackingPlaneTrack *BKE_tracking_plane_track_get_named(struct MovieTracking *tracking,
struct MovieTrackingObject *object,
const char *name);
struct MovieTrackingPlaneTrack *BKE_tracking_plane_track_get_active(struct MovieTracking *tracking);
void BKE_tracking_plane_tracks_deselect_all(struct ListBase *plane_tracks_base);
bool BKE_tracking_plane_track_has_point_track(struct MovieTrackingPlaneTrack *plane_track,
struct MovieTrackingTrack *track);
bool BKE_tracking_plane_track_remove_point_track(struct MovieTrackingPlaneTrack *plane_track,
struct MovieTrackingTrack *track);
void BKE_tracking_plane_tracks_remove_point_track(struct MovieTracking *tracking,
struct MovieTrackingTrack *track);
void BKE_tracking_plane_track_replace_point_track(struct MovieTrackingPlaneTrack *plane_track,
struct MovieTrackingTrack *old_track,
struct MovieTrackingTrack *new_track);
void BKE_tracking_plane_tracks_replace_point_track(struct MovieTracking *tracking,
struct MovieTrackingTrack *old_track,
struct MovieTrackingTrack *new_track);
/* **** Plane Marker **** */
struct MovieTrackingPlaneMarker *BKE_tracking_plane_marker_insert(struct MovieTrackingPlaneTrack *plane_track,
struct MovieTrackingPlaneMarker *plane_marker);
void BKE_tracking_plane_marker_delete(struct MovieTrackingPlaneTrack *plane_track, int framenr);
struct MovieTrackingPlaneMarker *BKE_tracking_plane_marker_get(struct MovieTrackingPlaneTrack *plane_track, int framenr);
struct MovieTrackingPlaneMarker *BKE_tracking_plane_marker_get_exact(struct MovieTrackingPlaneTrack *plane_track, int framenr);
struct MovieTrackingPlaneMarker *BKE_tracking_plane_marker_ensure(struct MovieTrackingPlaneTrack *plane_track, int framenr);
void BKE_tracking_plane_marker_get_subframe_corners(struct MovieTrackingPlaneTrack *plane_track,
float framenr,
float corners[4][2]);
/* **** Object **** */
struct MovieTrackingObject *BKE_tracking_object_add(struct MovieTracking *tracking, const char *name);
bool BKE_tracking_object_delete(struct MovieTracking *tracking, struct MovieTrackingObject *object);
void BKE_tracking_object_unique_name(struct MovieTracking *tracking, struct MovieTrackingObject *object);
struct MovieTrackingObject *BKE_tracking_object_get_named(struct MovieTracking *tracking, const char *name);
struct MovieTrackingObject *BKE_tracking_object_get_active(struct MovieTracking *tracking);
struct MovieTrackingObject *BKE_tracking_object_get_camera(struct MovieTracking *tracking);
struct ListBase *BKE_tracking_object_get_tracks(struct MovieTracking *tracking, struct MovieTrackingObject *object);
struct ListBase *BKE_tracking_object_get_plane_tracks(struct MovieTracking *tracking, struct MovieTrackingObject *object);
struct MovieTrackingReconstruction *BKE_tracking_object_get_reconstruction(struct MovieTracking *tracking,
struct MovieTrackingObject *object);
/* **** Camera **** */
void BKE_tracking_camera_shift_get(struct MovieTracking *tracking, int winx, int winy, float *shiftx, float *shifty);
void BKE_tracking_camera_to_blender(struct MovieTracking *tracking, struct Scene *scene,
struct Camera *camera, int width, int height);
struct MovieReconstructedCamera *BKE_tracking_camera_get_reconstructed(struct MovieTracking *tracking,
struct MovieTrackingObject *object,
int framenr);
void BKE_tracking_camera_get_reconstructed_interpolate(struct MovieTracking *tracking,
struct MovieTrackingObject *object,
float framenr, float mat[4][4]);
/* **** Distortion/Undistortion **** */
struct MovieDistortion *BKE_tracking_distortion_new(struct MovieTracking *tracking,
int calibration_width, int calibration_height);
void BKE_tracking_distortion_update(struct MovieDistortion *distortion, struct MovieTracking *tracking,
int calibration_width, int calibration_height);
void BKE_tracking_distortion_set_threads(struct MovieDistortion *distortion, int threads);
struct MovieDistortion *BKE_tracking_distortion_copy(struct MovieDistortion *distortion);
struct ImBuf *BKE_tracking_distortion_exec(struct MovieDistortion *distortion, struct MovieTracking *tracking,
struct ImBuf *ibuf, int width, int height, float overscan, bool undistort);
void BKE_tracking_distortion_distort_v2(struct MovieDistortion *distortion,
const float co[2],
float r_co[2]);
void BKE_tracking_distortion_undistort_v2(struct MovieDistortion *distortion,
const float co[2],
float r_co[2]);
void BKE_tracking_distortion_free(struct MovieDistortion *distortion);
void BKE_tracking_distort_v2(struct MovieTracking *tracking, const float co[2], float r_co[2]);
void BKE_tracking_undistort_v2(struct MovieTracking *tracking, const float co[2], float r_co[2]);
struct ImBuf *BKE_tracking_undistort_frame(struct MovieTracking *tracking, struct ImBuf *ibuf,
int calibration_width, int calibration_height, float overscan);
struct ImBuf *BKE_tracking_distort_frame(struct MovieTracking *tracking, struct ImBuf *ibuf,
int calibration_width, int calibration_height, float overscan);
void BKE_tracking_max_distortion_delta_across_bound(struct MovieTracking *tracking, struct rcti *rect,
bool undistort, float delta[2]);
/* **** Image sampling **** */
struct ImBuf *BKE_tracking_sample_pattern(int frame_width, int frame_height,
struct ImBuf *struct_ibuf, struct MovieTrackingTrack *track,
struct MovieTrackingMarker *marker, bool from_anchor, bool use_mask,
int num_samples_x, int num_samples_y, float pos[2]);
struct ImBuf *BKE_tracking_get_pattern_imbuf(struct ImBuf *ibuf, struct MovieTrackingTrack *track,
struct MovieTrackingMarker *marker, bool anchored, bool disable_channels);
struct ImBuf *BKE_tracking_get_search_imbuf(struct ImBuf *ibuf, struct MovieTrackingTrack *track,
struct MovieTrackingMarker *marker, bool anchored, bool disable_channels);
void BKE_tracking_disable_channels(struct ImBuf *ibuf, bool disable_red, bool disable_green,
bool disable_blue, bool grayscale);
/* **** 2D tracking **** */
void BKE_tracking_refine_marker(struct MovieClip *clip, struct MovieTrackingTrack *track, struct MovieTrackingMarker *marker, bool backwards);
/* *** 2D auto track *** */
struct AutoTrackContext *BKE_autotrack_context_new(struct MovieClip *clip, struct MovieClipUser *user,
const bool backwards, const bool sequence);
bool BKE_autotrack_context_step(struct AutoTrackContext *context);
void BKE_autotrack_context_sync(struct AutoTrackContext *context);
void BKE_autotrack_context_sync_user(struct AutoTrackContext *context, struct MovieClipUser *user);
void BKE_autotrack_context_finish(struct AutoTrackContext *context);
void BKE_autotrack_context_free(struct AutoTrackContext *context);
/* **** Plane tracking **** */
void BKE_tracking_track_plane_from_existing_motion(struct MovieTrackingPlaneTrack *plane_track, int start_frame);
void BKE_tracking_retrack_plane_from_existing_motion_at_segment(struct MovieTrackingPlaneTrack *plane_track, int start_frame);
void BKE_tracking_homography_between_two_quads(/*const*/ float reference_corners[4][2], /*const*/ float corners[4][2], float H[3][3]);
/* **** Camera solving **** */
bool BKE_tracking_reconstruction_check(struct MovieTracking *tracking, struct MovieTrackingObject *object,
char *error_msg, int error_size);
struct MovieReconstructContext *BKE_tracking_reconstruction_context_new(struct MovieClip *clip,
struct MovieTrackingObject *object,
int keyframe1, int keyframe2,
int width, int height);
void BKE_tracking_reconstruction_context_free(struct MovieReconstructContext *context);
void BKE_tracking_reconstruction_solve(struct MovieReconstructContext *context, short *stop, short *do_update,
float *progress, char *stats_message, int message_size);
bool BKE_tracking_reconstruction_finish(struct MovieReconstructContext *context, struct MovieTracking *tracking);
void BKE_tracking_reconstruction_scale(struct MovieTracking *tracking, float scale[3]);
/* **** Feature detection **** */
void BKE_tracking_detect_fast(struct MovieTracking *tracking, struct ListBase *tracksbase, struct ImBuf *imbuf,
int framenr, int margin, int min_trackness, int min_distance, struct bGPDlayer *layer,
bool place_outside_layer);
void BKE_tracking_detect_harris(struct MovieTracking *tracking, struct ListBase *tracksbase, struct ImBuf *ibuf,
int framenr, int margin, float threshold, int min_distance, struct bGPDlayer *layer,
bool place_outside_layer);
/* **** 2D stabilization **** */
void BKE_tracking_stabilization_data_get(struct MovieClip *clip, int framenr, int width, int height,
float translation[2], float *scale, float *angle);
struct ImBuf *BKE_tracking_stabilize_frame(struct MovieClip *clip, int framenr, struct ImBuf *ibuf,
float translation[2], float *scale, float *angle);
void BKE_tracking_stabilization_data_to_mat4(int width, int height, float aspect, float translation[2],
float scale, float angle, float mat[4][4]);
/* Dopesheet */
void BKE_tracking_dopesheet_tag_update(struct MovieTracking *tracking);
void BKE_tracking_dopesheet_update(struct MovieTracking *tracking);
#define TRACK_SELECTED(track) ((track)->flag & SELECT || (track)->pat_flag & SELECT || (track)->search_flag & SELECT)
#define TRACK_AREA_SELECTED(track, area) ((area) == TRACK_AREA_POINT ? (track)->flag & SELECT : \
((area) == TRACK_AREA_PAT ? (track)->pat_flag & SELECT : \
(track)->search_flag & SELECT))
#define TRACK_VIEW_SELECTED(sc, track) ((((track)->flag & TRACK_HIDDEN) == 0) && \
(TRACK_AREA_SELECTED(track, TRACK_AREA_POINT) || \
(((sc)->flag & SC_SHOW_MARKER_PATTERN) && TRACK_AREA_SELECTED(track, TRACK_AREA_PAT)) || \
(((sc)->flag & SC_SHOW_MARKER_SEARCH) && TRACK_AREA_SELECTED(track, TRACK_AREA_SEARCH))))
#define PLANE_TRACK_VIEW_SELECTED(plane_track) ((((plane_track)->flag & PLANE_TRACK_HIDDEN) == 0) && \
((plane_track)->flag & SELECT))
#define MARKER_VISIBLE(sc, track, marker) (((marker)->flag & MARKER_DISABLED) == 0 || ((sc)->flag & SC_HIDE_DISABLED) == 0 || (sc->clip->tracking.act_track == track))
#define TRACK_CLEAR_UPTO 0
#define TRACK_CLEAR_REMAINED 1
#define TRACK_CLEAR_ALL 2
#define CLAMP_PAT_DIM 1
#define CLAMP_PAT_POS 2
#define CLAMP_SEARCH_DIM 3
#define CLAMP_SEARCH_POS 4
#define TRACK_AREA_NONE -1
#define TRACK_AREA_POINT 1
#define TRACK_AREA_PAT 2
#define TRACK_AREA_SEARCH 4
#define TRACK_AREA_ALL (TRACK_AREA_POINT | TRACK_AREA_PAT | TRACK_AREA_SEARCH)
#endif
|
floydkots/basics_to_advanced_cpp
|
tests/basics/ppa_01_test.cpp
|
<gh_stars>0
//
// Created by floyd on 12/5/17.
//
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "../../src/basics/topic_2/ppa_01.h"
using testing::Eq;
namespace {
class ppa_01_test : public testing::Test {
public:
ppa_01 ppa01;
ppa_01_test() {
ppa01;
}
};
}
TEST_F(ppa_01_test, ppa_01Test_shouldSetAgeResultTo0_Test) {
int ageResult;
ppa01.detectAgeResult(1, ageResult);
ppa01.detectAgeResult(5, ageResult);
ASSERT_EQ(0, ageResult);
}
TEST_F(ppa_01_test, ppa_01Test_shouldSetAgeResultToNegativeOne_Test) {
int ageResult;
ppa01.detectAgeResult(-1, ageResult);
ppa01.detectAgeResult(102, ageResult);
ASSERT_EQ(-1, ageResult);
}
TEST_F(ppa_01_test, ppa_01Test_shouldSetAgeResultTo1_Test) {
int ageResult;
ppa01.detectAgeResult(6, ageResult);
ppa01.detectAgeResult(12, ageResult);
ASSERT_EQ(1, ageResult);
}TEST_F(ppa_01_test, ppa_01Test_shouldSetAgeResultTo2_Test) {
int ageResult;
ppa01.detectAgeResult(13, ageResult);
ppa01.detectAgeResult(15, ageResult);
ASSERT_EQ(2, ageResult);
}
TEST_F(ppa_01_test, ppa_01Test_shouldSetAgeResultTo3_Test) {
int ageResult;
ppa01.detectAgeResult(50, ageResult);
ASSERT_EQ(3, ageResult);
}
TEST_F(ppa_01_test, ppa_01Test_shouldSetAgeResultTo4_Test) {
int ageResult;
ppa01.detectAgeResult(51, ageResult);
ASSERT_EQ(4, ageResult);
}
TEST_F(ppa_01_test, ppa_01Test_shouldSetAgeResultTo5_Test) {
int ageResult;
ppa01.detectAgeResult(61, ageResult);
ASSERT_EQ(5, ageResult);
}
|
gautamkmr/caffe2
|
third_party/aten/src/ATen/cpu/tbb/tbb_remote/src/test/test_cache_aligned_allocator.cpp
|
<filename>third_party/aten/src/ATen/cpu/tbb/tbb_remote/src/test/test_cache_aligned_allocator.cpp
/*
Copyright (c) 2005-2017 Intel Corporation
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.
*/
// Test whether cache_aligned_allocator works with some of the host's STL containers.
#include "tbb/cache_aligned_allocator.h"
#include "tbb/tbb_allocator.h"
#define HARNESS_NO_PARSE_COMMAND_LINE 1
// the real body of the test is there:
#include "test_allocator.h"
template<>
struct is_zero_filling<tbb::zero_allocator<void> > {
static const bool value = true;
};
// Test that NFS_Allocate() throws bad_alloc if cannot allocate memory.
void Test_NFS_Allocate_Throws() {
#if TBB_USE_EXCEPTIONS && !__TBB_THROW_ACROSS_MODULE_BOUNDARY_BROKEN
using namespace tbb::internal;
// First, allocate a reasonably big amount of memory, big enough
// to not cause warp around in system allocator after adding object header
// during address2 allocation.
const size_t itemsize = 1024;
const size_t nitems = 1024;
void *address1 = NULL;
try {
address1 = NFS_Allocate( nitems, itemsize, NULL );
} catch( ... ) {
// intentionally empty
}
ASSERT( address1, "NFS_Allocate unable to obtain 1024*1024 bytes" );
bool exception_caught = false;
try {
// Try allocating more memory than left in the address space; should cause std::bad_alloc
(void) NFS_Allocate( 1, ~size_t(0) - itemsize*nitems + NFS_GetLineSize(), NULL);
} catch( std::bad_alloc ) {
exception_caught = true;
} catch( ... ) {
ASSERT( __TBB_EXCEPTION_TYPE_INFO_BROKEN, "Unexpected exception type (std::bad_alloc was expected)" );
exception_caught = true;
}
ASSERT( exception_caught, "NFS_Allocate did not throw bad_alloc" );
try {
NFS_Free( address1 );
} catch( ... ) {
ASSERT( false, "NFS_Free did not accept the address obtained with NFS_Allocate" );
}
#endif /* TBB_USE_EXCEPTIONS && !__TBB_THROW_ACROSS_MODULE_BOUNDARY_BROKEN */
}
int TestMain () {
int result = TestMain<tbb::cache_aligned_allocator<void> >();
result += TestMain<tbb::tbb_allocator<void> >();
result += TestMain<tbb::zero_allocator<void> >();
ASSERT( !result, NULL );
Test_NFS_Allocate_Throws();
return Harness::Done;
}
|
danielbaenabird/fyne
|
widget/check_test.go
|
<filename>widget/check_test.go
package widget_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/danielbaenabird/fyne/v2"
"github.com/danielbaenabird/fyne/v2/data/binding"
"github.com/danielbaenabird/fyne/v2/layout"
"github.com/danielbaenabird/fyne/v2/test"
"github.com/danielbaenabird/fyne/v2/widget"
)
func TestCheck_Binding(t *testing.T) {
c := widget.NewCheck("", nil)
c.SetChecked(true)
assert.Equal(t, true, c.Checked)
val := binding.NewBool()
c.Bind(val)
waitForBinding()
assert.Equal(t, false, c.Checked)
err := val.Set(true)
assert.Nil(t, err)
waitForBinding()
assert.Equal(t, true, c.Checked)
c.SetChecked(false)
v, err := val.Get()
assert.Nil(t, err)
assert.Equal(t, false, v)
c.Unbind()
waitForBinding()
assert.Equal(t, false, c.Checked)
}
func TestCheck_Layout(t *testing.T) {
test.NewApp()
defer test.NewApp()
for name, tt := range map[string]struct {
text string
checked bool
disabled bool
}{
"checked": {
text: "Test",
checked: true,
},
"unchecked": {
text: "Test",
},
"checked_disabled": {
text: "Test",
checked: true,
disabled: true,
},
"unchecked_disabled": {
text: "Test",
disabled: true,
},
} {
t.Run(name, func(t *testing.T) {
check := &widget.Check{
Text: tt.text,
Checked: tt.checked,
}
if tt.disabled {
check.Disable()
}
window := test.NewWindow(fyne.NewContainerWithLayout(layout.NewCenterLayout(), check))
window.Resize(check.MinSize().Max(fyne.NewSize(150, 200)))
test.AssertRendersToMarkup(t, "check/layout_"+name+".xml", window.Canvas())
window.Close()
})
}
}
func TestNewCheckWithData(t *testing.T) {
val := binding.NewBool()
err := val.Set(true)
assert.Nil(t, err)
c := widget.NewCheckWithData("", val)
waitForBinding()
assert.Equal(t, true, c.Checked)
c.SetChecked(false)
v, err := val.Get()
assert.Nil(t, err)
assert.Equal(t, false, v)
}
|
aezocn/plsqlweb
|
src/org/reddragonfly/iplsqldevj/bean/Database.java
|
<reponame>aezocn/plsqlweb<gh_stars>1-10
/*
* @author phanrider
* @version 1.0, 2007-11-20
*
* @source: DbConnect.java Create on 2007-11-20 ไธๅ11:04:22
*/
package org.reddragonfly.iplsqldevj.bean;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.Reader;
import java.sql.*;
import java.util.Vector;
import oracle.jdbc.OracleResultSet;
import oracle.sql.BLOB;
public class Database {
private Connection conn;
public Database()throws Exception{
String url = "jdbc:oracle:thin:@192.168.1.1:1521:gsdb";
String driverName = "oracle.jdbc.driver.OracleDriver";
String user = "test";
String password = "<PASSWORD>";
Driver dbDriver = (Driver) Class.forName(driverName).newInstance();
DriverManager.registerDriver(dbDriver);
this.conn = DriverManager.getConnection(url, user, password);
}
public Database(String url, String user, String password )throws Exception{
String driverName = "oracle.jdbc.driver.OracleDriver";
Driver dbDriver = (Driver) Class.forName(driverName).newInstance();
DriverManager.registerDriver(dbDriver);
this.conn = DriverManager.getConnection(url, user, password);
}
public Connection getConnection() throws Exception{
return this.conn;
}
public Database(boolean isAutoCommit,Connection conn) throws Exception{
this.conn = conn;
this.conn.setAutoCommit(isAutoCommit);
}
public ResultSet getRS(String sql) throws Exception {
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
//stmt.setFetchSize(50);
rs = stmt.executeQuery(sql);
}
catch (Exception e) {
throw new Exception(e.getMessage());
}
return rs;
}
/**
* ๆง่กๆๅ
ฅๅๆดๆฐ่ฏญๅฅ
* @param sql - sql่ฏญๅฅ
* @throws Exception
* @return int
*/
public int execSqlUpdate(String sql) throws Exception {
Statement stmt = null;
try {
int executeResult;
stmt = conn.createStatement();
executeResult = stmt.executeUpdate(sql);
stmt.close();
return executeResult;
}
catch (Exception e) {
throw new Exception(e.getMessage());
}
finally {
try {
stmt.close();
}
catch (Exception e) {
}
}
}
/**
* prepareๆง่กๆๅ
ฅๅๆดๆฐ่ฏญๅฅ
* @param sql - sql่ฏญๅฅ
* @param param - ๅๆฐ
* @throws Exception
* @return int
* @see ๆไฝoracleๆฐๆฎๅบ็ๆถๅ๏ผdateๅๆฐๆฎ้่ฟjava.sql.Timestampๅๅ
ฅ๏ผๆไฝๅฎไพๅฆไธ๏ผ
Database db = new Database(true);
Vector v=new Vector();
v.add(new Integer(1));
v.add(java.sql.Timestamp.valueOf("2003-03-10 13:23:00"));
v.add(new String("343"));
db.execPrepareSqlUpdate("insert into czh_a(a,b,c) values (?,?,?)",v);
*/
public int execPrepareSqlUpdate(String sql, Vector params) throws Exception {
return execPrepareSqlUpdate(sql, params.toArray());
}
public int execPrepareSqlUpdate(String sql, Object[] params) throws Exception {
PreparedStatement pstmt = null;
try {
int executeResult;
pstmt = conn.prepareStatement(sql);
for (int i = 0; i <= params.length - 1; i++) {
pstmt.setObject(i + 1, params[i]);
}
executeResult = pstmt.executeUpdate();
return executeResult;
}
catch (Exception e) {
throw new Exception(e.getMessage());
}
finally {
try {
pstmt.close();
}
catch (Exception e) {
}
}
}
public ResultSet getDesc(String sql) throws Exception {
Statement stmt = null;
ResultSet rs = null;
boolean exc;
try {
stmt = conn.createStatement();
//stmt.setFetchSize(50);
exc= stmt.execute(sql);
if(exc){
rs=stmt.getResultSet();
}
}
catch (Exception e) {
throw new Exception(e.getMessage());
}
return rs;
}
/**
* ๅพๅฐClobๅญๆฎตๅ
ๅฎน
* @param rs
* @param columnName ๅๅ็งฐ
* @return
* @throws Exception
*/
public String getClob(ResultSet rs, String columnName) throws Exception {
Clob clob = null;
String str = "";
Reader is = null;
try {
clob = rs.getClob(columnName);
if (clob != null) {
is = clob.getCharacterStream();
BufferedReader br = new BufferedReader(is);
String s = br.readLine();
while (s != null) {
str += s + "\n";
s = br.readLine();
}
is.close();
}
}
catch (Exception e) {
throw new Exception(e.getMessage());
}
return str;
}
/**
* ๅพๅฐClobๅญๆฎตๅ
ๅฎน
* @param rs
* @param columnIndex ๅ็ดขๅผ
* @return
* @throws Exception
*/
public String getClob(ResultSet rs, int columnIndex) throws Exception {
Clob clob = null;
String str = "";
Reader is = null;
try {
clob = rs.getClob(columnIndex);
if (clob != null) {
is = clob.getCharacterStream();
BufferedReader br = new BufferedReader(is);
String s = br.readLine();
while (s != null) {
str += s + "\n";
s = br.readLine();
}
is.close();
}
}
catch (Exception e) {
throw new Exception(e.getMessage());
}
return str;
}
private byte[] getBlob(BLOB blob) throws Exception {
if (blob == null) {
return new byte[0];
}
InputStream is = blob.getBinaryStream();
int upMaxByte = 1024;
byte[] buffer = new byte[upMaxByte];
int readByte = 0;
int flength = (int) blob.length();
byte[] rtn = new byte[flength];
int i = 0;
while (i < flength) {
if (i + upMaxByte > flength) {
readByte = (int) (flength - i);
}
else {
readByte = upMaxByte;
}
is.read(buffer, 0, readByte);
System.arraycopy(buffer,0,rtn,i,readByte);
i += upMaxByte;
}
is.close();
return rtn;
}
/**
* ๅพๅฐBlobๅญๆฎต
* @param rs
* @param columnIndex
* @return
* @throws Exception
*/
public byte[] getBlob(ResultSet rs, int columnIndex) throws Exception {
return this.getBlob( ( (OracleResultSet) rs).getBLOB(columnIndex));
}
/**
* ่ทๅพBlob
* @param rs
* @param columnName
* @return
* @throws Exception
*/
public byte[] getBlob(ResultSet rs, String columnName) throws Exception {
return this.getBlob( ( (OracleResultSet) rs).getBLOB(columnName));
}
public void cleanup() {
try {
if (this.conn != null) {
if (!conn.isClosed()) {
this.conn.close();
}
}
}
catch (Exception e) {
}
}
public void close(ResultSet rs) {
try {
if (rs != null) {
rs.getStatement().close();
rs.close();
rs = null;
}
}
catch (Exception e) {
}
}
public void rollback() throws Exception {
try {
this.conn.rollback();
}
catch (Exception e) {
throw new Exception(e.getMessage());
}
}
public void commit() throws Exception {
try {
this.conn.commit();
}
catch (Exception e) {
throw new Exception(e.getMessage());
}
}
public long getSeqNextVal(String sequenceName) throws Exception {
ResultSet rs = null;
try {
String sql = "select " + sequenceName + ".nextval from dual";
rs = this.getRS(sql);
if (rs.next()) {
long nextval = rs.getLong(1);
return nextval;
}else {
throw new Exception("can't get " + sequenceName + " nextval!");
}
}catch (Exception e) {
throw new Exception(e.getMessage());
}finally {
if(rs != null) this.close(rs);
}
}
//ๆต่ฏ็จ
public static void main(String args[]){
try{
Database db=new Database();
String sql="select * from t_dict_man --where state='A'";
ResultSet rs=db.getRS(sql);
while(rs.next()){
System.out.println(rs.getString("code")+" "+rs.getString("name"));
}
db.close(rs);
db.cleanup();
}
catch(Exception e){
e.printStackTrace();
}
}
}
|
ilay09/keystone
|
keystone/tests/unit/identity/backends/test_ldap.py
|
# 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.
from oslo_config import fixture as config_fixture
from keystone.identity.backends import ldap
from keystone.tests.unit import core
from keystone.tests.unit.identity.backends import test_base
from keystone.tests.unit.ksfixtures import ldapdb
class TestIdentityDriver(core.BaseTestCase,
test_base.IdentityDriverTests):
allows_name_update = False
allows_self_service_change_password = False
expected_is_domain_aware = False
expected_default_assignment_driver = 'sql'
expected_is_sql = False
expected_generates_uuids = False
def setUp(self):
super(TestIdentityDriver, self).setUp()
config_fixture_ = self.useFixture(config_fixture.Config())
config_fixture_.config(
group='ldap',
url='fake://memory',
user='cn=Admin',
password='password',
suffix='cn=example,cn=com')
self.useFixture(ldapdb.LDAPDatabase())
self.driver = ldap.Identity()
|
panaris/billy
|
app/controllers/user_activities_controller.rb
|
class UserActivitiesController < ApplicationController
def index
@filter_date = parse_filter(params)
user_id = params[:user] || current_user.id
@activities = UserActivity.get(params[:year], params[:month], user_id)
load_users
respond_to do |format|
format.html
format.json do
view_model = @activities.map do |a|
create_view_model(a)
end
render :json => view_model
end
end
end
def load_users
if (current_user.admin?)
@users = User.all
else
@users = [current_user]
end
end
def show
activity = UserActivity.find(params[:id])
render :json => activity
end
def create
activity = UserActivity.find_or_create_by(id: params[:id])
create_or_update activity
create_response activity
end
def update
activity = UserActivity.find(params[:id])
create_or_update activity
create_response activity
end
def destroy
UserActivity.find(params[:id]).delete
respond_to do |format|
format.html { render :json => {result: 'ok'} }
format.json { render :json => {result: 'ok'} }
end
end
def stats
user = current_user
stats = ActivityStats.new
stats.today_hours = UserActivity.where("user_id = ? and DATE(date) = ?", user.id, Date.today.to_date).sum(:hours)
stats.yesterday_hours = UserActivity.where("user_id = ? and DATE(date) = ?", user.id, Date.yesterday.to_date).sum(:hours)
render :json => stats
end
def report
@activities = UserActivity.get(params[:year], params[:month], params[:user])
respond_to do |format|
format.xls
end
end
def report_2
@formatted_activities = ActivityReport.report_2(params[:year].to_i, params[:month].to_i, params[:user])
@month = Date.new(params[:year].to_i, params[:month].to_i, 1).strftime("%B")
@user_name = User.find(params[:user]).name
respond_to do |format|
format.xls
end
end
def report_presenze
@formatted_activities = ActivityReport.report_presenze(params[:year].to_i, params[:month].to_i)
@month = Date.new(params[:year].to_i, params[:month].to_i, 1).strftime("%B")
@user_name = 'FOOO'
respond_to do |format|
format.xls
end
end
private
def parse_filter (params)
if (params[:year].nil? or params[:month].nil?)
Date.today
else
Date.new(params[:year].to_i, params[:month].to_i, 1)
end
end
def create_view_model(activity)
result = {
:id => activity.id,
:date => activity.date,
:hours => activity.hours,
:description => activity.description,
:user_activity_type_id => activity.user_activity_type.id,
:expenses => activity.expenses.count > 0
}
if activity.user_activity_type.working?
if !activity.job_order_activity.nil? # this shouldn't happens...but it do.
result[:jobOrder] = activity.job_order_activity.job_order.code
result[:activity] = activity.job_order_activity.description
end
end
result
end
def create_response(activity)
@result = create_view_model(activity)
respond_to do |format|
format.html { render :json => @result }
format.json { render :json => @result }
end
end
def create_or_update(activity)
activity.date = DateTime.parse(params[:date])
activity.hours = params[:hours].to_f
activity.description = params[:description]
activity.user = current_user
user_activity_type_id = params[:user_activity_type_id] || UserActivityType.working_id
activity.user_activity_type = UserActivityType.find(user_activity_type_id)
if activity.user_activity_type.working?
activity.job_order_activity = get_job_order(params[:job_order_id])
end
activity.save
end
def get_job_order (job_order_id)
job_order = JobOrder.find(job_order_id)
job_order.activities.select{|a| a.id == params[:job_order_activity_id]}.first
end
end
|
joonvena/mvj
|
batchrun/migrations/0003_logentry_kind_1.py
|
<gh_stars>1-10
from django.db import migrations, models
from enumfields.fields import EnumIntegerField
from ..enums import LogEntryKind
class Migration(migrations.Migration):
dependencies = [
("batchrun", "0002_add_safedelete_to_logs"),
]
operations = [
migrations.AlterField( # (*) Add default value to "kind" field
model_name="jobrunlogentry",
name="kind",
field=models.CharField(max_length=30, default="stdout"),
),
migrations.AddField(
model_name="jobrunlogentry",
name="kind2",
field=EnumIntegerField(
enum=LogEntryKind, default=LogEntryKind.STDOUT, verbose_name="kind"
),
),
]
|
zrj-rimwis/DeltaPorts
|
ports/graphics/mesa-dri-classic/newport/files/patch-src_amd_vulkan_radv__device.c
|
<filename>ports/graphics/mesa-dri-classic/newport/files/patch-src_amd_vulkan_radv__device.c
--- src/amd/vulkan/radv_device.c.orig 2020-09-28 22:52:10 UTC
+++ src/amd/vulkan/radv_device.c
@@ -56,6 +56,10 @@
#include "compiler/glsl_types.h"
#include "util/driconf.h"
+#if DETECT_OS_FREEBSD
+#define CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC_FAST
+#endif
+
static struct radv_timeline_point *
radv_timeline_find_point_at_least_locked(struct radv_device *device,
struct radv_timeline *timeline,
|
Mahamurahti/React-Roadmap
|
React/Main_Concepts/09. Forms/forms.js
|
<filename>React/Main_Concepts/09. Forms/forms.js<gh_stars>0
'use strict';
// HTML FORMS
// <form>
// <label>
// Name:
// <input type="text" name="name" />
// </label>
// <input type="submit" value="Submit" />
// </form>
// Controlled component
class NameForm extends React.Component{
constructor(props) {
super(props);
// The "source of truth"
this.state = {value: ''}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event){
this.setState({value: event.target.value})
}
handleSubmit(event){
event.preventDefault();
alert('A name was submitted: ' + this.state.value)
}
render() {
// Input fields value is the value of the source of truth meaning "this.state.value"
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange}/>
</label>
<input type="submit" value='Submit'/>
</form>
);
}
}
// Uncontrolled Component
class NameFormTwo extends React.Component{
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this)
this.input = React.createRef()
}
handleSubmit(event){
event.preventDefault()
alert('A name was submitted: ' + this.input.current.value)
}
render(){
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" defaultValue="Bob" ref={this.input}/>
</label>
<input type="submit" value='Submit'/>
</form>
)
}
}
// Controlled component
class EssayForm extends React.Component{
constructor(props) {
super(props);
// Set some default text in the textarea
this.state = {
value: 'Please write an essay here about what you love about coding'
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event){
this.setState({value: event.target.value})
}
handleSubmit(event){
event.preventDefault();
alert('An essay was submitted: ' + this.state.value)
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Essay:
<textarea value={this.state.value} onChange={this.handleChange}/>
</label>
<input type="submit" value="Submit"/>
</form>
);
}
}
// Controlled component
class FlavourForm extends React.Component{
constructor(props) {
super(props);
this.state = {value: 'coconut'}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event){
this.setState({value: event.target.value})
}
handleSubmit(event){
event.preventDefault();
const values = this.state.value
alert('Your favourite flavour is ' + values)
}
render(){
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favourite flavour:
<select value={this.state.value} onChange={this.handleChange}>
<option value="grapefruit">Grapefruit</option>
<option value="strawberry">Strawberry</option>
<option value="blackberry">Blackberry</option>
<option value="banana">Banana</option>
<option value="apple">Apple</option>
<option value="mango">Mango</option>
<option value="citrus">Citrus</option>
</select>
</label>
<input type="submit" value="Submit"/>
</form>
)
}
}
// Controlled component
class Reservation extends React.Component{
constructor(props) {
super(props);
this.state = {
isGoing: true,
numberOfGuests: 2
}
this.handleInputChange = this.handleInputChange.bind(this)
}
handleInputChange(event){
const target = event.target
const value = target.type === 'checkbox' ? target.checked : target.value
const name = target.name
this.setState({
[name]: value
})
}
render() {
return (
<form>
<label>
Is going:
<input
type="checkbox"
name="isGoing"
checked={this.state.isGoing}
onChange={this.handleInputChange}
/>
</label>
<br />
<label>
Number of guests:
<input
type="number"
name="numberOfGuests"
value={this.state.numberOfGuests}
onChange={this.handleInputChange}
/>
</label>
</form>
);
}
}
function App(){
return (
<div>
<NameForm />
<NameFormTwo />
<EssayForm />
<FlavourForm />
<Reservation />
</div>
)
}
ReactDOM.render(<App />, document.querySelector('#root'))
|
davidkpiano/azure-sdk-for-node
|
lib/services/logicManagement/lib/models/keyVaultKey.js
|
<reponame>davidkpiano/azure-sdk-for-node
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* The key vault key.
*
*/
class KeyVaultKey {
/**
* Create a KeyVaultKey.
* @member {string} [kid] The key id.
* @member {object} [attributes] The key attributes.
* @member {boolean} [attributes.enabled] Whether the key is enabled or not.
* @member {number} [attributes.created] When the key was created.
* @member {number} [attributes.updated] When the key was updated.
*/
constructor() {
}
/**
* Defines the metadata of KeyVaultKey
*
* @returns {object} metadata of KeyVaultKey
*
*/
mapper() {
return {
required: false,
serializedName: 'KeyVaultKey',
type: {
name: 'Composite',
className: 'KeyVaultKey',
modelProperties: {
kid: {
required: false,
serializedName: 'kid',
type: {
name: 'String'
}
},
attributes: {
required: false,
serializedName: 'attributes',
type: {
name: 'Composite',
className: 'KeyVaultKeyAttributes'
}
}
}
}
};
}
}
module.exports = KeyVaultKey;
|
snsokolov/contests
|
codeforces/580B_company.py
|
#!/usr/bin/env python3
# 580B_company.py - Codeforces.com/problemset/problem/580/B by Sergey 2015
import unittest
import sys
###############################################################################
# Company Class (Main Program)
###############################################################################
class Company:
""" Company representation """
def __init__(self, test_inputs=None):
""" Default constructor """
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
# Reading single elements
[self.n, self.d] = map(int, uinput().split())
# Reading multiple number of lines of the same number of elements each
l, s = self.n, 2
inp = (" ".join(uinput() for i in range(l))).split()
self.numm = [[int(inp[i]) for i in range(j, l*s, s)] for j in range(s)]
self.numa, self.numb = self.numm
def calculate(self):
""" Main calcualtion function of the class """
result = 0
# Sorting both arrays by using first array as a key
self.numa, self.numb = zip(*sorted(zip(self.numa, self.numb)))
# Calculating partial sums
self.psum = [0]
for i in range(self.n):
self.psum.append(self.psum[-1] + self.numb[i])
# Calculating result
for i in range(self.n):
mrb = self.numa[i] + self.d
sum = self.psum[lbound(self.numa, mrb)] - self.psum[i]
result = max(result, sum)
return str(result)
# Find lower bound - leftmost position for new element to be inserted
def lbound(v, n):
b = 0
e = len(v)
while b != e:
mid = (b + e) // 2
if v[mid] < n:
b = mid + 1
else:
e = mid
return b
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_single_test(self):
""" Company class testing """
# Constructor test
test = "4 5\n75 5\n0 100\n150 20\n75 1"
d = Company(test)
self.assertEqual(d.n, 4)
self.assertEqual(d.d, 5)
self.assertEqual(d.numa, [75, 0, 150, 75])
self.assertEqual(d.numb, [5, 100, 20, 1])
# Sample test
self.assertEqual(Company(test).calculate(), "100")
# Sample test
test = "5 100\n0 7\n11 32\n99 10\n46 8\n87 54"
self.assertEqual(Company(test).calculate(), "111")
# Sample test
test = ""
# self.assertEqual(Company(test).calculate(), "0")
# My tests
test = ""
# self.assertEqual(Company(test).calculate(), "0")
# Time limit test
self.time_limit_test(1000)
def time_limit_test(self, nmax):
""" Timelimit testing """
import random
import timeit
# Random inputs
test = str(nmax) + " " + str(nmax) + "\n"
numnums = [str(i) + " " + str(i+1) for i in range(nmax)]
test += "\n".join(numnums) + "\n"
# Run the test
start = timeit.default_timer()
d = Company(test)
calc = timeit.default_timer()
d.calculate()
stop = timeit.default_timer()
print("\nTimelimit Test: " +
"{0:.3f}s (init {1:.3f}s calc {2:.3f}s)".
format(stop-start, calc-start, stop-calc))
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
sys.stdout.write(Company().calculate())
|
klueless-io/handlebars-helpers
|
spec/handlebars/helpers/misc/safe_spec.rb
|
<filename>spec/handlebars/helpers/misc/safe_spec.rb
# frozen_string_literal: true
require 'handlebars/helpers/misc/safe'
RSpec.describe Handlebars::Helpers::Misc::Safe do
# Safe will return the value with <> and single and double quotes left as is
describe '#parse' do
subject { described_class.new.parse(value) }
let(:value) { nil }
context 'safely handle nil' do
it { is_expected.to eq('') }
end
context 'value with characters that are considered safe' do
context 'when <>' do
let(:value) { '<hello>' }
it { is_expected.to eq('<hello>') }
end
context 'when ""' do
let(:value) { '"hello"' }
it { is_expected.to eq('"hello"') }
end
end
end
describe 'use as handlebars helper' do
let(:subject) do
Handlebars::Helpers::Template.render(template, data) do |register|
register.helper(:safe, &described_class.new.handlebars_helper)
end
end
let(:template) { '{{safe value}}' }
let(:data) { { value: value } }
let(:value) { nil }
context 'when nil' do
it { is_expected.to eq('') }
end
context 'when value has <> or ""' do
let(:value) { '"<hello>"' }
it { is_expected.to eq('"<hello>"') }
end
end
end
|
kevinhikaruevans/uojs2
|
src/client/components/status-info/index.js
|
<reponame>kevinhikaruevans/uojs2
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import actions, { changeStateMaster } from './actions'
import reducer from './reducer'
import map from './map'
import style from './style'
@connect((state) => ({
id : state.statusInfo.serial,
health : state.statusInfo.health,
mana : state.statusInfo.mana,
weight : state.statusInfo.weight,
stamina : state.statusInfo.stamina,
playerName : state.statusInfo.playerName,
strength : state.statusInfo.strength,
dexterity : state.statusInfo.dexterity,
intelligence : state.statusInfo.intelligence,
statCap : state.statusInfo.statCap,
luck : state.statusInfo.luck,
damage : state.statusInfo.damage,
followers : state.statusInfo.followers,
gold : state.statusInfo.gold,
resist : state.statusInfo.resist,
state : state.statusInfo.state
}))
class StatusInfo extends Component {
static displayName = '[component] status-info';
static propTypes = {
id : PropTypes.number,
strength : PropTypes.number, // eslint-disable-line react/no-unused-prop-types
dexterity : PropTypes.number, // eslint-disable-line react/no-unused-prop-types
intelligence : PropTypes.number, // eslint-disable-line react/no-unused-prop-types
statCap : PropTypes.number,
luck : PropTypes.number,
playerName : PropTypes.string,
gold : PropTypes.number,
className : PropTypes.string,
dispatch : PropTypes.func,
health : PropTypes.shape({
current : PropTypes.number,
max : PropTypes.number
}),
mana : PropTypes.shape({
current : PropTypes.number,
max : PropTypes.number
}),
stamina : PropTypes.shape({
current : PropTypes.number,
max : PropTypes.number
}),
weight : PropTypes.shape({
current : PropTypes.number,
max : PropTypes.number
}),
damage : PropTypes.shape({
min : PropTypes.number,
max : PropTypes.number
}),
followers : PropTypes.shape({
current : PropTypes.number,
max : PropTypes.number
}),
resist : PropTypes.shape({
cold : PropTypes.number,
energy : PropTypes.number,
fire : PropTypes.number,
poison : PropTypes.number
}),
state : PropTypes.shape({
strength : PropTypes.oneOf([0, 1, 2]),
dexterity : PropTypes.oneOf([0, 1, 2]),
intelligence : PropTypes.oneOf([0, 1, 2])
})
};
state = {
minimize : localStorage.getItem(`status-info-minimize-${this.props.id}`) === 'true',
x : parseInt(localStorage.getItem(`status-info-x-${this.props.id}`), 10) || '50%',
y : parseInt(localStorage.getItem(`status-info-y-${this.props.id}`), 10) || '50%'
};
onToggleMinimize = (e) => {
e.preventDefault();
this.setState({
minimize : !this.state.minimize
}, () => {
localStorage.setItem(`status-info-minimize-${this.props.id}`, this.state.minimize)
})
};
// @TODO: go base class method
get className() {
let result = style['status-info'];
if(this.props.className) {
result = `${result} ${this.props.className}`;
}
return result;
}
onMove = (e) => {
if(this.move) {
let x = e.clientX;
let y = e.clientY;
const offsetWidth = e.currentTarget.offsetWidth / 2;
const offsetHeight = e.currentTarget.offsetHeight / 2;
if(e.clientX > offsetWidth) {
if(x + offsetWidth > window.innerWidth) {
x = window.innerWidth - offsetWidth;
}
x = x - offsetWidth;
} else {
x = 0;
}
if(e.clientY > offsetHeight) {
if(y + offsetHeight > window.innerHeight) {
y = window.innerHeight - offsetHeight;
}
y = y - offsetHeight;
} else {
y = 0;
}
this.setState({
x,
y
}, () => {
localStorage.setItem(`status-info-x-${this.props.id}`, x);
localStorage.setItem(`status-info-y-${this.props.id}`, y);
});
}
};
onMoveStart = (e) => {
e.preventDefault();
this.move = true;
};
onMoveStop = (e) => {
e.preventDefault();
this.move = false;
};
onClickChangeState = (stat) => {
let state = this.props.state[stat];
++state;
if(state > 2) {
state = 0;
}
return (e) => {
e.preventDefault();
this.props.dispatch(changeStateMaster({
stat : map.number[stat],
state
}))
};
};
get elStats() {
const stats = Object.keys(map.number);
return stats.map((stat, index) => {
const props = {
key : index,
className : style['status-info__list-item'],
onClick : this.onClickChangeState(stat),
// @TODO: i18n
children : `str: ${this.props[stat]}`,
'data-state' : map.symbol[this.props.state[stat]]
};
return <li {...props} />
})
}
get elFull() {
return(
<div className={style['status-info__full']}>
<div className={style['status-info__header']}>
<strong className={style['status-info__player-name']}>{this.props.playerName}</strong>
<div onClick={this.onToggleMinimize}>minimize</div>
</div>
<ul className={style['status-info__list']}>
{this.elStats}
</ul>
<ul className={style['status-info__list']}>
<li className={`${style['status-info__list-item']} ${style['status-info__list-item_split']}`}>
<span className={style['status-info__points']}>{this.props.health.current}</span>
<span className={style['status-info__points']}>{this.props.health.max}</span>
</li>
<li className={`${style['status-info__list-item']} ${style['status-info__list-item_split']}`}>
<span className={style['status-info__points']}>{this.props.stamina.current}</span>
<span className={style['status-info__points']}>{this.props.stamina.max}</span>
</li>
<li className={`${style['status-info__list-item']} ${style['status-info__list-item_split']}`}>
<span className={style['status-info__points']}>{this.props.mana.current}</span>
<span className={style['status-info__points']}>{this.props.mana.max}</span>
</li>
</ul>
<ul className={style['status-info__list']}>
<li className={style['status-info__list-item']}>cap: {this.props.statCap}</li>
<li className={style['status-info__list-item']}>lck: {this.props.luck}</li>
<li className={`${style['status-info__list-item']} ${style['status-info__list-item_split']}`}>
<span className={style['status-info__points']}>{this.props.weight.current}</span>
<span className={style['status-info__points']}>{this.props.weight.max}</span>
</li>
</ul>
<ul className={style['status-info__list']}>
<li className={style['status-info__list-item']}>dmg: {this.props.damage.min} - {this.props.damage.max}</li>
<li className={`${style['status-info__list-item']} ${style['status-info__list-item_split']}`}>
<span className={style['status-info__points']}>{this.props.followers.current}</span>
<span className={style['status-info__points']}>{this.props.followers.max}</span>
</li>
</ul>
<ul className={style['status-info__list']}>
<li className={`${style['status-info__list-item']} ${style['status-info__list-item_split']}`}>
<span className={style['status-info__points']}>fir: {this.props.resist.fire}/70</span>
<span className={style['status-info__points']}>cld: {this.props.resist.cold}/70</span>
<span className={style['status-info__points']}>psn: {this.props.resist.poison}/70</span>
<span className={style['status-info__points']}>nrg: {this.props.resist.energy}/70</span>
</li>
<li className={style['status-info__list-item']}>gold: {this.props.gold}</li>
</ul>
</div>
)
}
get elShort() {
return(
<div className={style['status-info__minimize']} onDoubleClick={this.onToggleMinimize}>
<div className={style['status-info__bar-block']} data-label="H">
<progress className={`${style['status-info__bar']} ${style['status-info__bar_health']}`} value={this.props.health.current} max={this.props.health.max} />
</div>
<div className={style['status-info__bar-block']} data-label="M">
<progress className={style['status-info__bar']} value={this.props.mana.current} max={this.props.mana.max} />
</div>
<div className={style['status-info__bar-block']} data-label="S">
<progress className={style['status-info__bar']} value={this.props.stamina.current} max={this.props.stamina.max} />
</div>
</div>
)
}
get content() {
if(this.state.minimize) {
return this.elShort
} else {
return this.elFull
}
}
render() {
const props = {
className : this.className,
onMouseMove : this.onMove,
onMouseDown : this.onMoveStart,
onMouseUp : this.onMoveStop,
onMouseLeave : this.onMoveStop,
style : {
top : this.state.y,
left : this.state.x
}
};
return(
<div {...props}>
{this.content}
</div>
)
}
}
export { StatusInfo as default, style, actions, reducer }
|
smuryginim/dozer
|
core/src/test/java/org/dozer/functional_tests/IsAccessibleTest.java
|
package org.dozer.functional_tests;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author <NAME>
*/
public class IsAccessibleTest extends AbstractFunctionalTest {
@Before
public void setUp() {
mapper = getMapper("nestedAccessible.xml");
}
@Test
public void shouldWorkWithNestedFields() {
Node child = new Node(null);
Node root = new Node(new Node(child));
mapper.map("a", root);
assertEquals("a", root.child.child.value);
}
@Test
public void shouldPreinstantiateChainElements() {
Node node = new Node(null);
mapper.map("a", node);
assertEquals("a", node.child.child.value);
}
@Test
public void shouldApplyIsAccessibleOnClass() {
Node node = new Node(null);
mapper.map("true", node, "class-level");
assertEquals("true", node.value);
assertEquals("true", node.publicValue);
assertTrue(node.setterInvoked);
}
@Test
public void shouldApplyIsAccessibleOnClass_Backwards() {
Node node = new Node(null);
node.publicValue = "true";
Node result = mapper.map(node, Node.class, "third");
assertEquals("true", result.value);
assertTrue(node.getterInvoked);
}
public static class Node {
Node child;
String value;
String publicValue;
boolean setterInvoked;
boolean getterInvoked;
public Node() {
}
public Node(Node child) {
this.child = child;
}
public String getPublicValue() {
this.getterInvoked = true;
return publicValue;
}
public void setPublicValue(String publicValue) {
this.setterInvoked = true;
this.publicValue = publicValue;
}
public boolean isSetterInvoked() {
return setterInvoked;
}
public boolean isGetterInvoked() {
return getterInvoked;
}
}
}
|
kaladay/Vitro
|
api/src/main/java/edu/cornell/mannlib/vitro/webapp/filestorage/serving/FileServingServlet.java
|
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.filestorage.serving;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.application.ApplicationUtils;
import edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.filestorage.model.FileInfo;
import edu.cornell.mannlib.vitro.webapp.modules.fileStorage.FileStorage;
/**
* <p>
* Handles a request to serve an uploaded file from the file storage system.
* </p>
* <p>
* The path of the request should be the "alias URL" of the desired file. We
* need to:
* </p>
* <ul>
* <li>Use the alias URL to find the URI of the file bytestream object.</li>
* <li>Find the file surrogate object to get the MIME type of the file, and
* confirm the filename.</li>
* <li>Set the MIME type on the output stream and serve the bytes.</li>
* </ul>
* <p>
* If the request is superficially correct, but no such file can be found,
* return a 404. If there is a break in the data structures within the model or
* the file system, return a 500.
* </p>
*/
@WebServlet(name = "serveFiles", urlPatterns = {"/file/*"})
public class FileServingServlet extends VitroHttpServlet {
/** If we can't locate the requested image, use this one instead. */
private static final String PATH_MISSING_LINK_IMAGE = "/images/missingLink.png";
private static final Log log = LogFactory.getLog(FileServingServlet.class);
private FileStorage fileStorage;
/**
* Get a reference to the File Storage system.
*/
@Override
public void init() throws ServletException {
super.init();
fileStorage = ApplicationUtils.instance().getFileStorage();
}
@Override
protected void doGet(HttpServletRequest rawRequest,
HttpServletResponse response) throws ServletException, IOException {
VitroRequest request = new VitroRequest(rawRequest);
// Use the alias URL to get the URI of the bytestream object.
String path = request.getServletPath() + request.getPathInfo();
log.debug("Path is '" + path + "'");
/*
* Get the mime type and an InputStream from the file. If we can't, use
* the dummy image file instead.
*/
InputStream in;
String mimeType = null;
try {
FileInfo fileInfo = figureFileInfo(request.getWebappDaoFactory(),
path);
mimeType = fileInfo.getMimeType();
String actualFilename = findAndValidateFilename(fileInfo, path);
in = openImageInputStream(fileInfo, actualFilename);
} catch (FileServingException e) {
log.info("Failed to serve the file at '" + path + "' -- " + e);
in = openMissingLinkImage(request);
mimeType = "image/png";
} catch (Exception e) {
log.warn("Failed to serve the file at '" + path + "' -- " + e);
in = openMissingLinkImage(request);
mimeType = "image/png";
}
/*
* Everything is ready. Set the status and the content type, and send
* the image bytes.
*/
response.setStatus(SC_OK);
if (mimeType != null) {
response.setContentType(mimeType);
}
ServletOutputStream out = null;
try {
out = response.getOutputStream();
byte[] buffer = new byte[8192];
int howMany;
while (-1 != (howMany = in.read(buffer))) {
out.write(buffer, 0, howMany);
}
} catch (IOException e) {
log.warn("Failed to serve the file", e);
} finally {
try {
in.close();
} catch (Exception e) {
log.warn("Serving " + request.getRequestURI()
+ ". Failed to close input stream.", e);
}
if (out != null) {
try {
out.close();
} catch (Exception e) {
log.warn("Serving " + request.getRequestURI()
+ ". Failed to close output stream.", e);
}
}
}
}
private FileInfo figureFileInfo(WebappDaoFactory fullWadf, String path)
throws FileServingException {
FileInfo fileInfo = FileInfo.instanceFromAliasUrl(fullWadf, path,
getServletContext());
if (fileInfo == null) {
throw new FileServingException("The request path is not valid "
+ "for the File servlet: '" + path + "'");
}
log.debug("File info is '" + fileInfo + "'");
return fileInfo;
}
/** Validate that the file exists, with the requested URI and filename. */
private String findAndValidateFilename(FileInfo fileInfo, String path)
throws FileServingException {
String requestedFilename = figureFilename(path);
String actualFilename = fileInfo.getFilename();
if (!actualFilename.equals(requestedFilename)
&& !actualFilename.equals(decode(requestedFilename))) {
throw new FileServingException(
"The requested filename does not match the "
+ "actual filename; request: '" + path
+ "', actual: '" + actualFilename + "'");
}
log.debug("Actual filename is '" + actualFilename + "'");
return actualFilename;
}
/** The filename is the portion of the path after the last slash. */
private String figureFilename(String path) {
int slashHere = path.lastIndexOf('/');
if (slashHere == -1) {
return path;
} else {
return path.substring(slashHere + 1);
}
}
/** The filename may have been encoded for URL transfer. */
private String decode(String filename) {
try {
return URLDecoder.decode(filename, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error("No UTF-8 decoder? How did this happen?", e);
return filename;
}
}
private InputStream openImageInputStream(FileInfo fileInfo,
String actualFilename) throws IOException {
return fileStorage.getInputStream(fileInfo.getBytestreamUri(),
actualFilename);
}
/** Any suprises when opening the image? Use this one instead. */
private InputStream openMissingLinkImage(VitroRequest vreq)
throws FileNotFoundException {
InputStream stream = vreq.getSession().getServletContext()
.getResourceAsStream(PATH_MISSING_LINK_IMAGE);
if (stream == null) {
throw new FileNotFoundException("No image file at '"
+ PATH_MISSING_LINK_IMAGE + "'");
}
return stream;
}
/**
* A POST request is treated the same as a GET request.
*/
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
/**
* There was a problem serving the file bytestream.
*/
private static class FileServingException extends Exception {
public FileServingException(String message) {
super(message);
}
}
}
|
hoyeungw/palma
|
vintage/crostab/src/archive/helper.js
|
import { StatFuncs } from '../tableSpec/StatFuncs'
import { Stat } from 'borel'
export const restoreCell = (cell) => {
// const cellSet = Ar.clone(cell)
const cellSet = Object.entries(cell).map(([field, stat]) => ({ field, stat }))
if (cellSet.length) {
for (let c of cellSet) {
if (!c.stat) c.stat = Stat.sum
if (typeof c.stat !== 'function') c.stat = StatFuncs[c] || Stat.sum
}
return cellSet
} else {
return [{ field: 0, stat: Stat.cnt }]
}
}
export const restoreFilters = (filters) => {
// const cellSet = Ar.clone(cell)
return Object.entries(filters).map(([field, crit]) => ({ field, crit }))
}
/**
*
* @param {{field:[],stat:function(*[]):number}[]} cellIns
* @param {{ field:string|number, stat:function(*[]):number }[]} cellDef
*/
export const fusionOb = (cellIns, cellDef) => {
const o = {}
for (let { field, stat } of cellDef) o[field] = cellIns[field] |> stat
// Xr().tag(JSON.stringify(cellIns)).tag(JSON.stringify(cellDef)).tag(JSON.stringify(o)).tx |> console.log
return o
}
/**
*
* @param {{field:[],stat:function(*[]):number}[]} cellIns
* @param {{ field:string|number, stat:function(*[]):number }[]} cellDef
*/
export const fusionAr = (cellIns, cellDef) => {
const o = []
for (let { field, stat } of cellDef) o.push(cellIns[field] |> stat)
return o
}
/**
*
* @param {{field:[],stat:function(*[]):number}[]} cellIns
* @param {{ field:string|number, stat:function(*[]):number }[]} cellDef
* @param {function(Object<string,number>):number} calc
*/
export const measure = (cellIns, cellDef, calc) => cellIns |> fusionOb(cellIns, cellDef) |> calc
|
noojee/eway-rapid-java
|
src/main/java/com/eway/payment/rapid/sdk/entities/CancelAuthorisationRequest.java
|
package com.eway.payment.rapid.sdk.entities;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CancelAuthorisationRequest extends Request {
@JsonProperty("TransactionId")
public String transactionId;
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
}
|
LobbyTech-MC/UntilTheEnd
|
src/main/java/ute/internal/karlatemp/mxlib/formatter/AbstractReplacer.java
|
<gh_stars>10-100
/*
* Copyright (c) 2018-2020 Karlatemp. All rights reserved.
* @author Karlatemp <<EMAIL>> <https://github.com/Karlatemp>
* @create 2020/03/09 22:32:11
*
* UntilTheEnd/UntilTheEnd/AbstractReplacer.java
*/
package ute.internal.karlatemp.mxlib.formatter;
public interface AbstractReplacer extends Replacer {
@Override
default boolean containsKey(String key) {
return true;
}
@Override
default boolean isEmpty() {
return false;
}
@Override
default void apply(StringBuilder builder, String key) {
builder.append(key);
}
@Override
default void apply(StringBuilder builder, int slot) {
apply(builder, String.valueOf(slot));
}
}
|
wallaby-rails/wallaby-core
|
lib/services/wallaby/class_finder.rb
|
# frozen_string_literal: true
module Wallaby
# Base class to find out the class for given {#script_name}, {#model_class}, {#current_controller_class}
class ClassFinder
include ActiveModel::Model
# @!attribute script_name
# @return [String]
attr_accessor :script_name
# @!attribute model_class
# @return [Class]
attr_accessor :model_class
# @!attribute current_controller_class
# @return [Class]
attr_accessor :current_controller_class
protected
# @return [Class]
def possible_default_class
Guesser.possible_class_from(possible_class_name, denamespace: denamespace?)
end
# @return [String] class name
def possible_class_name
@possible_class_name ||= Inflector.try(:"to_#{type}_name", script_name, model_class)
end
# This attribute will determine if the {#possible_default_class}
# should keep removing the namespaces one by one when looking up the class
# @return [Boolean]
def denamespace?
true
end
# @return [String] type for the finder
def type
self.class.name.demodulize.sub(FINDER, EMPTY_STRING).underscore
end
end
end
|
pzas03/jagger
|
chassis/core/src/test/java/com/griddynamics/jagger/ExampleSimpleUserScenarioJLoadScenarioProvider.java
|
<reponame>pzas03/jagger
package com.griddynamics.jagger;
import com.griddynamics.jagger.invoker.scenario.JHttpUserScenarioInvocationListener;
import com.griddynamics.jagger.invoker.scenario.JHttpUserScenarioInvokerProvider;
import com.griddynamics.jagger.user.test.configurations.JLoadScenario;
import com.griddynamics.jagger.user.test.configurations.JLoadTest;
import com.griddynamics.jagger.user.test.configurations.JParallelTestsGroup;
import com.griddynamics.jagger.user.test.configurations.JTestDefinition;
import com.griddynamics.jagger.user.test.configurations.auxiliary.Id;
import com.griddynamics.jagger.user.test.configurations.limits.JLimit;
import com.griddynamics.jagger.user.test.configurations.limits.JLimitVsRefValue;
import com.griddynamics.jagger.user.test.configurations.limits.auxiliary.LowErrThresh;
import com.griddynamics.jagger.user.test.configurations.limits.auxiliary.RefValue;
import com.griddynamics.jagger.user.test.configurations.limits.auxiliary.UpErrThresh;
import com.griddynamics.jagger.user.test.configurations.load.JLoadProfile;
import com.griddynamics.jagger.user.test.configurations.load.JLoadProfileInvocation;
import com.griddynamics.jagger.user.test.configurations.load.auxiliary.InvocationCount;
import com.griddynamics.jagger.user.test.configurations.load.auxiliary.ThreadCount;
import com.griddynamics.jagger.user.test.configurations.termination.JTerminationCriteria;
import com.griddynamics.jagger.user.test.configurations.termination.JTerminationCriteriaIterations;
import com.griddynamics.jagger.user.test.configurations.termination.auxiliary.IterationsNumber;
import com.griddynamics.jagger.user.test.configurations.termination.auxiliary.MaxDurationInSeconds;
import com.griddynamics.jagger.util.StandardMetricsNamesUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Example of user scenario load scenario
*/
@Configuration
public class ExampleSimpleUserScenarioJLoadScenarioProvider {
@Bean
public JLoadScenario exampleSimpleJaggerLoadScenarioUS() {
JTestDefinition jTestDefinition = JTestDefinition.builder(Id.of("td_example"), new ExampleUserScenarioProvider())
.withInvoker(new JHttpUserScenarioInvokerProvider())
.addListener(new JHttpUserScenarioInvocationListener())
.build();
JLoadProfile jLoadProfileInvocations = JLoadProfileInvocation.builder(InvocationCount.of(100), ThreadCount.of(2)).build();
JTerminationCriteria jTerminationCriteria = JTerminationCriteriaIterations.of(IterationsNumber.of(500), MaxDurationInSeconds.of(50));
JLimit firstStepLimit = JLimitVsRefValue.builder(ExampleUserScenarioProvider.SCENARIO_ID,
ExampleUserScenarioProvider.STEP_1_ID,
StandardMetricsNamesUtil.LATENCY_ID,
RefValue.of(1.5))
.withOnlyErrors(LowErrThresh.of(0.8), UpErrThresh.of(1.2))
.build();
JLoadTest jLoadTest = JLoadTest.builder(Id.of("lt_example"), jTestDefinition, jLoadProfileInvocations, jTerminationCriteria)
.withLimits(firstStepLimit)
.build();
JParallelTestsGroup jParallelTestsGroup = JParallelTestsGroup.builder(Id.of("ptg_example"), jLoadTest).build();
return JLoadScenario.builder(Id.of("ls_example_scenario"), jParallelTestsGroup).build();
}
}
|
anastasia143/qreal
|
qrutils/interpreter/blocks/receiveThreadMessageBlock.cpp
|
<reponame>anastasia143/qreal
/* Copyright 2007-2015 QReal Research Group
*
* 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 "receiveThreadMessageBlock.h"
#include <qrutils/interpreter/thread.h>
using namespace qReal::interpretation::blocks;
void ReceiveThreadMessageBlock::run()
{
mVariable = stringProperty("Variable");
if (mVariable.isEmpty()) {
error(tr("Need to specify variable which will contain received message"));
return;
}
QString message;
if (mThread->getMessage(message)) {
receiveMessage(message);
return;
}
if (!boolProperty("Synchronized")) {
emit done(mNextBlockId);
}
}
void ReceiveThreadMessageBlock::receiveMessage(const QString &message)
{
evalCode(mVariable + " = " + message);
emit done(mNextBlockId);
}
|
shawnburke/fx
|
modules/task/backend_test.go
|
<filename>modules/task/backend_test.go
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package task
import (
"context"
"testing"
"time"
"go.uber.org/fx/service"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func withBackendSetup(t *testing.T, backend Backend) func() {
_globalBackend = backend
require.NoError(t, _globalBackend.Start())
return func() {
assert.NoError(t, _globalBackend.Stop())
_globalBackend = NopBackend{}
}
}
func TestNopBackend(t *testing.T) {
b := &NopBackend{}
assert.NotNil(t, b.Encoder())
assert.NoError(t, b.Start())
assert.NoError(t, b.Enqueue(nil, nil))
assert.NoError(t, b.Stop())
}
func TestInMemBackend(t *testing.T) {
b := NewInMemBackend(newTestHost(t))
defer withBackendSetup(t, b)()
require.NotNil(t, b.Encoder())
require.NoError(t, b.Start())
require.NoError(t, b.ExecuteAsync())
memB := b.(*inMemBackend)
publishEncodedVal(t, memB)
publishEncodedVal(t, memB)
}
func TestInMemBackendStartTimeout(t *testing.T) {
b := NewInMemBackend(newTestHost(t))
_ = b.Start()
defer b.Stop()
time.Sleep(time.Millisecond)
}
func publishEncodedVal(t *testing.T, b Backend) {
bytes, err := b.Encoder().Marshal("Hello")
assert.NoError(t, err)
// Publish a non FnSignature value that results in error
err = b.Enqueue(context.Background(), bytes)
assert.NoError(t, err)
errorCh := b.(*inMemBackend).errorCh
require.NotNil(t, errorCh)
if err, ok := <-errorCh; ok {
assert.Error(t, err)
assert.Contains(t, err.Error(), "type mismatch")
}
}
func newTestHost(t *testing.T) service.Host {
mi, err := service.NewScopedHost(service.NopHost(), "task", "hello")
require.NoError(t, err)
return mi
}
|
iridium-browser/iridium-browser
|
chrome/browser/continuous_search/android/junit/src/org/chromium/chrome/browser/continuous_search/ContinuousSearchContainerMediatorTest.java
|
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.continuous_search;
import android.view.View;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.supplier.Supplier;
import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.chrome.browser.browser_controls.BrowserControlsStateProvider;
import org.chromium.ui.modelutil.PropertyModel;
/**
* Tests for {@link ContinuousSearchContainerMediator}.
*/
@RunWith(BaseRobolectricTestRunner.class)
public class ContinuousSearchContainerMediatorTest {
private ContinuousSearchContainerMediator mMediator;
private PropertyModel mModel;
private BrowserControlsStateProvider.Observer mCurrentBrowserControlsObserver;
private int mCurrentTopControlsHeight;
private int mCurrentTopControlsMinHeight;
private int mCurrentExpectedHeight;
private boolean mCanAnimateNative;
private static final int DEFAULT_MIN_HEIGHT = 40;
private static final int DEFAULT_CONTAINER_HEIGHT = 50;
private static final int JAVA_HEIGHT = 60;
@Before
public void setUp() {
BrowserControlsStateProvider browserControlsStateProvider =
new BrowserControlsStateProvider() {
@Override
public void addObserver(Observer obs) {
mCurrentBrowserControlsObserver = obs;
}
@Override
public void removeObserver(Observer obs) {
if (mCurrentBrowserControlsObserver == obs) {
mCurrentBrowserControlsObserver = null;
}
}
@Override
public int getTopControlsHeight() {
return mCurrentTopControlsHeight;
}
@Override
public int getTopControlsMinHeight() {
return mCurrentTopControlsMinHeight;
}
@Override
public int getTopControlOffset() {
return 0;
}
@Override
public int getTopControlsMinHeightOffset() {
return 0;
}
@Override
public int getBottomControlsHeight() {
return 0;
}
@Override
public int getBottomControlsMinHeight() {
return 0;
}
@Override
public int getBottomControlsMinHeightOffset() {
return 0;
}
@Override
public boolean shouldAnimateBrowserControlsHeightChanges() {
return false;
}
@Override
public int getBottomControlOffset() {
return 0;
}
@Override
public float getBrowserControlHiddenRatio() {
return 0;
}
@Override
public int getContentOffset() {
return 0;
}
@Override
public float getTopVisibleContentOffset() {
return 0;
}
};
Supplier<Boolean> canAnimateNativeSupplier = () -> mCanAnimateNative;
Supplier<Integer> defaultContainerHeightSupplier = () -> DEFAULT_CONTAINER_HEIGHT;
Runnable initializeLayout = () -> {};
mMediator = new ContinuousSearchContainerMediator(browserControlsStateProvider,
canAnimateNativeSupplier, defaultContainerHeightSupplier, initializeLayout);
Runnable requestLayout = () -> mMediator.setJavaHeight(JAVA_HEIGHT);
mModel = new PropertyModel(ContinuousSearchContainerProperties.ALL_KEYS);
mMediator.onLayoutInitialized(mModel, requestLayout);
}
@Test
public void testShow_WithMinHeight_WithNativeAnimation() {
triggerShow();
// State 1. All top controls are offset-ed above the screen.
updateBrowserControlParamsAndAssertModel(
DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT + DEFAULT_MIN_HEIGHT, DEFAULT_MIN_HEIGHT,
true, -(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT), DEFAULT_MIN_HEIGHT - JAVA_HEIGHT,
false, View.GONE);
// State 2. Top controls are half-visible.
updateBrowserControlParamsAndAssertModel(
DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT + DEFAULT_MIN_HEIGHT, DEFAULT_MIN_HEIGHT,
true, -(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT) / 2,
((DEFAULT_CONTAINER_HEIGHT - JAVA_HEIGHT) / 2) + DEFAULT_MIN_HEIGHT, true,
View.GONE);
// State 3. Top controls are fully visible.
updateBrowserControlParamsAndAssertModel(
DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT + DEFAULT_MIN_HEIGHT, DEFAULT_MIN_HEIGHT,
true, 0, DEFAULT_CONTAINER_HEIGHT + DEFAULT_MIN_HEIGHT, false, View.VISIBLE);
Assert.assertNotNull(
"Mediator should be registered as a BrowserControlsStateProvider.Observer.",
mCurrentBrowserControlsObserver);
}
@Test
public void testShow_WithMinHeight_NoNativeAnimation() {
triggerShow();
// State 1. All top controls are offset-ed above the screen.
updateBrowserControlParamsAndAssertModel(
DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT + DEFAULT_MIN_HEIGHT, DEFAULT_MIN_HEIGHT,
false, -(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT), DEFAULT_MIN_HEIGHT - JAVA_HEIGHT,
false, View.GONE);
// State 2. Top controls are half-visible.
updateBrowserControlParamsAndAssertModel(
DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT + DEFAULT_MIN_HEIGHT, DEFAULT_MIN_HEIGHT,
false, -(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT) / 2,
((DEFAULT_CONTAINER_HEIGHT - JAVA_HEIGHT) / 2) + DEFAULT_MIN_HEIGHT, false,
View.VISIBLE);
// State 3. Top controls are fully visible.
updateBrowserControlParamsAndAssertModel(
DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT + DEFAULT_MIN_HEIGHT, DEFAULT_MIN_HEIGHT,
false, 0, DEFAULT_CONTAINER_HEIGHT + DEFAULT_MIN_HEIGHT, false, View.VISIBLE);
Assert.assertNotNull(
"Mediator should be registered as a BrowserControlsStateProvider.Observer.",
mCurrentBrowserControlsObserver);
}
@Test
public void testShow_NoMinHeight_WithNativeAnimation() {
triggerShow();
// State 1. All top controls are offset-ed above the screen.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, true,
-(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT), -JAVA_HEIGHT, false, View.GONE);
// State 2. Top controls are half-visible.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, true,
-(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT) / 2,
(DEFAULT_CONTAINER_HEIGHT - JAVA_HEIGHT) / 2, true, View.GONE);
// State 3. Top controls are fully visible.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, true, 0,
DEFAULT_CONTAINER_HEIGHT, false, View.VISIBLE);
Assert.assertNotNull(
"Mediator should be registered as a BrowserControlsStateProvider.Observer.",
mCurrentBrowserControlsObserver);
}
@Test
public void testShow_NoMinHeight_NoNativeAnimation() {
triggerShow();
// State 1. All top controls are offset-ed above the screen.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, false,
-(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT), -JAVA_HEIGHT, false, View.GONE);
// State 2. Top controls are half-visible.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, false,
-(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT) / 2,
(DEFAULT_CONTAINER_HEIGHT - JAVA_HEIGHT) / 2, false, View.VISIBLE);
// State 3. Top controls are fully visible.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, false,
0, DEFAULT_CONTAINER_HEIGHT, false, View.VISIBLE);
Assert.assertNotNull(
"Mediator should be registered as a BrowserControlsStateProvider.Observer.",
mCurrentBrowserControlsObserver);
}
/**
* (TODO:crbug/1184913) Show/hide animations driven by native are have some unexpected behavior
* when it comes to interaction between container and toolbar. It's not worth adding more
* tests for hide until that is fixed.
*/
@Test
public void testHide() {
triggerShow();
triggerHide();
updateBrowserControlParamsAndAssertModel(
DEFAULT_CONTAINER_HEIGHT, 0, true, 0, DEFAULT_CONTAINER_HEIGHT, false, View.GONE);
Assert.assertNull(
"Mediator should be not registered as a BrowserControlsStateProvider.Observer.",
mCurrentBrowserControlsObserver);
}
/**
* Tests that the container is invisible when the tab is obscured.
*/
@Test
public void testTabObscured_whileShowing() {
triggerShow();
// Top controls are fully visible.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, true, 0,
DEFAULT_CONTAINER_HEIGHT, false, View.VISIBLE);
mMediator.updateTabObscured(true);
Assert.assertTrue("Tab obscurity shouldn't change mMediator.mIsVisible.",
mMediator.isVisibleForTesting());
Assert.assertFalse("Composited view should only be visible while animating.",
mModel.get(ContinuousSearchContainerProperties.COMPOSITED_VIEW_VISIBLE));
Assert.assertEquals("Android view should be View.INVISIBLE when tab is obscured.",
View.INVISIBLE,
mModel.get(ContinuousSearchContainerProperties.ANDROID_VIEW_VISIBILITY));
mMediator.updateTabObscured(false);
Assert.assertTrue("Tab obscurity shouldn't change mMediator.mIsVisible.",
mMediator.isVisibleForTesting());
Assert.assertFalse("Composited view should only be visible while animating.",
mModel.get(ContinuousSearchContainerProperties.COMPOSITED_VIEW_VISIBLE));
Assert.assertEquals("Android view should be View.VISIBLE when tab is not obscured",
View.VISIBLE,
mModel.get(ContinuousSearchContainerProperties.ANDROID_VIEW_VISIBILITY));
}
/**
* Tests that the container is invisible when the tab is obscured, while the container is
* animating.
*/
@Test
public void testTabObscured_whileAnimating() {
triggerShow();
mMediator.updateTabObscured(true);
// When tab is obscured, Android view should be View.INVISIBLE and composited view should
// be invisible.
// State 1. All top controls are offset-ed above the screen.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, true,
-(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT), -JAVA_HEIGHT, false, View.INVISIBLE);
// State 2. Top controls are half-visible.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, true,
-(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT) / 2,
(DEFAULT_CONTAINER_HEIGHT - JAVA_HEIGHT) / 2, false, View.INVISIBLE);
// State 3. Top controls are fully visible.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, true, 0,
DEFAULT_CONTAINER_HEIGHT, false, View.INVISIBLE);
// ===========================================
mMediator.updateTabObscured(false);
// Tab is no longer is obscured. Android view should be View.GONE and composited view should
// be visible during animation.
// State 1. All top controls are offset-ed above the screen.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, true,
-(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT), -JAVA_HEIGHT, false, View.GONE);
// State 2. Top controls are half-visible.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, true,
-(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT) / 2,
(DEFAULT_CONTAINER_HEIGHT - JAVA_HEIGHT) / 2, true, View.GONE);
// State 3. Top controls are fully visible.
updateBrowserControlParamsAndAssertModel(DEFAULT_CONTAINER_HEIGHT + JAVA_HEIGHT, 0, true, 0,
DEFAULT_CONTAINER_HEIGHT, false, View.VISIBLE);
}
private void triggerShow() {
CallbackHelper heightObserverCallback = new CallbackHelper();
mMediator.addHeightObserver(result -> {
Assert.assertEquals("Height provided by mediator doesn't match java height.",
mCurrentExpectedHeight, result.intValue());
heightObserverCallback.notifyCalled();
});
mCurrentExpectedHeight = JAVA_HEIGHT;
mMediator.show();
Assert.assertTrue("Mediator should be visible.", mMediator.isVisibleForTesting());
Assert.assertEquals(
"Height observer should've been called.", 1, heightObserverCallback.getCallCount());
Assert.assertEquals("Mediator didn't register BrowserControlsStateProvider.Observer.",
mMediator, mCurrentBrowserControlsObserver);
}
private void triggerHide() {
mCurrentExpectedHeight = 0;
mMediator.hide();
Assert.assertFalse("Mediator should be invisible.", mMediator.isVisibleForTesting());
Assert.assertEquals(
"Mediator should still be registered as a BrowserControlsStateProvider.Observer.",
mMediator, mCurrentBrowserControlsObserver);
}
/**
* Sets browser controls params mocks call to onControlsOffsetChanged. In reality this is done
* by BrowserControlsStateProvider.
*/
private void updateBrowserControlParamsAndAssertModel(int topControlsHeight, int minHeight,
boolean canAnimate, int topOffset, int expectedVerticalOffset,
boolean expectedCompositedViewVisibility, int expectedAndroidViewVisibility) {
mCurrentTopControlsHeight = topControlsHeight;
mCurrentTopControlsMinHeight = minHeight;
mCanAnimateNative = canAnimate;
mCurrentBrowserControlsObserver.onControlsOffsetChanged(topOffset, 0, 0, 0, true);
assertModelVerticalOffset(expectedVerticalOffset);
assertModelViewVisibility(expectedCompositedViewVisibility, expectedAndroidViewVisibility);
}
private void assertModelVerticalOffset(int expectation) {
Assert.assertEquals("Container vertical offset should be " + expectation, expectation,
mModel.get(ContinuousSearchContainerProperties.VERTICAL_OFFSET));
}
private void assertModelViewVisibility(
boolean isCompositedViewVisible, int androidViewVisibility) {
Assert.assertEquals(
"Composited view should be " + (isCompositedViewVisible ? "" : "in") + "visible.",
isCompositedViewVisible,
mModel.get(ContinuousSearchContainerProperties.COMPOSITED_VIEW_VISIBLE));
Assert.assertEquals("Android view visibility should be " + androidViewVisibility,
androidViewVisibility,
mModel.get(ContinuousSearchContainerProperties.ANDROID_VIEW_VISIBILITY));
}
}
|
CanadianBaconBoi/AdvancedPeripherals
|
src/main/java/de/srendi/advancedperipherals/common/village/VillageStructures.java
|
package de.srendi.advancedperipherals.common.village;
import com.mojang.datafixers.util.Pair;
import de.srendi.advancedperipherals.AdvancedPeripherals;
import de.srendi.advancedperipherals.common.configuration.APConfig;
import net.minecraft.core.Registry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.data.worldgen.*;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.levelgen.feature.structures.StructurePoolElement;
import net.minecraft.world.level.levelgen.feature.structures.StructureTemplatePool;
import net.minecraft.world.level.levelgen.feature.structures.StructureTemplatePool.Projection;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
public class VillageStructures {
//Adapted from Pneumaticcraft
public static void init() {
if (!APConfig.WORLD_CONFIG.ENABLE_VILLAGER_STRUCTURES.get())
return;
//Ensure the vanilla static init is done
PlainVillagePools.bootstrap();
SavannaVillagePools.bootstrap();
TaigaVillagePools.bootstrap();
DesertVillagePools.bootstrap();
SnowyVillagePools.bootstrap();
//Add the scientist house to each village biome
for (String biome : new String[]{"desert", "snowy", "plains", "savanna", "taiga"}) {
AdvancedPeripherals.debug("Register generating scientist_" + biome + " village house");
addToPool(new ResourceLocation("village/" + biome + "/houses"),
AdvancedPeripherals.MOD_ID + ":villages/scientist_" + biome, APConfig.WORLD_CONFIG.VILLAGER_STRUCTURE_WEIGHT.get());
}
}
private static void addToPool(ResourceLocation pool, String toAdd, int weight) {
StructureTemplatePool old = BuiltinRegistries.TEMPLATE_POOL.get(pool);
if (old == null) {
AdvancedPeripherals.debug("no jigsaw pool for " + pool + "? skipping villager house generation for it");
return;
}
List<StructurePoolElement> shuffled = old.getShuffledTemplates(ThreadLocalRandom.current());
List<Pair<StructurePoolElement, Integer>> newPieces = shuffled.stream().map(p -> Pair.of(p, 1)).collect(Collectors.toList());
StructurePoolElement newPiece = StructurePoolElement.legacy(toAdd).apply(Projection.RIGID);
newPieces.add(Pair.of(newPiece, weight));
Registry.register(BuiltinRegistries.TEMPLATE_POOL, pool, new StructureTemplatePool(pool, old.getName(), newPieces));
AdvancedPeripherals.debug("Finished registration for " + toAdd);
}
}
|
wilsonchang17/Leetcode-practice
|
Pascal's Triangle.py
|
<filename>Pascal's Triangle.py
class Solution:
def generate(self, row: int) -> List[List[int]]:
if row == 1:
return [[1]]
if row == 2:
return [[1],[1,1]]
ans = [[1],[1,1]]
for i in range(2,row):
temp = []
for j in range(i+1):
if j == i or j == 0:
temp.append(1)
else:
temp.append(ans[i-1][j-1]+ans[i-1][j])
ans.append(temp)
return ans
|
xdxxdx/neighbor
|
neighbor-server/src/main/java/cn/icrat/dao/entity/Areas.java
|
package cn.icrat.dao.entity;
import cn.icrat.dao.base.BaseDomain;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Objects;
@Entity
public class Areas extends BaseDomain {
private String areaid;
private String area;
private String cityid;
@Basic
@Column(name = "areaid")
public String getAreaid() {
return areaid;
}
public void setAreaid(String areaid) {
this.areaid = areaid;
}
@Basic
@Column(name = "area")
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
@Basic
@Column(name = "cityid")
public String getCityid() {
return cityid;
}
public void setCityid(String cityid) {
this.cityid = cityid;
}
}
|
silenc3502/MYSQL-Arch-Doc-Summary
|
mysql-server/sql/json_path.h
|
<reponame>silenc3502/MYSQL-Arch-Doc-Summary<filename>mysql-server/sql/json_path.h
#ifndef SQL_JSON_PATH_INCLUDED
#define SQL_JSON_PATH_INCLUDED
/* Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
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, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file json_path.h
This file contains interface support for the JSON path abstraction.
The path abstraction is described by the functional spec
attached to WL#7909.
*/
#include <stddef.h>
#include <algorithm>
#include <new>
#include <string>
#include <utility>
#include "my_alloc.h" // MEM_ROOT
#include "my_dbug.h" // DBUG_ASSERT
#include "my_inttypes.h"
#include "my_sys.h"
#include "prealloced_array.h" // Prealloced_array
class String;
/** The type of a Json_path_leg. */
enum enum_json_path_leg_type {
/**
A path leg that represents a JSON object member (such as `.name`).
This path leg matches a single member in a JSON object.
*/
jpl_member,
/**
A path leg that represents a JSON array cell (such as `[10]`).
This path leg matches a single element in a JSON object.
*/
jpl_array_cell,
/**
A path leg that represents a range in a JSON array
(such as `[2 to 7]`).
*/
jpl_array_range,
/**
A path leg that represents the member wildcard (`.*`), which
matches all the members of a JSON object.
*/
jpl_member_wildcard,
/**
A path leg that represents the array wildcard (`[*]`), which
matches all the elements of a JSON array.
*/
jpl_array_cell_wildcard,
/**
A path leg that represents the ellipsis (`**`), which matches any
JSON value and recursively all the JSON values nested within it if
it is an object or an array.
*/
jpl_ellipsis
};
/**
A class that represents the index of an element in a JSON array. The
index is 0-based and relative to the beginning of the array.
*/
class Json_array_index final {
/**
The array index. It is 0 if the specified index was before the
first element of the array, or equal to the array length if the
specified index was after the last element of the array.
*/
size_t m_index;
/** True if the array index is within the bounds of the array. */
bool m_within_bounds;
public:
/**
Construct a new Json_array_index object representing the specified
position in an array of the given length.
@param index the array index
@param from_end true if @a index is relative to the end of the array
@param array_length the length of the array
*/
Json_array_index(size_t index, bool from_end, size_t array_length)
: m_index(from_end ? (index < array_length ? array_length - index - 1 : 0)
: std::min(index, array_length)),
m_within_bounds(index < array_length) {}
/**
Is the array index within the bounds of the array?
@retval true if the array index is within bounds
@retval false otherwise
*/
bool within_bounds() const { return m_within_bounds; }
/**
Get the position in the array pointed to by this array index.
If the index is out of bounds, 0 will be returned if the array
index is before the first element in the array, or a value equal
to the length of the array if the index is after the last element.
@return the position in the array (0-based index relative to the
start of the array)
*/
size_t position() const { return m_index; }
};
/**
One path leg in a JSON path expression.
A path leg describes either a key/value pair in an object
or a 0-based index into an array.
*/
class Json_path_leg final {
/// The type of this path leg.
enum_json_path_leg_type m_leg_type;
/// The index of an array cell, or the start of an array range.
size_t m_first_array_index = 0;
/// Is #m_first_array_index relative to the end of the array?
bool m_first_array_index_from_end = false;
/// The end (inclusive) of an array range.
size_t m_last_array_index = 0;
/// Is #m_last_array_index relative to the end of the array?
bool m_last_array_index_from_end = false;
/// The member name of a member path leg.
std::string m_member_name;
public:
/**
Construct a wildcard or ellipsis path leg.
@param leg_type the type of wildcard (#jpl_ellipsis,
#jpl_member_wildcard or #jpl_array_cell_wildcard)
*/
explicit Json_path_leg(enum_json_path_leg_type leg_type)
: m_leg_type(leg_type) {
DBUG_ASSERT(leg_type == jpl_ellipsis || leg_type == jpl_member_wildcard ||
leg_type == jpl_array_cell_wildcard);
}
/**
Construct an array cell path leg.
@param index the 0-based index in the array,
relative to the beginning of the array
*/
explicit Json_path_leg(size_t index) : Json_path_leg(index, false) {}
/**
Construct an array cell path leg.
@param index the 0-based index in the array
@param from_end true if @a index is relative to the end of the array
*/
Json_path_leg(size_t index, bool from_end)
: m_leg_type(jpl_array_cell),
m_first_array_index(index),
m_first_array_index_from_end(from_end) {}
/**
Construct an array range path leg.
@param idx1 the start index of the range, inclusive
@param idx1_from_end true if the start index is relative
to the end of the array
@param idx2 the last index of the range, inclusive
@param idx2_from_end true if the last index is relative
to the end of the array
*/
Json_path_leg(size_t idx1, bool idx1_from_end, size_t idx2,
bool idx2_from_end)
: m_leg_type(jpl_array_range),
m_first_array_index(idx1),
m_first_array_index_from_end(idx1_from_end),
m_last_array_index(idx2),
m_last_array_index_from_end(idx2_from_end) {}
/**
Construct an object member path leg.
@param member_name the name of the object member
@param length the length of the member name
*/
Json_path_leg(const char *member_name, size_t length)
: m_leg_type(jpl_member), m_member_name(member_name, length) {}
/** Construct an object member path leg. */
Json_path_leg(const std::string &member_name)
: Json_path_leg(member_name.c_str(), member_name.length()) {}
/** Get the type of the path leg. */
enum_json_path_leg_type get_type() const { return m_leg_type; }
/** Get the member name of a ::jpl_member path leg. */
const std::string &get_member_name() const { return m_member_name; }
/** Turn into a human-readable string. */
bool to_string(String *buf) const;
/**
Is this path leg an auto-wrapping array accessor?
An auto-wrapping array accessor is an array accessor that matches
non-arrays by auto-wrapping them in a single-element array before doing
the matching.
This function returns true for any ::jpl_array_cell or ::jpl_array_range
path leg that would match the element contained in a single-element
array, and which therefore would also match non-arrays that have been
auto-wrapped in single-element arrays.
*/
bool is_autowrap() const;
/**
Get the first array cell pointed to by an array range, or the
array cell pointed to by an array cell index.
@param array_length the length of the array
*/
Json_array_index first_array_index(size_t array_length) const {
DBUG_ASSERT(m_leg_type == jpl_array_cell || m_leg_type == jpl_array_range);
return Json_array_index(m_first_array_index, m_first_array_index_from_end,
array_length);
}
/**
Get the last array cell pointed to by an array range. The range
includes this cell.
@param array_length the length of the array
*/
Json_array_index last_array_index(size_t array_length) const {
DBUG_ASSERT(m_leg_type == jpl_array_range);
return Json_array_index(m_last_array_index, m_last_array_index_from_end,
array_length);
}
/**
A structure that represents an array range.
*/
struct Array_range {
size_t m_begin; ///< Beginning of the range, inclusive.
size_t m_end; ///< End of the range, exclusive.
};
/**
Get the array range pointed to by a path leg of type
::jpl_array_range or ::jpl_array_cell_wildcard.
@param array_length the length of the array
*/
Array_range get_array_range(size_t array_length) const;
};
using Json_path_leg_pointers = Prealloced_array<const Json_path_leg *, 8>;
using Json_path_iterator = Json_path_leg_pointers::const_iterator;
/**
A path expression which can be used to seek to
a position inside a JSON value.
*/
class Json_seekable_path {
protected:
/** An array of pointers to the legs of the JSON path. */
Json_path_leg_pointers m_path_legs;
Json_seekable_path();
public:
/** Return the number of legs in this searchable path */
size_t leg_count() const { return m_path_legs.size(); }
/** Get an iterator pointing to the first path leg. */
Json_path_iterator begin() const { return m_path_legs.begin(); }
/** Get an iterator pointing just past the last path leg. */
Json_path_iterator end() const { return m_path_legs.end(); }
/** Get a pointer to the last path leg. The path must not be empty. */
const Json_path_leg *last_leg() const { return m_path_legs.back(); }
};
/**
A JSON path expression.
From the user's point of view, a path expression is a string literal
with the following structure. We parse this structure into a
Json_path object:
pathExpression ::= scope pathLeg (pathLeg)*
scope ::= dollarSign
pathLeg ::= member | arrayLocation | doubleAsterisk
member ::= period (keyName | asterisk)
arrayLocation ::=
leftBracket
(arrayIndex | arrayRange | asterisk)
rightBracket
arrayIndex ::=
non-negative-integer |
last [ minus non-negative-integer ]
arrayRange ::= arrayIndex to arrayIndex
keyName ::= ECMAScript-identifier | ECMAScript-string-literal
doubleAsterisk ::= **
to ::= "to"
last ::= "last"
*/
class Json_path final : public Json_seekable_path {
private:
/**
A MEM_ROOT in which the Json_path_leg objects pointed to by
#Json_seekable_path::m_path_legs are allocated.
*/
MEM_ROOT m_mem_root;
public:
Json_path();
~Json_path() {
for (const auto ptr : m_path_legs) ptr->~Json_path_leg();
}
/** Move constructor. */
Json_path(Json_path &&other) : m_mem_root(std::move(other.m_mem_root)) {
// Move the contents of m_path_legs from other into this.
m_path_legs = std::move(other.m_path_legs);
/*
Must also make sure that other.m_path_legs is empty, so that we
don't end up destroying the same objects twice; once from this's
destructor and once from other's destructor.
Move-constructing a vector would usually leave "other" empty,
but it is not guaranteed. Furthermore, m_path_legs is a
Prealloced_array, not a std::vector, so often moving will mean
copying from one prealloced area to another instead of simply
swapping pointers to the backing array. (And at the time of
writing Prealloced_array doesn't even have a move-assignment
operator, so the above assignment will always copy and leave
"other" unchanged.)
*/
other.m_path_legs.clear();
}
/** Move assignment. */
Json_path &operator=(Json_path &&other) {
if (&other != this) {
this->~Json_path();
new (this) Json_path(std::move(other));
}
return *this;
}
/**
Add a path leg to the end of this path.
@param[in] leg the leg to add
@return false on success, true on error
*/
bool append(const Json_path_leg &leg) {
auto ptr = new (&m_mem_root) Json_path_leg(leg);
return ptr == nullptr || m_path_legs.push_back(ptr);
}
/**
Resets this to an empty path with no legs.
*/
void clear() {
// Destruct all the Json_path_leg objects, and clear the pointers to them.
for (const auto ptr : m_path_legs) ptr->~Json_path_leg();
m_path_legs.clear();
// Mark the memory as ready for reuse.
free_root(&m_mem_root, MYF(MY_MARK_BLOCKS_FREE));
}
/**
Return true if the path can match more than one value in a JSON document.
@retval true if the path contains a path leg which is a wildcard,
ellipsis or array range
@retval false otherwise
*/
bool can_match_many() const;
/** Turn into a human-readable string. */
bool to_string(String *buf) const;
};
/**
A lightweight path expression. This exists so that paths can be cloned
from the path legs of other paths without allocating heap memory
to copy those legs into. This class does not own the memory of the
Json_path_leg objects pointed to by #Json_seekable_path::m_path_legs, it
just points to Json_path_leg objects that belong to a Json_path instance.
*/
class Json_path_clone final : public Json_seekable_path {
public:
/**
Add a path leg to the end of this cloned path.
@param[in] leg the leg to add
@return false on success, true on error
*/
bool append(const Json_path_leg *leg) { return m_path_legs.push_back(leg); }
/**
Resets this to an empty path with no legs.
*/
void clear() { m_path_legs.clear(); }
};
/**
Initialize a Json_path from a path expression.
Stops parsing on the first error. It initializes the Json_path and
returns false if the path is parsed successfully. Otherwise, it
returns false. In that case, the output bad_index argument will
contain an index into the path expression. The parsing failed near
that index.
@param[in] path_length The length of the path expression.
@param[in] path_expression The string form of the path expression.
@param[out] path The Json_path object to be initialized.
@param[out] bad_index If null is returned, the parsing failed around here.
@return false on success, true on error
*/
bool parse_path(size_t path_length, const char *path_expression,
Json_path *path, size_t *bad_index);
/**
A helper function that uses the above one as workhorse. Entry point for
for JSON_TABLE (Table_function_json class) and Json_path_cache. Raises an
error if the path expression is syntactically incorrect. Raises an
error if the path expression contains wildcard tokens but is not
supposed to. Otherwise updates the supplied Json_path object with
the parsed path.
@param[in] path_value A String to be interpreted as a path.
@param[in] forbid_wildcards True if the path shouldn't contain * or **
@param[out] json_path The object that will hold the parsed path
@returns false on success (valid path or NULL), true on error
*/
bool parse_path(const String &path_value, bool forbid_wildcards,
Json_path *json_path);
#endif /* SQL_JSON_PATH_INCLUDED */
|
mohdab98/cmps252_hw4.2
|
src/cmps252/HW4_2/UnitTesting/record_1522.java
|
package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("18")
class Record_1522 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 1522: FirstName is Karina")
void FirstNameOfRecord1522() {
assertEquals("Karina", customers.get(1521).getFirstName());
}
@Test
@DisplayName("Record 1522: LastName is Wesemann")
void LastNameOfRecord1522() {
assertEquals("Wesemann", customers.get(1521).getLastName());
}
@Test
@DisplayName("Record 1522: Company is Cannon Engineering & Equip Co")
void CompanyOfRecord1522() {
assertEquals("Cannon Engineering & Equip Co", customers.get(1521).getCompany());
}
@Test
@DisplayName("Record 1522: Address is 9430 Scranton Rd")
void AddressOfRecord1522() {
assertEquals("9430 Scranton Rd", customers.get(1521).getAddress());
}
@Test
@DisplayName("Record 1522: City is San Diego")
void CityOfRecord1522() {
assertEquals("San Diego", customers.get(1521).getCity());
}
@Test
@DisplayName("Record 1522: County is San Diego")
void CountyOfRecord1522() {
assertEquals("San Diego", customers.get(1521).getCounty());
}
@Test
@DisplayName("Record 1522: State is CA")
void StateOfRecord1522() {
assertEquals("CA", customers.get(1521).getState());
}
@Test
@DisplayName("Record 1522: ZIP is 92121")
void ZIPOfRecord1522() {
assertEquals("92121", customers.get(1521).getZIP());
}
@Test
@DisplayName("Record 1522: Phone is 858-546-7779")
void PhoneOfRecord1522() {
assertEquals("858-546-7779", customers.get(1521).getPhone());
}
@Test
@DisplayName("Record 1522: Fax is 858-546-7285")
void FaxOfRecord1522() {
assertEquals("858-546-7285", customers.get(1521).getFax());
}
@Test
@DisplayName("Record 1522: Email is <EMAIL>")
void EmailOfRecord1522() {
assertEquals("<EMAIL>", customers.get(1521).getEmail());
}
@Test
@DisplayName("Record 1522: Web is http://www.karinawesemann.com")
void WebOfRecord1522() {
assertEquals("http://www.karinawesemann.com", customers.get(1521).getWeb());
}
}
|
gknorman/ISIS3
|
isis/src/odyssey/apps/thmvistrim/main.cpp
|
<filename>isis/src/odyssey/apps/thmvistrim/main.cpp
/** This is free and unencumbered software released into the public domain.
The authors of ISIS do not claim copyright on the contents of this file.
For more details about the LICENSE terms and the AUTHORS, you will
find files of those names at the top level of this repository. **/
/* SPDX-License-Identifier: CC0-1.0 */
#include "Isis.h"
#include <string>
#include "ThemisVisCamera.h"
#include "SpecialPixel.h"
#include "ProcessByLine.h"
#include "CameraFactory.h"
#include "PushFrameCameraGroundMap.h"
using namespace Isis;
using namespace std;
void TrimFramelets(Buffer &, Buffer &);
bool NeedsTrimmed(int);
int frameletSize;
int frameletTopTrimSize, frameletBottomTrimSize,
frameletLeftTrimSize, frameletRightTrimSize;
void CalculateBottomTrim(Cube *icube);
void IsisMain() {
// Grab the file to import
ProcessByLine p;
UserInterface &ui = Application::GetUserInterface();
Cube *icube = p.SetInputCube("FROM");
// Make sure it is a Themis EDR/RDR
try {
if(icube->group("Instrument")["InstrumentID"][0] != "THEMIS_VIS") {
FileName inFileName = ui.GetCubeName("FROM");
QString msg = "This program is intended for use on THEMIS VIS images only. [";
msg += inFileName.expanded() + "] does not appear to be a THEMIS VIS image.";
throw IException(IException::User, msg, _FILEINFO_);
}
}
catch(IException &e) {
throw IException(e, IException::User,
"Unable to run thmvistrim with the given input cube.", _FILEINFO_);
}
p.SetOutputCube("TO");
frameletSize = 192 / toInt(icube->group("Instrument")["SpatialSumming"][0]);
frameletTopTrimSize = ui.GetInteger("TOPTRIM");
frameletLeftTrimSize = ui.GetInteger("LEFTTRIM");
frameletRightTrimSize = ui.GetInteger("RIGHTTRIM");
if(ui.WasEntered("BOTTOMTRIM")) {
frameletBottomTrimSize = ui.GetInteger("BOTTOMTRIM");
}
else {
CalculateBottomTrim(icube);
}
p.StartProcess(TrimFramelets);
p.EndProcess();
}
void TrimFramelets(Buffer &inBuffer, Buffer &outBuffer) {
if(NeedsTrimmed(inBuffer.Line())) {
for(int i = 0; i < outBuffer.size(); i++) {
outBuffer[i] = Isis::Null;
}
}
else {
for(int i = 0; i < outBuffer.size(); i++) {
if((i > frameletLeftTrimSize) && (i < outBuffer.size() - frameletRightTrimSize)) {
outBuffer[i] = inBuffer[i];
}
else {
outBuffer[i] = Isis::Null;
}
}
}
}
bool NeedsTrimmed(int line) {
int frameletLine = (line - 1) % frameletSize + 1;
return (frameletLine <= frameletTopTrimSize) || (frameletLine > (frameletSize - frameletBottomTrimSize));
}
/**
* This method uses the cube's camera to determine how much
* overlap exists. The lat,lon for the beginning of the
* second framelet is calculated, and then we determine where
* that lat,lon occurs in the first framelet. That occurring line
* minus the framelet size is how much vertical overlap there is.
* The top overlap is subtracted from the overlap because there is
* that much less vertical overlap.
*
* @param icube The input themis vis cube
*/
void CalculateBottomTrim(Cube *icube) {
frameletBottomTrimSize = 0;
if(icube->camera() == NULL) {
string msg = "A camera is required to automatically calculate the bottom "
"trim of a cube. Please run spiceinit on the input cube";
throw IException(IException::Unknown, msg, _FILEINFO_);
}
// We really don't care at all about the original camera. What's needed is
// a known even-framelet camera and a known odd-framelet camera. In order
// to get these, we change the cube labels in a local copy and create an
// odd framelet and an even framelet camera.
Pvl &cubeLabels = *icube->label();
PvlKeyword &framelets = cubeLabels.findGroup("Instrument", Pvl::Traverse)["Framelets"];
framelets = "Even";
Camera *camEven = CameraFactory::Create(*icube);
framelets = "Odd";
Camera *camOdd = CameraFactory::Create(*icube);
// Framelet 2 is even, so let's use the even camera to find the lat,lon at it's beginning
if(camEven->SetImage(1, frameletSize + 1)) {
double framelet2StartLat = camEven->UniversalLatitude();
double framelet2StartLon = camEven->UniversalLongitude();
// Let's figure out where this is in the nearest odd framelet (hopefully framelet 1)
if(camOdd->SetUniversalGround(framelet2StartLat, framelet2StartLon)) {
// The equivalent line to the start of framelet 2 is this found line
int equivalentLine = (int)(camOdd->Line() + 0.5);
// Trim the vertical overlap...
frameletBottomTrimSize = frameletSize - equivalentLine;
// Compensate for the top trim...
frameletBottomTrimSize -= frameletTopTrimSize;
// This will happen if the top trim is bigger than the overlap,
// make sure the bottom trim is good
if(frameletBottomTrimSize < 0) frameletBottomTrimSize = 0;
}
}
delete camEven;
delete camOdd;
}
|
constantstruggle/berty
|
js/packages/store/protocol/grpc-web-gen/bertytypes_pb_service.js
|
// package: berty.types.v1
// file: bertytypes.proto
|
ProgressBG-Python-Course/ProgressBG-VC2-Python
|
pages/themes/beginners/exceptions/Task_and_HW/pycharm_input_test.py
|
<filename>pages/themes/beginners/exceptions/Task_and_HW/pycharm_input_test.py
while True:
try:
usr_input = input("Enter something>>> ")
break
except:
print("An ERROR!")
|
thomasletsch/javaee-addon
|
src/test/java/org/vaadin/addons/javaee/selenium/po/BaseSideMenuPOTest.java
|
package org.vaadin.addons.javaee.selenium.po;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class BaseSideMenuPOTest {
@Test
public void testBuildXPath() {
BaseSideMenuPO po = new BaseSideMenuPO() {
};
String xpath = po.buildXPath(1, 2, 3);
assertEquals("//div[@id='SideMenu']/div/div[1]/div[2]/div[2]/div[2]/div[3]/div[1]", xpath);
}
}
|
HandScapeIncDrive/HSFLballPod
|
HandScapeSDK.framework/Versions/A/Headers/HSCHandMode.h
|
//
// HSCHandMode.h
// HandScapeSDK
//
// Created by <NAME> on 10/28/14.
// Copyright (c) 2014 HandScape, Inc. All rights reserved.
//
#ifndef HandScapeSDK_HSCHandMode_h
#define HandScapeSDK_HSCHandMode_h
typedef enum HSCHandMode
{
HSCHandMode_BOTH_HANDS, HSCHandMode_LEFT_HAND_ONLY, HSCHandMode_RIGHT_HAND_ONLY
} HSCHandMode;
#endif
|
JArandaIzquierdo/FP
|
Examenes/Julio20182/Ejercicio1.cpp
|
<reponame>JArandaIzquierdo/FP
#include <iostream>
using namespace std;
bool comprobar(int v1[], int v2[], int tamV1, int tamV2){
bool iguales = false;
if(tamV1 != tamV2)
return false;
for(int i=0;i<tamV1;i++){
iguales=false;
for(int j=0; j<tamV2;j++){
if(v1[i]==v2[j])
iguales = true;
}
if(iguales==false)
return false;
}
if(iguales)
return true;
}
int main(){
const int tamV1=3;
const int tamV2=3;
int v1[tamV1]={1,2,3};
int v2[tamV2]={3,1,2};
bool sonIguales=comprobar(v1, v2, tamV1, tamV2);
if(sonIguales)
cout<<"Los vectores son iguales"<<endl;
else
cout<<"Los vectores NO son iguales"<<endl;
}
|
ewangchong/bob-lab
|
src/main/java/com/codergray/lintcode/binarysearch/Sqrt.java
|
package com.codergray.lintcode.binarysearch;
/**
* Created by cwang on 2/28/17.
*/
public class Sqrt {
public static int sqrt(int x) {
// write your code here
if(x<=0)
return 0;
if(x<4){
return 1;
}
// int start=0;
long root = x/2;
long end = x;
while(true){
if(root*root<=x && (root+1)*(root+1)>x){
break;
}else{
if(root*root>x){
end = root;
root = end/2;
}else{
root = (root+end)/2;
}
}
}
return (int)root;
}
public static void main(String[] args){
System.out.println(sqrt(81));
}
}
|
kei6u/datadog-agent
|
pkg/serverless/logs/scheduler.go
|
<filename>pkg/serverless/logs/scheduler.go
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package logs
import (
"github.com/DataDog/datadog-agent/pkg/logs/config"
"github.com/DataDog/datadog-agent/pkg/logs/schedulers"
"github.com/DataDog/datadog-agent/pkg/util/log"
)
// chanSource is the LogSource installed by this scheduler.
var chanSource *config.LogSource
// Scheduler is a logs-agent Scheduler that only manages one source, connected to
// the serverless logs channel.
type Scheduler struct {
logsChan chan *config.ChannelMessage
extraTags []string
}
var _ schedulers.Scheduler = &Scheduler{}
// NewScheduler creates a new Scheduler.
func NewScheduler(logsChan chan *config.ChannelMessage, extraTags []string) schedulers.Scheduler {
return &Scheduler{logsChan, extraTags}
}
// Start implements schedulers.Scheduler#Start.
func (s *Scheduler) Start(sourceMgr schedulers.SourceManager) {
log.Debug("Adding AWS Logs collection source")
chanSource = config.NewLogSource("AWS Logs", &config.LogsConfig{
Type: config.StringChannelType,
Source: "lambda", // TODO(remy): do we want this to be configurable at some point?
Tags: s.extraTags,
Channel: s.logsChan,
})
sourceMgr.AddSource(chanSource)
}
// Stop implements schedulers.Scheduler#Stop.
func (s *Scheduler) Stop() {}
// UpdateLogsTags updates the tags used for this source.
func UpdateLogsTags(tags []string) {
if chanSource != nil {
// NOTE(dustin): this is unsafe and susceptible to "write tearing", if
// the logs agent happens to be reading from this value at the same
// time as we write to it.
chanSource.Config.Tags = tags
}
}
|
hovinhthinh/Qsearch
|
src/storage/table/index/TABLEM.java
|
package storage.table.index;
import nlp.NLP;
import org.json.JSONException;
import org.json.JSONObject;
import util.Gson;
import util.distributed.String2StringMap;
import java.util.Arrays;
import java.util.List;
public class TABLEM extends String2StringMap {
@Override
public List<String> map(String input) {
try {
JSONObject o = new JSONObject(input);
TableIndex tableIndex = new TableIndex();
tableIndex.table = data.table.tablem.TABLEM.parseFromJSON(o);
if (tableIndex.table == null) {
return null;
}
tableIndex.caption = String.join(" ", NLP.tokenize(
o.has("title") ? o.getString("title") : "")
);
tableIndex.pageTitle = String.join(" ", NLP.tokenize(
o.has("pageTitle") ? o.getString("pageTitle") : "")
);
tableIndex.sectionTitles = "";
tableIndex.pageContent = String.join(" ", NLP.tokenize(
o.has("plainTextContent") ? o.getString("plainTextContent") : "")
);
tableIndex.tableText = tableIndex.table.getTableRawContentForSearch();
return Arrays.asList(Gson.toJson(tableIndex));
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
|
dylanbobb/Data-Structures-OOP
|
Course/src/course/InputGrades2.java
|
<gh_stars>1-10
package course;
import java.util.Scanner;
public class InputGrades2
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Student[] studentArr = new Student[4];
Course[] courseArr = new Course[5];
for(int i = 0; i < 4; i++)
{
System.out.print("Enter ID for student #" + (i+1) + ": ");
int idNum = keyboard.nextInt();
keyboard.nextLine();
for(int k = 0; k < 5; k++)
{
System.out.print("Enter course ID #" + (k+1) + ": ");
String id = keyboard.nextLine();
System.out.print("Enter credit worth for course #" + (k+1) + ": ");
double credit = keyboard.nextDouble();
keyboard.nextLine();
System.out.print("Enter grade for course #" + (k+1) + ": ");
char grade = keyboard.nextLine().toUpperCase().charAt(0);
while(grade != 'A' &&
grade != 'B' &&
grade != 'C' &&
grade != 'D' &&
grade != 'F')
{
System.out.println("Error: Invalid grade");
System.out.println("Please try again");
System.out.print("Enter grade for course #" + (k+1) + ": ");
grade = keyboard.nextLine().toUpperCase().charAt(0);
}
courseArr[k] = new Course(id,credit,grade);
}
studentArr[i] = new Student(idNum,courseArr);
}
}
}
|
newsummit/incubator-pinot
|
thirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/datalayer/bao/jdbc/DataCompletenessConfigManagerImpl.java
|
/**
* Copyright (C) 2014-2018 LinkedIn Corp. (<EMAIL>)
*
* 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.linkedin.thirdeye.datalayer.bao.jdbc;
import com.google.inject.Singleton;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import com.linkedin.thirdeye.datalayer.bao.DataCompletenessConfigManager;
import com.linkedin.thirdeye.datalayer.dto.DataCompletenessConfigDTO;
import com.linkedin.thirdeye.datalayer.pojo.DataCompletenessConfigBean;
import com.linkedin.thirdeye.datalayer.util.Predicate;
@Singleton
public class DataCompletenessConfigManagerImpl extends AbstractManagerImpl<DataCompletenessConfigDTO> implements DataCompletenessConfigManager {
public DataCompletenessConfigManagerImpl() {
super(DataCompletenessConfigDTO.class, DataCompletenessConfigBean.class);
}
@Override
public List<DataCompletenessConfigDTO> findAllByDataset(String dataset) {
Predicate predicate = Predicate.EQ("dataset", dataset);
return findByPredicate(predicate);
}
@Override
public DataCompletenessConfigDTO findByDatasetAndDateSDF(String dataset, String dateToCheckInSDF) {
Predicate predicate =
Predicate.AND(Predicate.EQ("dataset", dataset), Predicate.EQ("dateToCheckInSDF", dateToCheckInSDF));
List<DataCompletenessConfigBean> list = genericPojoDao.get(predicate, DataCompletenessConfigBean.class);
DataCompletenessConfigDTO result = null;
if (CollectionUtils.isNotEmpty(list)) {
result = MODEL_MAPPER.map(list.get(0), DataCompletenessConfigDTO.class);
}
return result;
}
@Override
public DataCompletenessConfigDTO findByDatasetAndDateMS(String dataset, Long dateToCheckInMS) {
Predicate predicate =
Predicate.AND(Predicate.EQ("dataset", dataset), Predicate.EQ("dateToCheckInMS", dateToCheckInMS));
List<DataCompletenessConfigBean> list = genericPojoDao.get(predicate, DataCompletenessConfigBean.class);
DataCompletenessConfigDTO result = null;
if (CollectionUtils.isNotEmpty(list)) {
result = MODEL_MAPPER.map(list.get(0), DataCompletenessConfigDTO.class);
}
return result;
}
@Override
public List<DataCompletenessConfigDTO> findAllInTimeRange(long startTime, long endTime) {
Predicate timePredicate = Predicate.AND(Predicate.GE("dateToCheckInMS", startTime), Predicate.LT("dateToCheckInMS", endTime));
return findByPredicate(timePredicate);
}
@Override
public List<DataCompletenessConfigDTO> findAllByDatasetAndInTimeRange(String dataset, long startTime, long endTime) {
Predicate timePredicate = Predicate.AND(Predicate.GE("dateToCheckInMS", startTime), Predicate.LT("dateToCheckInMS", endTime));
Predicate datasetPredicate = Predicate.EQ("dataset", dataset);
Predicate predicate = Predicate.AND(datasetPredicate, timePredicate);
return findByPredicate(predicate);
}
@Override
public List<DataCompletenessConfigDTO> findAllByDatasetAndInTimeRangeAndPercentCompleteGT(String dataset,
long startTime, long endTime, double percentComplete) {
Predicate timePredicate = Predicate.AND(Predicate.GE("dateToCheckInMS", startTime), Predicate.LT("dateToCheckInMS", endTime));
Predicate datasetPredicate = Predicate.EQ("dataset", dataset);
Predicate percentCompletePrediate = Predicate.GT("percentComplete", percentComplete);
Predicate predicate = Predicate.AND(datasetPredicate, timePredicate, percentCompletePrediate);
return findByPredicate(predicate);
}
@Override
public List<DataCompletenessConfigDTO> findAllByTimeOlderThan(long time) {
Predicate predicate = Predicate.LT("dateToCheckInMS", time);
return findByPredicate(predicate);
}
@Override
public List<DataCompletenessConfigDTO> findAllByTimeOlderThanAndStatus(long time, boolean dataComplete) {
Predicate datePredicate = Predicate.LT("dateToCheckInMS", time);
Predicate dataCompletePredicate = Predicate.EQ("dataComplete", dataComplete);
Predicate predicate = Predicate.AND(datePredicate, dataCompletePredicate);
return findByPredicate(predicate);
}
@Override
public List<DataCompletenessConfigDTO> findAllByDatasetAndInTimeRangeAndStatus(String dataset, long startTime,
long endTime, boolean dataComplete) {
Predicate timePredicate = Predicate.AND(Predicate.GE("dateToCheckInMS", startTime), Predicate.LT("dateToCheckInMS", endTime));
Predicate datasetPredicate = Predicate.EQ("dataset", dataset);
Predicate statusPredicate = Predicate.EQ("dataComplete", dataComplete);
Predicate finalPredicate = Predicate.AND(datasetPredicate, timePredicate, statusPredicate);
return findByPredicate(finalPredicate);
}
}
|
hispindia/BIHAR-2.7
|
dhis-2/dhis-services/dhis-service-patient/src/test/java/org/hisp/dhis/patientdatavalue/aggregation/PatientDataValueAggregationEngineTest.java
|
<gh_stars>0
/*
* Copyright (c) 2004-2009, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.patientdatavalue.aggregation;
import org.hisp.dhis.DhisSpringTest;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementCategoryService;
import org.hisp.dhis.dataelement.DataElementService;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.patient.Patient;
import org.hisp.dhis.patient.PatientService;
import org.hisp.dhis.patientdatavalue.PatientDataValue;
import org.hisp.dhis.patientdatavalue.PatientDataValueStore;
import org.junit.Test;
/**
* @author <NAME>
* @version $Id$
*/
@SuppressWarnings( "unused" ) //TODO
public class PatientDataValueAggregationEngineTest
extends DhisSpringTest
{
private PatientDataValueStore patientDataValueStore;
private PatientService patientService;
private OrganisationUnitService organisationUnitService;
private PatientDataValueAggregationEngine aggregationEngine;
private DataElement dataElementA;
private DataElement dataElementB;
private Patient patientA;
private Patient patientB;
private PatientDataValue valueA;
private PatientDataValue valueB;
private PatientDataValue valueC;
private PatientDataValue valueD;
private OrganisationUnit organisationUnit;
@Override
public void setUpTest()
{
patientDataValueStore = (PatientDataValueStore) getBean( PatientDataValueStore.ID );
dataElementService = (DataElementService) getBean( DataElementService.ID );
categoryService = (DataElementCategoryService) getBean( DataElementCategoryService.ID );
patientService = (PatientService) getBean( PatientService.ID );
organisationUnitService = (OrganisationUnitService) getBean ( OrganisationUnitService.ID );
aggregationEngine = (PatientDataValueAggregationEngine) getBean( PatientDataValueAggregationEngine.ID );
dataElementA = createDataElement( 'A' );
dataElementB = createDataElement( 'B' );
dataElementService.addDataElement( dataElementA );
dataElementService.addDataElement( dataElementB );
organisationUnit = createOrganisationUnit( 'A' );
organisationUnitService.addOrganisationUnit( organisationUnit );
patientA = createPatient( 'A', organisationUnit );
patientB = createPatient( 'B', organisationUnit );
patientService.savePatient( patientA );
patientService.savePatient( patientB );
}
@Test
public void aggregate()
{
}
}
|
shiyuting79118/-
|
web/common/dojo-release-1.12.2/dojo/DeferredList.js
|
<filename>web/common/dojo-release-1.12.2/dojo/DeferredList.js
/*
Copyright (c) 2004-2016, The JS Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/DeferredList",["./_base/kernel","./_base/Deferred","./_base/array"],function(b,c,d){b.DeferredList=function(a,b,k,l,m){var f=[];c.call(this);var e=this;0!==a.length||b||this.resolve([0,[]]);var g=0;d.forEach(a,function(c,d){function h(b,c){f[d]=[b,c];g++;g===a.length&&e.resolve(f)}c.then(function(a){b?e.resolve([d,a]):h(!0,a)},function(a){k?e.reject(a):h(!1,a);if(l)return null;throw a;})})};b.DeferredList.prototype=new c;b.DeferredList.prototype.gatherResults=function(a){a=new b.DeferredList(a,
!1,!0,!1);a.addCallback(function(a){var b=[];d.forEach(a,function(a){b.push(a[1])});return b});return a};return b.DeferredList});
//# sourceMappingURL=DeferredList.js.map
|
korjaa/mbed-os
|
features/nanostack/sal-stack-nanostack/source/Security/PANA/pana_avp.c
|
/*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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 "nsconfig.h"
#include "ns_types.h"
#include "string.h"
#include "common_functions.h"
#include "Security/PANA/pana_avp.h"
#ifdef PANA
uint8_t *pana_avp_base_write(uint8_t avp_type, uint16_t length, uint8_t *dptr, uint16_t flags, uint32_t vendor_id)
{
dptr = common_write_16_bit(avp_type, dptr); //AVP Type
dptr = common_write_16_bit(flags, dptr); //FLAGS
dptr = common_write_16_bit(length, dptr); //LEN
dptr = common_write_16_bit(0, dptr); //RESERVED
if (flags & PANA_EAP_VENDOR_FLAG) {
dptr = common_write_32_bit(vendor_id, dptr); //SET VENDOR
}
return dptr;
}
uint8_t *pana_avp_32_bit_write(uint8_t avp_type, uint32_t value, uint8_t *dptr)
{
dptr = pana_avp_base_write(avp_type, 4, dptr, 0, 0);
return common_write_32_bit(value, dptr);
}
uint8_t *pana_avp_write_n_bytes(uint16_t avp_type, uint16_t length, const uint8_t *value, uint8_t *dptr)
{
dptr = pana_avp_base_write(avp_type, length,dptr, 0, 0);
if (value) {
memcpy(dptr, value, length);
} else {
memset(dptr, 0, length);
}
dptr += length;
//Padding
while(length % 4) {
*dptr++= 0;
length++;
}
return dptr;
}
uint8_t *pana_avp_vendor_id_write_n_bytes(uint16_t avp_type, uint16_t length, const uint8_t *value, uint8_t *dptr, uint32_t vendor_id)
{
dptr = pana_avp_base_write(avp_type, length,dptr, PANA_EAP_VENDOR_FLAG, vendor_id);
if (value) {
memcpy(dptr, value, length);
} else {
memset(dptr, 0, length);
}
dptr += length;
while(length % 4) {
*dptr++= 0;
length++;
}
return dptr;
}
bool pana_avp_discover(uint8_t *dptr, uint16_t data_len, pana_avp_t *avp)
{
uint16_t avp_code;
uint16_t readed = 0, pana_temp_var_16 = 0;
avp->avp_ptr = NULL;
while (readed < data_len) {
avp->flags = 0;
avp->vendor_id = 0;
avp_code = common_read_16_bit(dptr);
dptr += 2;
avp->flags = common_read_16_bit(dptr);
dptr += 2;
pana_temp_var_16 = common_read_16_bit(dptr);
if (pana_temp_var_16 == 0) {
return false;
}
dptr += 4; //Update pointer and Skip Reserved
avp->len = pana_temp_var_16;
if (avp->flags & PANA_EAP_VENDOR_FLAG) {
avp->vendor_id = common_read_32_bit(dptr);
dptr += 4;
readed += 4;
}
readed += 8;
readed += pana_temp_var_16;
//Set Data Start here already
avp->avp_ptr = dptr;
dptr += pana_temp_var_16;
//Check division remainder
while(pana_temp_var_16 % 4) {
dptr++;
readed++;
pana_temp_var_16++;
}
if (readed > data_len) {
avp->avp_ptr = NULL;
return false;
}
if (avp_code == avp->code) {
//Save AVP pointer
return true;
}
avp->avp_ptr = NULL;
}
return false;
}
#endif
|
wjh1225/site
|
src/main/java/com/thinkgem/jeesite/mother/m/dao/OrderDao.java
|
<reponame>wjh1225/site<gh_stars>0
package com.thinkgem.jeesite.mother.m.dao;
import com.sun.tools.corba.se.idl.constExpr.Or;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.mother.m.entity.Order;
import java.util.List;
import java.util.Map;
/**
* Created by wangJH on 2017/11/3.
*/
@MyBatisDao
public interface OrderDao extends CrudDao<Order> {
//ๆน้็ๆ่ฎขๅ
int addList(List<Order> list);
List<String> findOrderNumber(Map<String, Object> map);
List<Order> findOrderListByOrderNumber(List<String> list);
int updateOrderState(Map<String, Object> map);
//ๅๅฐๅ่ดง
int delivery(Order order);
//้่ดนๆไฝ
int updateRefund(Map<String, Object> map);
//ๅ ้ค
int updateByOrderNumber(String orderNumber);
}
|
Biba93/FlashLang
|
app/src/main/java/com/github/biba/flashlang/operations/impl/info/local/impl/achievement/UploadAllOperation.java
|
package com.github.biba.flashlang.operations.impl.info.local.impl.achievement;
import com.github.biba.flashlang.domain.models.achievement.Achievement;
import com.github.biba.flashlang.operations.impl.info.local.impl.generic.AbstractUploadAllOperation;
public class UploadAllOperation extends AbstractUploadAllOperation<Achievement> {
public UploadAllOperation(final Achievement[] pModels) {
super(pModels);
}
}
|
sbordet/dynamic-proxies-samples
|
core/src/main/java/eu/javaspecialists/books/dynamicproxies/ch01/ProxyStructure.java
|
<filename>core/src/main/java/eu/javaspecialists/books/dynamicproxies/ch01/ProxyStructure.java
/*
* Copyright (C) 2020 <NAME>
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. <NAME>
* licenses this file to you under the Apache License, Version
* 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package eu.javaspecialists.books.dynamicproxies.ch01;
public class ProxyStructure {
// tag::listing[]
public class Client {
void execute(Subject subject) {
subject.request();
}
}
public interface Subject {
void request();
}
public class RealSubject implements Subject {
@Override
public void request() {
/* left to our imagination */
}
}
public class Proxy implements Subject {
private final RealSubject realSubject = new RealSubject();
@Override
public void request() {
realSubject.request();
}
}
// end::listing[]
}
|
Navarie/Balrok
|
src/main/java/visual/ShowKappaRok.java
|
package visual;
import common.GameImpl;
import framework.Game;
import minidraw.framework.DrawingEditor;
import minidraw.standard.MiniDrawApplication;
import variants.configuration.KappaFactoryBuilder;
import view.tool.StateTool;
public class ShowKappaRok {
public static void main(String[] args) {
Game game = new GameImpl(new KappaFactoryBuilder().build());
DrawingEditor editor = new MiniDrawApplication( "KappaRok!",
new BalrokFactory(game) );
StateTool stateTool = new StateTool(editor, game);
editor.open();
editor.showStatus("Initialised.");
game.addObserver(stateTool);
editor.setTool(stateTool);
}
}
|
laminalfalah/backend-framework
|
backend-framework-reactive/src/main/java/io/github/laminalfalah/backend/reactive/validator/PasswordValidatorReactive.java
|
<filename>backend-framework-reactive/src/main/java/io/github/laminalfalah/backend/reactive/validator/PasswordValidatorReactive.java
package io.github.laminalfalah.backend.reactive.validator;
/*
* Copyright (C) 2021 the original author laminalfalah All Right Reserved.
*
* io.github.laminalfalah.backend.reactive.validator
*
* This is part of the backend-framework.
*
* 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.
*/
import io.github.laminalfalah.backend.reactive.annotation.PasswordValidationReactive;
import io.github.laminalfalah.backend.validation.properties.PasswordProperties;
import io.github.laminalfalah.backend.validation.reactive.AbstractReactiveConstraintValidator;
import reactor.core.publisher.Mono;
import javax.validation.ConstraintValidatorContext;
import static io.github.laminalfalah.backend.validation.helper.PasswordHelper.*;
/**
* @author laminalfalah on 06/07/21
*/
public class PasswordValidatorReactive extends AbstractReactiveConstraintValidator<PasswordValidationReactive, String> {
private final PasswordProperties properties;
public PasswordValidatorReactive(PasswordProperties properties) {
this.properties = properties;
}
@Override
public Mono<Boolean> validate(String value, PasswordValidationReactive annotation, ConstraintValidatorContext context) {
if (value == null) {
return Mono.fromCallable(() -> false);
}
var validator = getPasswordValidator(properties);
var result = getRuleResult(validator, value);
if (result.isValid()) {
return Mono.fromCallable(() -> true);
}
var messages = getMessages(validator, result);
messages.forEach(v -> context.buildConstraintViolationWithTemplate(v)
.addConstraintViolation()
.disableDefaultConstraintViolation()
);
return Mono.fromCallable(() -> false);
}
}
|
SeriousWatermelon/wang-wen-jun
|
think-in-spring/src/main/java/com/wang/think/circulardependence/TestB.java
|
package com.wang.think.circulardependence;
/**
* @description: ๅพช็ฏๅผ็จ็ฑป ๆกไพ
* @author: <NAME>
* @date: 2020/12/23 17:53
*/
public class TestB {
private TestC testC;
public TestB() {
}
/**
* ๆ้ ๅจ ๅพช็ฏไพ่ต๏ผๆ ๆณ่งฃๅณ
*
* @param testC ๅๆฐ
*/
public TestB(TestC testC) {
this.testC = testC;
}
/**
* setter ๆนๅผๆณจๅ
ฅ็ๅพช็ฏไพ่ต๏ผๅฏไปฅ่งฃๅณ๏ผๆๅๆด้ฒไบ ObjectFactory๏ผ
*/
public void b() {
testC.c();
}
public TestC getTestC() {
return testC;
}
public void setTestC(TestC testC) {
this.testC = testC;
}
}
|
kylebarron/MagicPython
|
test/numbers/invalid.py
|
0123
0123l
123f
123d
123A
123__456
123_
0 : constant.numeric.dec.python, source.python
123 : constant.numeric.dec.python, invalid.illegal.dec.python, source.python
0123l : invalid.illegal.name.python, source.python
123f : invalid.illegal.name.python, source.python
123d : invalid.illegal.name.python, source.python
123A : invalid.illegal.name.python, source.python
123__456 : invalid.illegal.name.python, source.python
123_ : invalid.illegal.name.python, source.python
|
anedyalkov/JS-Applications
|
Exams/JavaScript-Software-University-master/JavaScript-Software-University-master/JavaScript-Advanced/Classes/Exercise/length-limit.js
|
class Stringer {
constructor(innerString, innerLength) {
this.innerString = innerString;
this.innerLength = innerLength;
this.resultString = innerString;
}
decrease(number) {
if (this.innerLength - number < 0) {
this.innerLength = 0;
} else {
this.innerLength -= number;
}
if (this.resultString.length > this.innerLength) {
if (this.innerLength === 0) {
this.resultString = '';
} else {
let difference = this.resultString.length - this.innerLength;
this.resultString = this.resultString.substr(0, difference);
}
}
}
increase(number) {
this.innerLength += number;
this.resultString = this.innerString.slice(0, this.innerLength);
}
toString() {
if (this.resultString.length < this.innerString.length) {
return `${this.resultString}${'.'.repeat(3)}`;
} else {
return this.innerString;
}
}
}
let test = new Stringer("Test", 5);
console.log(test.toString()); //Test
test.decrease(3);
console.log(test.toString()); //Te...
test.decrease(5);
console.log(test.toString()); //...
test.increase(5);
console.log(test.toString()); //Test
|
bigr-erasmusmc/StrongR
|
strongr/restdomain/model/oauth2/token.py
|
import strongr.core.gateways as gateways
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from authlib.flask.oauth2.sqla import OAuth2TokenMixin
from strongr.core.sqlalchemydatatypes.uuidtype import UUIDType
Base = gateways.Gateways.sqlalchemy_base()
class Token(Base, OAuth2TokenMixin):
__tablename__ = 'oauth_token'
id = Column(Integer, primary_key=True)
user_id = Column(String(64), ForeignKey('oauth_users.user_id', ondelete='CASCADE'))
|
madanagopaltcomcast/pxCore
|
examples/pxScene2d/external/libnode-v6.9.0/deps/cares/src/ares_version.c
|
<reponame>madanagopaltcomcast/pxCore<filename>examples/pxScene2d/external/libnode-v6.9.0/deps/cares/src/ares_version.c
#include "ares_setup.h"
#include "ares.h"
const char *ares_version(int *version)
{
if(version)
*version = ARES_VERSION;
return ARES_VERSION_STR;
}
|
WIZARD-CXY/pl
|
leetcode/nextpermutationstl.cpp
|
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(next_permutation(nums.begin(),nums.end())){
}else{
sort(nums.begin(),nums.end());
}
}
};
|
asantoz/trino
|
core/trino-main/src/main/java/io/trino/operator/UpdateOperator.java
|
/*
* 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 io.trino.operator;
import com.google.common.collect.ImmutableList;
import io.trino.spi.Page;
import io.trino.sql.planner.plan.PlanNodeId;
import java.util.List;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class UpdateOperator
extends AbstractRowChangeOperator
{
public static class UpdateOperatorFactory
implements OperatorFactory
{
private final int operatorId;
private final PlanNodeId planNodeId;
private final List<Integer> columnValueAndRowIdChannels;
private boolean closed;
public UpdateOperatorFactory(int operatorId, PlanNodeId planNodeId, List<Integer> columnValueAndRowIdChannels)
{
this.operatorId = operatorId;
this.planNodeId = requireNonNull(planNodeId, "planNodeId is null");
this.columnValueAndRowIdChannels = ImmutableList.copyOf(requireNonNull(columnValueAndRowIdChannels, "columnValueAndRowIdChannels is null"));
}
@Override
public Operator createOperator(DriverContext driverContext)
{
checkState(!closed, "Factory is already closed");
OperatorContext context = driverContext.addOperatorContext(operatorId, planNodeId, UpdateOperator.class.getSimpleName());
return new UpdateOperator(context, columnValueAndRowIdChannels);
}
@Override
public void noMoreOperators()
{
closed = true;
}
@Override
public OperatorFactory duplicate()
{
return new UpdateOperatorFactory(operatorId, planNodeId, columnValueAndRowIdChannels);
}
}
private final List<Integer> columnValueAndRowIdChannels;
public UpdateOperator(OperatorContext operatorContext, List<Integer> columnValueAndRowIdChannels)
{
super(operatorContext);
this.columnValueAndRowIdChannels = columnValueAndRowIdChannels;
}
@Override
public void addInput(Page page)
{
requireNonNull(page, "page is null");
checkState(state == State.RUNNING, "Operator is %s", state);
// Call the UpdatablePageSource to update rows in the page supplied.
pageSource().updateRows(page, columnValueAndRowIdChannels);
rowCount += page.getPositionCount();
}
}
|
jinzaizhichi/ledesoft
|
zerotier/config.json.js
|
<gh_stars>1000+
{
"version":"0.1",
"md5":"d97d8271a7da1cfd4ff813aae8d9b2b9",
"home_url":"Module_zerotier.asp",
"title":"ZeroTier",
"description":"ๅๅธๅผ็่ๆไปฅๅคช็ฝ",
"changelog":"",
"build_date":"2017-10-16_19:22:00"
}
|
dosmanak/kubernetes-ingress
|
controller/handler/pattern-files.go
|
// Copyright 2019 HAProxy Technologies LLC
//
// 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 handler
import (
"os"
"path/filepath"
"github.com/google/renameio"
config "github.com/haproxytech/kubernetes-ingress/controller/configuration"
"github.com/haproxytech/kubernetes-ingress/controller/haproxy/api"
"github.com/haproxytech/kubernetes-ingress/controller/store"
"github.com/haproxytech/kubernetes-ingress/controller/utils"
)
type PatternFiles struct {
files files
}
func (h *PatternFiles) Update(k store.K8s, cfg *config.ControllerCfg, api api.HAProxyClient) (reload bool, err error) {
h.files.dir = cfg.Env.PatternDir
if k.ConfigMaps.PatternFiles == nil {
return false, nil
}
for name, v := range k.ConfigMaps.PatternFiles.Annotations {
err = h.files.writeFile(name, v)
if err != nil {
logger.Errorf("failed writing patternfile '%s': %s", name, err)
}
}
for name, f := range h.files.data {
if !f.inUse {
err = h.files.deleteFile(name)
if err != nil {
logger.Errorf("failed deleting atternfile '%s': %s", name, err)
}
continue
}
if f.updated {
logger.Debugf("patternfile '%s' updated: reload required", name)
reload = true
}
f.inUse = false
f.updated = false
}
return reload, nil
}
type files struct {
dir string
data map[string]*file
}
type file struct {
hash string
inUse bool
updated bool
}
func (f *files) deleteFile(name string) error {
delete(f.data, name)
err := os.Remove(filepath.Join(f.dir, name))
return err
}
// writeFile checks if content hash has changed before writing it.
func (f *files) writeFile(name, content string) error {
newHash := utils.Hash([]byte(content))
if f.data == nil {
f.data = map[string]*file{}
}
if f.data[name] == nil {
f.data[name] = &file{}
}
file := f.data[name]
if file.hash != newHash {
if err := renameio.WriteFile(filepath.Join(f.dir, name), []byte(content), os.ModePerm); err != nil {
return err
}
file.hash = newHash
file.updated = true
}
file.inUse = true
return nil
}
|
Echon126/projectConfige
|
src/main/java/com/example/demo/entity/ForerunnerValidate.java
|
package com.example.demo.entity;
/**
* ๅฏนๅญๆฎต็ๆ ก้ช
* @author LCC
* @Date 2014ๅนด8ๆ9ๆฅ
*/
public class ForerunnerValidate {
/**
* ้็ฉบ
*/
private Boolean required;
/**
* ๆๅคงๅผ[ๅ
ๅซ]
*/
private String max;
/**
* ๆๅฐๅผ[ๅ
ๅซ]
*/
private String min;
/**
* ๆญฃๅ่กจ่พพๅผ
*/
private String custom;
/// Getter And Setter ///
public Boolean getRequired() {
return required;
}
public void setRequired(Boolean required) {
this.required = required;
}
public String getMax() {
return max;
}
public void setMax(String max) {
this.max = max;
}
public String getMin() {
return min;
}
public void setMin(String min) {
this.min = min;
}
public String getCustom() {
return custom;
}
public void setCustom(String custom) {
this.custom = custom;
}
}
|
nickrobinson/aoc2020
|
pkg/baggage/baggage.go
|
package baggage
import (
"errors"
log "github.com/sirupsen/logrus"
"gonum.org/v1/gonum/graph"
"gonum.org/v1/gonum/graph/simple"
)
type BaggageGraph struct {
ids map[string]int64
*simple.DirectedGraph
}
type Node struct {
color string
id int64
}
func (n Node) ID() int64 { return n.id }
func (n Node) String() string { return n.color }
func NewBaggageGraph() BaggageGraph {
return BaggageGraph{
ids: make(map[string]int64),
DirectedGraph: simple.NewDirectedGraph(),
}
}
func (g *BaggageGraph) AddNode(color string) {
if _, exists := g.ids[color]; exists {
return
}
// We know the node is not yet in the graph, so we can add it.
u := g.DirectedGraph.NewNode()
uid := u.ID()
u = Node{color: color, id: uid}
g.DirectedGraph.AddNode(u)
g.ids[color] = uid
}
func (g *BaggageGraph) AddEdge(fromColor string, toColor string) error {
fromNode := g.NodeFor(fromColor)
if fromNode == nil {
log.Errorf("Could not find node for %s", fromColor)
return errors.New("No matching node found")
}
toNode := g.NodeFor(toColor)
if toNode == nil {
log.Errorf("Could not find node for %s", fromColor)
return errors.New("No matching node found")
}
g.DirectedGraph.SetEdge(g.DirectedGraph.NewEdge(fromNode, toNode))
return nil
}
func (g BaggageGraph) NodeFor(word string) graph.Node {
id, ok := g.ids[word]
if !ok {
return nil
}
return g.DirectedGraph.Node(id)
}
|
nanotkarashish/spring-tests
|
rest-jsonpath/src/main/java/net/petrikainulainen/spring/testmvc/user/dto/UserDTO.java
|
package net.petrikainulainen.spring.testmvc.user.dto;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
* @author <NAME>
*/
public class UserDTO {
private String username;
private SecurityRole role;
public UserDTO(String username, SecurityRole role) {
this.username = username;
this.role = role;
}
public String getUsername() {
return username;
}
public SecurityRole getRole() {
return role;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
gourmetjs/gourmet-ssr
|
contrib/react-i80/gmsrc/BoundRoute.js
|
"use strict";
// `BoundRoute` can be created as one of two types:
// - A path based `BoundRoute` is created by `searchByPath()` and has
// the following members.
// - gmctx, _type
// - params: extracted from the matching path
// - url: result of `parseHref()` as following shape:
// - {origin, path, search, hash, href}
// - A component based `BoundRoute` is created by `searchByComponent` and has
// the following members.
// - gmctx, _type
// - params: input parameters given to `searchByComponent`
// - search: input parameters given to `searchByComponent`
// - hash: input parameters given to `searchByComponent`
// - reverse(): reverse URL function that returns a path string
module.exports = class BoundRoute {
constructor(gmctx, type, params) {
this.gmctx = gmctx;
this._type = type;
this.params = params;
}
getComponent() {
return this._type;
}
getHandlers() {
return this.getComponent().routeHandlers;
}
makeHref() {
if (this.url)
return this.url.href; // This route was made from a href, simply return the original href.
if (this.reverse) {
const path = this.reverse();
return encodeURI(path) + (this.search || "") + (this.hash || "");
}
throw Error("This BoundRoute was unable to generate a URL.");
}
};
|
cyberatz/go-choria
|
srvcache/servers_test.go
|
// Copyright (c) 2020-2021, <NAME> and the Choria Project contributors
//
// SPDX-License-Identifier: Apache-2.0
package srvcache
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestChoria(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "SRVCache")
}
var _ = Describe("Servers", func() {
var s *servers
BeforeEach(func() {
s = &servers{servers: []Server{NewServer("h1", 8080, "http"), NewServer("h2", 8080, "https")}}
})
Describe("Count", func() {
It("Should store the supplied servers", func() {
Expect(s.servers).To(HaveLen(2))
Expect(s.Count()).To(Equal(2))
})
})
Describe("Servers", func() {
It("Should return the stored servers", func() {
srvs := s.Servers()
Expect(srvs).To(HaveLen(2))
Expect(srvs[0].Host()).To(Equal("h1"))
Expect(srvs[1].Host()).To(Equal("h2"))
})
})
Describe("Each", func() {
It("Should yield all instances and allow edits", func() {
s.Each(func(srv Server) {
srv.SetHost("test" + srv.Host())
})
hps := s.HostPorts()
Expect(hps).To(Equal([]string{
"testh1:8080",
"testh2:8080",
}))
})
It("Should correctly handle empty collections", func() {
s = &servers{[]Server{}}
called := false
s.Each(func(srv Server) {
called = true
})
Expect(called).To(BeFalse())
})
})
Describe("Strings", func() {
It("Should return the right strings", func() {
Expect(s.Strings()).To(Equal([]string{
"http://h1:8080",
"https://h2:8080",
}))
})
})
Describe("URLs", func() {
It("Should produce correct URLs", func() {
urls, err := s.URLs()
Expect(err).ToNot(HaveOccurred())
Expect(urls[0].Host).To(Equal("h1:8080"))
Expect(urls[0].Scheme).To(Equal("http"))
Expect(urls[1].Host).To(Equal("h2:8080"))
Expect(urls[1].Scheme).To(Equal("https"))
})
})
Describe("HostPorts", func() {
It("Should produce correct hps", func() {
Expect(s.HostPorts()).To(Equal([]string{
"h1:8080",
"h2:8080",
}))
})
})
})
|
masakudamatsu/line-height-picker
|
src/img/AlertIconImage.js
|
import React from 'react';
const AlertIcon = ({className}) => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
className={className}
width="24"
height="24"
viewBox="0 0 24 24"
strokeWidth="2.5"
stroke="currentColor"
fill="none"
strokeLinecap="round"
strokeLinejoin="round"
role="img"
>
<title>Alert icon</title>
<path stroke="none" d="M0 0h24v24H0z" />
<path d="M12 9v2m0 4v.01" />
<path d="M5.07 19H19a2 2 0 0 0 1.75 -2.75L13.75 4a2 2 0 0 0 -3.5 0L3.25 16.25a2 2 0 0 0 1.75 2.75" />
</svg>
);
};
export default AlertIcon;
|
truthiswill/intellij-community
|
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/comparatorCombinators/afterIntegerDiff.java
|
// "Replace with Comparator.comparingInt" "true"
import java.util.*;
public class Main {
void sort(List<String> data) {
data.sort(Comparator.comparingInt(String::length));
}
}
|
y2ghost/study
|
c/network/hb_client2.c
|
<reponame>y2ghost/study
#include <etcp.h>
#include <stdio.h>
#include <heartbeat.h>
int main(int argc, char **argv)
{
fd_set allfd;
fd_set readfd;
char msg[1024] = {'\0'};
struct timeval tv;
struct sockaddr_in hblisten;
int sdata = -1;
int shb = -1;
int slisten = -1;
int rc = 0;
int hblistenlen = sizeof(hblisten);
int heartbeats = 0;
int maxfd1 = 0;
char hbmsg[1]= {'\0'};
if (3 != argc) {
fprintf(stderr, "invalid parameters!\n");
return 1;
}
slisten = tcp_server(NULL, "0");
rc = getsockname(slisten, (struct sockaddr*)&hblisten, (socklen_t*)&hblistenlen);
if (0 != rc) {
error(1, errno, "getsockname failure");
}
sdata = tcp_client(argv[1], argv[2]);
rc = send(sdata, (char *)&hblisten.sin_port, sizeof(hblisten.sin_port), 0);
if (rc < 0) {
error(1, errno, "send failure sending port");
}
shb = accept(slisten, NULL, NULL);
if (shb < 0) {
error(1, errno, "accept failure");
}
FD_ZERO(&allfd);
FD_SET(sdata, &allfd);
FD_SET(shb, &allfd);
maxfd1 = (sdata > shb ? sdata: shb) + 1;
tv.tv_sec = IDLE_TIME;
tv.tv_usec = 0;
while (1) {
readfd = allfd;
rc = select(maxfd1, &readfd, NULL, NULL, &tv);
if (rc < 0) {
error(1, errno, "select failure");
}
if (rc == 0) {
if (++heartbeats > 3) {
error(1, 0, "connection dead\n");
}
error(0, 0, "sending heartbeat #%d\n", heartbeats);
rc = send(shb, "", 1, 0);
if (rc < 0) {
error(1, errno, "send failure");
}
tv.tv_sec = WAIT_TIME;
continue;
}
if (0 != FD_ISSET(shb, &readfd)) {
rc = recv(shb, hbmsg, 1, 0);
if (rc == 0) {
error(1, 0, "server terminated (shb)\n");
}
if (rc < 0) {
error(1, errno, "bad recv on shb");
}
}
if (0 != FD_ISSET(sdata, &readfd)) {
rc = recv(sdata, msg, sizeof(msg), 0);
if (rc == 0) {
error(1, 0, "server terminated (sdata)\n");
}
if (rc < 0) {
error(1, errno, "recv failure");
}
/* process data */
}
heartbeats = 0;
tv.tv_sec = WAIT_TIME;
}
}
|
nilsvu/spectre
|
src/Parallel/Algorithms/AlgorithmGroupDeclarations.hpp
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include "Parallel/ArrayIndex.hpp"
#include "Parallel/Algorithms/AlgorithmGroup.decl.h"
namespace Parallel {
namespace Algorithms {
/*!
* \ingroup ParallelGroup
* \brief A struct that stores the charm++ types relevant for a particular group
* component
*
* \details The type traits are:
* - `cproxy`: the charm++ proxy.
* See https://charm.readthedocs.io/en/latest/faq/manual.html#what-is-a-proxy
* - `cbase`: the charm++ base class. See
* https://charm.readthedocs.io/en/latest/charm++/manual.html#chare-objects
* - `algorithm_type`: the chare type (`AlgorithmGroup`) for the group
* component.
* - `ckindex`: A charm++ chare index object. Useful for obtaining entry
* method indices that are needed for creating callbacks. See
* https://charm.readthedocs.io/en/latest/charm++/manual.html#creating-a-ckcallback-object
* - `cproxy_section`: The charm++ section proxy class. See
* https://charm.readthedocs.io/en/latest/charm++/manual.html?#sections-subsets-of-a-chare-array-group
* - component_type: this object. Serves to allow checking the component type in
* both source code and the testing framework.
*/
struct Group {
template <typename ParallelComponent,
typename SpectreArrayIndex>
using cproxy = CProxy_AlgorithmGroup<ParallelComponent,
SpectreArrayIndex>;
template <typename ParallelComponent,
typename SpectreArrayIndex>
using cbase = CBase_AlgorithmGroup<ParallelComponent,
SpectreArrayIndex>;
template <typename ParallelComponent,
typename SpectreArrayIndex>
using algorithm_type = AlgorithmGroup<ParallelComponent,
SpectreArrayIndex>;
template <typename ParallelComponent,
typename SpectreArrayIndex>
using ckindex = CkIndex_AlgorithmGroup<ParallelComponent,
SpectreArrayIndex>;
template <typename ParallelComponent, typename SpectreArrayIndex>
using cproxy_section =
CProxySection_AlgorithmGroup<ParallelComponent, SpectreArrayIndex>;
using component_type = Group;
};
} // namespace Algorithms
} // namespace Parallel
|
creatubbles/ctb-api-unity
|
Docs/reference/html/class_creatubbles_1_1_api_1_1_requests_1_1_o_auth_token_reponse.js
|
var class_creatubbles_1_1_api_1_1_requests_1_1_o_auth_token_reponse =
[
[ "access_token", "class_creatubbles_1_1_api_1_1_requests_1_1_o_auth_token_reponse.html#aff0155f135d1dd9d9abfe12afb242a2a", null ]
];
|
hellomoto-ai/bci-learning-studio
|
bci_learning_studio/qt/device_manager/sample_acquisition.py
|
<filename>bci_learning_studio/qt/device_manager/sample_acquisition.py<gh_stars>0
import time
import logging
import serial
from PyQt5 import QtCore
_LG = logging.getLogger(__name__)
class SampleAcquisitionThread(QtCore.QThread):
acquired = QtCore.pyqtSignal('PyQt_PyObject')
def __init__(self, board, wait_factor=0.85):
super().__init__()
self._board = board
self.wait_factor = wait_factor
def run(self):
_LG.info('Starting sample acquisition thread.')
# `cycle` here is a sensitive value;
# Setting it same as (1.0 * board.cycle) will cause sample acquisition
# out of sync (delayed) and you will see end byte not matching to
# expected value -> wrong value.
# Setting it to (0.5 * board.cycle) will cause sample acquisition
# too quick so that sample distribution over time is skewed.
#
# 0.85 was found okay in the sense that it does not cause wrong
# end byte while sample distribution over time is kind of smooth.
cycle = self.wait_factor * self._board.cycle
unit_wait = cycle / 10.0
last_acquired = time.monotonic()
while self._board.streaming:
now = time.monotonic()
if now - last_acquired < cycle:
self.sleep(unit_wait)
continue
try:
sample = self._board.read_sample()
if sample['valid']:
sample['sampling_rate'] = self._board.sample_rate
self.acquired.emit({'type': 'eeg', 'data': sample})
last_acquired = now
except serial.serialutil.SerialException:
_LG.info('Connection seems to be closed.')
except Exception: # pylint: disable=broad-except
_LG.exception('failed to fetch')
_LG.info('Sample acquisition thread stopped.')
|
ISCAS-VDI/neutron-base
|
neutron/pecan_wsgi/hooks/notifier.py
|
# Copyright (c) 2015 Mirantis, 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.
from neutron_lib import constants
from oslo_config import cfg
from oslo_log import log
from oslo_serialization import jsonutils
from pecan import hooks
from neutron.api.rpc.agentnotifiers import dhcp_rpc_agent_api
from neutron.common import rpc as n_rpc
from neutron import manager
from neutron.pecan_wsgi import constants as pecan_constants
LOG = log.getLogger(__name__)
class NotifierHook(hooks.PecanHook):
priority = 135
@property
def _notifier(self):
if not hasattr(self, '_notifier_inst'):
self._notifier_inst = n_rpc.get_notifier('network')
return self._notifier_inst
def _nova_notify(self, action, resource, *args):
action_resource = '%s_%s' % (action, resource)
if not hasattr(self, '_nova_notifier'):
# this is scoped to avoid a dependency on nova client when nova
# notifications aren't enabled
from neutron.notifiers import nova
self._nova_notifier = nova.Notifier()
self._nova_notifier.send_network_change(action_resource, *args)
def _notify_dhcp_agent(self, context, resource_name, action, resources):
plugin = manager.NeutronManager.get_plugin_for_resource(resource_name)
notifier_method = '%s.%s.end' % (resource_name, action)
# use plugin's dhcp notifier, if this is already instantiated
agent_notifiers = getattr(plugin, 'agent_notifiers', {})
dhcp_agent_notifier = (
agent_notifiers.get(constants.AGENT_TYPE_DHCP) or
dhcp_rpc_agent_api.DhcpAgentNotifyAPI()
)
# The DHCP Agent does not accept bulk notifications
for resource in resources:
item = {resource_name: resource}
LOG.debug("Sending DHCP agent notification for: %s", item)
dhcp_agent_notifier.notify(context, item, notifier_method)
def before(self, state):
if state.request.method not in ('POST', 'PUT', 'DELETE'):
return
resource = state.request.context.get('resource')
if not resource:
return
action = pecan_constants.ACTION_MAP.get(state.request.method)
event = '%s.%s.start' % (resource, action)
if action in ('create', 'update'):
# notifier just gets plain old body without any treatment other
# than the population of the object ID being operated on
payload = state.request.json.copy()
if action == 'update':
payload['id'] = state.request.context.get('resource_id')
elif action == 'delete':
resource_id = state.request.context.get('resource_id')
payload = {resource + '_id': resource_id}
self._notifier.info(state.request.context.get('neutron_context'),
event, payload)
def after(self, state):
resource_name = state.request.context.get('resource')
collection_name = state.request.context.get('collection')
neutron_context = state.request.context.get('neutron_context')
if not resource_name:
LOG.debug("Skipping NotifierHook processing as there was no "
"resource associated with the request")
return
action = pecan_constants.ACTION_MAP.get(state.request.method)
if not action or action == 'get':
LOG.debug("No notification will be sent for action: %s", action)
return
if state.response.status_int > 300:
LOG.debug("No notification will be sent due to unsuccessful "
"status code: %s", state.response.status_int)
return
if action == 'delete':
# The object has been deleted, so we must notify the agent with the
# data of the original object
data = {collection_name:
state.request.context.get('original_resources', [])}
else:
try:
data = jsonutils.loads(state.response.body)
except ValueError:
if not state.response.body:
data = {}
resources = []
if data:
if resource_name in data:
resources = [data[resource_name]]
elif collection_name in data:
# This was a bulk request
resources = data[collection_name]
# Send a notification only if a resource can be identified in the
# response. This means that for operations such as add_router_interface
# no notification will be sent
if cfg.CONF.dhcp_agent_notification and data:
self._notify_dhcp_agent(
neutron_context, resource_name,
action, resources)
if cfg.CONF.notify_nova_on_port_data_changes:
orig = {}
if action == 'update':
orig = state.request.context.get('original_resources')[0]
elif action == 'delete':
# NOTE(kevinbenton): the nova notifier is a bit strange because
# it expects the original to be in the last argument on a
# delete rather than in the 'original_obj' position
resources = (
state.request.context.get('original_resources') or [])
for resource in resources:
self._nova_notify(action, resource_name, orig,
{resource_name: resource})
event = '%s.%s.end' % (resource_name, action)
if action == 'delete':
resource_id = state.request.context.get('resource_id')
payload = {resource_name + '_id': resource_id}
elif action in ('create', 'update'):
if not resources:
# create/update did not complete so no notification
return
if len(resources) > 1:
payload = {collection_name: resources}
else:
payload = {resource_name: resources[0]}
else:
return
self._notifier.info(neutron_context, event, payload)
|
gmerz/MatterApi
|
matterapi/endpoints/async_api/shared_channels.py
|
<filename>matterapi/endpoints/async_api/shared_channels.py
""" Module to access the SharedChannels endpoints """
# pylint: disable=too-many-lines,too-many-locals,too-many-public-methods,too-few-public-methods
from typing import Any, Dict, List, Optional
from ...models import RemoteClusterInfo, SharedChannel
from ..base import ApiBaseClass
class SharedChannelsApi(ApiBaseClass):
"""Endpoints for getting information about shared channels."""
async def get_all_shared_channels(
self,
team_id: str,
*,
page: Optional[int] = 0,
per_page: Optional[int] = 0,
) -> List[SharedChannel]:
"""Get all shared channels for team.
Get all shared channels for a team.
Permissions:
Must be authenticated.
Minimum Server Version:
5.50
Api Reference:
`GetAllSharedChannels <https://api.mattermost.com/#operation/GetAllSharedChannels>`_
"""
url = f"/sharedchannels/{team_id}"
params: Dict[str, Any] = {
"page": page,
"per_page": per_page,
}
params = {k: v for k, v in params.items() if v is not None}
request_kwargs = {
"url": url,
"params": params,
}
# pylint: disable-next=protected-access
async with self.client._get_httpx_client() as httpx_client:
response = await httpx_client.get(
**request_kwargs,
)
if self.skip_response_parsing:
return response
if response.status_code == 200:
response200 = []
_response200 = response.json()
for response200_item_data in _response200:
response200_item = SharedChannel.parse_obj(response200_item_data)
response200.append(response200_item)
return response200
return response
async def get_remote_cluster_info(
self,
remote_id: str,
) -> RemoteClusterInfo:
"""Get remote cluster info by ID for user.
Get remote cluster info based on remoteId.
Permissions:
Must be authenticated and user must belong to at least one
channel shared with the remote cluster.
Minimum Server Version:
5.50
Api Reference:
`GetRemoteClusterInfo <https://api.mattermost.com/#operation/GetRemoteClusterInfo>`_
"""
url = f"/sharedchannels/remote_info/{remote_id}"
request_kwargs = {
"url": url,
}
# pylint: disable-next=protected-access
async with self.client._get_httpx_client() as httpx_client:
response = await httpx_client.get(
**request_kwargs,
)
if self.skip_response_parsing:
return response
if response.status_code == 200:
response200 = RemoteClusterInfo.parse_obj(response.json())
return response200
return response
|
tmtsoftware/csw
|
csw-event/csw-event-client/src/main/scala/csw/event/client/internal/kafka/KafkaPublisher.scala
|
package csw.event.client.internal.kafka
import akka.Done
import akka.actor.Cancellable
import akka.actor.typed.ActorSystem
import akka.kafka.ProducerSettings
import akka.stream.scaladsl.Source
import csw.event.api.exceptions.PublishFailure
import csw.event.api.scaladsl.EventPublisher
import csw.event.client.internal.commons.{EventConverter, EventPublisherUtil}
import csw.params.events.Event
import csw.time.core.models.TMTTime
import org.apache.kafka.clients.producer.{Callback, ProducerRecord}
import scala.concurrent.duration.{DurationDouble, FiniteDuration}
import scala.concurrent.{Future, Promise}
import scala.util.control.NonFatal
/**
* An implementation of [[csw.event.api.scaladsl.EventPublisher]] API which uses Apache Kafka as the provider for publishing
* and subscribing events.
*
* @param producerSettings future of settings for akka-streams-kafka API for Apache Kafka producer
*/
// $COVERAGE-OFF$
private[event] class KafkaPublisher(producerSettings: Future[ProducerSettings[String, Array[Byte]]])(implicit
actorSystem: ActorSystem[_]
) extends EventPublisher {
import actorSystem.executionContext
private val parallelism = 1
private val defaultInitialDelay: FiniteDuration = 0.millis
private val kafkaProducer = producerSettings.map(_.createKafkaProducer())
private val eventPublisherUtil = new EventPublisherUtil()
private val streamTermination: Future[Done] = eventPublisherUtil.streamTermination(publishInternal)
override def publish(event: Event): Future[Done] = {
eventPublisherUtil.publish(event, streamTermination.isCompleted)
}
private def publishInternal(event: Event): Future[Done] = {
val p = Promise[Done]()
kafkaProducer.map(_.send(eventToProducerRecord(event), completePromise(event, p))).recover { case NonFatal(ex) =>
p.failure(PublishFailure(event, ex))
}: Any
p.future
}
override def publish[Mat](source: Source[Event, Mat]): Mat =
eventPublisherUtil.publishFromSource(source, parallelism, publishInternal, None)
override def publish[Mat](source: Source[Event, Mat], onError: PublishFailure => Unit): Mat =
eventPublisherUtil.publishFromSource(source, parallelism, publishInternal, Some(onError))
override def publish(eventGenerator: => Option[Event], every: FiniteDuration): Cancellable =
publish(eventPublisherUtil.eventSource(Future.successful(eventGenerator), parallelism, defaultInitialDelay, every))
override def publish(eventGenerator: => Option[Event], startTime: TMTTime, every: FiniteDuration): Cancellable =
publish(eventPublisherUtil.eventSource(Future.successful(eventGenerator), parallelism, startTime.durationFromNow, every))
override def publish(eventGenerator: => Option[Event], every: FiniteDuration, onError: PublishFailure => Unit): Cancellable =
publish(eventPublisherUtil.eventSource(Future.successful(eventGenerator), parallelism, defaultInitialDelay, every), onError)
override def publish(
eventGenerator: => Option[Event],
startTime: TMTTime,
every: FiniteDuration,
onError: PublishFailure => Unit
): Cancellable =
publish(
eventPublisherUtil.eventSource(Future.successful(eventGenerator), parallelism, startTime.durationFromNow, every),
onError
)
override def publishAsync(eventGenerator: => Future[Option[Event]], every: FiniteDuration): Cancellable =
publish(eventPublisherUtil.eventSource(eventGenerator, parallelism, defaultInitialDelay, every))
override def publishAsync(eventGenerator: => Future[Option[Event]], startTime: TMTTime, every: FiniteDuration): Cancellable =
publish(eventPublisherUtil.eventSource(eventGenerator, parallelism, startTime.durationFromNow, every))
override def publishAsync(
eventGenerator: => Future[Option[Event]],
every: FiniteDuration,
onError: PublishFailure => Unit
): Cancellable =
publish(eventPublisherUtil.eventSource(eventGenerator, parallelism, defaultInitialDelay, every), onError)
override def publishAsync(
eventGenerator: => Future[Option[Event]],
startTime: TMTTime,
every: FiniteDuration,
onError: PublishFailure => Unit
): Cancellable =
publish(eventPublisherUtil.eventSource(eventGenerator, parallelism, startTime.durationFromNow, every), onError)
override def shutdown(): Future[Done] =
kafkaProducer.map { x =>
eventPublisherUtil.shutdown()
scala.concurrent.blocking(x.close())
Done
}
private def eventToProducerRecord(event: Event): ProducerRecord[String, Array[Byte]] =
new ProducerRecord(event.eventKey.key, EventConverter.toBytes[Array[Byte]](event))
// callback to be complete the future operation for publishing when the record has been acknowledged by the server
private def completePromise(event: Event, promisedDone: Promise[Done]): Callback = {
case (_, null) => promisedDone.success(Done)
case (_, ex: Exception) => promisedDone.failure(PublishFailure(event, ex))
}
}
// $COVERAGE-ON$
|
metux/chromium-deb
|
ash/wm/tablet_mode/tablet_mode_backdrop_delegate_impl.cc
|
<reponame>metux/chromium-deb
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/wm/tablet_mode/tablet_mode_backdrop_delegate_impl.h"
namespace ash {
TabletModeBackdropDelegateImpl::TabletModeBackdropDelegateImpl() = default;
TabletModeBackdropDelegateImpl::~TabletModeBackdropDelegateImpl() = default;
bool TabletModeBackdropDelegateImpl::HasBackdrop(aura::Window* window) {
return true;
}
} // namespace ash
|
lsr123/PX4-loacl_code
|
NuttX/apps/graphics/traveler/tools/misc/pll2txt.c
|
/****************************************************************************
* apps/graphics/traveler/tools/misc/pll2txt.c
*
* Copyright (C) 2014 <NAME>. All rights reserved.
* Author: <NAME> <<EMAIL>>
*
* 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.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included files
****************************************************************************/
#define FAR
#include "trv_types.h"
#include "trv_plane.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/****************************************************************************
* Private Data
****************************************************************************/
static bool b_use_hex = false;
/****************************************************************************
* Private Functions
****************************************************************************/
static int dump_plane(FILE *instream, FILE *outstream, int nrects)
{
struct trv_rect_data_s rect;
int i;
for (i = 1; i <= nrects; i++)
{
if (fread((char*)&rect, RESIZEOF_TRVRECTDATA_T, 1, instream) != 1)
{
fprintf(stderr, "ERROR: Read failure\n");
return -1;
}
if (b_use_hex)
{
fprintf(outstream, "%04x %04x %04x %04x %04x %02x %02x %02x\n",
rect.plane, rect.hstart, rect.hend, rect.vstart, rect.vend,
rect.attribute, rect.texture, rect.scale);
}
else
{
fprintf(outstream, "%5d %5d %5d %5d %5d %02x %2d %d\n",
rect.plane, rect.hstart, rect.hend, rect.vstart, rect.vend,
rect.attribute, rect.texture, rect.scale);
}
}
return 0;
}
static void show_usage(const char *progname)
{
fprintf(stderr,"Usage: %s [-h] [-o outfilename] [infile]\n",
progname);
exit(EXIT_FAILURE);
}
/****************************************************************************
* Public Functions
****************************************************************************/
int main(int argc, char **argv, char **envp)
{
char *infile = "transfrm.pll";
char *outfile = NULL;
struct trv_planefile_header_s header;
int option;
FILE *instream;
FILE *outstream = stdout;
while ((option = getopt(argc, argv, "ho:")) != EOF)
{
switch (option)
{
case 'h' :
b_use_hex = true;
break;
case 'o' :
outfile = optarg;
break;
default:
fprintf(stderr, "ERROR: Unrecognized option: %c\n", option);
show_usage(argv[0]);
break;
}
}
/* We expect at least one argument after the options: The input
* file name.
*/
if (optind == argc - 1)
{
infile = argv[optind];
}
else if (optind < argc - 1)
{
fprintf(stderr, "ERROR: Unexpected garbage after [infile]\n");
show_usage(argv[0]);
}
instream = fopen(infile, "rb");
if (!instream)
{
fprintf(stderr, "ERROR: Unable to open %s\n", infile);
return EXIT_FAILURE;
}
printf("Reading plane file: %s\n", infile);
if (outfile)
{
outstream = fopen(outfile, "w");
if (!outstream)
{
fprintf(stderr, "ERROR: Unable to open %s\n", outfile);
return EXIT_FAILURE;
}
printf("Generating text file: %s\n", outfile);
}
if (fread((char*)&header, SIZEOF_TRVPLANEFILEHEADER_T, 1, instream) != 1)
{
fprintf(stderr, "Unable to Read %s header\n", infile);
return EXIT_FAILURE;
}
fprintf(outstream, "nxrects=%d, nyrects=%d, nzrects=%d\n",
header.nxrects, header.nyrects, header.nzrects );
fprintf(outstream, "X Planes: \n");
if (dump_plane(instream, outstream, header.nxrects))
{
goto stop_dump;
}
fprintf(outstream, "Y Planes: \n");
if (dump_plane(instream, outstream, header.nyrects))
{
goto stop_dump;
}
fprintf(outstream, "Z Planes: \n");
dump_plane(instream, outstream, header.nzrects);
stop_dump:
fclose(instream);
if (outfile)
{
fclose(outstream);
}
return EXIT_SUCCESS;
}
|
FAD95/NEXT.JS-Course
|
node_modules/@iconify/icons-mdi/src/language-swift.js
|
<filename>node_modules/@iconify/icons-mdi/src/language-swift.js
let data = {
"body": "<path d=\"M17.09 19.72c-2.36 1.36-5.59 1.5-8.86.1A13.807 13.807 0 0 1 2 14.5c.67.55 1.46 1 2.3 1.4c3.37 1.57 6.73 1.46 9.1 0c-3.37-2.59-6.24-5.96-8.37-8.71c-.45-.45-.78-1.01-1.12-1.51c8.28 6.05 7.92 7.59 2.41-1.01c4.89 4.94 9.43 7.74 9.43 7.74c.16.09.25.16.36.22c.1-.25.19-.51.26-.78c.79-2.85-.11-6.12-2.08-8.81c4.55 2.75 7.25 7.91 6.12 12.24c-.03.11-.06.22-.05.39c2.24 2.83 1.64 5.78 1.35 5.22c-1.21-2.39-3.48-1.65-4.62-1.17z\" fill=\"currentColor\"/>",
"width": 24,
"height": 24
};
export default data;
|
liruqi/actor-platform-v0.9
|
actor-server/actor-tests/src/test/scala/im/actor/server/api/rpc/service/GroupsServiceSpec.scala
|
<filename>actor-server/actor-tests/src/test/scala/im/actor/server/api/rpc/service/GroupsServiceSpec.scala
package im.actor.server.api.rpc.service
import im.actor.api.rpc._
import im.actor.api.rpc.counters.UpdateCountersChanged
import im.actor.api.rpc.groups._
import im.actor.api.rpc.messaging._
import im.actor.api.rpc.misc.ResponseSeqDate
import im.actor.api.rpc.peers.{ ApiOutPeer, ApiPeerType, ApiUserOutPeer }
import im.actor.server._
import im.actor.server.acl.ACLUtils
import im.actor.server.api.rpc.service.groups.{ GroupInviteConfig, GroupRpcErrors, GroupsServiceImpl }
import im.actor.server.group.GroupServiceMessages
import im.actor.server.presences.{ GroupPresenceManager, PresenceManager }
import org.scalatest.Inside._
import slick.dbio.DBIO
import scala.util.Random
class GroupsServiceSpec
extends BaseAppSuite
with GroupsServiceHelpers
with MessageParsing
with ImplicitGroupRegions
with ImplicitSequenceService
with ImplicitAuthService
with ImplicitSessionRegionProxy
with SequenceMatchers {
behavior of "GroupsService"
it should "send invites on group creation" in e1
it should "send updates on group invite" in e2
it should "send updates ot title change" in e3
it should "persist service messages in history" in e4
it should "generate invite url for group member" in e5
it should "not generate invite url for group non members" in e6
it should "revoke invite token and generate new token for group member" in e7
it should "allow user to join group by correct invite link and send correct updates" in e8
it should "not allow group member to join group by invite link" in e9
it should "send updates on user join" in e10
it should "send UserInvited and UserJoined on user's first MessageRead" in e11
it should "receive userJoined once" in e12
it should "not allow to create group with empty name" in e13
"Creator of group" should "be groupAdmin" in e14
"MakeUserAdmin" should "allow group member to become admin" in e15
it should "forbid to perform action by non-admin" in e16
it should "return error when user is already admin" in e17
"EditGroupAbout" should "allow group admin to change 'about'" in e18
it should "forbid to change 'about' by non-admin" in e19
it should "set 'about' to empty when None comes" in e20
it should "forbid to set invalid 'about' field (empty, or longer than 255 characters)" in e21
"EditGroupTopic" should "allow any group member to change topic" in e22
it should "forbid to set invalid topic (empty, or longer than 255 characters)" in e23
it should "set topic to empty when None comes" in e24
"Leave group" should "mark messages read in left user dialog" in e25
"Kick user" should "mark messages read in kicked user dialog" in e26
"Kick user" should "mark messages read in public group" in e27
implicit val presenceManagerRegion = PresenceManager.startRegion()
implicit val groupPresenceManagerRegion = GroupPresenceManager.startRegion()
val groupInviteConfig = GroupInviteConfig("http://actor.im")
val messagingService = messaging.MessagingServiceImpl(mediator)
implicit val service = new GroupsServiceImpl(groupInviteConfig)
def e1() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val sessionId = createSessionId()
implicit val clientData = ClientData(authId1, sessionId, Some(user1.id))
val groupOutPeer = createGroup("Fun group", Set(user2.id)).groupPeer
expectUpdatesUnordered(failUnmatched)(0, Array.empty, Seq(UpdateGroupUserInvited.header, UpdateGroupInvite.header)) {
case (UpdateGroupUserInvited.header, update) โ parseUpdate[UpdateGroupUserInvited](update)
case (UpdateGroupInvite.header, update) โ parseUpdate[UpdateGroupInvite](update)
}
whenReady(db.run(persist.GroupUser.findUserIds(groupOutPeer.groupId))) { userIds โ
userIds.toSet shouldEqual Set(user1.id, user2.id)
}
}
def e2() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val sessionId = createSessionId()
val clientData1 = ClientData(authId1, sessionId, Some(user1.id))
val clientData2 = ClientData(authId2, sessionId, Some(user2.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(clientData1.authId, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
{
implicit val clientData = clientData1
val groupOutPeer = createGroup("Fun group", Set.empty).groupPeer
whenReady(service.handleInviteUser(groupOutPeer, Random.nextLong(), user2OutPeer)) { resp โ
resp should matchPattern {
case Ok(ResponseSeqDate(1001, _, _)) โ
}
}
expectUpdatesUnordered(failUnmatched)(0, Array.empty, Seq(UpdateGroupUserInvited.header, UpdateGroupInvite.header)) {
case (UpdateGroupUserInvited.header, update) โ parseUpdate[UpdateGroupUserInvited](update)
case (UpdateGroupInvite.header, update) โ parseUpdate[UpdateGroupInvite](update)
}
}
{
implicit val clientData = clientData2
expectUpdatesUnordered(failUnmatched)(0, Array.empty, Seq(UpdateGroupInvite.header)) {
case (UpdateGroupInvite.header, update) โ parseUpdate[UpdateGroupInvite](update)
}
}
}
def e3() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val sessionId = createSessionId()
val clientData1 = ClientData(authId1, sessionId, Some(user1.id))
val clientData2 = ClientData(authId2, sessionId, Some(user2.id))
{
implicit val clientData = clientData1
val groupOutPeer = createGroup("Fun group", Set(user2.id)).groupPeer
whenReady(service.handleEditGroupTitle(groupOutPeer, Random.nextLong(), "Very fun group")) { resp โ
resp should matchPattern {
case Ok(ResponseSeqDate(1002, _, _)) โ
}
}
expectUpdatesUnordered(failUnmatched)(0, Array.empty, Seq(
UpdateGroupUserInvited.header,
UpdateGroupInvite.header,
UpdateGroupTitleChanged.header
)) {
case (UpdateGroupUserInvited.header, update) โ parseUpdate[UpdateGroupUserInvited](update)
case (UpdateGroupInvite.header, update) โ parseUpdate[UpdateGroupInvite](update)
case (UpdateGroupTitleChanged.header, update) โ parseUpdate[UpdateGroupTitleChanged](update)
}
}
{
implicit val clientData = clientData2
expectUpdatesUnordered(failUnmatched)(0, Array.empty, Seq(
UpdateGroupInvite.header,
UpdateGroupTitleChanged.header
)) {
case (UpdateGroupInvite.header, update) โ parseUpdate[UpdateGroupInvite](update)
case (UpdateGroupTitleChanged.header, update) โ parseUpdate[UpdateGroupTitleChanged](update)
}
}
}
def e4() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val sessionId = createSessionId()
implicit val clientData = ClientData(authId1, sessionId, Some(user1.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(clientData.authId, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
val groupOutPeer = createGroup("Fun group", Set.empty).groupPeer
whenReady(db.run(persist.HistoryMessage.find(user1.id, models.Peer.group(groupOutPeer.groupId)))) { serviceMessages โ
serviceMessages should have length 1
serviceMessages
.map { e โ parseMessage(e.messageContentData) } shouldEqual
Vector(Right(GroupServiceMessages.groupCreated))
}
whenReady(service.handleInviteUser(groupOutPeer, Random.nextLong(), user2OutPeer)) { resp โ
resp should matchPattern { case Ok(_) โ }
whenReady(db.run(persist.HistoryMessage.find(user1.id, models.Peer.group(groupOutPeer.groupId)))) { serviceMessages โ
serviceMessages should have length 2
serviceMessages.map { e โ parseMessage(e.messageContentData) } shouldEqual
Vector(
Right(GroupServiceMessages.userInvited(user2.id)),
Right(GroupServiceMessages.groupCreated)
)
}
whenReady(db.run(persist.HistoryMessage.find(user2.id, models.Peer.group(groupOutPeer.groupId)))) { serviceMessages โ
serviceMessages should have length 1
serviceMessages.map { e โ parseMessage(e.messageContentData) } shouldEqual
Vector(Right(GroupServiceMessages.userInvited(user2.id)))
}
}
//TODO: is it ok to remove avatar of group without avatar
whenReady(service.handleRemoveGroupAvatar(groupOutPeer, Random.nextLong())) { resp โ
resp should matchPattern { case Ok(_) โ }
Thread.sleep(500)
whenReady(db.run(persist.HistoryMessage.find(user1.id, models.Peer.group(groupOutPeer.groupId)))) { serviceMessages โ
serviceMessages should have length 3
serviceMessages.map { e โ parseMessage(e.messageContentData) } shouldEqual
Vector(
Right(GroupServiceMessages.changedAvatar(None)),
Right(GroupServiceMessages.userInvited(user2.id)),
Right(GroupServiceMessages.groupCreated)
)
}
whenReady(db.run(persist.HistoryMessage.find(user2.id, models.Peer.group(groupOutPeer.groupId)))) { serviceMessages โ
serviceMessages should have length 2
serviceMessages.map { e โ parseMessage(e.messageContentData) } shouldEqual
Vector(
Right(GroupServiceMessages.changedAvatar(None)),
Right(GroupServiceMessages.userInvited(user2.id))
)
}
}
whenReady(service.handleEditGroupTitle(groupOutPeer, Random.nextLong(), "Not fun group")) { resp โ
resp should matchPattern { case Ok(_) โ }
whenReady(db.run(persist.HistoryMessage.find(user1.id, models.Peer.group(groupOutPeer.groupId)))) { serviceMessages โ
serviceMessages should have length 4
serviceMessages.map { e โ parseMessage(e.messageContentData) }.head shouldEqual Right(GroupServiceMessages.changedTitle("Not fun group"))
}
}
whenReady(service.handleLeaveGroup(groupOutPeer, Random.nextLong())(ClientData(authId2, sessionId, Some(user2.id)))) { resp โ
resp should matchPattern { case Ok(_) โ }
whenReady(db.run(persist.HistoryMessage.find(user1.id, models.Peer.group(groupOutPeer.groupId)))) { serviceMessages โ
serviceMessages should have length 5
serviceMessages.map { e โ parseMessage(e.messageContentData) }.head shouldEqual Right(GroupServiceMessages.userLeft(user2.id))
}
}
whenReady(service.handleInviteUser(groupOutPeer, Random.nextLong(), user2OutPeer)) { resp โ
resp should matchPattern { case Ok(_) โ }
whenReady(db.run(persist.HistoryMessage.find(user1.id, models.Peer.group(groupOutPeer.groupId)))) { serviceMessages โ
serviceMessages should have length 6
serviceMessages.map { e โ parseMessage(e.messageContentData) }.head shouldEqual Right(GroupServiceMessages.userInvited(user2.id))
}
}
whenReady(service.handleKickUser(groupOutPeer, Random.nextLong(), user2OutPeer)) { resp โ
resp should matchPattern { case Ok(_) โ }
whenReady(db.run(persist.HistoryMessage.find(user1.id, models.Peer.group(groupOutPeer.groupId)))) { serviceMessages โ
serviceMessages should have length 7
serviceMessages.map { e โ parseMessage(e.messageContentData) }.head shouldEqual Right(GroupServiceMessages.userKicked(user2.id))
}
}
}
def e5() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val sessionId = createSessionId()
implicit val clientData = ClientData(authId1, sessionId, Some(user1.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(clientData.authId, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
val groupOutPeer = createGroup("Fun group", Set(user2.id)).groupPeer
{
implicit val clientData = ClientData(authId1, sessionId, Some(user1.id))
var expUrl: String = ""
whenReady(service.handleGetGroupInviteUrl(groupOutPeer)) { resp โ
inside(resp) {
case Ok(ResponseInviteUrl(url)) โ
url should startWith(groupInviteConfig.baseUrl)
expUrl = url
}
}
whenReady(service.handleGetGroupInviteUrl(groupOutPeer)) { resp โ
inside(resp) {
case Ok(ResponseInviteUrl(url)) โ
url should startWith(groupInviteConfig.baseUrl)
url shouldEqual expUrl
}
}
}
{
implicit val clientData = ClientData(authId2, sessionId, Some(user2.id))
var expUrl: String = ""
whenReady(service.handleGetGroupInviteUrl(groupOutPeer)) { resp โ
inside(resp) {
case Ok(ResponseInviteUrl(url)) โ
url should startWith(groupInviteConfig.baseUrl)
expUrl = url
}
}
whenReady(service.handleGetGroupInviteUrl(groupOutPeer)) { resp โ
inside(resp) {
case Ok(ResponseInviteUrl(url)) โ
url should startWith(groupInviteConfig.baseUrl)
url shouldEqual expUrl
}
}
}
val findTokens =
for {
tokens โ DBIO.sequence(List(
persist.GroupInviteToken.find(groupOutPeer.groupId, user1.id),
persist.GroupInviteToken.find(groupOutPeer.groupId, user2.id)
))
} yield tokens.flatten
whenReady(db.run(findTokens)) { tokens โ
tokens should have length 2
tokens.foreach(_.groupId shouldEqual groupOutPeer.groupId)
tokens.map(_.creatorId) should contain allOf (user1.id, user2.id)
}
}
def e6() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val sessionId = createSessionId()
implicit val clientData = ClientData(authId1, sessionId, Some(user1.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(clientData.authId, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
val groupOutPeer = createGroup("Fun group", Set.empty).groupPeer
{
implicit val clientData = ClientData(authId2, sessionId, Some(user2.id))
whenReady(service.handleGetGroupInviteUrl(groupOutPeer)) { resp โ
resp should matchNotAuthorized
}
}
}
def e7() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val sessionId = createSessionId()
implicit val clientData = ClientData(authId1, sessionId, Some(user1.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(clientData.authId, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
val groupOutPeer = createGroup("Fun group", Set.empty).groupPeer
var expUrl: String = ""
whenReady(service.handleGetGroupInviteUrl(groupOutPeer)) { resp โ
inside(resp) {
case Ok(ResponseInviteUrl(url)) โ
url should startWith(groupInviteConfig.baseUrl)
expUrl = url
}
}
whenReady(service.handleRevokeInviteUrl(groupOutPeer)) { resp โ
inside(resp) {
case Ok(ResponseInviteUrl(url)) โ
url should startWith(groupInviteConfig.baseUrl)
url should not equal expUrl
}
}
whenReady(db.run(persist.GroupInviteToken.find(groupOutPeer.groupId, user1.id))) { tokens โ
tokens should have length 1
}
}
def e8() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val sessionId = createSessionId()
implicit val clientData = ClientData(authId1, sessionId, Some(user1.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(clientData.authId, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
val groupOutPeer = createGroup("Invite Fun group", Set.empty).groupPeer
whenReady(service.handleGetGroupInviteUrl(groupOutPeer)) { resp โ
inside(resp) {
case Ok(ResponseInviteUrl(url)) โ
url should startWith(groupInviteConfig.baseUrl)
{
implicit val clientData = ClientData(authId2, sessionId, Some(user2.id))
whenReady(service.handleJoinGroup(url)) { resp โ
resp should matchPattern {
case Ok(ResponseJoinGroup(_, _, _, _, _, _)) โ
}
}
}
}
}
whenReady(db.run(persist.GroupUser.findUserIds(groupOutPeer.groupId))) { userIds โ
userIds should have length 2
userIds should contain allOf (user1.id, user2.id)
}
}
def e9() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
implicit val clientData = ClientData(authId1, createSessionId(), Some(user1.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(clientData.authId, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
val groupOutPeer = createGroup("Fun group", Set(user2.id)).groupPeer
whenReady(service.handleGetGroupInviteUrl(groupOutPeer)) { resp โ
inside(resp) {
case Ok(ResponseInviteUrl(url)) โ
url should startWith(groupInviteConfig.baseUrl)
{
implicit val clientData = ClientData(authId2, createSessionId(), Some(user2.id))
val outPeer = ApiOutPeer(ApiPeerType.Group, groupOutPeer.groupId, groupOutPeer.accessHash)
whenReady(messagingService.handleMessageRead(outPeer, System.currentTimeMillis()))(_ โ ())
whenReady(service.handleJoinGroup(url)) { resp โ
inside(resp) {
case Error(err) โ err shouldEqual GroupRpcErrors.UserAlreadyInvited
}
}
}
}
}
}
def e10() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val sessionId = createSessionId()
implicit val clientData1 = ClientData(authId1, sessionId, Some(user1.id))
val clientData2 = ClientData(authId2, sessionId, Some(user2.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(clientData1.authId, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
val createGroupResponse = createGroup("Invite Fun group", Set.empty)
val groupOutPeer = createGroupResponse.groupPeer
whenReady(service.jhandleGetGroupInviteUrl(groupOutPeer, clientData1)) { resp โ
inside(resp) {
case Ok(ResponseInviteUrl(url)) โ
url should startWith(groupInviteConfig.baseUrl)
whenReady(service.jhandleJoinGroup(url, clientData2))(_ โ ())
expectUpdatesUnorderedOnly(failUnmatched)(createGroupResponse.seq, createGroupResponse.state, List(UpdateMessage.header, UpdateCountersChanged.header)) {
case (UpdateMessage.header, u) โ
val update = parseUpdate[UpdateMessage](u)
update.message shouldEqual GroupServiceMessages.userJoined
case (UpdateCountersChanged.header, update) โ parseUpdate[UpdateCountersChanged](update)
}
}
}
whenReady(db.run(persist.GroupUser.findUserIds(groupOutPeer.groupId))) { userIds โ
userIds should have length 2
userIds should contain allOf (user1.id, user2.id)
}
}
def e11() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val sessionId = createSessionId()
val clientData1 = ClientData(authId1, sessionId, Some(user1.id))
val clientData2 = ClientData(authId2, sessionId, Some(user2.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(clientData1.authId, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
val groupOutPeer = {
implicit val clientData = clientData1
val groupOutPeer = createGroup("Invite Fun group", Set.empty).groupPeer
whenReady(service.handleInviteUser(groupOutPeer, Random.nextLong, user2OutPeer)) { _ โ }
groupOutPeer
}
{
implicit val clientData = clientData2
// send it twice to ensure that ServiceMessage isn't sent twice
whenReady(messagingService.handleMessageRead(ApiOutPeer(ApiPeerType.Group, groupOutPeer.groupId, groupOutPeer.accessHash), System.currentTimeMillis))(identity)
whenReady(messagingService.handleMessageRead(ApiOutPeer(ApiPeerType.Group, groupOutPeer.groupId, groupOutPeer.accessHash), System.currentTimeMillis))(identity)
}
{
implicit val clientData = clientData1
expectUpdatesUnordered(ignoreUnmatched)(0, Array.empty, Seq(
UpdateGroupInvite.header,
UpdateGroupUserInvited.header,
UpdateMessageRead.header,
UpdateCountersChanged.header,
UpdateMessage.header
)) {
case (UpdateMessage.header, u) โ
val update = parseUpdate[UpdateMessage](u)
update.message shouldEqual GroupServiceMessages.userJoined
}
}
}
def e12() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val clientData2 = ClientData(authId2, createSessionId(), Some(user2.id))
val groupOutPeer = {
implicit val clientData = clientData1
createGroup("Fun group", Set.empty).groupPeer
}
val url = whenReady(service.jhandleGetGroupInviteUrl(groupOutPeer, clientData1)) { _.toOption.get.url }
whenReady(service.jhandleJoinGroup(url, clientData2)) { resp โ
resp should matchPattern {
case Ok(ResponseJoinGroup(_, _, _, _, _, _)) โ
}
}
val peer = ApiOutPeer(ApiPeerType.Group, groupOutPeer.groupId, groupOutPeer.accessHash)
whenReady(messagingService.jhandleSendMessage(peer, 22324L, ApiTextMessage("hello", Vector.empty, None), clientData1)) { _ โ }
whenReady(messagingService.jhandleMessageRead(peer, System.currentTimeMillis, clientData2)) { _ โ }
{
implicit val clientData = clientData1
expectUpdatesUnorderedOnly(ignoreUnmatched)(0, Array.empty, List(
UpdateGroupInvite.header,
UpdateMessageSent.header,
UpdateMessage.header,
UpdateCountersChanged.header,
UpdateMessageRead.header
)) {
case (UpdateMessage.header, u) โ
val update = parseUpdate[UpdateMessage](u)
update.message shouldEqual GroupServiceMessages.userJoined
}
}
}
def e13() = {
val (user1, authId1, _) = createUser()
implicit val clientData = ClientData(authId1, createSessionId(), Some(user1.id))
whenReady(service.handleCreateGroup(1L, "", Vector.empty)) { resp โ
inside(resp) {
case Error(GroupRpcErrors.WrongGroupTitle) โ
}
}
}
def e14() = {
val (user1, authId1, _) = createUser()
implicit val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val groupOutPeer = createGroup("Fun group", Set.empty).groupPeer
whenReady(db.run(persist.GroupUser.find(groupOutPeer.groupId, user1.id))) { groupUser โ
groupUser shouldBe defined
groupUser.get.isAdmin shouldEqual true
}
}
def e15() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
implicit val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(clientData1.authId, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
val groupOutPeer = createGroup("Fun group", Set(user2.id)).groupPeer
whenReady(service.handleMakeUserAdmin(groupOutPeer, user2OutPeer)) { resp โ
inside(resp) {
case Ok(ResponseMakeUserAdmin(members, _, _)) โ
members.find(_.userId == user2.id) foreach (_.isAdmin shouldEqual Some(true))
}
}
}
def e16() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val (user3, authId3, _) = createUser()
val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val clientData2 = ClientData(authId2, createSessionId(), Some(user2.id))
val user3Model = getUserModel(user3.id)
val user3AccessHash = ACLUtils.userAccessHash(clientData2.authId, user3.id, user3Model.accessSalt)
val user3OutPeer = ApiUserOutPeer(user3.id, user3AccessHash)
val groupOutPeer = {
implicit val clientData = clientData1
createGroup("Fun group", Set(user2.id)).groupPeer
}
whenReady(service.jhandleMakeUserAdmin(groupOutPeer, user3OutPeer, clientData2)) { resp โ
resp shouldEqual Error(CommonErrors.forbidden("Only admin can perform this action."))
}
}
def e17() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
implicit val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(clientData1.authId, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
val groupOutPeer = createGroup("Fun group", Set(user2.id)).groupPeer
whenReady(service.handleMakeUserAdmin(groupOutPeer, user2OutPeer)) { resp โ
resp should matchPattern {
case Ok(_: ResponseMakeUserAdmin) โ
}
}
whenReady(service.handleMakeUserAdmin(groupOutPeer, user2OutPeer)) { resp โ
resp shouldEqual Error(GroupRpcErrors.UserAlreadyAdmin)
}
}
def e18() = {
val (user1, authId1, _) = createUser()
implicit val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val groupOutPeer = createGroup("Fun group", Set.empty).groupPeer
val about = Some("It is group for fun")
whenReady(service.handleEditGroupAbout(groupOutPeer, 1L, about)) { resp โ
resp should matchPattern {
case Ok(_: ResponseSeqDate) โ
}
}
whenReady(db.run(persist.Group.find(groupOutPeer.groupId))) { group โ
group.get.about shouldEqual about
}
}
def e19() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val clientData2 = ClientData(authId2, createSessionId(), Some(user2.id))
val groupOutPeer = {
implicit val clientData = clientData1
createGroup("Fun group", Set(user2.id)).groupPeer
}
whenReady(service.jhandleEditGroupAbout(groupOutPeer, 1L, Some("It is group for fun"), clientData2)) { resp โ
resp shouldEqual Error(CommonErrors.forbidden("Only admin can perform this action."))
}
}
def e20() = {
val (user1, authId1, _) = createUser()
implicit val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val groupOutPeer = createGroup("Fun group", Set.empty).groupPeer
whenReady(service.handleEditGroupAbout(groupOutPeer, 1L, None)) { resp โ
resp should matchPattern {
case Ok(_: ResponseSeqDate) โ
}
}
whenReady(db.run(persist.Group.find(groupOutPeer.groupId))) { group โ
group.get.about shouldEqual None
}
}
def e21() = {
val (user1, authId1, _) = createUser()
implicit val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val groupOutPeer = createGroup("Fun group", Set.empty).groupPeer
val longAbout = 1 to 300 map (e โ ".") mkString ""
whenReady(service.handleEditGroupAbout(groupOutPeer, 1L, Some(longAbout))) { resp โ
resp shouldEqual Error(GroupRpcErrors.AboutTooLong)
}
val emptyAbout = ""
whenReady(service.handleEditGroupAbout(groupOutPeer, 1L, Some(emptyAbout))) { resp โ
resp shouldEqual Error(GroupRpcErrors.AboutTooLong)
}
whenReady(db.run(persist.Group.find(groupOutPeer.groupId))) { group โ
group.get.about shouldEqual None
}
}
def e22() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val clientData2 = ClientData(authId2, createSessionId(), Some(user2.id))
val groupOutPeer = {
implicit val cd = clientData1
createGroup("Fun group", Set(user2.id)).groupPeer
}
val topic1 = Some("Fun stufff")
whenReady(service.jhandleEditGroupTopic(groupOutPeer, 1L, topic1, clientData1)) { resp โ
resp should matchPattern {
case Ok(_: ResponseSeqDate) โ
}
}
val topic2 = Some("Fun stuff. Typo!")
whenReady(service.jhandleEditGroupTopic(groupOutPeer, 1L, topic2, clientData2)) { resp โ
resp should matchPattern {
case Ok(_: ResponseSeqDate) โ
}
}
whenReady(db.run(persist.Group.find(groupOutPeer.groupId))) { group โ
group.get.topic shouldEqual topic2
}
}
def e23() = {
val (user1, authId1, _) = createUser()
implicit val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val groupOutPeer = createGroup("Fun group", Set.empty).groupPeer
val longTopic = 1 to 300 map (e โ ".") mkString ""
whenReady(service.handleEditGroupTopic(groupOutPeer, 1L, Some(longTopic))) { resp โ
resp shouldEqual Error(GroupRpcErrors.TopicTooLong)
}
val emptyTopic = ""
whenReady(service.handleEditGroupTopic(groupOutPeer, 1L, Some(emptyTopic))) { resp โ
resp shouldEqual Error(GroupRpcErrors.TopicTooLong)
}
whenReady(db.run(persist.Group.find(groupOutPeer.groupId))) { group โ
group.get.topic shouldEqual None
}
}
def e24() = {
val (user1, authId1, _) = createUser()
implicit val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val groupOutPeer = createGroup("Fun group", Set.empty).groupPeer
whenReady(service.handleEditGroupTopic(groupOutPeer, 1L, None)) { resp โ
resp should matchPattern {
case Ok(_: ResponseSeqDate) โ
}
}
whenReady(db.run(persist.Group.find(groupOutPeer.groupId))) { group โ
group.get.topic shouldEqual None
}
}
def e25() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val clientData1 = ClientData(authId1, createSessionId(), Some(user1.id))
val clientData2 = ClientData(authId2, createSessionId(), Some(user2.id))
val groupOutPeer = {
implicit val clientData = clientData1
createGroup("Fun group", Set(user2.id)).groupPeer
}
val outPeer = ApiOutPeer(ApiPeerType.Group, groupOutPeer.groupId, groupOutPeer.accessHash)
for (_ โ 1 to 6) {
implicit val clientData = clientData1
whenReady(messagingService.handleSendMessage(outPeer, Random.nextLong(), ApiTextMessage("hello", Vector.empty, None))) { _ โ }
}
{
implicit val clientData = clientData2
whenReady(messagingService.handleLoadDialogs(Long.MaxValue, 100)) { resp โ
val dialog = resp.toOption.get.dialogs.head
dialog.unreadCount > 6 shouldEqual true
}
whenReady(service.handleLeaveGroup(groupOutPeer, Random.nextLong())) { resp โ
resp should matchPattern { case Ok(_) โ }
}
whenReady(messagingService.handleLoadDialogs(Long.MaxValue, 100)) { resp โ
val dialog = resp.toOption.get.dialogs.head
dialog.unreadCount shouldEqual 0
}
}
for (_ โ 1 to 6) {
implicit val clientData = clientData1
whenReady(messagingService.handleSendMessage(outPeer, Random.nextLong(), ApiTextMessage("bye left user", Vector.empty, None))) { _ โ }
}
{
implicit val clientData = clientData2
whenReady(messagingService.handleLoadDialogs(Long.MaxValue, 100)) { resp โ
val dialog = resp.toOption.get.dialogs.head
dialog.unreadCount shouldEqual 0
}
}
}
def e26() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val sessionId = createSessionId()
val clientData1 = ClientData(authId1, sessionId, Some(user1.id))
val clientData2 = ClientData(authId2, sessionId, Some(user2.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(authId1, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
val groupOutPeer = {
implicit val clientData = clientData1
createGroup("Fun group", Set(user2.id)).groupPeer
}
val outPeer = ApiOutPeer(ApiPeerType.Group, groupOutPeer.groupId, groupOutPeer.accessHash)
for (_ โ 1 to 6) {
implicit val clientData = clientData1
whenReady(messagingService.handleSendMessage(outPeer, Random.nextLong(), ApiTextMessage("hello", Vector.empty, None))) { _ โ }
}
{
implicit val clientData = clientData2
whenReady(messagingService.handleLoadDialogs(Long.MaxValue, 100)) { resp โ
val dialog = resp.toOption.get.dialogs.head
dialog.unreadCount > 6 shouldEqual true
}
}
{
implicit val clientData = clientData1
whenReady(service.handleKickUser(groupOutPeer, Random.nextLong(), user2OutPeer)) { resp โ
resp should matchPattern { case Ok(_) โ }
}
}
{
implicit val clientData = clientData2
whenReady(messagingService.handleLoadDialogs(Long.MaxValue, 100)) { resp โ
val dialog = resp.toOption.get.dialogs.head
dialog.unreadCount shouldEqual 0
}
}
for (_ โ 1 to 6) {
implicit val clientData = clientData1
whenReady(messagingService.handleSendMessage(outPeer, Random.nextLong(), ApiTextMessage("bye kicked user", Vector.empty, None))) { _ โ }
}
{
implicit val clientData = clientData2
whenReady(messagingService.handleLoadDialogs(Long.MaxValue, 100)) { resp โ
val dialog = resp.toOption.get.dialogs.head
dialog.unreadCount shouldEqual 0
}
}
}
def e27() = {
val (user1, authId1, _) = createUser()
val (user2, authId2, _) = createUser()
val sessionId = createSessionId()
val clientData1 = ClientData(authId1, sessionId, Some(user1.id))
val clientData2 = ClientData(authId2, sessionId, Some(user2.id))
val user2Model = getUserModel(user2.id)
val user2AccessHash = ACLUtils.userAccessHash(authId1, user2.id, user2Model.accessSalt)
val user2OutPeer = ApiUserOutPeer(user2.id, user2AccessHash)
val groupOutPeer = {
implicit val clientData = clientData1
createPubGroup("Public group", "desc", Set(user2.id)).groupPeer
}
val outPeer = ApiOutPeer(ApiPeerType.Group, groupOutPeer.groupId, groupOutPeer.accessHash)
for (_ โ 1 to 6) {
implicit val clientData = clientData1
whenReady(messagingService.handleSendMessage(outPeer, Random.nextLong(), ApiTextMessage("hello public", Vector.empty, None))) { _ โ }
}
{
implicit val clientData = clientData2
whenReady(messagingService.handleLoadDialogs(Long.MaxValue, 100)) { resp โ
val dialog = resp.toOption.get.dialogs.head
dialog.unreadCount > 6 shouldEqual true
}
}
{
implicit val clientData = clientData1
whenReady(service.handleKickUser(groupOutPeer, Random.nextLong(), user2OutPeer)) { resp โ
resp should matchPattern { case Ok(_) โ }
}
}
{
implicit val clientData = clientData2
whenReady(messagingService.handleLoadDialogs(Long.MaxValue, 100)) { resp โ
val dialog = resp.toOption.get.dialogs.head
dialog.unreadCount shouldEqual 0
}
}
for (_ โ 1 to 6) {
implicit val clientData = clientData1
whenReady(messagingService.handleSendMessage(outPeer, Random.nextLong(), ApiTextMessage("bye kicked user", Vector.empty, None))) { _ โ }
}
{
implicit val clientData = clientData2
whenReady(messagingService.handleLoadDialogs(Long.MaxValue, 100)) { resp โ
val dialog = resp.toOption.get.dialogs.head
dialog.unreadCount shouldEqual 0
}
}
}
}
|
paulosalgado/cursos
|
java-reflection-alura/src/br/com/alura/reflection/nulos/modelo/Produto.java
|
package br.com.alura.reflection.nulos.modelo;
public class Produto {
public String codigo;
public String nome;
public String fornecedor;
public Float preco;
public String descricao;
}
|
marcellalcs/natds-commons
|
packages/natds-themes/config/shared/config.js
|
<filename>packages/natds-themes/config/shared/config.js<gh_stars>0
import registerHtmlFormat from '../html/registerHtmlFormat';
import registerHtmlCreatePathsAction from '../html/registerCreatePathsAction';
import registerAttributesFormatter from '../android/registerAttributesFormat';
import registerThemeFormatAndroid from '../android/registerThemeFormat';
import { registerDpTransform } from '../android/registerDpTransform';
import { registerAttributeTypeTransform } from '../android/registerAttributeTypeTransform';
import { registerCreateResourcesAction } from '../android/registerCreateResourcesAction';
import { registerThemeFormat, registerThemeProtocolFormat } from '../ios/registerFormats';
import registerAttributeTypeTransformIos from '../ios/registerAttributeTypeTransform';
import { registerValueStringLiteralTransform } from '../ios/registerValueStringLiteralTransform';
import { registerTemplateHeaderHelper } from './templateHelpers';
import { registerTypeDefinitionsAction } from './registerTypeDefinitionsAction';
import { registerCamelTransform } from './registerCamelTransform';
import { registerPxTransform } from './registerPxTransform';
export const customFormats = [
registerHtmlFormat,
registerAttributesFormatter,
registerThemeFormatAndroid,
registerThemeFormat,
registerThemeProtocolFormat,
];
export const customActions = [
registerHtmlCreatePathsAction,
registerTypeDefinitionsAction,
registerCreateResourcesAction,
];
export const customTransforms = [
registerCamelTransform,
registerDpTransform,
registerAttributeTypeTransform,
registerAttributeTypeTransformIos,
registerValueStringLiteralTransform,
registerPxTransform,
];
registerTemplateHeaderHelper();
|
linyingzhen/btnew
|
src/discovery/Index/_Header.js
|
<filename>src/discovery/Index/_Header.js
/**
* const prefixCls = 'style-553336';
* const images = '/static/images/src/discovery/Index';
* @Author: czy0729
* @Date: 2018-08-23 12:37:28
* @Last Modified by: czy0729
* @Last Modified time: 2018-11-12 14:06:26
* @Path m.benting.com.cn /src/discovery/Index/_Header.js
*/
import React from 'react';
import PropTypes from 'prop-types';
import { Badge } from 'antd-mobile';
import { observer } from '@';
import { Header, Tabs, Button } from '@components';
import Utils from '@utils';
import G from '@stores/g';
import { tabsDS } from './ds';
const _Header = (props, { $ }) => {
const { count, isRead } = G.getState('discoverySpecial');
const { page } = $.getState('_affixTabs');
const _tabsDS = Utils.deepCopy(tabsDS);
if (!isRead && count) {
const index = _tabsDS.findIndex(item => item.title === '็ฒพ้');
_tabsDS[index] = {
title: <Badge dot>็ฒพ้</Badge>
};
}
return (
<Header show style={{ height: '0.9rem' }}>
<Tabs
tabs={_tabsDS}
page={page}
extra={
<Button
type="primary"
size="xs"
inline
onClick={() =>
Utils.checkLogin(() => {
Utils.actionSheet(
['ๅๅธๅพๆ', 'ๅ้ๅธ็บขๅ
', 'ๅ็ฐ้็บขๅ
'],
index => {
if (index === 0) {
Utils.router.push('/discovery/post');
} else if (index === 1) {
Utils.router.push('/discovery/redpacket/coin');
} else if (index === 2) {
Utils.router.push('/discovery/redpacket/cash');
}
},
{
destructiveButtonIndex: undefined
}
);
})
}
>
ๅๅธ
</Button>
}
onTabClick={$.page.onTabClick}
>
<div />
</Tabs>
</Header>
);
};
_Header.contextTypes = {
$: PropTypes.object
};
export default observer(_Header);
|
MooersLab/jupyterlabcctbxsnipsplus
|
MtzObjects/mtzObjectSummary.py
|
<filename>MtzObjects/mtzObjectSummary.py
# Description: Read mtz file into a mtz object and print summary.
# Source: NA
"""
from iotbx import mtz
mtz_obj = mtz.object(file_name="/Users/blaine/${1:3nd4}.mtz")
mtz_obj.show_summary()
"""
from iotbx import mtz
mtz_obj = mtz.object(file_name="/Users/blaine/3nd4.mtz")
mtz_obj.show_summary()
|
RJM1996/kkb-work
|
src/7.21-node.js-05/2020-07-21-nodejs05/code/websocket-teach/index.js
|
const { Server } = require("ws");
const moment = require("moment");
const wss = new Server({
port: 3000,
});
wss.on("connection", (ws) => {
console.log("hi");
let intervalCount;
// ๆฅๅๆฐๆฎ
ws.on("message", (data) => {
console.log(data);
if (data === "start") {
// ๆจ้ๆฐๆฎ
// ่ฏทๆฑ db
// ็ปๅฐๅ็ซฏ
intervalCount = setInterval(() => {
ws.send(getDate());
}, 1000);
} else if (data === "stop") {
//ๅๆญขๆจ้ๆฐๆฎ
clearInterval(intervalCount);
}
});
});
function getDate() {
return moment().format("MMMM Do YYYY, h:mm:ss a");
}
|
kelvinluime/hkn-member-portal
|
src/services/events.js
|
<gh_stars>1-10
import * as firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
// get events for queried user
const getUserEvent = userId => {
// console.log("get events for "+userId+" :")
return firebase
.firestore()
.collection('pointReward')
.where('user_id', '==', userId)
.get()
.then(querySnapshot => {
return querySnapshot.docs.map(doc => doc.data());
})
.catch(() => {
throw Error('Points Query failed.');
});
};
const getPoints = () => {
const eventPoints = firebase.firestore().collection('pointReward');
if (firebase.auth().currentUser) {
return eventPoints
.where('user_id', '==', firebase.auth().currentUser.uid)
.get()
.then(snapshot => {
return snapshot.docs.map(doc => doc.data());
})
.catch(() => {
throw Error('Points Query failed.');
});
}
throw Error('Points Query failed, userId invalid');
};
// get all the events
const getAllEvents = () => {
return firebase
.firestore()
.collection('events')
.get()
.then(querySnapshot => {
return querySnapshot.docs.map(doc => {
return { id: doc.id, ...doc.data() };
});
});
};
// From Firebase's timestamp to Date object for getting events
const timestampToDate = timestamp => {
return timestamp.toDate();
};
// From Date object to Firebase's timestamp for updating events
const dateToTimestamp = date => {
return firebase.firestore.Timestamp.fromDate(date);
};
const getEventById = eventId => {
return firebase
.firestore()
.collection('events')
.doc(eventId)
.get()
.then(querySnapshot => {
const currentData = querySnapshot.data();
const { startDate, endDate } = currentData;
const convertedStartDate = timestampToDate(startDate);
const convertedEndDate = timestampToDate(endDate);
currentData.startDate = convertedStartDate;
currentData.endDate = convertedEndDate;
return currentData;
})
.catch(() => {
throw Error('Event Detail Query failed.');
});
};
const setEventDetails = (eventId, eventDetails) => {
const incomingEventDetails = eventDetails;
const { startDate, endDate } = incomingEventDetails;
const convertedStartDate = dateToTimestamp(startDate);
const convertedEndDate = dateToTimestamp(endDate);
incomingEventDetails.startDate = convertedStartDate;
incomingEventDetails.endDate = convertedEndDate;
return firebase
.firestore()
.collection('events')
.doc(eventId)
.set(incomingEventDetails);
};
const deleteEventById = eventId => {
return firebase
.firestore()
.collection('events')
.doc(eventId)
.delete()
.then(res => {
return res;
})
.catch(() => {
throw Error('Deletion of event by ID has failed.');
});
};
export {
getUserEvent,
getPoints,
getEventById,
deleteEventById,
setEventDetails,
getAllEvents,
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.