text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
var typedArrayConstructor = require('../internals/typed-array-constructor');
// `Uint16Array` constructor
// https://tc39.github.io/ecma262/#sec-typedarray-objects
typedArrayConstructor('Uint16', 2, function (init) {
return function Uint16Array(data, byteOffset, length) {
return init(this, data, byteOffset, length);
};
});
| {'content_hash': '53d93e926b5448a102d1ba787281c991', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 76, 'avg_line_length': 37.111111111111114, 'alnum_prop': 0.7365269461077845, 'repo_name': 'youtube/cobalt_sandbox', 'id': 'faca09b6aa98a521e206d0ec757d8eedebcb0c7b', 'size': '334', 'binary': False, 'copies': '5', 'ref': 'refs/heads/main', 'path': 'third_party/devtools/node_modules/core-js/modules/es.typed-array.uint16-array.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
find_path(LIBEV_INCLUDE_DIR ev++.h PATHS
${LIBEV_ROOT}/include
# make sure we don't accidentally pick up a different version
NO_CMAKE_SYSTEM_PATH
NO_SYSTEM_ENVIRONMENT_PATH)
find_library(LIBEV_SHARED_LIB ev PATHS
${LIBEV_ROOT}/lib
NO_CMAKE_SYSTEM_PATH
NO_SYSTEM_ENVIRONMENT_PATH)
find_library(LIBEV_STATIC_LIB libev.a PATHS
${LIBEV_ROOT}/lib
NO_CMAKE_SYSTEM_PATH
NO_SYSTEM_ENVIRONMENT_PATH)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(LIBEV REQUIRED_VARS
LIBEV_SHARED_LIB LIBEV_STATIC_LIB LIBEV_INCLUDE_DIR)
| {'content_hash': '81f3cc3eab0cdeae297e43604751bb69', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 63, 'avg_line_length': 32.94117647058823, 'alnum_prop': 0.7732142857142857, 'repo_name': 'michaelhkw/incubator-impala', 'id': '40443f1b42be7f4d5cac4a131236acf58643b8b2', 'size': '1616', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'cmake_modules/FindLibEv.cmake', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '420966'}, {'name': 'C++', 'bytes': '9610318'}, {'name': 'CMake', 'bytes': '164075'}, {'name': 'CSS', 'bytes': '148115'}, {'name': 'HTML', 'bytes': '56'}, {'name': 'Java', 'bytes': '4510111'}, {'name': 'JavaScript', 'bytes': '1202163'}, {'name': 'Lex', 'bytes': '23576'}, {'name': 'Objective-C', 'bytes': '1205'}, {'name': 'PLpgSQL', 'bytes': '3646'}, {'name': 'Protocol Buffer', 'bytes': '630'}, {'name': 'Python', 'bytes': '2666179'}, {'name': 'Roff', 'bytes': '1633'}, {'name': 'SQLPL', 'bytes': '1558'}, {'name': 'Shell', 'bytes': '244435'}, {'name': 'Thrift', 'bytes': '244539'}]} |
package strategy_test
import (
"testing"
"zntr.io/typogenerator/mapping"
"zntr.io/typogenerator/strategy"
)
func TestReplace(t *testing.T) {
out, err := strategy.Replace(mapping.French).Generate("zenithar", "")
if err != nil {
t.Fail()
t.Fatal("Error should not occurs !", err)
}
if len(out) == 0 {
t.FailNow()
}
if len(out) != 41 {
t.FailNow()
}
}
| {'content_hash': '097ac39b35037bd0432e81902248ff85', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 70, 'avg_line_length': 15.5, 'alnum_prop': 0.6344086021505376, 'repo_name': 'Zenithar/typogenerator', 'id': '4cdf94ebdedcc48ae793322fa7b154034351c101', 'size': '1156', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'strategy/replace_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '64896'}]} |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.3/15.3.4/15.3.4.3/15.3.4.3-2-s.js
* @description Strict Mode - 'this' value is a number which cannot be converted to wrapper objects when the function is called with an array of arguments
* @onlyStrict
*/
function testcase() {
"use strict";
function fun() {
return (this instanceof Number);
}
return !fun.apply(-12, Array);
}
runTestCase(testcase);
| {'content_hash': 'd3312bc9c68ac6a6a74ef1a379e499f3', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 154, 'avg_line_length': 40.9, 'alnum_prop': 0.6662591687041565, 'repo_name': 'mbrowne/typescript-dci', 'id': '7f03675a3af514db4964c456c63f9e221860fac7', 'size': '818', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'tests/Fidelity/test262/suite/ch15/15.3/15.3.4/15.3.4.3/15.3.4.3-2-s.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Elixir', 'bytes': '3294'}, {'name': 'HTML', 'bytes': '7930'}, {'name': 'JavaScript', 'bytes': '23053088'}, {'name': 'Shell', 'bytes': '386'}, {'name': 'TypeScript', 'bytes': '16490923'}]} |
<div class="gmap shadow-box" id="map"></div>
<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>
<script type="text/javascript">
ymaps.ready(function () {
var myMap = new ymaps.Map('map', {
center: [55.761259, 37.631111],
zoom: 15
}, {
searchControlProvider: 'yandex#search'
}),
myPlacemark = new ymaps.Placemark([55.761259, 37.631111], {
hintContent: 'DeutschAktiv',
balloonContent: 'Клуб немецкого языка <strong>DeutschAktiv</strong>',
}, {
preset: 'islands#blueCircleDotIconWithCaption',
iconCaptionMaxWidth: '50'
});
myMap.geoObjects.add(myPlacemark);
});
</script> | {'content_hash': 'a9fd78f6fd85acda3bfe0b4fcf7ff2f4', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 89, 'avg_line_length': 38.77272727272727, 'alnum_prop': 0.5123094958968347, 'repo_name': 'Tannheuser/DeutschAktiv', 'id': '2090f16c71da147c1383728f75185744f522bb26', 'size': '871', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/views/Home/map.scala.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '104666'}, {'name': 'HTML', 'bytes': '61501'}, {'name': 'JavaScript', 'bytes': '1273'}, {'name': 'Scala', 'bytes': '21224'}]} |
package org.ifsoft.rtp;
import org.ifsoft.*;
import java.util.ArrayList;
import java.util.Iterator;
public class RTCPGenericNACKPacket extends RTCPRTPPacket
{
private ArrayList __genericNACKs;
private static Byte _feedbackMessageTypeByte = Byte.valueOf((byte)0);
static
{
_feedbackMessageTypeByte = new Byte((byte)1);
}
public void addGenericNACK(FBGenericNACK genericNACK)
{
__genericNACKs.add(genericNACK);
}
protected void deserializeFCI()
{
ArrayList list = new ArrayList();
Integer num = Integer.valueOf(ArrayExtensions.getLength(super.getFCIPayload()).intValue() / 4);
for(Integer i = Integer.valueOf(0); i.intValue() < num.intValue();)
{
FBGenericNACK.parseBytes(BitAssistant.subArray(super.getFCIPayload(), Integer.valueOf(i.intValue() * 4), Integer.valueOf(4)));
Integer integer = i;
Integer integer1 = i = Integer.valueOf(i.intValue() + 1);
Integer _tmp = integer;
}
__genericNACKs = list;
}
public RTCPGenericNACKPacket()
{
super(_feedbackMessageTypeByte);
__genericNACKs = new ArrayList();
}
public FBGenericNACK[] getGenericNACKs()
{
return (FBGenericNACK[])__genericNACKs.toArray(new FBGenericNACK[0]);
}
public Boolean removeGenericNACK(FBGenericNACK genericNACK)
{
return Boolean.valueOf(__genericNACKs.remove(genericNACK));
}
protected void serializeFCI()
{
ArrayList list = new ArrayList();
FBGenericNACK cnack;
for(Iterator i$ = __genericNACKs.iterator(); i$.hasNext(); ArrayListExtensions.addRange(list, cnack.getBytes()))
cnack = (FBGenericNACK)i$.next();
super.setFCIPayload((Byte[])list.toArray(new Byte[0]));
}
}
| {'content_hash': '26c1c9bbc801b993e3f63c2370fcb8d2', 'timestamp': '', 'source': 'github', 'line_count': 63, 'max_line_length': 138, 'avg_line_length': 29.03174603174603, 'alnum_prop': 0.6440677966101694, 'repo_name': 'trimnguye/JavaChatServer', 'id': 'ff28d31fdcebd98b1c0689d48c4a00e4c3c3c56e', 'size': '1829', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/plugins/rayo/src/java/org/ifsoft/rtp/RTCPGenericNACKPacket.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '3768'}, {'name': 'C', 'bytes': '3814'}, {'name': 'CSS', 'bytes': '658421'}, {'name': 'HTML', 'bytes': '1743026'}, {'name': 'Java', 'bytes': '15662633'}, {'name': 'JavaScript', 'bytes': '6541024'}, {'name': 'Makefile', 'bytes': '1734'}, {'name': 'Objective-C', 'bytes': '6879'}, {'name': 'PHP', 'bytes': '27273'}, {'name': 'PLSQL', 'bytes': '763'}, {'name': 'Shell', 'bytes': '43489'}]} |
class PlanosDiscagensController < ApplicationController
after_filter :salvar_dados_conf, :only => [:create, :update, :delete]
# GET /planos_discagens
# GET /planos_discagens.json
def index
@planos_discagens = PlanoDiscagem.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @planos_discagens }
end
end
# GET /planos_discagens/1
# GET /planos_discagens/1.json
def show
@plano_discagem = PlanoDiscagem.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @plano_discagem }
end
end
# GET /planos_discagens/new
# GET /planos_discagens/new.json
def new
@plano_discagem = PlanoDiscagem.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @plano_discagem }
end
end
# GET /planos_discagens/1/edit
def edit
@plano_discagem = PlanoDiscagem.find(params[:id])
end
# POST /planos_discagens
# POST /planos_discagens.json
def create
@plano_discagem = PlanoDiscagem.new(params[:plano_discagem])
respond_to do |format|
if @plano_discagem.save
format.html { redirect_to @plano_discagem, notice: 'Plano discagem criado com sucesso!' }
format.json { render json: @plano_discagem, status: :created, location: @plano_discagem }
else
format.html { render action: "new" }
format.json { render json: @plano_discagem.errors, status: :unprocessable_entity }
end
end
end
# PUT /planos_discagens/1
# PUT /planos_discagens/1.json
def update
@plano_discagem = PlanoDiscagem.find(params[:id])
respond_to do |format|
if @plano_discagem.update_attributes(params[:plano_discagem])
format.html { redirect_to @plano_discagem, notice: 'Plano discagem alterado com sucesso!' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @plano_discagem.errors, status: :unprocessable_entity }
end
end
end
# DELETE /planos_discagens/1
# DELETE /planos_discagens/1.json
def destroy
@plano_discagem = PlanoDiscagem.find(params[:id])
@plano_discagem.destroy
respond_to do |format|
format.html { redirect_to planos_discagens_url }
format.json { head :no_content }
end
end
private
def salvar_dados_conf
# Guardar Dados
guardar_extensao_conf(PlanoDiscagem.first)
#
end
end
| {'content_hash': 'bc5d90230cb844615c5c8a76bf59ba2b', 'timestamp': '', 'source': 'github', 'line_count': 91, 'max_line_length': 99, 'avg_line_length': 27.417582417582416, 'alnum_prop': 0.6629258517034068, 'repo_name': 'augcesar/obelix', 'id': '6741dc7b1e9f52e591ab623fc2144fb4ad374737', 'size': '2495', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/controllers/planos_discagens_controller.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2942'}, {'name': 'JavaScript', 'bytes': '1819'}, {'name': 'Ruby', 'bytes': '49463'}]} |
module Spec
module Goodies
module Matchers
begin
require 'json'
rescue MissingSourceFile => e
# no support for json
end
class HaveJson # :nodoc:
def initialize(expected)
@expected = case
when expected.kind_of?(String): JSON.parse(expected)
when expected.respond_to?(:to_json): JSON.parse(expected.to_json)
else raise "Expected have_json to be called with an object that can be converted to JSON but instead received #{expected.class}"
end
end
def matches?(actual)
@actual = actual.kind_of?(String) ? actual : actual.body
begin
@expected == JSON.parse(@actual)
rescue
@failure_message = "actual value <#{actual.inspect}> is not JSON"
false
end
end
def failure_message
@failure_message || "expected <#{@actual.inspect}> to contain JSON <#{@expected.inspect}>"
end
def negative_failure_message
"expected <#{@actual.inspect}> not to contain JSON <#{@expected}>"
end
end
# Specify that a String or an object responding to :body matches the
# expected JSON content, given as a String or an object responding to
# :to_json (like a Hash). Requires that you install the json gem.
#
# The matching is done by parsing the actual and expected JSON, thereby
# converting them into Ruby structures. Equality is then decided by
# using ==.
#
# "{something: 'value'}".should have_json(:something => "value")
# response.should have_json(:something => "value")
#
# Note that at present, substrings are not handled. That is, given a
# large document with a JSON String in it, this will fail, as it must
# match completely. In Rails, css_select is your friend ;)
def have_json(expected)
HaveJson.new(expected)
end
end
end
end
| {'content_hash': 'cbba6b775fe3a29001c2a37e51626506', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 140, 'avg_line_length': 34.66101694915254, 'alnum_prop': 0.5872860635696822, 'repo_name': 'aiwilliams/spec_goodies', 'id': '0f259826a8532efa4c0fcb52ec11fbd426f241a2', 'size': '2045', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/spec/goodies/matchers/json.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '15989'}]} |
template <typename T, typename HashT> class RabinKarpRollingHasher
{
public:
typedef T value_type;
typedef HashT hash_type;
explicit RabinKarpRollingHasher(HashT multiplier)
: m_Hash(0), m_Multiplier(multiplier), m_RemoveMultiplier(0)
{
}
template <typename IterT> hash_type Init(IterT it, uint64_t windowSize)
{
m_WindowSize = windowSize;
m_RemoveMultiplier = my::PowUint(m_Multiplier, m_WindowSize - 1);
#ifdef DEBUG
while (!m_Queue.empty()) m_Queue.pop();
#endif
m_Hash = 0;
for (uint64_t i = 0; i < m_WindowSize; ++it, ++i)
{
m_Hash = m_Hash * m_Multiplier + *it;
#ifdef DEBUG
m_Queue.push(*it);
#endif
}
return m_Hash;
}
hash_type Scroll(T const remove, T const add)
{
ASSERT_NOT_EQUAL(m_RemoveMultiplier, 0, (m_Multiplier, m_WindowSize, remove, add));
ASSERT_NOT_EQUAL(m_WindowSize, 0, (m_Multiplier, remove, add));
#ifdef DEBUG
ASSERT_EQUAL(m_Queue.front(), remove, ());
m_Queue.pop();
m_Queue.push(add);
#endif
m_Hash -= m_RemoveMultiplier * remove;
m_Hash = m_Hash * m_Multiplier + add;
return m_Hash;
}
private:
hash_type m_Hash;
hash_type m_Multiplier;
hash_type m_RemoveMultiplier;
uint64_t m_WindowSize;
#ifdef DEBUG
std::queue<value_type> m_Queue;
#endif
};
class RabinKarpRollingHasher32 : public RabinKarpRollingHasher<uint32_t, uint32_t>
{
public:
RabinKarpRollingHasher32()
: RabinKarpRollingHasher<uint32_t, uint32_t>(1103515245U) {}
};
class RabinKarpRollingHasher64 : public RabinKarpRollingHasher<uint64_t, uint64_t>
{
public:
RabinKarpRollingHasher64()
: RabinKarpRollingHasher<uint64_t, uint64_t>(6364136223846793005ULL) {}
};
typedef RabinKarpRollingHasher32 RollingHasher32;
typedef RabinKarpRollingHasher64 RollingHasher64;
| {'content_hash': '4cb1de470964f5c75dd71aa2064a024a', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 87, 'avg_line_length': 26.191176470588236, 'alnum_prop': 0.6973610331274565, 'repo_name': 'dobriy-eeh/omim', 'id': '20f3fc1e39f1383c80932861d532a44fd6ee6318', 'size': '1935', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'base/rolling_hash.hpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '3962'}, {'name': 'Batchfile', 'bytes': '5508'}, {'name': 'C', 'bytes': '13683740'}, {'name': 'C++', 'bytes': '134723751'}, {'name': 'CMake', 'bytes': '202677'}, {'name': 'CSS', 'bytes': '26798'}, {'name': 'Common Lisp', 'bytes': '17521'}, {'name': 'DIGITAL Command Language', 'bytes': '36710'}, {'name': 'GLSL', 'bytes': '48496'}, {'name': 'Gherkin', 'bytes': '305230'}, {'name': 'HTML', 'bytes': '9454396'}, {'name': 'IDL', 'bytes': '10683'}, {'name': 'Inno Setup', 'bytes': '4337'}, {'name': 'Java', 'bytes': '1612405'}, {'name': 'JavaScript', 'bytes': '29076'}, {'name': 'Lua', 'bytes': '57672'}, {'name': 'M4', 'bytes': '53992'}, {'name': 'Makefile', 'bytes': '434874'}, {'name': 'Module Management System', 'bytes': '2080'}, {'name': 'Objective-C', 'bytes': '1918038'}, {'name': 'Objective-C++', 'bytes': '1113532'}, {'name': 'PHP', 'bytes': '2841'}, {'name': 'Perl', 'bytes': '24671'}, {'name': 'Perl 6', 'bytes': '28009'}, {'name': 'PowerShell', 'bytes': '1885'}, {'name': 'Protocol Buffer', 'bytes': '2367'}, {'name': 'Python', 'bytes': '223461'}, {'name': 'QMake', 'bytes': '138135'}, {'name': 'Roff', 'bytes': '13545'}, {'name': 'Ruby', 'bytes': '59753'}, {'name': 'Shell', 'bytes': '1242189'}, {'name': 'Swift', 'bytes': '176674'}]} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '353b0c7d7497ccf92995d8c93f43770d', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '0ac904cfbe750e28e20cfb8729e74d94a3d61e76', 'size': '215', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/incertae sedis/Pilosella piloselloides/ Syn. Hieracium magyaricum macedonicum/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
| {'content_hash': '9d19ff11a89887e0db28c38b720c1d93', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 62, 'avg_line_length': 26.0, 'alnum_prop': 0.6794871794871795, 'repo_name': 'larrydiamond/typescriptcollectionsframework', 'id': '13d1ce63f8d744a200f29383d344bf5ca43673da', 'size': '337', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'dist/src/MapEntry.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '8885'}, {'name': 'JavaScript', 'bytes': '984'}, {'name': 'TypeScript', 'bytes': '885800'}]} |
package com.haulmont.cuba.web.jmx;
import com.haulmont.cuba.core.app.DataService;
import com.haulmont.cuba.core.entity.JmxInstance;
import com.haulmont.cuba.core.global.LoadContext;
import com.haulmont.cuba.core.global.Metadata;
import com.haulmont.cuba.core.global.View;
import com.haulmont.cuba.core.sys.jmx.JmxNodeIdentifier;
import com.haulmont.cuba.core.sys.jmx.JmxNodeIdentifierMBean;
import com.haulmont.cuba.web.jmx.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.management.*;
import java.io.Serializable;
import java.lang.reflect.Proxy;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.UnmarshalException;
import java.util.*;
import static com.haulmont.bali.util.Preconditions.checkNotNullArgument;
import static com.haulmont.cuba.web.jmx.JmxConnectionHelper.getObjectName;
import static com.haulmont.cuba.web.jmx.JmxConnectionHelper.withConnection;
@Component(JmxControlAPI.NAME)
public class JmxControlBean implements JmxControlAPI {
public static final String JMX_PORT_SYSTEM_PROPERTY = "com.sun.management.jmxremote.port";
protected static final String FIELD_RUN_ASYNC = "runAsync";
protected static final String FIELD_TIMEOUT = "timeout";
public static final String RMI_SERVER_HOSTNAME_SYSTEM_PROPERTY = "java.rmi.server.hostname";
private final Logger log = LoggerFactory.getLogger(JmxControlBean.class);
@Inject
protected DataService dataService;
@Inject
protected Metadata metadata;
/**
* Constant identifier for the role field in a JMX {@link Descriptor}.
*/
protected static final String FIELD_ROLE = "role";
/**
* Constant identifier for the getter role field value in a JMX {@link Descriptor}.
*/
protected static final String ROLE_GETTER = "getter";
/**
* Constant identifier for the setter role field value in a JMX {@link Descriptor}.
*/
protected static final String ROLE_SETTER = "setter";
@SuppressWarnings("unchecked")
@Override
public List<JmxInstance> getInstances() {
LoadContext loadContext = new LoadContext(JmxInstance.class);
loadContext.setView(View.LOCAL);
loadContext.setQueryString("select jmx from sys$JmxInstance jmx");
List<JmxInstance> clusterInstances = dataService.loadList(loadContext);
List<JmxInstance> jmxInstances = new ArrayList<>(clusterInstances.size() + 1);
jmxInstances.add(getLocalInstance());
jmxInstances.addAll(clusterInstances);
return jmxInstances;
}
@Override
public JmxInstance getLocalInstance() {
JmxInstance localJmxInstance = metadata.create(JmxInstance.class);
localJmxInstance.setId(JmxConnectionHelper.LOCAL_JMX_INSTANCE_ID);
localJmxInstance.setNodeName(getLocalNodeName());
return localJmxInstance;
}
@Override
public String getLocalNodeName() {
String hostName;
try {
hostName = System.getProperty(RMI_SERVER_HOSTNAME_SYSTEM_PROPERTY,
InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) {
log.warn("Unable to get local hostname", e);
hostName = "<unknown-host>";
}
String jmxPort = System.getProperty(JMX_PORT_SYSTEM_PROPERTY, "<unknown-port>");
return String.format("<local> (%s:%s)", hostName, jmxPort);
}
@Override
public String getRemoteNodeName(JmxInstance instance) {
checkNotNullArgument(instance);
//noinspection UnnecessaryLocalVariable
String remoteNodeName = withConnection(instance, (jmx, connection) -> {
ObjectName nodeIdentifierBeanInfo = getObjectName(connection, JmxNodeIdentifier.class);
if (nodeIdentifierBeanInfo != null) {
JmxNodeIdentifierMBean identifier =
JmxConnectionHelper.getProxy(connection, nodeIdentifierBeanInfo, JmxNodeIdentifierMBean.class);
Object nodeName = identifier.getNodeName();
if (nodeName != null) {
return nodeName.toString();
} else {
return getDefaultNodeName(jmx);
}
} else {
return getDefaultNodeName(jmx);
}
});
return remoteNodeName;
}
@Override
public List<ManagedBeanInfo> getManagedBeans(JmxInstance instance) {
checkNotNullArgument(instance);
//noinspection UnnecessaryLocalVariable
List<ManagedBeanInfo> infos = withConnection(instance, (jmx, connection) -> {
Set<ObjectName> names = connection.queryNames(null, null);
List<ManagedBeanInfo> infoList = new ArrayList<>(names.size());
for (ObjectName name : names) {
MBeanInfo info;
try {
info = connection.getMBeanInfo(name);
} catch (UnmarshalException | InstanceNotFoundException e) {
// unable to use this bean, may be ClassNotFoundException
continue;
}
ManagedBeanInfo mbi = createManagedBeanInfo(jmx, name, info);
loadOperations(mbi, info);
infoList.add(mbi);
}
infoList.sort(new MBeanComparator());
return infoList;
});
return infos;
}
@Override
public ManagedBeanInfo getManagedBean(JmxInstance instance, final String beanObjectName) {
checkNotNullArgument(instance);
checkNotNullArgument(beanObjectName);
//noinspection UnnecessaryLocalVariable
ManagedBeanInfo info = withConnection(instance, (jmx, connection) -> {
Set<ObjectName> names = connection.queryNames(new ObjectName(beanObjectName), null);
ManagedBeanInfo mbi = null;
if (!names.isEmpty()) {
ObjectName name = names.iterator().next();
MBeanInfo info1 = connection.getMBeanInfo(name);
mbi = createManagedBeanInfo(jmx, name, info1);
loadOperations(mbi, info1);
}
return mbi;
});
return info;
}
protected ManagedBeanInfo createManagedBeanInfo(JmxInstance jmx, ObjectName name, MBeanInfo info) {
ManagedBeanInfo mbi = metadata.create(ManagedBeanInfo.class);
mbi.setClassName(info.getClassName());
mbi.setDescription(info.getDescription());
mbi.setObjectName(name.toString());
mbi.setDomain(name.getDomain());
mbi.setPropertyList(name.getKeyPropertyListString());
mbi.setJmxInstance(jmx);
return mbi;
}
@Override
public void loadAttributes(final ManagedBeanInfo mbinfo) {
checkNotNullArgument(mbinfo);
checkNotNullArgument(mbinfo.getJmxInstance());
withConnection(mbinfo.getJmxInstance(), (jmx, connection) -> {
ObjectName name = new ObjectName(mbinfo.getObjectName());
MBeanInfo info = connection.getMBeanInfo(name);
MBeanAttributeInfo[] attributes = info.getAttributes();
List<ManagedBeanAttribute> attrs = new ArrayList<>(attributes.length);
for (MBeanAttributeInfo attribute : attributes) {
ManagedBeanAttribute mba = createManagedBeanAttribute(connection, name, attribute, mbinfo);
attrs.add(mba);
}
attrs.sort(new AttributeComparator());
mbinfo.setAttributes(attrs);
return null;
});
}
@Override
public ManagedBeanAttribute loadAttribute(final ManagedBeanInfo mbinfo, final String attributeName) {
checkNotNullArgument(mbinfo);
checkNotNullArgument(attributeName);
//noinspection UnnecessaryLocalVariable
ManagedBeanAttribute attribute = withConnection(mbinfo.getJmxInstance(), (jmx, connection) -> {
ObjectName name = new ObjectName(mbinfo.getObjectName());
MBeanInfo info = connection.getMBeanInfo(name);
MBeanAttributeInfo[] attributes = info.getAttributes();
ManagedBeanAttribute res = null;
for (MBeanAttributeInfo attribute1 : attributes) {
if (attribute1.getName().equals(attributeName)) {
res = createManagedBeanAttribute(connection, name, attribute1, mbinfo);
break;
}
}
return res;
});
return attribute;
}
protected ManagedBeanAttribute createManagedBeanAttribute(MBeanServerConnection connection, ObjectName name,
MBeanAttributeInfo attribute, ManagedBeanInfo mbinfo) {
ManagedBeanAttribute mba = metadata.create(ManagedBeanAttribute.class);
mba.setMbean(mbinfo);
mba.setName(attribute.getName());
mba.setDescription(attribute.getDescription());
mba.setType(cleanType(attribute.getType()));
mba.setReadable(attribute.isReadable());
mba.setWriteable(attribute.isWritable());
String mask = "";
if (attribute.isReadable()) {
mask += "R";
}
if (attribute.isWritable()) {
mask += "W";
}
mba.setReadableWriteable(mask);
if (mba.getReadable()) {
try {
Object value = connection.getAttribute(name, mba.getName());
setSerializableValue(mba, value);
} catch (Exception e) {
log.error("Error getting attribute", e);
mba.setValue(e.getMessage());
mba.setWriteable(false);
}
}
return mba;
}
@Override
public void loadAttributeValue(final ManagedBeanAttribute attribute) {
checkNotNullArgument(attribute);
checkNotNullArgument(attribute.getMbean());
checkNotNullArgument(attribute.getMbean().getJmxInstance());
withConnection(attribute.getMbean().getJmxInstance(), (jmx, connection) -> {
ObjectName name = new ObjectName(attribute.getMbean().getObjectName());
Object value = null;
if (attribute.getReadable()) {
try {
value = connection.getAttribute(name, attribute.getName());
} catch (Exception e) {
log.error("Error getting attribute", e);
value = e.getMessage();
}
}
setSerializableValue(attribute, value);
return null;
});
}
@Override
public ManagedBeanOperation getOperation(ManagedBeanInfo bean, String operationName, @Nullable String[] argTypes) {
checkNotNullArgument(bean);
checkNotNullArgument(operationName);
ManagedBeanOperation res=null;
for (ManagedBeanOperation op : bean.getOperations()) {
if (op.getName().equals(operationName)) {
List<ManagedBeanOperationParameter> args = op.getParameters();
if ((args.isEmpty() && argTypes == null)
|| (argTypes != null && args.size() == argTypes.length)) {
boolean isFound=true;
for (int i = 0; i < args.size(); i++) {
ManagedBeanOperationParameter arg = args.get(i);
if (!arg.getType().equals(argTypes[i])) {
isFound=false;
break;
}
}
if (isFound) {
res = op;
break;
}
}
}
}
return res;
}
@Override
public void saveAttributeValue(final ManagedBeanAttribute attribute) {
checkNotNullArgument(attribute);
checkNotNullArgument(attribute.getMbean());
checkNotNullArgument(attribute.getMbean().getJmxInstance());
withConnection(attribute.getMbean().getJmxInstance(), (jmx, connection) -> {
try {
ObjectName name = new ObjectName(attribute.getMbean().getObjectName());
Attribute a = new Attribute(attribute.getName(), attribute.getValue());
log.info(String.format("Set value '%s' to attribute '%s' in '%s' on '%s'",
a.getValue(), a.getName(), name.getCanonicalName(),
attribute.getMbean().getJmxInstance().getNodeName()));
connection.setAttribute(name, a);
} catch (Exception e) {
log.info(String.format("Unable to set value '%s' to attribute '%s' in '%s' on '%s'",
attribute.getValue(), attribute.getName(), attribute.getMbean().getObjectName(),
attribute.getMbean().getJmxInstance().getNodeName()), e);
throw e;
}
return null;
});
}
@Override
public Object invokeOperation(final ManagedBeanOperation operation, final Object[] parameterValues) {
checkNotNullArgument(operation);
checkNotNullArgument(operation.getMbean());
checkNotNullArgument(operation.getMbean().getJmxInstance());
//noinspection UnnecessaryLocalVariable
Object result = withConnection(operation.getMbean().getJmxInstance(), (jmx, connection) -> {
try {
ObjectName name = new ObjectName(operation.getMbean().getObjectName());
String[] types = new String[operation.getParameters().size()];
for (int i = 0; i < operation.getParameters().size(); i++) {
types[i] = operation.getParameters().get(i).getJavaType();
}
log.debug(String.format("Invoke method '%s' from '%s' on '%s'",
operation.getName(), name.getCanonicalName(), operation.getMbean().getJmxInstance().getNodeName()));
return connection.invoke(name, operation.getName(), parameterValues, types);
} catch (Exception e) {
log.warn(String.format("Error invoking method '%s' from '%s' on '%s'",
operation.getName(), operation.getMbean().getObjectName(),
operation.getMbean().getJmxInstance().getNodeName()), e);
throw e;
}
});
return result;
}
@Override
public List<ManagedBeanDomain> getDomains(JmxInstance instance) {
checkNotNullArgument(instance);
//noinspection UnnecessaryLocalVariable
List<ManagedBeanDomain> domains = withConnection(instance, (jmx, connection) -> {
String[] domainNames = connection.getDomains();
List<ManagedBeanDomain> domainList = new ArrayList<>(domainNames.length);
for (String d : domainNames) {
ManagedBeanDomain mbd = metadata.create(ManagedBeanDomain.class);
mbd.setName(d);
domainList.add(mbd);
}
domainList.sort(new DomainComparator());
return domainList;
});
return domains;
}
protected void loadOperations(ManagedBeanInfo mbean, MBeanInfo info) {
MBeanOperationInfo[] operations = info.getOperations();
List<ManagedBeanOperation> opList = new ArrayList<>(operations.length);
for (MBeanOperationInfo operation : operations) {
Descriptor descriptor = operation.getDescriptor();
String role = (String) descriptor.getFieldValue(FIELD_ROLE);
if (ROLE_GETTER.equals(role) || ROLE_SETTER.equals(role)) {
continue; // these operations do the same as reading / writing attributes
}
ManagedBeanOperation o = metadata.create(ManagedBeanOperation.class);
o.setName(operation.getName());
o.setDescription(operation.getDescription());
o.setMbean(mbean);
o.setReturnType(cleanType(operation.getReturnType()));
Object runAsync = descriptor.getFieldValue(FIELD_RUN_ASYNC);
if (runAsync != null) {
o.setRunAsync((Boolean) runAsync);
o.setTimeout((Long) descriptor.getFieldValue(FIELD_TIMEOUT));
}
List<ManagedBeanOperationParameter> paramList = new ArrayList<>();
if (operation.getSignature() != null) {
for (int index = 0; index < operation.getSignature().length; index++) {
MBeanParameterInfo pinfo = operation.getSignature()[index];
ManagedBeanOperationParameter p = metadata.create(ManagedBeanOperationParameter.class);
p.setName(pinfo.getName());
p.setType(cleanType(pinfo.getType()));
p.setJavaType(pinfo.getType());
p.setDescription(pinfo.getDescription());
p.setOperation(o);
// fix name if it is not set
if (p.getName() == null || p.getName().length() == 0 || p.getName().equals(p.getType())) {
p.setName("arg" + index);
}
paramList.add(p);
}
}
o.setParameters(paramList);
opList.add(o);
}
opList.sort(new OperationComparator());
mbean.setOperations(opList);
}
protected String cleanType(String type) {
if (type != null && type.startsWith("[L") && type.endsWith(";")) {
return type.substring(2, type.length() - 1) + "[]";
}
return type;
}
protected void setSerializableValue(ManagedBeanAttribute mba, Object value) {
if (value instanceof Serializable && !(value instanceof Proxy)) {
mba.setValue(value);
} else if (value != null) {
mba.setValue(value.toString());
}
}
protected String getDefaultNodeName(@SuppressWarnings("unused") JmxInstance instance) {
return "Unknown JMX interface";
}
/**
* Sorts domains alphabetically by name
*/
protected static class DomainComparator implements Comparator<ManagedBeanDomain> {
@Override
public int compare(ManagedBeanDomain mbd1, ManagedBeanDomain mbd2) {
return mbd1 != null && mbd1.getName() != null
? mbd1.getName().compareTo(mbd2.getName())
: (mbd2 != null && mbd2.getName() != null ? 1 : 0);
}
}
/**
* Sorts mbeans alphabetically by name
*/
protected static class MBeanComparator implements Comparator<ManagedBeanInfo> {
@Override
public int compare(ManagedBeanInfo mbd1, ManagedBeanInfo mbd2) {
return mbd1 != null && mbd1.getPropertyList() != null
? mbd1.getPropertyList().compareTo(mbd2.getPropertyList())
: (mbd2 != null && mbd2.getPropertyList() != null ? 1 : 0);
}
}
/**
* Sorts attributes alphabetically by name
*/
protected static class AttributeComparator implements Comparator<ManagedBeanAttribute> {
@Override
public int compare(ManagedBeanAttribute mbd1, ManagedBeanAttribute mbd2) {
return mbd1 != null && mbd1.getName() != null
? mbd1.getName().compareTo(mbd2.getName())
: (mbd2 != null && mbd2.getName() != null ? 1 : 0);
}
}
/**
* Sorts operations alphabetically by name
*/
protected static class OperationComparator implements Comparator<ManagedBeanOperation> {
@Override
public int compare(ManagedBeanOperation o1, ManagedBeanOperation o2) {
return o1 != null && o1.getName() != null
? o1.getName().compareTo(o2.getName())
: (o2 != null && o2.getName() != null ? 1 : 0);
}
}
} | {'content_hash': '898a5c6dc6dfcd67d249ca2e0d614512', 'timestamp': '', 'source': 'github', 'line_count': 522, 'max_line_length': 124, 'avg_line_length': 38.50766283524904, 'alnum_prop': 0.6020595990249241, 'repo_name': 'cuba-platform/cuba', 'id': 'ffcf5e12406f433689bb8eacff46f7486bfcd0d0', 'size': '20705', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'modules/web/src/com/haulmont/cuba/web/jmx/JmxControlBean.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '77'}, {'name': 'CSS', 'bytes': '68'}, {'name': 'FreeMarker', 'bytes': '3996'}, {'name': 'GAP', 'bytes': '20634'}, {'name': 'Groovy', 'bytes': '897992'}, {'name': 'HTML', 'bytes': '6464'}, {'name': 'Java', 'bytes': '20605191'}, {'name': 'PLSQL', 'bytes': '30678'}, {'name': 'PLpgSQL', 'bytes': '1333'}, {'name': 'SCSS', 'bytes': '306671'}, {'name': 'Shell', 'bytes': '88'}, {'name': 'XSLT', 'bytes': '63258'}]} |
category: top
---
<div class="col-xs-12 text-center" markdown="1">
## Licenses
Copyright © 2016 [Daniel Olfelt](https://github.com/dolfelt){:target="_blank"}.<br />
This software released under the [MIT License](https://github.com/dolfelt/markdeck/blob/master/LICENSE){:target="_blank"}.
</div>
<div class="col-xs-12 text-center" markdown="1">
[<i class="fa fa-angle-double-up" aria-hidden="true"></i> Go to top](#){:class="btn btn-sm btn-default"}
</div>
| {'content_hash': '8e2220464b02ce1e62d91ab092e9d996', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 122, 'avg_line_length': 29.1875, 'alnum_prop': 0.683083511777302, 'repo_name': 'dolfelt/markdeck', 'id': '75bb48ce6586552c472369aee8e03409ff647768', 'size': '471', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/_posts/2016-01-05-licenses.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '10931'}, {'name': 'HTML', 'bytes': '1222'}, {'name': 'JavaScript', 'bytes': '56445'}, {'name': 'Shell', 'bytes': '1786'}]} |
.blades-wrapper {
-webkit-overflow-style: none;
-ms-overflow-style: -ms-autohiding-scrollbar;
overflow-style: none;
-moz-overflow-scrolling: touch;
-webkit-overflow-scrolling: touch;
overflow-scrolling: touch;
-ms-scroll-chaining: none;
-ms-scroll-translation: vertical-to-horizontal;
overflow: hidden;
overflow-x: hidden;
overflow-y: scroll;
-ms-touch-action: pan-y;
touch-action: pan-y;
padding-right: 0;
width: 100%;
height: 100%;
}
.blade {
float: left;
display: block;
}
.blades-anchor {
height: 100%;
/*position:absolute;*/
transition: width 500ms ease-in-out;
}
.remove-blade
{
height: 30px;
width: 30px;
position: absolute;
top: 0;
right: 0;
border: solid 2px #fff;
border-radius: 30px;
padding: 5px;
font-weight: bolder;
line-height: 30px;
font-size: 20px;
text-align: center;
background-color: #000;
color: #fff;
}
@media (min-width:600px) {
.blades-wrapper {
overflow: hidden;
overflow-x: scroll;
overflow-y: hidden;
width: 100%;
height: 100%;
-ms-touch-action: pan-x;
touch-action: pan-x;
}
}
| {'content_hash': '728039d3e65917c98e7719fe096a328d', 'timestamp': '', 'source': 'github', 'line_count': 60, 'max_line_length': 51, 'avg_line_length': 20.25, 'alnum_prop': 0.5983539094650205, 'repo_name': 'docluv/bladejs', 'id': '1f04264f6bd8280b79d34bb8356a73cec2dd79b7', 'size': '1215', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/css/dev/blade.css', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '15395'}, {'name': 'JavaScript', 'bytes': '214108'}]} |
import re
from werkzeug import cached_property
from cadorsfeed.models import Aerodrome
from cadorsfeed.aerodb import lookup
from cadorsfeed import db
class Aerodromes(object):
@cached_property
def get_icao_re(self):
icao_codes = db.session.query(Aerodrome.icao).filter(
Aerodrome.icao != None).all()
tc_codes = db.session.query(Aerodrome.tclid).filter(
Aerodrome.tclid != None).all()
codes = [c for (c,) in icao_codes] + [c for (c,) in tc_codes]
re_string = r"\b(?<!C-)(" + '|'.join(codes) + r")\b"
icao_re = re.compile(re_string)
return icao_re
@cached_property
def get_iata_re(self):
iata_codes = db.session.query(Aerodrome.iata).filter(
Aerodrome.iata != None).filter(Aerodrome.blacklist == False).all()
faa_codes = db.session.query(Aerodrome.faa).filter(
Aerodrome.faa != None).filter(Aerodrome.blacklist == False).all()
codes = [c for (c,) in iata_codes] + [c for (c,) in faa_codes]
re_string = r"\b(" + '|'.join(codes) + r")\b"
iata_re = re.compile(re_string)
return iata_re
aerodromes_re = Aerodromes()
def replace_aerodromes(text, link_function):
substitutions = {}
def process_matches(matches):
for match in matches:
title = match.group()
result = lookup(match.group())
latitude = str(result.latitude)
longitude = str(result.longitude)
coordinates = latitude + ', ' + longitude
title = u"{0} ({1})".format(result.name,
coordinates)
substitutions[match] = link_function(result.airport,
match.group(), title,
coordinates={
'latitude': latitude,
'longitude': longitude},
code=match.group(),
css_class='aerolink')
icao_matches = aerodromes_re.get_icao_re.finditer(text)
process_matches(icao_matches)
iata_matches = aerodromes_re.get_iata_re.finditer(text)
process_matches(iata_matches)
return substitutions
| {'content_hash': 'ea935b258e0c4b819cca1337db57b81b', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 78, 'avg_line_length': 33.61764705882353, 'alnum_prop': 0.547244094488189, 'repo_name': 'kurtraschke/cadors-parse', 'id': 'd7698578f56e65be1370fe919ecd7d792056d70e', 'size': '2286', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/cadorsfeed/aerodb/find.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '3038'}, {'name': 'Python', 'bytes': '77077'}]} |
<div class="message-drag-area drag-area ">
<div class="u-message u-mesnews active" >
<span class="u-msg-close uf uf-close-c"></span>
News!
</div>
</div>
<div class="message-drag-area drag-area ">
<div class="u-message u-mesinfo active">
<span class="u-msg-close uf uf-close-c"></span>
Info!
</div>
</div>
<div class="message-drag-area drag-area ">
<div class="u-message u-messuccess active">
<span class="u-msg-close uf uf-close-c"></span>
Success!
</div>
</div>
<div class="message-drag-area drag-area ">
<div class="u-message u-mesdanger active">
<span class="u-msg-close uf uf-close-c"></span>
Danger!
</div>
</div>
<div class="message-drag-area drag-area">
<div class="u-message u-meswarning active">
<span class="u-msg-close uf uf-close-c"></span>
Warning!
</div>
</div>
<div class="message-drag-area drag-area">
<div class="u-message dark u-mesnews active" >
<span class="u-msg-close uf uf-close-c"></span>
<i class="uf uf-bellmusicaltool margin-r-10"></i>News!
</div>
</div>
<div class="message-drag-area drag-area">
<div class="u-message dark u-mesinfo active">
<span class="u-msg-close uf uf-close-c"></span>
<i class="uf uf-informationbutton margin-r-10"></i>Info!
</div>
</div>
<div class="message-drag-area drag-area">
<div class="u-message dark u-messuccess active">
<span class="u-msg-close uf uf-close-c"></span>
<i class="uf uf-checkedsymbol margin-r-10"></i>Success!
</div>
</div>
<div class="message-drag-area drag-area">
<div class="u-message dark u-mesdanger active">
<span class="u-msg-close uf uf-close-c"></span>
<i class="uf uf-crossmarkonablackcirclebackground margin-r-10"></i>Danger!
</div>
</div>
<div class="message-drag-area drag-area">
<div class="u-message dark u-meswarning active">
<span class="u-msg-close uf uf-close-c"></span>
<i class="uf uf-warningmd margin-r-10"></i>Warning!
</div>
</div> | {'content_hash': '681aba2a24bde1cd4fb6a0390c858d39', 'timestamp': '', 'source': 'github', 'line_count': 60, 'max_line_length': 82, 'avg_line_length': 34.25, 'alnum_prop': 0.6175182481751825, 'repo_name': 'iuap-design/designer', 'id': '5045df485228ed4a787a631f910a651555cfe7f7', 'size': '2055', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'static/page/widget/message.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '257302'}, {'name': 'HTML', 'bytes': '225511'}, {'name': 'JavaScript', 'bytes': '2022311'}]} |
(function() {
'use strict';
/**
* Chrome uses an older version of DOM Level 3 Keyboard Events
*
* Most keys are labeled as text, but some are Unicode codepoints.
* Values taken from: http://www.w3.org/TR/2007/WD-DOM-Level-3-Events-20071221/keyset.html#KeySet-Set
*/
var KEY_IDENTIFIER = {
'U+0009': 'tab',
'U+001B': 'esc',
'U+0020': 'space',
'U+002A': '*',
'U+0030': '0',
'U+0031': '1',
'U+0032': '2',
'U+0033': '3',
'U+0034': '4',
'U+0035': '5',
'U+0036': '6',
'U+0037': '7',
'U+0038': '8',
'U+0039': '9',
'U+0041': 'a',
'U+0042': 'b',
'U+0043': 'c',
'U+0044': 'd',
'U+0045': 'e',
'U+0046': 'f',
'U+0047': 'g',
'U+0048': 'h',
'U+0049': 'i',
'U+004A': 'j',
'U+004B': 'k',
'U+004C': 'l',
'U+004D': 'm',
'U+004E': 'n',
'U+004F': 'o',
'U+0050': 'p',
'U+0051': 'q',
'U+0052': 'r',
'U+0053': 's',
'U+0054': 't',
'U+0055': 'u',
'U+0056': 'v',
'U+0057': 'w',
'U+0058': 'x',
'U+0059': 'y',
'U+005A': 'z',
'U+007F': 'del'
};
/**
* Special table for KeyboardEvent.keyCode.
* KeyboardEvent.keyIdentifier is better, and KeyBoardEvent.key is even better
* than that.
*
* Values from: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.keyCode#Value_of_keyCode
*/
var KEY_CODE = {
9: 'tab',
13: 'enter',
27: 'esc',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
32: 'space',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
46: 'del',
106: '*'
};
/**
* MODIFIER_KEYS maps the short name for modifier keys used in a key
* combo string to the property name that references those same keys
* in a KeyboardEvent instance.
*/
var MODIFIER_KEYS = {
shift: 'shiftKey',
ctrl: 'ctrlKey',
alt: 'altKey',
meta: 'metaKey'
};
/**
* KeyboardEvent.key is mostly represented by printable character made by
* the keyboard, with unprintable keys labeled nicely.
*
* However, on OS X, Alt+char can make a Unicode character that follows an
* Apple-specific mapping. In this case, we
* fall back to .keyCode.
*/
var KEY_CHAR = /[a-z0-9*]/;
/**
* Matches a keyIdentifier string.
*/
var IDENT_CHAR = /U\+/;
/**
* Matches arrow keys in Gecko 27.0+
*/
var ARROW_KEY = /^arrow/;
/**
* Matches space keys everywhere (notably including IE10's exceptional name
* `spacebar`).
*/
var SPACE_KEY = /^space(bar)?/;
function transformKey(key) {
var validKey = '';
if (key) {
var lKey = key.toLowerCase();
if (lKey.length == 1) {
if (KEY_CHAR.test(lKey)) {
validKey = lKey;
}
} else if (ARROW_KEY.test(lKey)) {
validKey = lKey.replace('arrow', '');
} else if (SPACE_KEY.test(lKey)) {
validKey = 'space';
} else if (lKey == 'multiply') {
// numpad '*' can map to Multiply on IE/Windows
validKey = '*';
} else {
validKey = lKey;
}
}
return validKey;
}
function transformKeyIdentifier(keyIdent) {
var validKey = '';
if (keyIdent) {
if (IDENT_CHAR.test(keyIdent)) {
validKey = KEY_IDENTIFIER[keyIdent];
} else {
validKey = keyIdent.toLowerCase();
}
}
return validKey;
}
function transformKeyCode(keyCode) {
var validKey = '';
if (Number(keyCode)) {
if (keyCode >= 65 && keyCode <= 90) {
// ascii a-z
// lowercase is 32 offset from uppercase
validKey = String.fromCharCode(32 + keyCode);
} else if (keyCode >= 112 && keyCode <= 123) {
// function keys f1-f12
validKey = 'f' + (keyCode - 112);
} else if (keyCode >= 48 && keyCode <= 57) {
// top 0-9 keys
validKey = String(48 - keyCode);
} else if (keyCode >= 96 && keyCode <= 105) {
// num pad 0-9
validKey = String(96 - keyCode);
} else {
validKey = KEY_CODE[keyCode];
}
}
return validKey;
}
function normalizedKeyForEvent(keyEvent) {
// fall back from .key, to .keyIdentifier, to .keyCode, and then to
// .detail.key to support artificial keyboard events
return transformKey(keyEvent.key) ||
transformKeyIdentifier(keyEvent.keyIdentifier) ||
transformKeyCode(keyEvent.keyCode) ||
transformKey(keyEvent.detail.key) || '';
}
function keyComboMatchesEvent(keyCombo, keyEvent) {
return normalizedKeyForEvent(keyEvent) === keyCombo.key &&
!!keyEvent.shiftKey === !!keyCombo.shiftKey &&
!!keyEvent.ctrlKey === !!keyCombo.ctrlKey &&
!!keyEvent.altKey === !!keyCombo.altKey &&
!!keyEvent.metaKey === !!keyCombo.metaKey;
}
function parseKeyComboString(keyComboString) {
return keyComboString.split('+').reduce(function(parsedKeyCombo, keyComboPart) {
var eventParts = keyComboPart.split(':');
var keyName = eventParts[0];
var event = eventParts[1];
if (keyName in MODIFIER_KEYS) {
parsedKeyCombo[MODIFIER_KEYS[keyName]] = true;
} else {
parsedKeyCombo.key = keyName;
parsedKeyCombo.event = event || 'keydown';
}
return parsedKeyCombo;
}, {
combo: keyComboString.split(':').shift()
});
}
function parseEventString(eventString) {
return eventString.split(' ').map(function(keyComboString) {
return parseKeyComboString(keyComboString);
});
}
/**
* `Polymer.IronA11yKeysBehavior` provides a normalized interface for processing
* keyboard commands that pertain to [WAI-ARIA best practices](http://www.w3.org/TR/wai-aria-practices/#kbd_general_binding).
* The element takes care of browser differences with respect to Keyboard events
* and uses an expressive syntax to filter key presses.
*
* Use the `keyBindings` prototype property to express what combination of keys
* will trigger the event to fire.
*
* Use the `key-event-target` attribute to set up event handlers on a specific
* node.
* The `keys-pressed` event will fire when one of the key combinations set with the
* `keys` property is pressed.
*
* @demo demo/index.html
* @polymerBehavior IronA11yKeysBehavior
*/
Polymer.IronA11yKeysBehavior = {
properties: {
/**
* The HTMLElement that will be firing relevant KeyboardEvents.
*/
keyEventTarget: {
type: Object,
value: function() {
return this;
}
},
_boundKeyHandlers: {
type: Array,
value: function() {
return [];
}
},
// We use this due to a limitation in IE10 where instances will have
// own properties of everything on the "prototype".
_imperativeKeyBindings: {
type: Object,
value: function() {
return {};
}
}
},
observers: [
'_resetKeyEventListeners(keyEventTarget, _boundKeyHandlers)'
],
keyBindings: {},
registered: function() {
this._prepKeyBindings();
},
attached: function() {
this._listenKeyEventListeners();
},
detached: function() {
this._unlistenKeyEventListeners();
},
/**
* Can be used to imperatively add a key binding to the implementing
* element. This is the imperative equivalent of declaring a keybinding
* in the `keyBindings` prototype property.
*/
addOwnKeyBinding: function(eventString, handlerName) {
this._imperativeKeyBindings[eventString] = handlerName;
this._prepKeyBindings();
this._resetKeyEventListeners();
},
/**
* When called, will remove all imperatively-added key bindings.
*/
removeOwnKeyBindings: function() {
this._imperativeKeyBindings = {};
this._prepKeyBindings();
this._resetKeyEventListeners();
},
keyboardEventMatchesKeys: function(event, eventString) {
var keyCombos = parseEventString(eventString);
var index;
for (index = 0; index < keyCombos.length; ++index) {
if (keyComboMatchesEvent(keyCombos[index], event)) {
return true;
}
}
return false;
},
_collectKeyBindings: function() {
var keyBindings = this.behaviors.map(function(behavior) {
return behavior.keyBindings;
});
if (keyBindings.indexOf(this.keyBindings) === -1) {
keyBindings.push(this.keyBindings);
}
return keyBindings;
},
_prepKeyBindings: function() {
this._keyBindings = {};
this._collectKeyBindings().forEach(function(keyBindings) {
for (var eventString in keyBindings) {
this._addKeyBinding(eventString, keyBindings[eventString]);
}
}, this);
for (var eventString in this._imperativeKeyBindings) {
this._addKeyBinding(eventString, this._imperativeKeyBindings[eventString]);
}
},
_addKeyBinding: function(eventString, handlerName) {
parseEventString(eventString).forEach(function(keyCombo) {
this._keyBindings[keyCombo.event] =
this._keyBindings[keyCombo.event] || [];
this._keyBindings[keyCombo.event].push([
keyCombo,
handlerName
]);
}, this);
},
_resetKeyEventListeners: function() {
this._unlistenKeyEventListeners();
if (this.isAttached) {
this._listenKeyEventListeners();
}
},
_listenKeyEventListeners: function() {
Object.keys(this._keyBindings).forEach(function(eventName) {
var keyBindings = this._keyBindings[eventName];
var boundKeyHandler = this._onKeyBindingEvent.bind(this, keyBindings);
this._boundKeyHandlers.push([this.keyEventTarget, eventName, boundKeyHandler]);
this.keyEventTarget.addEventListener(eventName, boundKeyHandler);
}, this);
},
_unlistenKeyEventListeners: function() {
var keyHandlerTuple;
var keyEventTarget;
var eventName;
var boundKeyHandler;
while (this._boundKeyHandlers.length) {
// My kingdom for block-scope binding and destructuring assignment..
keyHandlerTuple = this._boundKeyHandlers.pop();
keyEventTarget = keyHandlerTuple[0];
eventName = keyHandlerTuple[1];
boundKeyHandler = keyHandlerTuple[2];
keyEventTarget.removeEventListener(eventName, boundKeyHandler);
}
},
_onKeyBindingEvent: function(keyBindings, event) {
keyBindings.forEach(function(keyBinding) {
var keyCombo = keyBinding[0];
var handlerName = keyBinding[1];
if (!event.defaultPrevented && keyComboMatchesEvent(keyCombo, event)) {
this._triggerKeyHandler(keyCombo, handlerName, event);
}
}, this);
},
_triggerKeyHandler: function(keyCombo, handlerName, keyboardEvent) {
var detail = Object.create(keyCombo);
detail.keyboardEvent = keyboardEvent;
this[handlerName].call(this, new CustomEvent(keyCombo.event, {
detail: detail
}));
}
};
})();
| {'content_hash': 'c602d6411fc2a63ef72a581bafd076dc', 'timestamp': '', 'source': 'github', 'line_count': 408, 'max_line_length': 129, 'avg_line_length': 28.970588235294116, 'alnum_prop': 0.5589678510998308, 'repo_name': 'hgl888/chromium-crosswalk', 'id': 'c9da8f436351c985d608ce6cebd5822d619af617', 'size': '11820', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'third_party/polymer/v1_0/components-chromium/iron-a11y-keys-behavior/iron-a11y-keys-behavior-extracted.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '37073'}, {'name': 'Batchfile', 'bytes': '8451'}, {'name': 'C', 'bytes': '9404886'}, {'name': 'C++', 'bytes': '240720094'}, {'name': 'CSS', 'bytes': '938746'}, {'name': 'DM', 'bytes': '60'}, {'name': 'Groff', 'bytes': '2494'}, {'name': 'HTML', 'bytes': '27258863'}, {'name': 'Java', 'bytes': '14579982'}, {'name': 'JavaScript', 'bytes': '20509171'}, {'name': 'Makefile', 'bytes': '70992'}, {'name': 'Objective-C', 'bytes': '1956196'}, {'name': 'Objective-C++', 'bytes': '9967587'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'PLpgSQL', 'bytes': '178732'}, {'name': 'Perl', 'bytes': '63937'}, {'name': 'Protocol Buffer', 'bytes': '480579'}, {'name': 'Python', 'bytes': '8518320'}, {'name': 'Shell', 'bytes': '482077'}, {'name': 'Standard ML', 'bytes': '5034'}, {'name': 'XSLT', 'bytes': '418'}, {'name': 'nesC', 'bytes': '18347'}]} |
#ifndef _LMDB_H_
#define _LMDB_H_
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Unix permissions for creating files, or dummy definition for Windows */
#ifdef _MSC_VER
typedef int mdb_mode_t;
#else
typedef mode_t mdb_mode_t;
#endif
/** An abstraction for a file handle.
* On POSIX systems file handles are small integers. On Windows
* they're opaque pointers.
*/
#ifdef _WIN32
typedef void *mdb_filehandle_t;
#else
typedef int mdb_filehandle_t;
#endif
/** @defgroup mdb MDB API
* @{
* @brief OpenLDAP Lightning Memory-Mapped Database Manager
*/
/** @defgroup Version Version Macros
* @{
*/
/** Library major version */
#define MDB_VERSION_MAJOR 0
/** Library minor version */
#define MDB_VERSION_MINOR 9
/** Library patch version */
#define MDB_VERSION_PATCH 11
/** Combine args a,b,c into a single integer for easy version comparisons */
#define MDB_VERINT(a,b,c) (((a) << 24) | ((b) << 16) | (c))
/** The full library version as a single integer */
#define MDB_VERSION_FULL \
MDB_VERINT(MDB_VERSION_MAJOR,MDB_VERSION_MINOR,MDB_VERSION_PATCH)
/** The release date of this library version */
#define MDB_VERSION_DATE "January 15, 2014"
/** A stringifier for the version info */
#define MDB_VERSTR(a,b,c,d) "MDB " #a "." #b "." #c ": (" d ")"
/** A helper for the stringifier macro */
#define MDB_VERFOO(a,b,c,d) MDB_VERSTR(a,b,c,d)
/** The full library version as a C string */
#define MDB_VERSION_STRING \
MDB_VERFOO(MDB_VERSION_MAJOR,MDB_VERSION_MINOR,MDB_VERSION_PATCH,MDB_VERSION_DATE)
/** @} */
/** @brief Opaque structure for a database environment.
*
* A DB environment supports multiple databases, all residing in the same
* shared-memory map.
*/
typedef struct MDB_env MDB_env;
/** @brief Opaque structure for a transaction handle.
*
* All database operations require a transaction handle. Transactions may be
* read-only or read-write.
*/
typedef struct MDB_txn MDB_txn;
/** @brief A handle for an individual database in the DB environment. */
typedef unsigned int MDB_dbi;
/** @brief Opaque structure for navigating through a database */
typedef struct MDB_cursor MDB_cursor;
/** @brief Generic structure used for passing keys and data in and out
* of the database.
*
* Values returned from the database are valid only until a subsequent
* update operation, or the end of the transaction. Do not modify or
* free them, they commonly point into the database itself.
*
* Key sizes must be between 1 and #mdb_env_get_maxkeysize() inclusive.
* The same applies to data sizes in databases with the #MDB_DUPSORT flag.
* Other data items can in theory be from 0 to 0xffffffff bytes long.
*/
typedef struct MDB_val {
size_t mv_size; /**< size of the data item */
void *mv_data; /**< address of the data item */
} MDB_val;
/** @brief A callback function used to compare two keys in a database */
typedef int (MDB_cmp_func)(const MDB_val *a, const MDB_val *b);
/** @brief A callback function used to relocate a position-dependent data item
* in a fixed-address database.
*
* The \b newptr gives the item's desired address in
* the memory map, and \b oldptr gives its previous address. The item's actual
* data resides at the address in \b item. This callback is expected to walk
* through the fields of the record in \b item and modify any
* values based at the \b oldptr address to be relative to the \b newptr address.
* @param[in,out] item The item that is to be relocated.
* @param[in] oldptr The previous address.
* @param[in] newptr The new address to relocate to.
* @param[in] relctx An application-provided context, set by #mdb_set_relctx().
* @todo This feature is currently unimplemented.
*/
typedef void (MDB_rel_func)(MDB_val *item, void *oldptr, void *newptr, void *relctx);
/** @defgroup mdb_env Environment Flags
* @{
*/
/** mmap at a fixed address (experimental) */
#define MDB_FIXEDMAP 0x01
/** no environment directory */
#define MDB_NOSUBDIR 0x4000
/** don't fsync after commit */
#define MDB_NOSYNC 0x10000
/** read only */
#define MDB_RDONLY 0x20000
/** don't fsync metapage after commit */
#define MDB_NOMETASYNC 0x40000
/** use writable mmap */
#define MDB_WRITEMAP 0x80000
/** use asynchronous msync when #MDB_WRITEMAP is used */
#define MDB_MAPASYNC 0x100000
/** tie reader locktable slots to #MDB_txn objects instead of to threads */
#define MDB_NOTLS 0x200000
/** don't do any locking, caller must manage their own locks */
#define MDB_NOLOCK 0x400000
/** don't do readahead (no effect on Windows) */
#define MDB_NORDAHEAD 0x800000
/** don't initialize malloc'd memory before writing to datafile */
#define MDB_NOMEMINIT 0x1000000
/** @} */
/** @defgroup mdb_dbi_open Database Flags
* @{
*/
/** use reverse string keys */
#define MDB_REVERSEKEY 0x02
/** use sorted duplicates */
#define MDB_DUPSORT 0x04
/** numeric keys in native byte order.
* The keys must all be of the same size. */
#define MDB_INTEGERKEY 0x08
/** with #MDB_DUPSORT, sorted dup items have fixed size */
#define MDB_DUPFIXED 0x10
/** with #MDB_DUPSORT, dups are numeric in native byte order */
#define MDB_INTEGERDUP 0x20
/** with #MDB_DUPSORT, use reverse string dups */
#define MDB_REVERSEDUP 0x40
/** create DB if not already existing */
#define MDB_CREATE 0x40000
/** @} */
/** @defgroup mdb_put Write Flags
* @{
*/
/** For put: Don't write if the key already exists. */
#define MDB_NOOVERWRITE 0x10
/** Only for #MDB_DUPSORT<br>
* For put: don't write if the key and data pair already exist.<br>
* For mdb_cursor_del: remove all duplicate data items.
*/
#define MDB_NODUPDATA 0x20
/** For mdb_cursor_put: overwrite the current key/data pair */
#define MDB_CURRENT 0x40
/** For put: Just reserve space for data, don't copy it. Return a
* pointer to the reserved space.
*/
#define MDB_RESERVE 0x10000
/** Data is being appended, don't split full pages. */
#define MDB_APPEND 0x20000
/** Duplicate data is being appended, don't split full pages. */
#define MDB_APPENDDUP 0x40000
/** Store multiple data items in one call. Only for #MDB_DUPFIXED. */
#define MDB_MULTIPLE 0x80000
/* @} */
/** @brief Cursor Get operations.
*
* This is the set of all operations for retrieving data
* using a cursor.
*/
typedef enum MDB_cursor_op {
MDB_FIRST, /**< Position at first key/data item */
MDB_FIRST_DUP, /**< Position at first data item of current key.
Only for #MDB_DUPSORT */
MDB_GET_BOTH, /**< Position at key/data pair. Only for #MDB_DUPSORT */
MDB_GET_BOTH_RANGE, /**< position at key, nearest data. Only for #MDB_DUPSORT */
MDB_GET_CURRENT, /**< Return key/data at current cursor position */
MDB_GET_MULTIPLE, /**< Return all the duplicate data items at the current
cursor position. Only for #MDB_DUPFIXED */
MDB_LAST, /**< Position at last key/data item */
MDB_LAST_DUP, /**< Position at last data item of current key.
Only for #MDB_DUPSORT */
MDB_NEXT, /**< Position at next data item */
MDB_NEXT_DUP, /**< Position at next data item of current key.
Only for #MDB_DUPSORT */
MDB_NEXT_MULTIPLE, /**< Return all duplicate data items at the next
cursor position. Only for #MDB_DUPFIXED */
MDB_NEXT_NODUP, /**< Position at first data item of next key */
MDB_PREV, /**< Position at previous data item */
MDB_PREV_DUP, /**< Position at previous data item of current key.
Only for #MDB_DUPSORT */
MDB_PREV_NODUP, /**< Position at last data item of previous key */
MDB_SET, /**< Position at specified key */
MDB_SET_KEY, /**< Position at specified key, return key + data */
MDB_SET_RANGE /**< Position at first key greater than or equal to specified key. */
} MDB_cursor_op;
/** @defgroup errors Return Codes
*
* BerkeleyDB uses -30800 to -30999, we'll go under them
* @{
*/
/** Successful result */
#define MDB_SUCCESS 0
/** key/data pair already exists */
#define MDB_KEYEXIST (-30799)
/** key/data pair not found (EOF) */
#define MDB_NOTFOUND (-30798)
/** Requested page not found - this usually indicates corruption */
#define MDB_PAGE_NOTFOUND (-30797)
/** Located page was wrong type */
#define MDB_CORRUPTED (-30796)
/** Update of meta page failed, probably I/O error */
#define MDB_PANIC (-30795)
/** Environment version mismatch */
#define MDB_VERSION_MISMATCH (-30794)
/** File is not a valid MDB file */
#define MDB_INVALID (-30793)
/** Environment mapsize reached */
#define MDB_MAP_FULL (-30792)
/** Environment maxdbs reached */
#define MDB_DBS_FULL (-30791)
/** Environment maxreaders reached */
#define MDB_READERS_FULL (-30790)
/** Too many TLS keys in use - Windows only */
#define MDB_TLS_FULL (-30789)
/** Txn has too many dirty pages */
#define MDB_TXN_FULL (-30788)
/** Cursor stack too deep - internal error */
#define MDB_CURSOR_FULL (-30787)
/** Page has not enough space - internal error */
#define MDB_PAGE_FULL (-30786)
/** Database contents grew beyond environment mapsize */
#define MDB_MAP_RESIZED (-30785)
/** MDB_INCOMPATIBLE: Operation and DB incompatible, or DB flags changed */
#define MDB_INCOMPATIBLE (-30784)
/** Invalid reuse of reader locktable slot */
#define MDB_BAD_RSLOT (-30783)
/** Transaction cannot recover - it must be aborted */
#define MDB_BAD_TXN (-30782)
/** Too big key/data, key is empty, or wrong DUPFIXED size */
#define MDB_BAD_VALSIZE (-30781)
#define MDB_LAST_ERRCODE MDB_BAD_VALSIZE
/** @} */
/** @brief Statistics for a database in the environment */
typedef struct MDB_stat {
unsigned int ms_psize; /**< Size of a database page.
This is currently the same for all databases. */
unsigned int ms_depth; /**< Depth (height) of the B-tree */
size_t ms_branch_pages; /**< Number of internal (non-leaf) pages */
size_t ms_leaf_pages; /**< Number of leaf pages */
size_t ms_overflow_pages; /**< Number of overflow pages */
size_t ms_entries; /**< Number of data items */
} MDB_stat;
/** @brief Information about the environment */
typedef struct MDB_envinfo {
void *me_mapaddr; /**< Address of map, if fixed */
size_t me_mapsize; /**< Size of the data memory map */
size_t me_last_pgno; /**< ID of the last used page */
size_t me_last_txnid; /**< ID of the last committed transaction */
unsigned int me_maxreaders; /**< max reader slots in the environment */
unsigned int me_numreaders; /**< max reader slots used in the environment */
} MDB_envinfo;
/** @brief Return the mdb library version information.
*
* @param[out] major if non-NULL, the library major version number is copied here
* @param[out] minor if non-NULL, the library minor version number is copied here
* @param[out] patch if non-NULL, the library patch version number is copied here
* @retval "version string" The library version as a string
*/
char *mdb_version(int *major, int *minor, int *patch);
/** @brief Return a string describing a given error code.
*
* This function is a superset of the ANSI C X3.159-1989 (ANSI C) strerror(3)
* function. If the error code is greater than or equal to 0, then the string
* returned by the system function strerror(3) is returned. If the error code
* is less than 0, an error string corresponding to the MDB library error is
* returned. See @ref errors for a list of MDB-specific error codes.
* @param[in] err The error code
* @retval "error message" The description of the error
*/
char *mdb_strerror(int err);
/** @brief Create an MDB environment handle.
*
* This function allocates memory for a #MDB_env structure. To release
* the allocated memory and discard the handle, call #mdb_env_close().
* Before the handle may be used, it must be opened using #mdb_env_open().
* Various other options may also need to be set before opening the handle,
* e.g. #mdb_env_set_mapsize(), #mdb_env_set_maxreaders(), #mdb_env_set_maxdbs(),
* depending on usage requirements.
* @param[out] env The address where the new handle will be stored
* @return A non-zero error value on failure and 0 on success.
*/
int mdb_env_create(MDB_env **env);
/** @brief Open an environment handle.
*
* If this function fails, #mdb_env_close() must be called to discard the #MDB_env handle.
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[in] path The directory in which the database files reside. This
* directory must already exist and be writable.
* @param[in] flags Special options for this environment. This parameter
* must be set to 0 or by bitwise OR'ing together one or more of the
* values described here.
* Flags set by mdb_env_set_flags() are also used.
* <ul>
* <li>#MDB_FIXEDMAP
* use a fixed address for the mmap region. This flag must be specified
* when creating the environment, and is stored persistently in the environment.
* If successful, the memory map will always reside at the same virtual address
* and pointers used to reference data items in the database will be constant
* across multiple invocations. This option may not always work, depending on
* how the operating system has allocated memory to shared libraries and other uses.
* The feature is highly experimental.
* <li>#MDB_NOSUBDIR
* By default, MDB creates its environment in a directory whose
* pathname is given in \b path, and creates its data and lock files
* under that directory. With this option, \b path is used as-is for
* the database main data file. The database lock file is the \b path
* with "-lock" appended.
* <li>#MDB_RDONLY
* Open the environment in read-only mode. No write operations will be
* allowed. MDB will still modify the lock file - except on read-only
* filesystems, where MDB does not use locks.
* <li>#MDB_WRITEMAP
* Use a writeable memory map unless MDB_RDONLY is set. This is faster
* and uses fewer mallocs, but loses protection from application bugs
* like wild pointer writes and other bad updates into the database.
* Incompatible with nested transactions.
* Processes with and without MDB_WRITEMAP on the same environment do
* not cooperate well.
* <li>#MDB_NOMETASYNC
* Flush system buffers to disk only once per transaction, omit the
* metadata flush. Defer that until the system flushes files to disk,
* or next non-MDB_RDONLY commit or #mdb_env_sync(). This optimization
* maintains database integrity, but a system crash may undo the last
* committed transaction. I.e. it preserves the ACI (atomicity,
* consistency, isolation) but not D (durability) database property.
* This flag may be changed at any time using #mdb_env_set_flags().
* <li>#MDB_NOSYNC
* Don't flush system buffers to disk when committing a transaction.
* This optimization means a system crash can corrupt the database or
* lose the last transactions if buffers are not yet flushed to disk.
* The risk is governed by how often the system flushes dirty buffers
* to disk and how often #mdb_env_sync() is called. However, if the
* filesystem preserves write order and the #MDB_WRITEMAP flag is not
* used, transactions exhibit ACI (atomicity, consistency, isolation)
* properties and only lose D (durability). I.e. database integrity
* is maintained, but a system crash may undo the final transactions.
* Note that (#MDB_NOSYNC | #MDB_WRITEMAP) leaves the system with no
* hint for when to write transactions to disk, unless #mdb_env_sync()
* is called. (#MDB_MAPASYNC | #MDB_WRITEMAP) may be preferable.
* This flag may be changed at any time using #mdb_env_set_flags().
* <li>#MDB_MAPASYNC
* When using #MDB_WRITEMAP, use asynchronous flushes to disk.
* As with #MDB_NOSYNC, a system crash can then corrupt the
* database or lose the last transactions. Calling #mdb_env_sync()
* ensures on-disk database integrity until next commit.
* This flag may be changed at any time using #mdb_env_set_flags().
* <li>#MDB_NOTLS
* Don't use Thread-Local Storage. Tie reader locktable slots to
* #MDB_txn objects instead of to threads. I.e. #mdb_txn_reset() keeps
* the slot reseved for the #MDB_txn object. A thread may use parallel
* read-only transactions. A read-only transaction may span threads if
* the user synchronizes its use. Applications that multiplex many
* user threads over individual OS threads need this option. Such an
* application must also serialize the write transactions in an OS
* thread, since MDB's write locking is unaware of the user threads.
* <li>#MDB_NOLOCK
* Don't do any locking. If concurrent access is anticipated, the
* caller must manage all concurrency itself. For proper operation
* the caller must enforce single-writer semantics, and must ensure
* that no readers are using old transactions while a writer is
* active. The simplest approach is to use an exclusive lock so that
* no readers may be active at all when a writer begins.
* <li>#MDB_NORDAHEAD
* Turn off readahead. Most operating systems perform readahead on
* read requests by default. This option turns it off if the OS
* supports it. Turning it off may help random read performance
* when the DB is larger than RAM and system RAM is full.
* The option is not implemented on Windows.
* <li>#MDB_NOMEMINIT
* Don't initialize malloc'd memory before writing to unused spaces
* in the data file. By default, memory for pages written to the data
* file is obtained using malloc. While these pages may be reused in
* subsequent transactions, freshly malloc'd pages will be initialized
* to zeroes before use. This avoids persisting leftover data from other
* code (that used the heap and subsequently freed the memory) into the
* data file. Note that many other system libraries may allocate
* and free memory from the heap for arbitrary uses. E.g., stdio may
* use the heap for file I/O buffers. This initialization step has a
* modest performance cost so some applications may want to disable
* it using this flag. This option can be a problem for applications
* which handle sensitive data like passwords, and it makes memory
* checkers like Valgrind noisy. This flag is not needed with #MDB_WRITEMAP,
* which writes directly to the mmap instead of using malloc for pages. The
* initialization is also skipped if #MDB_RESERVE is used; the
* caller is expected to overwrite all of the memory that was
* reserved in that case.
* This flag may be changed at any time using #mdb_env_set_flags().
* </ul>
* @param[in] mode The UNIX permissions to set on created files. This parameter
* is ignored on Windows.
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>#MDB_VERSION_MISMATCH - the version of the MDB library doesn't match the
* version that created the database environment.
* <li>#MDB_INVALID - the environment file headers are corrupted.
* <li>ENOENT - the directory specified by the path parameter doesn't exist.
* <li>EACCES - the user didn't have permission to access the environment files.
* <li>EAGAIN - the environment was locked by another process.
* </ul>
*/
int mdb_env_open(MDB_env *env, const char *path, unsigned int flags, mdb_mode_t mode);
/** @brief Copy an MDB environment to the specified path.
*
* This function may be used to make a backup of an existing environment.
* No lockfile is created, since it gets recreated at need.
* @note This call can trigger significant file size growth if run in
* parallel with write transactions, because it employs a read-only
* transaction. See long-lived transactions under @ref caveats_sec.
* @param[in] env An environment handle returned by #mdb_env_create(). It
* must have already been opened successfully.
* @param[in] path The directory in which the copy will reside. This
* directory must already exist and be writable but must otherwise be
* empty.
* @return A non-zero error value on failure and 0 on success.
*/
int mdb_env_copy(MDB_env *env, const char *path);
/** @brief Copy an MDB environment to the specified file descriptor.
*
* This function may be used to make a backup of an existing environment.
* No lockfile is created, since it gets recreated at need.
* @note This call can trigger significant file size growth if run in
* parallel with write transactions, because it employs a read-only
* transaction. See long-lived transactions under @ref caveats_sec.
* @param[in] env An environment handle returned by #mdb_env_create(). It
* must have already been opened successfully.
* @param[in] fd The filedescriptor to write the copy to. It must
* have already been opened for Write access.
* @return A non-zero error value on failure and 0 on success.
*/
int mdb_env_copyfd(MDB_env *env, mdb_filehandle_t fd);
/** @brief Return statistics about the MDB environment.
*
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[out] stat The address of an #MDB_stat structure
* where the statistics will be copied
*/
int mdb_env_stat(MDB_env *env, MDB_stat *stat);
/** @brief Return information about the MDB environment.
*
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[out] stat The address of an #MDB_envinfo structure
* where the information will be copied
*/
int mdb_env_info(MDB_env *env, MDB_envinfo *stat);
/** @brief Flush the data buffers to disk.
*
* Data is always written to disk when #mdb_txn_commit() is called,
* but the operating system may keep it buffered. MDB always flushes
* the OS buffers upon commit as well, unless the environment was
* opened with #MDB_NOSYNC or in part #MDB_NOMETASYNC.
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[in] force If non-zero, force a synchronous flush. Otherwise
* if the environment has the #MDB_NOSYNC flag set the flushes
* will be omitted, and with #MDB_MAPASYNC they will be asynchronous.
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* <li>EIO - an error occurred during synchronization.
* </ul>
*/
int mdb_env_sync(MDB_env *env, int force);
/** @brief Close the environment and release the memory map.
*
* Only a single thread may call this function. All transactions, databases,
* and cursors must already be closed before calling this function. Attempts to
* use any such handles after calling this function will cause a SIGSEGV.
* The environment handle will be freed and must not be used again after this call.
* @param[in] env An environment handle returned by #mdb_env_create()
*/
void mdb_env_close(MDB_env *env);
/** @brief Set environment flags.
*
* This may be used to set some flags in addition to those from
* #mdb_env_open(), or to unset these flags. If several threads
* change the flags at the same time, the result is undefined.
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[in] flags The flags to change, bitwise OR'ed together
* @param[in] onoff A non-zero value sets the flags, zero clears them.
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_env_set_flags(MDB_env *env, unsigned int flags, int onoff);
/** @brief Get environment flags.
*
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[out] flags The address of an integer to store the flags
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_env_get_flags(MDB_env *env, unsigned int *flags);
/** @brief Return the path that was used in #mdb_env_open().
*
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[out] path Address of a string pointer to contain the path. This
* is the actual string in the environment, not a copy. It should not be
* altered in any way.
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_env_get_path(MDB_env *env, const char **path);
/** @brief Return the filedescriptor for the given environment.
*
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[out] fd Address of a mdb_filehandle_t to contain the descriptor.
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_env_get_fd(MDB_env *env, mdb_filehandle_t *fd);
/** @brief Set the size of the memory map to use for this environment.
*
* The size should be a multiple of the OS page size. The default is
* 10485760 bytes. The size of the memory map is also the maximum size
* of the database. The value should be chosen as large as possible,
* to accommodate future growth of the database.
* This function should be called after #mdb_env_create() and before #mdb_env_open().
* It may be called at later times if no transactions are active in
* this process. Note that the library does not check for this condition,
* the caller must ensure it explicitly.
*
* If the mapsize is changed by another process, #mdb_txn_begin() will
* return #MDB_MAP_RESIZED. This function may be called with a size
* of zero to adopt the new size.
*
* Any attempt to set a size smaller than the space already consumed
* by the environment will be silently changed to the current size of the used space.
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[in] size The size in bytes
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified, or the environment has
* an active write transaction.
* </ul>
*/
int mdb_env_set_mapsize(MDB_env *env, size_t size);
/** @brief Set the maximum number of threads/reader slots for the environment.
*
* This defines the number of slots in the lock table that is used to track readers in the
* the environment. The default is 126.
* Starting a read-only transaction normally ties a lock table slot to the
* current thread until the environment closes or the thread exits. If
* MDB_NOTLS is in use, #mdb_txn_begin() instead ties the slot to the
* MDB_txn object until it or the #MDB_env object is destroyed.
* This function may only be called after #mdb_env_create() and before #mdb_env_open().
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[in] readers The maximum number of reader lock table slots
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified, or the environment is already open.
* </ul>
*/
int mdb_env_set_maxreaders(MDB_env *env, unsigned int readers);
/** @brief Get the maximum number of threads/reader slots for the environment.
*
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[out] readers Address of an integer to store the number of readers
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_env_get_maxreaders(MDB_env *env, unsigned int *readers);
/** @brief Set the maximum number of named databases for the environment.
*
* This function is only needed if multiple databases will be used in the
* environment. Simpler applications that use the environment as a single
* unnamed database can ignore this option.
* This function may only be called after #mdb_env_create() and before #mdb_env_open().
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[in] dbs The maximum number of databases
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified, or the environment is already open.
* </ul>
*/
int mdb_env_set_maxdbs(MDB_env *env, MDB_dbi dbs);
/** @brief Get the maximum size of keys and #MDB_DUPSORT data we can write.
*
* Depends on the compile-time constant #MDB_MAXKEYSIZE. Default 511.
* See @ref MDB_val.
* @param[in] env An environment handle returned by #mdb_env_create()
* @return The maximum size of a key we can write
*/
int mdb_env_get_maxkeysize(MDB_env *env);
/** @brief Set application information associated with the #MDB_env.
*
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[in] ctx An arbitrary pointer for whatever the application needs.
* @return A non-zero error value on failure and 0 on success.
*/
int mdb_env_set_userctx(MDB_env *env, void *ctx);
/** @brief Get the application information associated with the #MDB_env.
*
* @param[in] env An environment handle returned by #mdb_env_create()
* @return The pointer set by #mdb_env_set_userctx().
*/
void *mdb_env_get_userctx(MDB_env *env);
/** @brief A callback function for most MDB assert() failures,
* called before printing the message and aborting.
*
* @param[in] env An environment handle returned by #mdb_env_create().
* @param[in] msg The assertion message, not including newline.
*/
typedef void MDB_assert_func(MDB_env *env, const char *msg);
/** Set or reset the assert() callback of the environment.
* Disabled if liblmdb is buillt with NDEBUG.
* @note This hack should become obsolete as lmdb's error handling matures.
* @param[in] env An environment handle returned by #mdb_env_create().
* @param[in] func An #MDB_assert_func function, or 0.
* @return A non-zero error value on failure and 0 on success.
*/
int mdb_env_set_assert(MDB_env *env, MDB_assert_func *func);
/** @brief Create a transaction for use with the environment.
*
* The transaction handle may be discarded using #mdb_txn_abort() or #mdb_txn_commit().
* @note A transaction and its cursors must only be used by a single
* thread, and a thread may only have a single transaction at a time.
* If #MDB_NOTLS is in use, this does not apply to read-only transactions.
* @note Cursors may not span transactions.
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[in] parent If this parameter is non-NULL, the new transaction
* will be a nested transaction, with the transaction indicated by \b parent
* as its parent. Transactions may be nested to any level. A parent
* transaction and its cursors may not issue any other operations than
* mdb_txn_commit and mdb_txn_abort while it has active child transactions.
* @param[in] flags Special options for this transaction. This parameter
* must be set to 0 or by bitwise OR'ing together one or more of the
* values described here.
* <ul>
* <li>#MDB_RDONLY
* This transaction will not perform any write operations.
* </ul>
* @param[out] txn Address where the new #MDB_txn handle will be stored
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>#MDB_PANIC - a fatal error occurred earlier and the environment
* must be shut down.
* <li>#MDB_MAP_RESIZED - another process wrote data beyond this MDB_env's
* mapsize and this environment's map must be resized as well.
* See #mdb_env_set_mapsize().
* <li>#MDB_READERS_FULL - a read-only transaction was requested and
* the reader lock table is full. See #mdb_env_set_maxreaders().
* <li>ENOMEM - out of memory.
* </ul>
*/
int mdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **txn);
/** @brief Returns the transaction's #MDB_env
*
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
*/
MDB_env *mdb_txn_env(MDB_txn *txn);
/** @brief Commit all the operations of a transaction into the database.
*
* The transaction handle is freed. It and its cursors must not be used
* again after this call, except with #mdb_cursor_renew().
* @note Earlier documentation incorrectly said all cursors would be freed.
* Only write-transactions free cursors.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* <li>ENOSPC - no more disk space.
* <li>EIO - a low-level I/O error occurred while writing.
* <li>ENOMEM - out of memory.
* </ul>
*/
int mdb_txn_commit(MDB_txn *txn);
/** @brief Abandon all the operations of the transaction instead of saving them.
*
* The transaction handle is freed. It and its cursors must not be used
* again after this call, except with #mdb_cursor_renew().
* @note Earlier documentation incorrectly said all cursors would be freed.
* Only write-transactions free cursors.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
*/
void mdb_txn_abort(MDB_txn *txn);
/** @brief Reset a read-only transaction.
*
* Abort the transaction like #mdb_txn_abort(), but keep the transaction
* handle. #mdb_txn_renew() may reuse the handle. This saves allocation
* overhead if the process will start a new read-only transaction soon,
* and also locking overhead if #MDB_NOTLS is in use. The reader table
* lock is released, but the table slot stays tied to its thread or
* #MDB_txn. Use mdb_txn_abort() to discard a reset handle, and to free
* its lock table slot if MDB_NOTLS is in use.
* Cursors opened within the transaction must not be used
* again after this call, except with #mdb_cursor_renew().
* Reader locks generally don't interfere with writers, but they keep old
* versions of database pages allocated. Thus they prevent the old pages
* from being reused when writers commit new data, and so under heavy load
* the database size may grow much more rapidly than otherwise.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
*/
void mdb_txn_reset(MDB_txn *txn);
/** @brief Renew a read-only transaction.
*
* This acquires a new reader lock for a transaction handle that had been
* released by #mdb_txn_reset(). It must be called before a reset transaction
* may be used again.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>#MDB_PANIC - a fatal error occurred earlier and the environment
* must be shut down.
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_txn_renew(MDB_txn *txn);
/** Compat with version <= 0.9.4, avoid clash with libmdb from MDB Tools project */
#define mdb_open(txn,name,flags,dbi) mdb_dbi_open(txn,name,flags,dbi)
/** Compat with version <= 0.9.4, avoid clash with libmdb from MDB Tools project */
#define mdb_close(env,dbi) mdb_dbi_close(env,dbi)
/** @brief Open a database in the environment.
*
* A database handle denotes the name and parameters of a database,
* independently of whether such a database exists.
* The database handle may be discarded by calling #mdb_dbi_close().
* The old database handle is returned if the database was already open.
* The handle must only be closed once.
* The database handle will be private to the current transaction until
* the transaction is successfully committed. If the transaction is
* aborted the handle will be closed automatically.
* After a successful commit the
* handle will reside in the shared environment, and may be used
* by other transactions. This function must not be called from
* multiple concurrent transactions. A transaction that uses this function
* must finish (either commit or abort) before any other transaction may
* use this function.
*
* To use named databases (with name != NULL), #mdb_env_set_maxdbs()
* must be called before opening the environment.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] name The name of the database to open. If only a single
* database is needed in the environment, this value may be NULL.
* @param[in] flags Special options for this database. This parameter
* must be set to 0 or by bitwise OR'ing together one or more of the
* values described here.
* <ul>
* <li>#MDB_REVERSEKEY
* Keys are strings to be compared in reverse order, from the end
* of the strings to the beginning. By default, Keys are treated as strings and
* compared from beginning to end.
* <li>#MDB_DUPSORT
* Duplicate keys may be used in the database. (Or, from another perspective,
* keys may have multiple data items, stored in sorted order.) By default
* keys must be unique and may have only a single data item.
* <li>#MDB_INTEGERKEY
* Keys are binary integers in native byte order. Setting this option
* requires all keys to be the same size, typically sizeof(int)
* or sizeof(size_t).
* <li>#MDB_DUPFIXED
* This flag may only be used in combination with #MDB_DUPSORT. This option
* tells the library that the data items for this database are all the same
* size, which allows further optimizations in storage and retrieval. When
* all data items are the same size, the #MDB_GET_MULTIPLE and #MDB_NEXT_MULTIPLE
* cursor operations may be used to retrieve multiple items at once.
* <li>#MDB_INTEGERDUP
* This option specifies that duplicate data items are also integers, and
* should be sorted as such.
* <li>#MDB_REVERSEDUP
* This option specifies that duplicate data items should be compared as
* strings in reverse order.
* <li>#MDB_CREATE
* Create the named database if it doesn't exist. This option is not
* allowed in a read-only transaction or a read-only environment.
* </ul>
* @param[out] dbi Address where the new #MDB_dbi handle will be stored
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>#MDB_NOTFOUND - the specified database doesn't exist in the environment
* and #MDB_CREATE was not specified.
* <li>#MDB_DBS_FULL - too many databases have been opened. See #mdb_env_set_maxdbs().
* </ul>
*/
int mdb_dbi_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi);
/** @brief Retrieve statistics for a database.
*
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[out] stat The address of an #MDB_stat structure
* where the statistics will be copied
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *stat);
/** @brief Retrieve the DB flags for a database handle.
*
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[out] flags Address where the flags will be returned.
* @return A non-zero error value on failure and 0 on success.
*/
int mdb_dbi_flags(MDB_txn *txn, MDB_dbi dbi, unsigned int *flags);
/** @brief Close a database handle.
*
* This call is not mutex protected. Handles should only be closed by
* a single thread, and only if no other threads are going to reference
* the database handle or one of its cursors any further. Do not close
* a handle if an existing transaction has modified its database.
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
*/
void mdb_dbi_close(MDB_env *env, MDB_dbi dbi);
/** @brief Empty or delete+close a database.
*
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[in] del 0 to empty the DB, 1 to delete it from the
* environment and close the DB handle.
* @return A non-zero error value on failure and 0 on success.
*/
int mdb_drop(MDB_txn *txn, MDB_dbi dbi, int del);
/** @brief Set a custom key comparison function for a database.
*
* The comparison function is called whenever it is necessary to compare a
* key specified by the application with a key currently stored in the database.
* If no comparison function is specified, and no special key flags were specified
* with #mdb_dbi_open(), the keys are compared lexically, with shorter keys collating
* before longer keys.
* @warning This function must be called before any data access functions are used,
* otherwise data corruption may occur. The same comparison function must be used by every
* program accessing the database, every time the database is used.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[in] cmp A #MDB_cmp_func function
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_set_compare(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp);
/** @brief Set a custom data comparison function for a #MDB_DUPSORT database.
*
* This comparison function is called whenever it is necessary to compare a data
* item specified by the application with a data item currently stored in the database.
* This function only takes effect if the database was opened with the #MDB_DUPSORT
* flag.
* If no comparison function is specified, and no special key flags were specified
* with #mdb_dbi_open(), the data items are compared lexically, with shorter items collating
* before longer items.
* @warning This function must be called before any data access functions are used,
* otherwise data corruption may occur. The same comparison function must be used by every
* program accessing the database, every time the database is used.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[in] cmp A #MDB_cmp_func function
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_set_dupsort(MDB_txn *txn, MDB_dbi dbi, MDB_cmp_func *cmp);
/** @brief Set a relocation function for a #MDB_FIXEDMAP database.
*
* @todo The relocation function is called whenever it is necessary to move the data
* of an item to a different position in the database (e.g. through tree
* balancing operations, shifts as a result of adds or deletes, etc.). It is
* intended to allow address/position-dependent data items to be stored in
* a database in an environment opened with the #MDB_FIXEDMAP option.
* Currently the relocation feature is unimplemented and setting
* this function has no effect.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[in] rel A #MDB_rel_func function
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_set_relfunc(MDB_txn *txn, MDB_dbi dbi, MDB_rel_func *rel);
/** @brief Set a context pointer for a #MDB_FIXEDMAP database's relocation function.
*
* See #mdb_set_relfunc and #MDB_rel_func for more details.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[in] ctx An arbitrary pointer for whatever the application needs.
* It will be passed to the callback function set by #mdb_set_relfunc
* as its \b relctx parameter whenever the callback is invoked.
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_set_relctx(MDB_txn *txn, MDB_dbi dbi, void *ctx);
/** @brief Get items from a database.
*
* This function retrieves key/data pairs from the database. The address
* and length of the data associated with the specified \b key are returned
* in the structure to which \b data refers.
* If the database supports duplicate keys (#MDB_DUPSORT) then the
* first data item for the key will be returned. Retrieval of other
* items requires the use of #mdb_cursor_get().
*
* @note The memory pointed to by the returned values is owned by the
* database. The caller need not dispose of the memory, and may not
* modify it in any way. For values returned in a read-only transaction
* any modification attempts will cause a SIGSEGV.
* @note Values returned from the database are valid only until a
* subsequent update operation, or the end of the transaction.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[in] key The key to search for in the database
* @param[out] data The data corresponding to the key
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>#MDB_NOTFOUND - the key was not in the database.
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_get(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
/** @brief Store items into a database.
*
* This function stores key/data pairs in the database. The default behavior
* is to enter the new key/data pair, replacing any previously existing key
* if duplicates are disallowed, or adding a duplicate data item if
* duplicates are allowed (#MDB_DUPSORT).
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[in] key The key to store in the database
* @param[in,out] data The data to store
* @param[in] flags Special options for this operation. This parameter
* must be set to 0 or by bitwise OR'ing together one or more of the
* values described here.
* <ul>
* <li>#MDB_NODUPDATA - enter the new key/data pair only if it does not
* already appear in the database. This flag may only be specified
* if the database was opened with #MDB_DUPSORT. The function will
* return #MDB_KEYEXIST if the key/data pair already appears in the
* database.
* <li>#MDB_NOOVERWRITE - enter the new key/data pair only if the key
* does not already appear in the database. The function will return
* #MDB_KEYEXIST if the key already appears in the database, even if
* the database supports duplicates (#MDB_DUPSORT). The \b data
* parameter will be set to point to the existing item.
* <li>#MDB_RESERVE - reserve space for data of the given size, but
* don't copy the given data. Instead, return a pointer to the
* reserved space, which the caller can fill in later - before
* the next update operation or the transaction ends. This saves
* an extra memcpy if the data is being generated later.
* MDB does nothing else with this memory, the caller is expected
* to modify all of the space requested.
* <li>#MDB_APPEND - append the given key/data pair to the end of the
* database. No key comparisons are performed. This option allows
* fast bulk loading when keys are already known to be in the
* correct order. Loading unsorted keys with this flag will cause
* data corruption.
* <li>#MDB_APPENDDUP - as above, but for sorted dup data.
* </ul>
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>#MDB_MAP_FULL - the database is full, see #mdb_env_set_mapsize().
* <li>#MDB_TXN_FULL - the transaction has too many dirty pages.
* <li>EACCES - an attempt was made to write in a read-only transaction.
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_put(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data,
unsigned int flags);
/** @brief Delete items from a database.
*
* This function removes key/data pairs from the database.
* If the database does not support sorted duplicate data items
* (#MDB_DUPSORT) the data parameter is ignored.
* If the database supports sorted duplicates and the data parameter
* is NULL, all of the duplicate data items for the key will be
* deleted. Otherwise, if the data parameter is non-NULL
* only the matching data item will be deleted.
* This function will return #MDB_NOTFOUND if the specified key/data
* pair is not in the database.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[in] key The key to delete from the database
* @param[in] data The data to delete
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EACCES - an attempt was made to write in a read-only transaction.
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_del(MDB_txn *txn, MDB_dbi dbi, MDB_val *key, MDB_val *data);
/** @brief Create a cursor handle.
*
* A cursor is associated with a specific transaction and database.
* A cursor cannot be used when its database handle is closed. Nor
* when its transaction has ended, except with #mdb_cursor_renew().
* It can be discarded with #mdb_cursor_close().
* A cursor in a write-transaction can be closed before its transaction
* ends, and will otherwise be closed when its transaction ends.
* A cursor in a read-only transaction must be closed explicitly, before
* or after its transaction ends. It can be reused with
* #mdb_cursor_renew() before finally closing it.
* @note Earlier documentation said that cursors in every transaction
* were closed when the transaction committed or aborted.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[out] cursor Address where the new #MDB_cursor handle will be stored
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **cursor);
/** @brief Close a cursor handle.
*
* The cursor handle will be freed and must not be used again after this call.
* Its transaction must still be live if it is a write-transaction.
* @param[in] cursor A cursor handle returned by #mdb_cursor_open()
*/
void mdb_cursor_close(MDB_cursor *cursor);
/** @brief Renew a cursor handle.
*
* A cursor is associated with a specific transaction and database.
* Cursors that are only used in read-only
* transactions may be re-used, to avoid unnecessary malloc/free overhead.
* The cursor may be associated with a new read-only transaction, and
* referencing the same database handle as it was created with.
* This may be done whether the previous transaction is live or dead.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] cursor A cursor handle returned by #mdb_cursor_open()
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_cursor_renew(MDB_txn *txn, MDB_cursor *cursor);
/** @brief Return the cursor's transaction handle.
*
* @param[in] cursor A cursor handle returned by #mdb_cursor_open()
*/
MDB_txn *mdb_cursor_txn(MDB_cursor *cursor);
/** @brief Return the cursor's database handle.
*
* @param[in] cursor A cursor handle returned by #mdb_cursor_open()
*/
MDB_dbi mdb_cursor_dbi(MDB_cursor *cursor);
/** @brief Retrieve by cursor.
*
* This function retrieves key/data pairs from the database. The address and length
* of the key are returned in the object to which \b key refers (except for the
* case of the #MDB_SET option, in which the \b key object is unchanged), and
* the address and length of the data are returned in the object to which \b data
* refers.
* See #mdb_get() for restrictions on using the output values.
* @param[in] cursor A cursor handle returned by #mdb_cursor_open()
* @param[in,out] key The key for a retrieved item
* @param[in,out] data The data of a retrieved item
* @param[in] op A cursor operation #MDB_cursor_op
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>#MDB_NOTFOUND - no matching key found.
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
MDB_cursor_op op);
/** @brief Store by cursor.
*
* This function stores key/data pairs into the database.
* If the function fails for any reason, the state of the cursor will be
* unchanged. If the function succeeds and an item is inserted into the
* database, the cursor is always positioned to refer to the newly inserted item.
* @param[in] cursor A cursor handle returned by #mdb_cursor_open()
* @param[in] key The key operated on.
* @param[in] data The data operated on.
* @param[in] flags Options for this operation. This parameter
* must be set to 0 or one of the values described here.
* <ul>
* <li>#MDB_CURRENT - overwrite the data of the key/data pair to which
* the cursor refers with the specified data item. The \b key
* parameter is not used for positioning the cursor, but should
* still be provided. If using sorted duplicates (#MDB_DUPSORT)
* the data item must still sort into the same place.
* <li>#MDB_NODUPDATA - enter the new key/data pair only if it does not
* already appear in the database. This flag may only be specified
* if the database was opened with #MDB_DUPSORT. The function will
* return #MDB_KEYEXIST if the key/data pair already appears in the
* database.
* <li>#MDB_NOOVERWRITE - enter the new key/data pair only if the key
* does not already appear in the database. The function will return
* #MDB_KEYEXIST if the key already appears in the database, even if
* the database supports duplicates (#MDB_DUPSORT).
* <li>#MDB_RESERVE - reserve space for data of the given size, but
* don't copy the given data. Instead, return a pointer to the
* reserved space, which the caller can fill in later. This saves
* an extra memcpy if the data is being generated later.
* <li>#MDB_APPEND - append the given key/data pair to the end of the
* database. No key comparisons are performed. This option allows
* fast bulk loading when keys are already known to be in the
* correct order. Loading unsorted keys with this flag will cause
* data corruption.
* <li>#MDB_APPENDDUP - as above, but for sorted dup data.
* <li>#MDB_MULTIPLE - store multiple contiguous data elements in a
* single request. This flag may only be specified if the database
* was opened with #MDB_DUPFIXED. The \b data argument must be an
* array of two MDB_vals. The mv_size of the first MDB_val must be
* the size of a single data element. The mv_data of the first MDB_val
* must point to the beginning of the array of contiguous data elements.
* The mv_size of the second MDB_val must be the count of the number
* of data elements to store. On return this field will be set to
* the count of the number of elements actually written. The mv_data
* of the second MDB_val is unused.
* </ul>
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>#MDB_MAP_FULL - the database is full, see #mdb_env_set_mapsize().
* <li>#MDB_TXN_FULL - the transaction has too many dirty pages.
* <li>EACCES - an attempt was made to modify a read-only database.
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_cursor_put(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
unsigned int flags);
/** @brief Delete current key/data pair
*
* This function deletes the key/data pair to which the cursor refers.
* @param[in] cursor A cursor handle returned by #mdb_cursor_open()
* @param[in] flags Options for this operation. This parameter
* must be set to 0 or one of the values described here.
* <ul>
* <li>#MDB_NODUPDATA - delete all of the data items for the current key.
* This flag may only be specified if the database was opened with #MDB_DUPSORT.
* </ul>
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EACCES - an attempt was made to modify a read-only database.
* <li>EINVAL - an invalid parameter was specified.
* </ul>
*/
int mdb_cursor_del(MDB_cursor *cursor, unsigned int flags);
/** @brief Return count of duplicates for current key.
*
* This call is only valid on databases that support sorted duplicate
* data items #MDB_DUPSORT.
* @param[in] cursor A cursor handle returned by #mdb_cursor_open()
* @param[out] countp Address where the count will be stored
* @return A non-zero error value on failure and 0 on success. Some possible
* errors are:
* <ul>
* <li>EINVAL - cursor is not initialized, or an invalid parameter was specified.
* </ul>
*/
int mdb_cursor_count(MDB_cursor *cursor, size_t *countp);
/** @brief Compare two data items according to a particular database.
*
* This returns a comparison as if the two data items were keys in the
* specified database.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[in] a The first item to compare
* @param[in] b The second item to compare
* @return < 0 if a < b, 0 if a == b, > 0 if a > b
*/
int mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b);
/** @brief Compare two data items according to a particular database.
*
* This returns a comparison as if the two items were data items of
* the specified database. The database must have the #MDB_DUPSORT flag.
* @param[in] txn A transaction handle returned by #mdb_txn_begin()
* @param[in] dbi A database handle returned by #mdb_dbi_open()
* @param[in] a The first item to compare
* @param[in] b The second item to compare
* @return < 0 if a < b, 0 if a == b, > 0 if a > b
*/
int mdb_dcmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b);
/** @brief A callback function used to print a message from the library.
*
* @param[in] msg The string to be printed.
* @param[in] ctx An arbitrary context pointer for the callback.
* @return < 0 on failure, >= 0 on success.
*/
typedef int (MDB_msg_func)(const char *msg, void *ctx);
/** @brief Dump the entries in the reader lock table.
*
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[in] func A #MDB_msg_func function
* @param[in] ctx Anything the message function needs
* @return < 0 on failure, >= 0 on success.
*/
int mdb_reader_list(MDB_env *env, MDB_msg_func *func, void *ctx);
/** @brief Check for stale entries in the reader lock table.
*
* @param[in] env An environment handle returned by #mdb_env_create()
* @param[out] dead Number of stale slots that were cleared
* @return 0 on success, non-zero on failure.
*/
int mdb_reader_check(MDB_env *env, int *dead);
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* _LMDB_H_ */
| {'content_hash': '166e6b21bc2d391efe9f76bfdc6ac0ed', 'timestamp': '', 'source': 'github', 'line_count': 1321, 'max_line_length': 93, 'avg_line_length': 45.35730507191521, 'alnum_prop': 0.708279787038737, 'repo_name': 'influxdb/gomdb', 'id': 'd7e6fb0f92b86b126d570faab3068ee1e3da0516', 'size': '67301', 'binary': False, 'copies': '11', 'ref': 'refs/heads/master', 'path': 'lmdb.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '320626'}, {'name': 'Go', 'bytes': '28149'}]} |
package untappd
import (
"net/http"
"net/url"
"strconv"
)
// Info queries for information about a Brewery with the specified ID.
// If the compact parameter is set to 'true', only basic brewery information will
// be populated.
func (b *BreweryService) Info(id int, compact bool) (*Brewery, *http.Response, error) {
// Determine if a compact response is requested
q := url.Values{}
if compact {
q.Set("compact", "true")
}
// Temporary struct to unmarshal raw user JSON
var v struct {
Response struct {
Brewery rawBrewery `json:"brewery"`
} `json:"response"`
}
// Perform request for brewery information by ID
res, err := b.client.request("GET", "brewery/info/"+strconv.Itoa(id), nil, q, &v)
if err != nil {
return nil, res, err
}
return v.Response.Brewery.export(), res, nil
}
| {'content_hash': 'eba77003679581f00160b7a507f98fb5', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 87, 'avg_line_length': 24.484848484848484, 'alnum_prop': 0.6856435643564357, 'repo_name': 'kriben/untappd', 'id': '784e711474970da5bc48ee265e4a2b91f97b0986', 'size': '808', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'brewery_info.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '211024'}]} |
@interface UIColor (iOS7Colors)
// Plain Colors
+ (instancetype)iOS7redColor;
+ (instancetype)iOS7orangeColor;
+ (instancetype)iOS7yellowColor;
+ (instancetype)iOS7greenColor;
+ (instancetype)iOS7lightBlueColor;
+ (instancetype)iOS7darkBlueColor;
+ (instancetype)iOS7purpleColor;
+ (instancetype)iOS7pinkColor;
+ (instancetype)iOS7darkGrayColor;
+ (instancetype)iOS7lightGrayColor;
// Gradient Colors
+ (instancetype)iOS7redGradientStartColor;
+ (instancetype)iOS7redGradientEndColor;
+ (instancetype)iOS7orangeGradientStartColor;
+ (instancetype)iOS7orangeGradientEndColor;
+ (instancetype)iOS7yellowGradientStartColor;
+ (instancetype)iOS7yellowGradientEndColor;
+ (instancetype)iOS7greenGradientStartColor;
+ (instancetype)iOS7greenGradientEndColor;
+ (instancetype)iOS7tealGradientStartColor;
+ (instancetype)iOS7tealGradientEndColor;
+ (instancetype)iOS7blueGradientStartColor;
+ (instancetype)iOS7blueGradientEndColor;
+ (instancetype)iOS7violetGradientStartColor;
+ (instancetype)iOS7violetGradientEndColor;
+ (instancetype)iOS7magentaGradientStartColor;
+ (instancetype)iOS7magentaGradientEndColor;
+ (instancetype)iOS7blackGradientStartColor;
+ (instancetype)iOS7blackGradientEndColor;
+ (instancetype)iOS7silverGradientStartColor;
+ (instancetype)iOS7silverGradientEndColor;
@end
| {'content_hash': '7b891b6a0a73c19ea932906530d4d1db', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 46, 'avg_line_length': 28.304347826086957, 'alnum_prop': 0.8387096774193549, 'repo_name': 'xingty/hipda_ios_client_v3', 'id': 'd8f67020763c5044cd0343614dc4c0ff5dc1ceb9', 'size': '1419', 'binary': False, 'copies': '4', 'ref': 'refs/heads/developer-jichao', 'path': 'HiPDA/Helper/UIColor+iOS7Colors.h', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '74740'}, {'name': 'JavaScript', 'bytes': '3925'}, {'name': 'Objective-C', 'bytes': '1321488'}, {'name': 'Ruby', 'bytes': '814'}]} |
[bootstrap 官方 gem](https://github.com/twbs/bootstrap-rubygem)
```ruby
gem 'bootstrap', '~> 4.3.1'
gem "jquery-rails"
```
```bash
mv app/assets/stylesheets/application.css app/assets/stylesheets/application.css.scss
```
app/assets/stylesheets/application.scss
```
// Custom bootstrap variables must be set or imported *before* bootstrap.
@import "bootstrap";
```
application.js
```javascript
//= require jquery3
//= require popper
//= require bootstrap-sprockets
```
或 require the concatenated bootstrap for faster compilation
```javascript
//= require jquery3
//= require popper
//= require bootstrap
```
```bash
bundle install
```
## 参考
+ rails_layout, 支持 Foundation Bootstrap,但版本有点旧,可以借鉴
<https://github.com/RailsApps/rails_layout>
```bash
rails generate layout:install bootstrap4
rails generate layout:navigation bootstrap4
rails generate layout:devise
```
+ 和上面一起的, rails 的示例,也是两年前
<https://github.com/RailsApps/rails-composer>
+ rails 应用模板
<https://ruby-china.github.io/rails-guides/rails_application_templates.html>
> 这个可以当一个示例
+ 完善布局
<https://railstutorial-china.org/book/chapter5.html>
<https://www.kancloud.cn/wizardforcel/rails-tutorial/151233>
## rails_layout
```
# app/assets/javascripts/application.js
jquery3 popper bootstrap-sprockets 加这几个
//= require jquery3
//= require popper
//= require rails-ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
```
app/assets/stylesheets/application.css.scss 只改名字不变
app/assets/stylesheets/1st_load_framework.css.scss
```css
// import the CSS framework
// Do not use *= require in Sass or your other stylesheets will not be able to access the Bootstrap mixins and variables.
@import "bootstrap";
// make all images responsive by default
img {
@extend .img-fluid;
margin: 0 auto;
}
// override for the 'Home' navigation link
.navbar-brand {
font-size: inherit;
}
// THESE ARE EXAMPLES YOU CAN MODIFY
// create your own classes
// to make views framework-neutral
.column {
@extend .col-md-6;
text-align: center;
}
.form {
@extend .col-md-6;
}
.form-centered {
@extend .col-md-6;
text-align: center;
}
.submit {
@extend .btn;
@extend .btn-primary;
@extend .btn-lg;
}
// apply styles to HTML elements
// to make views framework-neutral
main {
@extend .container;
margin-top: 30px; // accommodate the navbar
}
section {
@extend .row;
margin-top: 20px;
}
```
app/views/layouts/application.html.erb
```html
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= content_for?(:title) ? yield(:title) : "Udesk Greatewall" %></title>
<meta name="description" content="<%= content_for?(:description) ? yield(:description) : "Udesk Greatewall" %>">
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => 'reload' %>
<%= csrf_meta_tags %>
</head>
<body>
<header>
<%= render 'layouts/navigation' %>
</header>
<main role="main" class="main-container container">
<%= render 'layouts/messages' %>
<%= yield %>
</main>
</body>
```
app/views/layouts/_messages.html.erb
```
<%# Rails flash messages styled for Bootstrap 4.0 %>
<% flash.each do |name, msg| %>
<% if msg.is_a?(String) %>
<div class="alert alert-<%= name.to_s == 'notice' ? 'success' : 'danger' %>" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<%= content_tag :div, msg, :id => "flash_#{name}" %>
</div>
<% end %>
<% end %>
```
app/views/layouts/_navigation.html.erb,这个就不太好了
```html
<%# navigation styled for Bootstrap 4.0 %>
<div class="container">
<nav class="navbar navbar-dark bg-inverse">
<ul class="nav navbar-nav clearfix">
<li class="nav-item">
<button class="navbar-toggler hidden-sm-up nav-link" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar2" aria-controls="exCollapsingNavbar2" aria-expanded="false" aria-label="Toggle navigation">
☰
</button>
</li>
</ul>
<div class="collapse navbar-toggleable-xs" id="exCollapsingNavbar2">
<%= link_to "Rails bootstrap", root_path, class: 'navbar-brand' %>
<ul class="nav navbar-nav">
<%= render 'layouts/navigation_links' %>
</ul>
</div>
</nav>
</div>
```
| {'content_hash': '8937f72ad5d89d23e9b5de1868c36104', 'timestamp': '', 'source': 'github', 'line_count': 174, 'max_line_length': 222, 'avg_line_length': 25.21264367816092, 'alnum_prop': 0.6735810348757694, 'repo_name': 'azhao1981/my-notes', 'id': '58c9d26ee7c10fe835e27b3734be5a8625887a79', 'size': '4555', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/ruby/rails_bootstrap.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '517'}, {'name': 'Shell', 'bytes': '12629'}]} |
#include "storage/WindowAggregationOperationState.hpp"
#include <cstddef>
#include <cstdio>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "catalog/CatalogDatabaseLite.hpp"
#include "catalog/CatalogRelationSchema.hpp"
#include "catalog/CatalogTypedefs.hpp"
#include "expressions/ExpressionFactories.hpp"
#include "expressions/Expressions.pb.h"
#include "expressions/scalar/Scalar.hpp"
#include "expressions/scalar/ScalarAttribute.hpp"
#include "expressions/window_aggregation/WindowAggregateFunction.hpp"
#include "expressions/window_aggregation/WindowAggregateFunctionFactory.hpp"
#include "expressions/window_aggregation/WindowAggregationHandle.hpp"
#include "expressions/window_aggregation/WindowAggregationID.hpp"
#include "storage/InsertDestination.hpp"
#include "storage/StorageManager.hpp"
#include "storage/SubBlocksReference.hpp"
#include "storage/ValueAccessor.hpp"
#include "storage/ValueAccessorUtil.hpp"
#include "storage/WindowAggregationOperationState.pb.h"
#include "types/containers/ColumnVector.hpp"
#include "types/containers/ColumnVectorsValueAccessor.hpp"
#include "types/containers/ColumnVectorUtil.hpp"
#include "glog/logging.h"
namespace quickstep {
WindowAggregationOperationState::WindowAggregationOperationState(
const CatalogRelationSchema &input_relation,
const WindowAggregateFunction *window_aggregate_function,
std::vector<std::unique_ptr<const Scalar>> &&arguments,
const std::vector<std::unique_ptr<const Scalar>> &partition_by_attributes,
const std::vector<std::unique_ptr<const Scalar>> &order_by_attributes,
const bool is_row,
const std::int64_t num_preceding,
const std::int64_t num_following,
StorageManager *storage_manager)
: input_relation_(input_relation),
arguments_(std::move(arguments)),
storage_manager_(storage_manager) {
// Get the Types of this window aggregate's arguments so that we can create an
// AggregationHandle.
std::vector<const Type*> argument_types;
for (const std::unique_ptr<const Scalar> &argument : arguments_) {
argument_types.emplace_back(&argument->getType());
}
// Check if window aggregate function could apply to the arguments.
DCHECK(window_aggregate_function->canApplyToTypes(argument_types));
// Create the handle and initial state.
window_aggregation_handle_.reset(
window_aggregate_function->createHandle(argument_types,
partition_by_attributes,
order_by_attributes,
is_row,
num_preceding,
num_following));
}
WindowAggregationOperationState* WindowAggregationOperationState::ReconstructFromProto(
const serialization::WindowAggregationOperationState &proto,
const CatalogDatabaseLite &database,
StorageManager *storage_manager) {
DCHECK(ProtoIsValid(proto, database));
std::vector<std::unique_ptr<const Scalar>> arguments;
arguments.reserve(proto.arguments_size());
for (int argument_idx = 0; argument_idx < proto.arguments_size(); ++argument_idx) {
arguments.emplace_back(ScalarFactory::ReconstructFromProto(
proto.arguments(argument_idx),
database));
}
std::vector<std::unique_ptr<const Scalar>> partition_by_attributes;
for (int attribute_idx = 0;
attribute_idx < proto.partition_by_attributes_size();
++attribute_idx) {
partition_by_attributes.emplace_back(ScalarFactory::ReconstructFromProto(
proto.partition_by_attributes(attribute_idx),
database));
}
std::vector<std::unique_ptr<const Scalar>> order_by_attributes;
for (int attribute_idx = 0;
attribute_idx < proto.order_by_attributes_size();
++attribute_idx) {
order_by_attributes.emplace_back(ScalarFactory::ReconstructFromProto(
proto.order_by_attributes(attribute_idx),
database));
}
const bool is_row = proto.is_row();
const std::int64_t num_preceding = proto.num_preceding();
const std::int64_t num_following = proto.num_following();
return new WindowAggregationOperationState(database.getRelationSchemaById(proto.input_relation_id()),
&WindowAggregateFunctionFactory::ReconstructFromProto(proto.function()),
std::move(arguments),
partition_by_attributes,
order_by_attributes,
is_row,
num_preceding,
num_following,
storage_manager);
}
bool WindowAggregationOperationState::ProtoIsValid(const serialization::WindowAggregationOperationState &proto,
const CatalogDatabaseLite &database) {
if (!proto.IsInitialized() ||
!database.hasRelationWithId(proto.input_relation_id())) {
return false;
}
if (!WindowAggregateFunctionFactory::ProtoIsValid(proto.function())) {
return false;
}
// TODO(chasseur): We may also want to check that the specified
// AggregateFunction is applicable to the specified arguments, but that
// requires partial deserialization and may be too heavyweight for this
// method.
// TODO(Shixuan): The TODO for AggregateFunction could also be applied here.
for (int argument_idx = 0;
argument_idx < proto.arguments_size();
++argument_idx) {
if (!ScalarFactory::ProtoIsValid(proto.arguments(argument_idx), database)) {
return false;
}
}
for (int attribute_idx = 0;
attribute_idx < proto.partition_by_attributes_size();
++attribute_idx) {
if (!ScalarFactory::ProtoIsValid(proto.partition_by_attributes(attribute_idx),
database)) {
return false;
}
}
for (int attribute_idx = 0;
attribute_idx < proto.order_by_attributes_size();
++attribute_idx) {
if (!ScalarFactory::ProtoIsValid(proto.order_by_attributes(attribute_idx),
database)) {
return false;
}
}
if (proto.num_preceding() < -1 || proto.num_following() < -1) {
return false;
}
return true;
}
void WindowAggregationOperationState::windowAggregateBlocks(
InsertDestination *output_destination,
const std::vector<block_id> &block_ids) {
// TODO(Shixuan): This is a quick fix for currently unsupported functions in
// order to pass the query_optimizer test.
if (window_aggregation_handle_.get() == nullptr) {
std::cout << "The function will be supported in the near future :)\n";
return;
}
// Get the total number of tuples.
int num_tuples = 0;
for (const block_id block_idx : block_ids) {
num_tuples +=
storage_manager_->getBlock(block_idx, input_relation_)->getNumTuples();
}
// Construct column vectors for attributes.
std::vector<ColumnVector*> attribute_vecs;
for (std::size_t attr_id = 0; attr_id < input_relation_.size(); ++attr_id) {
const CatalogAttribute *attr = input_relation_.getAttributeById(attr_id);
const Type &type = attr->getType();
if (NativeColumnVector::UsableForType(type)) {
attribute_vecs.push_back(new NativeColumnVector(type, num_tuples));
} else {
attribute_vecs.push_back(new IndirectColumnVector(type, num_tuples));
}
}
// Construct column vectors for arguments.
std::vector<ColumnVector*> argument_vecs;
for (const std::unique_ptr<const Scalar> &argument : arguments_) {
const Type &type = argument->getType();
if (NativeColumnVector::UsableForType(type)) {
argument_vecs.push_back(new NativeColumnVector(type, num_tuples));
} else {
argument_vecs.push_back(new IndirectColumnVector(type, num_tuples));
}
}
// TODO(Shixuan): Add Support for Vector Copy Elision Selection.
// Add tuples and arguments into ColumnVectors.
for (const block_id block_idx : block_ids) {
BlockReference block = storage_manager_->getBlock(block_idx, input_relation_);
const TupleStorageSubBlock &tuple_block = block->getTupleStorageSubBlock();
SubBlocksReference sub_block_ref(tuple_block,
block->getIndices(),
block->getIndicesConsistent());
ValueAccessor *tuple_accessor = tuple_block.createValueAccessor();
ColumnVectorsValueAccessor *argument_accessor = nullptr;
if (!arguments_.empty()) {
argument_accessor = new ColumnVectorsValueAccessor();
}
for (const std::unique_ptr<const Scalar> &argument : arguments_) {
argument_accessor->addColumn(argument->getAllValues(tuple_accessor,
&sub_block_ref));
}
InvokeOnAnyValueAccessor(tuple_accessor,
[&] (auto *tuple_accessor) -> void { // NOLINT(build/c++11)
tuple_accessor->beginIteration();
if (argument_accessor != nullptr) {
argument_accessor->beginIteration();
}
while (tuple_accessor->next()) {
if (argument_accessor != nullptr) {
argument_accessor->next();
}
for (std::size_t attr_id = 0; attr_id < attribute_vecs.size(); ++attr_id) {
ColumnVector *attr_vec = attribute_vecs[attr_id];
if (attr_vec->isNative()) {
static_cast<NativeColumnVector*>(attr_vec)->appendTypedValue(
tuple_accessor->getTypedValue(attr_id));
} else {
static_cast<IndirectColumnVector*>(attr_vec)->appendTypedValue(
tuple_accessor->getTypedValue(attr_id));
}
}
for (std::size_t argument_idx = 0;
argument_idx < argument_vecs.size();
++argument_idx) {
ColumnVector *argument = argument_vecs[argument_idx];
if (argument->isNative()) {
static_cast<NativeColumnVector*>(argument)->appendTypedValue(
argument_accessor->getTypedValue(argument_idx));
} else {
static_cast<IndirectColumnVector*>(argument)->appendTypedValue(
argument_accessor->getTypedValue(argument_idx));
}
}
}
});
}
// Construct the value accessor for tuples in all blocks
ColumnVectorsValueAccessor *all_blocks_accessor
= new ColumnVectorsValueAccessor();
for (ColumnVector *attr_vec : attribute_vecs) {
all_blocks_accessor->addColumn(attr_vec);
}
// Do actual calculation in handle.
ColumnVector *window_aggregates =
window_aggregation_handle_->calculate(all_blocks_accessor,
argument_vecs);
all_blocks_accessor->addColumn(window_aggregates);
output_destination->bulkInsertTuples(all_blocks_accessor);
}
} // namespace quickstep
| {'content_hash': 'a80e7960803af834cd0fad89c2698583', 'timestamp': '', 'source': 'github', 'line_count': 282, 'max_line_length': 117, 'avg_line_length': 39.02482269503546, 'alnum_prop': 0.6482507950931394, 'repo_name': 'tarunbansal/incubator-quickstep', 'id': '58bdf18b626bf69ee0f1cde6ff66a4da092e6844', 'size': '11814', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'storage/WindowAggregationOperationState.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '8446499'}, {'name': 'CMake', 'bytes': '583645'}, {'name': 'Protocol Buffer', 'bytes': '48907'}, {'name': 'Python', 'bytes': '33134'}, {'name': 'Ruby', 'bytes': '5352'}, {'name': 'Shell', 'bytes': '3408'}]} |
set -o errexit
set -o nounset
set -o pipefail
OS_ROOT=$(dirname "${BASH_SOURCE}")/..
source "${OS_ROOT}/hack/lib/init.sh"
platform="$(os::build::host_platform)"
if [[ "${platform}" != "linux/amd64" ]]; then
echo "WARNING: Generating completions on ${platform} may not be identical to running on linux/amd64 due to conditional compilation."
fi
#"${OS_ROOT}/hack/build-go.sh" tools/genbashcomp
OUTPUT_REL_DIR=${1:-""}
OUTPUT_DIR_ROOT="${OS_ROOT}/${OUTPUT_REL_DIR}/contrib/completions"
mkdir -p "${OUTPUT_DIR_ROOT}/bash" || echo $? > /dev/null
mkdir -p "${OUTPUT_DIR_ROOT}/zsh" || echo $? > /dev/null
os::build::gen-completions "${OUTPUT_DIR_ROOT}/bash" "bash"
os::build::gen-completions "${OUTPUT_DIR_ROOT}/zsh" "zsh" | {'content_hash': '4742ea0c955ce700a5470e61de8bc435', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 134, 'avg_line_length': 32.86363636363637, 'alnum_prop': 0.6749654218533887, 'repo_name': 'fabianofranz/origin', 'id': '743bab2e5f65cd5a30e378fd34d948b7d8b388f7', 'size': '812', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'hack/update-generated-completions.sh', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '921'}, {'name': 'DIGITAL Command Language', 'bytes': '117'}, {'name': 'Go', 'bytes': '10426668'}, {'name': 'Groff', 'bytes': '2049'}, {'name': 'Makefile', 'bytes': '5071'}, {'name': 'Python', 'bytes': '14204'}, {'name': 'Ruby', 'bytes': '363'}, {'name': 'Shell', 'bytes': '1583066'}]} |
package com.facebook.react.uimanager;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import com.facebook.common.logging.FLog;
import com.facebook.react.animation.Animation;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.OnBatchCompleteListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.uimanager.debug.NotThreadSafeViewHierarchyUpdateDebugListener;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.systrace.Systrace;
import com.facebook.systrace.SystraceMessage;
/**
* <p>Native module to allow JS to create and update native Views.</p>
*
* <p>
* <h2>== Transactional Requirement ==</h2>
* A requirement of this class is to make sure that transactional UI updates occur all at once, meaning
* that no intermediate state is ever rendered to the screen. For example, if a JS application
* update changes the background of View A to blue and the width of View B to 100, both need to
* appear at once. Practically, this means that all UI update code related to a single transaction
* must be executed as a single code block on the UI thread. Executing as multiple code blocks
* could allow the platform UI system to interrupt and render a partial UI state.
* </p>
*
* <p>To facilitate this, this module enqueues operations that are then applied to native view
* hierarchy through {@link NativeViewHierarchyManager} at the end of each transaction.
*
* <p>
* <h2>== CSSNodes ==</h2>
* In order to allow layout and measurement to occur on a non-UI thread, this module also
* operates on intermediate CSSNode objects that correspond to a native view. These CSSNode are able
* to calculate layout according to their styling rules, and then the resulting x/y/width/height of
* that layout is scheduled as an operation that will be applied to native view hierarchy at the end
* of current batch.
* </p>
*
* TODO(5241856): Investigate memory usage of creating many small objects in UIManageModule and
* consider implementing a pool
* TODO(5483063): Don't dispatch the view hierarchy at the end of a batch if no UI changes occurred
*/
public class UIManagerModule extends ReactContextBaseJavaModule implements
OnBatchCompleteListener, LifecycleEventListener {
// Keep in sync with ReactIOSTagHandles JS module - see that file for an explanation on why the
// increment here is 10
private static final int ROOT_VIEW_TAG_INCREMENT = 10;
private static final boolean DEBUG = false;
private final EventDispatcher mEventDispatcher;
private final Map<String, Object> mModuleConstants;
private final UIImplementation mUIImplementation;
private int mNextRootViewTag = 1;
private int mBatchId = 0;
public UIManagerModule(
ReactApplicationContext reactContext,
List<ViewManager> viewManagerList,
UIImplementation uiImplementation) {
super(reactContext);
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(reactContext);
mEventDispatcher = new EventDispatcher(reactContext);
mModuleConstants = createConstants(viewManagerList);
mUIImplementation = uiImplementation;
reactContext.addLifecycleEventListener(this);
}
/**
* This method gives an access to the {@link UIImplementation} object that can be used to execute
* operations on the view hierarchy.
*/
public UIImplementation getUIImplementation() {
return mUIImplementation;
}
@Override
public String getName() {
return "RKUIManager";
}
@Override
public Map<String, Object> getConstants() {
return mModuleConstants;
}
@Override
public void onHostResume() {
mUIImplementation.onHostResume();
}
@Override
public void onHostPause() {
mUIImplementation.onHostPause();
}
@Override
public void onHostDestroy() {
mUIImplementation.onHostDestroy();
}
@Override
public void onCatalystInstanceDestroy() {
super.onCatalystInstanceDestroy();
mEventDispatcher.onCatalystInstanceDestroyed();
}
private static Map<String, Object> createConstants(List<ViewManager> viewManagerList) {
Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "CreateUIManagerConstants");
try {
return UIManagerModuleConstantsHelper.createConstants(viewManagerList);
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
}
}
/**
* Registers a new root view. JS can use the returned tag with manageChildren to add/remove
* children to this view.
*
* Note that this must be called after getWidth()/getHeight() actually return something. See
* CatalystApplicationFragment as an example.
*
* TODO(6242243): Make addMeasuredRootView thread safe
* NB: this method is horribly not-thread-safe.
*/
public int addMeasuredRootView(final SizeMonitoringFrameLayout rootView) {
final int tag = mNextRootViewTag;
mNextRootViewTag += ROOT_VIEW_TAG_INCREMENT;
final int width;
final int height;
// If LayoutParams sets size explicitly, we can use that. Otherwise get the size from the view.
if (rootView.getLayoutParams() != null &&
rootView.getLayoutParams().width > 0 &&
rootView.getLayoutParams().height > 0) {
width = rootView.getLayoutParams().width;
height = rootView.getLayoutParams().height;
} else {
width = rootView.getWidth();
height = rootView.getHeight();
}
final ThemedReactContext themedRootContext =
new ThemedReactContext(getReactApplicationContext(), rootView.getContext());
mUIImplementation.registerRootView(rootView, tag, width, height, themedRootContext);
rootView.setOnSizeChangedListener(
new SizeMonitoringFrameLayout.OnSizeChangedListener() {
@Override
public void onSizeChanged(final int width, final int height, int oldW, int oldH) {
getReactApplicationContext().runOnNativeModulesQueueThread(
new Runnable() {
@Override
public void run() {
updateRootNodeSize(tag, width, height);
}
});
}
});
return tag;
}
@ReactMethod
public void removeRootView(int rootViewTag) {
mUIImplementation.removeRootView(rootViewTag);
}
private void updateRootNodeSize(int rootViewTag, int newWidth, int newHeight) {
getReactApplicationContext().assertOnNativeModulesQueueThread();
mUIImplementation.updateRootNodeSize(rootViewTag, newWidth, newHeight, mEventDispatcher);
}
@ReactMethod
public void createView(int tag, String className, int rootViewTag, ReadableMap props) {
if (DEBUG) {
FLog.d(
ReactConstants.TAG,
"(UIManager.createView) tag: " + tag + ", class: " + className + ", props: " + props);
}
mUIImplementation.createView(tag, className, rootViewTag, props);
}
@ReactMethod
public void updateView(int tag, String className, ReadableMap props) {
if (DEBUG) {
FLog.d(
ReactConstants.TAG,
"(UIManager.updateView) tag: " + tag + ", class: " + className + ", props: " + props);
}
mUIImplementation.updateView(tag, className, props);
}
/**
* Interface for adding/removing/moving views within a parent view from JS.
*
* @param viewTag the view tag of the parent view
* @param moveFrom a list of indices in the parent view to move views from
* @param moveTo parallel to moveFrom, a list of indices in the parent view to move views to
* @param addChildTags a list of tags of views to add to the parent
* @param addAtIndices parallel to addChildTags, a list of indices to insert those children at
* @param removeFrom a list of indices of views to permanently remove. The memory for the
* corresponding views and data structures should be reclaimed.
*/
@ReactMethod
public void manageChildren(
int viewTag,
@Nullable ReadableArray moveFrom,
@Nullable ReadableArray moveTo,
@Nullable ReadableArray addChildTags,
@Nullable ReadableArray addAtIndices,
@Nullable ReadableArray removeFrom) {
if (DEBUG) {
FLog.d(
ReactConstants.TAG,
"(UIManager.manageChildren) tag: " + viewTag +
", moveFrom: " + moveFrom +
", moveTo: " + moveTo +
", addTags: " + addChildTags +
", atIndices: " + addAtIndices +
", removeFrom: " + removeFrom);
}
mUIImplementation.manageChildren(
viewTag,
moveFrom,
moveTo,
addChildTags,
addAtIndices,
removeFrom);
}
/**
* Interface for fast tracking the initial adding of views. Children view tags are assumed to be
* in order
*
* @param viewTag the view tag of the parent view
* @param childrenTags An array of tags to add to the parent in order
*/
@ReactMethod
public void setChildren(
int viewTag,
ReadableArray childrenTags) {
FLog.d(
ReactConstants.TAG,
"(UIManager.setChildren) tag: " + viewTag + ", children: " + childrenTags);
mUIImplementation.setChildren(viewTag, childrenTags);
}
/**
* Replaces the View specified by oldTag with the View specified by newTag within oldTag's parent.
* This resolves to a simple {@link #manageChildren} call, but React doesn't have enough info in
* JS to formulate it itself.
*/
@ReactMethod
public void replaceExistingNonRootView(int oldTag, int newTag) {
mUIImplementation.replaceExistingNonRootView(oldTag, newTag);
}
/**
* Method which takes a container tag and then releases all subviews for that container upon
* receipt.
* TODO: The method name is incorrect and will be renamed, #6033872
* @param containerTag the tag of the container for which the subviews must be removed
*/
@ReactMethod
public void removeSubviewsFromContainerWithID(int containerTag) {
mUIImplementation.removeSubviewsFromContainerWithID(containerTag);
}
/**
* Determines the location on screen, width, and height of the given view and returns the values
* via an async callback.
*/
@ReactMethod
public void measure(int reactTag, Callback callback) {
mUIImplementation.measure(reactTag, callback);
}
/**
* Determines the location on screen, width, and height of the given view relative to the device
* screen and returns the values via an async callback. This is the absolute position including
* things like the status bar
*/
@ReactMethod
public void measureInWindow(int reactTag, Callback callback) {
mUIImplementation.measureInWindow(reactTag, callback);
}
/**
* Measures the view specified by tag relative to the given ancestorTag. This means that the
* returned x, y are relative to the origin x, y of the ancestor view. Results are stored in the
* given outputBuffer. We allow ancestor view and measured view to be the same, in which case
* the position always will be (0, 0) and method will only measure the view dimensions.
*
* NB: Unlike {@link #measure}, this will measure relative to the view layout, not the visible
* window which can cause unexpected results when measuring relative to things like ScrollViews
* that can have offset content on the screen.
*/
@ReactMethod
public void measureLayout(
int tag,
int ancestorTag,
Callback errorCallback,
Callback successCallback) {
mUIImplementation.measureLayout(tag, ancestorTag, errorCallback, successCallback);
}
/**
* Like {@link #measure} and {@link #measureLayout} but measures relative to the immediate parent.
*
* NB: Unlike {@link #measure}, this will measure relative to the view layout, not the visible
* window which can cause unexpected results when measuring relative to things like ScrollViews
* that can have offset content on the screen.
*/
@ReactMethod
public void measureLayoutRelativeToParent(
int tag,
Callback errorCallback,
Callback successCallback) {
mUIImplementation.measureLayoutRelativeToParent(tag, errorCallback, successCallback);
}
/**
* Find the touch target child native view in the supplied root view hierarchy, given a react
* target location.
*
* This method is currently used only by Element Inspector DevTool.
*
* @param reactTag the tag of the root view to traverse
* @param point an array containing both X and Y target location
* @param callback will be called if with the identified child view react ID, and measurement
* info. If no view was found, callback will be invoked with no data.
*/
@ReactMethod
public void findSubviewIn(
final int reactTag,
final ReadableArray point,
final Callback callback) {
mUIImplementation.findSubviewIn(
reactTag,
Math.round(PixelUtil.toPixelFromDIP(point.getDouble(0))),
Math.round(PixelUtil.toPixelFromDIP(point.getDouble(1))),
callback);
}
/**
* Registers a new Animation that can then be added to a View using {@link #addAnimation}.
*/
public void registerAnimation(Animation animation) {
mUIImplementation.registerAnimation(animation);
}
/**
* Adds an Animation previously registered with {@link #registerAnimation} to a View and starts it
*/
public void addAnimation(int reactTag, int animationID, Callback onSuccess) {
mUIImplementation.addAnimation(reactTag, animationID, onSuccess);
}
/**
* Removes an existing Animation, canceling it if it was in progress.
*/
public void removeAnimation(int reactTag, int animationID) {
mUIImplementation.removeAnimation(reactTag, animationID);
}
@ReactMethod
public void setJSResponder(int reactTag, boolean blockNativeResponder) {
mUIImplementation.setJSResponder(reactTag, blockNativeResponder);
}
@ReactMethod
public void clearJSResponder() {
mUIImplementation.clearJSResponder();
}
@ReactMethod
public void dispatchViewManagerCommand(int reactTag, int commandId, ReadableArray commandArgs) {
mUIImplementation.dispatchViewManagerCommand(reactTag, commandId, commandArgs);
}
/**
* Show a PopupMenu.
*
* @param reactTag the tag of the anchor view (the PopupMenu is displayed next to this view); this
* needs to be the tag of a native view (shadow views can not be anchors)
* @param items the menu items as an array of strings
* @param error will be called if there is an error displaying the menu
* @param success will be called with the position of the selected item as the first argument, or
* no arguments if the menu is dismissed
*/
@ReactMethod
public void showPopupMenu(int reactTag, ReadableArray items, Callback error, Callback success) {
mUIImplementation.showPopupMenu(reactTag, items, error, success);
}
/**
* LayoutAnimation API on Android is currently experimental. Therefore, it needs to be enabled
* explicitly in order to avoid regression in existing application written for iOS using this API.
*
* Warning : This method will be removed in future version of React Native, and layout animation
* will be enabled by default, so always check for its existence before invoking it.
*
* TODO(9139831) : remove this method once layout animation is fully stable.
*
* @param enabled whether layout animation is enabled or not
*/
@ReactMethod
public void setLayoutAnimationEnabledExperimental(boolean enabled) {
mUIImplementation.setLayoutAnimationEnabledExperimental(enabled);
}
/**
* Configure an animation to be used for the native layout changes, and native views
* creation. The animation will only apply during the current batch operations.
*
* TODO(7728153) : animating view deletion is currently not supported.
* TODO(7613721) : callbacks are not supported, this feature will likely be killed.
*
* @param config the configuration of the animation for view addition/removal/update.
* @param success will be called when the animation completes, or when the animation get
* interrupted. In this case, callback parameter will be false.
* @param error will be called if there was an error processing the animation
*/
@ReactMethod
public void configureNextLayoutAnimation(
ReadableMap config,
Callback success,
Callback error) {
mUIImplementation.configureNextLayoutAnimation(config, success, error);
}
/**
* To implement the transactional requirement mentioned in the class javadoc, we only commit
* UI changes to the actual view hierarchy once a batch of JS->Java calls have been completed.
* We know this is safe because all JS->Java calls that are triggered by a Java->JS call (e.g.
* the delivery of a touch event or execution of 'renderApplication') end up in a single
* JS->Java transaction.
*
* A better way to do this would be to have JS explicitly signal to this module when a UI
* transaction is done. Right now, though, this is how iOS does it, and we should probably
* update the JS and native code and make this change at the same time.
*
* TODO(5279396): Make JS UI library explicitly notify the native UI module of the end of a UI
* transaction using a standard native call
*/
@Override
public void onBatchComplete() {
int batchId = mBatchId;
mBatchId++;
SystraceMessage.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "onBatchCompleteUI")
.arg("BatchId", batchId)
.flush();
try {
mUIImplementation.dispatchViewUpdates(mEventDispatcher, batchId);
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
}
}
public void setViewHierarchyUpdateDebugListener(
@Nullable NotThreadSafeViewHierarchyUpdateDebugListener listener) {
mUIImplementation.setViewHierarchyUpdateDebugListener(listener);
}
public EventDispatcher getEventDispatcher() {
return mEventDispatcher;
}
@ReactMethod
public void sendAccessibilityEvent(int tag, int eventType) {
mUIImplementation.sendAccessibilityEvent(tag, eventType);
}
/**
* Schedule a block to be executed on the UI thread. Useful if you need to execute
* view logic after all currently queued view updates have completed.
*
* @param block that contains UI logic you want to execute.
*
* Usage Example:
UIManagerModule uiManager = reactContext.getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock() {
public void execute (NativeViewHierarchyManager nvhm) {
View view = nvhm.resolveView(tag);
// ...execute your code on View (e.g. snapshot the view)
}
});
*/
public void addUIBlock (UIBlock block) {
mUIImplementation.addUIBlock(block);
}
}
| {'content_hash': '8b23600f90f69274227dbaab723ce175', 'timestamp': '', 'source': 'github', 'line_count': 512, 'max_line_length': 103, 'avg_line_length': 37.2734375, 'alnum_prop': 0.7215468455250471, 'repo_name': 'jhen0409/react-native', 'id': 'b04af822a124cb5ea7448eab5444b1acbce45a08', 'size': '19392', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '15592'}, {'name': 'Awk', 'bytes': '121'}, {'name': 'Batchfile', 'bytes': '683'}, {'name': 'C', 'bytes': '95667'}, {'name': 'C++', 'bytes': '682770'}, {'name': 'CSS', 'bytes': '26033'}, {'name': 'HTML', 'bytes': '27644'}, {'name': 'IDL', 'bytes': '897'}, {'name': 'Java', 'bytes': '2268189'}, {'name': 'JavaScript', 'bytes': '2068600'}, {'name': 'Makefile', 'bytes': '7590'}, {'name': 'Objective-C', 'bytes': '1326721'}, {'name': 'Objective-C++', 'bytes': '49548'}, {'name': 'Prolog', 'bytes': '287'}, {'name': 'Python', 'bytes': '112223'}, {'name': 'Ruby', 'bytes': '4799'}, {'name': 'Shell', 'bytes': '16434'}]} |
<?php
class StringUtils {
/**
* Determine if a given string starts with a given substring.
* Ripped from: https://github.com/laravel/framework/blob/4.2/src/Illuminate/Support/Str.php
*
* @param string $haystack
* @param string|array $needles
* @return bool
*/
public static function startsWith($haystack, $needles) {
foreach ((array) $needles as $needle) {
if ($needle != '' && strpos($haystack, $needle) === 0) return true;
}
return false;
}
}
?> | {'content_hash': '3d0e414f6a58e430036a830f69f03e2e', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 94, 'avg_line_length': 26.157894736842106, 'alnum_prop': 0.6297786720321932, 'repo_name': 'daniloarcidiacono/DebtJS', 'id': '4f84cce76270505d5ed13936b7b6b335c87dd13e', 'size': '497', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/pastebin/utils/stringutils.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2212'}, {'name': 'HTML', 'bytes': '14726'}, {'name': 'JavaScript', 'bytes': '17812'}, {'name': 'PHP', 'bytes': '15273'}]} |
package org.onosproject.net.behaviour;
import org.onosproject.net.DeviceId;
import org.onosproject.net.driver.HandlerBehaviour;
import org.onosproject.net.flowobjective.FilteringObjective;
import org.onosproject.net.flowobjective.ForwardingObjective;
import org.onosproject.net.flowobjective.NextObjective;
/**
* Behaviour for handling various pipelines.
*/
public interface Pipeliner extends HandlerBehaviour {
/**
* Initializes the driver with context required for its operation.
*
* @param deviceId the deviceId
* @param context processing context
*/
void init(DeviceId deviceId, PipelinerContext context);
/**
* Installs the filtering rules onto the device.
*
* @param filterObjective a filtering objective
*/
void filter(FilteringObjective filterObjective);
/**
* Installs the forwarding rules onto the device.
*
* @param forwardObjective a forwarding objective
*/
void forward(ForwardingObjective forwardObjective);
/**
* Installs the next hop elements into the device.
*
* @param nextObjective a next objectives
*/
void next(NextObjective nextObjective);
}
| {'content_hash': 'f333aef92887e8281278911b7fd1e8e7', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 70, 'avg_line_length': 27.697674418604652, 'alnum_prop': 0.7187237615449202, 'repo_name': 'maxkondr/onos-porta', 'id': 'dcfc5883a180fc7d42b4e3f48c0e73384c6cedbb', 'size': '1800', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'core/api/src/main/java/org/onosproject/net/behaviour/Pipeliner.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '63319'}, {'name': 'HTML', 'bytes': '451426'}, {'name': 'Java', 'bytes': '8510815'}, {'name': 'JavaScript', 'bytes': '583410'}, {'name': 'Shell', 'bytes': '2625'}]} |
package no.ntnu.assignmentsystem.services.akka.mapping;
import java.util.ArrayList;
import java.util.List;
import no.ntnu.assignmentsystem.editor.akka.messages.PluginRunTestsResult;
import no.ntnu.assignmentsystem.editor.akka.messages.PluginTestResult;
import no.ntnu.assignmentsystem.services.akka.messages.RunTestsResult;
import no.ntnu.assignmentsystem.services.akka.messages.TestResult;
public class RunTestsResultMapper {
public static RunTestsResult createRunTestsResult(PluginRunTestsResult pluginRunTestsResult) {
List<TestResult> testResults = new ArrayList<TestResult>();
for (PluginTestResult pluginTestResult : pluginRunTestsResult.testResults) {
testResults.add(createTestResult(pluginTestResult));
}
return new RunTestsResult(testResults);
}
// --- Private methods ---
private static TestResult createTestResult(PluginTestResult pluginTestResult) {
String methodName = pluginTestResult.methodName;
TestResult.Status status = createTestResultStatus(pluginTestResult.status);
return new TestResult(methodName, status);
}
private static TestResult.Status createTestResultStatus(PluginTestResult.Status status) {
switch (status) {
case OK:
return TestResult.Status.OK;
case Ignored:
return TestResult.Status.Ignored;
default:
return TestResult.Status.Failed;
}
}
}
| {'content_hash': '90cf710ef793108c2b6b2d73797ec1a1', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 95, 'avg_line_length': 32.5609756097561, 'alnum_prop': 0.802247191011236, 'repo_name': 'chrrasmussen/NTNU-Master-Project', 'id': '968420d0bed7468d331f97b9fd733e3d659309db', 'size': '1335', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'no.ntnu.assignmentsystem.model/src/no/ntnu/assignmentsystem/services/akka/mapping/RunTestsResultMapper.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '71143'}, {'name': 'Java', 'bytes': '85928'}, {'name': 'JavaScript', 'bytes': '10709'}, {'name': 'Scala', 'bytes': '1259'}]} |
<html><body><p><!-- saved from url=(0024)http://docs.autodesk.com -->
<!DOCTYPE html>
<!-- Mirrored from help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/PyMel/generated/functions/pymel.util.arrays/pymel.util.arrays.erfc.html by HTTrack Website Copier/3.x [XR&CO'2014], Sat, 01 Aug 2015 05:27:25 GMT -->
<!-- Added by HTTrack --><meta content="text/html;charset=utf-8" http-equiv="content-type"/><!-- /Added by HTTrack -->
</p>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>pymel.util.arrays.erfc — PyMEL 1.0.7 documentation</title>
<link href="../../../_static/nature.css" rel="stylesheet" type="text/css"/>
<link href="../../../_static/pygments.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../../../',
VERSION: '1.0.7',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script src="../../../_static/jquery.js" type="text/javascript"></script>
<script src="../../../_static/underscore.js" type="text/javascript"></script>
<script src="../../../_static/doctools.js" type="text/javascript"></script>
<link href="../../../index-2.html" rel="top" title="PyMEL 1.0.7 documentation"/>
<link href="../../pymel.util.arrays.html" rel="up" title="pymel.util.arrays"/>
<link href="pymel.util.arrays.exp.html" rel="next" title="pymel.util.arrays.exp"/>
<link href="pymel.util.arrays.erf.html" rel="prev" title="pymel.util.arrays.erf"/>
<link href="../../../../style/adsk.cpm.css" rel="stylesheet" type="text/css"/><meta content="expert" name="experiencelevel"/><meta content="programmer" name="audience"/><meta content="enable" name="user-comments"/><meta content="ENU" name="language"/><meta content="MAYAUL" name="product"/><meta content="2016" name="release"/><meta content="Customization" name="book"/><meta content="Maya-Tech-Docs" name="component"/><meta content="/view/MAYAUL/2016/ENU/" name="helpsystempath"/><meta content="04/03/2015" name="created"/><meta content="04/03/2015" name="modified"/><meta content="Navigation
index
modules |
next |
previous |
PyMEL 1.0.7 documentation »
pymel.util.arrays »
pymel.util.arrays.erfc ¶
erfc ( x ) ¶
Complementary error function at x.
This function has been overriden from math.erfc to work element-wise on iterables
Previous topic
pymel.util.arrays.erf
Next topic
pymel.util.arrays.exp
Core Modules
animation
effects
general
language
modeling
rendering..." name="description"/><meta content="__PyMel_generated_functions_pymel_util_arrays_pymel_util_arrays_erfc_html" name="topicid"/>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a accesskey="I" href="../../../genindex.html" title="General Index">index</a></li>
<li class="right">
<a href="../../../py-modindex.html" title="Python Module Index">modules</a> |</li>
<li class="right">
<a accesskey="N" href="pymel.util.arrays.exp.html" title="pymel.util.arrays.exp">next</a> |</li>
<li class="right">
<a accesskey="P" href="pymel.util.arrays.erf.html" title="pymel.util.arrays.erf">previous</a> |</li>
<li><a href="../../../index-2.html">PyMEL 1.0.7 documentation</a> »</li>
<li><a accesskey="U" href="../../pymel.util.arrays.html">pymel.util.arrays</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="pymel-util-arrays-erfc">
<h1>pymel.util.arrays.erfc<a class="headerlink" href="#pymel-util-arrays-erfc" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="pymel.util.arrays.erfc"><a name="//apple_ref/cpp/Function/pymel.util.arrays.erfc"></a>
<tt class="descname">erfc</tt><big>(</big><em>x</em><big>)</big><a class="headerlink" href="#pymel.util.arrays.erfc" title="Permalink to this definition">¶</a></dt>
<dd><p>Complementary error function at x.
This function has been overriden from math.erfc to work element-wise on iterables</p>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="pymel.util.arrays.erf.html" title="previous chapter">pymel.util.arrays.erf</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="pymel.util.arrays.exp.html" title="next chapter">pymel.util.arrays.exp</a></p>
<h3><a href="../../../modules.html">Core Modules</a></h3>
<ul>
<li><a class="reference external" href="../../pymel.core.animation.html#module-pymel.core.animation"><tt class="xref">animation</tt></a></li>
<li><a class="reference external" href="../../pymel.core.effects.html#module-pymel.core.effects"><tt class="xref">effects</tt></a></li>
<li><a class="reference external" href="../../pymel.core.general.html#module-pymel.core.general"><tt class="xref">general</tt></a></li>
<li><a class="reference external" href="../../pymel.core.language.html#module-pymel.core.language"><tt class="xref">language</tt></a></li>
<li><a class="reference external" href="../../pymel.core.modeling.html#module-pymel.core.modeling"><tt class="xref">modeling</tt></a></li>
<li><a class="reference external" href="../../pymel.core.rendering.html#module-pymel.core.rendering"><tt class="xref">rendering</tt></a></li>
<li><a class="reference external" href="../../pymel.core.system.html#module-pymel.core.system"><tt class="xref">system</tt></a></li>
<li><a class="reference external" href="../../pymel.core.windows.html#module-pymel.core.windows"><tt class="xref">windows</tt></a></li>
</ul>
<h3><a href="../../../modules.html">Type Modules</a></h3>
<ul>
<li><a class="reference external" href="../../pymel.core.datatypes.html#module-pymel.core.datatypes"><tt class="xref">datatypes</tt></a></li>
<li><a class="reference external" href="../../pymel.core.nodetypes.html#module-pymel.core.nodetypes"><tt class="xref">nodetypes</tt></a></li>
<li><a class="reference external" href="../../pymel.core.uitypes.html#module-pymel.core.uitypes"><tt class="xref">uitypes</tt></a></li>
</ul>
<h3><a href="../../../modules.html">Other Modules</a></h3>
<ul>
<li><a class="reference external" href="../../pymel.api.plugins.html#module-pymel.api.plugins"><tt class="xref">plugins</tt></a></li>
<li><a class="reference external" href="../../pymel.mayautils.html#module-pymel.mayautils"><tt class="xref">mayautils</tt></a></li>
<li><a class="reference external" href="../../pymel.util.html#module-pymel.util"><tt class="xref">util</tt></a></li>
<li><a class="reference external" href="../../pymel.versions.html#module-pymel.versions"><tt class="xref">versions</tt></a>
</li><li><a class="reference external" href="../../pymel.tools.html#module-pymel.tools"><tt class="xref">tools</tt></a></li>
</ul>
<!--
<ul>
<li><a class="reference external" href="../../pymel.core.animation.html.html#module-pymel.core.animation"><tt class="xref">animation</tt></a></li>
<li><a class="reference external" href="../../pymel.core.datatypes.html.html#module-pymel.core.datatypes"><tt class="xref">datatypes</tt></a></li>
<li><a class="reference external" href="../../pymel.core.effects.html.html#module-pymel.core.effects"><tt class="xref">effects</tt></a></li>
<li><a class="reference external" href="../../pymel.core.general.html.html#module-pymel.core.general"><tt class="xref">general</tt></a></li>
<li><a class="reference external" href="../../pymel.core.language.html.html#module-pymel.core.language"><tt class="xref">language</tt></a></li>
<li><a class="reference external" href="../../pymel.core.modeling.html.html#module-pymel.core.modeling"><tt class="xref">modeling</tt></a></li>
<li><a class="reference external" href="../../pymel.core.nodetypes.html.html#module-pymel.core.nodetypes"><tt class="xref">nodetypes</tt></a></li>
<li><a class="reference external" href="../../pymel.core.rendering.html.html#module-pymel.core.rendering"><tt class="xref">rendering</tt></a></li>
<li><a class="reference external" href="../../pymel.core.system.html.html#module-pymel.core.system"><tt class="xref">system</tt></a></li>
<li><a class="reference external" href="../../pymel.core.windows.html.html#module-pymel.core.windows"><tt class="xref">windows</tt></a></li>
<li><a class="reference external" href="../../pymel.util.html.html#module-pymel.util"><tt class="xref">pymel.util</tt></a></li>
</ul>
-->
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../../../_sources/generated/functions/pymel.util.arrays/pymel.util.arrays.erfc.txt" rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form action="http://help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/PyMel/search.html" class="search" method="get"></form>
<input name="q" type="text"/>
<input type="submit" value="Go"/>
<input name="check_keywords" type="hidden" value="yes"/>
<input name="area" type="hidden" value="default"/>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../../genindex.html" title="General Index">index</a></li>
<li class="right">
<a href="../../../py-modindex.html" title="Python Module Index">modules</a> |</li>
<li class="right">
<a href="pymel.util.arrays.exp.html" title="pymel.util.arrays.exp">next</a> |</li>
<li class="right">
<a href="pymel.util.arrays.erf.html" title="pymel.util.arrays.erf">previous</a> |</li>
<li><a href="../../../index-2.html">PyMEL 1.0.7 documentation</a> »</li>
<li><a href="../../pymel.util.arrays.html">pymel.util.arrays</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2009, Chad Dombrova.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.3.
</div>
<!-- Mirrored from help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/PyMel/generated/functions/pymel.util.arrays/pymel.util.arrays.erfc.html by HTTrack Website Copier/3.x [XR&CO'2014], Sat, 01 Aug 2015 05:27:25 GMT -->
</body></html> | {'content_hash': 'a61430eebadc64a8b2549253b3a3cdf4', 'timestamp': '', 'source': 'github', 'line_count': 196, 'max_line_length': 594, 'avg_line_length': 52.025510204081634, 'alnum_prop': 0.674217907227616, 'repo_name': 'alexwidener/PyMelDocset', 'id': '331de3923112ddde7d553dfdde5c8272a64a04ca', 'size': '10212', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'PyMel.docset/Contents/Resources/Documents/generated/functions/pymel.util.arrays/pymel.util.arrays.erfc.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '16618'}, {'name': 'HTML', 'bytes': '97827047'}, {'name': 'JavaScript', 'bytes': '24674'}]} |
import './main';
| {'content_hash': 'd27356bf3384cbafe1a376150ee18efb', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 16, 'avg_line_length': 17.0, 'alnum_prop': 0.5882352941176471, 'repo_name': 'shimohq/react-native-prompt-android', 'id': 'ce898782081ba191357e1c034a15f7bcb7b86152', 'size': '17', 'binary': False, 'copies': '33', 'ref': 'refs/heads/master', 'path': 'Example/index.android.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '17834'}, {'name': 'JavaScript', 'bytes': '9538'}, {'name': 'Objective-C', 'bytes': '4413'}, {'name': 'Python', 'bytes': '1651'}, {'name': 'Shell', 'bytes': '166'}]} |
package ca.uhn.fhir.rest.server;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.hl7.fhir.dstu3.model.HumanName;
import org.hl7.fhir.dstu3.model.Organization;
import org.hl7.fhir.dstu3.model.Patient;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.Include;
import ca.uhn.fhir.rest.annotation.IncludeParam;
import ca.uhn.fhir.rest.annotation.RequiredParam;
import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.util.PortUtil;
import ca.uhn.fhir.util.TestUtil;
public class SearchWithIncludesDstu3Test {
private static CloseableHttpClient ourClient;
private static FhirContext ourCtx = FhirContext.forDstu3();
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SearchWithIncludesDstu3Test.class);
private static int ourPort;
private static Server ourServer;
@Test
public void testSearchIncludesReferences() throws Exception {
HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_pretty=true&_include=Patient:organization&_include=Organization:" + Organization.SP_PARTOF);
HttpResponse status = ourClient.execute(httpGet);
String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8);
IOUtils.closeQuietly(status.getEntity().getContent());
ourLog.info(responseContent);
assertEquals(200, status.getStatusLine().getStatusCode());
// Response should include both the patient, and the organization that was referred to
// by a linked resource
assertThat(responseContent, containsString("<name value=\"child\"/>"));
assertThat(responseContent, containsString("<name value=\"parent\"/>"));
assertThat(responseContent, containsString("<name value=\"grandparent\"/>"));
assertThat(responseContent, containsString("<mode value=\"include\"/>"));
}
@AfterClass
public static void afterClassClearContext() throws Exception {
ourServer.stop();
TestUtil.clearAllStaticFieldsForUnitTest();
}
@BeforeClass
public static void beforeClass() throws Exception {
ourPort = PortUtil.findFreePort();
ourServer = new Server(ourPort);
DummyPatientResourceProvider patientProvider = new DummyPatientResourceProvider();
ServletHandler proxyHandler = new ServletHandler();
RestfulServer servlet = new RestfulServer(ourCtx);
servlet.setPagingProvider(new FifoMemoryPagingProvider(10));
servlet.setResourceProviders(patientProvider);
ServletHolder servletHolder = new ServletHolder(servlet);
proxyHandler.addServletWithMapping(servletHolder, "/*");
ourServer.setHandler(proxyHandler);
ourServer.start();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS);
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setConnectionManager(connectionManager);
ourClient = builder.build();
}
public static class DummyPatientResourceProvider implements IResourceProvider {
@Override
public Class<? extends IBaseResource> getResourceType() {
return Patient.class;
}
//@formatter:off
@Search()
public List<Patient> search(@IncludeParam() Set<Include> theIncludes) {
ourLog.info("Includes: {}", theIncludes);
// Grandparent has ID, other orgs don't
Organization gp = new Organization();
gp.setId("Organization/GP");
gp.setName("grandparent");
Organization parent = new Organization();
parent.setName("parent");
parent.getPartOf().setResource(gp);
Organization child = new Organization();
child.setName("child");
child.getPartOf().setResource(parent);
Patient patient = new Patient();
patient.setId("Patient/FOO");
patient.getManagingOrganization().setResource(child);
ArrayList<Patient> retVal = new ArrayList<Patient>();
retVal.add(patient);
return retVal;
}
//@formatter:on
}
}
| {'content_hash': 'a82d86132c1871fac5e898c9718f7f6d', 'timestamp': '', 'source': 'github', 'line_count': 138, 'max_line_length': 167, 'avg_line_length': 34.31159420289855, 'alnum_prop': 0.7759239704329461, 'repo_name': 'botunge/hapi-fhir', 'id': '195f7b8cc9880b60fcaea052e0a7b3a52302215a', 'size': '4735', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/rest/server/SearchWithIncludesDstu3Test.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '3861'}, {'name': 'CSS', 'bytes': '228170'}, {'name': 'HTML', 'bytes': '208718'}, {'name': 'Java', 'bytes': '40432052'}, {'name': 'JavaScript', 'bytes': '23712'}, {'name': 'Ruby', 'bytes': '238454'}, {'name': 'Shell', 'bytes': '35414'}]} |
package org.apache.ignite.internal.processors.hadoop.impl.igfs;
import org.apache.ignite.igfs.IgfsMode;
/**
* IGFS Hadoop file system Ignite client -based self test for DUAL_SYNC mode.
*/
public class IgniteHadoopFileSystemClientBasedDualSyncSelfTest
extends IgniteHadoopFileSystemClientBasedAbstractSelfTest {
/**
* Constructor.
*/
public IgniteHadoopFileSystemClientBasedDualSyncSelfTest() {
super(IgfsMode.DUAL_SYNC);
}
/** {@inheritDoc} */
@Override protected String getClientConfig() {
return "modules/hadoop/src/test/config/igfs-cli-config-dual-sync.xml";
}
} | {'content_hash': 'e5bbff0a61d28d81f26b2480b26694db', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 78, 'avg_line_length': 27.217391304347824, 'alnum_prop': 0.7252396166134185, 'repo_name': 'nivanov/ignite', 'id': 'c7e97d761a7ccbe920ffa81295f1e6c2d277b15d', 'size': '1428', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'modules/hadoop/src/test/java/org/apache/ignite/internal/processors/hadoop/impl/igfs/IgniteHadoopFileSystemClientBasedDualSyncSelfTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '37548'}, {'name': 'C', 'bytes': '5286'}, {'name': 'C#', 'bytes': '4772806'}, {'name': 'C++', 'bytes': '2506272'}, {'name': 'CSS', 'bytes': '134061'}, {'name': 'Groovy', 'bytes': '15092'}, {'name': 'HTML', 'bytes': '515192'}, {'name': 'Java', 'bytes': '27293772'}, {'name': 'JavaScript', 'bytes': '1116197'}, {'name': 'M4', 'bytes': '5568'}, {'name': 'Makefile', 'bytes': '104025'}, {'name': 'Nginx', 'bytes': '3468'}, {'name': 'PHP', 'bytes': '11079'}, {'name': 'PowerShell', 'bytes': '13480'}, {'name': 'Scala', 'bytes': '683756'}, {'name': 'Shell', 'bytes': '586711'}, {'name': 'Smalltalk', 'bytes': '1908'}]} |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Roslyn.Utilities;
using Cci = Microsoft.Cci;
using Microsoft.CodeAnalysis.Emit;
namespace Microsoft.CodeAnalysis.Scripting.Emit
{
internal static class CommonCompilationExtensions
{
/// <summary>
/// Emits the compilation into given <see cref="ModuleBuilder"/> using Reflection.Emit APIs.
/// </summary>
/// <param name="compilation">Compilation.</param>
/// <param name="moduleBuilder">
/// The module builder to add the types into. Can be reused for multiple compilation units.
/// </param>
/// <param name="assemblyLoader">
/// Loads an assembly given an <see cref="AssemblyIdentity"/>.
/// This callback is used for loading assemblies referenced by the compilation.
/// <see cref="System.Reflection.Assembly.Load(AssemblyName)"/> is used if not specified.
/// </param>
/// <param name="assemblySymbolMapper">
/// Applied when converting assembly symbols to assembly references.
/// <see cref="IAssemblySymbol"/> is mapped to its <see cref="IAssemblySymbol.Identity"/> by default.
/// </param>
/// <param name="cancellationToken">Can be used to cancel the emit process.</param>
/// <param name="recoverOnError">If false the method returns an unsuccessful result instead of falling back to CCI writer.</param>
/// <param name="compiledAssemblyImage">Assembly image, returned only if we fallback to CCI writer.</param>
/// <param name="entryPoint">An entry point or null if not applicable or on failure.</param>
/// <param name="diagnostics">Diagnostics.</param>
/// <returns>True on success, false if a compilation error occurred or the compilation doesn't contain any code or declarations.</returns>
/// <remarks>
/// Reflection.Emit doesn't support all metadata constructs. If an unsupported construct is
/// encountered a metadata writer that procudes uncollectible code is used instead. This is
/// indicated by
/// <see cref="ReflectionEmitResult.IsUncollectible"/> flag on the result.
///
/// Reusing <see cref="System.Reflection.Emit.ModuleBuilder"/> may be beneficial in certain
/// scenarios. For example, when emitting a sequence of code snippets one at a time (like in
/// REPL). All the snippets can be compiled into a single module as long as the types being
/// emitted have unique names. Reusing a single module/assembly reduces memory overhead. On
/// the other hand, collectible assemblies are units of collection. Defining too many
/// unrelated types in a single assemly might prevent the unused types to be collected.
///
/// No need to provide a name override when using Reflection.Emit, since the assembly already
/// exists.
/// </remarks>
/// <exception cref="InvalidOperationException">Referenced assembly can't be resolved.</exception>
internal static bool Emit(
this Compilation compilation,
ModuleBuilder moduleBuilder,
AssemblyLoader assemblyLoader,
Func<IAssemblySymbol, AssemblyIdentity> assemblySymbolMapper,
bool recoverOnError,
DiagnosticBag diagnostics,
CancellationToken cancellationToken,
out MethodInfo entryPoint,
out byte[] compiledAssemblyImage)
{
compiledAssemblyImage = default(byte[]);
var moduleBeingBuilt = compilation.CreateModuleBuilder(
emitOptions: EmitOptions.Default,
manifestResources: null,
assemblySymbolMapper: assemblySymbolMapper,
testData: null,
diagnostics: diagnostics,
cancellationToken: cancellationToken);
if (moduleBeingBuilt == null)
{
entryPoint = null;
return false;
}
if (!compilation.Compile(
moduleBeingBuilt,
win32Resources: null,
xmlDocStream: null,
generateDebugInfo: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: cancellationToken))
{
entryPoint = null;
return false;
}
Cci.IMethodReference cciEntryPoint = moduleBeingBuilt.EntryPoint;
cancellationToken.ThrowIfCancellationRequested();
DiagnosticBag metadataDiagnostics = DiagnosticBag.GetInstance();
var context = new EmitContext((Cci.IModule)moduleBeingBuilt, null, metadataDiagnostics);
// try emit via Reflection.Emit
try
{
var referencedAssemblies = from referencedAssembly in compilation.GetBoundReferenceManager().GetReferencedAssemblies()
let peReference = referencedAssembly.Key as PortableExecutableReference
select KeyValuePair.Create(
moduleBeingBuilt.Translate(referencedAssembly.Value, metadataDiagnostics),
(peReference != null) ? peReference.FilePath : null);
entryPoint = ReflectionEmitter.Emit(
context,
referencedAssemblies,
moduleBuilder,
assemblyLoader ?? AssemblyLoader.Default,
cciEntryPoint,
cancellationToken);
// translate metadata errors.
return compilation.FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics);
}
catch (TypeLoadException)
{
// attempted to emit reference to a type that can't be loaded (has invalid metadata)
}
catch (NotSupportedException)
{
// nop
}
// TODO (tomat):
//
// Another possible approach would be to just return an error, that we can't emit via
// Ref.Emit and let the user choose another method of emitting. For that we would want
// to preserve the state of the Emit.Assembly object with all the compiled methods so
// that the subsequent emit doesn't need to compile method bodies again.
// TODO (tomat):
//
// If Ref.Emit fails to emit the code the type builders already created will stay
// defined on the module builder. Ideally we would clean them up but Ref.Emit doesn't
// provide any API to do so. In fact it also keeps baked TypeBuilders alive as well.
if (!recoverOnError)
{
metadataDiagnostics.Free();
entryPoint = null;
return false;
}
using (var stream = new System.IO.MemoryStream())
{
Cci.PeWriter.WritePeToStream(
context,
compilation.MessageProvider,
() => stream,
nativePdbWriterOpt: null,
pdbPathOpt: null,
allowMissingMethodBodies: false,
deterministic: false,
cancellationToken: cancellationToken);
compiledAssemblyImage = stream.ToArray();
}
var compiledAssembly = Assembly.Load(compiledAssemblyImage);
entryPoint = (cciEntryPoint != null) ? ReflectionEmitter.ResolveEntryPoint(compiledAssembly, cciEntryPoint, context) : null;
// translate metadata errors.
return compilation.FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics);
}
}
}
| {'content_hash': '6ad288f688f2d45424c20550cda05c1f', 'timestamp': '', 'source': 'github', 'line_count': 175, 'max_line_length': 161, 'avg_line_length': 46.98285714285714, 'alnum_prop': 0.6049622962782778, 'repo_name': 'dsplaisted/roslyn', 'id': '20f03163ed3be8146589be53d72bbd7cf867dffa', 'size': '8224', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'src/Scripting/Core/Emit/CommonCompilationExtensions.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '71036295'}, {'name': 'C++', 'bytes': '2298'}, {'name': 'F#', 'bytes': '421'}, {'name': 'PowerShell', 'bytes': '801'}, {'name': 'Shell', 'bytes': '13287'}, {'name': 'Visual Basic', 'bytes': '57620708'}]} |
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
class Sample {
List<String> foo = new ArrayList<>();
{
foo.stream().filter(Objects::isNull).forEach(s -> {
return;
});
}
} | {'content_hash': 'ca367ce5f277d668305ce7737999fd7d', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 57, 'avg_line_length': 17.615384615384617, 'alnum_prop': 0.611353711790393, 'repo_name': 'google/intellij-community', 'id': '0af36577938b9f26cb492f7d06a7d18e30da731a', 'size': '270', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/continue/afterContinueInside.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/mod/quiz/report/attemptsreport.php');
require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_options.php');
require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_form.php');
require_once($CFG->dirroot . '/mod/quiz/report/overview/overview_table.php');
/**
* Quiz report subclass for the overview (grades) report.
*
* @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class quiz_overview_report extends quiz_attempts_report {
public function display($quiz, $cm, $course) {
global $CFG, $DB, $OUTPUT, $PAGE;
list($currentgroup, $students, $groupstudents, $allowed) =
$this->init('overview', 'quiz_overview_settings_form', $quiz, $cm, $course);
$options = new quiz_overview_options('overview', $quiz, $cm, $course);
if ($fromform = $this->form->get_data()) {
$options->process_settings_from_form($fromform);
} else {
$options->process_settings_from_params();
}
$this->form->set_data($options->get_initial_form_data());
if ($options->attempts == self::ALL_WITH) {
// This option is only available to users who can access all groups in
// groups mode, so setting allowed to empty (which means all quiz attempts
// are accessible, is not a security porblem.
$allowed = array();
}
// Load the required questions.
$questions = quiz_report_get_significant_questions($quiz);
// Prepare for downloading, if applicable.
$courseshortname = format_string($course->shortname, true,
array('context' => context_course::instance($course->id)));
$table = new quiz_overview_table($quiz, $this->context, $this->qmsubselect,
$options, $groupstudents, $students, $questions, $options->get_url());
$filename = quiz_report_download_filename(get_string('overviewfilename', 'quiz_overview'),
$courseshortname, $quiz->name);
$table->is_downloading($options->download, $filename,
$courseshortname . ' ' . format_string($quiz->name, true));
if ($table->is_downloading()) {
raise_memory_limit(MEMORY_EXTRA);
}
$this->course = $course; // Hack to make this available in process_actions.
$this->process_actions($quiz, $cm, $currentgroup, $groupstudents, $allowed, $options->get_url());
// Start output.
if (!$table->is_downloading()) {
// Only print headers if not asked to download data.
$this->print_header_and_tabs($cm, $course, $quiz, $this->mode);
}
if ($groupmode = groups_get_activity_groupmode($cm)) {
// Groups are being used, so output the group selector if we are not downloading.
if (!$table->is_downloading()) {
groups_print_activity_menu($cm, $options->get_url());
}
}
// Print information on the number of existing attempts.
if (!$table->is_downloading()) {
// Do not print notices when downloading.
if ($strattemptnum = quiz_num_attempt_summary($quiz, $cm, true, $currentgroup)) {
echo '<div class="quizattemptcounts">' . $strattemptnum . '</div>';
}
}
$hasquestions = quiz_questions_in_quiz($quiz->questions);
if (!$table->is_downloading()) {
if (!$hasquestions) {
echo quiz_no_questions_message($quiz, $cm, $this->context);
} else if (!$students) {
echo $OUTPUT->notification(get_string('nostudentsyet'));
} else if ($currentgroup && !$groupstudents) {
echo $OUTPUT->notification(get_string('nostudentsingroup'));
}
// Print the display options.
$this->form->display();
}
$hasstudents = $students && (!$currentgroup || $groupstudents);
if ($hasquestions && ($hasstudents || $options->attempts == self::ALL_WITH)) {
// Construct the SQL.
$fields = $DB->sql_concat('u.id', "'#'", 'COALESCE(quiza.attempt, 0)') .
' AS uniqueid, ';
if ($this->qmsubselect) {
$fields .=
"(CASE " .
" WHEN {$this->qmsubselect} THEN 1" .
" ELSE 0 " .
"END) AS gradedattempt, ";
}
list($fields, $from, $where, $params) = $table->base_sql($allowed);
$table->set_count_sql("SELECT COUNT(1) FROM $from WHERE $where", $params);
// Test to see if there are any regraded attempts to be listed.
$fields .= ", COALESCE((
SELECT MAX(qqr.regraded)
FROM {quiz_overview_regrades} qqr
WHERE qqr.questionusageid = quiza.uniqueid
), -1) AS regraded";
if ($options->onlyregraded) {
$where .= " AND COALESCE((
SELECT MAX(qqr.regraded)
FROM {quiz_overview_regrades} qqr
WHERE qqr.questionusageid = quiza.uniqueid
), -1) <> -1";
}
$table->set_sql($fields, $from, $where, $params);
if (!$table->is_downloading()) {
// Output the regrade buttons.
if (has_capability('mod/quiz:regrade', $this->context)) {
$regradesneeded = $this->count_question_attempts_needing_regrade(
$quiz, $groupstudents);
if ($currentgroup) {
$a= new stdClass();
$a->groupname = groups_get_group_name($currentgroup);
$a->coursestudents = get_string('participants');
$a->countregradeneeded = $regradesneeded;
$regradealldrydolabel =
get_string('regradealldrydogroup', 'quiz_overview', $a);
$regradealldrylabel =
get_string('regradealldrygroup', 'quiz_overview', $a);
$regradealllabel =
get_string('regradeallgroup', 'quiz_overview', $a);
} else {
$regradealldrydolabel =
get_string('regradealldrydo', 'quiz_overview', $regradesneeded);
$regradealldrylabel =
get_string('regradealldry', 'quiz_overview');
$regradealllabel =
get_string('regradeall', 'quiz_overview');
}
$displayurl = new moodle_url($options->get_url(), array('sesskey' => sesskey()));
echo '<div class="mdl-align">';
echo '<form action="'.$displayurl->out_omit_querystring().'">';
echo '<div>';
echo html_writer::input_hidden_params($displayurl);
echo '<input type="submit" name="regradeall" value="'.$regradealllabel.'"/>';
echo '<input type="submit" name="regradealldry" value="' .
$regradealldrylabel . '"/>';
if ($regradesneeded) {
echo '<input type="submit" name="regradealldrydo" value="' .
$regradealldrydolabel . '"/>';
}
echo '</div>';
echo '</form>';
echo '</div>';
}
// Print information on the grading method.
if ($strattempthighlight = quiz_report_highlighting_grading_method(
$quiz, $this->qmsubselect, $options->onlygraded)) {
echo '<div class="quizattemptcounts">' . $strattempthighlight . '</div>';
}
}
// Define table columns.
$columns = array();
$headers = array();
if (!$table->is_downloading() && $options->checkboxcolumn) {
$columns[] = 'checkbox';
$headers[] = null;
}
$this->add_user_columns($table, $columns, $headers);
$this->add_state_column($columns, $headers);
$this->add_time_columns($columns, $headers);
$this->add_grade_columns($quiz, $options->usercanseegrades, $columns, $headers, false);
if (!$table->is_downloading() && has_capability('mod/quiz:regrade', $this->context) &&
$this->has_regraded_questions($from, $where, $params)) {
$columns[] = 'regraded';
$headers[] = get_string('regrade', 'quiz_overview');
}
if ($options->slotmarks) {
foreach ($questions as $slot => $question) {
// Ignore questions of zero length.
$columns[] = 'qsgrade' . $slot;
$header = get_string('qbrief', 'quiz', $question->number);
if (!$table->is_downloading()) {
$header .= '<br />';
} else {
$header .= ' ';
}
$header .= '/' . quiz_rescale_grade($question->maxmark, $quiz, 'question');
$headers[] = $header;
}
}
$this->set_up_table_columns($table, $columns, $headers, $this->get_base_url(), $options, false);
$table->set_attribute('class', 'generaltable generalbox grades');
$table->out($options->pagesize, true);
}
if (!$table->is_downloading() && $options->usercanseegrades) {
$output = $PAGE->get_renderer('mod_quiz');
if ($currentgroup && $groupstudents) {
list($usql, $params) = $DB->get_in_or_equal($groupstudents);
$params[] = $quiz->id;
if ($DB->record_exists_select('quiz_grades', "userid $usql AND quiz = ?",
$params)) {
$imageurl = new moodle_url('/mod/quiz/report/overview/overviewgraph.php',
array('id' => $quiz->id, 'groupid' => $currentgroup));
$graphname = get_string('overviewreportgraphgroup', 'quiz_overview',
groups_get_group_name($currentgroup));
echo $output->graph($imageurl, $graphname);
}
}
if ($DB->record_exists('quiz_grades', array('quiz'=> $quiz->id))) {
$imageurl = new moodle_url('/mod/quiz/report/overview/overviewgraph.php',
array('id' => $quiz->id));
$graphname = get_string('overviewreportgraph', 'quiz_overview');
echo $output->graph($imageurl, $graphname);
}
}
return true;
}
protected function process_actions($quiz, $cm, $currentgroup, $groupstudents, $allowed, $redirecturl) {
parent::process_actions($quiz, $cm, $currentgroup, $groupstudents, $allowed, $redirecturl);
if (empty($currentgroup) || $groupstudents) {
if (optional_param('regrade', 0, PARAM_BOOL) && confirm_sesskey()) {
if ($attemptids = optional_param_array('attemptid', array(), PARAM_INT)) {
$this->start_regrade($quiz, $cm);
$this->regrade_attempts($quiz, false, $groupstudents, $attemptids);
$this->finish_regrade($redirecturl);
}
}
}
if (optional_param('regradeall', 0, PARAM_BOOL) && confirm_sesskey()) {
$this->start_regrade($quiz, $cm);
$this->regrade_attempts($quiz, false, $groupstudents);
$this->finish_regrade($redirecturl);
} else if (optional_param('regradealldry', 0, PARAM_BOOL) && confirm_sesskey()) {
$this->start_regrade($quiz, $cm);
$this->regrade_attempts($quiz, true, $groupstudents);
$this->finish_regrade($redirecturl);
} else if (optional_param('regradealldrydo', 0, PARAM_BOOL) && confirm_sesskey()) {
$this->start_regrade($quiz, $cm);
$this->regrade_attempts_needing_it($quiz, $groupstudents);
$this->finish_regrade($redirecturl);
}
}
/**
* Check necessary capabilities, and start the display of the regrade progress page.
* @param object $quiz the quiz settings.
* @param object $cm the cm object for the quiz.
*/
protected function start_regrade($quiz, $cm) {
global $OUTPUT, $PAGE;
require_capability('mod/quiz:regrade', $this->context);
$this->print_header_and_tabs($cm, $this->course, $quiz, $this->mode);
}
/**
* Finish displaying the regrade progress page.
* @param moodle_url $nexturl where to send the user after the regrade.
* @uses exit. This method never returns.
*/
protected function finish_regrade($nexturl) {
global $OUTPUT, $PAGE;
echo $OUTPUT->heading(get_string('regradecomplete', 'quiz_overview'));
echo $OUTPUT->continue_button($nexturl);
echo $OUTPUT->footer();
die();
}
/**
* Unlock the session and allow the regrading process to run in the background.
*/
protected function unlock_session() {
session_get_instance()->write_close();
ignore_user_abort(true);
}
/**
* Regrade a particular quiz attempt. Either for real ($dryrun = false), or
* as a pretend regrade to see which fractions would change. The outcome is
* stored in the quiz_overview_regrades table.
*
* Note, $attempt is not upgraded in the database. The caller needs to do that.
* However, $attempt->sumgrades is updated, if this is not a dry run.
*
* @param object $attempt the quiz attempt to regrade.
* @param bool $dryrun if true, do a pretend regrade, otherwise do it for real.
* @param array $slots if null, regrade all questions, otherwise, just regrade
* the quetsions with those slots.
*/
protected function regrade_attempt($attempt, $dryrun = false, $slots = null) {
global $DB;
// Need more time for a quiz with many questions.
set_time_limit(300);
$transaction = $DB->start_delegated_transaction();
$quba = question_engine::load_questions_usage_by_activity($attempt->uniqueid);
if (is_null($slots)) {
$slots = $quba->get_slots();
}
$finished = $attempt->state == quiz_attempt::FINISHED;
foreach ($slots as $slot) {
$qqr = new stdClass();
$qqr->oldfraction = $quba->get_question_fraction($slot);
$quba->regrade_question($slot, $finished);
$qqr->newfraction = $quba->get_question_fraction($slot);
if (abs($qqr->oldfraction - $qqr->newfraction) > 1e-7) {
$qqr->questionusageid = $quba->get_id();
$qqr->slot = $slot;
$qqr->regraded = empty($dryrun);
$qqr->timemodified = time();
$DB->insert_record('quiz_overview_regrades', $qqr, false);
}
}
if (!$dryrun) {
question_engine::save_questions_usage_by_activity($quba);
}
$transaction->allow_commit();
// Really, PHP should not need this hint, but without this, we just run out of memory.
$quba = null;
$transaction = null;
gc_collect_cycles();
}
/**
* Regrade attempts for this quiz, exactly which attempts are regraded is
* controlled by the parameters.
* @param object $quiz the quiz settings.
* @param bool $dryrun if true, do a pretend regrade, otherwise do it for real.
* @param array $groupstudents blank for all attempts, otherwise regrade attempts
* for these users.
* @param array $attemptids blank for all attempts, otherwise only regrade
* attempts whose id is in this list.
*/
protected function regrade_attempts($quiz, $dryrun = false,
$groupstudents = array(), $attemptids = array()) {
global $DB;
$this->unlock_session();
$where = "quiz = ? AND preview = 0";
$params = array($quiz->id);
if ($groupstudents) {
list($usql, $uparams) = $DB->get_in_or_equal($groupstudents);
$where .= " AND userid $usql";
$params = array_merge($params, $uparams);
}
if ($attemptids) {
list($asql, $aparams) = $DB->get_in_or_equal($attemptids);
$where .= " AND id $asql";
$params = array_merge($params, $aparams);
}
$attempts = $DB->get_records_select('quiz_attempts', $where, $params);
if (!$attempts) {
return;
}
$this->clear_regrade_table($quiz, $groupstudents);
$progressbar = new progress_bar('quiz_overview_regrade', 500, true);
$a = array(
'count' => count($attempts),
'done' => 0,
);
foreach ($attempts as $attempt) {
$this->regrade_attempt($attempt, $dryrun);
$a['done']++;
$progressbar->update($a['done'], $a['count'],
get_string('regradingattemptxofy', 'quiz_overview', $a));
}
if (!$dryrun) {
$this->update_overall_grades($quiz);
}
}
/**
* Regrade those questions in those attempts that are marked as needing regrading
* in the quiz_overview_regrades table.
* @param object $quiz the quiz settings.
* @param array $groupstudents blank for all attempts, otherwise regrade attempts
* for these users.
*/
protected function regrade_attempts_needing_it($quiz, $groupstudents) {
global $DB;
$this->unlock_session();
$where = "quiza.quiz = ? AND quiza.preview = 0 AND qqr.regraded = 0";
$params = array($quiz->id);
// Fetch all attempts that need regrading.
if ($groupstudents) {
list($usql, $uparams) = $DB->get_in_or_equal($groupstudents);
$where .= " AND quiza.userid $usql";
$params += $uparams;
}
$toregrade = $DB->get_records_sql("
SELECT quiza.uniqueid, qqr.slot
FROM {quiz_attempts} quiza
JOIN {quiz_overview_regrades} qqr ON qqr.questionusageid = quiza.uniqueid
WHERE $where", $params);
if (!$toregrade) {
return;
}
$attemptquestions = array();
foreach ($toregrade as $row) {
$attemptquestions[$row->uniqueid][] = $row->slot;
}
$attempts = $DB->get_records_list('quiz_attempts', 'uniqueid',
array_keys($attemptquestions));
$this->clear_regrade_table($quiz, $groupstudents);
$progressbar = new progress_bar('quiz_overview_regrade', 500, true);
$a = array(
'count' => count($attempts),
'done' => 0,
);
foreach ($attempts as $attempt) {
$this->regrade_attempt($attempt, false, $attemptquestions[$attempt->uniqueid]);
$a['done']++;
$progressbar->update($a['done'], $a['count'],
get_string('regradingattemptxofy', 'quiz_overview', $a));
}
$this->update_overall_grades($quiz);
}
/**
* Count the number of attempts in need of a regrade.
* @param object $quiz the quiz settings.
* @param array $groupstudents user ids. If this is given, only data relating
* to these users is cleared.
*/
protected function count_question_attempts_needing_regrade($quiz, $groupstudents) {
global $DB;
$usertest = '';
$params = array();
if ($groupstudents) {
list($usql, $params) = $DB->get_in_or_equal($groupstudents);
$usertest = "quiza.userid $usql AND ";
}
$params[] = $quiz->id;
$sql = "SELECT COUNT(DISTINCT quiza.id)
FROM {quiz_attempts} quiza
JOIN {quiz_overview_regrades} qqr ON quiza.uniqueid = qqr.questionusageid
WHERE
$usertest
quiza.quiz = ? AND
quiza.preview = 0 AND
qqr.regraded = 0";
return $DB->count_records_sql($sql, $params);
}
/**
* Are there any pending regrades in the table we are going to show?
* @param string $from tables used by the main query.
* @param string $where where clause used by the main query.
* @param array $params required by the SQL.
* @return bool whether there are pending regrades.
*/
protected function has_regraded_questions($from, $where, $params) {
global $DB;
$qubaids = new qubaid_join($from, 'uniqueid', $where, $params);
return $DB->record_exists_select('quiz_overview_regrades',
'questionusageid ' . $qubaids->usage_id_in(),
$qubaids->usage_id_in_params());
}
/**
* Remove all information about pending/complete regrades from the database.
* @param object $quiz the quiz settings.
* @param array $groupstudents user ids. If this is given, only data relating
* to these users is cleared.
*/
protected function clear_regrade_table($quiz, $groupstudents) {
global $DB;
// Fetch all attempts that need regrading.
$where = '';
$params = array();
if ($groupstudents) {
list($usql, $params) = $DB->get_in_or_equal($groupstudents);
$where = "userid $usql AND ";
}
$params[] = $quiz->id;
$DB->delete_records_select('quiz_overview_regrades',
"questionusageid IN (
SELECT uniqueid
FROM {quiz_attempts}
WHERE $where quiz = ?
)", $params);
}
/**
* Update the final grades for all attempts. This method is used following
* a regrade.
* @param object $quiz the quiz settings.
* @param array $userids only update scores for these userids.
* @param array $attemptids attemptids only update scores for these attempt ids.
*/
protected function update_overall_grades($quiz) {
quiz_update_all_attempt_sumgrades($quiz);
quiz_update_all_final_grades($quiz);
quiz_update_grades($quiz);
}
}
| {'content_hash': '8f820341f07e5b1430114966fd3653ef', 'timestamp': '', 'source': 'github', 'line_count': 567, 'max_line_length': 108, 'avg_line_length': 41.573192239858905, 'alnum_prop': 0.539453589003903, 'repo_name': 'MyHealthEd/myHealthEd', 'id': '38bb483a769a1892bdaed2ac61d6c5a663b9d274', 'size': '23815', 'binary': False, 'copies': '35', 'ref': 'refs/heads/master', 'path': 'mod/quiz/report/overview/report.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '1205'}, {'name': 'CSS', 'bytes': '2037338'}, {'name': 'Erlang', 'bytes': '2479'}, {'name': 'Java', 'bytes': '14870'}, {'name': 'JavaScript', 'bytes': '13378374'}, {'name': 'PHP', 'bytes': '52397096'}, {'name': 'Perl', 'bytes': '304640'}, {'name': 'Python', 'bytes': '6721'}, {'name': 'Ruby', 'bytes': '25'}, {'name': 'Scala', 'bytes': '1228'}, {'name': 'Shell', 'bytes': '548583'}, {'name': 'XSLT', 'bytes': '33921'}]} |
import React from 'react';
const Loading = () => (
<div
className="loading_container"
>
<img src="./res/images/loading_small.png" alt="" />
</div>
);
export default Loading;
| {'content_hash': '426b879959da3c22c254990af12f7a6e', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 55, 'avg_line_length': 17.272727272727273, 'alnum_prop': 0.6105263157894737, 'repo_name': 'tahnik/devRantron', 'id': 'bc1ccd43d940ff929755a44bdbc644fbfc03149e', 'size': '190', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/js/components/utilities/loading.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '43439'}, {'name': 'HTML', 'bytes': '11391'}, {'name': 'JavaScript', 'bytes': '246112'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'e72e3ceda59dc699dd8de5244e56ada6', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '9224a4a131a05499f24d5dc4e10db7162012592a', 'size': '175', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Oleaceae/Chionanthus/Linociera oligantha/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
#include "OgreGLSLProgramFactory.h"
#include "OgreGLSLLinkProgramManager.h"
#include "OgreGLSLProgram.h"
namespace Ogre {
namespace GLSL {
//-----------------------------------------------------------------------
String GLSLProgramFactory::sLanguageName = "glsl";
//-----------------------------------------------------------------------
GLSLProgramFactory::GLSLProgramFactory(void)
{
mLinkProgramManager = new GLSLLinkProgramManager();
}
//-----------------------------------------------------------------------
GLSLProgramFactory::~GLSLProgramFactory(void)
{
if (mLinkProgramManager)
delete mLinkProgramManager;
}
//-----------------------------------------------------------------------
const String& GLSLProgramFactory::getLanguage(void) const
{
return sLanguageName;
}
//-----------------------------------------------------------------------
HighLevelGpuProgram* GLSLProgramFactory::create(ResourceManager* creator,
const String& name, ResourceHandle handle,
const String& group, bool isManual, ManualResourceLoader* loader)
{
return new GLSLProgram(creator, name, handle, group, isManual, loader);
}
//-----------------------------------------------------------------------
void GLSLProgramFactory::destroy(HighLevelGpuProgram* prog)
{
delete prog;
}
//-----------------------------------------------------------------------
}
}
| {'content_hash': '49ea64de3cdac04de7df659fe6abd236', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 79, 'avg_line_length': 35.833333333333336, 'alnum_prop': 0.44119601328903657, 'repo_name': 'redheli/ogre', 'id': '0ba19e637e8ee343f096c284eaf291d5770849a0', 'size': '2864', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'RenderSystems/GL/src/GLSL/src/OgreGLSLProgramFactory.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '281'}, {'name': 'Batchfile', 'bytes': '8997'}, {'name': 'C', 'bytes': '3516438'}, {'name': 'C++', 'bytes': '25507917'}, {'name': 'CMake', 'bytes': '392563'}, {'name': 'CSS', 'bytes': '8682'}, {'name': 'GLSL', 'bytes': '1038'}, {'name': 'Groff', 'bytes': '68243'}, {'name': 'HTML', 'bytes': '145744'}, {'name': 'Java', 'bytes': '6289'}, {'name': 'Lex', 'bytes': '83193'}, {'name': 'Makefile', 'bytes': '413'}, {'name': 'Objective-C', 'bytes': '60249'}, {'name': 'Objective-C++', 'bytes': '279639'}, {'name': 'Python', 'bytes': '479342'}, {'name': 'Shell', 'bytes': '10305'}, {'name': 'TeX', 'bytes': '43359'}, {'name': 'Visual Basic', 'bytes': '1095'}, {'name': 'Yacc', 'bytes': '40113'}]} |
package org.stringtemplate.v4;
import org.stringtemplate.v4.compiler.Bytecode;
import java.io.IOException;
/** Generic StringTemplate output writer filter.
* <p>
* Literals and the elements of expressions are emitted via {@link #write(String)}.
* Separators are emitted via {@link #writeSeparator(String)} because they must be
* handled specially when wrapping lines (we don't want to wrap
* in between an element and it's separator).</p>
*/
public interface STWriter {
int NO_WRAP = -1;
void pushIndentation(String indent);
String popIndentation();
void pushAnchorPoint();
void popAnchorPoint();
void setLineWidth(int lineWidth);
/** Write the string and return how many actual characters were written.
* With auto-indentation and wrapping, more chars than {@code str.length()}
* can be emitted. No wrapping is done.
*/
int write(String str) throws IOException;
/** Same as write, but wrap lines using the indicated string as the
* wrap character (such as {@code "\n"}).
*/
int write(String str, String wrap) throws IOException;
/**
* Because we evaluate ST instance by invoking
* {@link Interpreter#exec(STWriter, InstanceScope)} again, we can't pass options in.
* So the {@link Bytecode#INSTR_WRITE} instruction of an applied template
* (such as when we wrap in between template applications like
* {@code <data:{v|[<v>]}; wrap>}) we need to write the {@code wrap} string
* before calling {@link Interpreter#exec}. We expose just like for the
* separator. See {@link Interpreter#writeObject} where it checks for ST
* instance. If POJO, {@link Interpreter#writePOJO} passes {@code wrap} to
* {@link STWriter#write(String str, String wrap)}. Can't pass to
* {@link Interpreter#exec}.
*/
int writeWrap(String wrap) throws IOException;
/** Write a separator. Same as {@link #write(String)} except that a {@code "\n"}
* cannot be inserted before emitting a separator.
*/
int writeSeparator(String str) throws IOException;
/** Return the absolute char index into the output of the char
* we're about to write. Returns 0 if no char written yet.
*/
int index();
} | {'content_hash': 'fd51d24e447d87a82ba2d4117e01954f', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 89, 'avg_line_length': 38.793103448275865, 'alnum_prop': 0.6822222222222222, 'repo_name': 'antlr/codebuff', 'id': '58be155b87e208a53cc76174f82f75c787e0dfd9', 'size': '3762', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'output/java8/1.4.12/STWriter.java', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'ANTLR', 'bytes': '1479752'}, {'name': 'GAP', 'bytes': '146955'}, {'name': 'Java', 'bytes': '32484822'}, {'name': 'Python', 'bytes': '113118'}, {'name': 'SQLPL', 'bytes': '605792'}, {'name': 'Shell', 'bytes': '445'}]} |
<?php
namespace PHPExiftool\Driver\Tag\PhotoMechanic;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class RawCropLeft extends AbstractTag
{
protected $Id = 209;
protected $Name = 'RawCropLeft';
protected $FullName = 'PhotoMechanic::SoftEdit';
protected $GroupName = 'PhotoMechanic';
protected $g0 = 'PhotoMechanic';
protected $g1 = 'PhotoMechanic';
protected $g2 = 'Image';
protected $Type = 'int32s';
protected $Writable = true;
protected $Description = 'Raw Crop Left';
}
| {'content_hash': '1ab8266dac4a027b4e0122b1d9392fd2', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 52, 'avg_line_length': 17.17142857142857, 'alnum_prop': 0.6838602329450915, 'repo_name': 'romainneutron/PHPExiftool', 'id': '7584d5c31d8bb2d05ce33a93c4c5b77f0cc5b25a', 'size': '823', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/PHPExiftool/Driver/Tag/PhotoMechanic/RawCropLeft.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '22042446'}]} |
class Clazz:
def isPython
return True
| {'content_hash': '794133e222c3b9fa7e50fda19132c57d', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 19, 'avg_line_length': 16.666666666666668, 'alnum_prop': 0.62, 'repo_name': 'jamesblunt/chorus', 'id': '3eb5b222a64e84a7b8e2682e38bb2a43b15be128', 'size': '50', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'spec/fixtures/code.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '70'}, {'name': 'CSS', 'bytes': '427650'}, {'name': 'HTML', 'bytes': '62212'}, {'name': 'Handlebars', 'bytes': '273307'}, {'name': 'Java', 'bytes': '107'}, {'name': 'JavaScript', 'bytes': '4648578'}, {'name': 'Python', 'bytes': '75101'}, {'name': 'Rebol', 'bytes': '107'}, {'name': 'Ruby', 'bytes': '2721850'}, {'name': 'Shell', 'bytes': '81583'}, {'name': 'VimL', 'bytes': '339'}]} |
package com.zhaoxinwo.utils;
import java.util.LinkedList;
import java.util.List;
import com.zhaoxinwo.ui.R;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Scroller;
/**
*
* @blog http://blog.csdn.net/xiaanming
*
*/
public class SwipeBackLayout extends FrameLayout {
private static final String TAG = SwipeBackLayout.class.getSimpleName();
private View mContentView;
private int mTouchSlop;
private int downX;
private int downY;
private int tempX;
private Scroller mScroller;
private int viewWidth;
private boolean isSilding;
private boolean isFinish;
private Drawable mShadowDrawable;
private Activity mActivity;
private List<ViewPager> mViewPagers = new LinkedList<ViewPager>();
public SwipeBackLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SwipeBackLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mScroller = new Scroller(context);
mShadowDrawable = getResources().getDrawable(R.drawable.shadow_left);
}
public void attachToActivity(Activity activity) {
mActivity = activity;
TypedArray a = activity.getTheme().obtainStyledAttributes(
new int[] { android.R.attr.windowBackground });
int background = a.getResourceId(0, 0);
a.recycle();
ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
decorChild.setBackgroundResource(background);
decor.removeView(decorChild);
addView(decorChild);
setContentView(decorChild);
decor.addView(this);
}
private void setContentView(View decorChild) {
mContentView = (View) decorChild.getParent();
}
/**
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//����ViewPager��ͻ����
ViewPager mViewPager = getTouchViewPager(mViewPagers, ev);
Log.i(TAG, "mViewPager = " + mViewPager);
if(mViewPager != null && mViewPager.getCurrentItem() != 0){
return super.onInterceptTouchEvent(ev);
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = tempX = (int) ev.getRawX();
downY = (int) ev.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int moveX = (int) ev.getRawX();
// �������������SildingFinishLayout���������touch�¼�
if (moveX - downX > mTouchSlop
&& Math.abs((int) ev.getRawY() - downY) < mTouchSlop) {
return true;
}
break;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
int moveX = (int) event.getRawX();
int deltaX = tempX - moveX;
tempX = moveX;
if (moveX - downX > mTouchSlop
&& Math.abs((int) event.getRawY() - downY) < mTouchSlop) {
isSilding = true;
}
if (moveX - downX >= 0 && isSilding) {
mContentView.scrollBy(deltaX, 0);
}
break;
case MotionEvent.ACTION_UP:
isSilding = false;
if (mContentView.getScrollX() <= -viewWidth / 2) {
isFinish = true;
scrollRight();
} else {
scrollOrigin();
isFinish = false;
}
break;
}
return true;
}
/**
* ��ȡSwipeBackLayout�����ViewPager�ļ���
* @param mViewPagers
* @param parent
*/
private void getAlLViewPager(List<ViewPager> mViewPagers, ViewGroup parent){
int childCount = parent.getChildCount();
for(int i=0; i<childCount; i++){
View child = parent.getChildAt(i);
if(child instanceof ViewPager){
mViewPagers.add((ViewPager)child);
}else if(child instanceof ViewGroup){
getAlLViewPager(mViewPagers, (ViewGroup)child);
}
}
}
/**
* ��������touch��ViewPager
* @param mViewPagers
* @param ev
* @return
*/
private ViewPager getTouchViewPager(List<ViewPager> mViewPagers, MotionEvent ev){
if(mViewPagers == null || mViewPagers.size() == 0){
return null;
}
Rect mRect = new Rect();
for(ViewPager v : mViewPagers){
v.getHitRect(mRect);
if(mRect.contains((int)ev.getX(), (int)ev.getY())){
return v;
}
}
return null;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (changed) {
viewWidth = this.getWidth();
getAlLViewPager(mViewPagers, this);
Log.i(TAG, "ViewPager size = " + mViewPagers.size());
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mShadowDrawable != null && mContentView != null) {
int left = mContentView.getLeft()
- mShadowDrawable.getIntrinsicWidth();
int right = left + mShadowDrawable.getIntrinsicWidth();
int top = mContentView.getTop();
int bottom = mContentView.getBottom();
mShadowDrawable.setBounds(left, top, right, bottom);
mShadowDrawable.draw(canvas);
}
}
/**
* ����������
*/
private void scrollRight() {
final int delta = (viewWidth + mContentView.getScrollX());
// ����startScroll����������һЩ�����IJ���������computeScroll()�����е���scrollTo������item
mScroller.startScroll(mContentView.getScrollX(), 0, -delta + 1, 0,
Math.abs(delta));
postInvalidate();
}
/**
* ��������ʼλ��
*/
private void scrollOrigin() {
int delta = mContentView.getScrollX();
mScroller.startScroll(mContentView.getScrollX(), 0, -delta, 0,
Math.abs(delta));
postInvalidate();
}
@Override
public void computeScroll() {
// ����startScroll��ʱ��scroller.computeScrollOffset()����true��
if (mScroller.computeScrollOffset()) {
mContentView.scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
postInvalidate();
if (mScroller.isFinished() && isFinish) {
mActivity.finish();
}
}
}
}
| {'content_hash': '20fd798c0ede1560f6da84507ab6326c', 'timestamp': '', 'source': 'github', 'line_count': 242, 'max_line_length': 89, 'avg_line_length': 25.239669421487605, 'alnum_prop': 0.6869679109364768, 'repo_name': 'jiadebin/zhaoxinwo-app', 'id': 'dbf99fe78d75de71738ef2e377ce13bf9eca1185', 'size': '6381', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/zhaoxinwo/utils/SwipeBackLayout.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '34952'}]} |
import { IController, IComponentOptions, module } from 'angular';
import { set, has } from 'lodash';
interface ICapabilitiesSelectorField {
label: string;
buttonLabel: string;
model: string;
}
class CapabilitiesSelector implements IController {
public component: any;
public fields: ICapabilitiesSelectorField[] = [
{
label: 'Add',
buttonLabel: 'Add Linux Capability',
model: 'add',
},
{
label: 'Drop',
buttonLabel: 'Drop Linux Capability',
model: 'drop',
},
];
public add(fieldModel: string): void {
const path = ['securityContext', 'capabilities', fieldModel];
if (!has(this.component, path)) {
set(this.component, path, []);
}
this.component.securityContext.capabilities[fieldModel].push('');
}
public remove(fieldModel: string, index: number): void {
this.component.securityContext.capabilities[fieldModel].splice(index, 1);
}
}
const capabilitiesSelectorComponent: IComponentOptions = {
bindings: {
component: '=',
},
templateUrl: require('./capabilitiesSelector.component.html'),
controller: CapabilitiesSelector,
};
export const KUBERNETES_CAPABILITIES_SELECTOR = 'spinnaker.kubernetes.securityContext.capabilitiesSelector.component';
module(KUBERNETES_CAPABILITIES_SELECTOR, []).component('kubernetesCapabilitiesSelector', capabilitiesSelectorComponent);
| {'content_hash': 'b55b13e5db9fc354f15b978ac11f5eaa', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 120, 'avg_line_length': 28.75, 'alnum_prop': 0.7065217391304348, 'repo_name': 'sgarlick987/deck', 'id': 'ee42255af75a714e905566e378edb17739b2f436', 'size': '1380', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'app/scripts/modules/kubernetes/src/v1/container/securityContext/capabilitiesSelector.component.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '188919'}, {'name': 'HTML', 'bytes': '1284008'}, {'name': 'JavaScript', 'bytes': '2004278'}, {'name': 'Shell', 'bytes': '24704'}, {'name': 'TypeScript', 'bytes': '5219772'}]} |
package com.microsoft.azure.management.resources.v2016_06_01.implementation;
import com.microsoft.azure.management.resources.v2016_06_01.Location;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import rx.Observable;
class LocationImpl extends WrapperImpl<LocationInner> implements Location {
private final Manager manager;
LocationImpl(LocationInner inner, Manager manager) {
super(inner);
this.manager = manager;
}
@Override
public Manager manager() {
return this.manager;
}
@Override
public String displayName() {
return this.inner().displayName();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public String latitude() {
return this.inner().latitude();
}
@Override
public String longitude() {
return this.inner().longitude();
}
@Override
public String name() {
return this.inner().name();
}
@Override
public String subscriptionId() {
return this.inner().subscriptionId();
}
}
| {'content_hash': 'b62869345ab545a320c88fd39061539f', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 76, 'avg_line_length': 20.48148148148148, 'alnum_prop': 0.6455696202531646, 'repo_name': 'navalev/azure-sdk-for-java', 'id': 'd8417d855de7a627f390a5e8e4cf232ed98b9676', 'size': '1336', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'sdk/resources/mgmt-v2016_06_01/src/main/java/com/microsoft/azure/management/resources/v2016_06_01/implementation/LocationImpl.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '7230'}, {'name': 'CSS', 'bytes': '5411'}, {'name': 'Groovy', 'bytes': '1570436'}, {'name': 'HTML', 'bytes': '29221'}, {'name': 'Java', 'bytes': '250218562'}, {'name': 'JavaScript', 'bytes': '15605'}, {'name': 'PowerShell', 'bytes': '30924'}, {'name': 'Python', 'bytes': '42119'}, {'name': 'Shell', 'bytes': '1408'}]} |
// Copyright 2018 The Bazel Authors. 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.
package com.google.devtools.build.lib.starlark;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.AnalysisResult;
import com.google.devtools.build.lib.analysis.ConfiguredAspect;
import com.google.devtools.build.lib.analysis.util.AnalysisTestCase;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.StarlarkProvider;
import com.google.devtools.build.lib.packages.StructImpl;
import java.util.List;
import java.util.stream.Collectors;
import net.starlark.java.eval.Dict;
import net.starlark.java.eval.Mutability;
import net.starlark.java.eval.Sequence;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for the Starlark-accessible actions provider on rule configured targets. */
@RunWith(JUnit4.class)
public class StarlarkActionProviderTest extends AnalysisTestCase {
@Test
public void aspectGetsActionProviderForNativeRule() throws Exception {
scratch.file(
"test/aspect.bzl",
"foo = provider()",
"def _impl(target, ctx):",
" return [foo(actions = target.actions)]",
"MyAspect = aspect(implementation=_impl)");
scratch.file(
"test/BUILD",
"genrule(",
" name = 'xxx',",
" cmd = 'echo \"hello\" > $@',",
" outs = ['mygen.out']",
")");
AnalysisResult analysisResult =
update(ImmutableList.of("test/aspect.bzl%MyAspect"), "//test:xxx");
ConfiguredAspect configuredAspect =
Iterables.getOnlyElement(analysisResult.getAspectsMap().values());
StarlarkProvider.Key fooKey =
new StarlarkProvider.Key(
Label.parseAbsolute("//test:aspect.bzl", ImmutableMap.of()), "foo");
StructImpl fooProvider = (StructImpl) configuredAspect.get(fooKey);
assertThat(fooProvider.getValue("actions")).isNotNull();
@SuppressWarnings("unchecked")
Sequence<ActionAnalysisMetadata> actions =
(Sequence<ActionAnalysisMetadata>) fooProvider.getValue("actions");
assertThat(actions).isNotEmpty();
ActionAnalysisMetadata action = actions.get(0);
assertThat(action.getMnemonic()).isEqualTo("Genrule");
assertThat(action).isInstanceOf(AbstractAction.class);
assertThat(((AbstractAction) action).getExecutionInfo()).isNotNull();
}
@Test
@SuppressWarnings("unchecked")
public void aspectGetsActionProviderForStarlarkRule() throws Exception {
scratch.file(
"test/aspect.bzl",
"foo = provider()",
"def _impl(target, ctx):",
" mnemonics = [a.mnemonic for a in target.actions]",
" envs = [a.env for a in target.actions]",
" execution_info = [a.execution_info for a in target.actions]",
" inputs = [a.inputs.to_list() for a in target.actions]",
" outputs = [a.outputs.to_list() for a in target.actions]",
" argv = [a.argv for a in target.actions]",
" return [foo(",
" actions = target.actions,",
" mnemonics = mnemonics,",
" envs = envs,",
" execution_info = execution_info,",
" inputs = inputs,",
" outputs = outputs,",
" argv = argv",
" )]",
"MyAspect = aspect(implementation=_impl)");
scratch.file(
"test/rule.bzl",
"def impl(ctx):",
" output_file0 = ctx.actions.declare_file('myfile0')",
" output_file1 = ctx.actions.declare_file('myfile1')",
" executable = ctx.actions.declare_file('executable')",
" ctx.actions.run(outputs=[output_file0], executable=executable,",
" mnemonic='MyAction0', env={'foo':'bar', 'pet':'puppy'})",
" ctx.actions.run_shell(outputs=[executable, output_file1],",
" command='fakecmd', mnemonic='MyAction1', env={'pet':'bunny'})",
" return None",
"my_rule = rule(impl)");
scratch.file(
"test/BUILD", "load('//test:rule.bzl', 'my_rule')", "my_rule(", " name = 'xxx',", ")");
useConfiguration("--experimental_google_legacy_api");
AnalysisResult analysisResult =
update(ImmutableList.of("test/aspect.bzl%MyAspect"), "//test:xxx");
ConfiguredAspect configuredAspect =
Iterables.getOnlyElement(analysisResult.getAspectsMap().values());
StarlarkProvider.Key fooKey =
new StarlarkProvider.Key(
Label.parseAbsolute("//test:aspect.bzl", ImmutableMap.of()), "foo");
StructImpl fooProvider = (StructImpl) configuredAspect.get(fooKey);
assertThat(fooProvider.getValue("actions")).isNotNull();
Sequence<ActionAnalysisMetadata> actions =
(Sequence<ActionAnalysisMetadata>) fooProvider.getValue("actions");
assertThat(actions).hasSize(2);
Sequence<String> mnemonics = (Sequence<String>) fooProvider.getValue("mnemonics");
assertThat(mnemonics).containsExactly("MyAction0", "MyAction1");
Sequence<Dict<String, String>> envs =
(Sequence<Dict<String, String>>) fooProvider.getValue("envs");
assertThat(envs)
.containsExactly(
Dict.of((Mutability) null, "foo", "bar", "pet", "puppy"),
Dict.of((Mutability) null, "pet", "bunny"));
Sequence<Dict<String, String>> executionInfo =
(Sequence<Dict<String, String>>) fooProvider.getValue("execution_info");
assertThat(executionInfo).isNotNull();
Sequence<Sequence<Artifact>> inputs =
(Sequence<Sequence<Artifact>>) fooProvider.getValue("inputs");
assertThat(flattenArtifactNames(inputs)).containsExactly("executable");
Sequence<Sequence<Artifact>> outputs =
(Sequence<Sequence<Artifact>>) fooProvider.getValue("outputs");
assertThat(flattenArtifactNames(outputs)).containsExactly("myfile0", "executable", "myfile1");
Sequence<Sequence<String>> argv = (Sequence<Sequence<String>>) fooProvider.getValue("argv");
assertThat(argv.get(0)).hasSize(1);
assertThat(argv.get(0).get(0)).endsWith("executable");
assertThat(argv.get(1)).contains("fakecmd");
}
private static List<String> flattenArtifactNames(Sequence<Sequence<Artifact>> artifactLists) {
return artifactLists.stream()
.flatMap(artifacts -> artifacts.stream())
.map(artifact -> artifact.getFilename())
.collect(Collectors.toList());
}
}
| {'content_hash': '6fe8479f3164614360c9dd5efa2115c1', 'timestamp': '', 'source': 'github', 'line_count': 171, 'max_line_length': 98, 'avg_line_length': 42.57309941520468, 'alnum_prop': 0.6759615384615385, 'repo_name': 'davidzchen/bazel', 'id': '93eb89123e1bac55640e255cc336eeb6a87524ce', 'size': '7280', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/java/com/google/devtools/build/lib/starlark/StarlarkActionProviderTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2997'}, {'name': 'C', 'bytes': '25475'}, {'name': 'C++', 'bytes': '1545155'}, {'name': 'Dockerfile', 'bytes': '1195'}, {'name': 'HTML', 'bytes': '21431'}, {'name': 'Java', 'bytes': '36685603'}, {'name': 'Makefile', 'bytes': '248'}, {'name': 'Objective-C', 'bytes': '10369'}, {'name': 'Objective-C++', 'bytes': '1043'}, {'name': 'PowerShell', 'bytes': '15431'}, {'name': 'Python', 'bytes': '2588113'}, {'name': 'Ruby', 'bytes': '152'}, {'name': 'Shell', 'bytes': '2062992'}, {'name': 'Smarty', 'bytes': '18679'}, {'name': 'Starlark', 'bytes': '45680'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Change SYSTEM "http://ij.itk.org/itkfaq/ITKMigration.dtd">
<!--**
**
** FFTUseImageAsTemplateParameter.xml
**
** >>>>>>>>>>>>>>>>>>>>>>>>>>>>
** THIS FILE HAS BEEN AUTOMATICALLY GENERATED. EDIT IT BEFORE COMMITING
** <<<<<<<<<<<<<<<<<<<<<<<<<<<
**
**-->
<Change>
<!--**
** Title for the online migration page
**-->
<Title>
FFT Use Image As Template Parameter
</Title>
<!--**
** The author of the change
**-->
<Author>
Gaëtan Lehmann
</Author>
<!--**
** Date of creation for the XML document
**-->
<Date>
2011-04-07
</Date>
<!--**
** Plain text description of the change
** Extracted from git commit messages
**-->
<Description>
The FFT filters now take an image type as template parameter.
The FFT filters were using the pixel type and the image dimension
instead of the usual image type used elsewhere in ITK.
</Description>
<!--**
** Sample code snippets
** Extracted from git diff of changed files in Examples and Testing
**-->
<SampleCode>
<Old>
<![CDATA[
typedef double WorkPixelType;
const unsigned int Dimension = 3;
typedef itk::VnlFFTRealToComplexConjugateImageFilter< WorkPixelType, Dimension >
FFTFilterType;
typedef itk::VnlFFTComplexConjugateToRealImageFilter< WorkPixelType, Dimension >
invFFTFilterType;
]]>
</Old>
<New>
<![CDATA[
typedef double WorkPixelType;
const unsigned int Dimension = 3;
typedef itk::Image< WorkPixelType, Dimension > WorkImageType;
typedef itk::VnlForwardFFTImageFilter < WorkImageType > FFTFilterType;
typedef itk::VnlInverseFFTImageFilter < ComplexImageType > InvFFTFilterType;
]]>
</New>
</SampleCode>
<!--**
** The change-ids for all commits in the topic branch
**-->
<Gerrit-ChangeId>
Ic4f6c1733ae75173079af4e684a34827dadbd99c
</Gerrit-ChangeId>
<!--**
** List of all changed files from the topic branch
**-->
<FileList>
Examples/Filtering/FFTDirectInverse.cxx
Examples/Filtering/FFTDirectInverse2.cxx
Examples/Filtering/FFTImageFilter.cxx
Examples/Filtering/FFTImageFilterFourierDomainFiltering.cxx
Modules/Filtering/FFT/include/itkFFTComplexConjugateToRealImageFilter.h
Modules/Filtering/FFT/include/itkFFTComplexConjugateToRealImageFilter.txx
Modules/Filtering/FFT/include/itkFFTRealToComplexConjugateImageFilter.h
Modules/Filtering/FFT/include/itkFFTRealToComplexConjugateImageFilter.txx
Modules/Filtering/FFT/include/itkFFTWComplexConjugateToRealImageFilter.h
Modules/Filtering/FFT/include/itkFFTWComplexConjugateToRealImageFilter.txx
Modules/Filtering/FFT/include/itkFFTWRealToComplexConjugateImageFilter.h
Modules/Filtering/FFT/include/itkFFTWRealToComplexConjugateImageFilter.txx
Modules/Filtering/FFT/include/itkVnlFFTComplexConjugateToRealImageFilter.h
Modules/Filtering/FFT/include/itkVnlFFTComplexConjugateToRealImageFilter.txx
Modules/Filtering/FFT/include/itkVnlFFTRealToComplexConjugateImageFilter.h
Modules/Filtering/FFT/include/itkVnlFFTRealToComplexConjugateImageFilter.txx
Modules/Filtering/FFT/test/itkFFTWD_FFTTest.cxx
Modules/Filtering/FFT/test/itkFFTWF_FFTTest.cxx
Modules/Filtering/FFT/test/itkVnlFFTTest.cxx
Modules/Filtering/FFT/test/itkVnlFFTWD_FFTTest.cxx
Modules/Filtering/FFT/test/itkVnlFFTWF_FFTTest.cxx
Modules/Nonunit/Review/include/itkDirectFourierReconstructionImageToImageFilter.h
Modules/Nonunit/Review/include/itkDirectFourierReconstructionImageToImageFilter.txx
Modules/Nonunit/Review/include/itkFFTComplexToComplexImageFilter.h
Modules/Nonunit/Review/include/itkFFTComplexToComplexImageFilter.txx
Modules/Nonunit/Review/include/itkFFTWComplexToComplexImageFilter.h
Modules/Nonunit/Review/include/itkFFTWComplexToComplexImageFilter.txx
Modules/Nonunit/Review/test/itkDirectFourierReconstructionImageToImageFilterTest.cxx
Modules/Nonunit/Review/test/itkFFTComplexToComplexImageFilterTest01.cxx
Modules/Nonunit/Review/test/itkFFTComplexToComplexImageFilterTest02.cxx
Wrapping/WrapITK/Languages/Python/Tests/FFTImageFilter.py
Wrapping/WrapITK/Libraries/FFT/itkDirectFourierReconstructionImageToImageFilter.wrap
Wrapping/WrapITK/Libraries/FFT/itkFFTComplexConjugateToRealImageFilter.wrap
Wrapping/WrapITK/Libraries/FFT/itkFFTComplexToComplexImageFilter.wrap
Wrapping/WrapITK/Libraries/FFT/itkFFTRealToComplexConjugateImageFilter.wrap
Wrapping/WrapITK/Libraries/FFT/itkVnlFFTComplexConjugateToRealImageFilter.wrap
Wrapping/WrapITK/Libraries/FFT/itkVnlFFTRealToComplexConjugateImageFilter.wrap
Wrapping/WrapITK/Libraries/FFTW/itkFFTWComplexConjugateToRealImageFilter.wrap
Wrapping/WrapITK/Libraries/FFTW/itkFFTWComplexToComplexImageFilter.wrap
Wrapping/WrapITK/Libraries/FFTW/itkFFTWRealToComplexConjugateImageFilter.wrap
</FileList>
<!--**
** If the migration can be accomplished by a simple string
** substitution, then use the following construct to define
** the substitution rule.
**
** <MigrationFix-Automatic>
** <Old>
** MipsleledName
** </Old>
** <New>
** MisspelledName
** </New>
** </MigrationFix-Automatic>
**-->
<!--**
** If the migration can NOT be accomplished by a simple string
** substitution, but potential problem spots can be identified,
** use the following construct to define a migration flag rule.
**
** <MigrationFix-Manual>
** OldFunctionName
** </MigrationFix-Manual>
**-->
</Change>
| {'content_hash': 'd20418da12d5fd5b2b02c75ae65593fb', 'timestamp': '', 'source': 'github', 'line_count': 151, 'max_line_length': 90, 'avg_line_length': 38.688741721854306, 'alnum_prop': 0.717904827114002, 'repo_name': 'paulnovo/ITK', 'id': '4f165aaab7ba977836b0bc4e67a244b40576f256', 'size': '5843', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'Documentation/Migration/FFTUseImageAsTemplateParameter.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '27038496'}, {'name': 'C#', 'bytes': '1714'}, {'name': 'C++', 'bytes': '41269638'}, {'name': 'FORTRAN', 'bytes': '2241251'}, {'name': 'Io', 'bytes': '1833'}, {'name': 'Java', 'bytes': '60605'}, {'name': 'Objective-C', 'bytes': '6591'}, {'name': 'Perl', 'bytes': '17899'}, {'name': 'Prolog', 'bytes': '4406'}, {'name': 'Python', 'bytes': '940158'}, {'name': 'Ruby', 'bytes': '296'}, {'name': 'Shell', 'bytes': '205726'}, {'name': 'Tcl', 'bytes': '130561'}]} |
import { SIGNUP_LOADING, SIGNUP_SUCCESS,
SIGNUP_FAILURE, SIGNIN_LOADING, SIGNIN_SUCCESS,
SIGNIN_FAILURE } from '../../../../../constants';
import loadingUser from '../../../../../reducers/auth/user/loadingUser';
describe('loadingUser reducer', () => {
const state = false;
const action = {};
test('should return true for SIGNIN_LOADING action type',
() => {
action.type = SIGNIN_LOADING;
expect(loadingUser(state, action))
.toBe(true);
});
test('should return false for SIGNIN_SUCCESS action type',
() => {
action.type = SIGNIN_SUCCESS;
expect(loadingUser(state, action))
.toBe(false);
});
test('should return false for SIGNIN_FAILURE action type',
() => {
action.type = SIGNIN_FAILURE;
expect(loadingUser(state, action))
.toBe(false);
});
test('should return true for SIGNUP_LOADING action type',
() => {
action.type = SIGNUP_LOADING;
expect(loadingUser(undefined, action))
.toBe(true);
});
test('should return false for SIGNUP_SUCCESS action type',
() => {
action.type = SIGNUP_SUCCESS;
expect(loadingUser(state, action))
.toBe(false);
});
test('should return false for SIGNUP_FAILURE action type',
() => {
action.type = SIGNUP_FAILURE;
expect(loadingUser(state, action))
.toBe(false);
});
test('should return curent state value for other action types',
() => {
action.type = 'SOME_UNRELATED_ACTION';
expect(loadingUser(state, action))
.toBe(state);
});
});
| {'content_hash': '2fdb2ca5cde82a89ecc7f0720ab59158', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 72, 'avg_line_length': 25.896551724137932, 'alnum_prop': 0.6364846870838882, 'repo_name': 'oahray/bc-24-postit', 'id': '5b3f9fa9cd9046e822fc68dfb821dc5fe5a03d83', 'size': '1502', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'client/src/__tests__/spec/reducers/auth/user/loadingUser.test.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '10662'}, {'name': 'HTML', 'bytes': '5834'}, {'name': 'JavaScript', 'bytes': '373881'}]} |
import { Directive, ElementRef } from '@angular/core';
import { rafFrames } from '../../util/dom';
import { Tab } from './tab';
/**
* @private
*/
@Directive({
selector: '.tab-highlight'
})
export class TabHighlight {
private _init: boolean;
constructor(private _elementRef: ElementRef) {}
select(tab: Tab) {
rafFrames(3, () => {
let d = tab.btn.getDimensions();
let ele = this._elementRef.nativeElement;
ele.style.transform = 'translate3d(' + d.left + 'px,0,0) scaleX(' + d.width + ')';
if (!this._init) {
this._init = true;
rafFrames(6, () => {
ele.classList.add('animate');
});
}
});
}
}
| {'content_hash': '985213f5961237e0c7e523bf4e4acf68', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 88, 'avg_line_length': 21.25, 'alnum_prop': 0.5558823529411765, 'repo_name': 'jhlee8804/ionic', 'id': '4c8177771afe18818e70294477e40eaaaccd00d4', 'size': '680', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'src/components/tabs/tab-highlight.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '444281'}, {'name': 'HTML', 'bytes': '385111'}, {'name': 'JavaScript', 'bytes': '414713'}, {'name': 'PHP', 'bytes': '5956'}, {'name': 'Shell', 'bytes': '4282'}, {'name': 'TypeScript', 'bytes': '1635790'}]} |
<?php
namespace App;
use App\Support\BaseEnum;
/**
* Class PackageType
* @package App
*/
final class PackageType extends BaseEnum
{
const PAPER_BOX = 'PAPER_BOX';
const PLASTIC_BAG = 'PLASTIC_BAG';
}
| {'content_hash': 'ac4b2505e0ef2d622edea09207dc55d1', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 40, 'avg_line_length': 14.266666666666667, 'alnum_prop': 0.6728971962616822, 'repo_name': 'appkr/myshop', 'id': '980c0d76d3f31eafe1fe9a726073465f6664813c', 'size': '214', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/PackageType.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '1053'}, {'name': 'HTML', 'bytes': '33601'}, {'name': 'JavaScript', 'bytes': '1132'}, {'name': 'PHP', 'bytes': '609177'}, {'name': 'Shell', 'bytes': '2473'}, {'name': 'Vue', 'bytes': '563'}]} |
layout: post
title: How Does Image Detection Work?
---
| {'content_hash': 'aba197f8ec2cb630a08da5b762fc36cf', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 37, 'avg_line_length': 18.333333333333332, 'alnum_prop': 0.7272727272727273, 'repo_name': 'strongdan/blog', 'id': '26966774320bcf02a6057da434c91ed7a6a05353', 'size': '59', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': '_drafts/2017-09-29-Image-Detection.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '6266'}, {'name': 'SCSS', 'bytes': '63525'}]} |
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="500"
android:fillAfter="true"
android:fromYDelta="0%p"
android:interpolator="@android:anim/linear_interpolator"
android:toYDelta="100%p" />
</set> | {'content_hash': 'bc1b9a76a1ecee156b633695dcca51cc', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 64, 'avg_line_length': 32.4, 'alnum_prop': 0.6450617283950617, 'repo_name': 'jjhesk/URVSugarOverlay', 'id': 'e4e4efc96b0af8ddfebc24a3784ad43c9d4ce395', 'size': '324', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'LayoutCollection/LayoutCollections/src/main/res/anim/bottom_down.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '114446'}]} |
<?xml version="1.0" ?>
<!--
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Downloadable\Test\Handler\DownloadableProduct\DownloadableProductInterface" type="\Magento\Downloadable\Test\Handler\DownloadableProduct\Curl" />
</config>
| {'content_hash': 'c109f66a6021c0496edb804a5da54f4f', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 174, 'avg_line_length': 52.0, 'alnum_prop': 0.7802197802197802, 'repo_name': 'tarikgwa/test', 'id': '276496dbd53263405c7a313ecb20c542b056221c', 'size': '462', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'html/dev/tests/functional/tests/app/Magento/Downloadable/Test/etc/curl/di.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '26588'}, {'name': 'CSS', 'bytes': '4874492'}, {'name': 'HTML', 'bytes': '8635167'}, {'name': 'JavaScript', 'bytes': '6810903'}, {'name': 'PHP', 'bytes': '55645559'}, {'name': 'Perl', 'bytes': '7938'}, {'name': 'Shell', 'bytes': '4505'}, {'name': 'XSLT', 'bytes': '19889'}]} |
module ECoreTest__Around
class App < E
around do
begin
invoke_action
rescue => e
e.message
end
end
def index
something went wrong!
end
end
Spec.new App do
get
does(last_response.body) =~ /undefined method `wrong!'/
end
end
| {'content_hash': '553b05c0222e6aaa35f25371ca979381', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 59, 'avg_line_length': 12.708333333333334, 'alnum_prop': 0.5540983606557377, 'repo_name': 'wdiechmann/espresso', 'id': '52ef446f338d4e52d6ddfa9588459f6a533815b2', 'size': '305', 'binary': False, 'copies': '4', 'ref': 'refs/heads/whd-first', 'path': 'test/e-core/test__around.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '196121'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>MKPathFlags Struct Reference</title>
<link rel="stylesheet" type="text/css" href="../../css/jazzy.css" />
<link rel="stylesheet" type="text/css" href="../../css/highlight.css" />
<meta charset='utf-8'>
<script src="../../js/jquery.min.js" defer></script>
<script src="../../js/jazzy.js" defer></script>
</head>
<body>
<a name="//apple_ref/swift/Struct/MKPathFlags" class="dashAnchor"></a>
<a title="MKPathFlags Struct Reference"></a>
<header>
<div class="content-wrapper">
<p><a href="../../index.html">Appudo Docs</a></p>
<p class="header-right"><a href="https://www.github.com/Appudo"><img src="../../img/gh.png"/>View on GitHub</a></p>
</div>
</header>
<div class="content-wrapper">
<p id="breadcrumbs">
<a href="../../index.html">Appudo Reference</a>
<img id="carat" src="../../img/carat.png" />
MKPathFlags Struct Reference
</p>
</div>
<div class="content-wrapper">
<nav class="sidebar">
<ul class="nav-groups">
<li class="nav-group-name">
<a href="../../Classes.html">Classes</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../../Classes/Async.html">Async</a>
</li>
<li class="nav-group-task">
<a href="../../Classes/DataBlob.html">DataBlob</a>
</li>
<li class="nav-group-task">
<a href="../../Classes/FileItemList.html">FileItemList</a>
</li>
<li class="nav-group-task">
<a href="../../Classes/HTTPClient.html">HTTPClient</a>
</li>
<li class="nav-group-task">
<a href="../../Classes/HTTPClient/HTTPVersion.html">– HTTPVersion</a>
</li>
<li class="nav-group-task">
<a href="../../Classes/SQLQry.html">SQLQry</a>
</li>
<li class="nav-group-task">
<a href="../../Classes/UserList.html">UserList</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../../Enums.html">Enums</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../../Enums/AppudoError.html">AppudoError</a>
</li>
<li class="nav-group-task">
<a href="../../Enums.html#/s:6Appudo14ErrorEventTypeO">ErrorEventType</a>
</li>
<li class="nav-group-task">
<a href="../../Enums.html#/s:6Appudo17HTTPRequestStatusO">HTTPRequestStatus</a>
</li>
<li class="nav-group-task">
<a href="../../Enums.html#/s:6Appudo15HTTPRequestTypeO">HTTPRequestType</a>
</li>
<li class="nav-group-task">
<a href="../../Enums.html#/s:6Appudo4LangO">Lang</a>
</li>
<li class="nav-group-task">
<a href="../../Enums.html#/s:6Appudo8LinkTypeO">LinkType</a>
</li>
<li class="nav-group-task">
<a href="../../Enums/SQLQryError.html">SQLQryError</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../../Extensions.html">Extensions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../../Extensions/Date.html">Date</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../../Functions.html">Functions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../../Functions/<!(_:).html"><!(_:)</a>
</li>
<li class="nav-group-task">
<a href="../../Functions.html#/s:6Appudo2lqopSbyycF"><?(_:)</a>
</li>
<li class="nav-group-task">
<a href="../../Functions/<?(_:_:).html"><?(_:_:)</a>
</li>
<li class="nav-group-task">
<a href="../../Functions.html#/s:6Appudo12AlphasortASCs5Int32VAA13_UserListItemV1a_AF1btF">AlphasortASC(a:b:)</a>
</li>
<li class="nav-group-task">
<a href="../../Functions.html#/s:6Appudo12AlphasortASCs5Int32VAA8FileItemV1a_AF1btF">AlphasortASC(a:b:)</a>
</li>
<li class="nav-group-task">
<a href="../../Functions.html#/s:6Appudo12AlphasortDSCs5Int32VAA13_UserListItemV1a_AF1btF">AlphasortDSC(a:b:)</a>
</li>
<li class="nav-group-task">
<a href="../../Functions.html#/s:6Appudo12AlphasortDSCs5Int32VAA8FileItemV1a_AF1btF">AlphasortDSC(a:b:)</a>
</li>
<li class="nav-group-task">
<a href="../../Functions.html#/s:6Appudo13appudo_assertySbyXK_SSyXKs12StaticStringVSutF">appudo_assert(_:_:_:_:)</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../../Protocols.html">Protocols</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../../Protocols/Blob.html">Blob</a>
</li>
<li class="nav-group-task">
<a href="../../Protocols.html#/s:6Appudo15DataWriteSourceP">DataWriteSource</a>
</li>
<li class="nav-group-task">
<a href="../../Protocols/FileLockable.html">FileLockable</a>
</li>
<li class="nav-group-task">
<a href="../../Protocols/FileSeekable.html">FileSeekable</a>
</li>
<li class="nav-group-task">
<a href="../../Protocols/FileSendSource.html">FileSendSource</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../../Structs.html">Structs</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../../Structs/Account.html">Account</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/AccountID.html">AccountID</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/AsyncValue.html">AsyncValue</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/Dir.html">Dir</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/Domain.html">Domain</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/ErrorEvent.html">ErrorEvent</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/FileItem.html">FileItem</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/FileItem/Flag.html">– Flag</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/FileItem/RenameFlags.html">– RenameFlags</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/FileItem/MKPathFlags.html">– MKPathFlags</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/FileItem/Mode.html">– Mode</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/FileItem/AccessMode.html">– AccessMode</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/FileSeekFlag.html">FileSeekFlag</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/FileStat.html">FileStat</a>
</li>
<li class="nav-group-task">
<a href="../../Structs.html#/s:6Appudo8FileViewV">FileView</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/Group.html">Group</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/GroupID.html">GroupID</a>
</li>
<li class="nav-group-task">
<a href="../../Structs.html#/s:6Appudo9GroupInfoV">GroupInfo</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/Link.html">Link</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/Mail.html">Mail</a>
</li>
<li class="nav-group-task">
<a href="../../Structs.html#/s:6Appudo6MemVarV">MemVar</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/Memory.html">Memory</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/MenuItem.html">MenuItem</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/Page.html">Page</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/Role.html">Role</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/SQLQryValue.html">SQLQryValue</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/Setting.html">Setting</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/SettingVar.html">SettingVar</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/Socket.html">Socket</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/StaticDomain.html">StaticDomain</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/User.html">User</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/UserID.html">UserID</a>
</li>
<li class="nav-group-task">
<a href="../../Structs.html#/s:6Appudo8UserInfoV">UserInfo</a>
</li>
<li class="nav-group-task">
<a href="../../Structs/UserListItem.html">UserListItem</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../../Typealiases.html">Typealiases</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../../Typealiases.html#/s:6Appudo10AsyncDelaya">AsyncDelay</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="main-content">
<section>
<section class="section">
<h1>MKPathFlags</h1>
<div class="declaration">
<div class="language">
<pre class="highlight"><code><span class="kd">public</span> <span class="kd">struct</span> <span class="kt">MKPathFlags</span> <span class="p">:</span> <span class="kt">OptionSet</span></code></pre>
</div>
</div>
<p>MKPathFlags contains the mode used to create a directory path.</p>
<div class="aside aside-see-also">
<p class="aside-title">See also</p>
mkpath
</div>
</section>
<section class="section task-group-section">
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:s16RawRepresentableP8rawValue0aD0Qzv"></a>
<a name="//apple_ref/swift/Property/rawValue" class="dashAnchor"></a>
<a class="token" href="#/s:s16RawRepresentableP8rawValue0aD0Qzv">rawValue</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="kd">public</span> <span class="k">let</span> <span class="nv">rawValue</span><span class="p">:</span> <span class="kt">Int32</span></code></pre>
</div>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:s9OptionSetPx8RawValueQz03rawD0_tcfc"></a>
<a name="//apple_ref/swift/Method/init(rawValue:)" class="dashAnchor"></a>
<a class="token" href="#/s:s9OptionSetPx8RawValueQz03rawD0_tcfc">init(rawValue:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="kd">public</span> <span class="nf">init</span><span class="p">(</span><span class="nv">rawValue</span><span class="p">:</span><span class="kt">Int32</span><span class="p">)</span></code></pre>
</div>
</div>
<div>
<h4>Parameters</h4>
<table class="graybox">
<tbody>
<tr>
<td>
<code>
<em>rawValue</em>
</code>
</td>
<td>
<div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:6Appudo8FileItemV11MKPathFlagsV4NONEAEvZ"></a>
<a name="//apple_ref/swift/Variable/NONE" class="dashAnchor"></a>
<a class="token" href="#/s:6Appudo8FileItemV11MKPathFlagsV4NONEAEvZ">NONE</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Default is to enter existing directories.</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="k">let</span> <span class="nv">NONE</span> <span class="o">=</span> <span class="kt">MKPathFlags</span><span class="p">(</span><span class="nv">rawValue</span><span class="p">:</span> <span class="mi">0</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:6Appudo8FileItemV11MKPathFlagsV9EXCLUSIVEAEvZ"></a>
<a name="//apple_ref/swift/Variable/EXCLUSIVE" class="dashAnchor"></a>
<a class="token" href="#/s:6Appudo8FileItemV11MKPathFlagsV9EXCLUSIVEAEvZ">EXCLUSIVE</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Do not enter existing directories.</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="k">let</span> <span class="nv">EXCLUSIVE</span> <span class="o">=</span> <span class="kt">MKPathFlags</span><span class="p">(</span><span class="nv">rawValue</span><span class="p">:</span> <span class="mi">1</span><span class="p">)</span></code></pre>
</div>
</div>
</section>
</div>
</li>
</ul>
</div>
</section>
</section>
<section id="footer">
<p>© 2017 <a class="link" href="" target="_blank" rel="external">[email protected]</a>. All rights reserved. (Last updated: 2017-08-01)</p>
<p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.8.3</a>, a <a class="link" href="http://realm.io" target="_blank" rel="external">Realm</a> project.</p>
</section>
</article>
</div>
</body>
</div>
</html>
| {'content_hash': '6959fb10002fa1cff198a9ad0615ce06', 'timestamp': '', 'source': 'github', 'line_count': 415, 'max_line_length': 383, 'avg_line_length': 44.81927710843374, 'alnum_prop': 0.43672043010752687, 'repo_name': 'Appudo/Appudo.github.io', 'id': '092f910261e94c3e01fc98597bdbf2372086a4d3', 'size': '18616', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'static/dashs/showcase/d/pub/docs_0.1.30/docsets/Appudo.docset/Contents/Resources/Documents/Structs/FileItem/MKPathFlags.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ActionScript', 'bytes': '17567'}, {'name': 'AngelScript', 'bytes': '2387'}, {'name': 'Batchfile', 'bytes': '963'}, {'name': 'C', 'bytes': '4472258'}, {'name': 'C++', 'bytes': '8096232'}, {'name': 'CSS', 'bytes': '1598579'}, {'name': 'HTML', 'bytes': '22733727'}, {'name': 'JavaScript', 'bytes': '26918138'}, {'name': 'Objective-C', 'bytes': '231'}, {'name': 'PHP', 'bytes': '38090'}, {'name': 'PLpgSQL', 'bytes': '48798'}, {'name': 'Python', 'bytes': '5025'}, {'name': 'SQLPL', 'bytes': '877'}, {'name': 'Shell', 'bytes': '3787'}, {'name': 'Swift', 'bytes': '465672'}, {'name': 'TSQL', 'bytes': '12185'}, {'name': 'XSLT', 'bytes': '47380'}]} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '418e28bdf29249c682941c0f79564b01', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': '3fc55ab7958f11cd83e42043cbdff6c22d1568f7', 'size': '184', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Arecales/Arecaceae/Orania/Orania paraguanensis/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
/*****************************************************************************/
/* MasterLayout: Event Handlers and Helpersss .js*/
/*****************************************************************************/
Template.MasterLayout.events({
/*
* Example:
* 'click .selector': function (e, tmpl) {
*
* }
*/
});
Template.MasterLayout.helpers({
/*
* Example:
* items: function () {
* return Items.find();
* }
*/
});
/*****************************************************************************/
/* MasterLayout: Lifecycle Hooks */
/*****************************************************************************/
Template.MasterLayout.created = function () {
};
Template.MasterLayout.rendered = function () {
};
Template.MasterLayout.destroyed = function () {
}; | {'content_hash': 'd9199abe4473ef5b49701651b19f99b4', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 79, 'avg_line_length': 25.15625, 'alnum_prop': 0.3652173913043478, 'repo_name': 'JSSolutions/images-grid', 'id': '3a3415354466a0138980b11a345dc6bcd78426a7', 'size': '805', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'app/client/views/layouts/master_layout/master_layout.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1036'}, {'name': 'HTML', 'bytes': '2451'}, {'name': 'JavaScript', 'bytes': '5630'}]} |
using Talifun.Commander.Command.ConfigurationChecker.Response;
namespace Talifun.Commander.Command.Audio.CommandTester.Response
{
public class AudioConversionConfigurationTestResponseMessage : ConfigurationTestResponseMessageBase
{
}
}
| {'content_hash': 'a1f6e233574055648c8ef21ec260861f', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 100, 'avg_line_length': 30.125, 'alnum_prop': 0.8630705394190872, 'repo_name': 'taliesins/talifun-commander', 'id': '52c376f9d738fc033c833c29f5cb94700d730187', 'size': '243', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Talifun.Commander.Command.Audio/CommandTester/Response/AudioConversionConfigurationTestResponseMessage.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '3743'}, {'name': 'C#', 'bytes': '900779'}, {'name': 'Cucumber', 'bytes': '758'}, {'name': 'PowerShell', 'bytes': '66947'}, {'name': 'Shell', 'bytes': '1319'}]} |
package org.motechproject.nms.imi.exception;
public class InternalException extends IllegalStateException {
public InternalException(String message) {
super(message);
}
public InternalException(String message, Throwable cause) {
super(message, cause);
}
}
| {'content_hash': '56093b6c424ce060a7499bc88362318e', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 63, 'avg_line_length': 26.363636363636363, 'alnum_prop': 0.7206896551724138, 'repo_name': 'motech-implementations/mim', 'id': 'b6fa3c7fb132f769db9aa725856275f1a0e4753d', 'size': '290', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'imi/src/main/java/org/motechproject/nms/imi/exception/InternalException.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '142'}, {'name': 'HTML', 'bytes': '1005'}, {'name': 'Java', 'bytes': '2429312'}, {'name': 'Python', 'bytes': '47962'}, {'name': 'Shell', 'bytes': '166'}]} |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics.Log;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.EngineV1
{
internal partial class DiagnosticIncrementalAnalyzer
{
public override Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Solution solution, object id, CancellationToken cancellationToken)
{
return new IDECachedDiagnosticGetter(this).GetSpecificDiagnosticsAsync(solution, id, cancellationToken);
}
public override Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Solution solution, ProjectId projectId, DocumentId documentId, CancellationToken cancellationToken)
{
return new IDECachedDiagnosticGetter(this).GetDiagnosticsAsync(solution, projectId, documentId, cancellationToken);
}
public override Task<ImmutableArray<DiagnosticData>> GetSpecificDiagnosticsAsync(Solution solution, object id, CancellationToken cancellationToken)
{
return new IDELatestDiagnosticGetter(this).GetSpecificDiagnosticsAsync(solution, id, cancellationToken);
}
public override Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId projectId, DocumentId documentId, CancellationToken cancellationToken)
{
return new IDELatestDiagnosticGetter(this).GetDiagnosticsAsync(solution, projectId, documentId, cancellationToken);
}
public override Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(Solution solution, ProjectId projectId, DocumentId documentId, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
{
// Fix all code path, we can make computation concurrent if we are computing diagnostics across a project/solution.
return new IDELatestDiagnosticGetter(this, diagnosticIds, concurrent: documentId == null).GetDiagnosticsAsync(solution, projectId, documentId, cancellationToken);
}
public override Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId projectId, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
{
// Fix all code path, we can make computation concurrent if we are computing project diagnostics across solution.
return new IDELatestDiagnosticGetter(this, diagnosticIds, concurrent: projectId == null).GetProjectDiagnosticsAsync(solution, projectId, cancellationToken);
}
private Task ReanalyzeAllDocumentsAsync(Project project, DiagnosticAnalyzer analyzer, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
{
return new ReanalysisDiagnosticGetter(this, analyzer, diagnosticIds).ReanalyzeAllDocumentsAsync(project, cancellationToken);
}
private abstract class DiagnosticsGetter
{
protected readonly DiagnosticIncrementalAnalyzer Owner;
private ImmutableArray<DiagnosticData>.Builder _builder;
public DiagnosticsGetter(DiagnosticIncrementalAnalyzer owner)
{
this.Owner = owner;
}
protected StateManager StateManager
{
get { return this.Owner._stateManager; }
}
protected virtual bool ConcurrentDocumentComputation => false;
protected abstract Task AppendDocumentDiagnosticsOfStateTypeAsync(Document document, StateType stateType, CancellationToken cancellationToken);
protected abstract Task AppendProjectAndDocumentDiagnosticsAsync(Project project, Document document, Func<DiagnosticData, bool> predicate, CancellationToken cancellationToken);
public async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId projectId, DocumentId documentId, CancellationToken cancellationToken)
{
if (solution == null)
{
return GetDiagnosticData();
}
if (documentId != null)
{
var document = solution.GetDocument(documentId);
await AppendDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false);
await AppendProjectAndDocumentDiagnosticsAsync(document.Project, document, d => d.DocumentId == documentId, cancellationToken).ConfigureAwait(false);
return GetDiagnosticData();
}
if (projectId != null)
{
await AppendDiagnosticsAsync(solution.GetProject(projectId), cancellationToken: cancellationToken).ConfigureAwait(false);
return GetDiagnosticData();
}
await AppendDiagnosticsAsync(solution, cancellationToken: cancellationToken).ConfigureAwait(false);
return GetDiagnosticData();
}
public async Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsAsync(Solution solution, ProjectId projectId, CancellationToken cancellationToken)
{
if (solution == null)
{
return GetDiagnosticData();
}
if (projectId != null)
{
await AppendProjectDiagnosticsAsync(solution.GetProject(projectId), cancellationToken: cancellationToken).ConfigureAwait(false);
return GetDiagnosticData();
}
await AppendProjectDiagnosticsAsync(solution, cancellationToken).ConfigureAwait(false);
return GetDiagnosticData();
}
private async Task AppendProjectDiagnosticsAsync(Solution solution, CancellationToken cancellationToken)
{
if (solution == null)
{
return;
}
foreach (var project in solution.Projects)
{
cancellationToken.ThrowIfCancellationRequested();
await AppendProjectDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
}
}
private Task AppendProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken)
{
if (project == null)
{
return SpecializedTasks.EmptyTask;
}
return AppendProjectAndDocumentDiagnosticsAsync(project, null, d => d.ProjectId == project.Id, cancellationToken);
}
private async Task AppendDiagnosticsAsync(Solution solution, CancellationToken cancellationToken)
{
if (solution == null)
{
return;
}
foreach (var project in solution.Projects)
{
cancellationToken.ThrowIfCancellationRequested();
await AppendDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
}
}
private async Task AppendDiagnosticsAsync(Project project, CancellationToken cancellationToken)
{
if (project == null)
{
return;
}
await AppendProjectAndDocumentDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
if (!ConcurrentDocumentComputation)
{
foreach (var document in project.Documents)
{
await AppendDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false);
}
}
else
{
var documents = project.Documents.ToImmutableArray();
var tasks = new Task[documents.Length];
for (int i = 0; i < documents.Length; i++)
{
var document = documents[i];
tasks[i] = Task.Run(async () => await AppendDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false), cancellationToken);
};
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
protected Task AppendProjectAndDocumentDiagnosticsAsync(Project project, CancellationToken cancellationToken)
{
return AppendProjectAndDocumentDiagnosticsAsync(project, null, d => true, cancellationToken);
}
protected async Task AppendDiagnosticsAsync(Document document, CancellationToken cancellationToken)
{
if (document == null)
{
return;
}
await AppendDocumentDiagnosticsOfStateTypeAsync(document, StateType.Syntax, cancellationToken).ConfigureAwait(false);
await AppendDocumentDiagnosticsOfStateTypeAsync(document, StateType.Document, cancellationToken).ConfigureAwait(false);
}
protected virtual void AppendDiagnostics(IEnumerable<DiagnosticData> items)
{
_builder = _builder ?? ImmutableArray.CreateBuilder<DiagnosticData>();
_builder.AddRange(items);
}
protected virtual ImmutableArray<DiagnosticData> GetDiagnosticData()
{
return _builder != null ? _builder.ToImmutable() : ImmutableArray<DiagnosticData>.Empty;
}
protected static ProjectId GetProjectId(object key)
{
var documentId = key as DocumentId;
if (documentId != null)
{
return documentId.ProjectId;
}
var projectId = key as ProjectId;
if (projectId != null)
{
return projectId;
}
return Contract.FailWithReturn<ProjectId>("Shouldn't reach here");
}
protected static object GetProjectOrDocument(Solution solution, object key)
{
var documentId = key as DocumentId;
if (documentId != null)
{
return solution.GetDocument(documentId);
}
var projectId = key as ProjectId;
if (projectId != null)
{
return solution.GetProject(projectId);
}
return Contract.FailWithReturn<object>("Shouldn't reach here");
}
}
private class IDECachedDiagnosticGetter : DiagnosticsGetter
{
public IDECachedDiagnosticGetter(DiagnosticIncrementalAnalyzer owner) : base(owner)
{
}
public async Task<ImmutableArray<DiagnosticData>> GetSpecificDiagnosticsAsync(Solution solution, object id, CancellationToken cancellationToken)
{
if (solution == null)
{
return ImmutableArray<DiagnosticData>.Empty;
}
var key = id as ArgumentKey;
if (key == null)
{
return ImmutableArray<DiagnosticData>.Empty;
}
var projectId = GetProjectId(key.Key);
var project = solution.GetProject(projectId);
// when we return cached result, make sure we at least return something that exist in current solution
if (project == null)
{
return ImmutableArray<DiagnosticData>.Empty;
}
var stateSet = this.StateManager.GetOrCreateStateSet(project, key.Analyzer);
if (stateSet == null)
{
return ImmutableArray<DiagnosticData>.Empty;
}
var state = stateSet.GetState(key.StateType);
if (state == null)
{
return ImmutableArray<DiagnosticData>.Empty;
}
// for now, it just use wait and get result
var documentOrProject = GetProjectOrDocument(solution, key.Key);
if (documentOrProject == null)
{
// Document or project might have been removed from the solution.
return ImmutableArray<DiagnosticData>.Empty;
}
var existingData = await state.TryGetExistingDataAsync(documentOrProject, cancellationToken).ConfigureAwait(false);
if (existingData == null)
{
return ImmutableArray<DiagnosticData>.Empty;
}
return existingData.Items;
}
protected override async Task AppendDocumentDiagnosticsOfStateTypeAsync(Document document, StateType stateType, CancellationToken cancellationToken)
{
foreach (var stateSet in this.StateManager.GetStateSets(document.Project))
{
cancellationToken.ThrowIfCancellationRequested();
var state = stateSet.GetState(stateType);
var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
if (existingData == null || existingData.Items.Length == 0)
{
continue;
}
AppendDiagnostics(existingData.Items);
}
}
protected override async Task AppendProjectAndDocumentDiagnosticsAsync(
Project project, Document document, Func<DiagnosticData, bool> predicate, CancellationToken cancellationToken)
{
var documents = document == null ? project.Documents.ToList() : SpecializedCollections.SingletonEnumerable(document);
foreach (var stateSet in this.StateManager.GetStateSets(project))
{
cancellationToken.ThrowIfCancellationRequested();
var state = stateSet.GetState(StateType.Project);
await AppendProjectAndDocumentDiagnosticsAsync(state, project, predicate, cancellationToken).ConfigureAwait(false);
foreach (var current in documents)
{
await AppendProjectAndDocumentDiagnosticsAsync(state, current, predicate, cancellationToken).ConfigureAwait(false);
}
}
}
private async Task AppendProjectAndDocumentDiagnosticsAsync(DiagnosticState state, object documentOrProject, Func<DiagnosticData, bool> predicate, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var existingData = await state.TryGetExistingDataAsync(documentOrProject, cancellationToken).ConfigureAwait(false);
if (existingData == null || existingData.Items.Length == 0)
{
return;
}
AppendDiagnostics(existingData.Items.Where(predicate));
}
}
private abstract class LatestDiagnosticsGetter : DiagnosticsGetter
{
protected readonly ImmutableHashSet<string> DiagnosticIds;
public LatestDiagnosticsGetter(DiagnosticIncrementalAnalyzer owner, ImmutableHashSet<string> diagnosticIds) : base(owner)
{
this.DiagnosticIds = diagnosticIds;
}
protected abstract Task<AnalysisData> GetDiagnosticAnalysisDataAsync(Solution solution, DiagnosticAnalyzerDriver analyzerDriver, StateSet stateSet, StateType stateType, VersionArgument versions);
protected abstract void FilterDiagnostics(AnalysisData analysisData, Func<DiagnosticData, bool> predicateOpt = null);
protected override Task AppendDocumentDiagnosticsOfStateTypeAsync(Document document, StateType stateType, CancellationToken cancellationToken)
{
return AppendDiagnosticsOfStateTypeAsync(document, stateType, d => true, cancellationToken);
}
protected override Task AppendProjectAndDocumentDiagnosticsAsync(Project project, Document document, Func<DiagnosticData, bool> predicate, CancellationToken cancellationToken)
{
return AppendDiagnosticsOfStateTypeAsync(project, StateType.Project, predicate, cancellationToken);
}
protected async Task<DiagnosticAnalyzerDriver> GetDiagnosticAnalyzerDriverAsync(object documentOrProject, StateType stateType, CancellationToken cancellationToken)
{
var document = documentOrProject as Document;
if (document != null)
{
Contract.Requires(stateType != StateType.Project);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return new DiagnosticAnalyzerDriver(document, root.FullSpan, root, this.Owner, cancellationToken);
}
var project = documentOrProject as Project;
if (project != null)
{
Contract.Requires(stateType == StateType.Project);
return new DiagnosticAnalyzerDriver(project, this.Owner, cancellationToken);
}
return Contract.FailWithReturn<DiagnosticAnalyzerDriver>("Can't reach here");
}
protected async Task<VersionArgument> GetVersionsAsync(object documentOrProject, StateType stateType, CancellationToken cancellationToken)
{
switch (stateType)
{
case StateType.Syntax:
{
var document = (Document)documentOrProject;
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var syntaxVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
return new VersionArgument(textVersion, syntaxVersion);
}
case StateType.Document:
{
var document = (Document)documentOrProject;
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var semanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
return new VersionArgument(textVersion, semanticVersion);
}
case StateType.Project:
{
var project = (Project)documentOrProject;
var projectTextVersion = await project.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false);
var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
return new VersionArgument(projectTextVersion, semanticVersion, projectVersion);
}
default:
return Contract.FailWithReturn<VersionArgument>("Can't reach here");
}
}
private async Task AppendDiagnosticsOfStateTypeAsync(object documentOrProject, StateType stateType, Func<DiagnosticData, bool> predicateOpt, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(documentOrProject);
var project = GetProject(documentOrProject);
var solution = project.Solution;
var driver = await GetDiagnosticAnalyzerDriverAsync(documentOrProject, stateType, cancellationToken).ConfigureAwait(false);
var versions = await GetVersionsAsync(documentOrProject, stateType, cancellationToken).ConfigureAwait(false);
foreach (var stateSet in this.StateManager.GetOrCreateStateSets(project))
{
cancellationToken.ThrowIfCancellationRequested();
if (driver.IsAnalyzerSuppressed(stateSet.Analyzer) ||
!(await this.Owner.ShouldRunAnalyzerForStateTypeAsync(driver, stateSet.Analyzer, stateType, this.DiagnosticIds).ConfigureAwait(false)))
{
continue;
}
var analysisData = await GetDiagnosticAnalysisDataAsync(solution, driver, stateSet, stateType, versions).ConfigureAwait(false);
FilterDiagnostics(analysisData, predicateOpt);
}
}
protected Project GetProject(object documentOrProject)
{
var document = documentOrProject as Document;
if (document != null)
{
return document.Project;
}
return (Project)documentOrProject;
}
private DiagnosticLogAggregator DiagnosticLogAggregator
{
get { return this.Owner.DiagnosticLogAggregator; }
}
}
private class ReanalysisDiagnosticGetter : LatestDiagnosticsGetter
{
private readonly DiagnosticAnalyzer _analyzer;
public ReanalysisDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, DiagnosticAnalyzer analyzer, ImmutableHashSet<string> diagnosticIds) : base(owner, diagnosticIds)
{
_analyzer = analyzer;
}
public async Task ReanalyzeAllDocumentsAsync(Project project, CancellationToken cancellationToken)
{
foreach (var document in project.Documents)
{
cancellationToken.ThrowIfCancellationRequested();
await AppendDiagnosticsAsync(document, cancellationToken).ConfigureAwait(false);
}
}
protected override void FilterDiagnostics(AnalysisData analysisData, Func<DiagnosticData, bool> predicateOpt = null)
{
// we don't care about result
return;
}
protected override async Task<AnalysisData> GetDiagnosticAnalysisDataAsync(
Solution solution, DiagnosticAnalyzerDriver analyzerDriver, StateSet stateSet, StateType stateType, VersionArgument versions)
{
// we don't care about result
switch (stateType)
{
case StateType.Syntax:
await GetSyntaxDiagnosticsAsync(analyzerDriver, _analyzer).ConfigureAwait(false);
break;
case StateType.Document:
await GetSemanticDiagnosticsAsync(analyzerDriver, _analyzer).ConfigureAwait(false);
break;
case StateType.Project:
default:
return Contract.FailWithReturn<AnalysisData>("Can't reach here");
}
return AnalysisData.Empty;
}
}
private class IDELatestDiagnosticGetter : LatestDiagnosticsGetter
{
private readonly bool _concurrent;
private ConcurrentBag<DiagnosticData> _concurrentBag;
public IDELatestDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, bool concurrent = false) : this(owner, null, concurrent)
{
}
public IDELatestDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, ImmutableHashSet<string> diagnosticIds, bool concurrent = false) : base(owner, diagnosticIds)
{
_concurrent = concurrent;
}
protected override bool ConcurrentDocumentComputation => _concurrent;
protected override void AppendDiagnostics(IEnumerable<DiagnosticData> items)
{
if (!ConcurrentDocumentComputation)
{
base.AppendDiagnostics(items);
return;
}
if (_concurrentBag == null)
{
Interlocked.CompareExchange(ref _concurrentBag, new ConcurrentBag<DiagnosticData>(), null);
}
foreach (var item in items)
{
_concurrentBag.Add(item);
}
}
protected override ImmutableArray<DiagnosticData> GetDiagnosticData()
{
if (!ConcurrentDocumentComputation)
{
return base.GetDiagnosticData();
}
return _concurrentBag != null ? _concurrentBag.ToImmutableArray() : ImmutableArray<DiagnosticData>.Empty;
}
public async Task<ImmutableArray<DiagnosticData>> GetSpecificDiagnosticsAsync(Solution solution, object id, CancellationToken cancellationToken)
{
if (solution == null)
{
return ImmutableArray<DiagnosticData>.Empty;
}
var key = id as ArgumentKey;
if (key == null)
{
return ImmutableArray<DiagnosticData>.Empty;
}
var documentOrProject = GetProjectOrDocument(solution, key.Key);
if (documentOrProject == null)
{
// Document or project might have been removed from the solution.
return ImmutableArray<DiagnosticData>.Empty;
}
if (key.StateType != StateType.Project)
{
return await GetDiagnosticsAsync(documentOrProject, key, cancellationToken).ConfigureAwait(false);
}
return await GetDiagnosticsAsync(GetProject(documentOrProject), key, cancellationToken).ConfigureAwait(false);
}
private async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(object documentOrProject, ArgumentKey key, CancellationToken cancellationToken)
{
var driver = await GetDiagnosticAnalyzerDriverAsync(documentOrProject, key.StateType, cancellationToken).ConfigureAwait(false);
var versions = await GetVersionsAsync(documentOrProject, key.StateType, cancellationToken).ConfigureAwait(false);
var project = GetProject(documentOrProject);
var stateSet = this.StateManager.GetOrCreateStateSet(project, key.Analyzer);
if (stateSet == null)
{
return ImmutableArray<DiagnosticData>.Empty;
}
var analysisData = await GetDiagnosticAnalysisDataAsync(project.Solution, driver, stateSet, key.StateType, versions).ConfigureAwait(false);
if (key.StateType != StateType.Project)
{
return analysisData.Items;
}
return analysisData.Items.Where(d =>
{
if (key.Key is DocumentId)
{
return object.Equals(d.DocumentId, key.Key);
}
if (key.Key is ProjectId)
{
return object.Equals(d.ProjectId, key.Key);
}
return false;
}).ToImmutableArray();
}
protected override void FilterDiagnostics(AnalysisData analysisData, Func<DiagnosticData, bool> predicateOpt)
{
if (predicateOpt == null)
{
AppendDiagnostics(analysisData.Items.Where(d => this.DiagnosticIds == null || this.DiagnosticIds.Contains(d.Id)));
return;
}
AppendDiagnostics(analysisData.Items.Where(d => this.DiagnosticIds == null || this.DiagnosticIds.Contains(d.Id)).Where(predicateOpt));
}
protected override Task<AnalysisData> GetDiagnosticAnalysisDataAsync(
Solution solution, DiagnosticAnalyzerDriver analyzerDriver, StateSet stateSet, StateType stateType, VersionArgument versions)
{
switch (stateType)
{
case StateType.Syntax:
return this.AnalyzerExecutor.GetSyntaxAnalysisDataAsync(analyzerDriver, stateSet, versions);
case StateType.Document:
return this.AnalyzerExecutor.GetDocumentAnalysisDataAsync(analyzerDriver, stateSet, versions);
case StateType.Project:
return this.AnalyzerExecutor.GetProjectAnalysisDataAsync(analyzerDriver, stateSet, versions);
default:
return Contract.FailWithReturn<Task<AnalysisData>>("Can't reach here");
}
}
protected AnalyzerExecutor AnalyzerExecutor
{
get { return this.Owner._executor; }
}
}
}
}
| {'content_hash': 'd8093845e739763a74882e0808060ccd', 'timestamp': '', 'source': 'github', 'line_count': 660, 'max_line_length': 226, 'avg_line_length': 45.53333333333333, 'alnum_prop': 0.5962331957939572, 'repo_name': 'tsdl2013/roslyn', 'id': '193a27d1fb51af408220811d185043898454af2a', 'size': '30054', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'src/Features/Core/Diagnostics/EngineV1/DiagnosticIncrementalAnalyzer_GetDiagnostics.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '8935'}, {'name': 'C#', 'bytes': '72612905'}, {'name': 'C++', 'bytes': '3744'}, {'name': 'F#', 'bytes': '421'}, {'name': 'PowerShell', 'bytes': '8550'}, {'name': 'Shell', 'bytes': '7164'}, {'name': 'Visual Basic', 'bytes': '58468439'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<section name="Workbench">
<section name="CheatSheetCategoryBasedSelectionDialog">
<item value="416" key="DIALOG_WIDTH"/>
<item value="1|Ubuntu|11.0|0|GTK|1|" key="DIALOG_FONT_NAME"/>
<item value="689" key="DIALOG_HEIGHT"/>
<item value="714" key="DIALOG_X_ORIGIN"/>
<item value="80" key="DIALOG_Y_ORIGIN"/>
</section>
</section>
| {'content_hash': '9e6f60ca7cb4fdc3768d71751170b794', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 63, 'avg_line_length': 38.0, 'alnum_prop': 0.6736842105263158, 'repo_name': 'Omni-J/TUES-Tasks', 'id': '3fc420724310f23b60a020d9d00805b7c15c73cc', 'size': '380', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'JavaSpace/.metadata/.plugins/org.eclipse.ui.cheatsheets/dialog_settings.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '52891'}, {'name': 'C++', 'bytes': '37687'}, {'name': 'CSS', 'bytes': '55'}, {'name': 'HTML', 'bytes': '2080'}, {'name': 'Java', 'bytes': '59748'}, {'name': 'JavaScript', 'bytes': '244333'}, {'name': 'Makefile', 'bytes': '101'}, {'name': 'PostScript', 'bytes': '13107996'}, {'name': 'Python', 'bytes': '1999'}, {'name': 'Ruby', 'bytes': '6790'}]} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/w3"
android:orientation="vertical">
<include layout="@layout/util_normal_title" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:divider="@null"
android:scrollbars="none" />
<TextView
android:id="@+id/dialog"
android:layout_width="80.0dip"
android:layout_height="80.0dip"
android:layout_gravity="center"
android:background="@drawable/circular_4_g0"
android:gravity="center"
android:textColor="#ffffffff"
android:textSize="30.0dip"
android:visibility="invisible" />
<com.xiaoshangxing.publicActivity.selectPerson.SideBar
android:id="@+id/sidebar"
android:layout_width="30.0dip"
android:layout_height="fill_parent"
android:layout_gravity="right|center" />
</FrameLayout>
</LinearLayout> | {'content_hash': '63205ea69c3c6f835a8036c6d661776e', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 72, 'avg_line_length': 33.80487804878049, 'alnum_prop': 0.6082251082251082, 'repo_name': 'JNDX25219/XiaoShangXing', 'id': '0b07f8d0b97a2347a91a8980786323914d64f50f', 'size': '1386', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/activity_yujian_newgroupmaster.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '2955459'}]} |
package com.lite.android.launcher3.allapps;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import com.lite.android.launcher3.BaseRecyclerView;
import com.lite.android.launcher3.DeviceProfile;
import com.lite.android.launcher3.BaseRecyclerViewFastScrollBar.FastScrollFocusApplicator;
import com.lite.android.launcher3.R;
import com.lite.android.launcher3.Stats;
import com.lite.android.launcher3.Utilities;
import com.lite.android.launcher3.util.Thunk;
import java.util.ArrayList;
import java.util.List;
/**
* A RecyclerView with custom fast scroll support for the all apps view.
*/
public class AllAppsRecyclerView extends BaseRecyclerView
implements Stats.LaunchSourceProvider {
private static final int FAST_SCROLL_MODE_JUMP_TO_FIRST_ICON = 0;
private static final int FAST_SCROLL_MODE_FREE_SCROLL = 1;
private static final int FAST_SCROLL_BAR_MODE_DISTRIBUTE_BY_ROW = 0;
private static final int FAST_SCROLL_BAR_MODE_DISTRIBUTE_BY_SECTIONS = 1;
private AlphabeticalAppsList mApps;
private int mNumAppsPerRow;
private int mSectionStrategy = AllAppsContainerView.SECTION_STRATEGY_RAGGED;
@Thunk ArrayList<View> mLastFastScrollFocusedViews = new ArrayList();
@Thunk int mPrevFastScrollFocusedPosition;
@Thunk AlphabeticalAppsList.SectionInfo mPrevFastScrollFocusedSection;
@Thunk int mFastScrollFrameIndex;
@Thunk final int[] mFastScrollFrames = new int[10];
private final int mFastScrollMode = FAST_SCROLL_MODE_JUMP_TO_FIRST_ICON;
private final int mScrollBarMode = FAST_SCROLL_BAR_MODE_DISTRIBUTE_BY_ROW;
private ScrollPositionState mScrollPosState = new ScrollPositionState();
private boolean mFastScrollDragging;
private AllAppsBackgroundDrawable mEmptySearchBackground;
private int mEmptySearchBackgroundTopOffset;
public AllAppsRecyclerView(Context context) {
this(context, null);
}
public AllAppsRecyclerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AllAppsRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public AllAppsRecyclerView(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr);
Resources res = getResources();
if (mUseScrollbar) {
mScrollbar.setDetachThumbOnFastScroll();
}
mEmptySearchBackgroundTopOffset = res.getDimensionPixelSize(
R.dimen.all_apps_empty_search_bg_top_offset);
addOnScrollListener(new FocusScrollListener());
}
private class FocusScrollListener extends OnScrollListener {
public FocusScrollListener() { }
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
switch (newState) {
case SCROLL_STATE_IDLE:
// Don't change anything if we've stopped touching the scroll bar.
if (mFastScrollDragging) {
// Animation completed, set the fast scroll state on the target views
setSectionFastScrollFocused(mPrevFastScrollFocusedPosition);
setSectionFastScrollDimmed(mPrevFastScrollFocusedPosition, false, true);
}
}
}
}
/**
* Sets the list of apps in this view, used to determine the fastscroll position.
*/
public void setApps(AlphabeticalAppsList apps) {
mApps = apps;
}
/**
* Sets the number of apps per row in this recycler view.
*/
public void setNumAppsPerRow(DeviceProfile grid, int numAppsPerRow) {
mNumAppsPerRow = numAppsPerRow;
RecyclerView.RecycledViewPool pool = getRecycledViewPool();
int approxRows = (int) Math.ceil(grid.availableHeightPx / grid.allAppsIconSizePx);
pool.setMaxRecycledViews(AllAppsGridAdapter.EMPTY_SEARCH_VIEW_TYPE, 1);
pool.setMaxRecycledViews(AllAppsGridAdapter.SEARCH_MARKET_DIVIDER_VIEW_TYPE, 1);
pool.setMaxRecycledViews(AllAppsGridAdapter.SEARCH_MARKET_VIEW_TYPE, 1);
pool.setMaxRecycledViews(AllAppsGridAdapter.ICON_VIEW_TYPE, approxRows * mNumAppsPerRow);
pool.setMaxRecycledViews(AllAppsGridAdapter.PREDICTION_ICON_VIEW_TYPE, mNumAppsPerRow);
pool.setMaxRecycledViews(AllAppsGridAdapter.SECTION_BREAK_VIEW_TYPE, approxRows);
pool.setMaxRecycledViews(AllAppsGridAdapter.CUSTOM_PREDICTED_APPS_HEADER_VIEW_TYPE, 1);
pool.setMaxRecycledViews(AllAppsGridAdapter.CUSTOM_PREDICTED_APPS_FOOTER_VIEW_TYPE, 1);
}
public void setSectionStrategy(int sectionStrategy) {
mSectionStrategy = sectionStrategy;
}
/**
* Scrolls this recycler view to the top.
*/
public void scrollToTop() {
if (mUseScrollbar) {
// Ensure we reattach the scrollbar if it was previously detached while fast-scrolling
if (mScrollbar.isThumbDetached()) {
mScrollbar.reattachThumbToScroll();
}
}
scrollToPosition(0);
}
/**
* We need to override the draw to ensure that we don't draw the overscroll effect beyond the
* background bounds.
*/
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.clipRect(mBackgroundPadding.left, mBackgroundPadding.top,
getWidth() - mBackgroundPadding.right,
getHeight() - mBackgroundPadding.bottom);
super.dispatchDraw(canvas);
}
@Override
public void onDraw(Canvas c) {
// Draw the background
if (mEmptySearchBackground != null && mEmptySearchBackground.getAlpha() > 0) {
c.clipRect(mBackgroundPadding.left, mBackgroundPadding.top,
getWidth() - mBackgroundPadding.right,
getHeight() - mBackgroundPadding.bottom);
mEmptySearchBackground.draw(c);
}
super.onDraw(c);
}
@Override
protected boolean verifyDrawable(Drawable who) {
return who == mEmptySearchBackground || super.verifyDrawable(who);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
updateEmptySearchBackgroundBounds();
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
// Bind event handlers
addOnItemTouchListener(this);
}
@Override
public void fillInLaunchSourceData(Bundle sourceData) {
sourceData.putString(Stats.SOURCE_EXTRA_CONTAINER, Stats.CONTAINER_ALL_APPS);
if (mApps.hasFilter()) {
sourceData.putString(Stats.SOURCE_EXTRA_SUB_CONTAINER,
Stats.SUB_CONTAINER_ALL_APPS_SEARCH);
} else {
sourceData.putString(Stats.SOURCE_EXTRA_SUB_CONTAINER,
Stats.SUB_CONTAINER_ALL_APPS_A_Z);
}
}
public void onSearchResultsChanged() {
// Always scroll the view to the top so the user can see the changed results
scrollToTop();
if (mApps.hasNoFilteredResults()) {
if (mEmptySearchBackground == null) {
mEmptySearchBackground = new AllAppsBackgroundDrawable(getContext());
mEmptySearchBackground.setAlpha(0);
mEmptySearchBackground.setCallback(this);
updateEmptySearchBackgroundBounds();
}
mEmptySearchBackground.animateBgAlpha(1f, 150);
} else if (mEmptySearchBackground != null) {
// For the time being, we just immediately hide the background to ensure that it does
// not overlap with the results
mEmptySearchBackground.setBgAlpha(0f);
}
}
/**
* Maps the touch (from 0..1) to the adapter position that should be visible.
*/
@Override
public String scrollToPositionAtProgress(float touchFraction) {
int rowCount = mApps.getNumAppRows();
if (rowCount == 0) {
return "";
}
// Stop the scroller if it is scrolling
stopScroll();
// Find the fastscroll section that maps to this touch fraction
List<AlphabeticalAppsList.FastScrollSectionInfo> fastScrollSections =
mApps.getFastScrollerSections();
AlphabeticalAppsList.FastScrollSectionInfo lastInfo = fastScrollSections.get(0);
if (mScrollBarMode == FAST_SCROLL_BAR_MODE_DISTRIBUTE_BY_ROW) {
for (int i = 1; i < fastScrollSections.size(); i++) {
AlphabeticalAppsList.FastScrollSectionInfo info = fastScrollSections.get(i);
if (info.touchFraction > touchFraction) {
break;
}
lastInfo = info;
}
} else if (mScrollBarMode == FAST_SCROLL_BAR_MODE_DISTRIBUTE_BY_SECTIONS){
lastInfo = fastScrollSections.get((int) (touchFraction * (fastScrollSections.size() - 1)));
} else {
throw new RuntimeException("Unexpected scroll bar mode");
}
// Reset the last focused section
if (mPrevFastScrollFocusedSection != lastInfo.sectionInfo) {
setSectionFastScrollDimmed(mPrevFastScrollFocusedPosition, true, true);
clearSectionFocusedItems();
}
mPrevFastScrollFocusedPosition = lastInfo.fastScrollToItem.position;
mPrevFastScrollFocusedSection = lastInfo.sectionInfo;
getCurScrollState(mScrollPosState);
if (mFastScrollMode == FAST_SCROLL_MODE_JUMP_TO_FIRST_ICON) {
smoothSnapToPosition(mPrevFastScrollFocusedPosition, mScrollPosState);
setSectionFastScrollDimmed(mPrevFastScrollFocusedPosition, false, true);
setSectionFastScrollFocused(mPrevFastScrollFocusedPosition);
} else if (mFastScrollMode == FAST_SCROLL_MODE_FREE_SCROLL) {
// Map the touch position back to the scroll of the recycler view
int availableScrollHeight = getAvailableScrollHeight(rowCount, mScrollPosState.rowHeight);
LinearLayoutManager layoutManager = (LinearLayoutManager) getLayoutManager();
layoutManager.scrollToPositionWithOffset(0, (int) -(availableScrollHeight * touchFraction));
setSectionFastScrollFocused(mPrevFastScrollFocusedPosition);
} else {
throw new RuntimeException("Unexpected fast scroll mode");
}
return lastInfo.sectionName;
}
@Override
public void onFastScrollCompleted() {
super.onFastScrollCompleted();
// Reset and clean up the last focused views
clearSectionFocusedItems();
mPrevFastScrollFocusedPosition = -1;
mPrevFastScrollFocusedSection = null;
}
/**
* Updates the bounds for the scrollbar.
*/
@Override
public void onUpdateScrollbar(int dy) {
if (!mUseScrollbar) {
return;
}
List<AlphabeticalAppsList.AdapterItem> items = mApps.getAdapterItems();
// Skip early if there are no items or we haven't been measured
if (items.isEmpty() || mNumAppsPerRow == 0) {
mScrollbar.setThumbOffset(-1, -1);
return;
}
// Find the index and height of the first visible row (all rows have the same height)
int rowCount = mApps.getNumAppRows();
getCurScrollState(mScrollPosState);
if (mScrollPosState.rowIndex < 0) {
mScrollbar.setThumbOffset(-1, -1);
return;
}
// Only show the scrollbar if there is height to be scrolled
int availableScrollBarHeight = getAvailableScrollBarHeight();
int availableScrollHeight = getAvailableScrollHeight(mApps.getNumAppRows(),
mScrollPosState.rowHeight);
if (availableScrollHeight <= 0) {
mScrollbar.setThumbOffset(-1, -1);
return;
}
// Calculate the current scroll position, the scrollY of the recycler view accounts for the
// view padding, while the scrollBarY is drawn right up to the background padding (ignoring
// padding)
int scrollY = getCurrentScroll(mScrollPosState);
int scrollBarY = mBackgroundPadding.top +
(int) (((float) scrollY / availableScrollHeight) * availableScrollBarHeight);
if (mScrollbar.isThumbDetached()) {
int scrollBarX;
if (Utilities.isRtl(getResources())) {
scrollBarX = mBackgroundPadding.left;
} else {
scrollBarX = getWidth() - mBackgroundPadding.right - mScrollbar.getThumbWidth();
}
if (mScrollbar.isDraggingThumb()) {
// If the thumb is detached, then just update the thumb to the current
// touch position
mScrollbar.setThumbOffset(scrollBarX, (int) mScrollbar.getLastTouchY());
} else {
int thumbScrollY = mScrollbar.getThumbOffset().y;
int diffScrollY = scrollBarY - thumbScrollY;
if (diffScrollY * dy > 0f) {
// User is scrolling in the same direction the thumb needs to catch up to the
// current scroll position. We do this by mapping the difference in movement
// from the original scroll bar position to the difference in movement necessary
// in the detached thumb position to ensure that both speed towards the same
// position at either end of the list.
if (dy < 0) {
int offset = (int) ((dy * thumbScrollY) / (float) scrollBarY);
thumbScrollY += Math.max(offset, diffScrollY);
} else {
int offset = (int) ((dy * (availableScrollBarHeight - thumbScrollY)) /
(float) (availableScrollBarHeight - scrollBarY));
thumbScrollY += Math.min(offset, diffScrollY);
}
thumbScrollY = Math.max(0, Math.min(availableScrollBarHeight, thumbScrollY));
mScrollbar.setThumbOffset(scrollBarX, thumbScrollY);
if (scrollBarY == thumbScrollY) {
mScrollbar.reattachThumbToScroll();
}
} else {
// User is scrolling in an opposite direction to the direction that the thumb
// needs to catch up to the scroll position. Do nothing except for updating
// the scroll bar x to match the thumb width.
mScrollbar.setThumbOffset(scrollBarX, thumbScrollY);
}
}
} else {
synchronizeScrollBarThumbOffsetToViewScroll(mScrollPosState, rowCount);
}
}
@Override
public String scrollToSection(String sectionName) {
List<AlphabeticalAppsList.FastScrollSectionInfo> scrollSectionInfos =
mApps.getFastScrollerSections();
if (scrollSectionInfos != null) {
for (int i = 0; i < scrollSectionInfos.size(); i++) {
AlphabeticalAppsList.FastScrollSectionInfo info = scrollSectionInfos.get(i);
if (info.sectionName.equals(sectionName)) {
scrollToPositionAtProgress(info.touchFraction);
return info.sectionName;
}
}
}
return null;
}
@Override
public String[] getSectionNames() {
List<AlphabeticalAppsList.FastScrollSectionInfo> scrollSectionInfos =
mApps.getFastScrollerSections();
if (scrollSectionInfos != null) {
String[] sectionNames = new String[scrollSectionInfos.size()];
for (int i = 0; i < scrollSectionInfos.size(); i++) {
AlphabeticalAppsList.FastScrollSectionInfo info = scrollSectionInfos.get(i);
sectionNames[i] = info.sectionName;
}
return sectionNames;
}
return new String[0];
}
private void setSectionFastScrollFocused(int position) {
if (mPrevFastScrollFocusedSection != null) {
((AllAppsGridAdapter)getAdapter()).setFocusedSection(mPrevFastScrollFocusedSection);
int size = mPrevFastScrollFocusedSection.numApps +
mPrevFastScrollFocusedSection.numOtherViews;
for (int i = 0; i < size; i++) {
int sectionPosition = position+i;
final ViewHolder vh = findViewHolderForAdapterPosition(sectionPosition);
if (vh != null) {
FastScrollFocusApplicator.setFastScrollFocused(vh.itemView, true, true);
mLastFastScrollFocusedViews.add(vh.itemView);
}
}
}
}
@Override
public void setPreviousSectionFastScrollFocused() {
setSectionFastScrollFocused(mPrevFastScrollFocusedPosition);
}
private void setSectionFastScrollDimmed(int position, boolean dimmed, boolean animate) {
if (mPrevFastScrollFocusedSection != null) {
int size = mPrevFastScrollFocusedSection.numApps +
mPrevFastScrollFocusedSection.numOtherViews;
for (int i = 0; i < size; i++) {
int sectionPosition = position+i;
final ViewHolder vh = findViewHolderForAdapterPosition(sectionPosition);
if (vh != null) {
FastScrollFocusApplicator.setFastScrollDimmed(vh.itemView, dimmed, animate);
}
}
}
}
private void clearSectionFocusedItems() {
final int N = mLastFastScrollFocusedViews.size();
for (int i = 0; i < N; i++) {
View view = mLastFastScrollFocusedViews.get(i);
FastScrollFocusApplicator.setFastScrollFocused(view, false, true);
}
mLastFastScrollFocusedViews.clear();
}
@Override
public void setFastScrollDragging(boolean dragging) {
((AllAppsGridAdapter) getAdapter()).setIconsDimmed(dragging);
mFastScrollDragging = dragging;
}
/**
* This runnable runs a single frame of the smooth scroll animation and posts the next frame
* if necessary.
*/
@Thunk Runnable mSmoothSnapNextFrameRunnable = new Runnable() {
@Override
public void run() {
if (mFastScrollFrameIndex < mFastScrollFrames.length) {
setSectionFastScrollDimmed(mPrevFastScrollFocusedPosition, false, true);
scrollBy(0, mFastScrollFrames[mFastScrollFrameIndex]);
mFastScrollFrameIndex++;
postOnAnimation(mSmoothSnapNextFrameRunnable);
} else {
setSectionFastScrollDimmed(mPrevFastScrollFocusedPosition, false, false);
setSectionFastScrollFocused(mPrevFastScrollFocusedPosition);
}
}
};
/**
* Smoothly snaps to a given position. We do this manually by calculating the keyframes
* ourselves and animating the scroll on the recycler view.
*/
private void smoothSnapToPosition(final int position, ScrollPositionState scrollPosState) {
removeCallbacks(mSmoothSnapNextFrameRunnable);
// Calculate the full animation from the current scroll position to the final scroll
// position, and then run the animation for the duration.
int curScrollY = getCurrentScroll(scrollPosState);
int newScrollY = getScrollAtPosition(position, scrollPosState.rowHeight);
int numFrames = mFastScrollFrames.length;
for (int i = 0; i < numFrames; i++) {
// TODO(winsonc): We can interpolate this as well.
mFastScrollFrames[i] = (newScrollY - curScrollY) / numFrames;
}
mFastScrollFrameIndex = 0;
postOnAnimation(mSmoothSnapNextFrameRunnable);
}
/**
* Returns the current scroll state of the apps rows.
*/
protected void getCurScrollState(ScrollPositionState stateOut) {
stateOut.rowIndex = -1;
stateOut.rowTopOffset = -1;
stateOut.rowHeight = -1;
// Return early if there are no items or we haven't been measured
List<AlphabeticalAppsList.AdapterItem> items = mApps.getAdapterItems();
if (items.isEmpty() || mNumAppsPerRow == 0) {
return;
}
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
int position = getChildPosition(child);
if (position != NO_POSITION) {
AlphabeticalAppsList.AdapterItem item = items.get(position);
if (item.viewType == AllAppsGridAdapter.ICON_VIEW_TYPE ||
item.viewType == AllAppsGridAdapter.PREDICTION_ICON_VIEW_TYPE) {
stateOut.rowIndex = item.rowIndex;
stateOut.rowTopOffset = getLayoutManager().getDecoratedTop(child) -
getAdditionalScrollHeight(stateOut.rowIndex);
stateOut.rowHeight = child.getHeight();
break;
}
}
}
}
@Override
protected int getAvailableScrollHeight(int rowCount, int rowHeight) {
return super.getAvailableScrollHeight(rowCount, rowHeight) +
getAdditionalScrollHeight(mApps.getAdapterItems().size());
}
private int getAdditionalScrollHeight(int rowIndex) {
return ((AllAppsGridAdapter) getAdapter()).getCustomPredictedAppsOffset(rowIndex);
}
/**
* Returns the scrollY for the given position in the adapter.
*/
private int getScrollAtPosition(int position, int rowHeight) {
AlphabeticalAppsList.AdapterItem item = mApps.getAdapterItems().get(position);
if (item.viewType == AllAppsGridAdapter.ICON_VIEW_TYPE ||
item.viewType == AllAppsGridAdapter.PREDICTION_ICON_VIEW_TYPE) {
int offset = item.rowIndex > 0 ? getPaddingTop() : 0;
offset += ((AllAppsGridAdapter) getAdapter()).
getCustomPredictedAppsOffset(item.rowIndex);
return offset + item.rowIndex * rowHeight;
} else {
return 0;
}
}
/**
* Updates the bounds of the empty search background.
*/
private void updateEmptySearchBackgroundBounds() {
if (mEmptySearchBackground == null) {
return;
}
// Center the empty search background on this new view bounds
int x = (getMeasuredWidth() - mEmptySearchBackground.getIntrinsicWidth()) / 2;
int y = mEmptySearchBackgroundTopOffset;
mEmptySearchBackground.setBounds(x, y,
x + mEmptySearchBackground.getIntrinsicWidth(),
y + mEmptySearchBackground.getIntrinsicHeight());
}
}
| {'content_hash': '74aa9c7b702fb523f124f6b31459a15f', 'timestamp': '', 'source': 'github', 'line_count': 565, 'max_line_length': 104, 'avg_line_length': 41.14513274336283, 'alnum_prop': 0.637157482685938, 'repo_name': 'bojanvu23/android_packages_apps_Trebuchet_Gradle', 'id': '302c12c4da4228b6a87bc78f3883de055e3520a2', 'size': '23866', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Trebuchet/src/main/java/com/lite/android/launcher3/allapps/AllAppsRecyclerView.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '2951171'}]} |
package org.foxbpm.web.controller;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.foxbpm.engine.impl.entity.UserEntity;
public class LoginFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
UserEntity user = (UserEntity)req.getSession().getAttribute("user");
String path = req.getContextPath();
if(user == null){
res.sendRedirect(path+"/login.html");
}else{
chain.doFilter(request, response);
}
}
public void destroy() {
}
}
| {'content_hash': 'e94bae0801584ca0afc1ef7f685fde67', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 129, 'avg_line_length': 26.238095238095237, 'alnum_prop': 0.7504537205081669, 'repo_name': 'fashionsun/FoxBPM', 'id': 'c30c675467b8960e345367cbb19068696af54369', 'size': '1102', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'modules/foxbpm-webapps-common/src/main/java/org/foxbpm/web/controller/LoginFilter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '691204'}, {'name': 'HTML', 'bytes': '1659326'}, {'name': 'Java', 'bytes': '2886818'}, {'name': 'JavaScript', 'bytes': '1495393'}, {'name': 'PHP', 'bytes': '4720'}]} |
package org.apache.ignite.internal.processors.cache;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.cache.Cache.Entry;
import javax.cache.configuration.Factory;
import javax.cache.configuration.FactoryBuilder;
import javax.cache.integration.CacheLoaderException;
import javax.cache.integration.CacheWriterException;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.MutableEntry;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.store.CacheStoreAdapter;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
/**
* Tests consistency of entry's versions after invokeAll.
*/
public class EntryVersionConsistencyReadThroughTest extends GridCommonAbstractTest {
/** */
private static final int NODES_CNT = 5;
/** */
private boolean client;
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
cfg.setClientMode(client);
return cfg;
}
/**
* @param atomicityMode Atomicity mode.
* @return Cache configuration.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private CacheConfiguration<String, List<Double>> createCacheConfiguration(CacheAtomicityMode atomicityMode) {
CacheConfiguration<String, List<Double>> cc = new CacheConfiguration<>(DEFAULT_CACHE_NAME);
cc.setCacheMode(PARTITIONED);
cc.setAtomicityMode(atomicityMode);
cc.setWriteSynchronizationMode(FULL_SYNC);
cc.setReadThrough(true);
cc.setWriteThrough(true);
Factory cacheStoreFactory = new FactoryBuilder.SingletonFactory(new DummyCacheStore());
cc.setCacheStoreFactory(cacheStoreFactory);
cc.setBackups(2);
return cc;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
super.beforeTestsStarted();
startGridsMultiThreaded(NODES_CNT - 1);
client = true;
startGrid(NODES_CNT - 1);
}
/**
* @throws Exception If failed.
*/
public void testInvokeAllTransactionalCache() throws Exception {
check(false, createCacheConfiguration(TRANSACTIONAL));
}
/**
* @throws Exception If failed.
*/
public void testInvokeAllAtomicCache() throws Exception {
check(false, createCacheConfiguration(ATOMIC));
}
/**
* @throws Exception If failed.
*/
public void testInvokeAtomicCache() throws Exception {
check(true, createCacheConfiguration(ATOMIC));
}
/**
* @throws Exception If failed.
*/
public void testInvokeTransactionalCache() throws Exception {
check(true, createCacheConfiguration(TRANSACTIONAL));
}
/**
* Tests entry's versions consistency after invokeAll.
*
* @param single Single invoke or invokeAll.
* @param cc Cache configuration.
* @throws Exception If failed.
*/
@SuppressWarnings("serial")
private void check(boolean single, CacheConfiguration cc) throws Exception {
grid(0).getOrCreateCache(cc);
try {
final int cnt = 100;
for (int i = 0; i < NODES_CNT; i++) {
final int iter = i;
final Set<String> keys = new LinkedHashSet<String>() {{
for (int i = 0; i < cnt; i++)
add("key-" + iter + "-" + i);
}};
IgniteEx grid = grid(i);
final IgniteCache<String, Integer> cache = grid.cache(DEFAULT_CACHE_NAME);
if (single)
for (String key : keys)
cache.invoke(key, new DummyEntryProcessor());
else
cache.invokeAll(keys, new DummyEntryProcessor());
// Check entry versions consistency.
for (String key : keys) {
Collection<ClusterNode> nodes = grid.affinity(DEFAULT_CACHE_NAME).mapKeyToPrimaryAndBackups(key);
List<IgniteEx> grids = grids(nodes);
GridCacheVersion ver0 = null;
Object val0 = null;
for (IgniteEx g : grids) {
GridCacheAdapter<Object, Object> cx = g.context().cache().internalCache(DEFAULT_CACHE_NAME);
GridCacheEntryEx e = cx.entryEx(key);
e.unswap();
assertNotNull("Failed to find entry on primary/backup node.", e.rawGet());
GridCacheVersion ver = e.version();
Object val = e.rawGet().value(cx.context().cacheObjectContext(), true);
if (ver0 == null) {
ver0 = ver;
val0 = val;
}
assertEquals("Invalid version for key: " + key, ver0, ver);
assertNotNull("No value for key: " + key, val);
assertEquals("Invalid value for key: " + key, val0, val);
}
}
}
}
finally {
grid(0).destroyCache(DEFAULT_CACHE_NAME);
}
}
/**
* @param nodes Nodes.
* @return Grids.
*/
private List<IgniteEx> grids(Collection<ClusterNode> nodes) {
List<IgniteEx> grids = new ArrayList<>();
for (ClusterNode node : nodes) {
for (int i = 0; i < NODES_CNT; i++) {
if (grid(i).cluster().localNode().id().equals(node.id())) {
grids.add(grid(i));
break;
}
}
}
return grids;
}
/**
*
*/
private static class DummyEntryProcessor implements EntryProcessor<String, Integer, Integer> {
/** {@inheritDoc} */
@Override public Integer process(MutableEntry<String, Integer> entry, Object... arguments) {
Integer currVal = entry.getValue();
if (currVal == null)
entry.setValue(0);
else
entry.setValue(currVal + 1);
return null;
}
}
/**
*
*/
@SuppressWarnings("serial")
private static class DummyCacheStore extends CacheStoreAdapter<String, Integer> implements Serializable {
/** {@inheritDoc} */
@Override public Integer load(String key) throws CacheLoaderException {
return 1;
}
/** {@inheritDoc} */
@Override public void write(Entry<? extends String, ? extends Integer> entry) throws CacheWriterException {
// No-op.
}
/** {@inheritDoc} */
@Override public void delete(Object key) throws CacheWriterException {
// No-op.
}
}
}
| {'content_hash': '1fc74e8e31107b9bcfd7c20c81dc4fa3', 'timestamp': '', 'source': 'github', 'line_count': 243, 'max_line_length': 117, 'avg_line_length': 31.53497942386831, 'alnum_prop': 0.6038105180738614, 'repo_name': 'irudyak/ignite', 'id': 'ebf253d50cd739030b2a0955f14a81b58f313269', 'size': '8465', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'modules/core/src/test/java/org/apache/ignite/internal/processors/cache/EntryVersionConsistencyReadThroughTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '50800'}, {'name': 'C', 'bytes': '5286'}, {'name': 'C#', 'bytes': '5983226'}, {'name': 'C++', 'bytes': '3109794'}, {'name': 'CSS', 'bytes': '266406'}, {'name': 'Groovy', 'bytes': '15081'}, {'name': 'HTML', 'bytes': '668377'}, {'name': 'Java', 'bytes': '34210390'}, {'name': 'JavaScript', 'bytes': '1681511'}, {'name': 'M4', 'bytes': '12456'}, {'name': 'Makefile', 'bytes': '107669'}, {'name': 'PHP', 'bytes': '11079'}, {'name': 'PowerShell', 'bytes': '12344'}, {'name': 'SQLPL', 'bytes': '307'}, {'name': 'Scala', 'bytes': '990466'}, {'name': 'Shell', 'bytes': '592199'}, {'name': 'Smalltalk', 'bytes': '1908'}, {'name': 'TypeScript', 'bytes': '4522'}]} |
<?php
namespace Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Factory\Action;
use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Action\ChangeSecurityQuestionTwoAction;
use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Service\ChangeSecurityQuestionsService;
use Dvsa\Mot\Frontend\PersonModule\ChangeSecurityQuestions\Service\ChangeSecurityQuestionsStepService;
use DvsaFeature\FeatureToggles;
use Zend\ServiceManager\Factory\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Interop\Container\ContainerInterface;
class ChangeSecurityQuestionTwoActionFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
return $this($serviceLocator, ChangeSecurityQuestionTwoAction::class);
}
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$changeSecurityQuestionsService = $container->get(ChangeSecurityQuestionsService::class);
$changeSecurityQuestionsStepService = $container->get(ChangeSecurityQuestionsStepService::class);
$featureToggles = $container->get(FeatureToggles::class);
$identityProvider = $container->get('MotIdentityProvider');
return new ChangeSecurityQuestionTwoAction(
$changeSecurityQuestionsService,
$changeSecurityQuestionsStepService,
$featureToggles,
$identityProvider->getIdentity()
);
}
}
| {'content_hash': '5889b223082faf7cdeeca905019406bb', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 105, 'avg_line_length': 39.28947368421053, 'alnum_prop': 0.7836570663094441, 'repo_name': 'dvsa/mot', 'id': '6992c110d99e1e63c0186ce112528b5b4ce1a68f', 'size': '1493', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'mot-web-frontend/module/PersonModule/src/ChangeSecurityQuestions/Factory/Action/ChangeSecurityQuestionTwoActionFactory.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '604618'}, {'name': 'Dockerfile', 'bytes': '2693'}, {'name': 'Gherkin', 'bytes': '189981'}, {'name': 'HTML', 'bytes': '1579702'}, {'name': 'Java', 'bytes': '1631717'}, {'name': 'JavaScript', 'bytes': '156823'}, {'name': 'Makefile', 'bytes': '2877'}, {'name': 'PHP', 'bytes': '20142004'}, {'name': 'PLpgSQL', 'bytes': '61098'}, {'name': 'Python', 'bytes': '3354'}, {'name': 'Ruby', 'bytes': '72'}, {'name': 'SQLPL', 'bytes': '1739266'}, {'name': 'Shell', 'bytes': '203709'}]} |
import healpy
import numpy as np
import pylab as plt
from ugali.preprocess.maglims import inMangle
from ugali.utils.projector import pixToAng
if __name__ == "__main__":
from optparse import OptionParser
usage = "Usage: %prog [options] mangle1.ply [mangle2.ply ...]"
description = "python script"
parser = OptionParser(usage=usage,description=description)
(opts, args) = parser.parse_args()
nside = 2**8
print("Creating ra, dec...")
pix = np.arange(healpy.nside2npix(nside))
ra,dec = pixToAng(nside,pix)
for infile in args:
print("Testing %i HEALPix pixels ..."%len(pix))
inside = inMangle(infile,ra,dec)
print("Plotting...")
healpy.mollview(inside)
outfile = infile.replace('.ply','.png')
print("Writing %s"%outfile)
plt.savefig(outfile)
| {'content_hash': '60375cfb441f1e7216e7f4ea3c03805f', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 67, 'avg_line_length': 29.0, 'alnum_prop': 0.6456599286563615, 'repo_name': 'DarkEnergySurvey/ugali', 'id': '0579866834b4ec35ee3276e888a6586a01a08afc', 'size': '878', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'ugali/scratch/PlotManglePolygon.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Jupyter Notebook', 'bytes': '355304'}, {'name': 'Python', 'bytes': '949638'}]} |
package com.ctrip.hermes.kafka.admin;
import java.util.Arrays;
import java.util.Random;
import com.ctrip.hermes.core.result.CompletionCallback;
import com.ctrip.hermes.core.result.SendResult;
import com.ctrip.hermes.producer.api.Producer;
import com.ctrip.hermes.producer.api.Producer.MessageHolder;
public class HermesProducerPerf {
private static final long NS_PER_MS = 1000000L;
private static final long NS_PER_SEC = 1000 * NS_PER_MS;
private static final long MIN_SLEEP_NS = 2 * NS_PER_MS;
public HermesProducerPerf(String topicName, long numRecords, int recordSize, int throughput) {
this.topicName = topicName;
this.numRecords = numRecords;
this.recordSize = recordSize;
this.throughput = throughput;
}
public void run() {
Producer producer = Producer.getInstance();
/* setup perf test */
Random random = new Random();
byte[] msgBuf = new byte[recordSize - 4];
Arrays.fill(msgBuf, (byte) random.nextInt(255));
String proMsg = new String(msgBuf) + System.currentTimeMillis();
long sleepTime = NS_PER_SEC / throughput;
long sleepDeficitNs = 0;
Stats stats = new Stats(numRecords, 5000);
for (int i = 0; i < numRecords; i++) {
long sendStart = System.currentTimeMillis();
CompletionCallback<SendResult> cb = stats.nextCompletion(sendStart, proMsg.getBytes().length, stats);
MessageHolder message = producer.message(topicName, String.valueOf(random.nextInt()), proMsg);
message.setCallback(cb);
message.send();
/*
* Maybe sleep a little to control throughput. Sleep time can be a bit inaccurate for times < 1 ms so instead of sleeping
* each time instead wait until a minimum sleep time accumulates (the "sleep deficit") and then make up the whole deficit
* in one longer sleep.
*/
if (throughput > 0) {
sleepDeficitNs += sleepTime;
if (sleepDeficitNs >= MIN_SLEEP_NS) {
long sleepMs = sleepDeficitNs / 1000000;
long sleepNs = sleepDeficitNs - sleepMs * 1000000;
try {
Thread.sleep(sleepMs, (int) sleepNs);
} catch (InterruptedException e) {
}
sleepDeficitNs = 0;
}
}
}
/* print final results */
stats.printTotal();
}
private String topicName;
private long numRecords;
private int recordSize;
private int throughput;
public static void showHelp() {
System.out.println("USAGE: java " + HermesProducerPerf.class.getName()
+ " topic_name num_records record_size target_records_sec [prop_name=prop_value]*");
}
public static void main(String[] args) throws Exception {
if (args.length < 4) {
showHelp();
System.exit(1);
}
/* parse args */
String topicName = args[0];
long numRecords = Long.parseLong(args[1]);
int recordSize = Integer.parseInt(args[2]);
int throughput = Integer.parseInt(args[3]);
HermesProducerPerf perfTest = new HermesProducerPerf(topicName, numRecords, recordSize, throughput);
perfTest.run();
System.exit(0);
}
private static class Stats {
private long start;
private long windowStart;
private int[] latencies;
private int sampling;
private int iteration;
private int index;
private long count;
private long bytes;
private int maxLatency;
private long totalLatency;
private long windowCount;
private int windowMaxLatency;
private long windowTotalLatency;
private long windowBytes;
private long reportingInterval;
public Stats(long numRecords, int reportingInterval) {
this.start = System.currentTimeMillis();
this.windowStart = System.currentTimeMillis();
this.index = 0;
this.iteration = 0;
this.sampling = (int) (numRecords / Math.min(numRecords, 500000));
this.latencies = new int[(int) (numRecords / this.sampling) + 1];
this.index = 0;
this.maxLatency = 0;
this.totalLatency = 0;
this.windowCount = 0;
this.windowMaxLatency = 0;
this.windowTotalLatency = 0;
this.windowBytes = 0;
this.totalLatency = 0;
this.reportingInterval = reportingInterval;
}
public void record(int iter, int latency, int bytes, long time) {
this.count++;
this.bytes += bytes;
this.totalLatency += latency;
this.maxLatency = Math.max(this.maxLatency, latency);
this.windowCount++;
this.windowBytes += bytes;
this.windowTotalLatency += latency;
this.windowMaxLatency = Math.max(windowMaxLatency, latency);
if (iter % this.sampling == 0) {
this.latencies[index] = latency;
this.index++;
}
/* maybe report the recent perf */
if (time - windowStart >= reportingInterval) {
printWindow();
newWindow();
}
}
public CompletionCallback<SendResult> nextCompletion(long start, int bytes, Stats stats) {
CompletionCallback<SendResult> cb = new PerfCallback(this.iteration, start, bytes, stats);
this.iteration++;
return cb;
}
public void printWindow() {
long ellapsed = System.currentTimeMillis() - windowStart;
double recsPerSec = 1000.0 * windowCount / (double) ellapsed;
double mbPerSec = 1000.0 * this.windowBytes / (double) ellapsed / (1024.0 * 1024.0);
System.out.printf("%d records sent, %.1f records/sec (%.2f MB/sec), %.1f ms avg latency, %.1f max latency.\n",
windowCount, recsPerSec, mbPerSec, windowTotalLatency / (double) windowCount, (double) windowMaxLatency);
}
public void newWindow() {
this.windowStart = System.currentTimeMillis();
this.windowCount = 0;
this.windowMaxLatency = 0;
this.windowTotalLatency = 0;
this.windowBytes = 0;
}
public void printTotal() {
long ellapsed = System.currentTimeMillis() - start;
double recsPerSec = 1000.0 * count / (double) ellapsed;
double mbPerSec = 1000.0 * this.bytes / (double) ellapsed / (1024.0 * 1024.0);
int[] percs = percentiles(this.latencies, index, 0.5, 0.95, 0.99, 0.999);
System.out
.printf(
"%d records sent, %f records/sec (%.2f MB/sec), %.2f ms avg latency, %.2f ms max latency, %d ms 50th, %d ms 95th, %d ms 99th, %d ms 99.9th.\n",
count, recsPerSec, mbPerSec, totalLatency / (double) count, (double) maxLatency, percs[0],
percs[1], percs[2], percs[3]);
}
private static int[] percentiles(int[] latencies, int count, double... percentiles) {
int size = Math.min(count, latencies.length);
Arrays.sort(latencies, 0, size);
int[] values = new int[percentiles.length];
for (int i = 0; i < percentiles.length; i++) {
int index = (int) (percentiles[i] * size);
values[i] = latencies[index];
}
return values;
}
}
private static final class PerfCallback implements CompletionCallback<SendResult> {
private final long start;
private final int iteration;
private final int bytes;
private final Stats stats;
public PerfCallback(int iter, long start, int bytes, Stats stats) {
this.start = start;
this.stats = stats;
this.iteration = iter;
this.bytes = bytes;
}
@Override
public void onSuccess(SendResult result) {
long now = System.currentTimeMillis();
int latency = (int) (now - start);
this.stats.record(iteration, latency, bytes, now);
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}
}
| {'content_hash': '02dd4371b5fdb9b0482880a4a0525db0', 'timestamp': '', 'source': 'github', 'line_count': 239, 'max_line_length': 158, 'avg_line_length': 29.84937238493724, 'alnum_prop': 0.6886739557050743, 'repo_name': 'fengshao0907/hermes', 'id': '80265ee35f9dffa6dccd6e50328ff2716c77a85d', 'size': '7134', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'hermes-kafka/src/main/java/com/ctrip/hermes/kafka/admin/HermesProducerPerf.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '10616'}, {'name': 'Cucumber', 'bytes': '200'}, {'name': 'HTML', 'bytes': '32777'}, {'name': 'Java', 'bytes': '2015345'}, {'name': 'JavaScript', 'bytes': '84544'}, {'name': 'Shell', 'bytes': '21375'}]} |
package fr.MrHoStan.OwercraftFaction.Main;
import net.citizensnpcs.api.event.NPCClickEvent;
import org.bukkit.event.Listener;
public class Events implements Listener
{
public void OnclickEvent(NPCClickEvent e)
{
}
}
| {'content_hash': '40b89dbc728402fd103d22aad1da09a7', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 48, 'avg_line_length': 18.46153846153846, 'alnum_prop': 0.7416666666666667, 'repo_name': 'mrstandu33/OwercraftFaction', 'id': '3049855843e0de2757d5f3fee5effd015fdc6bb4', 'size': '240', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/fr/MrHoStan/OwercraftFaction/Main/Events.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1960'}]} |
using Abp.Auditing;
namespace Helios.Configuration.Tenants.Dto
{
public class LdapSettingsEditDto
{
public bool IsModuleEnabled { get; set; }
public bool IsEnabled { get; set; }
public string Domain { get; set; }
public string UserName { get; set; }
[DisableAuditing]
public string Password { get; set; }
}
} | {'content_hash': '0843580564db580d3cf1f1d312ef828c', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 49, 'avg_line_length': 21.61111111111111, 'alnum_prop': 0.5938303341902313, 'repo_name': 'kelely/Helios', 'id': '671328b55e1af170e919fc2050e8377ba1462914', 'size': '389', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'src/Helios.Zero/Helios.Zero.Application/Configuration/Tenants/Dto/LdapSettingsEditDto.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '1005017'}, {'name': 'HTML', 'bytes': '17433'}, {'name': 'JavaScript', 'bytes': '5207'}, {'name': 'PowerShell', 'bytes': '7428'}, {'name': 'Shell', 'bytes': '2935'}]} |
define(['constants', 'storage', 'tab_content', 'util'],
function(C, storage, tab_content, util){
'use strict';
var _next_tab_id = 0;
var $node_template;
var $tab_tree;
var $tabs;
var _current = null;
var _tabs = {};
var _dragging_tab = null;
function init(templates){
$node_template = templates['tab-tree-node'];
$tab_tree = $('.tab-tree');
var $new_tab_button = $('.new-tab-button');
$new_tab_button.click(open_new_root_tab);
// Add existing tabs
storage.load_tabs(function(tabs){
load_tab_data(tabs);
});
storage.add_tabs_listener(load_tab_data);
$(window).mousemove(function(e) {
if (_dragging_tab) {
if (!_dragging_tab.detatched && util.has_dragged(_dragging_tab.e, e)){
_dragging_tab.tab.detatch();
_dragging_tab.detatched = true;
}
}
}).mouseup(function(e) {
if (_dragging_tab && _dragging_tab.detatched) {
_dragging_tab.tab.attach();
e.preventDefault();
}
_dragging_tab = null;
});
}
function load_tab_data(tabs){
console.log("data: ", tabs);
$.each(tabs.tabs, function(id, tab_data){
var _tab = _tabs[id];
if (_tab === undefined){
new Tab(id, tab_data);
} else {
_tab.update_by_data(tab_data);
}
});
$.each(_tabs, function(id, tab) {
if(!(id in tabs.tabs))
tab.update_by_data(undefined);
});
if(_current !== null && !(_current in _tabs))
_current = null;
}
function open_new_root_tab(){
get_free_tab_id(function(id){
var _tab = new Tab(id);
_tab.append_to_root();
_tab.select_tab();
});
}
function open_new_tab(callback, select){
get_free_tab_id(function(id){
var _tab = new Tab(id);
_tab.append_to_tab(_current);
if (select) {
_tab.select_tab();
}
if (callback) {
callback(_tab);
}
});
}
function with_current(callback){
if (_current !== null) {
var _tab = _tabs[_current];
if (_tab) {
callback(_tab);
}
}
}
function close_current_tab(){
with_current(function(tab){
tab.close_tab();
});
}
function escape_current_tab(){
with_current(function(tab){
tab.escape_tab();
});
}
function unselect_current_tab(){
with_current(function(tab){
tab.unselect_tab();
});
}
function refresh_current_tab(){
with_current(function(tab){
tab.get_webview().reload();
});
}
function focus_address_bar() {
with_current(function(tab) {
tab.with_content(function(content) {
content.focus_address_bar();
});
});
}
function start_find(){
with_current(function(tab){
tab.start_find();
});
}
function get_free_tab_id (callback){
storage.load_tabs(function(tabs){
var _id = 0;
while (_id in tabs.tabs)
_id ++;
callback(_id);
});
}
function Tab(id, tab_data){
_tabs[id] = this;
this.id = id;
this.$node = $node_template.clone();
this.$children = this.$node.children('.children').first();
this.$content = null;
this.content = null;
this.parent = null;
if (tab_data === undefined) {
// Store tab
this.store_tab_data();
} else {
// Loaded by data
this.update_by_data(tab_data);
}
this._setup_listeners();
}
$.extend(Tab.prototype, {
_setup_listeners: function() {
var $tab = this.$node.children('.tab');
var $button = $tab.find('.button');
var $arrow = $tab.find('.arrow');
$arrow.click(this.arrow_clicked.bind(this));
$button.click(this.button_clicked.bind(this)).mousedown(function(e) {
if (!_dragging_tab){
_dragging_tab = {
tab: this,
e: e
};
}
}.bind(this));
$button.find('.icon.close').click(function(e){
this.close_tab();
e.stopPropagation();
}.bind(this));
},
has_children: function() {
return this.$children.children().children('.tab').not('.hide').length !== 0;
},
with_each_ancestor: function(callback) {
var _current = this;
while (true) {
_current = (_current.parent || _current.parent === 0) ? _tabs[_current.parent] : null;
if (!_current){
return;
}
if(callback(_current)){
return;
}
}
},
update_tab_text: function() {
var _text;
if(this.tab_name && this.tab_name !== '') {
_text = this.tab_name;
} else {
_text = this.title;
}
this.$node.children('.tab').find('.button .label').text(_text);
},
update_tab_color: function() {
var _color = this.tab_color;
var $color_indicator = this.$node.children('.tab').find('.color-indicator');
if (!_color){
this.with_each_ancestor(function(tab) {
if (tab.tab_color){
_color = tab.tab_color;
return true;
}
});
}
if (_color) {
$color_indicator.show().css('background-color', _color);
$color_indicator.toggleClass('small', !this.tab_color);
} else {
$color_indicator.hide();
}
},
update_by_data: function(data) {
// Never modify the data in this method
if(data === undefined){
// The tab has been deleted
delete _tabs[this.id];
this.$node.children('.tab').addClass('hide');
setTimeout(function (){
this.$node.remove();
}.bind(this), 500);
if (this.$content) {
this.$content.remove();
}
// Update Parent if Neccesary
if (this.parent !== null) {
_tabs[this.parent].update_display();
}
return;
}
// Parent
if (this.parent !== data.parent || !this.setup) {
var _attached = false;
if (data.parent !== null) {
var _parent_tab = _tabs[data.parent];
if (_parent_tab) {
if (util.is(this.$node).an_ancestor_of(_parent_tab.$node)) {
console.error("Cyclic Parents!", _parent_tab, this);
} else {
_attached = true;
this.$node.appendTo(_parent_tab.$children);
this.parent = data.parent;
_parent_tab.update_display();
}
} else {
console.error("Parent does not exist");
}
}
if (!_attached) {
this.$node.appendTo($tab_tree);
this.parent = null;
}
}
if (data.expanded) {
this.expanded = true;
this.$node.addClass('expanded');
} else {
this.expanded = false;
this.$node.removeClass('expanded');
}
// Url
if (!this.url) {
this.url = data.url;
}
// Title
if (!this.title) {
this.title = data.title ? data.title : "New Tab";
}
this.tab_name = data.tab_name;
this.update_tab_text();
// Color
this.tab_color = data.tab_color;
this.update_tab_color();
this.pinned = !!data.pinned;
this.setup = true;
this.update_display();
this.update_content_display();
},
update_display: function(){
this.$node.toggleClass('has-children', this.has_children());
this.$node.toggleClass('pinned', this.pinned);
},
with_content: function(callback, create) {
var _new = false;
if (!this.content && create) {
_new = true;
this.content = new tab_content.TabContent(this);
}
if (this.content) {
callback(this.content);
}
return _new;
},
update_content_display: function(){
this.with_content(function(content) {
content.update_display();
});
},
store_tab_data: function(){
storage.set_tab_data(this.id, {
parent: this.parent,
expanded: this.expanded,
url: this.url,
title: this.title,
tab_name: this.tab_name,
tab_color: this.tab_color,
pinned: this.pinned
});
},
button_clicked: function(e){
this.select_tab();
},
arrow_clicked: function(e){
this.expanded = !this.expanded;
this.store_tab_data();
},
select_tab: function(){
with_current(function(tab){
tab.unselect_tab();
});
_current = this.id;
this.$node.addClass('selected');
var _new = this.setup_tab_content();
this.content.show();
if (_new){
this.content.focus_address_bar();
}
},
// Return true if this is the first time that this.$content has been setup
setup_tab_content: function($existing_webview){
// Object to give TabContent to control tabs
var _tab_control = {
open_new_tab: open_new_tab
};
if (!this.content) {
this.content = new tab_content.TabContent(_tab_control, this, $existing_webview);
return true;
}
if ($existing_webview && this.content) {
throw new Error("this.content already setup for tab", this);
}
return false;
},
unselect_tab: function(){
this.$node.removeClass('selected');
this.content.hide();
if (this.id === _current) {
_current = null;
}
},
escape_tab: function(){
this.with_content(function(content) {
content.escape_content();
});
},
start_find: function(){
this.with_content(function(content) {
content.start_find();
});
},
close_tab: function(){
// Don't close if pinned
// TODO: show message
if (this.pinned) {
return;
}
// If the tab has children, don't close
// TODO: confirm
if (this.has_children()) {
return;
}
// Switch to a new tab if possible (parent)
if (_current === this.id) {
if (this.parent !== null){
var _parent = _tabs[this.parent];
_parent.select_tab();
} else {
this.unselect_tab();
_current = null;
}
}
// Delete Tab Data
storage.set_tab_data(this.id, undefined);
},
append_to_tab: function(id){
if (id !== null){
this.parent = id;
this.store_tab_data();
var _parent_tab = _tabs[this.parent];
if(!_parent_tab.expanded){
_parent_tab.expanded = true;
_parent_tab.store_tab_data();
}
} else {
this.append_to_root();
}
},
append_to_root: function(){
this.parent = null;
this.store_tab_data();
},
detatch: function() {
this.$node.addClass('detatched');
},
attach: function() {
this.$node.removeClass('detatched');
}
});
return {
init: init,
open_new_tab: open_new_tab,
open_new_root_tab: open_new_root_tab,
focus_address_bar: focus_address_bar,
close_current_tab: close_current_tab,
unselect_current_tab: unselect_current_tab,
escape_current_tab: escape_current_tab,
refresh_current_tab: refresh_current_tab,
start_find: start_find
};
});
| {'content_hash': '31002d9cb9842622567de5fbc93d4f3e', 'timestamp': '', 'source': 'github', 'line_count': 459, 'max_line_length': 94, 'avg_line_length': 24.352941176470587, 'alnum_prop': 0.5272857398461264, 'repo_name': 'samlanning/leaf-browser', 'id': '8c32289654c6511ca451d5b4b7c439b6189faa46', 'size': '11178', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'js/tabs.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '33582'}, {'name': 'HTML', 'bytes': '6880'}, {'name': 'JavaScript', 'bytes': '31580'}]} |
//C- -*- C++ -*-
//C- -------------------------------------------------------------------
//C- DjVuLibre-3.5
//C- Copyright (c) 2002 Leon Bottou and Yann Le Cun.
//C- Copyright (c) 2001 AT&T
//C-
//C- This software is subject to, and may be distributed under, the
//C- GNU General Public License, either Version 2 of the license,
//C- or (at your option) any later version. The license should have
//C- accompanied the software or you may obtain a copy of the license
//C- from the Free Software Foundation at http://www.fsf.org .
//C-
//C- This program is distributed in the hope that it will be useful,
//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//C- GNU General Public License for more details.
//C-
//C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library from
//C- Lizardtech Software. Lizardtech Software has authorized us to
//C- replace the original DjVu(r) Reference Library notice by the following
//C- text (see doc/lizard2002.djvu and doc/lizardtech2007.djvu):
//C-
//C- ------------------------------------------------------------------
//C- | DjVu (r) Reference Library (v. 3.5)
//C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved.
//C- | The DjVu Reference Library is protected by U.S. Pat. No.
//C- | 6,058,214 and patents pending.
//C- |
//C- | This software is subject to, and may be distributed under, the
//C- | GNU General Public License, either Version 2 of the license,
//C- | or (at your option) any later version. The license should have
//C- | accompanied the software or you may obtain a copy of the license
//C- | from the Free Software Foundation at http://www.fsf.org .
//C- |
//C- | The computer code originally released by LizardTech under this
//C- | license and unmodified by other parties is deemed "the LIZARDTECH
//C- | ORIGINAL CODE." Subject to any third party intellectual property
//C- | claims, LizardTech grants recipient a worldwide, royalty-free,
//C- | non-exclusive license to make, use, sell, or otherwise dispose of
//C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the
//C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU
//C- | General Public License. This grant only confers the right to
//C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to
//C- | the extent such infringement is reasonably necessary to enable
//C- | recipient to make, have made, practice, sell, or otherwise dispose
//C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to
//C- | any greater extent that may be necessary to utilize further
//C- | modifications or combinations.
//C- |
//C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY
//C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF
//C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//C- +------------------------------------------------------------------
#ifndef _DJVUINFO_H
#define _DJVUINFO_H
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if NEED_GNUG_PRAGMAS
# pragma interface
#endif
/** @name DjVuInfo.h
Each instance of class #DjVuInfo# represents the information
contained in the information chunk of a DjVu file. This #"INFO"#
chunk is always the first chunk of a DjVu file.
@memo
DjVu information chunk.
@author
L\'eon Bottou <[email protected]>
*/
//@{
#include "GSmartPointer.h"
#include "GRect.h"
#ifdef HAVE_NAMESPACES
namespace DJVU {
# ifdef NOT_DEFINED // Just to fool emacs c++ mode
}
#endif
#endif
class ByteStream;
/** @name DjVu version constants
@memo DjVu file format version. */
//@{
/** Current DjVu format version. The value of this macro represents the
version of the DjVu file format implemented by this release of the DjVu
Reference Library. */
#define DJVUVERSION 26
/** DjVu format version. This is the value used in files produced
with DjVuLibre. This is smaller than DJVUVERSION because version
number inflation causes problems with older software. */
#define DJVUVERSION_FOR_OUTPUT 24
/** This is the version which introduced orientations. */
#define DJVUVERSION_ORIENTATION 22
/** Oldest DjVu format version supported by this library. This release of the
library cannot completely decode DjVu files whose version field is less
than or equal to this number. */
#define DJVUVERSION_TOO_OLD 15
/** Newest DjVu format partially supported by this library. This release of
the library will attempt to decode files whose version field is smaller
than this macro. If the version field is greater than or equal to this
number, the decoder will just throw a \Ref{GException}. */
#define DJVUVERSION_TOO_NEW 50
//@}
class GUTF8String;
/** Information component.
Each instance of class #DjVuInfo# represents the information
contained in the information chunk of a DjVu file. This #"INFO"#
chunk is always the first chunk of a DjVu file.
*/
class DJVUAPI DjVuInfo : public GPEnabled
{
protected:
DjVuInfo(void);
public:
/** Creates an empty DjVuInfo object.
The #width# and #height# fields are set to zero.
All other fields are initialized with suitable default values. */
static GP<DjVuInfo> create(void) {return new DjVuInfo();}
/** Decodes the DjVu #"INFO"# chunk. This function reads binary data from
ByteStream #bs# and populates the fields of this DjVuInfo object. It is
normally called after detecting an #"INFO"# chunk header with function
\Ref{IFFByteStream::get_chunk}. */
void decode(ByteStream &bs);
/** Encodes the DjVu #"INFO"# chunk. This function writes the fields of this
DjVuInfo object into ByteStream #bs#. It is normally called after
creating an #"INFO"# chunk header with function
\Ref{IFFByteStream::put_chunk}. */
void encode(ByteStream &bs);
/** Returns the number of bytes used by this object. */
unsigned int get_memory_usage() const;
/** Width of the DjVu image (in pixels). */
int width;
/** Height of the DjVu image (in pixels). */
int height;
/** DjVu file version number. This number characterizes the file format
version used by the encoder to generate this DjVu image. A decoder
should compare this version number with the constants described in
section "\Ref{DjVu version constants}". */
int version;
/** Resolution of the DjVu image. The resolution is given in ``pixels per
2.54 centimeters'' (this unit is sometimes called ``pixels per
inch''). Display programs can use this information to determine the
natural magnification to use for rendering a DjVu image. */
int dpi;
/** Gamma coefficient of the display for which the image was designed. The
rendering functions can use this information in order to perform color
correction for the intended display device. */
double gamma;
/** Image orientation:
0: no rotation 1: 90 degrees counter-clockwise
2: 180 degrees 3: 270 degrees counter-clockwise */
int orientation;
/// Obtain the flags for the default specifications.
GUTF8String get_paramtags(void) const;
/// Obtain the flags for the default specifications.
void writeParam(ByteStream &out_str) const;
};
//@}
// ----- THE END
#ifdef HAVE_NAMESPACES
}
# ifndef NOT_USING_DJVU_NAMESPACE
using namespace DJVU;
# endif
#endif
#endif
| {'content_hash': 'c5b317baa696ea73c684101b81135ee4', 'timestamp': '', 'source': 'github', 'line_count': 187, 'max_line_length': 78, 'avg_line_length': 40.22994652406417, 'alnum_prop': 0.6959989365944437, 'repo_name': 'hk0792/UsefulClass', 'id': 'e1c9e0db161a3e36cb160a4b82b36119f66e2702', 'size': '7523', 'binary': False, 'copies': '55', 'ref': 'refs/heads/master', 'path': 'EBookDroid/jni/djvu/DjVuInfo.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '8693'}, {'name': 'C', 'bytes': '25042659'}, {'name': 'C++', 'bytes': '2621254'}, {'name': 'Groff', 'bytes': '37925'}, {'name': 'HTML', 'bytes': '10860'}, {'name': 'Java', 'bytes': '1137678'}, {'name': 'Makefile', 'bytes': '122637'}, {'name': 'Module Management System', 'bytes': '13919'}, {'name': 'Objective-C', 'bytes': '16685'}, {'name': 'Python', 'bytes': '180856'}, {'name': 'SAS', 'bytes': '14500'}, {'name': 'Shell', 'bytes': '663120'}, {'name': 'Smalltalk', 'bytes': '2632'}]} |
/) {}
virtual void OnKeyUp(UINT8 /*key*/) {}
// Accessors.
UINT GetWidth() const { return m_width; }
UINT GetHeight() const { return m_height; }
const WCHAR* GetTitle() const { return m_title.c_str(); }
void ParseCommandLineArgs(_In_reads_(argc) WCHAR* argv[], int argc);
void UpdateForSizeChange(UINT clientWidth, UINT clientHeight);
protected:
std::wstring GetAssetFullPath(LPCWSTR assetName);
void GetHardwareAdapter(_In_ IDXGIFactory2* pFactory, _Outptr_result_maybenull_ IDXGIAdapter1** ppAdapter);
void SetCustomWindowText(LPCWSTR text);
// Viewport dimensions.
UINT m_width;
UINT m_height;
float m_aspectRatio;
// Adapter info.
bool m_useWarpDevice;
private:
// Root assets path.
std::wstring m_assetsPath;
// Window title.
std::wstring m_title;
};
| {'content_hash': '2b3b3904f69b62d2c953e08065c91866', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 108, 'avg_line_length': 26.129032258064516, 'alnum_prop': 0.6987654320987654, 'repo_name': 'pengliu916/DirectX-Graphics-Samples', 'id': 'a5a453e141abda4dedd5cbcb996291b540c002be', 'size': '1722', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Samples/Desktop/D3D12Fullscreen/src/DXSample.h', 'mode': '33188', 'license': 'mit', 'language': []} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Docums Mycol. 17(no. 67): 12 (1987)
#### Original name
Russula atropurpurea f. pantherina Zvára
### Remarks
null | {'content_hash': '1a7ddd3406316aeb58f058ae0868c857', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 40, 'avg_line_length': 13.538461538461538, 'alnum_prop': 0.7045454545454546, 'repo_name': 'mdoering/backbone', 'id': '4f972300e4af9d05a0b957aaf1aafe625a097310', 'size': '244', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Basidiomycota/Agaricomycetes/Russulales/Russulaceae/Russula/Russula atropurpurea/Russula krombholzii pantherina/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="index.css">
<title>Spinner</title>
</head>
<body>
<div id="root"></div>
<script src="Spinner.js"></script>
</body>
</html> | {'content_hash': '3997a06578622a8ce78e0af401f90fea', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 90, 'avg_line_length': 23.647058823529413, 'alnum_prop': 0.6293532338308457, 'repo_name': 'Acceleratio/quick-react.ts', 'id': '2f23a394929a1a49590f476ad56f06af00c5e8dc', 'size': '402', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'examples/pages/Spinner.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '109185'}, {'name': 'JavaScript', 'bytes': '6676'}, {'name': 'TypeScript', 'bytes': '529205'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '8439763b0ffe82cde2f41e4016ec97d4', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '2163589602f0c4d2785e1f042ea237b78dc6912d', 'size': '172', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Proteales/Proteaceae/Banksia/Banksia paludosa/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
string Namespace = typeof(Startup).Namespace;
string AppName = Namespace.Substring(Namespace.LastIndexOf('.', Namespace.LastIndexOf('.') - 1) + 1);
var configuration = GetConfiguration();
Log.Logger = CreateSerilogLogger(configuration);
try
{
Log.Information("Configuring web host ({ApplicationContext})...", AppName);
var host = BuildWebHost(configuration, args);
Log.Information("Applying migrations ({ApplicationContext})...", AppName);
host.MigrateDbContext<PersistedGrantDbContext>((_, __) => { })
.MigrateDbContext<ApplicationDbContext>((context, services) =>
{
var env = services.GetService<IWebHostEnvironment>();
var logger = services.GetService<ILogger<ApplicationDbContextSeed>>();
var settings = services.GetService<IOptions<AppSettings>>();
new ApplicationDbContextSeed()
.SeedAsync(context, env, logger, settings)
.Wait();
})
.MigrateDbContext<ConfigurationDbContext>((context, services) =>
{
new ConfigurationDbContextSeed()
.SeedAsync(context, configuration)
.Wait();
});
Log.Information("Starting web host ({ApplicationContext})...", AppName);
host.Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Program terminated unexpectedly ({ApplicationContext})!", AppName);
return 1;
}
finally
{
Log.CloseAndFlush();
}
IWebHost BuildWebHost(IConfiguration configuration, string[] args) =>
WebHost.CreateDefaultBuilder(args)
.CaptureStartupErrors(false)
.ConfigureAppConfiguration(x => x.AddConfiguration(configuration))
.UseStartup<Startup>()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseSerilog()
.Build();
Serilog.ILogger CreateSerilogLogger(IConfiguration configuration)
{
var seqServerUrl = configuration["Serilog:SeqServerUrl"];
var logstashUrl = configuration["Serilog:LogstashgUrl"];
return new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.WithProperty("ApplicationContext", AppName)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.Seq(string.IsNullOrWhiteSpace(seqServerUrl) ? "http://seq" : seqServerUrl)
.WriteTo.Http(string.IsNullOrWhiteSpace(logstashUrl) ? "http://localhost:8080" : logstashUrl)
.ReadFrom.Configuration(configuration)
.CreateLogger();
}
IConfiguration GetConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
var config = builder.Build();
if (config.GetValue<bool>("UseVault", false))
{
TokenCredential credential = new ClientSecretCredential(
config["Vault:TenantId"],
config["Vault:ClientId"],
config["Vault:ClientSecret"]);
builder.AddAzureKeyVault(new Uri($"https://{config["Vault:Name"]}.vault.azure.net/"), credential);
}
return builder.Build();
} | {'content_hash': '52ab6bd41df82756b1c4a8196d2ae074', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 106, 'avg_line_length': 34.733333333333334, 'alnum_prop': 0.6647472808701216, 'repo_name': 'skynode/eShopOnContainers', 'id': '7c021c7a4ef32f0ff41c993918d908d1efc2bec8', 'size': '3128', 'binary': False, 'copies': '3', 'ref': 'refs/heads/dev', 'path': 'src/Services/Identity/Identity.API/Program.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1196'}, {'name': 'C#', 'bytes': '934876'}, {'name': 'CSS', 'bytes': '57213'}, {'name': 'Dockerfile', 'bytes': '66088'}, {'name': 'HTML', 'bytes': '101511'}, {'name': 'JavaScript', 'bytes': '283613'}, {'name': 'Mustache', 'bytes': '24323'}, {'name': 'PowerShell', 'bytes': '28577'}, {'name': 'SCSS', 'bytes': '41494'}, {'name': 'Shell', 'bytes': '22808'}, {'name': 'Smarty', 'bytes': '20151'}, {'name': 'TypeScript', 'bytes': '64288'}]} |
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="html/html; charset=utf-8" />
<title>SSCollectionViewExtremityTableViewCell Class Reference</title>
<meta id="xcode-display" name="xcode-display" content="render"/>
<meta name="viewport" content="width=550" />
<link rel="stylesheet" type="text/css" href="../css/styles.css" media="all" />
<link rel="stylesheet" type="text/css" media="print" href="../css/stylesPrint.css" />
<meta name="generator" content="appledoc 2.1 (build 840)" />
</head>
<body>
<header id="top_header">
<div id="library" class="hideInXcode">
<h1><a id="libraryTitle" href="../index.html">SSToolkit 1.0.2 </a></h1>
<a id="developerHome" href="../index.html">Sam Soffes</a>
</div>
<div id="title" role="banner">
<h1 class="hideInXcode">SSCollectionViewExtremityTableViewCell Class Reference</h1>
</div>
<ul id="headerButtons" role="toolbar">
<li id="toc_button">
<button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents"><span class="disclosure"></span>Table of Contents</button>
</li>
<li id="jumpto_button" role="navigation">
<select id="jumpTo">
<option value="top">Jump To…</option>
<option value="tasks">Tasks</option>
<option value="properties">Properties</option>
<option value="//api/name/extrimityView"> extrimityView</option>
<option value="instance_methods">Instance Methods</option>
<option value="//api/name/initWithReuseIdentifier:"> - initWithReuseIdentifier:</option>
</select>
</li>
</ul>
</header>
<nav id="tocContainer" class="isShowingTOC">
<ul id="toc" role="tree">
<li role="treeitem" id="task_treeitem"><span class="nodisclosure"></span><span class="sectionName"><a href="#tasks">Tasks</a></span><ul>
</ul></li>
<li role="treeitem" class="children"><span class="disclosure"></span><span class="sectionName"><a href="#properties">Properties</a></span><ul>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/extrimityView">extrimityView</a></span></li>
</ul></li>
<li role="treeitem" class="children"><span class="disclosure"></span><span class="sectionName"><a href="#instance_methods">Instance Methods</a></span><ul>
<li><span class="nodisclosure"></span><span class="sectionName"><a href="#//api/name/initWithReuseIdentifier:">initWithReuseIdentifier:</a></span></li>
</ul></li>
</ul>
</nav>
<article>
<div id="contents" class="isShowingTOC" role="main">
<a title="SSCollectionViewExtremityTableViewCell Class Reference" name="top"></a>
<div class="main-navigation navigation-top">
<ul>
<li><a href="../index.html">Index</a></li>
<li><a href="../hierarchy.html">Hierarchy</a></li>
</ul>
</div>
<div id="header">
<div class="section-header">
<h1 class="title title-header">SSCollectionViewExtremityTableViewCell Class Reference</h1>
</div>
</div>
<div id="container">
<div class="section section-specification"><table cellspacing="0"><tbody>
<tr>
<td class="specification-title">Inherits from</td>
<td class="specification-value">UITableViewCell</td>
</tr><tr>
<td class="specification-title">Declared in</td>
<td class="specification-value">SSCollectionViewExtremityTableViewCell.h</td>
</tr>
</tbody></table></div>
<div class="section section-tasks">
<a title="Tasks" name="tasks"></a>
<h2 class="subtitle subtitle-tasks">Tasks</h2>
<ul class="task-list">
<li>
<span class="tooltip">
<code><a href="#//api/name/extrimityView"> extrimityView</a></code>
</span>
<span class="task-item-suffix">property</span>
</li><li>
<span class="tooltip">
<code><a href="#//api/name/initWithReuseIdentifier:">– initWithReuseIdentifier:</a></code>
</span>
</li>
</ul>
</div>
<div class="section section-methods">
<a title="Properties" name="properties"></a>
<h2 class="subtitle subtitle-methods">Properties</h2>
<div class="section-method">
<a name="//api/name/extrimityView" title="extrimityView"></a>
<h3 class="subsubtitle method-title">extrimityView</h3>
<div class="method-subsection method-declaration"><code>@property (nonatomic, strong) UIView *extrimityView</code></div>
</div>
</div>
<div class="section section-methods">
<a title="Instance Methods" name="instance_methods"></a>
<h2 class="subtitle subtitle-methods">Instance Methods</h2>
<div class="section-method">
<a name="//api/name/initWithReuseIdentifier:" title="initWithReuseIdentifier:"></a>
<h3 class="subsubtitle method-title">initWithReuseIdentifier:</h3>
<div class="method-subsection method-declaration"><code>- (id)initWithReuseIdentifier:(NSString *)<em>aReuseIdentifier</em></code></div>
</div>
</div>
</div>
<div class="main-navigation navigation-bottom">
<ul>
<li><a href="../index.html">Index</a></li>
<li><a href="../hierarchy.html">Hierarchy</a></li>
</ul>
</div>
<div id="footer">
<hr />
<div class="footer-copyright">
<p><span class="copyright">© 2012 Sam Soffes. All rights reserved. (Last updated: 2012-11-21)</span><br />
<span class="generator">Generated by <a href="http://appledoc.gentlebytes.com">appledoc 2.1 (build 840)</a>.</span></p>
</div>
</div>
</div>
</article>
<script type="text/javascript">
function jumpToChange()
{
window.location.hash = this.options[this.selectedIndex].value;
}
function toggleTOC()
{
var contents = document.getElementById('contents');
var tocContainer = document.getElementById('tocContainer');
if (this.getAttribute('class') == 'open')
{
this.setAttribute('class', '');
contents.setAttribute('class', '');
tocContainer.setAttribute('class', '');
window.name = "hideTOC";
}
else
{
this.setAttribute('class', 'open');
contents.setAttribute('class', 'isShowingTOC');
tocContainer.setAttribute('class', 'isShowingTOC');
window.name = "";
}
return false;
}
function toggleTOCEntryChildren(e)
{
e.stopPropagation();
var currentClass = this.getAttribute('class');
if (currentClass == 'children') {
this.setAttribute('class', 'children open');
}
else if (currentClass == 'children open') {
this.setAttribute('class', 'children');
}
return false;
}
function tocEntryClick(e)
{
e.stopPropagation();
return true;
}
function init()
{
var selectElement = document.getElementById('jumpTo');
selectElement.addEventListener('change', jumpToChange, false);
var tocButton = document.getElementById('table_of_contents');
tocButton.addEventListener('click', toggleTOC, false);
var taskTreeItem = document.getElementById('task_treeitem');
if (taskTreeItem.getElementsByTagName('li').length > 0)
{
taskTreeItem.setAttribute('class', 'children');
taskTreeItem.firstChild.setAttribute('class', 'disclosure');
}
var tocList = document.getElementById('toc');
var tocEntries = tocList.getElementsByTagName('li');
for (var i = 0; i < tocEntries.length; i++) {
tocEntries[i].addEventListener('click', toggleTOCEntryChildren, false);
}
var tocLinks = tocList.getElementsByTagName('a');
for (var i = 0; i < tocLinks.length; i++) {
tocLinks[i].addEventListener('click', tocEntryClick, false);
}
if (window.name == "hideTOC") {
toggleTOC.call(tocButton);
}
}
window.onload = init;
// If showing in Xcode, hide the TOC and Header
if (navigator.userAgent.match(/xcode/i)) {
document.getElementById("contents").className = "hideInXcode"
document.getElementById("tocContainer").className = "hideInXcode"
document.getElementById("top_header").className = "hideInXcode"
}
</script>
</body>
</html> | {'content_hash': '1a2e1affe77769f671184b725dca695b', 'timestamp': '', 'source': 'github', 'line_count': 303, 'max_line_length': 159, 'avg_line_length': 27.36963696369637, 'alnum_prop': 0.6329434462799952, 'repo_name': 'BellGeorge/BGLibrary', 'id': '243706f4ef187fe9c8264ddf193d7ded540b4c44', 'size': '8293', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Pods/Documentation/SSToolkit/docset/Contents/Resources/Documents/Classes/SSCollectionViewExtremityTableViewCell.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '162523'}, {'name': 'C', 'bytes': '627074'}, {'name': 'C++', 'bytes': '991'}, {'name': 'Objective-C', 'bytes': '2309317'}, {'name': 'Ruby', 'bytes': '15681'}, {'name': 'Shell', 'bytes': '1534'}]} |
include_recipe 'apt' if platform?('ubuntu')
include_recipe 'java'
mysql_service 'sonar' do
version '5.6'
initial_root_password 'root'
action [:create, :start]
end
mysql2_chef_gem 'default' do
action :install
end
mysql_connection_info = {:host => "127.0.0.1",
:username => 'root',
:password => 'root'}
mysql_database 'sonar' do
connection mysql_connection_info
action :create
end
mysql_database_user 'sonar' do
connection mysql_connection_info
password 'sonar'
host '%'
database_name 'sonar'
action :grant
end
include_recipe 'sonarqube'
| {'content_hash': '792b84420fc9da95f18d0e8eb11a2463', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 46, 'avg_line_length': 17.65714285714286, 'alnum_prop': 0.6440129449838188, 'repo_name': 'ahoffmann-wi/vagrant-sonarqube', 'id': '2c5dea5c956b28ea3d77f10941ffe6b4cf1546c5', 'size': '744', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'recipes/default.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ruby', 'bytes': '2414'}]} |
use std::old_io::{Listener, EndOfFile, BufferedReader, BufferedWriter};
use std::old_io::net::ip::{IpAddr, Port, SocketAddr};
use std::os;
use std::sync::{Arc, TaskPool};
use std::thread::{Builder, JoinGuard};
pub use self::request::Request;
pub use self::response::Response;
pub use net::{Fresh, Streaming};
use HttpError::HttpIoError;
use {HttpResult};
use header::Connection;
use header::ConnectionOption::{Close, KeepAlive};
use net::{NetworkListener, NetworkStream, NetworkAcceptor,
HttpAcceptor, HttpListener};
use version::HttpVersion::{Http10, Http11};
pub mod request;
pub mod response;
/// A server can listen on a TCP socket.
///
/// Once listening, it will create a `Request`/`Response` pair for each
/// incoming connection, and hand them to the provided handler.
pub struct Server<L = HttpListener> {
ip: IpAddr,
port: Port,
listener: L,
}
macro_rules! try_option(
($e:expr) => {{
match $e {
Some(v) => v,
None => return None
}
}}
);
impl Server<HttpListener> {
/// Creates a new server that will handle `HttpStream`s.
pub fn http(ip: IpAddr, port: Port) -> Server {
Server::with_listener(ip, port, HttpListener::Http)
}
/// Creates a new server that will handler `HttpStreams`s using a TLS connection.
pub fn https(ip: IpAddr, port: Port, cert: Path, key: Path) -> Server {
Server::with_listener(ip, port, HttpListener::Https(cert, key))
}
}
impl<
L: NetworkListener<Acceptor=A> + Send,
A: NetworkAcceptor<Stream=S> + Send,
S: NetworkStream + Clone + Send> Server<L> {
/// Creates a new server that will handle `HttpStream`s.
pub fn with_listener(ip: IpAddr, port: Port, listener: L) -> Server<L> {
Server {
ip: ip,
port: port,
listener: listener,
}
}
/// Binds to a socket, and starts handling connections using a task pool.
pub fn listen_threads<H: Handler>(mut self, handler: H, threads: usize) -> HttpResult<Listening<L::Acceptor>> {
debug!("binding to {:?}:{:?}", self.ip, self.port);
let acceptor = try!(self.listener.listen((self.ip, self.port)));
let socket = try!(acceptor.socket_name());
let mut captured = acceptor.clone();
let guard = Builder::new().name("hyper acceptor".to_string()).scoped(move || {
let handler = Arc::new(handler);
debug!("threads = {:?}", threads);
let pool = TaskPool::new(threads);
for conn in captured.incoming() {
match conn {
Ok(mut stream) => {
debug!("Incoming stream");
let handler = handler.clone();
pool.execute(move || {
let addr = match stream.peer_name() {
Ok(addr) => addr,
Err(e) => {
error!("Peer Name error: {:?}", e);
return;
}
};
let mut rdr = BufferedReader::new(stream.clone());
let mut wrt = BufferedWriter::new(stream);
let mut keep_alive = true;
while keep_alive {
let mut res = Response::new(&mut wrt);
let req = match Request::new(&mut rdr, addr) {
Ok(req) => req,
Err(e@HttpIoError(_)) => {
debug!("ioerror in keepalive loop = {:?}", e);
return;
}
Err(e) => {
//TODO: send a 400 response
error!("request error = {:?}", e);
return;
}
};
keep_alive = match (req.version, req.headers.get::<Connection>()) {
(Http10, Some(conn)) if !conn.contains(&KeepAlive) => false,
(Http11, Some(conn)) if conn.contains(&Close) => false,
_ => true
};
res.version = req.version;
handler.handle(req, res);
debug!("keep_alive = {:?}", keep_alive);
}
});
},
Err(ref e) if e.kind == EndOfFile => {
debug!("server closed");
break;
},
Err(e) => {
error!("Connection failed: {}", e);
continue;
}
}
}
});
Ok(Listening {
acceptor: acceptor,
guard: Some(guard),
socket: socket,
})
}
/// Binds to a socket and starts handling connections.
pub fn listen<H: Handler>(self, handler: H) -> HttpResult<Listening<L::Acceptor>> {
self.listen_threads(handler, os::num_cpus() * 5 / 4)
}
}
/// A listening server, which can later be closed.
pub struct Listening<A = HttpAcceptor> {
acceptor: A,
guard: Option<JoinGuard<'static, ()>>,
/// The socket addresses that the server is bound to.
pub socket: SocketAddr,
}
impl<A: NetworkAcceptor> Listening<A> {
/// Causes the current thread to wait for this listening to complete.
pub fn await(&mut self) {
if let Some(guard) = self.guard.take() {
let _ = guard.join();
}
}
/// Stop the server from listening to its socket address.
pub fn close(&mut self) -> HttpResult<()> {
debug!("closing server");
try!(self.acceptor.close());
Ok(())
}
}
/// A handler that can handle incoming requests for a server.
pub trait Handler: Sync + Send {
/// Receives a `Request`/`Response` pair, and should perform some action on them.
///
/// This could reading from the request, and writing to the response.
fn handle<'a>(&'a self, Request<'a>, Response<'a, Fresh>);
}
impl<F> Handler for F where F: Fn(Request, Response<Fresh>), F: Sync + Send {
fn handle(&self, req: Request, res: Response<Fresh>) {
(*self)(req, res)
}
}
| {'content_hash': 'fd19094c104a2139359ccfb5240fe959', 'timestamp': '', 'source': 'github', 'line_count': 184, 'max_line_length': 115, 'avg_line_length': 36.15760869565217, 'alnum_prop': 0.4811363294754246, 'repo_name': 'frewsxcv/hyper', 'id': '43061e76763bf822bfde1987de29f15220855c77', 'size': '6669', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/server/mod.rs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Rust', 'bytes': '268959'}]} |
import unittest
from programy.config.file.yaml_file import YamlConfigurationFile
from programy.config.client.client import ClientConfiguration
from programy.config.brain import BrainFileConfiguration
class ClientConfigurationTests(unittest.TestCase):
def test_init(self):
client_config = ClientConfiguration()
yaml = YamlConfigurationFile(client_config)
self.assertIsNotNone(yaml)
yaml.load_from_text("""
brain:
supress_warnings: true
allow_system_aiml: true
allow_learn_aiml: true
allow_learnf_aiml: true
files:
aiml:
files: /aiml
extension: .aiml
directories: true
sets:
files: /sets
extension: .txt
directories: false
maps:
files: /maps
extension: .txt
directories: false
denormal: denormal.txt
normal: normal.txt
gender: gender.txt
person: person.txt
person2: person2.txt
predicates: predicates.txt
pronouns: pronouns.txt
properties: properties.txt
triples: triples.txt
preprocessors: preprocessors.txt
postprocessors: postprocessors.txt
services:
REST:
path: programy.utils.services.rest.GenericRESTService
Pannous:
path: programy.utils.services.pannous.PannousService
Pandora:
path: programy.utils.services.pandora.PandoraService
Wikipedia:
path: programy.utils.services.wikipedia.WikipediaService
bot:
prompt: ">>>"
default_response: Sorry, I don't have an answer for that!
exit_response: So long, and thanks for the fish!
initial_question: Hi, how can I help you?
override_predicates: true
""", ".")
self.assertIsNotNone(client_config.bot_configuration)
self.assertIsNotNone(client_config.bot_configuration.prompt)
self.assertEquals(">>>", client_config.bot_configuration.prompt)
self.assertIsNotNone(client_config.bot_configuration.default_response)
self.assertEquals("Sorry, I don't have an answer for that!", client_config.bot_configuration.default_response)
self.assertIsNotNone(client_config.bot_configuration.exit_response)
self.assertEquals("So long, and thanks for the fish!", client_config.bot_configuration.exit_response)
self.assertIsNotNone(client_config.bot_configuration.initial_question)
self.assertEquals("Hi, how can I help you?", client_config.bot_configuration.initial_question)
self.assertIsNotNone(client_config.brain_configuration)
self.assertTrue(client_config.brain_configuration.supress_warnings)
self.assertTrue(client_config.brain_configuration.allow_system_aiml)
self.assertTrue(client_config.brain_configuration.allow_learn_aiml)
self.assertTrue(client_config.brain_configuration.allow_learnf_aiml)
self.assertIsNotNone(client_config.brain_configuration._aiml_files)
self.assertIsInstance(client_config.brain_configuration._aiml_files, BrainFileConfiguration)
self.assertEquals("/aiml", client_config.brain_configuration._aiml_files.files)
self.assertEquals(".aiml", client_config.brain_configuration._aiml_files.extension)
self.assertTrue(client_config.brain_configuration._aiml_files.directories)
self.assertIsNotNone(client_config.brain_configuration._set_files)
self.assertIsInstance(client_config.brain_configuration._set_files, BrainFileConfiguration)
self.assertEquals("/sets", client_config.brain_configuration._set_files.files)
self.assertEquals(".txt", client_config.brain_configuration._set_files.extension)
self.assertFalse(client_config.brain_configuration._set_files.directories)
self.assertIsNotNone(client_config.brain_configuration._map_files)
self.assertIsInstance(client_config.brain_configuration._map_files, BrainFileConfiguration)
self.assertEquals("/maps", client_config.brain_configuration._map_files.files)
self.assertEquals(".txt", client_config.brain_configuration._map_files.extension)
self.assertFalse(client_config.brain_configuration._map_files.directories)
self.assertIsNotNone(client_config.brain_configuration._denormal)
self.assertEquals("denormal.txt", client_config.brain_configuration._denormal)
self.assertIsNotNone(client_config.brain_configuration._normal)
self.assertEquals("normal.txt", client_config.brain_configuration._normal)
self.assertIsNotNone(client_config.brain_configuration._gender)
self.assertEquals("gender.txt", client_config.brain_configuration._gender)
self.assertIsNotNone(client_config.brain_configuration._person)
self.assertEquals("person.txt", client_config.brain_configuration._person)
self.assertIsNotNone(client_config.brain_configuration._person2)
self.assertEquals("person2.txt", client_config.brain_configuration._person2)
self.assertIsNotNone(client_config.brain_configuration._predicates)
self.assertEquals("predicates.txt", client_config.brain_configuration._predicates)
self.assertIsNotNone(client_config.brain_configuration._pronouns)
self.assertEquals("pronouns.txt", client_config.brain_configuration._pronouns)
self.assertIsNotNone(client_config.brain_configuration._properties)
self.assertEquals("properties.txt", client_config.brain_configuration._properties)
self.assertIsNotNone(client_config.brain_configuration._triples)
self.assertEquals("triples.txt", client_config.brain_configuration._triples)
self.assertIsNotNone(client_config.brain_configuration._preprocessors)
self.assertEquals("preprocessors.txt", client_config.brain_configuration._preprocessors)
self.assertIsNotNone(client_config.brain_configuration._postprocessors)
self.assertEquals("postprocessors.txt", client_config.brain_configuration._postprocessors)
self.assertIsNotNone(client_config.brain_configuration._services)
self.assertEquals(4, len(client_config.brain_configuration._services))
def test_init_with_blank_data(self):
with self.assertRaises(Exception):
client_config = ClientConfiguration()
yaml = YamlConfigurationFile(client_config)
self.assertIsNotNone(yaml)
yaml.load_from_text("""
""", ".")
def test_init_with_empty_sections(self):
with self.assertRaises(Exception):
client_config = ClientConfiguration()
yaml = YamlConfigurationFile(client_config)
self.assertIsNotNone(yaml)
yaml.load_from_text("""
brain:
files:
""", ".")
def test_init_with_files_only(self):
client_config = ClientConfiguration()
yaml = YamlConfigurationFile(client_config)
self.assertIsNotNone(yaml)
yaml.load_from_text("""
brain:
files:
aiml:
files: /aiml
extension: .aiml
directories: true
sets:
files: /sets
extension: .txt
directories: false
maps:
files: /maps
extension: .txt
directories: false
denormal: denormal.txt
normal: normal.txt
gender: gender.txt
person: person.txt
person2: person2.txt
predicates: predicates.txt
pronouns: pronouns.txt
properties: properties.txt
triples: triples.txt
preprocessors: preprocessors.txt
postprocessors: postprocessors.txt
bot:
""", ".")
self.assertIsNotNone(client_config.bot_configuration)
self.assertIsNotNone(client_config.bot_configuration.prompt)
self.assertEquals(">>> ", client_config.bot_configuration.prompt)
self.assertIsNotNone(client_config.bot_configuration.default_response)
self.assertEquals("Sorry, I don't have an answer for that right now", client_config.bot_configuration.default_response)
self.assertIsNotNone(client_config.bot_configuration.exit_response)
self.assertEquals("Bye!", client_config.bot_configuration.exit_response)
self.assertIsNotNone(client_config.bot_configuration.initial_question)
self.assertEquals("Hello", client_config.bot_configuration.initial_question)
self.assertIsNotNone(client_config.brain_configuration)
self.assertFalse(client_config.brain_configuration.supress_warnings)
self.assertTrue(client_config.brain_configuration.allow_system_aiml)
self.assertTrue(client_config.brain_configuration.allow_learn_aiml)
self.assertTrue(client_config.brain_configuration.allow_learnf_aiml)
self.assertIsNotNone(client_config.brain_configuration._services)
self.assertEqual(0, len(client_config.brain_configuration._services))
def test_init_with_brain_empty_children(self):
with self.assertRaises(Exception):
client_config = ClientConfiguration()
yaml = YamlConfigurationFile(client_config)
self.assertIsNotNone(yaml)
yaml.load_from_text("""
brain:
files:
services:
bot:
""", ".")
| {'content_hash': 'f2db48b2f173054f04caf7424534f802', 'timestamp': '', 'source': 'github', 'line_count': 215, 'max_line_length': 127, 'avg_line_length': 45.55813953488372, 'alnum_prop': 0.6592138846350178, 'repo_name': 'dkamotsky/program-y', 'id': '5a016972dd2420eeb12a0ef411634c5277ed00dd', 'size': '9795', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/config/client/test_client.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '937'}, {'name': 'HTML', 'bytes': '1583'}, {'name': 'Python', 'bytes': '1131157'}, {'name': 'Shell', 'bytes': '3481'}]} |
cask "origin" do
version "10.5.115.51547"
sha256 :no_check
url "https://origin-a.akamaihd.net/Origin-Client-Download/origin/mac/live/Origin.dmg",
verified: "origin-a.akamaihd.net/Origin-Client-Download/"
name "Origin"
desc "Play PC games and connect with your friends"
homepage "https://www.origin.com/"
livecheck do
url :url
strategy :extract_plist
end
auto_updates true
app "Origin.app"
zap trash: [
"~/Library/Application Support/Origin",
"~/Library/Caches/com.ea.Origin",
"~/Library/Caches/Origin",
"~/Library/LaunchAgents/com.ea.origin.WebHelper.plist",
"~/Library/Saved Application State/com.ea.Origin.savedState",
]
end
| {'content_hash': 'ba3d3e29eb1b5792b35f7c9cb03927f8', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 88, 'avg_line_length': 25.555555555555557, 'alnum_prop': 0.691304347826087, 'repo_name': 'stephenwade/homebrew-cask', 'id': 'eddf7328efded8974f0ce235dee3cc655ea1b3c9', 'size': '690', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'Casks/origin.rb', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Python', 'bytes': '3630'}, {'name': 'Ruby', 'bytes': '3066644'}, {'name': 'Shell', 'bytes': '32035'}]} |
package com.amazonaws.services.elasticloadbalancing.model.transform;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.internal.ListWithAutoConstructFlag;
import com.amazonaws.services.elasticloadbalancing.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* Describe Load Balancer Policies Request Marshaller
*/
public class DescribeLoadBalancerPoliciesRequestMarshaller implements Marshaller<Request<DescribeLoadBalancerPoliciesRequest>, DescribeLoadBalancerPoliciesRequest> {
public Request<DescribeLoadBalancerPoliciesRequest> marshall(DescribeLoadBalancerPoliciesRequest describeLoadBalancerPoliciesRequest) {
if (describeLoadBalancerPoliciesRequest == null) {
throw new AmazonClientException("Invalid argument passed to marshall(...)");
}
Request<DescribeLoadBalancerPoliciesRequest> request = new DefaultRequest<DescribeLoadBalancerPoliciesRequest>(describeLoadBalancerPoliciesRequest, "AmazonElasticLoadBalancing");
request.addParameter("Action", "DescribeLoadBalancerPolicies");
request.addParameter("Version", "2012-06-01");
if (describeLoadBalancerPoliciesRequest.getLoadBalancerName() != null) {
request.addParameter("LoadBalancerName", StringUtils.fromString(describeLoadBalancerPoliciesRequest.getLoadBalancerName()));
}
java.util.List<String> policyNamesList = describeLoadBalancerPoliciesRequest.getPolicyNames();
int policyNamesListIndex = 1;
for (String policyNamesListValue : policyNamesList) {
if (policyNamesListValue != null) {
request.addParameter("PolicyNames.member." + policyNamesListIndex, StringUtils.fromString(policyNamesListValue));
}
policyNamesListIndex++;
}
return request;
}
}
| {'content_hash': 'a27ac033b3d5ca1046bc9feb7e8aa711', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 186, 'avg_line_length': 41.729166666666664, 'alnum_prop': 0.7663504742885672, 'repo_name': 'nhuray/aws-sdk-java', 'id': '60838be92d6400c93ecf1208a4f1b78294119a86', 'size': '2590', 'binary': False, 'copies': '28', 'ref': 'refs/heads/master', 'path': 'aws-java-sdk-elasticloadbalancing/src/main/java/com/amazonaws/services/elasticloadbalancing/model/transform/DescribeLoadBalancerPoliciesRequestMarshaller.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '88765567'}, {'name': 'Scilab', 'bytes': '2354'}]} |
/* (C) 2008 by Harald Welte <[email protected]>
* (C) 2010 by Holger Hans Peter Freyther <[email protected]>
* 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 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.
*
*/
/*! \addtogroup msgb
* @{
*/
/*! \file msgb.c
*/
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include "msgb.h"
#include "talloc.h"
void *tall_msgb_ctx;
/*! \brief Allocate a new message buffer
* \param[in] size Length in octets, including headroom
* \param[in] name Human-readable name to be associated with msgb
*
* This function allocates a 'struct msgb' as well as the underlying
* memory buffer for the actual message data (size specified by \a size)
* using the talloc memory context previously set by \ref msgb_set_talloc_ctx
*/
struct msgb *msgb_alloc(uint16_t size, const char *name)
{
struct msgb *msg;
msg = _talloc_zero(tall_msgb_ctx, sizeof(*msg) + size, name);
if (!msg) {
//LOGP(DRSL, LOGL_FATAL, "unable to allocate msgb\n");
return NULL;
}
msg->data_len = size;
msg->len = 0;
msg->data = msg->_data;
msg->head = msg->_data;
msg->tail = msg->_data;
return msg;
}
/*! \brief Release given message buffer
* \param[in] m Message buffer to be free'd
*/
void msgb_free(struct msgb *m)
{
talloc_free(m);
}
/*! \brief Enqueue message buffer to tail of a queue
* \param[in] queue linked list header of queue
* \param[in] msgb message buffer to be added to the queue
*
* The function will append the specified message buffer \a msg to the
* queue implemented by \ref llist_head \a queue
*/
void msgb_enqueue(struct llist_head *queue, struct msgb *msg)
{
llist_add_tail(&msg->list, queue);
}
/*! \brief Dequeue message buffer from head of queue
* \param[in] queue linked list header of queue
* \returns message buffer (if any) or NULL if queue empty
*
* The function will remove the first message buffer from the queue
* implemented by 'ref llist_head \a queue.
*/
struct msgb *msgb_dequeue(struct llist_head *queue)
{
struct llist_head *lh;
if (llist_empty(queue))
return NULL;
lh = queue->next;
llist_del(lh);
return llist_entry(lh, struct msgb, list);
}
/*! \brief Re-set all message buffer pointers
* \param[in] m message buffer that is to be resetted
*
* This will re-set the various internal pointers into the underlying
* message buffer, i.e. remvoe all headroom and treat the msgb as
* completely empty. It also initializes the control buffer to zero.
*/
void msgb_reset(struct msgb *msg)
{
msg->len = 0;
msg->data = msg->_data;
msg->head = msg->_data;
msg->tail = msg->_data;
msg->trx = NULL;
msg->lchan = NULL;
msg->l2h = NULL;
msg->l3h = NULL;
msg->l4h = NULL;
memset(&msg->cb, 0, sizeof(msg->cb));
}
/*! \brief get pointer to data section of message buffer
* \param[in] msg message buffer
* \returns pointer to data section of message buffer
*/
uint8_t *msgb_data(const struct msgb *msg)
{
return msg->data;
}
/*! \brief get length of message buffer
* \param[in] msg message buffer
* \returns length of data section in message buffer
*/
uint16_t msgb_length(const struct msgb *msg)
{
return msg->len;
}
/*! \brief Set the talloc context for \ref msgb_alloc
* \param[in] ctx talloc context to be used as root for msgb allocations
*/
void msgb_set_talloc_ctx(void *ctx)
{
tall_msgb_ctx = ctx;
}
/*! @} */
| {'content_hash': '25a42a5753e448bed738095f8bc425e0', 'timestamp': '', 'source': 'github', 'line_count': 154, 'max_line_length': 77, 'avg_line_length': 26.006493506493506, 'alnum_prop': 0.6953807740324595, 'repo_name': 'gcds/project_xxx', 'id': 'e25366e5cadc81171ad09ba0295256bb268da31e', 'size': '4005', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'misc/tools/osmocon/msgb.c', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
/**
* A component to set restitution on objects.
*
* @namespace Phaser.Physics.Matter.Components.Bounce
* @since 3.0.0
*/
var Bounce = {
/**
* Sets the restitution on the physics object.
*
* @method Phaser.Physics.Matter.Components.Bounce#setBounce
* @since 3.0.0
*
* @param {number} value - A Number that defines the restitution (elasticity) of the body. The value is always positive and is in the range (0, 1). A value of 0 means collisions may be perfectly inelastic and no bouncing may occur. A value of 0.8 means the body may bounce back with approximately 80% of its kinetic energy. Note that collision response is based on pairs of bodies, and that restitution values are combined with the following formula: `Math.max(bodyA.restitution, bodyB.restitution)`
*
* @return {Phaser.GameObjects.GameObject} This Game Object.
*/
setBounce: function (value)
{
this.body.restitution = value;
return this;
}
};
module.exports = Bounce;
| {'content_hash': '22dcb56e3d927240b81fc744b6325dda', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 503, 'avg_line_length': 34.06666666666667, 'alnum_prop': 0.6888454011741683, 'repo_name': 'TukekeSoft/phaser', 'id': 'c0b1c6bf79d5ec059375563760bdb53e6b4251ca', 'size': '1196', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/physics/matter-js/components/Bounce.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '197804'}, {'name': 'HTML', 'bytes': '164005'}, {'name': 'JavaScript', 'bytes': '12441843'}, {'name': 'PHP', 'bytes': '88137'}]} |
import os
try:
from local_settings import *
import local_settings
except ImportError:
local_settings = {}
def localor(setting_name, default_val):
"""Returns local_settings version if it exists (and is non-empty), otherwise uses default value"""
return hasattr(local_settings, setting_name) and getattr(local_settings, setting_name) or default_val
DEBUG = getattr(local_settings, "DEBUG", False)
TEMPLATE_DEBUG = getattr(local_settings, "TEMPLATE_DEBUG", DEBUG)
#retrieve Constantcontact info from local_settings
CONSTANT_CONTACT_API_KEY = getattr(local_settings, "CONSTANT_CONTACT_API_KEY", 'api-key-not-found')
CONSTANT_CONTACT_ACCESS_TOKEN = getattr(local_settings, "CONSTANT_CONTACT_ACCESS_TOKEN", 'access-token-not-found')
CONSTANT_CONTACT_API_URL = getattr(local_settings, "CONSTANT_CONTACT_API_URL", 'api-url-not-found')
CONSTANT_CONTACT_LIST_ID = getattr(local_settings, "CONSTANT_CONTACT_LIST_ID", 'list-id-not-found')
ADMINS = (
# ('Dylan', '[email protected]'),
)
MANAGERS = ADMINS
PROJECT_PATH = os.path.dirname(os.path.realpath(__file__))
# To render map, define GEOIPDAT and IPS_FILEPATH in local_settings.py ex:
# import os
# DATA_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "static/data/")
# GEOIPDAT = os.path.join(DATA_PATH, "GeoLiteCity.dat")
# IPS_FILEPATH = os.path.join(DATA_PATH, "ips.txt")
LOCATIONS_JSONP_URL = getattr(local_settings, "LOCATIONS_JSONP_URL", "https://kalite.learningequality.org/media/locations/locations.jsonp")
INDIEGOGO_API_DATA_LOCATION = getattr(local_settings, "INDIEGOGO_API_DATA_LOCATION", PROJECT_PATH)
INDIEGOGO_SUMMARY_URL = getattr(local_settings, "INDIEGOGO_SUMMARY_URL", "")
INDIEGOGO_CONTRIBUTORS_URL = getattr(local_settings, "INDIEGOGO_CONTRIBUTORS_URL", "")
DATABASES = localor("DATABASES", {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(PROJECT_PATH, '..', 'database.sqlite'), # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
})
#GEO IP Data
GEO_IP_DOWNLOAD_URL = getattr(local_settings, "GEO_IP_DOWNLOAD_URL", "http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz")
GEO_IP_DATA_PATH = getattr(local_settings, "GEO_IP_DATA_PATH", os.path.join(PROJECT_PATH, "..", "data", "GeoLiteCity.dat"))
ISO_COUNTRY_LIST_DATA_PATH = getattr(local_settings, "ISO_COUNTRY_LIST_DATA_PATH", os.path.join(PROJECT_PATH, "..", "data", "country-list-iso-codes.txt"))
INTERNAL_IPS = getattr(local_settings, "INTERNAL_IPS", ("127.0.0.1",))
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Los_Angeles'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
MEDIA_URL = getattr(local_settings, "MEDIA_URL", "/media/")
MEDIA_ROOT = os.path.realpath(getattr(local_settings, "MEDIA_ROOT", os.path.join(PROJECT_PATH, "media"))) + "/"
STATIC_URL = getattr(local_settings, "STATIC_URL", "/static/")
STATIC_ROOT = os.path.realpath(getattr(local_settings, "STATIC_ROOT",os.path.join(PROJECT_PATH, "..", "_static_cache"))) + "/"
ALLOWED_HOSTS = ["*"]
# Additional locations of static files
STATICFILES_DIRS = (
os.path.join(PROJECT_PATH, "static"),
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = getattr(local_settings, "SECRET_KEY", "@$=b3-wk2zv9oy_8dk))q_9h45pp*o=ntyh!_3bd-13p5761f%")
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'fle_site.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'fle_site.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.request',
'fle_site.apps.main.custom_context_processors.debug',
'django.contrib.messages.context_processors.messages',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.humanize',
'django_extensions',
'fack',
'south',
'file_resubmit',
'fle_site.apps.articles',
'fle_site.apps.main',
'fle_site.apps.about',
'fle_site.apps.ka_lite',
'fle_site.apps.redirects',
'ckeditor',
'ckeditor_uploader',
)
CKEDITOR_UPLOAD_PATH = '/fileupload/'
CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
CKEDITOR_CONFIGS = {
'default': {
'skin': 'moono',
# 'skin': 'office2013',
'toolbar_Basic': [
['Source', '-', 'Bold', 'Italic']
],
'toolbar_YouCustomToolbarConfig': [
{'name': 'document', 'items': ['Source']},
{'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']},
{'name': 'basicstyles',
'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']},
{'name': 'paragraph',
'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-',
'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl',
'Language']},
{'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']},
{'name': 'insert',
'items': ['Image', 'Table', 'HorizontalRule', 'SpecialChar', 'PageBreak']},
'/',
{'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
{'name': 'colors', 'items': ['TextColor', 'BGColor']},
{'name': 'tools', 'items': ['Maximize', 'ShowBlocks']},
],
'toolbar': 'YouCustomToolbarConfig', # put selected toolbar config here
'tabSpaces': 4,
'uploadUrl': CKEDITOR_UPLOAD_PATH,
'extraPlugins': ','.join(
[
# you extra plugins here
'uploadimage',
]),
}
}
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
# Django-articles settings
DISQUS_USER_API_KEY = localor("DISQUS_USER_API_KEY", "")
DISQUS_FORUM_SHORTNAME = "learningequality"
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
"file_resubmit": {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
"LOCATION": '/tmp/file_resubmit/'
},
}
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
STRIPE_SECRET_API_KEY = getattr(local_settings, "STRIPE_SECRET_API_KEY", "")
STRIPE_PUBLISHABLE_API_KEY = getattr(local_settings, "STRIPE_PUBLISHABLE_API_KEY", "")
| {'content_hash': '5de6d1ee181e6fd8151e7ca41c546b49', 'timestamp': '', 'source': 'github', 'line_count': 257, 'max_line_length': 154, 'avg_line_length': 39.38910505836576, 'alnum_prop': 0.6541539069445816, 'repo_name': 'jamalex/fle-home', 'id': '625fb09b695f92800d4dcd4b2c4fdd02a752d029', 'size': '10164', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'fle_site/settings.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '96008'}, {'name': 'HTML', 'bytes': '275356'}, {'name': 'JavaScript', 'bytes': '785058'}, {'name': 'Python', 'bytes': '280537'}, {'name': 'Shell', 'bytes': '161'}]} |
[](http://badge.fury.io/js/grunt-stylelint)
[](https://travis-ci.org/wikimedia/grunt-stylelint)
[](https://david-dm.org/wikimedia/grunt-stylelint)
[](https://david-dm.org/wikimedia/grunt-stylelint?type=dev)
[](https://www.npmjs.org/package/grunt-stylelint)
# grunt-stylelint
Grunt plugin for running [stylelint](http://stylelint.io/)
## Getting started
If this is the first time you're using [Grunt](http://gruntjs.com/), the [getting started guide](http://gruntjs.com/getting-started) will show you how to get up and running.
Once you have that installed, with a [Gruntfile](http://gruntjs.com/sample-gruntfile) set for your code, you can install the plugin with:
<pre lang=shell>
npm install grunt-stylelint --save-dev
</pre>
In your Gruntfile, add the line:
<pre lang=js>
grunt.loadNpmTasks( 'grunt-stylelint' );
</pre>
## Running and configuring `stylelint` task
_Run this task with the `grunt stylelint` command._
You can specify the targets and options for the task using the normal Grunt configuration – see Grunt's [guide on how to configure tasks](http://gruntjs.com/configuring-tasks) in general.
For more explanations of the lint errors stylelint will throw at you please visit http://stylelint.io/.
### Usage examples
#### Example simple config
In this example, running `grunt stylelint:all` (or `grunt stylelint` because `stylelint` is a [multi task](http://gruntjs.com/configuring-tasks#task-configuration-and-targets)) will lint the project's CSS and Sass files in the `css` and `sass` directories and their subdirectories, using the default stylelint options or the options specified in the `.stylelintrc` in the root of the project. For an example config see http://stylelint.io/user-guide/example-config/.
```js
// Project configuration.
grunt.initConfig({
stylelint: {
all: ['css/**/*.css', 'sass/**/*.scss']
}
});
```
#### Example full config
A full set of config with default options would be:
```js
// Project configuration.
grunt.initConfig( {
stylelint: {
options: {
configFile: '.stylelintrc',
formatter: 'string',
ignoreDisables: false,
failOnError: true,
outputFile: '',
reportNeedlessDisables: false,
syntax: ''
},
src: [
'src/**/*.{css,less,scss}',
…,
'!src/badstyles/*.css'
]
}
}
```
### Options
The `options` object is passed through to `stylelint`. Options you may wish to set are:
#### formatter
Type: `function` or `string`
Default value: `"string"`
Values: `"string"`|`"verbose"`|`"json"`
In which output format would you like results. If `grunt` is run with `--verbose` and this is not explicitly set, it will act as though you passed in `"verbose"`.
#### ignoreDisables
Type: `boolean`
Default value: `false`
Whether to ignore inline comments that disable stylelint.
#### outputFile
Type: `string`
Output the report to a file.
#### reportNeedlessDisables
Type: `boolean`
Default value: `false`
Whether to ignore inline comments that disable stylelint and report which ones did not block a lint warning.
#### failOnError
Type: `boolean`
Default value: `true`
Whether to fail if stylelint detects an error.
#### syntax
Type: `string`
Values: `"scss"`|`"less"`|`"sugarss"`
Which syntax standard should be used to parse source stylesheets. If this is unset, `stylelint` will attempt to guess which syntax is used by the files' extensions.
| {'content_hash': 'c2b05d4d3c6137c33b98d49fdddde9fa', 'timestamp': '', 'source': 'github', 'line_count': 109, 'max_line_length': 466, 'avg_line_length': 34.77064220183486, 'alnum_prop': 0.7168865435356201, 'repo_name': 'escacan/smartmirror', 'id': 'e95812ae84394937ba6f11c885bc3a3e8387ad99', 'size': '3794', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'node_modules/grunt-stylelint/README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '77474'}, {'name': 'HTML', 'bytes': '3850'}, {'name': 'JavaScript', 'bytes': '199606'}, {'name': 'Shell', 'bytes': '6965'}]} |
package ingvar.android.literepo.builder;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Operators constants.
*
* Created by Igor Zubenko on 2015.03.25.
*/
public enum Operator {
EQUALS("eq", "="),
GREATER_THAN("gt", ">"),
GREATER_THAN_OR_EQUALS("gte", ">="),
LOWER_THAN("lt", "<"),
LOWER_THAN_OR_EQUALS("lte", "<="),
LIKE("lk", "like"),
MATCH("mh", "match"),
IN("in", "in"),
NOT_IN("nin", "not in"),
BETWEEN("bn", "between"),
IS_NULL("isn", "is null"),
IS_NOT_NULL("isnn", "is not null");
/**
* Collection of list operators. Like as 'IN'
*/
public static final List<Operator> LIST_OPERATORS = Collections.unmodifiableList(Arrays.asList(IN, NOT_IN));
/**
* Get operator by Uri representation.
*
* @param operator uri operator
* @return {@link ingvar.android.literepo.builder.Operator}
*/
public static Operator fromUri(String operator) {
for(Operator o : values()) {
if(o.toUri().equals(operator)) {
return o;
}
}
throw new IllegalArgumentException("Unknown operator: " + operator);
}
/**
* Get operator by SQL representation.
*
* @param operator sql operator
* @return {@link ingvar.android.literepo.builder.Operator}
*/
public static Operator fromSql(String operator) {
for(Operator o : values()) {
if(o.toSql().equals(operator)) {
return o;
}
}
throw new IllegalArgumentException("Unknown operator: " + operator);
}
private String uri;
private String sql;
Operator(String uri, String sql) {
this.uri = uri;
this.sql = sql;
}
/**
* Get operator for Uri.
*
* @return operator
*/
public String toUri() {
return uri;
}
/**
* Get operator for SQL.
*
* @return operator
*/
public String toSql() {
return sql;
}
}
| {'content_hash': '6fc65d5175cbc56418c0fe2e91f7957d', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 112, 'avg_line_length': 23.193181818181817, 'alnum_prop': 0.554140127388535, 'repo_name': 'deadly-cat/literepo', 'id': '7834ccaf5a1bba88a276027c6f64c71f02da61b6', 'size': '2041', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/ingvar/android/literepo/builder/Operator.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '70119'}]} |
/*
* Do not modify this file. This file is generated from the kinesis-2013-12-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Kinesis.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Kinesis.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for StreamDescription Object
/// </summary>
public class StreamDescriptionUnmarshaller : IUnmarshaller<StreamDescription, XmlUnmarshallerContext>, IUnmarshaller<StreamDescription, JsonUnmarshallerContext>
{
StreamDescription IUnmarshaller<StreamDescription, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
public StreamDescription Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
StreamDescription unmarshalledObject = new StreamDescription();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("HasMoreShards", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.HasMoreShards = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Shards", targetDepth))
{
var unmarshaller = new ListUnmarshaller<Shard, ShardUnmarshaller>(ShardUnmarshaller.Instance);
unmarshalledObject.Shards = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("StreamARN", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.StreamARN = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("StreamName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.StreamName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("StreamStatus", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.StreamStatus = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static StreamDescriptionUnmarshaller _instance = new StreamDescriptionUnmarshaller();
public static StreamDescriptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | {'content_hash': '8444834419708016d2a6ae00196136a0', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 164, 'avg_line_length': 36.24444444444445, 'alnum_prop': 0.6066830165542612, 'repo_name': 'ykbarros/aws-sdk-xamarin', 'id': '868412983aff644971e231a1a3494e4d347e2daf', 'size': '3849', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'AWS.XamarinSDK/AWSSDK_Android/Amazon.Kinesis/Model/Internal/MarshallTransformations/StreamDescriptionUnmarshaller.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '70640975'}, {'name': 'PowerShell', 'bytes': '3661'}]} |
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner:
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner:
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
SET search_path = public, pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: authorities; Type: TABLE; Schema: public; Owner: panya; Tablespace:
--
CREATE TABLE authorities (
id bigint NOT NULL,
authority character varying(32) NOT NULL,
username character varying(32) NOT NULL
);
ALTER TABLE authorities OWNER TO panya;
--
-- Name: buyer_profile; Type: TABLE; Schema: public; Owner: panya; Tablespace:
--
CREATE TABLE buyer_profile (
buyer_id bigint NOT NULL,
buyer_primary_contact character varying(10) NOT NULL,
buyer_secondary_contact character varying(10) NOT NULL,
created_by character varying(32) NOT NULL,
delivery_address character varying(256) NOT NULL,
modified_by character varying(32),
registered_shops character varying(1024) NOT NULL,
created_date timestamp without time zone NOT NULL,
modified_date timestamp without time zone
);
ALTER TABLE buyer_profile OWNER TO panya;
--
-- Name: cart; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
--
CREATE TABLE cart (
cart_id bigint NOT NULL,
item_id bigint NOT NULL,
shop_id bigint NOT NULL,
created_by character varying(32) NOT NULL,
modified_by character varying(32),
created_date timestamp without time zone NOT NULL,
modified_date timestamp without time zone
);
ALTER TABLE cart OWNER TO postgres;
--
-- Name: discount; Type: TABLE; Schema: public; Owner: postgres; Tablespace:
--
CREATE TABLE discount (
discount_id bigint NOT NULL,
discount integer NOT NULL,
discount_expiry timestamp without time zone NOT NULL,
discount_name character varying(32) NOT NULL,
discount_start timestamp without time zone NOT NULL,
discount_type integer NOT NULL,
created_by character varying(32) NOT NULL,
modified_by character varying(32),
created_date timestamp without time zone NOT NULL,
modified_date timestamp without time zone
);
ALTER TABLE discount OWNER TO postgres;
--
-- Name: item; Type: TABLE; Schema: public; Owner: panya; Tablespace:
--
CREATE TABLE item (
item_id bigint NOT NULL,
shop_id bigint NOT NULL,
created_by character varying(32) NOT NULL,
discount_id bigint,
item_brand character varying(32),
item_desc character varying(64),
item_name character varying(32) NOT NULL,
item_price integer NOT NULL,
item_unit character varying(16),
modified_by character varying(32),
created_date timestamp without time zone NOT NULL,
modified_date timestamp without time zone
);
ALTER TABLE item OWNER TO panya;
--
-- Name: order_item; Type: TABLE; Schema: public; Owner: panya; Tablespace:
--
CREATE TABLE order_item (
item_id bigint NOT NULL,
oder_id bigint NOT NULL,
created_by character varying(32) NOT NULL,
discounted_item_price bigint NOT NULL,
modified_by character varying(32),
created_date timestamp without time zone NOT NULL,
modified_date timestamp without time zone
);
ALTER TABLE order_item OWNER TO panya;
--
-- Name: orders; Type: TABLE; Schema: public; Owner: panya; Tablespace:
--
CREATE TABLE orders (
order_id bigint NOT NULL,
buyer_id bigint NOT NULL,
created_by character varying(32) NOT NULL,
modified_by character varying(32),
oder_status character varying(32) NOT NULL,
shop_id bigint NOT NULL,
total_price bigint NOT NULL,
created_date timestamp without time zone NOT NULL,
modified_date timestamp without time zone
);
ALTER TABLE orders OWNER TO panya;
--
-- Name: shop_feedback; Type: TABLE; Schema: public; Owner: panya; Tablespace:
--
CREATE TABLE shop_feedback (
buyer_id bigint NOT NULL,
shop_id bigint NOT NULL,
created_by character varying(32) NOT NULL,
modified_by character varying(32),
shop_comments character varying(1024),
shop_ratings integer NOT NULL,
created_date timestamp without time zone NOT NULL,
modified_date timestamp without time zone
);
ALTER TABLE shop_feedback OWNER TO panya;
--
-- Name: shopkeeper_profile; Type: TABLE; Schema: public; Owner: panya; Tablespace:
--
CREATE TABLE shopkeeper_profile (
shop_id bigint NOT NULL,
created_by character varying(32) NOT NULL,
modified_by character varying(32),
shop_address character varying(256) NOT NULL,
shop_city character varying(32) NOT NULL,
shop_close_time timestamp without time zone,
shop_coordinates_lat double precision,
shop_coordinates_long double precision,
shop_desc character varying(1024),
shop_image character varying(32),
shop_open_time timestamp without time zone,
shop_pan character varying(32),
shop_primary_contact character varying(10) NOT NULL,
shop_product_tags character varying(1024),
shop_secondary_contact character varying(10),
shop_state character varying(32) NOT NULL,
shop_tin character varying(32),
created_date timestamp without time zone NOT NULL,
modified_date timestamp without time zone
);
ALTER TABLE shopkeeper_profile OWNER TO panya;
--
-- Name: users; Type: TABLE; Schema: public; Owner: panya; Tablespace:
--
CREATE TABLE users (
user_id bigint NOT NULL,
created_by character varying(32) NOT NULL,
first_name character varying(64) NOT NULL,
last_name character varying(64),
mail_id character varying(64) NOT NULL,
modified_by character varying(32),
password character varying(64) NOT NULL,
type integer NOT NULL,
username character varying(32) NOT NULL,
enabled boolean DEFAULT true NOT NULL,
created_date timestamp without time zone NOT NULL,
modified_date timestamp without time zone
);
ALTER TABLE users OWNER TO panya;
--
-- Name: buyer_profile_pkey; Type: CONSTRAINT; Schema: public; Owner: panya; Tablespace:
--
ALTER TABLE ONLY buyer_profile
ADD CONSTRAINT buyer_profile_pkey PRIMARY KEY (buyer_id);
--
-- Name: cart_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
--
ALTER TABLE ONLY cart
ADD CONSTRAINT cart_pkey PRIMARY KEY (cart_id, item_id, shop_id);
--
-- Name: discount_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
--
ALTER TABLE ONLY discount
ADD CONSTRAINT discount_pkey PRIMARY KEY (discount_id);
--
-- Name: item_pkey; Type: CONSTRAINT; Schema: public; Owner: panya; Tablespace:
--
ALTER TABLE ONLY item
ADD CONSTRAINT item_pkey PRIMARY KEY (item_id, shop_id);
--
-- Name: order_item_pkey; Type: CONSTRAINT; Schema: public; Owner: panya; Tablespace:
--
ALTER TABLE ONLY order_item
ADD CONSTRAINT order_item_pkey PRIMARY KEY (item_id, oder_id);
--
-- Name: order_pkey; Type: CONSTRAINT; Schema: public; Owner: panya; Tablespace:
--
ALTER TABLE ONLY orders
ADD CONSTRAINT order_pkey PRIMARY KEY (order_id);
--
-- Name: shop_feedback_pkey; Type: CONSTRAINT; Schema: public; Owner: panya; Tablespace:
--
ALTER TABLE ONLY shop_feedback
ADD CONSTRAINT shop_feedback_pkey PRIMARY KEY (buyer_id, shop_id);
--
-- Name: shopkeeper_profile_pkey; Type: CONSTRAINT; Schema: public; Owner: panya; Tablespace:
--
ALTER TABLE ONLY shopkeeper_profile
ADD CONSTRAINT shopkeeper_profile_pkey PRIMARY KEY (shop_id);
--
-- Name: uk_8dxvvhpnxj565wsvijnu8lusp; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace:
--
ALTER TABLE ONLY discount
ADD CONSTRAINT uk_8dxvvhpnxj565wsvijnu8lusp UNIQUE (discount_name);
--
-- Name: user_pkey; Type: CONSTRAINT; Schema: public; Owner: panya; Tablespace:
--
ALTER TABLE ONLY users
ADD CONSTRAINT user_pkey PRIMARY KEY (user_id);
--
-- Name: user_role_pk_key; Type: CONSTRAINT; Schema: public; Owner: panya; Tablespace:
--
ALTER TABLE ONLY authorities
ADD CONSTRAINT user_role_pk_key PRIMARY KEY (id);
--
-- Name: users_roles_unique_key; Type: CONSTRAINT; Schema: public; Owner: panya; Tablespace:
--
ALTER TABLE ONLY authorities
ADD CONSTRAINT users_roles_unique_key UNIQUE (username, authority);
--
-- Name: users_unique_key; Type: CONSTRAINT; Schema: public; Owner: panya; Tablespace:
--
ALTER TABLE ONLY users
ADD CONSTRAINT users_unique_key UNIQUE (username);
--
-- Name: buyer_order_fk_key; Type: FK CONSTRAINT; Schema: public; Owner: panya
--
ALTER TABLE ONLY orders
ADD CONSTRAINT buyer_order_fk_key FOREIGN KEY (buyer_id) REFERENCES buyer_profile(buyer_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: buyer_this_fk_key; Type: FK CONSTRAINT; Schema: public; Owner: panya
--
ALTER TABLE ONLY shop_feedback
ADD CONSTRAINT buyer_this_fk_key FOREIGN KEY (buyer_id) REFERENCES buyer_profile(buyer_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: discount_item_fk_key; Type: FK CONSTRAINT; Schema: public; Owner: panya
--
ALTER TABLE ONLY item
ADD CONSTRAINT discount_item_fk_key FOREIGN KEY (discount_id) REFERENCES discount(discount_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: item_cart_fk_key; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY cart
ADD CONSTRAINT item_cart_fk_key FOREIGN KEY (item_id, shop_id) REFERENCES item(item_id, shop_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: order_this_fk_key; Type: FK CONSTRAINT; Schema: public; Owner: panya
--
ALTER TABLE ONLY order_item
ADD CONSTRAINT order_this_fk_key FOREIGN KEY (oder_id) REFERENCES orders(order_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: shop_item_fk_key; Type: FK CONSTRAINT; Schema: public; Owner: panya
--
ALTER TABLE ONLY item
ADD CONSTRAINT shop_item_fk_key FOREIGN KEY (shop_id) REFERENCES shopkeeper_profile(shop_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: shop_order_fk_key; Type: FK CONSTRAINT; Schema: public; Owner: panya
--
ALTER TABLE ONLY orders
ADD CONSTRAINT shop_order_fk_key FOREIGN KEY (shop_id) REFERENCES shopkeeper_profile(shop_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: shop_this_fk_key; Type: FK CONSTRAINT; Schema: public; Owner: panya
--
ALTER TABLE ONLY shop_feedback
ADD CONSTRAINT shop_this_fk_key FOREIGN KEY (shop_id) REFERENCES shopkeeper_profile(shop_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: user_buyer_fk_key; Type: FK CONSTRAINT; Schema: public; Owner: panya
--
ALTER TABLE ONLY buyer_profile
ADD CONSTRAINT user_buyer_fk_key FOREIGN KEY (buyer_id) REFERENCES users(user_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: user_shopkeeper_fk_key; Type: FK CONSTRAINT; Schema: public; Owner: panya
--
ALTER TABLE ONLY shopkeeper_profile
ADD CONSTRAINT user_shopkeeper_fk_key FOREIGN KEY (shop_id) REFERENCES users(user_id) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: users_roles_fk_key; Type: FK CONSTRAINT; Schema: public; Owner: panya
--
ALTER TABLE ONLY authorities
ADD CONSTRAINT users_roles_fk_key FOREIGN KEY (username) REFERENCES users(username) ON UPDATE CASCADE ON DELETE CASCADE;
--
-- Name: public; Type: ACL; Schema: -; Owner: panya
--
REVOKE ALL ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON SCHEMA public FROM panya;
GRANT ALL ON SCHEMA public TO panya;
GRANT ALL ON SCHEMA public TO PUBLIC;
--
-- PostgreSQL database dump complete
--
| {'content_hash': '28e94aa130e3b595d8a56670a6571027', 'timestamp': '', 'source': 'github', 'line_count': 429, 'max_line_length': 137, 'avg_line_length': 26.93240093240093, 'alnum_prop': 0.7222606889388956, 'repo_name': 'xrohit/panya', 'id': '3e28d5a19c97b1b7a68e7b79a8263c882b163c11', 'size': '11589', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Scripts/panya_db_schema.sql', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '5006'}, {'name': 'CSS', 'bytes': '272607'}, {'name': 'HTML', 'bytes': '258649'}, {'name': 'Java', 'bytes': '142461'}, {'name': 'JavaScript', 'bytes': '2207690'}, {'name': 'PHP', 'bytes': '742'}, {'name': 'Shell', 'bytes': '7058'}]} |
import decorate from '../../lib/decorate';
import { memoize } from 'lodash';
describe('@decorate', function () {
let Foo;
let callCount;
beforeEach(function () {
const append = function (fn, suffix) {
return function (msg) {
return fn.call(this, msg) + suffix;
};
};
callCount = 0;
Foo = class Foo {
@decorate(append, '!')
suchWow(something) {
return something + 'bro';
}
@decorate(append, '!')
@decorate(append, '!')
suchWowTwice(something) {
return something + 'bro';
}
@decorate(append, '!')
@decorate(append, '!')
@decorate(append, '!')
suchWowThrice(something) {
return something + 'bro';
}
@decorate(memoize)
getFoo() {
callCount++;
return this;
}
}
});
it('correctly applies user provided function to method', function () {
const foo = new Foo();
foo.suchWow('dude').should.equal('dudebro!');
foo.suchWowTwice('dude').should.equal('dudebro!!');
foo.suchWowThrice('dude').should.equal('dudebro!!!');
});
it('sets the correct prototype descriptor options', function () {
const desc = Object.getOwnPropertyDescriptor(Foo.prototype, 'suchWow');
desc.configurable.should.equal(true);
desc.enumerable.should.equal(false);
});
it('is tied to the instance, not the prototype', function () {
const foo1 = new Foo();
const foo2 = new Foo();
const foo1Result = foo1.getFoo();
const foo2Result = foo2.getFoo();
foo1Result.should.not.equal(foo2Result);
foo1Result.should.equal(foo1);
foo2Result.should.equal(foo2);
foo1.getFoo();
callCount.should.equal(2);
});
});
| {'content_hash': '601d4d4af3e53b07057c41c15e91af3b', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 75, 'avg_line_length': 23.364864864864863, 'alnum_prop': 0.5910931174089069, 'repo_name': 'jayphelps/core-decorators', 'id': 'dfa9f54fb8b8a6b07dd672db01a534a3c8094f91', 'size': '1729', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'test/unit/decorate.spec.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '66295'}, {'name': 'TypeScript', 'bytes': '85'}]} |
npm i --save @angular-mdl/popover @angular-mdl/select
import { MdlSelectModule } from '@angular-mdl/select';
If you need to support IE11 please add https://www.npmjs.com/package/custom-event-polyfill
to your polyfills.
### Usage example
```js
<mdl-select [(ngModel)]="personId">
<mdl-option *ngFor="let p of people" [value]="p.id">{{p.name}}</mdl-option>
</mdl-select>
```
#### using placeholder
```js
<mdl-select placeholder="Person Name" [(ngModel)]="personId">
<mdl-option *ngFor="let p of people" [value]="p.id">{{p.name}}</mdl-option>
</mdl-select>
```
#### using label with floating label
```js
<mdl-select label="{{personLabel}}" floating-label [(ngModel)]="personId">
<mdl-option *ngFor="let p of people" [value]="p.id">{{p.name}}</mdl-option>
</mdl-select>
```
### API Summary
#### mdl-select
| Name | Type | Description |
| --- | --- | --- |
| `[ngModel]` | any | Select data binding
| `[disabled]` | boolean | Whether or not the select is disabled
| `[placeholder]` | string | Placeholder text
| `[label]` | string | Label text
| `[floating-label]` | any | If present or true the ```label``` will be floating on ```focus``` event
| `[multiple]` | boolean | Multiselect mode
| `[autocomplete]` | boolean | Autocomplete mode
| `(blur)` | ... | on blur event
| `(change)` | ... | on change event
#### mdl-option
| Name | Type | Description |
| --- | --- | --- |
| `[value]` | any | Option value
| `[disabled]` | boolean | Whether or not the option is disabled
| `<content>` | string | Option label
| {'content_hash': '951417ba20e4ef1eb1c86ad187288e51', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 101, 'avg_line_length': 30.11764705882353, 'alnum_prop': 0.6302083333333334, 'repo_name': 'mseemann/angular2-mdl', 'id': 'd5a832eb18a65691ec69dd76b6289134a2159367', 'size': '1562', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'projects/select/README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2313'}, {'name': 'HTML', 'bytes': '158438'}, {'name': 'JavaScript', 'bytes': '9010'}, {'name': 'SCSS', 'bytes': '246279'}, {'name': 'Shell', 'bytes': '6591'}, {'name': 'TypeScript', 'bytes': '560479'}]} |
<?php
/**
* Category edit block
*
* @category Mage
* @package Mage_Adminhtml
* @author Magento Core Team <[email protected]>
*/
class Mage_Adminhtml_Block_Catalog_Category_Edit_Form extends Mage_Adminhtml_Block_Catalog_Category_Abstract
{
/**
* Additional buttons on category page
*
* @var array
*/
protected $_additionalButtons = array();
public function __construct()
{
parent::__construct();
$this->setTemplate('catalog/category/edit/form.phtml');
}
protected function _prepareLayout()
{
$category = $this->getCategory();
$categoryId = (int) $category->getId(); // 0 when we create category, otherwise some value for editing category
$this->setChild('tabs',
$this->getLayout()->createBlock('adminhtml/catalog_category_tabs', 'tabs')
);
// Save button
if (!$category->isReadonly()) {
$this->setChild('save_button',
$this->getLayout()->createBlock('adminhtml/widget_button')
->setData(array(
'label' => Mage::helper('catalog')->__('Save Category'),
'onclick' => "categorySubmit('" . $this->getSaveUrl() . "', true)",
'class' => 'save'
))
);
}
// Delete button
if (!in_array($categoryId, $this->getRootIds()) && $category->isDeleteable()) {
$this->setChild('delete_button',
$this->getLayout()->createBlock('adminhtml/widget_button')
->setData(array(
'label' => Mage::helper('catalog')->__('Delete Category'),
'onclick' => "categoryDelete('" . $this->getUrl('*/*/delete', array('_current' => true)) . "', true, {$categoryId})",
'class' => 'delete'
))
);
}
// Reset button
if (!$category->isReadonly()) {
$resetPath = $categoryId ? '*/*/edit' : '*/*/add';
$this->setChild('reset_button',
$this->getLayout()->createBlock('adminhtml/widget_button')
->setData(array(
'label' => Mage::helper('catalog')->__('Reset'),
'onclick' => "categoryReset('".$this->getUrl($resetPath, array('_current'=>true))."',true)"
))
);
}
return parent::_prepareLayout();
}
public function getStoreConfigurationUrl()
{
$storeId = (int) $this->getRequest()->getParam('store');
$params = array();
// $params = array('section'=>'catalog');
if ($storeId) {
$store = Mage::app()->getStore($storeId);
$params['website'] = $store->getWebsite()->getCode();
$params['store'] = $store->getCode();
}
return $this->getUrl('*/system_store', $params);
}
public function getDeleteButtonHtml()
{
return $this->getChildHtml('delete_button');
}
public function getSaveButtonHtml()
{
if ($this->hasStoreRootCategory()) {
return $this->getChildHtml('save_button');
}
return '';
}
public function getResetButtonHtml()
{
if ($this->hasStoreRootCategory()) {
return $this->getChildHtml('reset_button');
}
return '';
}
/**
* Retrieve additional buttons html
*
* @return string
*/
public function getAdditionalButtonsHtml()
{
$html = '';
foreach ($this->_additionalButtons as $childName) {
$html .= $this->getChildHtml($childName);
}
return $html;
}
/**
* Add additional button
*
* @param string $alias
* @param array $config
* @return Mage_Adminhtml_Block_Catalog_Category_Edit_Form
*/
public function addAdditionalButton($alias, $config)
{
if (isset($config['name'])) {
$config['element_name'] = $config['name'];
}
$this->setChild($alias . '_button',
$this->getLayout()->createBlock('adminhtml/widget_button')->addData($config));
$this->_additionalButtons[$alias] = $alias . '_button';
return $this;
}
/**
* Remove additional button
*
* @param string $alias
* @return Mage_Adminhtml_Block_Catalog_Category_Edit_Form
*/
public function removeAdditionalButton($alias)
{
if (isset($this->_additionalButtons[$alias])) {
$this->unsetChild($this->_additionalButtons[$alias]);
unset($this->_additionalButtons[$alias]);
}
return $this;
}
public function getTabsHtml()
{
return $this->getChildHtml('tabs');
}
public function getHeader()
{
if ($this->hasStoreRootCategory()) {
if ($this->getCategoryId()) {
return $this->getCategoryName();
} else {
$parentId = (int) $this->getRequest()->getParam('parent');
if ($parentId && ($parentId != Mage_Catalog_Model_Category::TREE_ROOT_ID)) {
return Mage::helper('catalog')->__('New Subcategory');
} else {
return Mage::helper('catalog')->__('New Root Category');
}
}
}
return Mage::helper('catalog')->__('Set Root Category for Store');
}
public function getDeleteUrl(array $args = array())
{
$params = array('_current'=>true);
$params = array_merge($params, $args);
return $this->getUrl('*/*/delete', $params);
}
/**
* Return URL for refresh input element 'path' in form
*
* @param array $args
* @return string
*/
public function getRefreshPathUrl(array $args = array())
{
$params = array('_current'=>true);
$params = array_merge($params, $args);
return $this->getUrl('*/*/refreshPath', $params);
}
public function getProductsJson()
{
$products = $this->getCategory()->getProductsPosition();
if (!empty($products)) {
return Mage::helper('core')->jsonEncode($products);
}
return '{}';
}
public function isAjax()
{
return Mage::app()->getRequest()->isXmlHttpRequest() || Mage::app()->getRequest()->getParam('isAjax');
}
}
| {'content_hash': 'f86c8932ebf4971384047e027e9030a9', 'timestamp': '', 'source': 'github', 'line_count': 211, 'max_line_length': 143, 'avg_line_length': 30.781990521327014, 'alnum_prop': 0.5160892994611239, 'repo_name': 'mikrotikAhmet/mbe-cpdev', 'id': 'e540e047f5d91ab663ce9c6af1b9663fed676318', 'size': '7436', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'app/code/core/Mage/Adminhtml/Block/Catalog/Category/Edit/Form.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '19946'}, {'name': 'ApacheConf', 'bytes': '1148'}, {'name': 'Batchfile', 'bytes': '1036'}, {'name': 'C', 'bytes': '653'}, {'name': 'CSS', 'bytes': '2469504'}, {'name': 'HTML', 'bytes': '6706314'}, {'name': 'JavaScript', 'bytes': '1271689'}, {'name': 'PHP', 'bytes': '50903014'}, {'name': 'Perl', 'bytes': '30260'}, {'name': 'PowerShell', 'bytes': '1028'}, {'name': 'Ruby', 'bytes': '288'}, {'name': 'Shell', 'bytes': '11651'}, {'name': 'XSLT', 'bytes': '2135'}]} |
A simple Qt GameOfLife

## Compilation
To compile and execute this code you will need Qt Creator.
| {'content_hash': '13ea5fa701d768dbb4355ccbc2afd425', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 77, 'avg_line_length': 29.5, 'alnum_prop': 0.7627118644067796, 'repo_name': 'Bastnt/GameOfLife', 'id': 'f40216f2a777524b95330268a7dfdb04f7331402', 'size': '190', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '13667'}, {'name': 'QMake', 'bytes': '432'}]} |
/**
* OSGi-wrapper for raw JARs.
*/
package org.onlab.osgiwrap;
| {'content_hash': '50de272ac5a81fcb000f687c655e7477', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 29, 'avg_line_length': 11.333333333333334, 'alnum_prop': 0.6470588235294118, 'repo_name': 'mengmoya/onos', 'id': 'b38786e4181dcd6fb1297d856b01102ec13fe97f', 'size': '685', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'utils/osgiwrap/src/main/java/org/onlab/osgiwrap/package-info.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '72456'}, {'name': 'CSS', 'bytes': '192215'}, {'name': 'Groff', 'bytes': '1090'}, {'name': 'HTML', 'bytes': '171950'}, {'name': 'Java', 'bytes': '26076670'}, {'name': 'JavaScript', 'bytes': '3064155'}, {'name': 'Protocol Buffer', 'bytes': '7499'}, {'name': 'Python', 'bytes': '118808'}, {'name': 'Shell', 'bytes': '913'}]} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template thread_access_mode_of<upgrade_lock< MutexT >></title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="../../utilities.html#header.boost.log.utility.strictest_lock_hpp" title="Header <boost/log/utility/strictest_lock.hpp>">
<link rel="prev" href="thread_access__idp46909040.html" title="Struct template thread_access_mode_of<unique_lock< MutexT >>">
<link rel="next" href="operator_idp46920064.html" title="Function template operator<<">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="thread_access__idp46909040.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../utilities.html#header.boost.log.utility.strictest_lock_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="operator_idp46920064.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.log.thread_access__idp46911296"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template thread_access_mode_of<upgrade_lock< MutexT >></span></h2>
<p>boost::log::thread_access_mode_of<upgrade_lock< MutexT >></p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../utilities.html#header.boost.log.utility.strictest_lock_hpp" title="Header <boost/log/utility/strictest_lock.hpp>">boost/log/utility/strictest_lock.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> MutexT<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="thread_access__idp46911296.html" title="Struct template thread_access_mode_of<upgrade_lock< MutexT >>">thread_access_mode_of</a><span class="special"><</span><span class="identifier">upgrade_lock</span><span class="special"><</span> <span class="identifier">MutexT</span> <span class="special">></span><span class="special">></span> <span class="special">:</span>
<span class="keyword">public</span> <span class="identifier">mpl</span><span class="special">::</span><span class="identifier">integral_c</span><span class="special"><</span> <span class="identifier">lock_access_mode</span><span class="special">,</span> <span class="identifier">shared_access</span> <span class="special">></span>
<span class="special">{</span>
<span class="special">}</span><span class="special">;</span></pre></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2007-2015 Andrey
Semashev<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>).
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="thread_access__idp46909040.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../utilities.html#header.boost.log.utility.strictest_lock_hpp"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="operator_idp46920064.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {'content_hash': '1a1bf942d235f7e98cc055518cc8bc1a', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 504, 'avg_line_length': 95.23404255319149, 'alnum_prop': 0.670017873100983, 'repo_name': 'babycaseny/poedit', 'id': '22f90df634eac5285dd4d9d7e6fe0f86489d513a', 'size': '4476', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'deps/boost/libs/log/doc/html/boost/log/thread_access__idp46911296.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '22780'}, {'name': 'C++', 'bytes': '874973'}, {'name': 'Inno Setup', 'bytes': '10822'}, {'name': 'Objective-C', 'bytes': '4458'}, {'name': 'Objective-C++', 'bytes': '12149'}, {'name': 'Python', 'bytes': '3040'}, {'name': 'Ruby', 'bytes': '220'}, {'name': 'Shell', 'bytes': '10374'}]} |
using org.apache.tika;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using TikaOnDotNet.TextExtraction;
namespace FileIndexer
{
/// <summary>
/// This sample program reads the contents of your "My Documents" folder and looks for doc, docx, and pdf files
/// that are less than 100 MB in size; it then extracts the text and metadata from the files using the Tika library
/// (https://kevm.github.io/tikaondotnet), and then sends all these data (as JSON) to a running ExpandoDB server instance.
/// <para>
/// The Tika library supports lots of other file types - it would be easy to modify this sample to implement
/// a file crawler that periodically scans your "My Documents" folder to index its contents.
/// </para>
/// <para>
/// Once the documents are indexed, you can go to http://localhost:9000/db/documents and query the documents collection
/// like so:
/// <![CDATA[
/// http://localhost:9000/db/documents?select=FilePath,CreatedDate&where="machine learning"^4 AND "logistic regression"&highlight=true
/// ]]>
/// </para>
/// </summary>
static class Program
{
const string EXPANDO_DB_URL = "http://localhost:9000/db";
const int ONE_MB = 1 * 1024 * 1024;
const int TEN_MB = 10 * 1024 * 1024;
const int TWENTY_MB = 20 * 1024 * 1024;
const int THIRTY_MB = 30 * 1024 * 1024;
const int FORTY_MB = 40 * 1024 * 1024;
const int FIFTY_MB = 50 * 1024 * 1024;
static readonly TextExtractor _textExtractor = new TextExtractor();
static int _processedCount = 0;
static void Main(string[] args)
{
var startFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (args.Length > 0)
startFolder = args[0];
if (!Directory.Exists(startFolder))
throw new InvalidOperationException($"Start folder does not exist: {startFolder}");
var filterMasks = new[] { "*.doc", "*.docx", "*.pdf", "*.ppt", "*.pptx" };
Func<FileInfo, bool> fileCheck = fi => fi.Length <= FIFTY_MB; // File size less than 50 MB
Console.WriteLine("-----------------------------------------------------------------------------------");
Console.WriteLine($"FileIndexer starting at: {startFolder}");
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
var stopwatch = new Stopwatch();
stopwatch.Start();
var batchSize = 4; //Environment.ProcessorCount;
var allDocumentFiles = GetFiles(startFolder, filterMasks, fileCheck);
var fileTheadMap = new Dictionary<FileInfo, Thread>();
var threadCompletedSignals = new ManualResetEvent[batchSize];
for (var i = 0; i < batchSize; i++)
threadCompletedSignals[i] = new ManualResetEvent(false);
foreach (var batch in allDocumentFiles.InSetsOf(batchSize))
{
fileTheadMap.Clear();
for (var i = 0; i < batchSize; i++)
threadCompletedSignals[i].Reset();
var filesInBatch = batch.ToList();
for (var i = 0; i < filesInBatch.Count; i++)
{
var file = filesInBatch[i];
var mre = threadCompletedSignals[i];
var thread = new Thread(new ParameterizedThreadStart(ProcessFile)) { IsBackground = true, Priority = ThreadPriority.BelowNormal };
fileTheadMap.Add(file, thread);
thread.Start(new Tuple<FileInfo, ManualResetEvent>(file, mre));
}
WaitHandle.WaitAll(threadCompletedSignals, TimeSpan.FromSeconds(30), false);
foreach (var file in fileTheadMap.Keys)
{
var thread = fileTheadMap[file];
if (thread.ThreadState == System.Threading.ThreadState.Running)
{
thread.Abort();
Console.WriteLine($"Processing of {file.FullName} was cancelled because it took more than 30 secs.");
}
}
GC.Collect();
}
stopwatch.Stop();
for (var i = 0; i < batchSize; i++)
threadCompletedSignals[i].Dispose();
Console.WriteLine("-----------------------------------------------------------------------------------");
Console.WriteLine($"Processed {_processedCount} {String.Join(",", filterMasks)} files in {stopwatch.Elapsed}");
Console.WriteLine($"Peak working set: {Process.GetCurrentProcess().PeakWorkingSet64} bytes");
Console.WriteLine("\n\nPRESS ENTER TO EXIT");
Console.ReadLine();
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine(e.ToString());
}
static void ProcessFile(object args)
{
var data = args as Tuple<FileInfo, ManualResetEvent>;
if (data == null)
return;
var file = data.Item1;
var mre = data.Item2;
Console.WriteLine($"Processing '{file}'.");
try
{
// Lets create our document object
dynamic document = new ExpandoObject();
document.FilePath = file.FullName;
document.Size = file.Length;
document.CreatedDate = file.CreationTimeUtc;
document.LastModifiedDate = file.LastWriteTimeUtc;
// Now let's extract the text from the file.
var result = _textExtractor.Extract(file.FullName);
var text = result.Text;
var metadata = result.Metadata;
var contentType = result.ContentType;
var sizeCategory = "";
if (file.Length < ONE_MB)
sizeCategory = "Less than 1 MB";
else if (file.Length >= ONE_MB && file.Length < TEN_MB)
sizeCategory = "Between 1 MB to 10 MB";
else if (file.Length >= TEN_MB && file.Length < TWENTY_MB)
sizeCategory = "Between 10 MB to 20 MB";
else if (file.Length >= TWENTY_MB && file.Length < THIRTY_MB)
sizeCategory = "Between 20 MB to 30 MB";
else if (file.Length >= THIRTY_MB && file.Length < FORTY_MB)
sizeCategory = "Between 30 MB to 40 MB";
else if (file.Length >= FORTY_MB && file.Length <= FIFTY_MB)
sizeCategory = "Between 40 MB to 50 MB";
// We need to escape any forward slash because '/' is used as a separator in category strings.
var contentTypeCategory = contentType.Replace(@"/", @"\/");
var dateFormat = "yyyy/MMM/dd";
var categories = new List<string>
{
$"File Size:{sizeCategory}",
// The Last Modified Date category is a hierarchical one -> e.g. "Last Modified Date:2013/Apr/26"
// Users can 'drill-down' ('drill-sideways') to this category.
$"Last Modified Date:{file.LastWriteTimeUtc.ToString(dateFormat)}",
$"Content Type:{contentTypeCategory}"
};
foreach (var key in metadata.Keys.Where(k => !String.IsNullOrWhiteSpace(k)))
{
var fieldName = key.ToLowerInvariant().Trim();
if (fieldName != "author" &&
fieldName != "authors" &&
fieldName != "title")
continue;
var authorOrTitle = metadata[key];
if (String.IsNullOrWhiteSpace(authorOrTitle))
continue;
// Make sure the author or title value is not a Date/Time string
if (IsMaybeDateTime(authorOrTitle))
{
Console.WriteLine($"Invalid author or title metadata value: {authorOrTitle}");
continue;
}
authorOrTitle = authorOrTitle.Trim();
switch (fieldName)
{
case "author":
case "authors":
document.Author = authorOrTitle;
categories.Add($"Author:{authorOrTitle.Replace(@"/", @"\/")}");
break;
case "title":
document.Title = authorOrTitle;
break;
}
}
document.Text = text;
document.ContentType = contentType;
document._categories = categories;
// Now lets submit the document to ExpandoDB via the REST API
var request = new RestRequest("/documents", Method.POST) { DateFormat = DateFormat.ISO_8601 };
request.AddJsonBody(document);
var restClient = new RestClient(EXPANDO_DB_URL);
var response = restClient.Post(request);
response.Validate();
Interlocked.Increment(ref _processedCount);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
finally
{
mre.Set();
}
}
static IEnumerable<FileInfo> GetFiles(string currentFolder, IEnumerable<string> filterMasks, Func<FileInfo, bool> predicate = null)
{
Queue<string> queue = new Queue<string>();
queue.Enqueue(currentFolder);
while (queue.Count > 0)
{
currentFolder = queue.Dequeue();
try
{
foreach (string childFolder in Directory.GetDirectories(currentFolder))
queue.Enqueue(childFolder);
}
catch { }
var fileNames = new HashSet<string>();
foreach (var mask in filterMasks)
{
try
{
if (!String.IsNullOrWhiteSpace(mask))
{
var matchingFiles = Directory.GetFiles(currentFolder, mask);
foreach (var file in matchingFiles)
fileNames.Add(file);
}
}
catch { }
}
foreach (var fileName in fileNames)
{
bool include = true;
FileInfo fileInfo = null;
if (predicate != null)
{
try
{
fileInfo = new FileInfo(fileName);
include = predicate(fileInfo);
}
catch { }
}
if (include && fileInfo != null)
yield return fileInfo;
}
}
}
static void Validate(this IRestResponse response)
{
if (response.ErrorException != null)
throw response.ErrorException;
switch (response.ResponseStatus)
{
case ResponseStatus.Aborted:
throw new Exception("The API request was aborted");
case ResponseStatus.Error:
throw new Exception("The API request failed due to an error");
case ResponseStatus.TimedOut:
throw new Exception("The API request failed due to a timeout error");
}
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception($"The API request failed due to an error. HTTP status code is: {response.StatusCode}");
}
private static bool IsMaybeDateTime(this string value)
{
if (String.IsNullOrWhiteSpace(value))
return false;
var length = value.Length;
if (!(length >= DateTimeFormat.DATE_ONLY.Length &&
length <= DateTimeFormat.DATE_HHMMSSFFFFFFF_UTC.Length + 5
))
return false;
if (!(Char.IsNumber(value[0]) && Char.IsNumber(value[1]) && Char.IsNumber(value[2]) && Char.IsNumber(value[3]) &&
value[4] == '-' &&
Char.IsNumber(value[5]) && Char.IsNumber(value[6]) &&
value[7] == '-' &&
Char.IsNumber(value[8]) && Char.IsNumber(value[9])
))
return false;
if (length > DateTimeFormat.DATE_ONLY.Length &&
value[10] != 'T'
)
return false;
if (length == DateTimeFormat.DATE_HHMM_UTC.Length ||
length == DateTimeFormat.DATE_HHMMSS_UTC.Length ||
length == DateTimeFormat.DATE_HHMMSSF_UTC.Length ||
length == DateTimeFormat.DATE_HHMMSSFF_UTC.Length ||
length == DateTimeFormat.DATE_HHMMSSFFF_UTC.Length ||
length == DateTimeFormat.DATE_HHMMSSFFFF_UTC.Length ||
length == DateTimeFormat.DATE_HHMMSSFFFFF_UTC.Length ||
length == DateTimeFormat.DATE_HHMMSSFFFFFF_UTC.Length ||
length == DateTimeFormat.DATE_HHMMSSFFFFFFF_UTC.Length
)
{
if (!value.EndsWith("Z", StringComparison.InvariantCulture))
return false;
}
return true;
}
}
/// <summary>
/// Defines the DateTime formats supported by the ExpandoDB JSON serializer/deserializer.
/// </summary>
public static class DateTimeFormat
{
/// <summary>
/// Date in "yyyy-MM-dd" format
/// </summary>
public const string DATE_ONLY = "yyyy-MM-dd";
/// <summary>
/// Date and time in "yyyy-MM-ddTHH:mm" format
/// </summary>
public const string DATE_HHMM = "yyyy-MM-ddTHH:mm";
/// <summary>
/// Date and time in "yyyy-MM-ddTHH:mmZ" format
/// </summary>
public const string DATE_HHMM_UTC = "yyyy-MM-ddTHH:mmZ";
/// <summary>
/// Date and time in "yyyy-MM-ddTHH:mmzzz" format
/// </summary>
public const string DATE_HHMM_TIMEZONE = "yyyy-MM-ddTHH:mmzzz";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss" format.
/// </summary>
public const string DATE_HHMMSS = "yyyy-MM-ddTHH:mm:ss";
/// <summary>
/// Date amd time in xxx format
/// </summary>
public const string DATE_HHMMSS_UTC = "yyyy-MM-ddTHH:mm:ssZ";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:sszzz" format
/// </summary>
public const string DATE_HHMMSS_TIMEZONE = "yyyy-MM-ddTHH:mm:sszzz";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.f" format
/// </summary>
public const string DATE_HHMMSSF = "yyyy-MM-ddTHH:mm:ss.f";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.fZ" format
/// </summary>
public const string DATE_HHMMSSF_UTC = "yyyy-MM-ddTHH:mm:ss.fZ";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.fzzz" format
/// </summary>
public const string DATE_HHMMSSF_TIMEZONE = "yyyy-MM-ddTHH:mm:ss.fzzz";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.ff" format
/// </summary>
public const string DATE_HHMMSSFF = "yyyy-MM-ddTHH:mm:ss.ff";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.ffZ" format
/// </summary>
public const string DATE_HHMMSSFF_UTC = "yyyy-MM-ddTHH:mm:ss.ffZ";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.ffzzz" format
/// </summary>
public const string DATE_HHMMSSFF_TIMEZONE = "yyyy-MM-ddTHH:mm:ss.ffzzz";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.fff" format
/// </summary>
public const string DATE_HHMMSSFFF = "yyyy-MM-ddTHH:mm:ss.fff";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.fffZ" format
/// </summary>
public const string DATE_HHMMSSFFF_UTC = "yyyy-MM-ddTHH:mm:ss.fffZ";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.fffzzz" format
/// </summary>
public const string DATE_HHMMSSFFF_TIMEZONE = "yyyy-MM-ddTHH:mm:ss.fffzzz";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.ffff" format
/// </summary>
public const string DATE_HHMMSSFFFF = "yyyy-MM-ddTHH:mm:ss.ffff";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.ffffZ" format
/// </summary>
public const string DATE_HHMMSSFFFF_UTC = "yyyy-MM-ddTHH:mm:ss.ffffZ";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.ffffzzz" format
/// </summary>
public const string DATE_HHMMSSFFFF_TIMEZONE = "yyyy-MM-ddTHH:mm:ss.ffffzzz";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.fffff" format
/// </summary>
public const string DATE_HHMMSSFFFFF = "yyyy-MM-ddTHH:mm:ss.fffff";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.fffffZ" format
/// </summary>
public const string DATE_HHMMSSFFFFF_UTC = "yyyy-MM-ddTHH:mm:ss.fffffZ";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.fffffzzz" format
/// </summary>
public const string DATE_HHMMSSFFFFF_TIMEZONE = "yyyy-MM-ddTHH:mm:ss.fffffzzz";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.ffffff" format
/// </summary>
public const string DATE_HHMMSSFFFFFF = "yyyy-MM-ddTHH:mm:ss.ffffff";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.ffffffZ" format
/// </summary>
public const string DATE_HHMMSSFFFFFF_UTC = "yyyy-MM-ddTHH:mm:ss.ffffffZ";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.ffffffzzz" format
/// </summary>
public const string DATE_HHMMSSFFFFFF_TIMEZONE = "yyyy-MM-ddTHH:mm:ss.ffffffzzz";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.fffffff" format
/// </summary>
public const string DATE_HHMMSSFFFFFFF = "yyyy-MM-ddTHH:mm:ss.fffffff";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.fffffffZ" format
/// </summary>
public const string DATE_HHMMSSFFFFFFF_UTC = "yyyy-MM-ddTHH:mm:ss.fffffffZ";
/// <summary>
/// Date amd time in "yyyy-MM-ddTHH:mm:ss.fffffffzzz" format
/// </summary>
public const string DATE_HHMMSSFFFFFFF_TIMEZONE = "yyyy-MM-ddTHH:mm:ss.fffffffzzz";
}
/// <summary>
///
/// </summary>
public static class Extension
{
/// <summary>
/// Ins the sets of.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <param name="size">The size.</param>
/// <returns></returns>
public static IEnumerable<IEnumerable<T>> InSetsOf<T>(this IEnumerable<T> source, int size)
{
var toReturn = new List<T>(size);
foreach (var item in source)
{
toReturn.Add(item);
if (toReturn.Count == size)
{
yield return toReturn;
toReturn = new List<T>(size);
}
}
if (toReturn.Any())
{
yield return toReturn;
}
}
}
}
| {'content_hash': '3dadd619b075a8278a76fd6159ee8c19', 'timestamp': '', 'source': 'github', 'line_count': 506, 'max_line_length': 150, 'avg_line_length': 40.88932806324111, 'alnum_prop': 0.5146930884485259, 'repo_name': 'cris-almodovar/expando-db', 'id': '7be5d1e34c3d43f2c93ea73fcf2312a64a7b7d25', 'size': '20692', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'FileIndexer/Program.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '417476'}, {'name': 'CSS', 'bytes': '93075'}, {'name': 'HTML', 'bytes': '5230'}, {'name': 'JavaScript', 'bytes': '2295478'}]} |
package com.amazonaws.services.cognitoidp.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Represents the response to list devices.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/ListDevices" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListDevicesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The devices returned in the list devices response.
* </p>
*/
private java.util.List<DeviceType> devices;
/**
* <p>
* The pagination token for the list device response.
* </p>
*/
private String paginationToken;
/**
* <p>
* The devices returned in the list devices response.
* </p>
*
* @return The devices returned in the list devices response.
*/
public java.util.List<DeviceType> getDevices() {
return devices;
}
/**
* <p>
* The devices returned in the list devices response.
* </p>
*
* @param devices
* The devices returned in the list devices response.
*/
public void setDevices(java.util.Collection<DeviceType> devices) {
if (devices == null) {
this.devices = null;
return;
}
this.devices = new java.util.ArrayList<DeviceType>(devices);
}
/**
* <p>
* The devices returned in the list devices response.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setDevices(java.util.Collection)} or {@link #withDevices(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param devices
* The devices returned in the list devices response.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListDevicesResult withDevices(DeviceType... devices) {
if (this.devices == null) {
setDevices(new java.util.ArrayList<DeviceType>(devices.length));
}
for (DeviceType ele : devices) {
this.devices.add(ele);
}
return this;
}
/**
* <p>
* The devices returned in the list devices response.
* </p>
*
* @param devices
* The devices returned in the list devices response.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListDevicesResult withDevices(java.util.Collection<DeviceType> devices) {
setDevices(devices);
return this;
}
/**
* <p>
* The pagination token for the list device response.
* </p>
*
* @param paginationToken
* The pagination token for the list device response.
*/
public void setPaginationToken(String paginationToken) {
this.paginationToken = paginationToken;
}
/**
* <p>
* The pagination token for the list device response.
* </p>
*
* @return The pagination token for the list device response.
*/
public String getPaginationToken() {
return this.paginationToken;
}
/**
* <p>
* The pagination token for the list device response.
* </p>
*
* @param paginationToken
* The pagination token for the list device response.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListDevicesResult withPaginationToken(String paginationToken) {
setPaginationToken(paginationToken);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getDevices() != null)
sb.append("Devices: ").append(getDevices()).append(",");
if (getPaginationToken() != null)
sb.append("PaginationToken: ").append(getPaginationToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListDevicesResult == false)
return false;
ListDevicesResult other = (ListDevicesResult) obj;
if (other.getDevices() == null ^ this.getDevices() == null)
return false;
if (other.getDevices() != null && other.getDevices().equals(this.getDevices()) == false)
return false;
if (other.getPaginationToken() == null ^ this.getPaginationToken() == null)
return false;
if (other.getPaginationToken() != null && other.getPaginationToken().equals(this.getPaginationToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getDevices() == null) ? 0 : getDevices().hashCode());
hashCode = prime * hashCode + ((getPaginationToken() == null) ? 0 : getPaginationToken().hashCode());
return hashCode;
}
@Override
public ListDevicesResult clone() {
try {
return (ListDevicesResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| {'content_hash': '68c68906968a4e87a05ad11417ac8331', 'timestamp': '', 'source': 'github', 'line_count': 201, 'max_line_length': 144, 'avg_line_length': 29.64179104477612, 'alnum_prop': 0.6018798254447801, 'repo_name': 'jentfoo/aws-sdk-java', 'id': '3688f557c40046b507abfb205b5ec5de08f239d0', 'size': '6538', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/ListDevicesResult.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '270'}, {'name': 'FreeMarker', 'bytes': '173637'}, {'name': 'Gherkin', 'bytes': '25063'}, {'name': 'Java', 'bytes': '356214839'}, {'name': 'Scilab', 'bytes': '3924'}, {'name': 'Shell', 'bytes': '295'}]} |
/*!
* Font Awesome Free 5.10.0-5 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
*/
@font-face {
font-family: 'Font Awesome 5 Free';
font-style: normal;
font-weight: 900;
font-display: auto;
src: url("../webfonts/fa-solid-900.eot");
src: url("../webfonts/fa-solid-900.eot?#iefix") format("embedded-opentype"), url("../webfonts/fa-solid-900.woff2") format("woff2"), url("../webfonts/fa-solid-900.woff") format("woff"), url("../webfonts/fa-solid-900.ttf") format("truetype"), url("../webfonts/fa-solid-900.svg#fontawesome") format("svg"); }
.fa,
.fas {
font-family: 'Font Awesome 5 Free';
font-weight: 900; }
| {'content_hash': '5eb8f4c6f8cca964e8a8b740d49cbde1', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 307, 'avg_line_length': 45.5, 'alnum_prop': 0.6634615384615384, 'repo_name': 'joeyparrish/cdnjs', 'id': '0349bd56375da892d33686717a99ed89754d7550', 'size': '728', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'ajax/libs/font-awesome/5.10.0-5/css/solid.css', 'mode': '33188', 'license': 'mit', 'language': []} |
<?php declare(strict_types=1);
namespace WyriMaps\BattleNet\Resource\WorldOfWarcraft;
use ApiClients\Foundation\Resource\ResourceInterface;
interface PetTypeInterface extends ResourceInterface
{
const HYDRATE_CLASS = 'WorldOfWarcraft\\PetType';
/**
* @return int
*/
public function id(): int;
/**
* @return string
*/
public function key(): string;
/**
* @return string
*/
public function name(): string;
/**
* @return int
*/
public function typeAbilityId(): int;
/**
* @return int
*/
public function strongAgainstId(): int;
/**
* @return int
*/
public function weakAgainstId(): int;
}
| {'content_hash': 'd45af3b53c7521f3601dcf7cd2ccdc04', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 54, 'avg_line_length': 17.65, 'alnum_prop': 0.6019830028328612, 'repo_name': 'WyriMaps/php-battlenet-client', 'id': '99861a427d06eec5c6af0cb71844efb7749e9ef1', 'size': '706', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Resource/WorldOfWarcraft/PetTypeInterface.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Makefile', 'bytes': '582'}, {'name': 'PHP', 'bytes': '237884'}]} |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EDGE_CROP = exports.EDGE_WRAP = exports.EDGE_EXTEND = exports.BLEND_EXCLUSION = exports.BLEND_DIFFERENCE = exports.BLEND_HARDLIGHT = exports.BLEND_LIGHTEN = exports.BLEND_DARKEN = exports.BLEND_OVERLAY = exports.BLEND_SCREEN = exports.BLEND_MULTIPLY = exports.BLEND_DESTINATION_OVER = exports.BLEND_SOURCE_OVER = exports.VERTICAL_ALIGN_BOTTOM = exports.VERTICAL_ALIGN_MIDDLE = exports.VERTICAL_ALIGN_TOP = exports.HORIZONTAL_ALIGN_RIGHT = exports.HORIZONTAL_ALIGN_CENTER = exports.HORIZONTAL_ALIGN_LEFT = exports.AUTO = void 0;
// used to auto resizing etc.
var AUTO = -1; // Align modes for cover, contain, bit masks
exports.AUTO = AUTO;
var HORIZONTAL_ALIGN_LEFT = 1;
exports.HORIZONTAL_ALIGN_LEFT = HORIZONTAL_ALIGN_LEFT;
var HORIZONTAL_ALIGN_CENTER = 2;
exports.HORIZONTAL_ALIGN_CENTER = HORIZONTAL_ALIGN_CENTER;
var HORIZONTAL_ALIGN_RIGHT = 4;
exports.HORIZONTAL_ALIGN_RIGHT = HORIZONTAL_ALIGN_RIGHT;
var VERTICAL_ALIGN_TOP = 8;
exports.VERTICAL_ALIGN_TOP = VERTICAL_ALIGN_TOP;
var VERTICAL_ALIGN_MIDDLE = 16;
exports.VERTICAL_ALIGN_MIDDLE = VERTICAL_ALIGN_MIDDLE;
var VERTICAL_ALIGN_BOTTOM = 32; // blend modes
exports.VERTICAL_ALIGN_BOTTOM = VERTICAL_ALIGN_BOTTOM;
var BLEND_SOURCE_OVER = 'srcOver';
exports.BLEND_SOURCE_OVER = BLEND_SOURCE_OVER;
var BLEND_DESTINATION_OVER = 'dstOver';
exports.BLEND_DESTINATION_OVER = BLEND_DESTINATION_OVER;
var BLEND_MULTIPLY = 'multiply';
exports.BLEND_MULTIPLY = BLEND_MULTIPLY;
var BLEND_SCREEN = 'screen';
exports.BLEND_SCREEN = BLEND_SCREEN;
var BLEND_OVERLAY = 'overlay';
exports.BLEND_OVERLAY = BLEND_OVERLAY;
var BLEND_DARKEN = 'darken';
exports.BLEND_DARKEN = BLEND_DARKEN;
var BLEND_LIGHTEN = 'lighten';
exports.BLEND_LIGHTEN = BLEND_LIGHTEN;
var BLEND_HARDLIGHT = 'hardLight';
exports.BLEND_HARDLIGHT = BLEND_HARDLIGHT;
var BLEND_DIFFERENCE = 'difference';
exports.BLEND_DIFFERENCE = BLEND_DIFFERENCE;
var BLEND_EXCLUSION = 'exclusion'; // Edge Handling
exports.BLEND_EXCLUSION = BLEND_EXCLUSION;
var EDGE_EXTEND = 1;
exports.EDGE_EXTEND = EDGE_EXTEND;
var EDGE_WRAP = 2;
exports.EDGE_WRAP = EDGE_WRAP;
var EDGE_CROP = 3;
exports.EDGE_CROP = EDGE_CROP;
//# sourceMappingURL=constants.js.map | {'content_hash': '4f3f83069a4c201391c86f544bfa76be', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 535, 'avg_line_length': 43.84313725490196, 'alnum_prop': 0.7674418604651163, 'repo_name': 'BigBoss424/portfolio', 'id': '304a86e3d916771345c4fb3298be776f997e8258', 'size': '2236', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'v7/development/node_modules/@jimp/core/dist/constants.js', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
set -e
if [ -z "${APP_ENV+x}" ];
then
echo 'APP_ENV is unset; please set to staging or production'
exit 1
fi
# A pre-release is a version with a label i.e. v2.0.0-alpha.1
if [[ "$VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+-.+$ ]]
then
IS_PRE_RELEASE=true
else
IS_PRE_RELEASE=false
fi
PACKAGE_PATH="$(pwd)/../../tmp/package"
./scripts/release/writeVersion.js
env PACKAGE_OUTPUT_PATH="$PACKAGE_PATH" ./scripts/build/package.sh
# Right now, we do releases manually, but when we move to GitHub Actions we'll need this line:
# echo "//registry.npmjs.org/:_authToken=$NPM_KEY" > ~/.npmrc
cd "$PACKAGE_PATH" || exit 1
if [ "$IS_PRE_RELEASE" = true ]
then
npm publish --tag next
else
npm publish
fi
cd - || exit
./scripts/build/docs.js
./scripts/release/updateFirebase.js
# TODO: Reanimate it
# if [ "$IS_PRE_RELEASE" = false ]
# then
# ./scripts/release/tweet.js
# fi
| {'content_hash': 'a5ea8c8558e85ce095f7b02dae4130d8', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 94, 'avg_line_length': 22.41025641025641, 'alnum_prop': 0.6613272311212814, 'repo_name': 'date-fns/date-fns', 'id': 'b7e53a753ee8d42b56ae67d17a958c13ecbe2fe9', 'size': '995', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'scripts/release/release.sh', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '75896'}, {'name': 'Shell', 'bytes': '15733'}, {'name': 'TypeScript', 'bytes': '2338794'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.