text
stringlengths 2
1.04M
| meta
dict |
---|---|
package resolve
import (
"context"
"github.com/google/gapid/core/analytics"
"github.com/google/gapid/core/math/interval"
"github.com/google/gapid/gapis/api"
"github.com/google/gapid/gapis/api/sync"
"github.com/google/gapid/gapis/capture"
"github.com/google/gapid/gapis/memory"
"github.com/google/gapid/gapis/messages"
"github.com/google/gapid/gapis/service"
"github.com/google/gapid/gapis/service/path"
)
// Memory resolves and returns the memory from the path p.
func Memory(ctx context.Context, p *path.Memory) (*service.Memory, error) {
ctx = capture.Put(ctx, path.FindCapture(p))
cmdIdx := p.After.Indices[0]
fullCmdIdx := p.After.Indices
allCmds, err := Cmds(ctx, path.FindCapture(p))
if err != nil {
return nil, err
}
sd, err := SyncData(ctx, path.FindCapture(p))
if err != nil {
return nil, err
}
cmds, err := sync.MutationCmdsFor(ctx, path.FindCapture(p), sd, allCmds, api.CmdID(cmdIdx), fullCmdIdx[1:], true)
if err != nil {
return nil, err
}
defer analytics.SendTiming("resolve", "memory")(analytics.Count(len(cmds)))
s, err := capture.NewState(ctx)
if err != nil {
return nil, err
}
err = api.ForeachCmd(ctx, cmds[:len(cmds)-1], func(ctx context.Context, id api.CmdID, cmd api.Cmd) error {
cmd.Mutate(ctx, id, s, nil)
return nil
})
if err != nil {
return nil, err
}
r := memory.Range{Base: p.Address, Size: p.Size}
var reads, writes, observed memory.RangeList
s.Memory.SetOnCreate(func(id memory.PoolID, pool *memory.Pool) {
if id == memory.PoolID(p.Pool) {
pool.OnRead = func(rng memory.Range) {
if rng.Overlaps(r) {
interval.Merge(&reads, rng.Window(r).Span(), false)
}
}
pool.OnWrite = func(rng memory.Range) {
if rng.Overlaps(r) {
interval.Merge(&writes, rng.Window(r).Span(), false)
}
}
}
})
lastCmd := cmds[len(cmds)-1]
api.MutateCmds(ctx, s, nil, lastCmd)
// Check whether the requested pool was ever created.
pool, err := s.Memory.Get(memory.PoolID(p.Pool))
if err != nil {
return nil, &service.ErrDataUnavailable{Reason: messages.ErrInvalidMemoryPool(p.Pool)}
}
slice := pool.Slice(r)
if !p.ExcludeObserved {
observed = slice.ValidRanges()
}
var data []byte
if !p.ExcludeData && slice.Size() > 0 {
data = make([]byte, slice.Size())
if err := slice.Get(ctx, 0, data); err != nil {
return nil, err
}
}
return &service.Memory{
Data: data,
Reads: service.NewMemoryRanges(reads),
Writes: service.NewMemoryRanges(writes),
Observed: service.NewMemoryRanges(observed),
}, nil
}
| {
"content_hash": "8038606e0d46d0c8a8f26f7f5a785aaa",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 114,
"avg_line_length": 25.656565656565657,
"alnum_prop": 0.675984251968504,
"repo_name": "dsrbecky/gapid",
"id": "00fa7ab8633842ca9570100ed9745fec3f915da3",
"size": "3134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gapis/resolve/memory.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "8181"
},
{
"name": "C",
"bytes": "228944"
},
{
"name": "C++",
"bytes": "1250234"
},
{
"name": "CMake",
"bytes": "403615"
},
{
"name": "GLSL",
"bytes": "24812"
},
{
"name": "Go",
"bytes": "4603353"
},
{
"name": "HTML",
"bytes": "132605"
},
{
"name": "Java",
"bytes": "1144829"
},
{
"name": "JavaScript",
"bytes": "11006"
},
{
"name": "Objective-C++",
"bytes": "13141"
},
{
"name": "Python",
"bytes": "1002"
},
{
"name": "Shell",
"bytes": "12480"
}
],
"symlink_target": ""
} |
module GraphQL
module Tracing
# This class uses the AppopticsAPM SDK from the appoptics_apm gem to create
# traces for GraphQL.
#
# There are 4 configurations available. They can be set in the
# appoptics_apm config file or in code. Please see:
# {https://docs.appoptics.com/kb/apm_tracing/ruby/configure}
#
# AppOpticsAPM::Config[:graphql][:enabled] = true|false
# AppOpticsAPM::Config[:graphql][:transaction_name] = true|false
# AppOpticsAPM::Config[:graphql][:sanitize_query] = true|false
# AppOpticsAPM::Config[:graphql][:remove_comments] = true|false
class AppOpticsTracing < GraphQL::Tracing::PlatformTracing
# These GraphQL events will show up as 'graphql.prep' spans
PREP_KEYS = ['lex', 'parse', 'validate', 'analyze_query', 'analyze_multiplex'].freeze
# These GraphQL events will show up as 'graphql.execute' spans
EXEC_KEYS = ['execute_multiplex', 'execute_query', 'execute_query_lazy'].freeze
# During auto-instrumentation this version of AppOpticsTracing is compared
# with the version provided in the appoptics_apm gem, so that the newer
# version of the class can be used
def self.version
Gem::Version.new('1.0.0')
end
self.platform_keys = {
'lex' => 'lex',
'parse' => 'parse',
'validate' => 'validate',
'analyze_query' => 'analyze_query',
'analyze_multiplex' => 'analyze_multiplex',
'execute_multiplex' => 'execute_multiplex',
'execute_query' => 'execute_query',
'execute_query_lazy' => 'execute_query_lazy'
}
def platform_trace(platform_key, _key, data)
return yield if !defined?(AppOpticsAPM) || gql_config[:enabled] == false
layer = span_name(platform_key)
kvs = metadata(data, layer)
kvs[:Key] = platform_key if (PREP_KEYS + EXEC_KEYS).include?(platform_key)
transaction_name(kvs[:InboundQuery]) if kvs[:InboundQuery] && layer == 'graphql.execute'
::AppOpticsAPM::SDK.trace(layer, kvs) do
kvs.clear # we don't have to send them twice
yield
end
end
def platform_field_key(type, field)
"graphql.#{type.graphql_name}.#{field.graphql_name}"
end
def platform_authorized_key(type)
"graphql.authorized.#{type.graphql_name}"
end
def platform_resolve_type_key(type)
"graphql.resolve_type.#{type.graphql_name}"
end
private
def gql_config
::AppOpticsAPM::Config[:graphql] ||= {}
end
def transaction_name(query)
return if gql_config[:transaction_name] == false ||
::AppOpticsAPM::SDK.get_transaction_name
split_query = query.strip.split(/\W+/, 3)
split_query[0] = 'query' if split_query[0].empty?
name = "graphql.#{split_query[0..1].join('.')}"
::AppOpticsAPM::SDK.set_transaction_name(name)
end
def multiplex_transaction_name(names)
return if gql_config[:transaction_name] == false ||
::AppOpticsAPM::SDK.get_transaction_name
name = "graphql.multiplex.#{names.join('.')}"
name = "#{name[0..251]}..." if name.length > 254
::AppOpticsAPM::SDK.set_transaction_name(name)
end
def span_name(key)
return 'graphql.prep' if PREP_KEYS.include?(key)
return 'graphql.execute' if EXEC_KEYS.include?(key)
key[/^graphql\./] ? key : "graphql.#{key}"
end
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def metadata(data, layer)
data.keys.map do |key|
case key
when :context
graphql_context(data[key], layer)
when :query
graphql_query(data[key])
when :query_string
graphql_query_string(data[key])
when :multiplex
graphql_multiplex(data[key])
when :path
[key, data[key].join(".")]
else
[key, data[key]]
end
end.flatten(2).each_slice(2).to_h.merge(Spec: 'graphql')
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
def graphql_context(context, layer)
context.errors && context.errors.each do |err|
AppOpticsAPM::API.log_exception(layer, err)
end
[[:Path, context.path.join('.')]]
end
def graphql_query(query)
return [] unless query
query_string = query.query_string
query_string = remove_comments(query_string) if gql_config[:remove_comments] != false
query_string = sanitize(query_string) if gql_config[:sanitize_query] != false
[[:InboundQuery, query_string],
[:Operation, query.selected_operation_name]]
end
def graphql_query_string(query_string)
query_string = remove_comments(query_string) if gql_config[:remove_comments] != false
query_string = sanitize(query_string) if gql_config[:sanitize_query] != false
[:InboundQuery, query_string]
end
def graphql_multiplex(data)
names = data.queries.map(&:operations).map(&:keys).flatten.compact
multiplex_transaction_name(names) if names.size > 1
[:Operations, names.join(', ')]
end
def sanitize(query)
return unless query
# remove arguments
query.gsub(/"[^"]*"/, '"?"') # strings
.gsub(/-?[0-9]*\.?[0-9]+e?[0-9]*/, '?') # ints + floats
.gsub(/\[[^\]]*\]/, '[?]') # arrays
end
def remove_comments(query)
return unless query
query.gsub(/#[^\n\r]*/, '')
end
end
end
end
| {
"content_hash": "4a9615e04ce9a896cc47945e98079bf2",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 96,
"avg_line_length": 33.21052631578947,
"alnum_prop": 0.5934143335094206,
"repo_name": "rmosolgo/graphql-ruby",
"id": "e5183e55c336a44a78cc02fcb01c28f2e1af3aac",
"size": "5710",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/graphql/tracing/appoptics_tracing.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "31125"
},
{
"name": "JavaScript",
"bytes": "9972"
},
{
"name": "Ragel",
"bytes": "9215"
},
{
"name": "Ruby",
"bytes": "2450857"
},
{
"name": "SCSS",
"bytes": "13574"
},
{
"name": "TypeScript",
"bytes": "131281"
},
{
"name": "Yacc",
"bytes": "21111"
}
],
"symlink_target": ""
} |
@interface RMTileCacheDownloadOperation : NSOperation
- (id)initWithTile:(RMTile)tile forTileSource:(id <RMTileSource>)source usingCache:(RMTileCache *)cache;
@property (nonatomic, strong) NSError *error;
@end
| {
"content_hash": "ff59c2de4e07f6d3d3b40cce841fd06c",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 104,
"avg_line_length": 30.428571428571427,
"alnum_prop": 0.7934272300469484,
"repo_name": "ravivooda/todomap",
"id": "8588b06fb709cd5f3263390d6bb4c751a9fb447e",
"size": "1732",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "ToDoMap/Pods/Mapbox-iOS-SDK/MapView/Map/RMTileCacheDownloadOperation.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "76815"
},
{
"name": "C++",
"bytes": "1379358"
},
{
"name": "Objective-C",
"bytes": "2137003"
},
{
"name": "Objective-C++",
"bytes": "221206"
},
{
"name": "Ruby",
"bytes": "300"
},
{
"name": "Shell",
"bytes": "29815"
}
],
"symlink_target": ""
} |
require "github-commit-mailer/version"
module Github
module Commit
module Mailer
class ConfigException < Exception
end
class GithubCommitMailer
def initialize(repo_dir, yml_cfg, last_commit_file)
@repo_dir = repo_dir
@yml_cfg = yml_cfg
@last_commit_file = last_commit_file
validate
end
def run
last_rev = get_last_emailed_commit
git_pull
revs = get_new_commits(last_rev)
if revs.length < 2 then
puts "No new commits. Exiting."
return
end
puts "Emailing the following commits:"
revs.each { |r|
puts "commit: '#{r}'"
}
rev_from = revs[revs.length - 1]
rev_to = revs[0]
cmd = "cd #{@repo_dir} && echo '#{rev_from} #{rev_to} refs/heads/master'|git-commit-notifier #{@yml_cfg}; cd -"
puts "#{cmd}"
raise "Error executing git-commit-notifier" if !system(cmd)
puts "Saving '#{rev_to}' to '#{@last_commit_file}' ..."
File.open(@last_commit_file, 'w') do |f|
f.puts "#{rev_to}"
end
end
private
def validate
raise ConfigException, "Git repository directory doesn't exist" if Dir[@repo_dir] == nil
raise ConfigException, "Yaml config file doesn't exist" if !File.exists?(@yml_cfg)
end
def get_last_emailed_commit
last_rev = nil
if File.exists? @last_commit_file then
last_rev = File.readlines(@last_commit_file)[0].strip
puts "Last emailed revision '#{last_rev}'"
end
last_rev
end
def git_pull
res = system("cd #{@repo_dir} && git pull --rebase ; cd -")
raise "Error executing git_pull" if !res
end
def get_new_commits(last_rev)
revs = []
IO.popen "git --git-dir #{@repo_dir}/.git log -200|grep -e '^commit '|awk '{print $2}'" do |io|
io.each do |line|
if last_rev.nil? or ! revs.include? last_rev then
revs << line.strip
end
end
end
revs
end
end
end
end
end
| {
"content_hash": "32b7b2f76581c9cd358d30f0519e038b",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 118,
"avg_line_length": 24.141176470588235,
"alnum_prop": 0.5682261208576999,
"repo_name": "mtricolici/github-commit-mailer",
"id": "280b216ec53d2852fc2a769a35bf444b35bca1d5",
"size": "2052",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/github-commit-mailer.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "3563"
}
],
"symlink_target": ""
} |
@interface LoginViewController : BaseViewController
@end
| {
"content_hash": "2540ee44f9f60027b0ea8cd97784524d",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 51,
"avg_line_length": 12,
"alnum_prop": 0.8166666666666667,
"repo_name": "lizhihui0215/RACStudy",
"id": "bae0c290d92770d00b0c61d0cb5a2490893293d9",
"size": "230",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RACDemo/RACDemo/View Controllers/Root View Controller/LoginViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "11629"
},
{
"name": "Ruby",
"bytes": "41"
}
],
"symlink_target": ""
} |
(function() { 'use strict';
/************************************************************************************
* @ngdoc constant
* @name ROLES
* @module metricapp
* @description
* Defines constants related to user roles.
* - EXPERT:
* - QUESTIONER:
* - METRICATOR:
************************************************************************************/
angular.module('metricapp')
.constant('ROLES', {
EXPERT: 'EXPERT',
QUESTIONER: 'QUESTIONER',
METRICATOR: 'METRICATOR'
});
})();
| {
"content_hash": "65f628bce02adc4429efbcd879ada457",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 85,
"avg_line_length": 22.818181818181817,
"alnum_prop": 0.42231075697211157,
"repo_name": "metricAppTeam/metricapp-client",
"id": "bf372a455d9303a75eee370d7929df3f7688d4bd",
"size": "502",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/core/common/enums/user.roles.const.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2130"
},
{
"name": "HTML",
"bytes": "253230"
},
{
"name": "JavaScript",
"bytes": "360331"
}
],
"symlink_target": ""
} |
package com.intellij.java.codeInsight.daemon;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.redundantCast.RedundantCastInspection;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.lang.java.JavaDocumentationProvider;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.psi.*;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase;
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl;
import com.intellij.util.ArrayUtilRt;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class LightAdvHighlightingFixtureTest extends LightJavaCodeInsightFixtureTestCase {
@Override
protected String getBasePath() {
return JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/daemonCodeAnalyzer/advFixture";
}
public void testHidingOnDemandImports() {
//noinspection StaticNonFinalField
myFixture.addClass("package foo; public class Foo {" +
" public static String foo;" +
"}");
myFixture.addClass("package foo; public class Bar {" +
" public static void foo(String s) {}" +
"}");
myFixture.configureByFile(getTestName(false) + ".java");
myFixture.checkHighlighting(false, false, false);
}
public void testFilteredCandidates() {
PsiFile file = myFixture.configureByText("a.java", "class a {{new StringBuilder().ap<caret>pend();}}");
PsiCallExpression callExpression =
PsiTreeUtil.getParentOfType(file.findElementAt(myFixture.getEditor().getCaretModel().getOffset()), PsiCallExpression.class);
assertNotNull(callExpression);
CandidateInfo[] candidates =
PsiResolveHelper.getInstance(myFixture.getProject()).getReferencedMethodCandidates(callExpression, false);
assertSize(27, candidates);
String generateDoc = new JavaDocumentationProvider().generateDoc(callExpression, callExpression);
assertEquals("<html>Candidates for method call <b>new StringBuilder().append()</b> are:<br><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(java.lang.Object)\">StringBuilder append(Object)</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(java.lang.String)\">StringBuilder append(String)</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(java.lang.StringBuilder)\">StringBuilder append(StringBuilder)</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(java.lang.StringBuffer)\">StringBuilder append(StringBuffer)</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(java.lang.CharSequence)\">StringBuilder append(CharSequence)</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(java.lang.CharSequence, int, int)\">StringBuilder append(CharSequence, int, int)</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(char[])\">StringBuilder append(char[])</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(char[], int, int)\">StringBuilder append(char[], int, int)</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(boolean)\">StringBuilder append(boolean)</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(char)\">StringBuilder append(char)</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(int)\">StringBuilder append(int)</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(long)\">StringBuilder append(long)</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(float)\">StringBuilder append(float)</a><br> " +
"<a href=\"psi_element://java.lang.StringBuilder#append(double)\">StringBuilder append(double)</a><br></html>", generateDoc);
}
public void testPackageNamedAsClassInDefaultPackage() {
myFixture.addClass("package test; public class A {}");
PsiClass aClass = myFixture.addClass("public class test {}");
doTest();
assertNull(ProgressManager.getInstance().runProcess(() -> ReferencesSearch.search(aClass).findFirst(), new EmptyProgressIndicator()));
}
public void testPackageNameAsClassFQName() {
myFixture.addClass("package foo.Bar; class A {}");
myFixture.addClass("package foo; public class Bar { public static class Inner {}}");
doTest();
}
public void testInaccessibleFunctionalTypeParameter() {
myFixture.addClass("package test; class A {}");
myFixture.addClass("package test; public interface I { void m(A a);}");
myFixture.addClass("package test; public interface J { A m();}");
doTest();
}
public void testBoundsPromotionWithCapturedWildcards() {
myFixture.addClass("package a; public interface Provider<A> {}");
myFixture.addClass("package b; public interface Provider<B> {}");
doTest();
}
public void testStaticImportCompoundWithInheritance() {
myFixture.addClass("package a; public interface A { static void foo(Object o){} static void foo(String str) {}}");
doTest();
}
public void testSuppressedInGenerated() {
myFixture.enableInspections(new RedundantCastInspection());
myFixture.addClass("package javax.annotation; public @interface Generated {}");
doTest();
}
public void testReferenceThroughInheritance() {
myFixture.addClass("package test;\n" +
"public class A {\n" +
" public static class B {}\n" +
"}");
doTest();
}
public void testReferenceThroughInheritance1() {
//noinspection UnnecessaryInterfaceModifier
myFixture.addClass("package me;\n" +
"import me.Serializer.Format;\n" +
"public interface Serializer<F extends Format> {\n" +
" public static interface Format {}\n" +
"}\n");
doTest();
}
public void testUsageOfProtectedAnnotationOutsideAPackage() {
myFixture.addClass("package a;\n" +
"import java.lang.annotation.ElementType;\n" +
"import java.lang.annotation.Target;\n" +
"\n" +
"public class A {\n" +
" @Target( { ElementType.METHOD, ElementType.TYPE } )\n" +
" protected @interface Test{\n" +
" }\n" +
"}");
doTest();
}
public void testPackageLocalClassUsedInArrayTypeOutsidePackage() {
myFixture.addClass("package a; class A {}");
myFixture.addClass("package a; public class B {public static A[] getAs() {return null;}}");
doTest();
}
public void testProtectedFieldUsedInAnnotationParameterOfInheritor() {
myFixture.addClass("package a; public class A {protected final static String A_FOO = \"A\";}");
doTest();
}
public void testStaticImportClassConflictingWithPackageName() {
myFixture.addClass("package p.P1; class Unrelated {}");
myFixture.addClass("package p; public class P1 {public static final int FOO = 1;}");
doTest();
}
public void testAmbiguousMethodCallWhenStaticImported() {
myFixture.addClass("package p;" +
"class A<K> {\n" +
" static <T> A<T> of(T t) {\n" +
" return null;\n" +
" }\n" +
"}\n" +
"class B<K> {\n" +
" static <T> B<T> of(T t) {\n" +
" return null;\n" +
" }\n" +
" static <T> B<T> of(T... t) {\n" +
" return null;\n" +
" }\n" +
"}\n");
doTest();
}
public void testClassPackageConflict() {
myFixture.addClass("package a; public class b {}");
myFixture.addClass("package c; public class a {}");
doTest();
}
public void testClassPackageConflict1() {
myFixture.addClass("package a; public class b {}");
myFixture.addClass("package c.d; public class a {}");
doTest();
}
public void testTypeAnnotations() {
myFixture.addClass("import java.lang.annotation.ElementType;\n" +
"import java.lang.annotation.Target;\n" +
"@Target({ElementType.TYPE_USE})\n" +
"@interface Nullable {}\n");
myFixture.addClass("class Middle<R> extends Base<@Nullable R, String>{}");
myFixture.addClass("class Child<R> extends Middle<R>{}");
PsiClass baseClass = myFixture.addClass("class Base<R, C> {}");
PsiClass fooClass = myFixture.addClass("class Foo {\n" +
" Child<String> field;\n" +
"}");
PsiField fooField = fooClass.findFieldByName("field", false);
PsiType substituted =
TypeConversionUtil.getSuperClassSubstitutor(baseClass, (PsiClassType)fooField.getType()).substitute(baseClass.getTypeParameters()[0]);
assertEquals(1, substituted.getAnnotations().length);
}
public void testCodeFragmentMayAccessDefaultPackage() {
myFixture.addClass("public class MainClass { }");
Project project = getProject();
PsiElement context = JavaPsiFacade.getInstance(project).findPackage("");
JavaCodeFragment fragment = JavaCodeFragmentFactory.getInstance(project).createReferenceCodeFragment("MainClass", context, true, true);
Document document = PsiDocumentManager.getInstance(project).getDocument(fragment);
Editor editor = EditorFactory.getInstance().createViewer(document, project);
Disposer.register(myFixture.getTestRootDisposable(), () -> EditorFactory.getInstance().releaseEditor(editor));
List<HighlightInfo> highlights = CodeInsightTestFixtureImpl.instantiateAndRun(fragment, editor, ArrayUtilRt.EMPTY_INT_ARRAY, false);
List<HighlightInfo> problems = DaemonAnalyzerTestCase.filter(highlights, HighlightSeverity.WARNING);
assertThat(problems).isEmpty();
}
public void testImplicitConstructorAccessibility() {
myFixture.addClass("package a; public class Base {" +
"private Base() {}\n" +
"protected Base(int... i) {}\n" +
"}");
doTest();
}
public void testDiamondsWithAnonymousProtectedConstructor() {
myFixture.addClass("package a; public class Base<T> { protected Base() {}}");
doTest();
}
public void testDiamondsWithProtectedCallInConstruction() {
myFixture.addClass("package a; public class Base { " +
" protected String createString() {return null;}" +
"}");
doTest();
}
public void testDefaultAnnotationsApplicability() {
myFixture.addClass("package foo; public @interface A {}");
myFixture.configureByFile("module-info.java");
myFixture.checkHighlighting();
}
public void testAlwaysFalseForLoop() {
doTest();
IntentionAction action = myFixture.findSingleIntention("Remove 'for' statement");
myFixture.launchAction(action);
myFixture.checkResultByFile(getTestName(false) + "_after.java");
}
public void testProtectedInnerClass() {
myFixture.addClass("package a;\n" +
"public class Outer {\n" +
" public Object get(Inner key) {\n" +
" return null;\n" +
" }\n" +
" public Inner get1() {return null;} \n" +
" public Inner f; \n" +
" protected class Inner {}\n" +
"}");
doTest();
}
public void testProtectedInnerClass1() {
myFixture.addClass("package a;\n" +
"public class A<T> {\n" +
" public T getData() {return null;}\n" +
"}");
myFixture.addClass("package a;\n" +
"public class Outer extends A<Outer.Inner> {\n" +
" protected class Inner {}\n" +
"}");
doTest();
}
private void doTest() {
myFixture.configureByFile(getTestName(false) + ".java");
myFixture.checkHighlighting();
}
} | {
"content_hash": "ef7d91961df677bfcbca9006a8fcdde5",
"timestamp": "",
"source": "github",
"line_count": 285,
"max_line_length": 176,
"avg_line_length": 46.435087719298245,
"alnum_prop": 0.6320840259936528,
"repo_name": "google/intellij-community",
"id": "913fb7ace30ea2c7bbdb34897f4ae4c15628b887",
"size": "13355",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/LightAdvHighlightingFixtureTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#include "flag.ht"
#define index work_around_gcc_bug
#include "jni.h"
#undef index
#ifdef FLG_UNIX
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef FLG_OSX_UNIX
#else
#include <wait.h>
#endif
#include <poll.h>
#else /* NT */
#include <windows.h>
#endif
#include "host.hf"
#include "utl.hf"
#define index work_around_gcc_bug
#include "com_gemstone_gemfire_internal_OSProcess.h"
#undef index
static void checkAsciiMessage(const char* message)
{
int j;
// some checks to try to catch uninitialized message buffers
UTL_ASSERT(message != NULL);
for (j = 0; j < 100; j++) {
int aChar = message[j] ;
if (aChar == '\0')
break;
UTL_ASSERT(aChar > 0 && aChar <= 0x7F);
}
}
static void throwByName(JNIEnv *env, const char *name, const char *msg)
{
jthrowable prev;
UTL_ASSERT(env != NULL);
checkAsciiMessage(msg);
prev = (*env)->ExceptionOccurred(env);
if (prev == NULL) {
jclass cls = (*env)->FindClass(env, name);
if (cls != NULL) { /* Otherwise an exception has already been thrown */
(*env)->ThrowNew(env, cls, msg);
(*env)->DeleteLocalRef(env, cls); /* clean up local ref*/
} else {
char msgBuf[300];
snprintf(msgBuf, sizeof(msgBuf), "unable to throw %s %s \n", name, msg);
HostPrintStderr("severe", msgBuf);
#ifdef FLG_DEBUG
HostCallDebugger();
#endif
}
} else {
(*env)->DeleteLocalRef(env, prev);
}
}
JNIEXPORT jint JNICALL
Java_com_gemstone_gemfire_internal_OSProcess_bgexecInternal(JNIEnv *env,
jclass c,
jobjectArray cmdarray,
jstring workdir,
jstring logfile,
jboolean inheritLogfile)
{
int result = -1;
int k = 0;
int argc;
char **argv = NULL;
const char *wdstr = NULL;
const char *logstr = NULL;
char *argstr = NULL; /* Win32 only */
char errmsg[1024];
if (cmdarray == NULL) {
goto error_cleanup;
}
argc = (*env)->GetArrayLength(env, cmdarray);
if (argc == 0) {
throwByName(env, "java/lang/IllegalArgumentException", "empty arg array");
goto error_cleanup;
}
/* calloc null terminates for us */
argv = (char**)UtlCalloc(argc + 1, sizeof(char *));
if (argv == NULL) {
throwByName(env, "java/lang/OutOfMemoryError", NULL);
goto error_cleanup;
}
for (k = 0; k < argc; k++) {
jstring jstr = (jstring)(*env)->GetObjectArrayElement(env, cmdarray, k);
argv[k] = (char*)(*env)->GetStringUTFChars(env, jstr, NULL);
(*env)->DeleteLocalRef(env, jstr);
if (argv[k] == NULL) {
goto error_cleanup;
}
}
wdstr = (*env)->GetStringUTFChars(env, workdir, NULL);
if (wdstr == NULL) {
goto error_cleanup;
}
logstr = (*env)->GetStringUTFChars(env, logfile, NULL);
if (logstr == NULL) {
goto error_cleanup;
}
#ifdef FLG_UNIX
do { /* loop because SIGCHLD can cause fork() to fail */
errno = 0;
#ifdef FLG_SOLARIS_UNIX
result = fork1();
#elif defined(FLG_LINUX_UNIX)
result = fork();
#elif defined(FLG_OSX_UNIX)
result = fork();
#else
+++ sorry, we only want _this_ thread forked. How do you do it?
result = fork();
#endif
#ifdef FLG_OSX_UNIX
} while (result == -1 && (errno == EINTR));
#else
} while (result == -1 && (errno == EINTR || errno == ERESTART));
#endif
if (result == 0) {
/* Child process */
int max_fd;
int logfd;
FILE* theLogFile;
char logbuff[4096];
const char* logptr;
int skipfd = 0;
char * envhack = getenv("GEMSTONE_SERVER_PIPE");
if (envhack != NULL) {
sscanf(envhack, "%d", &skipfd);
}
#if defined(FLG_LINUX_UNIX) || defined(FLG_OSX_UNIX)
{
/* Record our pid in an env var. We use this to get the main pid
* to fix bug 28770.
*/
char* inStr = (char*)UtlMalloc(100, "OSPROCESS_BGEXEC_PID");
snprintf(inStr, 99, "OSPROCESS_BGEXEC_PID=%d", getpid());
putenv(inStr);
inStr = (char*)UtlMalloc(100, "TEST_OSPROCESS_BGEXEC_PID");
snprintf(inStr, 99, "TEST_OSPROCESS_BGEXEC_PID=%d", getpid());
putenv(inStr);
}
#endif
/* close everything */
max_fd = sysconf(_SC_OPEN_MAX);
int j;
for (j = 3; j < max_fd; j++) {
if (j != skipfd) {
close(j);
}
}
if (strstr(logstr, "bgexec") != NULL) {
char *endptr;
/* It contains "bgexec" so tack on the pid.
* But first remove the empty file created in OSProcess.java.
*/
unlink(logstr);
strncpy(logbuff, logstr, sizeof(logbuff) - 10);
logbuff[sizeof(logbuff) - 10] = '\0';
endptr = strrchr(logbuff, '.');
if (endptr != NULL) {
endptr[0] = '\0';
} else {
endptr = logbuff + strlen(logbuff);
}
sprintf(endptr, "_%d.log", getpid());
logptr = logbuff;
} else {
logptr = logstr;
}
logfd = open(logptr, O_WRONLY|O_APPEND|O_CREAT, 0644);
if (logfd == -1) {
/* Bummer. Can't do much since have no place to write error */
_exit(-1);
}
close(0);
open("/dev/null", O_RDONLY); /* makes stdin point at /dev/null */
fcntl(0, F_SETFD, 0); /* unset close-on-exec for good measure */
if (-1 == dup2(logfd, 1)) {
const char* msg = "dup2 of stdout failed\n";
char* msg2 = strerror(errno);
size_t num = write(logfd, msg, strlen(msg));
num = write(logfd, msg2, strlen(msg2));
if (num < 0) {
_exit(num);
}
_exit(-1);
}
if (-1 == dup2(logfd, 2)) {
const char* msg = "dup2 of stderr failed: ";
char* msg2 = strerror(errno);
size_t num = write(logfd, msg, strlen(msg));
num = write(logfd, msg2, strlen(msg2));
if (num < 0) {
_exit(num);
}
_exit(-1);
}
/* don't want this file hanging around after exec */
fcntl(logfd, F_SETFD, 1);
/* unset close-on-exec for good measure */
fcntl(1, F_SETFD, 0);
fcntl(2, F_SETFD, 0);
errno = 0;
theLogFile = fdopen(1, "a");
/* Note we use '1' instead of 'logfd'.
* Due to the dup2 call above we can do this.
* And since logfd might be greater than
* 255 this fixes bug 14707.
*/
if (!theLogFile) {
const char* msg = "fdopen(1, \"a\") failed: ";
char* msg2 = strerror(errno);
size_t num = write(logfd, msg, strlen(msg));
num = write(logfd, msg2, strlen(msg2));
if (num < 0) {
_exit(num);
}
_exit(-1);
}
/* Now we can write messages to user's theLogFile. */
#if 0
fprintf(theLogFile, "trace messages\n");
fflush(theLogFile);
i = 0;
while (argv[i]) {
fprintf(theLogFile, "argv[%d] = '%s'\n", i, argv[i]);
i++;
}
fprintf(theLogFile, "workdir = '%s'\n", wdstr);
fprintf(theLogFile, "logfile = '%s'\n", logptr);
fflush(theLogFile);
#endif
errno = 0;
if (chdir(wdstr) == -1) {
fprintf(theLogFile, "chdir(%s) failed with errno=%d (i.e. %s)\n",
wdstr, errno, strerror(errno));
fflush(theLogFile);
_exit(-1);
}
/* Make sure this process not part of parent's session */
errno = 0;
if (setsid() == -1) {
fprintf(theLogFile, "setsid() failed with errno=%d (i.e. %s)\n",
errno, strerror(errno));
fflush(theLogFile);
_exit(-1);
}
errno = 0;
execv(argv[0], argv);
fprintf(theLogFile, "execv() failed with errno=%d (i.e. %s)\n",
errno, strerror(errno));
fprintf(theLogFile, "The command and its args follow:\n");
fprintf(theLogFile, "%s\n", argv[0]);
int i2 = 1;
while (argv[i2]) {
fprintf(theLogFile, " %s\n", argv[i2]);
i2++;
}
fflush(theLogFile);
_exit(-1);
} else {
/* parent process */
if (result < 0) {
sprintf(errmsg, "fork failed with result = %d, errno = %d, %s\n",
result, errno, strerror(errno));
throwByName(env, "java/io/IOException", errmsg);
goto error_cleanup;
}
}
#else /* NT Win32 */
if (argv) {
char *p;
size_t len;
int i;
size_t argstrLength = 1;
int needsShell = 0;
char* argv0 = argv[0];
const char* shellPrefix = "cmd /c ";
#if 0
if (strlen(argv0) > 4) {
char* extPtr = argv0 + strlen(argv0) - 4;
if (strcmp(extPtr, ".bat") == 0 || strcmp(extPtr, ".BAT") == 0) {
needsShell = 1;
}
}
#endif
if (needsShell) {
argstrLength += strlen(shellPrefix);
}
i = 0;
while (argv[i]) {
argstrLength += strlen(argv[i]) + 1;
i++;
}
argstr = (char*)UtlCalloc(argstrLength, sizeof(char));
if (argstr == NULL) {
throwByName(env, "java/lang/OutOfMemoryError", NULL);
goto error_cleanup;
}
i = 0;
p = argstr;
if (needsShell) {
strcpy(p, shellPrefix);
p += strlen(shellPrefix);
}
while (argv[i]) {
if (i != 0) {
strcpy(p, " ");
p += 1;
}
len = strlen(argv[i]);
strcpy(p, argv[i]);
p += len;
i++;
}
}
{
int errcode;
BOOL childcreated;
HANDLE hChildin, hChildout;
SECURITY_ATTRIBUTES saAttr;
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
hChildout = CreateFile(logstr, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE, // bug 20179
&saAttr, OPEN_ALWAYS,
/* FILE_FLAG_WRITE_THROUGH bug 23892 */ 0,
NULL);
if (hChildout == INVALID_HANDLE_VALUE) {
sprintf(errmsg,
"Could not create log file '%s' failed with error=%d",
logstr, GetLastError());
throwByName(env, "java/io/IOException", errmsg);
goto error_cleanup;
}
SetFilePointer(hChildout, 0, 0, FILE_END);
hChildin = CreateFile("nul", GENERIC_READ, 0,
&saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
NULL);
if (hChildin == INVALID_HANDLE_VALUE) {
sprintf(errmsg, "could not open 'nul' file. error=%d\n",
GetLastError());
throwByName(env, "java/io/IOException", errmsg);
CloseHandle(hChildout);
goto error_cleanup;
}
#if 0
fprintf(stdout, "trace messages\n");
fflush(stdout);
i = 0;
while (argv[i]) {
fprintf(stdout, "argv[%d] = '%s'\n", i, argv[i]);
i++;
}
fprintf(stdout, "workdir = '%s'\n", wdstr);
fprintf(stdout, "logfile = '%s'\n", logstr);
fprintf(stdout, "argstr = '%s'\n", argstr);
fflush(stdout);
#endif
/* make sure our child does no inherit our stdin, stdout, and stderr */
SetHandleInformation(GetStdHandle(STD_INPUT_HANDLE), HANDLE_FLAG_INHERIT, FALSE);
SetHandleInformation(GetStdHandle(STD_OUTPUT_HANDLE), HANDLE_FLAG_INHERIT, FALSE);
SetHandleInformation(GetStdHandle(STD_ERROR_HANDLE), HANDLE_FLAG_INHERIT, FALSE);
memset(&siStartInfo, 0, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.lpReserved = NULL;
siStartInfo.lpReserved2 = NULL;
siStartInfo.cbReserved2 = 0;
siStartInfo.lpDesktop = NULL;
siStartInfo.dwFlags = 0;
siStartInfo.dwFlags = STARTF_USESTDHANDLES;
siStartInfo.hStdInput = hChildin;
siStartInfo.hStdOutput = hChildout;
siStartInfo.hStdError = hChildout;
childcreated = CreateProcess(NULL, (char*)argstr, NULL, NULL, TRUE /*inheritLogfile*/,
CREATE_NEW_PROCESS_GROUP|CREATE_DEFAULT_ERROR_MODE|CREATE_NO_WINDOW|DETACHED_PROCESS,
NULL, wdstr, &siStartInfo, &piProcInfo);
errcode = GetLastError();
CloseHandle(hChildin);
CloseHandle(hChildout);
if (!childcreated) {
sprintf(errmsg, "CreateProcess failed with errcode=%d\n",
errcode);
throwByName(env, "java/io/IOException", errmsg);
goto error_cleanup;
} else {
result = piProcInfo.dwProcessId;
CloseHandle(piProcInfo.hThread);
CloseHandle(piProcInfo.hProcess);
}
}
#endif
error_cleanup:
if (wdstr) {
(*env)->ReleaseStringUTFChars(env, workdir, wdstr);
}
if (logstr) {
(*env)->ReleaseStringUTFChars(env, logfile, logstr);
}
if (argv) {
int len = (*env)->GetArrayLength(env, cmdarray);
int i;
for (i = 0; i < len; i++) {
if (argv[i] != NULL) {
jstring jstr = (jstring)(*env)->GetObjectArrayElement(env, cmdarray, i);
(*env)->ReleaseStringUTFChars(env, jstr, argv[i]);
(*env)->DeleteLocalRef(env, jstr);
}
}
UtlFree(argv);
if (argstr) {
UtlFree(argstr);
}
}
return (jint)result;
}
/*
* Class: com_gemstone_gemfire_internal_OSProcess
* Method: nativeExists
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_gemstone_gemfire_internal_OSProcess_nativeExists(JNIEnv * env,
jclass c,
jint pid)
{
#ifdef FLG_UNIX
if (kill((pid_t)pid, 0) == -1) {
if (errno == EPERM) {
/* Process exists; it probably belongs to another user. Fix for bug 27698. */
return JNI_TRUE;
} else {
return JNI_FALSE;
}
} else {
return JNI_TRUE;
}
#else
HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
if (h == NULL) {
return JNI_FALSE;
} else {
CloseHandle(h);
return JNI_TRUE;
}
#endif
}
/*
* Class: com_gemstone_gemfire_internal_OSProcess
* Method: kill
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_gemstone_gemfire_internal_OSProcess__1kill(JNIEnv *env,
jclass c,
jint pid)
{
#ifdef FLG_UNIX
if (kill((pid_t)pid, SIGKILL) == -1) {
return JNI_FALSE;
} else {
return JNI_TRUE;
}
#else
jboolean result = JNI_FALSE;
HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
if (h) {
if (TerminateProcess(h, 1)) {
result = JNI_TRUE;
}
CloseHandle(h);
}
return result;
#endif
}
/*
* Class: com_gemstone_gemfire_internal_OSProcess
* Method: shutdown
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_gemstone_gemfire_internal_OSProcess__1shutdown(JNIEnv * env,
jclass c,
jint pid)
{
#ifdef FLG_UNIX
if (kill((pid_t)pid, SIGTERM) == -1) {
return JNI_FALSE;
} else {
return JNI_TRUE;
}
#else
/* no nice way on nt; so just do a kill */
return Java_com_gemstone_gemfire_internal_OSProcess__1kill(env, c, pid);
#endif
}
/*
* Class: com_gemstone_gemfire_internal_OSProcess
* Method: printStacks
* Signature: (I)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_gemstone_gemfire_internal_OSProcess__1printStacks(JNIEnv * env,
jclass c,
jint pid)
{
#ifdef FLG_UNIX
if (pid == 0) {
pid = getpid();
}
if (kill((pid_t)pid, SIGQUIT) == -1) {
return JNI_FALSE;
} else {
return JNI_TRUE;
}
#else
jboolean result = JNI_FALSE;
char nameBuf[128];
HANDLE targetEvent = NULL;
sprintf(nameBuf, "gsjvm_sigbreakevent%d"/*must agree with os_win32.cpp*/, pid);
targetEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, nameBuf);
if (targetEvent != NULL) {
if (SetEvent(targetEvent)) {
result = JNI_TRUE;
}
CloseHandle(targetEvent);
}
return result;
#endif
}
/*
* Class: com_gemstone_gemfire_internal_OSProcess
* Method: waitForPid
* Signature: (I)V
*/
JNIEXPORT void JNICALL
Java_com_gemstone_gemfire_internal_OSProcess_waitForPid(JNIEnv *env,
jclass c,
jint pid)
{
#ifdef FLG_UNIX
pid_t resultPid;
int status;
do {
resultPid = waitpid(pid, &status, 0);
} while (resultPid == -1 && errno == EINTR);
#else /* NT */
HANDLE h = OpenProcess(SYNCHRONIZE, FALSE, (DWORD)pid);
if (h != NULL) {
WaitForSingleObject(h, INFINITE);
CloseHandle(h);
}
#endif
}
/*
* Class: com_gemstone_gemfire_internal_OSProcess
* Method: reapPid
* Signature: (I)Z
*/
/**
* Reaps a child process if it has died.
* Does not wait for the child.
* @param pid the id of the process to reap
* @return true if it was reaped or lost (someone else reaped it);
* false if the child still exists.
* HACK: If pid is -1 then returns true if this platform needs reaping.
*/
JNIEXPORT jboolean JNICALL
Java_com_gemstone_gemfire_internal_OSProcess_reapPid(JNIEnv *env,
jclass c,
jint pid)
{
#ifdef FLG_UNIX
pid_t resultPid;
int status;
if (pid < 0) { // initialization call , just return true on unix
return JNI_TRUE;
}
do {
resultPid = waitpid(pid, &status, WNOHANG);
} while (resultPid == -1 && errno == EINTR);
if (resultPid != pid) {
if (resultPid == -1) {
/* we get an error if someone else reaped the pid
*
* printf("waitpid for pid %d failed with result_pid = %d errno %d\n",
* pid, resultPid, errno);
*/
return JNI_TRUE;
} else {
/* this means that the child process still exists
*
* printf("waitpid for pid %d returned %d and status = %d\n",
* pid, resultPid, status);
*/
return JNI_FALSE;
}
} else {
/* the child died and we reaped it */
/*
* printf("pid %d exited with status code %d\n", pid, info.si_status);
*/
return JNI_TRUE;
}
#else
/* nothing needed on NT */
return JNI_FALSE;
#endif
}
/* deleted reaperRun */
/*
* Class: com_gemstone_gemfire_internal_OSProcess
* Method: jniSetCurDir
* Signature: (Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL
Java_com_gemstone_gemfire_internal_OSProcess_jniSetCurDir(JNIEnv * env,
jclass c,
jstring dir)
{
const char *dirStr = (*env)->GetStringUTFChars(env, dir, NULL);
jboolean result;
if (dirStr == NULL) {
return JNI_FALSE;
}
#ifdef FLG_UNIX
if (chdir(dirStr) != -1) {
result = JNI_TRUE;
} else {
/* what to do with errno? */
result = JNI_FALSE;
}
#else
if (SetCurrentDirectory(dirStr)) {
result = JNI_TRUE;
} else {
/* what to do with GetLastError() ? */
result = JNI_FALSE;
}
#endif
(*env)->ReleaseStringUTFChars(env, dir, dirStr);
return result;
}
JNIEXPORT jint JNICALL
Java_com_gemstone_gemfire_internal_OSProcess_getProcessId(JNIEnv *env, jclass c)
{
// note on Linux, getpid() may return the "process id" of the current
// thread, which may be different from the process id of the Java VM main thread .
return HOST_GETPID();
}
#if defined(FLG_LINUX_UNIX)
#define STDERR_ALIAS 2
static void redirectFd(int target, const char* filename) {
int fd = open(filename, O_WRONLY|O_CREAT|O_APPEND|O_LARGEFILE, 0666);
int duplicate = fcntl(target, F_DUPFD, 10);
const char msg[] = "Failed to redirect line %d, fd %d, with errono %d";
if(duplicate == -1) {
if(target == STDERR_ALIAS) {
fprintf(stdout, msg, __LINE__, target, errno);
} else {
fprintf(stderr, msg, __LINE__, target, errno);
}
}
int ret = fcntl(duplicate, F_SETFD, FD_CLOEXEC);
if(ret == -1) {
if(target == STDERR_ALIAS) {
fprintf(stdout, msg, __LINE__, target, errno);
} else {
fprintf(stderr, msg, __LINE__, target, errno);
}
}
ret = dup2(fd, target);
if(ret == -1) {
if(target == STDERR_ALIAS) {
fprintf(stdout, msg, __LINE__, target, errno);
} else {
fprintf(stderr, msg, __LINE__, target, errno);
}
}
close(fd);
close(duplicate);
}
#undef STDERR_ALIAS
#endif
/*
* Class: com_gemstone_gemfire_internal_OSProcess
* Method: redirectCOutput
*/
JNIEXPORT void JNICALL
Java_com_gemstone_gemfire_internal_OSProcess_redirectCOutput(JNIEnv * env,
jclass c,
jstring fname)
{
jclass booleanClazz = (*env)->FindClass(env, "java/lang/Boolean");
jmethodID getBooleanMethod = (*env)->GetStaticMethodID(env,
booleanClazz,
"getBoolean",
"(Ljava/lang/String;)Z");
jstring property = (*env)->NewStringUTF(env,
"gemfire.disableLowLevelIORedirection");
jboolean disableIORedirect = (*env)->CallStaticBooleanMethod(env,
booleanClazz,
getBooleanMethod,
property);
(*env)->DeleteLocalRef(env, property);
(*env)->DeleteLocalRef(env, booleanClazz);
if( disableIORedirect == JNI_FALSE ) {
const char *fnameStr = (*env)->GetStringUTFChars(env, fname, NULL);
if (fnameStr != NULL) {
#if defined(FLG_LINUX_UNIX)
redirectFd(1, fnameStr);
redirectFd(2, fnameStr);
#else
freopen(fnameStr, "a+", stdout);
freopen(fnameStr, "a+", stderr);
#endif
(*env)->ReleaseStringUTFChars(env, fname, fnameStr);
}
}
}
/*
* Class: com_gemstone_gemfire_internal_OSProcess
* Method: registerSigQuitHandler
*/
JNIEXPORT void JNICALL
Java_com_gemstone_gemfire_internal_OSProcess_registerSigQuitHandler(JNIEnv * env,
jclass c)
{
#ifdef FLG_UNIX
HostInstallSigQuitHandler(/*env*/);
#endif
}
| {
"content_hash": "4babfafb6b407bb416e2936a2bfe9834",
"timestamp": "",
"source": "github",
"line_count": 787,
"max_line_length": 94,
"avg_line_length": 26.681067344345617,
"alnum_prop": 0.5934374702352605,
"repo_name": "SnappyDataInc/snappy-store",
"id": "130d56f2df11f9e932755c0764b0d05b411ea506",
"size": "21663",
"binary": false,
"copies": "3",
"ref": "refs/heads/snappy/master",
"path": "gemfire-core/src/main/java/com/gemstone/gemfire/internal/OSProcess.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AGS Script",
"bytes": "90653"
},
{
"name": "Assembly",
"bytes": "738033"
},
{
"name": "Batchfile",
"bytes": "23509"
},
{
"name": "C",
"bytes": "298655"
},
{
"name": "C#",
"bytes": "1338285"
},
{
"name": "C++",
"bytes": "784695"
},
{
"name": "CSS",
"bytes": "54987"
},
{
"name": "Gnuplot",
"bytes": "3125"
},
{
"name": "HTML",
"bytes": "8595527"
},
{
"name": "Java",
"bytes": "117988027"
},
{
"name": "JavaScript",
"bytes": "33027"
},
{
"name": "Makefile",
"bytes": "9359"
},
{
"name": "Mathematica",
"bytes": "92588"
},
{
"name": "PHP",
"bytes": "869892"
},
{
"name": "PLSQL",
"bytes": "80858"
},
{
"name": "PLpgSQL",
"bytes": "205179"
},
{
"name": "Pascal",
"bytes": "3707"
},
{
"name": "Pawn",
"bytes": "93609"
},
{
"name": "Perl",
"bytes": "196843"
},
{
"name": "Python",
"bytes": "131049"
},
{
"name": "Ruby",
"bytes": "26443"
},
{
"name": "SQLPL",
"bytes": "47702"
},
{
"name": "Shell",
"bytes": "550962"
},
{
"name": "SourcePawn",
"bytes": "15059"
},
{
"name": "TSQL",
"bytes": "5461819"
},
{
"name": "Thrift",
"bytes": "55057"
},
{
"name": "XSLT",
"bytes": "67112"
},
{
"name": "sed",
"bytes": "6411"
}
],
"symlink_target": ""
} |
/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/value_index_factory.hpp"
#include <caf/optional.hpp>
#include "vast/attribute.hpp"
#include "vast/base.hpp"
#include "vast/concept/parseable/numeric/integral.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/base.hpp"
#include "vast/detail/type_traits.hpp"
#include "vast/type.hpp"
#include "vast/value_index.hpp"
namespace vast {
namespace {
template <class T>
size_t extract_max_size(const T& x, size_t default_value = 1024) {
if (auto a = extract_attribute(x, "max_size"))
if (auto max_size = to<size_t>(*a))
return *max_size;
return default_value;
}
template <class T>
optional<base> parse_base(const T& x) {
if (auto a = extract_attribute(x, "base")) {
if (auto b = to<base>(*a))
return *b;
return {};
}
// Use base 8 by default, as it yields the best performance on average for
// VAST's indexing.
return base::uniform<64>(8);
}
template <class T>
value_index_ptr make(type x) {
return std::make_unique<T>(std::move(x));
}
template <class T>
value_index_ptr make_arithmetic(type x) {
static_assert(detail::is_any_v<T, integer_type, count_type, real_type,
timespan_type, timestamp_type>);
using concrete_data = type_to_data<T>;
using value_index_type = arithmetic_index<concrete_data>;
if (auto base = parse_base(x))
return std::make_unique<value_index_type>(std::move(x), std::move(*base));
return nullptr;
}
template <class T, class Index>
auto add_value_index_factory() {
return factory<value_index>::add(T{}, make<Index>);
}
template <class T>
auto add_arithmetic_index_factory() {
return factory<value_index>::add(T{}, make_arithmetic<T>);
}
template <class T, class Index>
auto add_container_index_factory() {
static auto f = [](type x) -> value_index_ptr {
auto max_size = extract_max_size(x);
return std::make_unique<Index>(std::move(x), max_size);
};
return factory<value_index>::add(T{}, f);
}
} // namespace <anonymous>
void factory_traits<value_index>::initialize() {
add_value_index_factory<boolean_type, arithmetic_index<boolean>>();
add_arithmetic_index_factory<integer_type>();
add_arithmetic_index_factory<count_type>();
add_arithmetic_index_factory<real_type>();
add_arithmetic_index_factory<timespan_type>();
add_arithmetic_index_factory<timestamp_type>();
add_value_index_factory<address_type, address_index>();
add_value_index_factory<subnet_type, subnet_index>();
add_value_index_factory<port_type, port_index>();
add_container_index_factory<string_type, string_index>();
add_container_index_factory<vector_type, sequence_index>();
add_container_index_factory<set_type, sequence_index>();
}
factory_traits<value_index>::key_type
factory_traits<value_index>::key(const type& t) {
auto f = [&](const auto& x) {
using concrete_type = std::decay_t<decltype(x)>;
if constexpr (std::is_same_v<concrete_type, alias_type>) {
return key(x.value_type);
} else {
static type instance = concrete_type{};
return instance;
}
};
return caf::visit(f, t);
}
} // namespace vast
| {
"content_hash": "bb74c8a81225d534e2cfd9d7f863ee30",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 80,
"avg_line_length": 35.043103448275865,
"alnum_prop": 0.5904059040590406,
"repo_name": "mavam/vast",
"id": "8f99c3680c7ce5b6e810ee9b7844d1771d5cfd8f",
"size": "4065",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libvast/src/value_index_factory.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Bro",
"bytes": "279"
},
{
"name": "C",
"bytes": "167174"
},
{
"name": "C++",
"bytes": "1403958"
},
{
"name": "CMake",
"bytes": "26662"
},
{
"name": "Gnuplot",
"bytes": "423"
},
{
"name": "Python",
"bytes": "11785"
},
{
"name": "Shell",
"bytes": "12612"
}
],
"symlink_target": ""
} |
namespace spvtools {
namespace opt {
namespace {
const uint32_t kCopyObjectOperandInIdx = 0;
const uint32_t kTypePointerStorageClassInIdx = 0;
const uint32_t kTypePointerTypeIdInIdx = 1;
} // namespace
bool MemPass::IsBaseTargetType(const Instruction* typeInst) const {
switch (typeInst->opcode()) {
case SpvOpTypeInt:
case SpvOpTypeFloat:
case SpvOpTypeBool:
case SpvOpTypeVector:
case SpvOpTypeMatrix:
case SpvOpTypeImage:
case SpvOpTypeSampler:
case SpvOpTypeSampledImage:
case SpvOpTypePointer:
return true;
default:
break;
}
return false;
}
bool MemPass::IsTargetType(const Instruction* typeInst) const {
if (IsBaseTargetType(typeInst)) return true;
if (typeInst->opcode() == SpvOpTypeArray) {
if (!IsTargetType(
get_def_use_mgr()->GetDef(typeInst->GetSingleWordOperand(1)))) {
return false;
}
return true;
}
if (typeInst->opcode() != SpvOpTypeStruct) return false;
// All struct members must be math type
return typeInst->WhileEachInId([this](const uint32_t* tid) {
Instruction* compTypeInst = get_def_use_mgr()->GetDef(*tid);
if (!IsTargetType(compTypeInst)) return false;
return true;
});
}
bool MemPass::IsNonPtrAccessChain(const SpvOp opcode) const {
return opcode == SpvOpAccessChain || opcode == SpvOpInBoundsAccessChain;
}
bool MemPass::IsPtr(uint32_t ptrId) {
uint32_t varId = ptrId;
Instruction* ptrInst = get_def_use_mgr()->GetDef(varId);
while (ptrInst->opcode() == SpvOpCopyObject) {
varId = ptrInst->GetSingleWordInOperand(kCopyObjectOperandInIdx);
ptrInst = get_def_use_mgr()->GetDef(varId);
}
const SpvOp op = ptrInst->opcode();
if (op == SpvOpVariable || IsNonPtrAccessChain(op)) return true;
const uint32_t varTypeId = ptrInst->type_id();
if (varTypeId == 0) return false;
const Instruction* varTypeInst = get_def_use_mgr()->GetDef(varTypeId);
return varTypeInst->opcode() == SpvOpTypePointer;
}
Instruction* MemPass::GetPtr(uint32_t ptrId, uint32_t* varId) {
*varId = ptrId;
Instruction* ptrInst = get_def_use_mgr()->GetDef(*varId);
Instruction* varInst;
if (ptrInst->opcode() == SpvOpConstantNull) {
*varId = 0;
return ptrInst;
}
if (ptrInst->opcode() != SpvOpVariable &&
ptrInst->opcode() != SpvOpFunctionParameter) {
varInst = ptrInst->GetBaseAddress();
} else {
varInst = ptrInst;
}
if (varInst->opcode() == SpvOpVariable) {
*varId = varInst->result_id();
} else {
*varId = 0;
}
while (ptrInst->opcode() == SpvOpCopyObject) {
uint32_t temp = ptrInst->GetSingleWordInOperand(0);
ptrInst = get_def_use_mgr()->GetDef(temp);
}
return ptrInst;
}
Instruction* MemPass::GetPtr(Instruction* ip, uint32_t* varId) {
assert(ip->opcode() == SpvOpStore || ip->opcode() == SpvOpLoad ||
ip->opcode() == SpvOpImageTexelPointer || ip->IsAtomicWithLoad());
// All of these opcode place the pointer in position 0.
const uint32_t ptrId = ip->GetSingleWordInOperand(0);
return GetPtr(ptrId, varId);
}
bool MemPass::HasOnlyNamesAndDecorates(uint32_t id) const {
return get_def_use_mgr()->WhileEachUser(id, [this](Instruction* user) {
SpvOp op = user->opcode();
if (op != SpvOpName && !IsNonTypeDecorate(op)) {
return false;
}
return true;
});
}
void MemPass::KillAllInsts(BasicBlock* bp, bool killLabel) {
bp->KillAllInsts(killLabel);
}
bool MemPass::HasLoads(uint32_t varId) const {
return !get_def_use_mgr()->WhileEachUser(varId, [this](Instruction* user) {
SpvOp op = user->opcode();
// TODO(): The following is slightly conservative. Could be
// better handling of non-store/name.
if (IsNonPtrAccessChain(op) || op == SpvOpCopyObject) {
if (HasLoads(user->result_id())) {
return false;
}
} else if (op != SpvOpStore && op != SpvOpName && !IsNonTypeDecorate(op)) {
return false;
}
return true;
});
}
bool MemPass::IsLiveVar(uint32_t varId) const {
const Instruction* varInst = get_def_use_mgr()->GetDef(varId);
// assume live if not a variable eg. function parameter
if (varInst->opcode() != SpvOpVariable) return true;
// non-function scope vars are live
const uint32_t varTypeId = varInst->type_id();
const Instruction* varTypeInst = get_def_use_mgr()->GetDef(varTypeId);
if (varTypeInst->GetSingleWordInOperand(kTypePointerStorageClassInIdx) !=
SpvStorageClassFunction)
return true;
// test if variable is loaded from
return HasLoads(varId);
}
void MemPass::AddStores(uint32_t ptr_id, std::queue<Instruction*>* insts) {
get_def_use_mgr()->ForEachUser(ptr_id, [this, insts](Instruction* user) {
SpvOp op = user->opcode();
if (IsNonPtrAccessChain(op)) {
AddStores(user->result_id(), insts);
} else if (op == SpvOpStore) {
insts->push(user);
}
});
}
void MemPass::DCEInst(Instruction* inst,
const std::function<void(Instruction*)>& call_back) {
std::queue<Instruction*> deadInsts;
deadInsts.push(inst);
while (!deadInsts.empty()) {
Instruction* di = deadInsts.front();
// Don't delete labels
if (di->opcode() == SpvOpLabel) {
deadInsts.pop();
continue;
}
// Remember operands
std::set<uint32_t> ids;
di->ForEachInId([&ids](uint32_t* iid) { ids.insert(*iid); });
uint32_t varId = 0;
// Remember variable if dead load
if (di->opcode() == SpvOpLoad) (void)GetPtr(di, &varId);
if (call_back) {
call_back(di);
}
context()->KillInst(di);
// For all operands with no remaining uses, add their instruction
// to the dead instruction queue.
for (auto id : ids)
if (HasOnlyNamesAndDecorates(id)) {
Instruction* odi = get_def_use_mgr()->GetDef(id);
if (context()->IsCombinatorInstruction(odi)) deadInsts.push(odi);
}
// if a load was deleted and it was the variable's
// last load, add all its stores to dead queue
if (varId != 0 && !IsLiveVar(varId)) AddStores(varId, &deadInsts);
deadInsts.pop();
}
}
MemPass::MemPass() {}
bool MemPass::HasOnlySupportedRefs(uint32_t varId) {
return get_def_use_mgr()->WhileEachUser(varId, [this](Instruction* user) {
auto dbg_op = user->GetCommonDebugOpcode();
if (dbg_op == CommonDebugInfoDebugDeclare ||
dbg_op == CommonDebugInfoDebugValue) {
return true;
}
SpvOp op = user->opcode();
if (op != SpvOpStore && op != SpvOpLoad && op != SpvOpName &&
!IsNonTypeDecorate(op)) {
return false;
}
return true;
});
}
uint32_t MemPass::Type2Undef(uint32_t type_id) {
const auto uitr = type2undefs_.find(type_id);
if (uitr != type2undefs_.end()) return uitr->second;
const uint32_t undefId = TakeNextId();
if (undefId == 0) {
return 0;
}
std::unique_ptr<Instruction> undef_inst(
new Instruction(context(), SpvOpUndef, type_id, undefId, {}));
get_def_use_mgr()->AnalyzeInstDefUse(&*undef_inst);
get_module()->AddGlobalValue(std::move(undef_inst));
type2undefs_[type_id] = undefId;
return undefId;
}
bool MemPass::IsTargetVar(uint32_t varId) {
if (varId == 0) {
return false;
}
if (seen_non_target_vars_.find(varId) != seen_non_target_vars_.end())
return false;
if (seen_target_vars_.find(varId) != seen_target_vars_.end()) return true;
const Instruction* varInst = get_def_use_mgr()->GetDef(varId);
if (varInst->opcode() != SpvOpVariable) return false;
const uint32_t varTypeId = varInst->type_id();
const Instruction* varTypeInst = get_def_use_mgr()->GetDef(varTypeId);
if (varTypeInst->GetSingleWordInOperand(kTypePointerStorageClassInIdx) !=
SpvStorageClassFunction) {
seen_non_target_vars_.insert(varId);
return false;
}
const uint32_t varPteTypeId =
varTypeInst->GetSingleWordInOperand(kTypePointerTypeIdInIdx);
Instruction* varPteTypeInst = get_def_use_mgr()->GetDef(varPteTypeId);
if (!IsTargetType(varPteTypeInst)) {
seen_non_target_vars_.insert(varId);
return false;
}
seen_target_vars_.insert(varId);
return true;
}
// Remove all |phi| operands coming from unreachable blocks (i.e., blocks not in
// |reachable_blocks|). There are two types of removal that this function can
// perform:
//
// 1- Any operand that comes directly from an unreachable block is completely
// removed. Since the block is unreachable, the edge between the unreachable
// block and the block holding |phi| has been removed.
//
// 2- Any operand that comes via a live block and was defined at an unreachable
// block gets its value replaced with an OpUndef value. Since the argument
// was generated in an unreachable block, it no longer exists, so it cannot
// be referenced. However, since the value does not reach |phi| directly
// from the unreachable block, the operand cannot be removed from |phi|.
// Therefore, we replace the argument value with OpUndef.
//
// For example, in the switch() below, assume that we want to remove the
// argument with value %11 coming from block %41.
//
// [ ... ]
// %41 = OpLabel <--- Unreachable block
// %11 = OpLoad %int %y
// [ ... ]
// OpSelectionMerge %16 None
// OpSwitch %12 %16 10 %13 13 %14 18 %15
// %13 = OpLabel
// OpBranch %16
// %14 = OpLabel
// OpStore %outparm %int_14
// OpBranch %16
// %15 = OpLabel
// OpStore %outparm %int_15
// OpBranch %16
// %16 = OpLabel
// %30 = OpPhi %int %11 %41 %int_42 %13 %11 %14 %11 %15
//
// Since %41 is now an unreachable block, the first operand of |phi| needs to
// be removed completely. But the operands (%11 %14) and (%11 %15) cannot be
// removed because %14 and %15 are reachable blocks. Since %11 no longer exist,
// in those arguments, we replace all references to %11 with an OpUndef value.
// This results in |phi| looking like:
//
// %50 = OpUndef %int
// [ ... ]
// %30 = OpPhi %int %int_42 %13 %50 %14 %50 %15
void MemPass::RemovePhiOperands(
Instruction* phi, const std::unordered_set<BasicBlock*>& reachable_blocks) {
std::vector<Operand> keep_operands;
uint32_t type_id = 0;
// The id of an undefined value we've generated.
uint32_t undef_id = 0;
// Traverse all the operands in |phi|. Build the new operand vector by adding
// all the original operands from |phi| except the unwanted ones.
for (uint32_t i = 0; i < phi->NumOperands();) {
if (i < 2) {
// The first two arguments are always preserved.
keep_operands.push_back(phi->GetOperand(i));
++i;
continue;
}
// The remaining Phi arguments come in pairs. Index 'i' contains the
// variable id, index 'i + 1' is the originating block id.
assert(i % 2 == 0 && i < phi->NumOperands() - 1 &&
"malformed Phi arguments");
BasicBlock* in_block = cfg()->block(phi->GetSingleWordOperand(i + 1));
if (reachable_blocks.find(in_block) == reachable_blocks.end()) {
// If the incoming block is unreachable, remove both operands as this
// means that the |phi| has lost an incoming edge.
i += 2;
continue;
}
// In all other cases, the operand must be kept but may need to be changed.
uint32_t arg_id = phi->GetSingleWordOperand(i);
Instruction* arg_def_instr = get_def_use_mgr()->GetDef(arg_id);
BasicBlock* def_block = context()->get_instr_block(arg_def_instr);
if (def_block &&
reachable_blocks.find(def_block) == reachable_blocks.end()) {
// If the current |phi| argument was defined in an unreachable block, it
// means that this |phi| argument is no longer defined. Replace it with
// |undef_id|.
if (!undef_id) {
type_id = arg_def_instr->type_id();
undef_id = Type2Undef(type_id);
}
keep_operands.push_back(
Operand(spv_operand_type_t::SPV_OPERAND_TYPE_ID, {undef_id}));
} else {
// Otherwise, the argument comes from a reachable block or from no block
// at all (meaning that it was defined in the global section of the
// program). In both cases, keep the argument intact.
keep_operands.push_back(phi->GetOperand(i));
}
keep_operands.push_back(phi->GetOperand(i + 1));
i += 2;
}
context()->ForgetUses(phi);
phi->ReplaceOperands(keep_operands);
context()->AnalyzeUses(phi);
}
void MemPass::RemoveBlock(Function::iterator* bi) {
auto& rm_block = **bi;
// Remove instructions from the block.
rm_block.ForEachInst([&rm_block, this](Instruction* inst) {
// Note that we do not kill the block label instruction here. The label
// instruction is needed to identify the block, which is needed by the
// removal of phi operands.
if (inst != rm_block.GetLabelInst()) {
context()->KillInst(inst);
}
});
// Remove the label instruction last.
auto label = rm_block.GetLabelInst();
context()->KillInst(label);
*bi = bi->Erase();
}
bool MemPass::RemoveUnreachableBlocks(Function* func) {
bool modified = false;
// Mark reachable all blocks reachable from the function's entry block.
std::unordered_set<BasicBlock*> reachable_blocks;
std::unordered_set<BasicBlock*> visited_blocks;
std::queue<BasicBlock*> worklist;
reachable_blocks.insert(func->entry().get());
// Initially mark the function entry point as reachable.
worklist.push(func->entry().get());
auto mark_reachable = [&reachable_blocks, &visited_blocks, &worklist,
this](uint32_t label_id) {
auto successor = cfg()->block(label_id);
if (visited_blocks.count(successor) == 0) {
reachable_blocks.insert(successor);
worklist.push(successor);
visited_blocks.insert(successor);
}
};
// Transitively mark all blocks reachable from the entry as reachable.
while (!worklist.empty()) {
BasicBlock* block = worklist.front();
worklist.pop();
// All the successors of a live block are also live.
static_cast<const BasicBlock*>(block)->ForEachSuccessorLabel(
mark_reachable);
// All the Merge and ContinueTarget blocks of a live block are also live.
block->ForMergeAndContinueLabel(mark_reachable);
}
// Update operands of Phi nodes that reference unreachable blocks.
for (auto& block : *func) {
// If the block is about to be removed, don't bother updating its
// Phi instructions.
if (reachable_blocks.count(&block) == 0) {
continue;
}
// If the block is reachable and has Phi instructions, remove all
// operands from its Phi instructions that reference unreachable blocks.
// If the block has no Phi instructions, this is a no-op.
block.ForEachPhiInst([&reachable_blocks, this](Instruction* phi) {
RemovePhiOperands(phi, reachable_blocks);
});
}
// Erase unreachable blocks.
for (auto ebi = func->begin(); ebi != func->end();) {
if (reachable_blocks.count(&*ebi) == 0) {
RemoveBlock(&ebi);
modified = true;
} else {
++ebi;
}
}
return modified;
}
bool MemPass::CFGCleanup(Function* func) {
bool modified = false;
modified |= RemoveUnreachableBlocks(func);
return modified;
}
void MemPass::CollectTargetVars(Function* func) {
seen_target_vars_.clear();
seen_non_target_vars_.clear();
type2undefs_.clear();
// Collect target (and non-) variable sets. Remove variables with
// non-load/store refs from target variable set
for (auto& blk : *func) {
for (auto& inst : blk) {
switch (inst.opcode()) {
case SpvOpStore:
case SpvOpLoad: {
uint32_t varId;
(void)GetPtr(&inst, &varId);
if (!IsTargetVar(varId)) break;
if (HasOnlySupportedRefs(varId)) break;
seen_non_target_vars_.insert(varId);
seen_target_vars_.erase(varId);
} break;
default:
break;
}
}
}
}
} // namespace opt
} // namespace spvtools
| {
"content_hash": "83444d5d231aa9d3f3584aa7a0dbbb7f",
"timestamp": "",
"source": "github",
"line_count": 481,
"max_line_length": 80,
"avg_line_length": 33.33056133056133,
"alnum_prop": 0.6483283433133733,
"repo_name": "turol/smaaDemo",
"id": "ca4889b7ccdff8b532fa8b4a90ecd55af89c8d67",
"size": "16968",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "foreign/SPIRV-Tools/source/opt/mem_pass.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "2388"
},
{
"name": "Batchfile",
"bytes": "30921"
},
{
"name": "Beef",
"bytes": "70886"
},
{
"name": "C",
"bytes": "7091582"
},
{
"name": "C#",
"bytes": "162562"
},
{
"name": "C++",
"bytes": "41661125"
},
{
"name": "CMake",
"bytes": "426103"
},
{
"name": "CSS",
"bytes": "91427"
},
{
"name": "Clean",
"bytes": "11414"
},
{
"name": "Cuda",
"bytes": "1465"
},
{
"name": "Emacs Lisp",
"bytes": "1654"
},
{
"name": "GDB",
"bytes": "555"
},
{
"name": "GLSL",
"bytes": "4672705"
},
{
"name": "Gnuplot",
"bytes": "424"
},
{
"name": "Go",
"bytes": "729085"
},
{
"name": "HLSL",
"bytes": "2178"
},
{
"name": "HTML",
"bytes": "14644599"
},
{
"name": "JavaScript",
"bytes": "2530778"
},
{
"name": "Jinja",
"bytes": "2972"
},
{
"name": "Kotlin",
"bytes": "1513"
},
{
"name": "Less",
"bytes": "200665"
},
{
"name": "Lua",
"bytes": "141119"
},
{
"name": "M4",
"bytes": "177557"
},
{
"name": "Makefile",
"bytes": "296169"
},
{
"name": "Meson",
"bytes": "629"
},
{
"name": "Objective-C",
"bytes": "18282"
},
{
"name": "Objective-C++",
"bytes": "97773"
},
{
"name": "Python",
"bytes": "573275"
},
{
"name": "Roff",
"bytes": "4568"
},
{
"name": "Ruby",
"bytes": "2885"
},
{
"name": "Shell",
"bytes": "137790"
},
{
"name": "Starlark",
"bytes": "39944"
},
{
"name": "Swift",
"bytes": "2743"
},
{
"name": "Yacc",
"bytes": "171933"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Sample.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sample.iOS")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dc103157-918c-436e-81de-762144e8c160")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "5de77afdfde7a4594be8102b4dbd0def",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 38.69444444444444,
"alnum_prop": 0.7430007178750897,
"repo_name": "gabornemeth/NUnit.XForms",
"id": "d3092e7134022b455fd43b606bae1e33a8d90b74",
"size": "1396",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Samples/Sample.iOS/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "185"
},
{
"name": "C#",
"bytes": "32766"
},
{
"name": "F#",
"bytes": "1577"
},
{
"name": "HTML",
"bytes": "41392"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
Integrated Taxonomic Information System
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a5ca36414aa726fcaff19c686f1d72a1",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.7218045112781954,
"repo_name": "mdoering/backbone",
"id": "36e3bfec5febe6b7307aded03081ddf746a3d624",
"size": "202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Asparagaceae/Hastingsia/Hastingsia bracteosa/ Syn. Hastingsia bracteosa bracteosa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package overlay
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"syscall"
"testing"
"github.com/containerd/containerd/mount"
"github.com/containerd/containerd/snapshot"
"github.com/containerd/containerd/snapshot/storage"
"github.com/containerd/containerd/snapshot/testsuite"
"github.com/containerd/containerd/testutil"
)
func newSnapshotter(ctx context.Context, root string) (snapshot.Snapshotter, func(), error) {
snapshotter, err := NewSnapshotter(root)
if err != nil {
return nil, nil, err
}
return snapshotter, func() {}, nil
}
func TestOverlay(t *testing.T) {
testutil.RequiresRoot(t)
testsuite.SnapshotterSuite(t, "Overlay", newSnapshotter)
}
func TestOverlayMounts(t *testing.T) {
ctx := context.TODO()
root, err := ioutil.TempDir("", "overlay")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(root)
o, _, err := newSnapshotter(ctx, root)
if err != nil {
t.Error(err)
return
}
mounts, err := o.Prepare(ctx, "/tmp/test", "")
if err != nil {
t.Error(err)
return
}
if len(mounts) != 1 {
t.Errorf("should only have 1 mount but received %d", len(mounts))
}
m := mounts[0]
if m.Type != "bind" {
t.Errorf("mount type should be bind but received %q", m.Type)
}
expected := filepath.Join(root, "snapshots", "1", "fs")
if m.Source != expected {
t.Errorf("expected source %q but received %q", expected, m.Source)
}
if m.Options[0] != "rw" {
t.Errorf("expected mount option rw but received %q", m.Options[0])
}
if m.Options[1] != "rbind" {
t.Errorf("expected mount option rbind but received %q", m.Options[1])
}
}
func TestOverlayCommit(t *testing.T) {
ctx := context.TODO()
root, err := ioutil.TempDir("", "overlay")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(root)
o, _, err := newSnapshotter(ctx, root)
if err != nil {
t.Error(err)
return
}
key := "/tmp/test"
mounts, err := o.Prepare(ctx, key, "")
if err != nil {
t.Error(err)
return
}
m := mounts[0]
if err := ioutil.WriteFile(filepath.Join(m.Source, "foo"), []byte("hi"), 0660); err != nil {
t.Error(err)
return
}
if err := o.Commit(ctx, "base", key); err != nil {
t.Error(err)
return
}
}
func TestOverlayOverlayMount(t *testing.T) {
ctx := context.TODO()
root, err := ioutil.TempDir("", "overlay")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(root)
o, _, err := newSnapshotter(ctx, root)
if err != nil {
t.Error(err)
return
}
key := "/tmp/test"
if _, err = o.Prepare(ctx, key, ""); err != nil {
t.Error(err)
return
}
if err := o.Commit(ctx, "base", key); err != nil {
t.Error(err)
return
}
var mounts []mount.Mount
if mounts, err = o.Prepare(ctx, "/tmp/layer2", "base"); err != nil {
t.Error(err)
return
}
if len(mounts) != 1 {
t.Errorf("should only have 1 mount but received %d", len(mounts))
}
m := mounts[0]
if m.Type != "overlay" {
t.Errorf("mount type should be overlay but received %q", m.Type)
}
if m.Source != "overlay" {
t.Errorf("expected source %q but received %q", "overlay", m.Source)
}
var (
bp = getBasePath(ctx, o, root, "/tmp/layer2")
work = "workdir=" + filepath.Join(bp, "work")
upper = "upperdir=" + filepath.Join(bp, "fs")
lower = "lowerdir=" + getParents(ctx, o, root, "/tmp/layer2")[0]
)
for i, v := range []string{
work,
upper,
lower,
} {
if m.Options[i] != v {
t.Errorf("expected %q but received %q", v, m.Options[i])
}
}
}
func getBasePath(ctx context.Context, sn snapshot.Snapshotter, root, key string) string {
o := sn.(*snapshotter)
ctx, t, err := o.ms.TransactionContext(ctx, false)
if err != nil {
panic(err)
}
defer t.Rollback()
s, err := storage.GetSnapshot(ctx, key)
if err != nil {
panic(err)
}
return filepath.Join(root, "snapshots", s.ID)
}
func getParents(ctx context.Context, sn snapshot.Snapshotter, root, key string) []string {
o := sn.(*snapshotter)
ctx, t, err := o.ms.TransactionContext(ctx, false)
if err != nil {
panic(err)
}
defer t.Rollback()
s, err := storage.GetSnapshot(ctx, key)
if err != nil {
panic(err)
}
parents := make([]string, len(s.ParentIDs))
for i := range s.ParentIDs {
parents[i] = filepath.Join(root, "snapshots", s.ParentIDs[i], "fs")
}
return parents
}
func TestOverlayOverlayRead(t *testing.T) {
testutil.RequiresRoot(t)
ctx := context.TODO()
root, err := ioutil.TempDir("", "overlay")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(root)
o, _, err := newSnapshotter(ctx, root)
if err != nil {
t.Error(err)
return
}
key := "/tmp/test"
mounts, err := o.Prepare(ctx, key, "")
if err != nil {
t.Error(err)
return
}
m := mounts[0]
if err := ioutil.WriteFile(filepath.Join(m.Source, "foo"), []byte("hi"), 0660); err != nil {
t.Error(err)
return
}
if err := o.Commit(ctx, "base", key); err != nil {
t.Error(err)
return
}
if mounts, err = o.Prepare(ctx, "/tmp/layer2", "base"); err != nil {
t.Error(err)
return
}
dest := filepath.Join(root, "dest")
if err := os.Mkdir(dest, 0700); err != nil {
t.Error(err)
return
}
if err := mount.MountAll(mounts, dest); err != nil {
t.Error(err)
return
}
defer syscall.Unmount(dest, 0)
data, err := ioutil.ReadFile(filepath.Join(dest, "foo"))
if err != nil {
t.Error(err)
return
}
if e := string(data); e != "hi" {
t.Errorf("expected file contents hi but got %q", e)
return
}
}
func TestOverlayView(t *testing.T) {
ctx := context.TODO()
root, err := ioutil.TempDir("", "overlay")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(root)
o, _, err := newSnapshotter(ctx, root)
if err != nil {
t.Fatal(err)
}
key := "/tmp/base"
mounts, err := o.Prepare(ctx, key, "")
if err != nil {
t.Fatal(err)
}
m := mounts[0]
if err := ioutil.WriteFile(filepath.Join(m.Source, "foo"), []byte("hi"), 0660); err != nil {
t.Fatal(err)
}
if err := o.Commit(ctx, "base", key); err != nil {
t.Fatal(err)
}
key = "/tmp/top"
_, err = o.Prepare(ctx, key, "base")
if err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(filepath.Join(getParents(ctx, o, root, "/tmp/top")[0], "foo"), []byte("hi, again"), 0660); err != nil {
t.Fatal(err)
}
if err := o.Commit(ctx, "top", key); err != nil {
t.Fatal(err)
}
mounts, err = o.View(ctx, "/tmp/view1", "base")
if err != nil {
t.Fatal(err)
}
if len(mounts) != 1 {
t.Fatalf("should only have 1 mount but received %d", len(mounts))
}
m = mounts[0]
if m.Type != "bind" {
t.Errorf("mount type should be bind but received %q", m.Type)
}
expected := getParents(ctx, o, root, "/tmp/view1")[0]
if m.Source != expected {
t.Errorf("expected source %q but received %q", expected, m.Source)
}
if m.Options[0] != "ro" {
t.Errorf("expected mount option ro but received %q", m.Options[0])
}
if m.Options[1] != "rbind" {
t.Errorf("expected mount option rbind but received %q", m.Options[1])
}
mounts, err = o.View(ctx, "/tmp/view2", "top")
if err != nil {
t.Fatal(err)
}
if len(mounts) != 1 {
t.Fatalf("should only have 1 mount but received %d", len(mounts))
}
m = mounts[0]
if m.Type != "overlay" {
t.Errorf("mount type should be overlay but received %q", m.Type)
}
if m.Source != "overlay" {
t.Errorf("mount source should be overlay but received %q", m.Source)
}
if len(m.Options) != 1 {
t.Errorf("expected 1 mount option but got %d", len(m.Options))
}
lowers := getParents(ctx, o, root, "/tmp/view2")
expected = fmt.Sprintf("lowerdir=%s:%s", lowers[0], lowers[1])
if m.Options[0] != expected {
t.Errorf("expected option %q but received %q", expected, m.Options[0])
}
}
| {
"content_hash": "8cc5f64d0ae151cc9c166bdd63c18728",
"timestamp": "",
"source": "github",
"line_count": 318,
"max_line_length": 131,
"avg_line_length": 23.70125786163522,
"alnum_prop": 0.6213347485737031,
"repo_name": "chanezon/containerd",
"id": "5b47f07aefee55b2078ec79e7ee95b9361a402d8",
"size": "7554",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "snapshot/overlay/overlay_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "1067316"
},
{
"name": "Makefile",
"bytes": "7917"
},
{
"name": "Protocol Buffer",
"bytes": "47057"
}
],
"symlink_target": ""
} |
package fm.audiobox.core.exceptions;
import com.google.api.client.auth.oauth2.TokenErrorResponse;
import com.google.api.client.auth.oauth2.TokenResponseException;
import com.google.api.client.http.HttpResponse;
/**
* This exception is thrown when the OAuth2 token and/or the refresh token
* have been invalidated or they are expired.
* <p>
* When this exception is thrown a new user authentication is required.
* <p>
* It is also highly recommended to invalidate/delete/clear any stored
* credential.
*/
public class AuthorizationException extends RemoteMessageException {
/**
* Instantiates a new Authorization exception.
*
* @param response the response that thrown the exception
*/
public AuthorizationException(HttpResponse response) {
super( response );
}
/**
* Instantiates a new Authorization exception.
*
* @param tokenException the TokenResponseException
*/
public AuthorizationException(TokenResponseException tokenException) {
this( AuthorizationException.buildErrors( tokenException.getDetails() ), tokenException.getStatusCode() );
}
/**
* Instantiates a new Authorization exception.
*
* @param errors the errors
* @param statusCode the status code
*/
public AuthorizationException(Errors errors, int statusCode) {
super( errors, statusCode );
}
/**
* Build errors.
*
* @param rsp the rsp
*
* @return the errors
*/
private static Errors buildErrors(TokenErrorResponse rsp) {
Errors e = new Errors();
e.set( rsp.getError(), rsp.getErrorDescription() );
return e;
}
}
| {
"content_hash": "9ac67890230db263c9c5b8cd3bd007f6",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 110,
"avg_line_length": 24.753846153846155,
"alnum_prop": 0.7153511497824736,
"repo_name": "icoretech/audiobox-jlib",
"id": "304fbc5790ac800ed779703209ad78772ee3b554",
"size": "2209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/fm/audiobox/core/exceptions/AuthorizationException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "373902"
},
{
"name": "Shell",
"bytes": "1594"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "225788446cda0cb144932891b391c60b",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "b40fcada6768d1d26416ed50abb2c8fe77ff4e7e",
"size": "174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Dryopteridaceae/Lastrea/Lastrea radicans/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="no-js ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="no-js ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="no-js ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!-->
<html lang="en" class="no-js">
<!--<![endif]-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Blog - Infinite Colour</title>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/modernizr-1.6.min.js" type="text/javascript"></script>
<!--Superfish-->
<link rel="stylesheet" type="text/css" href="css/superfish.css" media="screen" />
<script type="text/javascript" src="js/hoverIntent.js"></script>
<script type="text/javascript" src="js/superfish.js"></script>
<!--custtom script-->
<script src="js/custom.js" type="text/javascript"></script>
<!--Color Picker-->
<script type="text/javascript" src="js/colorpicker.js"></script>
<script type="text/javascript" src="js/eye.js"></script>
<script type="text/javascript" src="js/utils.js"></script>
<script type="text/javascript" src="js/layout20b9.js?ver=1.0.2"></script>
<link rel="stylesheet" type="text/css" href="css/colorpicker.css" media="screen" />
<!--Style and Layout-->
<link rel="stylesheet" type="text/css" href="css/reset.css" media="screen" />
<link rel="stylesheet" type="text/css" href="css/style.css" media="screen" />
<!--Nivo Slider Slideshow-->
<link rel="stylesheet" type="text/css" href="css/nivo-slider.css" media="screen" />
<script type="text/javascript" src="js/jquery.nivo.slider.js"></script>
<!--carouFredSel-->
<script type="text/javascript" src="js/jquery.carouFredSel-3.2.1.js"></script>
<!--Accordion-->
<script type="text/javascript" src="js/accordion/chili-1.7.pack.js"></script>
<script type="text/javascript" src="js/accordion/jquery.easing.js"></script>
<script type="text/javascript" src="js/accordion/jquery.dimensions.js"></script>
<script type="text/javascript" src="js/accordion/jquery.accordion.js"></script>
<script type="text/javascript">
jQuery().ready(function(){
// simple accordion
/*jQuery('#accordion').accordion();*/
jQuery('#accordion_click').accordion({
/*animated: 'bounceslide'*/
animated: 'easeslide',
autoheight: true
});
jQuery('#accordion_hover').accordion({
/*animated: 'bounceslide'*/
event: 'mouseover',
animated: 'bounceslide',
autoheight: true
});
});
</script>
</head>
<body id="inner-page">
<div class="color_picker">
<h2>Background</h2>
<div class="colorSelector">
<div style="background-color: #071121; width:120px; background-image:none;"></div>
</div>
<h2>Navigation</h2>
<div class="colorSelector2">
<div style="background-color: #6b737a; width:120px; background-image:none;"></div>
</div>
</div>
<!-- end color_picker-->
<!--/end #color_picker-->
<section id="top_container">
<div class="top_gradient_bg">
<header id="header" class="center">
<nav role="navigation" class="navBox">
<div class="subtle_border">
<h1 id="logo"><a href="index-2.html">Infinite</a></h1>
<ul class="sf-menu">
<li><a href="index-2.html">Home</a></li>
<li><a href="#">Features</a>
<ul>
<li><a href="#">Homepage Slideshows</a>
<ul>
<li><a href="index-2.html">Nivo Slider</a></li>
<li><a href="index2.html">Peacemaker 3D</a></li>
</ul>
</li>
<li><a href="typography.html">Typography Elements</a></li>
<li><a href="tab_accordion.html">Tab, Accordion</a></li>
<li><a href="#">Layout Options</a>
<ul>
<li><a href="left_sidebar.html">Left Sidebar</a></li>
<li><a href="right_sidebar.html">Right Sidebar</a></li>
<li><a href="full_width.html">Full Width</a></li>
<li><a href="layout_columns.html">Layout Columns</a></li>
</ul>
</li>
<li><a href="testimonial_news.html">Testimonials, News</a></li>
<li><a href="footer_link_lists.html">Footer Link Lists</a></li>
</ul>
</li>
<li><a href="#">Pages</a>
<ul>
<li><a href="about_us.html">About Us</a></li>
<li><a href="#">Portfolio</a>
<ul>
<li><a href="two_columns.html">Two Columns</a></li>
<li><a href="three_columns.html">Three Columns</a></li>
<li><a href="four_columns.html">Four Columns</a></li>
<li><a href="filterable_portfolio.html">Filterable Portfolio</a></li>
<li><a href="project_details.html">Portfolio Details Page</a></li>
</ul>
</li>
<li><a href="services.html">Services</a></li>
<li><a href="products.html">Products</a></li>
<li><a href="pricing.html">Pricing</a>
<ul><li><a href="pricing_with_sidebar.html">Pricing w/ Sidebar</a></li></ul>
</li>
<li><a href="site_map.html">Site Map</a></li>
<li><a href="testimonials.html">Testimonials</a></li>
<li><a href="404.html">404 Error Page</a></li>
</ul>
</li>
<li><a href="blog.html">Blog</a>
<ul>
<li><a href="single.html">Single Page</a></li>
</ul>
</li>
<li><a href="contact.html">Contact</a></li>
<li class="search_icon"> <a href="#">Search</a>
<div>
<form action="#" method="get">
<input type="text" name="s" id="s" value="Search..." onblur="if (this.value == ''){this.value = 'Search...'; }" onfocus="if (this.value == 'Search...') {this.value = '';}" />
</form>
</div>
</li>
</ul><!-- end ul-->
</div>
</nav>
<!-- end nav-->
</header>
<!-- end #header-->
</div>
<!-- end .top_gradient_bg-->
</section>
<!-- end #top_container-->
<section id="main">
<div class="intro_wrap">
<div class="center">
<h2 class="page_title">Blog</h2>
</div>
</div>
<!-- end .intro_wrap-->
<div class="center">
<section id="content" class="float_left">
<div class="breadcrumbs">
<ul>
<li><a href="index-2.html">Home</a> /</li>
<li class="current_page">Blog</li>
</ul>
</div><!-- end .breadcrumbs-->
<section id="blog">
<article class="entry">
<h3><a href="#">Morbi varius, enim dapibus porttitor rutrum, tellus tellus hendrerit lorem, ac sodales est quam vitae ipsum. Cras lobortis</a> </h3>
<div class="meta"><span class="date_post">March 18th, 2010</span><span class="author"><a href="#">John Doe</a></span><span class="comment"><a href="#">34</a></span><span class="tag"><a href="#">Tutorials</a>, <a href="#">Design</a></span></div>
<p><img src="images/blog_img_1.jpg" alt="Image" /></p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer varius, metus nec sodales rhoncus, lorem sapien pretium enim, non pharetra libero purus quis est. In eleifend, purus ac malesuada rutrum, lorem lorem gravida est, nec congue odio augue id tellus. Nunc lacinia consectetur aliquet. Nullam ac lacus non turpis interdum tincidunt sit amet ut diam. Curabitur pretium neque posuere magna gravida ac tincidunt massa elementum. Integer justo nunc, sollicitudin sit amet tempus vel, malesuada accumsan neque. Morbi varius, enim dapibus porttitor rutrum, tellus tellus hendrerit lorem, ac sodales est quam vitae ipsum. </p>
<p><a href="single.html" class="button">Continue Reading</a></p>
</article><!-- end article-->
<article class="entry">
<h3><a href="#">Integer varius, metus nec sodales rhoncus</a> </h3>
<div class="meta"><span class="date_post">March 18th, 2010</span><span class="author"><a href="#">John Doe</a></span><span class="comment"><a href="#">34</a></span><span class="tag"><a href="#">Tutorials</a>, <a href="#">Design</a></span></div>
<p><img src="images/blog_img_1.jpg" alt="Image" /></p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer varius, metus nec sodales rhoncus, lorem sapien pretium enim, non pharetra libero purus quis est. In eleifend, purus ac malesuada rutrum, lorem lorem gravida est, nec congue odio augue id tellus. Nunc lacinia consectetur aliquet. Nullam ac lacus non turpis interdum tincidunt sit amet ut diam. Curabitur pretium neque posuere magna gravida ac tincidunt massa elementum. Integer justo nunc, sollicitudin sit amet tempus vel, malesuada accumsan neque. Morbi varius, enim dapibus porttitor rutrum, tellus tellus hendrerit lorem, ac sodales est quam vitae ipsum. </p>
<p><a href="single.html" class="button">Continue Reading</a></p>
</article><!-- end article-->
</section>
</section>
<!-- end #content-->
<section id="sidebar" class="float_right">
<div class="widgetwrap">
<h5>Categories</h5>
<ul class="categories">
<li><a href="#">Freebies</a> <span>(21)</span></li>
<li><a href="#">Tutorials</a> <span>(56)</span></li>
<li><a href="#">Inspirations</a> <span>(11)</span></li>
<li><a href="#">Resources</a> <span>(34)</span></li>
</ul>
</div>
<!-- end .widgetwrap-->
<div class="widgetwrap">
<h5>Tags</h5>
<ul class="tags_list">
<li><a href="#">css</a></li>
<li><a href="#">html5</a></li>
<li><a href="#">jquery</a></li>
<li><a href="#">standard</a></li>
<li><a href="#">seo</a></li>
<li><a href="#">business</a></li>
<li><a href="#">photoshop</a></li>
</ul>
</div>
<!-- end .widgetwrap-->
<div class="widgetwrap">
<h5>Arbitrary Text or HTML</h5>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus leo ante, consectetur sit amet vulputate vel, dapibus sit amet lectus. Etiam varius dui eget lorem elementum eget mattis sapien interdum. In hac habitasse plateas.</p>
</div><!-- end .widgetwrap-->
<div class="widgetwrap ads">
<h5>Advertisement</h5>
<ul>
<li><a href="#"><img src="images/gr_125x125_v1.gif" alt="Image" /></a></li>
<li class="last"><a href="#"><img src="images/tf_125x125_v2.gif" alt="Image" /></a></li>
<li><a href="#"><img src="images/gr_125x125_v1.gif" alt="Image" /></a></li>
<li class="last"><a href="#"><img src="images/tf_125x125_v2.gif" alt="Image" /></a></li>
</ul>
</div>
<!-- end .widgetwrap-->
<div class="widgetwrap recent_tweet">
<h5>Recent Tweet</h5>
<ul id="twitter_update_list" class="tweet">
<li> </li>
</ul>
<p><a href="#" class="button">Follow on Twitter</a></p>
</div>
<!-- end .widgetwrap-->
</section>
<!-- end #sidebar-->
</div>
<!-- end .center-->
<section class="sub_content">
<div class="top_shadow">
<div class="columns">
<div class="center">
<div class="one_fifth">
<h5>Pages</h5>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</div>
<!-- end .one_fith -->
<div class="one_fifth">
<h5>Worth Links</h5>
<ul>
<li><a href="#">HTML5 Awesome</a></li>
<li><a href="#">Web Designer Aid</a></li>
<li><a href="#">FBrushes</a></li>
<li><a href="#">Smashing Magazine</a></li>
<li><a href="#">Themeforest</a></li>
<li><a href="#">Six Revisions</a></li>
</ul>
</div>
<!-- end .one_fith -->
<div class="one_fifth">
<h5>Categories</h5>
<ul>
<li><a href="#">Featured</a></li>
<li><a href="#">Web Design</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Business</a></li>
<li><a href="#">Startup</a></li>
<li><a href="#">Uncategorized</a></li>
</ul>
</div>
<!-- end .one_fith -->
<div class="one_fifth">
<h5>Archives</h5>
<ul>
<li><a href="#">March 2011</a></li>
<li><a href="#">February 2011</a></li>
<li><a href="#">January 2011</a></li>
<li><a href="#">December 2010</a></li>
<li><a href="#">November 2010</a></li>
<li><a href="#">October 2010</a></li>
</ul>
</div>
<!-- end .one_fith -->
<div class="one_fifth last">
<h5>Blog Roll</h5>
<ul>
<li><a href="#">Login</a></li>
<li><a href="#">Documentation</a></li>
<li><a href="#">WordPress Blog</a></li>
<li><a href="#">Themes</a></li>
<li><a href="#">Support Forum</a></li>
<li><a href="#">WordPress Planet</a></li>
</ul>
</div>
<!-- end .one_fith -->
</div>
<!-- end .center -->
</div>
<!-- end .columns -->
</div>
<!-- end .top_shadow -->
</section>
<!--end .sub_content -->
</section>
<!-- end #main-->
<footer id="footer" class="clearfix">
<div class="shadow">
<div class="center">
<p>© Copyright 2011. All Rights Reserved. Created by Joefrey a <em>Curator</em> of <a href="http://html5awesome.com/">HTML5 Awesome</a></p>
</div>
</div>
</footer>
<!-- twitter start script -->
<script type="text/javascript" src="../../../../twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/html5awesome.json?callback=twitterCallback2&count=4"></script>
</body>
</html>
| {
"content_hash": "a33a85fb596b35d030fff779c832d9b9",
"timestamp": "",
"source": "github",
"line_count": 339,
"max_line_length": 644,
"avg_line_length": 42.958702064896755,
"alnum_prop": 0.532307903591293,
"repo_name": "vinayck/Project-1-Vantage",
"id": "09e4e225c4de56ae854c11798dae658adaa81aa3",
"size": "14563",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "fancybox/blog.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "120346"
},
{
"name": "JavaScript",
"bytes": "167864"
}
],
"symlink_target": ""
} |
<!doctype html>
<div style="position: fixed; height: 5000px; width: 100px; background: lightblue; will-change: transform"></div>
<div style="position: fixed; top: 25px; height: 100px; width: 100px; background: lightgray"></div>
<div id="foo" style="position: fixed; top: 50px; height: 100px; width: 100px; background: lightgray"></div>
<script src="../../resources/run-after-layout-and-paint.js"></script>
<script>
// This test verifies that a repaint request for a squashed layer that is position:fixed into another position: fixed layer
// issue the correct paint invalidations even with the window scrolled.
if (window.testRunner) {
testRunner.dumpAsText();
testRunner.waitUntilDone();
}
runAfterLayoutAndPaint(function() {
if (window.internals)
internals.startTrackingRepaints(document);
var output = '';
document.getElementById("foo").style.background = 'red';
if (window.internals)
output += internals.layerTreeAsText(document, internals.LAYER_TREE_INCLUDES_INVALIDATIONS) + ' ';
if (window.internals)
internals.stopTrackingRepaints(document);
scrollTo(0, 50);
if (window.internals)
internals.startTrackingRepaints(document);
document.getElementById("foo").style.background = 'blue';
if (window.internals)
output += internals.layerTreeAsText(document, internals.LAYER_TREE_INCLUDES_INVALIDATIONS);
if (window.internals)
internals.stopTrackingRepaints(document);
testRunner.setCustomTextOutput(output);
if (window.testRunner)
testRunner.notifyDone();
});
</script> | {
"content_hash": "bda78c9a4c04ec5458d4f55aacec4e78",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 123,
"avg_line_length": 34.255319148936174,
"alnum_prop": 0.7062111801242236,
"repo_name": "chromium/chromium",
"id": "ec5dbadea6106a7e9178a8909e73c90e1643e94f",
"size": "1610",
"binary": false,
"copies": "9",
"ref": "refs/heads/main",
"path": "third_party/blink/web_tests/compositing/squashing/squash-paint-invalidation-fixed-position.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package org.apache.flink.table.dataformat.vector.heap;
import org.apache.flink.table.dataformat.SqlTimestamp;
import org.apache.flink.table.dataformat.vector.writable.WritableTimestampVector;
import java.util.Arrays;
import static org.apache.flink.table.dataformat.SqlTimestamp.fromEpochMillis;
/**
* This class represents a nullable byte column vector.
*/
public class HeapTimestampVector extends AbstractHeapVector implements WritableTimestampVector {
private static final long serialVersionUID = 1L;
private final long[] milliseconds;
private final int[] nanoOfMilliseconds;
public HeapTimestampVector(int len) {
super(len);
this.milliseconds = new long[len];
this.nanoOfMilliseconds = new int[len];
}
@Override
public SqlTimestamp getTimestamp(int i, int precision) {
if (dictionary == null) {
return fromEpochMillis(milliseconds[i], nanoOfMilliseconds[i]);
} else {
return dictionary.decodeToTimestamp(dictionaryIds.vector[i]);
}
}
@Override
public void setTimestamp(int i, SqlTimestamp timestamp) {
milliseconds[i] = timestamp.getMillisecond();
nanoOfMilliseconds[i] = timestamp.getNanoOfMillisecond();
}
@Override
public void fill(SqlTimestamp value) {
Arrays.fill(milliseconds, value.getMillisecond());
Arrays.fill(nanoOfMilliseconds, value.getNanoOfMillisecond());
}
}
| {
"content_hash": "d0683b94d3075d6588150a6437a8d925",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 96,
"avg_line_length": 27.75,
"alnum_prop": 0.7762762762762763,
"repo_name": "bowenli86/flink",
"id": "3fa9947641d6485730902638ca688092859c234d",
"size": "2141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/dataformat/vector/heap/HeapTimestampVector.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4588"
},
{
"name": "CSS",
"bytes": "58146"
},
{
"name": "Clojure",
"bytes": "93329"
},
{
"name": "Dockerfile",
"bytes": "12142"
},
{
"name": "FreeMarker",
"bytes": "25294"
},
{
"name": "HTML",
"bytes": "108358"
},
{
"name": "Java",
"bytes": "51972721"
},
{
"name": "JavaScript",
"bytes": "1829"
},
{
"name": "Makefile",
"bytes": "5134"
},
{
"name": "Python",
"bytes": "1014734"
},
{
"name": "Scala",
"bytes": "13770008"
},
{
"name": "Shell",
"bytes": "513941"
},
{
"name": "TSQL",
"bytes": "123113"
},
{
"name": "TypeScript",
"bytes": "246974"
}
],
"symlink_target": ""
} |
using System;
using Cake.Core.Scripting;
using Cake.Host.Scripting;
namespace Cake.Host.Commands
{
/// <summary>
/// A command that dry runs a build script.
/// </summary>
public sealed class DryRunCommand : ICommand
{
private readonly IScriptRunner _scriptRunner;
private readonly DryRunScriptHost _host;
// Delegate factory used by Autofac.
public delegate DryRunCommand Factory();
public DryRunCommand(IScriptRunner scriptRunner, DryRunScriptHost host)
{
_scriptRunner = scriptRunner;
_host = host;
}
public bool Execute(CakeOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
_scriptRunner.Run(_host, options.Script, options.Arguments);
return true;
}
}
} | {
"content_hash": "32372e778ce41d6301cd88c1d4d536e5",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 79,
"avg_line_length": 26.58823529411765,
"alnum_prop": 0.5951327433628318,
"repo_name": "SharpeRAD/CakeBoss",
"id": "774ad866927d7479682ee2a1af0c04fff1b9700e",
"size": "906",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Cake.Host/Commands/DryRunCommand.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "748"
},
{
"name": "C#",
"bytes": "202120"
},
{
"name": "PowerShell",
"bytes": "5811"
}
],
"symlink_target": ""
} |
package com.palantir.nexus.db.pool;
import com.palantir.exception.PalantirSqlException;
import java.sql.Connection;
import java.sql.SQLException;
public abstract class BaseConnectionManager implements ConnectionManager {
@Override
public Connection getConnectionUnchecked() {
try {
return getConnection();
} catch (SQLException e) {
throw PalantirSqlException.create(e);
}
}
@Override
public void closeUnchecked() {
try {
close();
} catch (SQLException e) {
throw PalantirSqlException.create(e);
}
}
@Override
public void initUnchecked() {
try {
init();
} catch (SQLException e) {
throw PalantirSqlException.create(e);
}
}
}
| {
"content_hash": "674f934147ec88f7d54aefa5dda3a98f",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 74,
"avg_line_length": 23.142857142857142,
"alnum_prop": 0.6,
"repo_name": "EvilMcJerkface/atlasdb",
"id": "3fffac773878d933208cedc65b5644c14b8fb656",
"size": "1444",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "commons-db/src/main/java/com/palantir/nexus/db/pool/BaseConnectionManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Clojure",
"bytes": "14990"
},
{
"name": "Dockerfile",
"bytes": "1432"
},
{
"name": "Groovy",
"bytes": "54298"
},
{
"name": "Java",
"bytes": "11033254"
},
{
"name": "Python",
"bytes": "8136"
},
{
"name": "Shell",
"bytes": "28082"
}
],
"symlink_target": ""
} |
int kpaddingHeightView = 17;
@interface ViewController (){
}
- (void)loadData;
- (void) showProgressHUD;
- (void) hideProgessHUD;
@property (nonatomic,strong) NSMutableArray *arrayProductType;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.title = @"demo dynamic control";
self.heightDynamicView.constant = kpaddingHeightView;
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[self loadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - private method
- (void)loadData{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:@"http://www.jsoneditoronline.org/?id=2025f42abb2c5ca7cd6c44aec67b75ca"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30];
NSURLSession *session = [NSURLSession new];
self.arrayProductType = [[NSMutableArray alloc] init];
__weak ViewController *weakSafeSelf = self;
[session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
if (error == nil) {
NSDictionary *responseData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if (responseData) {
NSArray *arrayDict = [responseData objectForKey:@"data"];
if (arrayDict != nil && [arrayDict isKindOfClass:[NSArray class]]) {
for (NSDictionary *dict in arrayDict) {
TypeProductEntity *productEntity = [[ParseManager sharedParseManager] parseTypeProductData:dict];
if (productEntity != nil) {
[weakSafeSelf.arrayProductType addObject:productEntity];
}
}
}
}
}
else{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
message:[NSString stringWithFormat:@"Failed with error code(%d) message:\n%@",(int)error.code, error.localizedDescription]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
}];
[alertController addAction:cancelAction];
}
[MBProgressHUD hideAllHUDsForView:weakSafeSelf.view animated:YES];
}];
}
- (void)showProgressHUD{
}
- (void)hideProgessHUD{
}
#pragma mark - uitextfield delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
if (self.productTypeTextfield == textField) {
NSMutableArray *arrayString = [NSMutableArray array];
for (TypeProductEntity *entity in self.arrayProductType) {
NSString *nameProductType = [entity.name mutableCopy];
[arrayString addObject:nameProductType];
}
[ActionSheetStringPicker showPickerWithTitle:@"Chọn ngành hàng"
rows:arrayString initialSelection:0
doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
}
cancelBlock:^(ActionSheetStringPicker *picker) {
}
origin:nil];
return NO;
}
return NO;
}
@end
| {
"content_hash": "5ac5ae6932c762dc7ce0156416464a71",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 208,
"avg_line_length": 34.833333333333336,
"alnum_prop": 0.5454545454545454,
"repo_name": "khiemnd/demoDynamicView",
"id": "88ee83e11ab0877ed19bb998048e24eb0bff8cd3",
"size": "4406",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demoDynamicView/demoDynamicView/ViewController.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "18249"
},
{
"name": "Ruby",
"bytes": "81"
}
],
"symlink_target": ""
} |
import AddVimeoButton from './AddVimeoButton';
export default AddVimeoButton;
| {
"content_hash": "25e5b29d47ffab6f7127aa69482d6d3b",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 46,
"avg_line_length": 39,
"alnum_prop": 0.8333333333333334,
"repo_name": "CtrHellenicStudies/Commentary",
"id": "50c2bb5c85af2eed820a2cba3c8fd041559d41f5",
"size": "78",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/modules/editor/components/popovers/addTooltip/AddTooltipMenu/AddVimeoButton/index.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "125750"
},
{
"name": "HTML",
"bytes": "306105"
},
{
"name": "JavaScript",
"bytes": "631509"
}
],
"symlink_target": ""
} |
require 'subscribem/constraints/subdomain_required'
Subscribem::Engine.routes.draw do
constraints(Subscribem::Constraints::SubdomainRequired) do
scope :module => 'account' do
root :to => 'dashboard#index', :as => :account_root
get '/sign_in', to: 'sessions#new', as: :sign_in
post '/sign_in', to: 'sessions#create', as: :sessions
get '/sign_up', to: 'users#new', as: :user_sign_up
post '/sign_up', to: 'users#create', as: :do_user_sign_up
end
end
root "dashboard#index"
get '/sign_up', to: 'accounts#new', as: :sign_up
post '/accounts', to: 'accounts#create', as: :accounts
end
| {
"content_hash": "29ca3b9d80998710fd3574af8734cb5e",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 63,
"avg_line_length": 33.473684210526315,
"alnum_prop": 0.6383647798742138,
"repo_name": "gjack/subscribem",
"id": "5450cfaf7b3cc394531902b77d88f91838283a82",
"size": "636",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/routes.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2140"
},
{
"name": "HTML",
"bytes": "6629"
},
{
"name": "JavaScript",
"bytes": "2074"
},
{
"name": "Ruby",
"bytes": "50483"
}
],
"symlink_target": ""
} |
package com.incito.fullwindowsuspend;
import com.incito.fullwindowsuspend.app.MyApplication;
import com.incito.fullwindowsuspend.tools.DisplayUtil;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
private static final String TAG = MyApplication.TAG;
private ListView ll_main;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.ll_main = (ListView)findViewById(R.id.ll_main);
Log.d(TAG, "du.getDensity(): " + DisplayUtil.getDensity());
Log.d(TAG, "du.getDensityDpi(): " + DisplayUtil.getDensityDpi());
Log.d(TAG, "du.getScaledDensity(): " + DisplayUtil.getScaledDensity());
Log.d(TAG, "du.getWidth(): " + DisplayUtil.getWidth());
Log.d(TAG, "du.getHeight(): " + DisplayUtil.getHeight());
Log.d(TAG, "du.getWidthPixels(): " + DisplayUtil.getWidthPixels());
Log.d(TAG, "du.getHeightPixels(): " + DisplayUtil.getHeightPixels());
Log.d(TAG, "du.getXdpi(): " + DisplayUtil.getXdpi());
Log.d(TAG, "du.getYdpi(): " + DisplayUtil.getYdpi());
ArrayAdapter<String> adapater = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
new String[]{
"Open Suspend Button",
"Close Suspend Button"
});
this.ll_main.setAdapter(adapater);
ll_main.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, FloatViewService.class);
switch (position) {
case 0:
//启动FloatViewService
startService(intent);
break;
case 1:
// 销毁悬浮窗
//终止FloatViewService
stopService(intent);
break;
default:
break;
}
}
});
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
}
}
| {
"content_hash": "c113e8a0d93376eafdffa8bf2fc9af3b",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 107,
"avg_line_length": 35.791666666666664,
"alnum_prop": 0.59953434225844,
"repo_name": "sinlov/loqtiAndroidWorkspace",
"id": "31e4b07e093b512e240bbff0d14c5ffa41477561",
"size": "2596",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FullWindowSuspend/src/com/incito/fullwindowsuspend/MainActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "121738"
}
],
"symlink_target": ""
} |
function processData(dbResult, mapping, dataColumns,dataLabels,timeSeries) {
var result = [];
var output = {};
for (var i = 0; i < dbResult.length; i++) {
for (var j = 0; j < mapping.length; j++) {
if (!result[j]) {
result[j] = dbResult[i][mapping[j][dataColumns[0]]]
}
}
}
for (var j = 0; j < mapping.length; j++) {
var tmpObj = {};
tmpObj["label"] = mapping[j]["Series Label"];
tmpObj["data"] = result[j];
output["series" + j] = tmpObj;
}
var chartOptions = require("chart-options.json");
return {0: output, 1: chartOptions};
}
| {
"content_hash": "1f8ccedfb32e71c5e36ca83153523fcd",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 76,
"avg_line_length": 26.24,
"alnum_prop": 0.5137195121951219,
"repo_name": "nuwanw/product-cep",
"id": "7e112ec65e2f3b6309e7c3979844c0abed2856ad",
"size": "656",
"binary": false,
"copies": "18",
"ref": "refs/heads/master",
"path": "modules/distribution/repository/conf/ues/jaggeryapps/portal/modules/flot-charts/pie-chart.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1435876"
},
{
"name": "Java",
"bytes": "482555"
},
{
"name": "JavaScript",
"bytes": "8731045"
},
{
"name": "PHP",
"bytes": "779"
},
{
"name": "Shell",
"bytes": "22327"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tiny editable spreadsheet</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="keywords" content="opensource editable table spreadsheet" />
<link rel="stylesheet" href="../css/table.css" type="text/css" media="screen" />
</head>
<body>
<table class="taboo-table taboo-table-bordered" id="table1"></table>
<table class="taboo-table" id="table2"></table>
<table class="taboo-table" id="table3"></table>
<table class="taboo-table" id="table4"></table>
<script src="../bower_components/lodash/lodash.min.js"></script>
<script src="../bower_components/taboo/taboo.js"></script>
<script src="../taboo-table.js"></script>
<script src="dev.js"></script>
</body>
</html>
| {
"content_hash": "c4ed4c612dc91b92e6e00a194bbfd244",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 84,
"avg_line_length": 41.45,
"alnum_prop": 0.6501809408926418,
"repo_name": "mrmagooey/taboo-table",
"id": "cc6caa3626c912d94f5533809de4f8e462e0eeda",
"size": "829",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dev/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9699"
},
{
"name": "HTML",
"bytes": "1786"
},
{
"name": "JavaScript",
"bytes": "24181"
}
],
"symlink_target": ""
} |
var ALGORITHMS = {
onFinish: undefined,
getMeasure: undefined,
run: function ( triangleBuildFunction, swappingFunction, optimizationFunction, onFinish ) {
ALGORITHMS.onFinish = onFinish;
ALGORITHMS.getMeasure = ALGORITHMS.OPTIMIZATIONMEASURE[ optimizationFunction ].get;
ALGORITHMS.TRIANGLEBUILD[ triangleBuildFunction ].run( swappingFunction );
}
};
| {
"content_hash": "1fe26b6593e8f8808da87f80f12774df",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 92,
"avg_line_length": 28.076923076923077,
"alnum_prop": 0.7835616438356164,
"repo_name": "daign/tripartite.js",
"id": "d3e5f520bfcb0b3b9440cce62f00876e93f91acb",
"size": "365",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/tripartite/algorithms/algorithms.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3409"
},
{
"name": "JavaScript",
"bytes": "141784"
}
],
"symlink_target": ""
} |
package edu.northwestern.bioinformatics.studycalendar.domain.delta;
import edu.northwestern.bioinformatics.studycalendar.domain.PlannedCalendar;
import edu.northwestern.bioinformatics.studycalendar.domain.Population;
import javax.persistence.ManyToOne;
import javax.persistence.JoinColumn;
import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Nataliya Shurupova
*/
@Entity
@DiscriminatorValue(value="popltn")
public class PopulationDelta extends Delta<Population> {
private final Logger log = LoggerFactory.getLogger(getClass());
public PopulationDelta() { }
public PopulationDelta(Population node) { super(node); }
@ManyToOne
@JoinColumn(name = "node_id")
@Override
public Population getNode() {
return super.getNode();
}
}
| {
"content_hash": "c1af65a027a5a5d23f998a72506803c0",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 76,
"avg_line_length": 26.393939393939394,
"alnum_prop": 0.7703788748564868,
"repo_name": "NUBIC/psc-mirror",
"id": "3f3d65ae4819af0800f621cdf680aab1f1109961",
"size": "871",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "domain/src/main/java/edu/northwestern/bioinformatics/studycalendar/domain/delta/PopulationDelta.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Groovy",
"bytes": "169396"
},
{
"name": "Java",
"bytes": "6322244"
},
{
"name": "JavaScript",
"bytes": "809902"
},
{
"name": "Ruby",
"bytes": "372186"
},
{
"name": "Shell",
"bytes": "364"
}
],
"symlink_target": ""
} |
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
| {
"content_hash": "a135b0c296c27fa5e0ff92f0103eb431",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 42,
"avg_line_length": 18.333333333333332,
"alnum_prop": 0.6424242424242425,
"repo_name": "wintersa/node-angular2",
"id": "c365620ca3cbf5d58bc6909714cde80f3e33696d",
"size": "165",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "routes/app.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "319"
},
{
"name": "HTML",
"bytes": "1280"
},
{
"name": "JavaScript",
"bytes": "11966"
},
{
"name": "TypeScript",
"bytes": "22449"
}
],
"symlink_target": ""
} |
package hex.aggregator;
import hex.*;
import hex.pca.PCAModel;
import hex.util.LinearAlgebraUtils;
import water.*;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.NewChunk;
import water.fvec.Vec;
import water.udf.CFuncRef;
import water.util.ArrayUtils;
import water.util.FrameUtils;
import water.util.VecUtils;
import java.util.Arrays;
public class AggregatorModel extends Model<AggregatorModel,AggregatorModel.AggregatorParameters,AggregatorModel.AggregatorOutput> implements Model.ExemplarMembers {
@Override
public ToEigenVec getToEigenVec() {
return LinearAlgebraUtils.toEigen;
}
public static class AggregatorParameters extends Model.Parameters {
public String algoName() { return "Aggregator"; }
public String fullName() { return "Aggregator"; }
public String javaName() { return AggregatorModel.class.getName(); }
@Override public long progressUnits() { return 5 + 2*train().anyVec().nChunks() - 1; } // nChunks maps and nChunks-1 reduces, multiply by two for main job overhead
//public double _radius_scale=1.0;
// public int _max_iterations = 1000; // Max iterations for SVD
public DataInfo.TransformType _transform = DataInfo.TransformType.NORMALIZE; // Data transformation
public PCAModel.PCAParameters.Method _pca_method = PCAModel.PCAParameters.Method.Power; // Method for dimensionality reduction
public int _k = 1; // Number of principal components
public int _target_num_exemplars = 5000;
public double _rel_tol_num_exemplars = 0.5;
public boolean _use_all_factor_levels = false; // When expanding categoricals, should first level be kept or dropped?
public boolean _save_mapping_frame = false;
public int _num_iteration_without_new_exemplar = 500;
}
public static class AggregatorOutput extends Model.Output {
public AggregatorOutput(Aggregator b) { super(b); }
@Override public int nfeatures() { return _output_frame.get().numCols()-1/*counts*/; }
@Override public ModelCategory getModelCategory() { return ModelCategory.Clustering; }
public Key<Frame> _output_frame;
public Key<Frame> _mapping_frame;
}
public Aggregator.Exemplar[] _exemplars;
public long[] _counts;
public Key<Vec> _exemplar_assignment_vec_key;
public AggregatorModel(Key selfKey, AggregatorParameters parms, AggregatorOutput output) { super(selfKey,parms,output); }
@Override
protected Frame predictScoreImpl(Frame orig, Frame adaptedFr, String destination_key, final Job j, boolean computeMetrics, CFuncRef customMetricFunc) {
return null;
}
@Override
protected Futures remove_impl(Futures fs) {
if (_exemplar_assignment_vec_key!=null)
_exemplar_assignment_vec_key.remove();
return super.remove_impl(fs);
}
@Override
public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) {
return null;
}
@Override
protected double[] score0(double[] data, double[] preds) {
return preds;
}
public Frame createFrameOfExemplars(Frame orig, Key destination_key) {
final long[] keep = new long[_exemplars.length];
for (int i=0;i<keep.length;++i)
keep[i]=_exemplars[i].gid;
Vec exAssignment = _exemplar_assignment_vec_key.get();
// preserve the original row order
Vec booleanCol = new MRTask() {
@Override
public void map(Chunk c2) {
for (int i=0;i<keep.length;++i) {
if (keep[i] < c2.start()) continue;
if (keep[i] >= c2.start()+c2._len) continue;
c2.set((int)(keep[i]-c2.start()), 1);
}
}
}.doAll(new Frame(new Vec[]{exAssignment.makeZero()}))._fr.vec(0);
Vec[] vecs = Arrays.copyOf(orig.vecs(), orig.vecs().length+1);
vecs[vecs.length-1] = booleanCol;
Frame ff = new Frame(orig.names(), orig.vecs());
ff.add("predicate", booleanCol);
Frame res = new Frame.DeepSelect().doAll(orig.types(),ff).outputFrame(destination_key, orig.names(), orig.domains());
FrameUtils.shrinkDomainsToObservedSubset(res);
booleanCol.remove();
assert(res.numRows()==_exemplars.length);
Vec cnts = res.anyVec().makeZero();
Vec.Writer vw = cnts.open();
for (int i=0;i<_counts.length;++i)
vw.set(i, _counts[i]);
vw.close();
res.add("counts", cnts);
DKV.put(destination_key, res);
return res;
}
public Frame createMappingOfExemplars(Key destinationKey){
final long[] keep = MemoryManager.malloc8(_exemplars.length);
for (int i=0;i<keep.length;++i)
keep[i]=_exemplars[i].gid;
Vec exAssignment = _exemplar_assignment_vec_key.get();
Arrays.sort(keep);
Vec exemplarAssignment = new MRTask() {
@Override
public void map(Chunk c1, NewChunk nc) {
for (int i = 0; i < c1._len; i++) {
long gid = c1.at8(i);
nc.addNum(ArrayUtils.find(keep, gid));
}
}
}.doAll(Vec.T_NUM,exAssignment).outputFrame().vec(0);
Frame mapping = new Frame(destinationKey,new String[]{"exemplar_assignment"}, new Vec[]{exemplarAssignment});
final long[] uniqueExemplars = new VecUtils.CollectIntegerDomain().doAll(mapping.vecs()).domain();
assert(uniqueExemplars.length==_exemplars.length);
assert(mapping.numRows()==exAssignment.length());
for(long exmp: uniqueExemplars){
assert(exmp <= _exemplars.length);
}
DKV.put(mapping);
return mapping;
}
@Override
public Frame scoreExemplarMembers(Key<Frame> destination_key, final int exemplarIdx) {
Vec booleanCol = new MRTask() {
@Override
public void map(Chunk c, NewChunk nc) {
for (int i=0;i<c._len;++i)
nc.addNum(c.at8(i)==_exemplars[exemplarIdx].gid ? 1 : 0,0);
}
}.doAll(Vec.T_NUM, new Frame(new Vec[]{_exemplar_assignment_vec_key.get()})).outputFrame().anyVec();
Frame orig = _parms.train();
Vec[] vecs = Arrays.copyOf(orig.vecs(), orig.vecs().length+1);
vecs[vecs.length-1] = booleanCol;
Frame ff = new Frame(orig.names(), orig.vecs());
ff.add("predicate", booleanCol);
Frame res = new Frame.DeepSelect().doAll(orig.types(),ff).outputFrame(destination_key, orig.names(), orig.domains());
FrameUtils.shrinkDomainsToObservedSubset(res);
DKV.put(res);
assert(res.numRows()==_counts[exemplarIdx]);
booleanCol.remove();
return res;
}
public void checkConsistency() {
long sum = 0;
for (long l : this._counts) sum += l;
assert (sum == _parms.train().numRows());
final long[] exemplarGIDs = new long[this._counts.length];
for (int i = 0; i < this._exemplars.length; ++i)
exemplarGIDs[i] = this._exemplars[i].gid;
long[] counts = new long[this._exemplars.length];
for (int i = 0; i < _parms.train().numRows(); ++i) {
long ass = (_exemplar_assignment_vec_key.get()).at8(i);
for (int j = 0; j < exemplarGIDs.length; ++j) {
if (exemplarGIDs[j] == ass) {
counts[j]++;
break;
}
}
}
sum = 0;
for (long l : counts) sum += l;
assert (sum == _parms.train().numRows());
for (int i = 0; i < counts.length; ++i) {
assert (counts[i] == this._counts[i]);
}
}
}
| {
"content_hash": "e5ac4ab33c2b6c0c2d1735568bded92a",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 167,
"avg_line_length": 36.10606060606061,
"alnum_prop": 0.6626101552664708,
"repo_name": "h2oai/h2o-dev",
"id": "1e5626c9eb21d109dc4fdb539c3cb898b06b5410",
"size": "7149",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "h2o-algos/src/main/java/hex/aggregator/AggregatorModel.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5090"
},
{
"name": "CSS",
"bytes": "162399"
},
{
"name": "CoffeeScript",
"bytes": "267048"
},
{
"name": "Emacs Lisp",
"bytes": "6465"
},
{
"name": "HTML",
"bytes": "140849"
},
{
"name": "Java",
"bytes": "6216622"
},
{
"name": "JavaScript",
"bytes": "38932"
},
{
"name": "Jupyter Notebook",
"bytes": "5585408"
},
{
"name": "Makefile",
"bytes": "34105"
},
{
"name": "Python",
"bytes": "2644394"
},
{
"name": "R",
"bytes": "1848754"
},
{
"name": "Rebol",
"bytes": "7059"
},
{
"name": "Ruby",
"bytes": "3506"
},
{
"name": "Scala",
"bytes": "22830"
},
{
"name": "Shell",
"bytes": "47513"
},
{
"name": "TeX",
"bytes": "579960"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
This file is part of the Exposure package.
Copyright 2013 by Sébastien Pujadas
For the full copyright and licence information, please view the LICENCE
file that was distributed with this source code.
-->
<doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping
http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd">
<document name="Exposure\Model\SponsorReturnOnFinancialContribution" collection="sponsorreturnsonfinancialcontribution">
<field name="id" id="true" />
<reference-one field="theme" target-document="Exposure\Model\Theme"
inversed-by="sponsorReturnsOnFinancialContribution"/>
<embed-one field="amount" target-document="Sociable\Model\MultiCurrencyValue"/>
<embed-one field="description" target-document="Sociable\Model\MultiLanguageString"/>
<reference-one field="type" target-document="Exposure\Model\SponsorReturnType"/>
</document>
</doctrine-mongo-mapping> | {
"content_hash": "c49a756f9fa30e0f2ec66fe71cca95c8",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 124,
"avg_line_length": 47.30769230769231,
"alnum_prop": 0.71869918699187,
"repo_name": "spujadas/exposure",
"id": "70d3974b90d8760a7cd3f221662c633a80c8011e",
"size": "1231",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "model/Exposure.Model.SponsorReturnOnFinancialContribution.dcm.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "136805"
},
{
"name": "JavaScript",
"bytes": "189737"
},
{
"name": "PHP",
"bytes": "941654"
}
],
"symlink_target": ""
} |
<?php
namespace Socloz\FeatureFlagBundle\Storage;
/**
* Description of StorageInterface
* @author jfb
*/
interface StorageInterface
{
public function setFeatureEnabled($feature, $state);
public function getFeatureEnabled($feature);
}
| {
"content_hash": "d60d3fb126ca11a8808b6f43968f04a8",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 56,
"avg_line_length": 14,
"alnum_prop": 0.7380952380952381,
"repo_name": "SoCloz/SoclozFeatureFlagBundle",
"id": "104a52cad97f250c33239efcdac1ab34825dda9b",
"size": "291",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Storage/StorageInterface.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "45569"
}
],
"symlink_target": ""
} |
<template name="beersMap">
<div id="storemapper-container" class="content">
<div id='storemapper'>
<p>Store Locator is loading from <a href='https://www.storemapper.co'>Storemapper plugin</a>...</p>
</div>
<script data-storemapper-start='2014,06,30' data-storemapper-id='1079'></script>
<div id="storemapper-script-insertion"></div>
</div>
</template> | {
"content_hash": "d335e30fa79f416c3b720312e4691a11",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 111,
"avg_line_length": 37.18181818181818,
"alnum_prop": 0.6185819070904646,
"repo_name": "funkyeah/twmeteor",
"id": "34083fe8039ea8dd0724ca9603df0a211e405156",
"size": "409",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/pages/where/beersMap.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "100423"
},
{
"name": "CoffeeScript",
"bytes": "31296"
},
{
"name": "JavaScript",
"bytes": "192167"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "fb12a3bf7ec78f5f1c7fdaa3885d3773",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "04948df44dd3695a030f991fa415ee2c9f902cc2",
"size": "206",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Fleischmannia bergantinensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import flask
from werkzeug.contrib.cache import SimpleCache
import config
import odkviewer.connector
app = flask.Flask(__name__)
cache = SimpleCache()
cache.default_timeout = config.cache_timeout
conn = odkviewer.connector.OdkConnector(config.odkurl, config.odkuser, config.odkpass)
@app.after_request
def gnu_terry_pratchett(resp):
resp.headers.add("X-Clacks-Overhead", "GNU Terry Pratchett")
return resp
def checkfid(formid):
# Make sure to get the data from the forms
if not cache.has('forms'):
cache.set('forms', conn.get_forms())
forms = cache.get('forms')
# If the form id is not in the form list, abort
if formid not in forms.keys():
flask.abort(404)
return forms.get(formid)
@app.route('/api/v1/forms')
def listforms():
if cache.has('forms'):
return flask.jsonify(cache.get('forms'))
forms = conn.get_forms()
cache.set('forms', forms)
return flask.jsonify(forms)
@app.route('/api/v1/forms/<formid>')
def getform(formid):
form = checkfid(formid)
return flask.jsonify(form)
@app.route('/api/v1/forms/<formid>/submissions')
def getsubmissions(formid):
form = checkfid(formid)
fdata = conn.get_submissions_from_form(formid, form)
return flask.jsonify(fdata)
@app.route('/')
def main():
return flask.render_template('index.html')
if __name__ == '__main__':
app.run(debug=config.debug)
| {
"content_hash": "a06554b1aba1b020a2a386a9b75f4e80",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 86,
"avg_line_length": 24.68421052631579,
"alnum_prop": 0.681592039800995,
"repo_name": "Ongawa/odk-viewer",
"id": "af6abed4011af47e43a1fb1e95dc473b1909495d",
"size": "1430",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "844"
},
{
"name": "HTML",
"bytes": "1862"
},
{
"name": "JavaScript",
"bytes": "9400"
},
{
"name": "Python",
"bytes": "11595"
}
],
"symlink_target": ""
} |
import { Validator } from "kamboja-foundation"
import { Types } from "mongoose"
import * as Kecubung from "kecubung"
import * as Core from "kamboja-core"
export class ObjectIdValidator extends Validator.ValidatorBase {
@Validator.decoratorName("objectid")
validate(arg: Core.FieldValidatorArg): Core.ValidationError[] | undefined {
if (this.isEmpty(arg.value)) return
if (!Types.ObjectId.isValid(arg.value)) {
let argument = <Kecubung.PrimitiveValueMetaData>arg.decoratorArgs[0]
let customMessage = argument && argument.value
return [{
field: arg.parentField ? `${arg.parentField}.${arg.field}` : arg.field,
message: customMessage || `[${arg.field}] is not valid`
}]
}
}
} | {
"content_hash": "3ee8f6761d1c156d270402339157b06f",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 87,
"avg_line_length": 41.526315789473685,
"alnum_prop": 0.641318124207858,
"repo_name": "kambojajs/kamboja",
"id": "cb675a441f70fd37918c7c9496ee1b0ddd43ce62",
"size": "789",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/moringa/src/validator/objectid-validator.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "166"
},
{
"name": "JavaScript",
"bytes": "5257"
},
{
"name": "Makefile",
"bytes": "378"
},
{
"name": "TypeScript",
"bytes": "673486"
}
],
"symlink_target": ""
} |
/*
* 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.github.pgasync.impl;
import com.github.pgasync.ResultSet;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Tests for BEGIN/COMMIT/ROLLBACK.
*
* @author Antti Laisi
*/
public class TransactionTest {
private final Consumer<Throwable> err = Throwable::printStackTrace;
private final Consumer<ResultSet> fail = result -> new AssertionError("Failure expected").printStackTrace();
@ClassRule
public static DatabaseRule dbr = new DatabaseRule();
@BeforeClass
public static void create() {
drop();
dbr.query("CREATE TABLE TX_TEST(ID INT8 PRIMARY KEY)");
}
@AfterClass
public static void drop() {
dbr.query("DROP TABLE IF EXISTS TX_TEST");
}
@Test
public void shouldCommitSelectInTransaction() throws Exception {
CountDownLatch sync = new CountDownLatch(1);
dbr.db().begin((transaction) ->
transaction.query("SELECT 1", result -> {
assertEquals(1L, result.row(0).getLong(0).longValue());
transaction.commit(sync::countDown, err);
}, err),
err);
assertTrue(sync.await(5, TimeUnit.SECONDS));
}
@Test
public void shouldCommitInsertInTransaction() throws Exception {
CountDownLatch sync = new CountDownLatch(1);
dbr.db().begin((transaction) ->
transaction.query("INSERT INTO TX_TEST(ID) VALUES(10)", result -> {
assertEquals(1, result.updatedRows());
transaction.commit(sync::countDown, err);
}, err),
err);
assertTrue(sync.await(5, TimeUnit.SECONDS));
assertEquals(10L, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 10").row(0).getLong(0).longValue());
}
@Test
public void shouldCommitParametrizedInsertInTransaction() {
// Ref: https://github.com/alaisi/postgres-async-driver/issues/34
long id = dbr.db().begin().flatMap(txn ->
txn.queryRows("INSERT INTO TX_TEST (ID) VALUES ($1) RETURNING ID", "35").last().flatMapSingle(row -> {
Long value = row.getLong(0);
return txn.commit().toSingleDefault(value);
}).toSingle()
).toBlocking().value();
assertEquals(35L, id);
}
@Test
public void shouldRollbackTransaction() throws Exception {
CountDownLatch sync = new CountDownLatch(1);
dbr.db().begin((transaction) ->
transaction.query("INSERT INTO TX_TEST(ID) VALUES(9)", result -> {
assertEquals(1, result.updatedRows());
transaction.rollback(sync::countDown, err);
}, err),
err);
assertTrue(sync.await(5, TimeUnit.SECONDS));
assertEquals(0L, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 9").size());
}
@Test
public void shouldRollbackTransactionOnBackendError() throws Exception {
CountDownLatch sync = new CountDownLatch(1);
dbr.db().begin(transaction ->
transaction.query("INSERT INTO TX_TEST(ID) VALUES(11)", result -> {
assertEquals(1, result.updatedRows());
transaction.query("INSERT INTO TX_TEST(ID) VALUES(11)", fail, t -> sync.countDown());
}, err),
err);
assertTrue(sync.await(5, TimeUnit.SECONDS));
assertEquals(0, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 11").size());
}
@Test
public void shouldInvalidateTxConnAfterError() throws Exception {
CountDownLatch sync = new CountDownLatch(1);
dbr.db().begin((transaction) ->
transaction.query("INSERT INTO TX_TEST(ID) VALUES(22)", result -> {
assertEquals(1, result.updatedRows());
transaction.query("INSERT INTO TX_TEST(ID) VALUES(22)", fail, t ->
transaction.query("SELECT 1", fail, t1 -> {
assertEquals("Transaction is already completed", t1.getMessage());
sync.countDown();
}));
}, err),
err);
assertTrue(sync.await(5, TimeUnit.SECONDS));
assertEquals(0, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 22").size());
}
@Test
public void shouldSupportNestedTransactions() throws Exception {
CountDownLatch sync = new CountDownLatch(1);
dbr.db().begin((transaction) ->
transaction.begin((nested) ->
nested.query("INSERT INTO TX_TEST(ID) VALUES(19)", result -> {
assertEquals(1, result.updatedRows());
nested.commit(() -> transaction.commit(sync::countDown, err), err);
}, err),
err),
err);
assertTrue(sync.await(5, TimeUnit.SECONDS));
assertEquals(1L, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 19").size());
}
@Test
public void shouldRollbackNestedTransaction() throws Exception {
CountDownLatch sync = new CountDownLatch(1);
dbr.db().begin((transaction) ->
transaction.query("INSERT INTO TX_TEST(ID) VALUES(24)", result -> {
assertEquals(1, result.updatedRows());
transaction.begin((nested) ->
nested.query("INSERT INTO TX_TEST(ID) VALUES(23)", res2 -> {
assertEquals(1, res2.updatedRows());
nested.rollback(() -> transaction.commit(sync::countDown, err), err);
}, err), err);
}, err),
err);
assertTrue(sync.await(5, TimeUnit.SECONDS));
assertEquals(1L, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 24").size());
assertEquals(0L, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 23").size());
}
@Test
public void shouldRollbackNestedTransactionOnBackendError() throws Exception {
CountDownLatch sync = new CountDownLatch(1);
dbr.db().begin((transaction) ->
transaction.query("INSERT INTO TX_TEST(ID) VALUES(25)", result -> {
assertEquals(1, result.updatedRows());
transaction.begin((nested) ->
nested.query("INSERT INTO TX_TEST(ID) VALUES(26)", res2 -> {
assertEquals(1, res2.updatedRows());
nested.query("INSERT INTO TD_TEST(ID) VALUES(26)",
fail, t -> transaction.commit(sync::countDown, err));
}, err), err);
}, err),
err);
assertTrue(sync.await(5, TimeUnit.SECONDS));
assertEquals(1L, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 25").size());
assertEquals(0L, dbr.query("SELECT ID FROM TX_TEST WHERE ID = 26").size());
}
}
| {
"content_hash": "72ca34f46355fa8493c149c5d4e9b06e",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 114,
"avg_line_length": 38.39108910891089,
"alnum_prop": 0.5822050290135397,
"repo_name": "jaceksokol/postgres-async-driver",
"id": "75a99f5c31662f7d446bcd5446ca8a35eafe496f",
"size": "7755",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/github/pgasync/impl/TransactionTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "237338"
}
],
"symlink_target": ""
} |
<component name="ProjectDictionaryState">
<dictionary name="xuans">
<words>
<w>addr</w>
<w>sontx</w>
</words>
</dictionary>
</component> | {
"content_hash": "1b7b163c84bbb367fadc87dc930e5ba0",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 41,
"avg_line_length": 20,
"alnum_prop": 0.6,
"repo_name": "sontx/badspy-project",
"id": "de6be68863540b48f76a172469f38758c1cd8d5e",
"size": "160",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "badserver/.idea/dictionaries/xuans.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1750"
},
{
"name": "C++",
"bytes": "33645"
},
{
"name": "Java",
"bytes": "21641"
}
],
"symlink_target": ""
} |
title: Transhumanism & Cosmism
layout: post
author: duettmannallison
permalink: /transhumanism-&-cosmism/
source-id: 1fU9Ou9ClD_4AyJ2b41OIl0-3SRdjTO7igU1PLWr6-Vs
published: true
---
# Transhumanism
* "Man is a rope, tied between beast and Ubermensch--a rope over an abyss...What is great in man is that he is a bridge and not an end: what can be loved in man is that he is an overture and a going under…" Nietzsche, And Thus Spoke Zarathustra*
### Read
* [Thus Spoke Zarathustra ](http://nationalvanguard.org/books/Thus-Spoke-Zarathustra-by-F.-Nietzsche.pdf)- e-book by Friedrich Nietzsche. The human condition as possible bridge to the Ubermensch.
* [Transhumanist Values](https://nickbostrom.com/ethics/values.html) - post by Bostrom. Breaks down some values transhumanists believe in.
* [Transhumanist Declaration](http://humanityplus.org/philosophy/transhumanist-declaration/) - by humanity+. One of several declarations outlining the transhumanist vision
* [The Transhumanist Reader](http://onlinelibrary.wiley.com/book/10.1002/9781118555927) - e-book by Natasha Vita-More, Max More. Older, comprehensive book on
* [The Principles of Extropy](http://www.aleph.se/Trans/Cultural/Philosophy/princip.html) - Max More. Introduces concept of extropy, and individual principles
* [The Principles of Extropy ](https://lifeboat.com/ex/the.principles.of.extropy)- A quarter century later. Revisits the original principles and how they evolved
* [The Technological Singularity](https://www.frc.ri.cmu.edu/~hpm/book98/com.ch1/vinge.singularity.html) - Verner Vinge. Older piece introducing the concept of Singularity
* [Technopoly](http://www.collier.sts.vt.edu/1504/pdfs/technopoly-neil-postman.pdf) - book by Neil Postman. chronicles our transformation into a Technopoly: a society that no longer merely uses technology as a support system but instead is shaped by it--with radical consequences for the meanings of politics, art, education, intelligence, and truth.
* [Afrofuturism](https://dj.dancecult.net/index.php/dancecult/article/view/392/395) - e-book by Ytasha Womack. In this hip, accessible primer to the music, literature, and art of Afrofuturism, author Ytasha Womack introduces readers to the burgeoning community of artists creating Afrofuturist works, the innovators from the past, and the wide range of subjects they explore
* Understand - two transhumanist going to war, one maximizing beauty, the other saving the world
* [The Hyperion cantos](http://readfreenow.com/reading/hyperion-hyperion-cantos-book-1/) - e-book by Dian Simons. Ideas of cybernetics, time being recursive
* [The Book of the New Sun](https://www.amazon.com/Book-New-Sun-Gene-Wolfe/dp/1568658079) - Gene Wolfe. Oddly solipsistic but positive
* [The Nexus Trilogy ](http://rameznaam.com/nexus/)- Ramez Namen. In a future not so far from ours, the ingestible and illegal drug/technology called Nexus can link human minds electronically, wirelessly, nearly telepathically.
* [How We Think: Digital Media & Contemporary Technogenesis](http://raley.english.ucsb.edu/wp-content2/uploads/Hayles-HWT.pdf) - e-book by Katherine Hayles. we think through, with, and alongside media. As the age of print passes and new technologies appear every day, this proposition has become far more complicated,
### Listen & Watch
* [Singularity FM](https://www.singularityweblog.com/category/podcasts/) - Podcast by Nikola Danaylov. Interviews with futurist thinkers
* [A history of the future in 100 objects ](http://longnow.org/seminars/02014/jul/16/history-future-100-objects/)- LongNow seminar by Adrian Horn
### Pages & Orgs
* [KurzweilAI.net](http://www.kurzweilai.net): Launched in 2000, Kurzweil Network explores the radical growth of pervasive technologies — both biological and machine — that are radically changing our world.
* [Humanity +](http://humanityplus.org): Humanity+ is a 501(c)3 international nonprofit membership organization that advocates the ethical use of technology to expand human capacities. In other words, we want people to be better than well.
* [Institute for Ethics and Emerging Technologies](https://ieet.org): The Institute for Ethics and Emerging Technologies is a nonprofit think tank which promotes ideas about how technological progress can increase freedom, happiness, and human flourishing in democratic societies.
* [Transhumanist resources ](http://www.aleph.se/Trans/index.html)
# Cosmism
*"Teetering here on the fulcrum of destiny stands our own bemused species. The future of the universe hinges on what we do next. If we take up the sacred fire, and stride forth into space as the torchbearers of Life, this universe will be aborning. Because of us, the barren dusts of a million billion worlds will coil up into the pulsing magic forms of animate matter. Slag will become soil, grass will sprout, and forests will spring up in once sterile places — a whole frozen universe will thaw and transmogrify, from howling desolation to blossoming paradise. Dust into Life; the very alchemy of God." Marshall Savage*
### Readings
* [A Cosmist Manifesto ](http://goertzel.org/CosmistManifesto_July2010.pdf)- e-book by Ben Goertzel. Comprehensive piece on long-term futurism, its values, and how it differs from singularitarianism
* [The Russian Cosmists: ](https://www.amazon.com/Russian-Cosmists-Esoteric-Futurism-Followers/dp/0199892946)The Esoteric Futurism of Nikolai Fedorov and His Followers - book by George Young. First and only historic perspective on Russian cosmism
* [What was Man Created for?](http://www.apocalyptism.ru/N-Fedorov-1.htm) - blog posts on Nikolai Fedorov. Short perspective on cosmism as created by Nikolai and other Russians.
### Listen & Watch
* [Modern Cosmism Foundation Youtube Channel](https://www.youtube.com/channel/UCc4qgx414hR5KJL6M80lH6Q) - good video of talks at Cosmism conference
### Do
* [Cosmism.com](http://cosmism.com/default.html) - website on everything cosmism
* [Turing Church](https://turingchurch.net/) - a little wooooey, but some good posts
* *
* *
| {
"content_hash": "20ea0de207b5d2314eda4cb1fb1055ed",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 622,
"avg_line_length": 72.91566265060241,
"alnum_prop": 0.7813945803040317,
"repo_name": "AllisonDuettmann/existentialhope",
"id": "8f249d445e5d71e7844d68291e08515e1c55e833",
"size": "6064",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "2017-10-26-Transhumanism-&-Cosmism.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1"
}
],
"symlink_target": ""
} |
package e2e
import (
"k8s.io/client-go/kubernetes"
"github.com/Jeffail/gabs"
)
type prometheusClient struct {
kubeClient kubernetes.Interface
}
func newPrometheusClient(kubeClient kubernetes.Interface) *prometheusClient {
return &prometheusClient{kubeClient}
}
// Query makes a request against the Prometheus /api/v1/query endpoint.
func (c *prometheusClient) query(query string) (int, error) {
req := c.kubeClient.CoreV1().RESTClient().Get().
Namespace("monitoring").
Resource("pods").
SubResource("proxy").
Name("prometheus-k8s-0:9090").
Suffix("/api/v1/query").Param("query", query)
b, err := req.DoRaw()
if err != nil {
return 0, err
}
res, err := gabs.ParseJSON(b)
if err != nil {
return 0, err
}
n, err := res.ArrayCountP("data.result")
return n, err
}
| {
"content_hash": "40f1767b34d43212ef399c6d8c67b776",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 77,
"avg_line_length": 20.894736842105264,
"alnum_prop": 0.6977329974811083,
"repo_name": "jescarri/prometheus-operator",
"id": "b87ce3e5fff8ca7f4b32d392304d2c007eb8703b",
"size": "1403",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "contrib/kube-prometheus/tests/e2e/prometheus_client.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1840"
},
{
"name": "Go",
"bytes": "1222048"
},
{
"name": "Jsonnet",
"bytes": "357509"
},
{
"name": "Makefile",
"bytes": "13122"
},
{
"name": "Shell",
"bytes": "11644"
}
],
"symlink_target": ""
} |
using System;
class CalculateSequence
{
static void Main(string[] args)
{
int sequenceNumber = 2;
int sequenceLength = 10;
for (int i = 0; i < sequenceLength; i++)
{
Console.WriteLine(sequenceNumber % 2 == 0 ? sequenceNumber : sequenceNumber * (-1));
sequenceNumber++;
}
}
}
| {
"content_hash": "f03b29f1d7cfbfdb23dc97bbf580f33d",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 96,
"avg_line_length": 23.125,
"alnum_prop": 0.5216216216216216,
"repo_name": "SevdalinZhelyazkov/TelerikAcademy",
"id": "c562433437feb6f96ceac232680beb5fa6d78316",
"size": "372",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "CSharp-Part-1/IntroToProgramming/PrintSequence/CalculateSequence.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "32824"
},
{
"name": "HTML",
"bytes": "93794"
},
{
"name": "JavaScript",
"bytes": "38671"
}
],
"symlink_target": ""
} |
<?php
/**
* Default hyphenation implementation, which does no word splitting at all.
*
* @package Document
* @access private
* @version //autogen//
*/
class ezcTestDocumentPdfHyphenator extends ezcDocumentPdfHyphenator
{
/**
* Split word into hypens
*
* Takes a word as a string and should return an array containing arrays of
* two words, which each represent a possible split of a word. The german
* word "Zuckerstück" for example changes its hyphens depending on the
* splitting point, so the return value would look like:
*
* <code>
* array(
* array( 'Zuk-', 'kerstück' ),
* array( 'Zucker-', 'stück' ),
* )
* </code>
*
* You should always also include the concatenation character in the split
* words, since it might change depending on the used language.
*
* @param mixed $word
* @return void
*/
public function splitWord( $word )
{
$splits = array();
for ( $i = 1; $i < iconv_strlen( $word, 'UTF-8' ); ++$i )
{
$splits[] = array(
iconv_substr( $word, 0, $i ) . '-',
iconv_substr( $word, $i )
);
}
return $splits;
}
}
?>
| {
"content_hash": "6fb2b494a988f662131e290e5dc49fae",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 79,
"avg_line_length": 26.829787234042552,
"alnum_prop": 0.5567010309278351,
"repo_name": "traceguide/api-php",
"id": "f54ea8d13b6e3d1dbb81d0a0463f9a3f326aa143",
"size": "2281",
"binary": false,
"copies": "21",
"ref": "refs/heads/master",
"path": "vendor/zetacomponents/document/tests/helper/pdf_test_hyphenator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "117719"
}
],
"symlink_target": ""
} |
package definitions
type ExtensionInfoNotification struct {
Body ExtensionInfoEvent `json:"body,omitempty"`
Event string `json:"event,omitempty"`
SubscriptionID string `json:"subscriptionId,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
UUID string `json:"uuid,omitempty"`
}
| {
"content_hash": "37a42ffeae18be5e69b5569f707d0fa7",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 68,
"avg_line_length": 41.55555555555556,
"alnum_prop": 0.6203208556149733,
"repo_name": "grokify/ringcentral-sdk-go",
"id": "3014a2e3dedc80737ba8d3fd1a82dc4f52c1a1e3",
"size": "374",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rcsdk/definitions/ExtensionInfoNotification.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "85299"
}
],
"symlink_target": ""
} |
#ifndef IJKSDL__IJKSDL_AUDIO_H
#define IJKSDL__IJKSDL_AUDIO_H
#include "ijksdl_stdinc.h"
#include "ijksdl_endian.h"
typedef uint16_t SDL_AudioFormat;
#define SDL_AUDIO_MASK_BITSIZE (0xFF)
#define SDL_AUDIO_MASK_DATATYPE (1<<8)
#define SDL_AUDIO_MASK_ENDIAN (1<<12)
#define SDL_AUDIO_MASK_SIGNED (1<<15)
#define SDL_AUDIO_BITSIZE(x) (x & SDL_AUDIO_MASK_BITSIZE)
#define SDL_AUDIO_ISFLOAT(x) (x & SDL_AUDIO_MASK_DATATYPE)
#define SDL_AUDIO_ISBIGENDIAN(x) (x & SDL_AUDIO_MASK_ENDIAN)
#define SDL_AUDIO_ISSIGNED(x) (x & SDL_AUDIO_MASK_SIGNED)
#define SDL_AUDIO_ISINT(x) (!SDL_AUDIO_ISFLOAT(x))
#define SDL_AUDIO_ISLITTLEENDIAN(x) (!SDL_AUDIO_ISBIGENDIAN(x))
#define SDL_AUDIO_ISUNSIGNED(x) (!SDL_AUDIO_ISSIGNED(x))
#define AUDIO_INVALID 0x0000
#define AUDIO_U8 0x0008 /**< Unsigned 8-bit samples */
#define AUDIO_S8 0x8008 /**< Signed 8-bit samples */
#define AUDIO_U16LSB 0x0010 /**< Unsigned 16-bit samples */
#define AUDIO_S16LSB 0x8010 /**< Signed 16-bit samples */
#define AUDIO_U16MSB 0x1010 /**< As above, but big-endian byte order */
#define AUDIO_S16MSB 0x9010 /**< As above, but big-endian byte order */
#define AUDIO_U16 AUDIO_U16LSB
#define AUDIO_S16 AUDIO_S16LSB
#define AUDIO_S32LSB 0x8020 /**< 32-bit integer samples */
#define AUDIO_S32MSB 0x9020 /**< As above, but big-endian byte order */
#define AUDIO_S32 AUDIO_S32LSB
#define AUDIO_F32LSB 0x8120 /**< 32-bit floating point samples */
#define AUDIO_F32MSB 0x9120 /**< As above, but big-endian byte order */
#define AUDIO_F32 AUDIO_F32LSB
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
#define AUDIO_U16SYS AUDIO_U16LSB
#define AUDIO_S16SYS AUDIO_S16LSB
#define AUDIO_S32SYS AUDIO_S32LSB
#define AUDIO_F32SYS AUDIO_F32LSB
#else
#define AUDIO_U16SYS AUDIO_U16MSB
#define AUDIO_S16SYS AUDIO_S16MSB
#define AUDIO_S32SYS AUDIO_S32MSB
#define AUDIO_F32SYS AUDIO_F32MSB
#endif
typedef void (*SDL_AudioCallback) (void *userdata, Uint8 * stream,
int len);
typedef struct SDL_AudioSpec
{
int freq; /**< DSP frequency -- samples per second */
SDL_AudioFormat format; /**< Audio data format */
Uint8 channels; /**< Number of channels: 1 mono, 2 stereo */
Uint8 silence; /**< Audio buffer silence value (calculated) */
Uint16 samples; /**< Audio buffer size in samples (power of 2) */
Uint16 padding; /**< NOT USED. Necessary for some compile environments */
Uint32 size; /**< Audio buffer size in bytes (calculated) */
SDL_AudioCallback callback;
void *userdata;
} SDL_AudioSpec;
void SDL_CalculateAudioSpec(SDL_AudioSpec * spec);
#endif
| {
"content_hash": "8ce3b664ba3e0dc374cd55d5ab8e84ed",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 89,
"avg_line_length": 39.66197183098591,
"alnum_prop": 0.6512784090909091,
"repo_name": "xpemail/ijkplayer",
"id": "324e80678f98ec5eb7dadc3a042317051082ea1a",
"size": "3822",
"binary": false,
"copies": "72",
"ref": "refs/heads/master",
"path": "ijkplayer/ijkmedia/ijksdl/ijksdl_audio.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "234690"
},
{
"name": "C++",
"bytes": "10034"
},
{
"name": "Forth",
"bytes": "2164"
},
{
"name": "Objective-C",
"bytes": "135314"
},
{
"name": "Ruby",
"bytes": "4227"
}
],
"symlink_target": ""
} |
module Wechat
module Generators
class InstallGenerator < Rails::Generators::Base
desc 'Install Wechat support files'
source_root File.expand_path('../templates', __FILE__)
def copy_config
template 'config/wechat.yml'
end
def add_wechat_route
route 'resource :wechat, only: [:show, :create]'
end
def copy_wechat_controller
template 'app/controllers/wechats_controller.rb'
end
end
end
end
| {
"content_hash": "1396380c8e329028cc79f8c736d90ccf",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 60,
"avg_line_length": 23.7,
"alnum_prop": 0.6371308016877637,
"repo_name": "zfben/wechat",
"id": "b949c4b86a1270a0c0fe8af2c9af5483f7d138b6",
"size": "474",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/generators/wechat/install_generator.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "154935"
}
],
"symlink_target": ""
} |
<img src="https://goreportcard.com/badge/github.com/IamBc/xerrors" />
<br/>
custom structs for error handling in golang
<br/>
<h3>Todo:</h3>
<ul>
<li>Examples</li>
<li>Configuration settings</li>
<li>Improve the documentation</li>
<li>Shorter way to create UI errors</li>
<li>Storage of extra parameters?</li>
</ul>
| {
"content_hash": "4fb75db85234e5459c2664df37e5f00d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 69,
"avg_line_length": 24.384615384615383,
"alnum_prop": 0.7160883280757098,
"repo_name": "IamBc/abc",
"id": "809323022e0c35f6ba76941636c2caba63977d94",
"size": "327",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/github.com/iambc/xerrors/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "791"
},
{
"name": "Go",
"bytes": "16131"
},
{
"name": "HTML",
"bytes": "2568"
},
{
"name": "JavaScript",
"bytes": "10595"
},
{
"name": "Shell",
"bytes": "451"
}
],
"symlink_target": ""
} |
package com.datastax.dse.driver.api.querybuilder.schema;
import com.datastax.oss.driver.api.core.CqlIdentifier;
import edu.umd.cs.findbugs.annotations.NonNull;
public interface AlterDseTableRenameColumn {
/**
* Adds a column rename to ALTER TABLE specification. This may be repeated with successive calls
* to rename columns.
*/
@NonNull
AlterDseTableRenameColumnEnd renameColumn(@NonNull CqlIdentifier from, @NonNull CqlIdentifier to);
/**
* Shortcut for {@link #renameColumn(CqlIdentifier, CqlIdentifier)
* renameField(CqlIdentifier.fromCql(from),CqlIdentifier.fromCql(to))}.
*/
@NonNull
default AlterDseTableRenameColumnEnd renameColumn(@NonNull String from, @NonNull String to) {
return renameColumn(CqlIdentifier.fromCql(from), CqlIdentifier.fromCql(to));
}
}
| {
"content_hash": "0cd9b98fda876b9432512ce1d3b47159",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 100,
"avg_line_length": 33.583333333333336,
"alnum_prop": 0.7692307692307693,
"repo_name": "datastax/java-driver",
"id": "5145c18db5937c9f00df56c3cb178039d9f8d10c",
"size": "1394",
"binary": false,
"copies": "1",
"ref": "refs/heads/4.x",
"path": "query-builder/src/main/java/com/datastax/dse/driver/api/querybuilder/schema/AlterDseTableRenameColumn.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "9423701"
},
{
"name": "Scala",
"bytes": "1509"
},
{
"name": "Shell",
"bytes": "10722"
}
],
"symlink_target": ""
} |
<?php
include '../db.inc.php';
//values entered by the user
$ISBN = $_GET['ISBN'];
$bookTitle = $_GET['bookTitle'];
$author = $_GET['Author'];
$publishedDate = $_GET['PublishedDate'];
$Publisher = $_GET['Publisher'];
$keywords = $_GET['keywords'];
$category = $_GET['category'];
$copyCount = $_GET['copyCount'];
try {
//select ISBNs from the database from book table
$sql = 'SELECT ISBN FROM book WHERE ISBN = :ISBN';
$result = $pdo->prepare($sql);
$result->bindValue(':ISBN', $ISBN);
$result->execute();
$row = $result->fetch();
//if condition is satisfied, the ISBN is not in the system, i.e. adding book and bookcopies
if ($ISBN != $row[0]) {
//add new book to Book table
try {
$sqlinstert = 'INSERT INTO book SET ISBN = :ISBN,
Title = :bookTitle,
Author = :Author,
PublishedDate = :publishedDate,
Publisher = :Publisher,
KeyWords = :keywords,
copyCount = :copyCount';
$book = $pdo->prepare($sqlinstert);
$book->bindValue(':ISBN', $ISBN);
$book->bindValue(':bookTitle', $bookTitle);
$book->bindValue(':Author', $author);
$book->bindValue(':publishedDate', $publishedDate);
$book->bindValue(':Publisher',$Publisher);
$book->bindValue(':keywords', $keywords);
$book->bindValue(':copyCount', $copyCount);
$book->execute();
Switch($category){
case 'Computer':
$ShelfNumber = 1001;
break;
case 'Literature':
$ShelfNumber = 1002;
break;
case 'Children':
$ShelfNumber = 1003;
break;
case 'Education':
$ShelfNumber = 1004;
break;
}
for ($i = 0; $i < $copyCount; $i++) {
$sql1 = 'INSERT INTO bookcopy SET
ISBN = :ISBN,
ShelfNumber = :ShelfNumber,
BStatusID = 1';
$add = $pdo->prepare($sql1);
$add->bindValue(':ISBN', $ISBN);
$add->bindValue(':ShelfNumber', $ShelfNumber);
$add->execute();
}
}
catch (PDOException $e) {
$error_message = 'insert bookcopy Error1 : ' . $e->getMessage();
include '../messagedispaly/outputMessage.php';
exit();
}
} //endif
else{
try{
$sql2 = 'SELECT copyCount FROM book WHERE ISBN = :ISBN';
$result = $pdo->prepare($sql2);
$result->bindValue(':ISBN', $ISBN);
$result->execute();
$row = $result->fetch();
$oldcount = $row[0];
$newcopyCount = $oldcount + $copyCount;
//update the copyCount when adding a book with an exsited ISBN
$sqlupdate = 'UPDATE book SET copyCount = :newcopyCount WHERE ISBN = :ISBN';
$s = $pdo->prepare($sqlupdate);
$s->bindValue(':newcopyCount', $newcopyCount);
$s->bindValue(':ISBN',$ISBN);
$s ->execute();
//addBookCopy($ISBN, $category, $copyCount);
Switch($category){
case 'Computer':
$ShelfNumber = 1001;
break;
case 'Literature':
$ShelfNumber = 1002;
break;
case 'Children':
$ShelfNumber = 1003;
break;
case 'Education':
$ShelfNumber = 1004;
break;
}
for ($i = 0; $i < $copyCount; $i++) {
$sql = 'INSERT INTO bookcopy SET
ISBN = :ISBN,
ShelfNumber = :ShelfNumber,
BStatusID = 1';
$add = $pdo->prepare($sql);
$add->bindValue(':ISBN', $ISBN);
$add->bindValue(':ShelfNumber', $ShelfNumber);
$add->execute();
}
}
catch (PDOException $e) {
$error_message = 'insert bookcopy Error2 : ' . $e->getMessage();
include '../messagedispaly/outputMessage.php';
exit();
}
}//endelse
$output_message = 'The books are successfully added into the database!';
}//endtry
catch (PDOException $e) {
$error_message = 'Error : ' . $e->getMessage();
include 'error.html.php';
exit();
}
include '../messagedispaly/outputMessage.php';
?>
| {
"content_hash": "18deb7e2d4763c23aa66047fe6e3e1bc",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 91,
"avg_line_length": 21.14367816091954,
"alnum_prop": 0.5974449578689861,
"repo_name": "dallen4/LibraryWebApp",
"id": "2ccbb240df4d492e7a60c7cd85fd462a5fce1826",
"size": "3679",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "admin/processAddbook.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2662"
},
{
"name": "PHP",
"bytes": "43657"
}
],
"symlink_target": ""
} |
.. This file is part of the OpenDSA eTextbook project. See
.. http://algoviz.org/OpenDSA for more details.
.. Copyright (c) 2012-2013 by the OpenDSA Project Contributors, and
.. distributed under an MIT open source license.
.. avmetadata::
:author: Cliff Shaffer
:satisfies: logarithms
:topic: Math Background
Logarithms
==========
The :term:`logarithm` of base :math:`b` for value :math:`y` is the
power to which :math:`b` is raised to get :math:`y`.
Normally, this is written as :math:`\log_b y = x`.
Thus, if :math:`\log_b y = x` then :math:`b^x = y`,
and :math:`b^{log_b y} = y`.
Logarithms are used frequently by programmers.
Here are two typical uses.
.. topic:: Example
Many programs require an encoding for a collection of objects.
What is the minimum number of bits needed to represent :math:`n`
distinct code values?
The answer is :math:`\lceil \log_2 n \rceil` bits.
For example, if you have 1000 codes to store, you will require at
least :math:`\lceil \log_2 1000 \rceil = 10` bits to have 1000
different codes (10 bits provide 1024 distinct code values).
.. topic:: Example
Consider the :ref:`binary search <binary search> <AnalProgram>`
algorithm for finding a given value within an array sorted by value
from lowest to highest.
Binary search first looks at the middle element
and determines if the value being searched for is in the upper half
or the lower half of the array.
The algorithm then continues splitting the appropriate
subarray in half until the desired value is found.
How many times can an array of size \(n\) be split in half until
only one element remains in the final subarray?
The answer is :math:`\lceil \log_2 n \rceil` times.
In OpenDSA, nearly all logarithms used have a base of two.
This is because data structures and algorithms most often divide
things in half, or store codes with binary bits.
Whenever you see the notation :math:`\log n` in OpenDSA,
either :math:`\log_2 n` is meant or else the term is being used
asymptotically and so the actual base does not matter.
Logarithms using any base other than two will show the base
explicitly.
Logarithms have the following properties, for any positive values of
:math:`m`, :math:`n`, and :math:`r`, and any positive integers
:math:`a` and :math:`b`.
#) :math:`\log (nm) = \log n + \log m`.
#) :math:`\log (n/m) = \log n - \log m`.
#) :math:`\log (n^r) = r \log n`.
#) :math:`\log_a n = \log_b n / \log_b a`.
The first two properties state that the logarithm
of two numbers multiplied (or divided) can be found by adding
(or subtracting) the logarithms of the two numbers. [#]_
Property (3) is simply an extension of property (1).
Property (4) tells us that, for variable :math:`n` and any two integer
constants :math:`a` and :math:`b`, :math:`\log_a n` and
:math:`\log_b n` differ by the constant factor :math:`\log_b a`,
regardless of the value of :math:`n`.
Most runtime analyses we use are of a type that ignores
constant factors in costs.
Property (4) says that such analyses need not be concerned with the
base of the logarithm, because this can change the total cost only by
a constant factor.
Note that :math:`2^{\log n} = n`.
When discussing logarithms, exponents often lead to confusion.
Property (3) tells us that :math:`\log n^2 = 2 \log n`.
How do we indicate the square of the logarithm (as opposed to the
logarithm of :math:`n^2`)?
This could be written as :math:`(\log n)^2`, but it is traditional to
use :math:`\log^2 n`.
On the other hand, we might want to take the logarithm of the
logarithm of :math:`n`.
This is written :math:`\log \log n`.
A special notation is used in the rare case when we need to know how
many times we must take the log of a number before we reach a
value :math:`\leq 1`.
This quantity is written :math:`\log^* n`.
For example, :math:`\log^* 1024 = 4` because
:math:`\log 1024 = 10`, :math:`\log 10 \approx 3.33`,
:math:`\log 3.33 \approx 1.74`,
and :math:`\log 1.74 < 1`, which is a total of 4 log operations.
Notes
-----
.. [#] These properties are the idea behind the slide rule.
Adding two numbers can be viewed as joining two lengths
together and measuring their combined length.
Multiplication is not so easily done.
However, if the numbers are first converted to the lengths of
their logarithms, then those lengths can be added and the
inverse logarithm of the resulting length gives the answer for
the multiplication (this is simply logarithm property (1)).
A slide rule measures the length of the logarithm for the
numbers, lets you slide bars representing these lengths to add
up the total length, and finally converts this total length to
the correct numeric answer by taking the inverse of the
logarithm for the result.
| {
"content_hash": "ba59682776c9f7c51b4ae7a876340d38",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 70,
"avg_line_length": 41.30769230769231,
"alnum_prop": 0.7097041175253466,
"repo_name": "hosamshahin/OpenDSA",
"id": "e0bb97e77eab6711b418cdb5a985b6d33cd98596",
"size": "4833",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RST/en/Background/Logarithms.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1946"
},
{
"name": "C++",
"bytes": "38018"
},
{
"name": "CSS",
"bytes": "711841"
},
{
"name": "Erlang",
"bytes": "2168"
},
{
"name": "Groff",
"bytes": "3834"
},
{
"name": "HTML",
"bytes": "3419016"
},
{
"name": "Java",
"bytes": "154075"
},
{
"name": "JavaScript",
"bytes": "8121755"
},
{
"name": "Makefile",
"bytes": "67506"
},
{
"name": "PHP",
"bytes": "309"
},
{
"name": "Processing",
"bytes": "152968"
},
{
"name": "Python",
"bytes": "183224"
},
{
"name": "Ruby",
"bytes": "7484"
},
{
"name": "Shell",
"bytes": "5008"
},
{
"name": "TeX",
"bytes": "87553"
}
],
"symlink_target": ""
} |
<?php
namespace Strider2038\ImgCache\Core\Streaming;
/**
* @author Igor Lazarev <[email protected]>
*/
class StringStream implements StreamInterface
{
/** @var string */
private $contents;
/** @var int */
private $position = 0;
public function __construct(string $contents)
{
$this->contents = $contents;
}
public function __toString()
{
return $this->getContents();
}
public function getContents(): string
{
return $this->contents;
}
public function close(): void
{
}
public function getSize(): ? int
{
return strlen($this->contents);
}
public function eof(): bool
{
return $this->position >= strlen($this->contents);
}
public function isWritable(): bool
{
return false;
}
public function write(string $string): int
{
throw new \RuntimeException('Not implemented');
}
public function isReadable(): bool
{
return true;
}
public function read(int $length): string
{
$length = max($length, 0);
$string = substr($this->contents, $this->position, $length);
$this->position += $length;
return $string;
}
public function rewind(): void
{
}
}
| {
"content_hash": "2a0f003ec5e8f9f64199fc02c37a13b5",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 68,
"avg_line_length": 17.84931506849315,
"alnum_prop": 0.56792018419033,
"repo_name": "strider2038/imgcache-service",
"id": "d5b2000855cf75c17f8ed7fec3735870ff8c6287",
"size": "1521",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Core/Streaming/StringStream.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "848509"
},
{
"name": "Shell",
"bytes": "1774"
}
],
"symlink_target": ""
} |
<?php
/*
* This file is part of Mandango.
*
* (c) Pablo Díez <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Mandango\Cache;
/**
* FilesystemCache.
*
* @author Pablo Díez <[email protected]>
*/
class FilesystemCache implements CacheInterface
{
private $dir;
/**
* Constructor.
*
* @param string $dir The directory.
*/
public function __construct($dir)
{
$this->dir = $dir;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
return file_exists($this->dir.'/'.$key.'.php');
}
/**
* {@inheritdoc}
*/
public function get($key)
{
$file = $this->dir.'/'.$key.'.php';
return file_exists($file) ? require($file) : null;
}
/**
* {@inheritdoc}
*/
public function set($key, $value)
{
if (!is_dir($this->dir) && false === @mkdir($this->dir, 0777, true)) {
throw new \RuntimeException(sprintf('Unable to create the "%s" directory.', $this->dir));
}
$file = $this->dir.'/'.$key.'.php';
$valueExport = var_export($value, true);
$content = <<<EOF
<?php
return $valueExport;
EOF;
if (false === @file_put_contents($file, $content, LOCK_EX)) {
throw new \RuntimeException(sprintf('Unable to write the "%s" file.', $file));
}
}
/**
* {@inheritdoc}
*/
public function remove($key)
{
$file = $this->dir.'/'.$key.'.php';
if (file_exists($file) && false === @unlink($file)) {
throw new \RuntimeException(sprintf('Unable to remove the "%s" file.', $file));
}
}
/**
* {@inheritdoc}
*/
public function clear()
{
if (is_dir($this->dir)) {
foreach (new \DirectoryIterator($this->dir) as $file) {
if ($file->isFile()) {
if (false === @unlink($file->getRealPath())) {
throw new \RuntimeException(sprintf('Unable to remove the "%s" file.', $file->getRealPath()));
}
}
}
}
}
}
| {
"content_hash": "dfcd8121c9e1fa792bdefa5bd6b27fb2",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 118,
"avg_line_length": 22.454545454545453,
"alnum_prop": 0.5020242914979757,
"repo_name": "Phantazm/Laravel-Mandango",
"id": "16f779d281278cbe634c6a0f9c37e5fe99ae36b2",
"size": "2225",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "src/Mandango/Cache/FilesystemCache.php",
"mode": "33261",
"license": "mit",
"language": [],
"symlink_target": ""
} |
.datepicker {
font-size: 12px;
width: 260px;
border: 1px solid #ddd;
.hidden {
display: none;
}
}
.datepicker-header {
position: relative;
padding: 5px;
> label {
font-weight: 600;
position: absolute;
left: 40px;
right: 40px;
line-height: 22px;
text-align: center;
cursor: pointer;
&:hover {
background: #33bcff;
color: #fff;
}
}
}
.datepicker-body {
position: relative;
}
.datepicker-prevbtn,
.datepicker-nextbtn {
border: 0;
background: transparent;
cursor: pointer;
}
.datepicker-nextbtn {
float: right;
}
.datepicker table {
table-layout: fixed;
width: 100%;
}
.datepicker th {
border-bottom: 1px solid #eee;
padding: 5px;
}
.datepicker td.nextmonth,
.datepicker td.prevmonth {
color: #999;
}
.datepicker td {
text-align: center;
padding: 6px 5px;
cursor: pointer;
&:hover {
background-color: #33bcff;
color: #fff;
}
}
.datepicker td.current {
background: #0089dc;
color: #fff;
}
.datepicker-footer {
padding: 4px;
text-align: right;
}
.datepicker-todaybtn {
border: none;
color: #0089dc;
background: transparent;
line-height: 24px;
border-radius: 5px;
cursor: pointer;
}
.datepicker-yeartable td {
text-align: center;
padding: 15px;
cursor: pointer;
}
.datepicker-monthtable td {
text-align: center;
padding: 15px;
cursor: pointer;
}
| {
"content_hash": "bf89baa97e492c6caed35572ebf9619d",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 32,
"avg_line_length": 13.821782178217822,
"alnum_prop": 0.6368194842406877,
"repo_name": "ElemeFE/tnt",
"id": "e4702e4bbfd460e9df0d735822b4bc85926be0f8",
"size": "1396",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/datepicker/index.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18290"
},
{
"name": "HTML",
"bytes": "3259"
},
{
"name": "JavaScript",
"bytes": "95597"
},
{
"name": "Makefile",
"bytes": "125"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grid Slider Demo - Jssor Slider, Carousel, Slideshow with Javascript Source Code</title>
</head>
<body style="font-family:Arial, Verdana;background-color:#fff;">
<!-- it works the same with all jquery version from 1.x to 2.x -->
<script type="text/javascript" src="../js/jquery-1.9.1.min.js"></script>
<!-- use jssor.slider.mini.js (40KB) instead for release -->
<!-- jssor.slider.mini.js = (jssor.js + jssor.slider.js) -->
<script type="text/javascript" src="../js/jssor.js"></script>
<script type="text/javascript" src="../js/jssor.slider.js"></script>
<script>
jQuery(document).ready(function ($) {
var nestedSliders = [];
$.each(["sliderh1_container", "sliderh2_container", "sliderh3_container", "sliderh4_container"], function (index, value) {
var sliderhOptions = {
$PauseOnHover: 1, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, 4 freeze for desktop, 8 freeze for touch device, 12 freeze for desktop and touch device, default value is 1
$AutoPlaySteps: 4, //[Optional] Steps to go for each navigation request (this options applys only when slideshow disabled), the default value is 1
$SlideDuration: 300, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500
$MinDragOffsetToSlide: 20, //[Optional] Minimum drag offset to trigger slide , default value is 20
$SlideWidth: 200, //[Optional] Width of every slide in pixels, default value is width of 'slides' container
//$SlideHeight: 150, //[Optional] Height of every slide in pixels, default value is height of 'slides' container
$SlideSpacing: 3, //[Optional] Space between each slide in pixels, default value is 0
$DisplayPieces: 4, //[Optional] Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1
$ParkingPosition: 0, //[Optional] The offset position to park slide (this options applys only when slideshow disabled), default value is 0.
$UISearchMode: 0, //[Optional] The way (0 parellel, 1 recursive, default value is 1) to search UI components (slides container, loading screen, navigator container, arrow navigator container, thumbnail navigator container etc).
$BulletNavigatorOptions: { //[Optional] Options to specify and enable navigator or not
$Class: $JssorBulletNavigator$, //[Required] Class to create navigator instance
$ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
$AutoCenter: 0, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
$Steps: 1, //[Optional] Steps to go for each navigation request, default value is 1
$Lanes: 1, //[Optional] Specify lanes to arrange items, default value is 1
$SpacingX: 0, //[Optional] Horizontal space between each item in pixel, default value is 0
$SpacingY: 0, //[Optional] Vertical space between each item in pixel, default value is 0
$Orientation: 1 //[Optional] The orientation of the navigator, 1 horizontal, 2 vertical, default value is 1
}
};
var jssor_sliderh = new $JssorSlider$(value, sliderhOptions);
nestedSliders.push(jssor_sliderh);
});
var options = {
$AutoPlay: false, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false
$AutoPlaySteps: 1, //[Optional] Steps to go for each navigation request (this options applys only when slideshow disabled), the default value is 1
$AutoPlayInterval: 4000, //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000
$PauseOnHover: 1, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, 4 freeze for desktop, 8 freeze for touch device, 12 freeze for desktop and touch device, default value is 1
$ArrowKeyNavigation: true, //[Optional] Allows keyboard (arrow key) navigation or not, default value is false
$SlideDuration: 300, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500
$MinDragOffsetToSlide: 80, //[Optional] Minimum drag offset to trigger slide , default value is 20
//$SlideWidth: 600, //[Optional] Width of every slide in pixels, default value is width of 'slides' container
$SlideHeight: 150, //[Optional] Height of every slide in pixels, default value is height of 'slides' container
$SlideSpacing: 3, //[Optional] Space between each slide in pixels, default value is 0
$DisplayPieces: 3, //[Optional] Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1
$ParkingPosition: 0, //[Optional] The offset position to park slide (this options applys only when slideshow disabled), default value is 0.
$UISearchMode: 0, //[Optional] The way (0 parellel, 1 recursive, default value is 1) to search UI components (slides container, loading screen, navigator container, arrow navigator container, thumbnail navigator container etc).
$PlayOrientation: 2, //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, 5 horizental reverse, 6 vertical reverse, default value is 1
$DragOrientation: 2, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0),
$BulletNavigatorOptions: { //[Optional] Options to specify and enable navigator or not
$Class: $JssorBulletNavigator$, //[Required] Class to create navigator instance
$ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
$AutoCenter: 2, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
$SpacingY: 5, //[Optional] Vertical space between each item in pixel, default value is 0
$Orientation: 2 //[Optional] The orientation of the navigator, 1 horizontal, 2 vertical, default value is 1
}
};
var jssor_slider1 = new $JssorSlider$("slider1_container", options);
//responsive code begin
//you can remove responsive code if you don't want the slider scales while window resizes
function ScaleSlider() {
var parentWidth = jssor_slider1.$Elmt.parentNode.clientWidth;
if (parentWidth) {
var sliderWidth = parentWidth;
//keep the slider width no more than 809
sliderWidth = Math.min(sliderWidth, 809);
jssor_slider1.$ScaleWidth(sliderWidth);
}
else
window.setTimeout(ScaleSlider, 30);
}
ScaleSlider();
$(window).bind("load", ScaleSlider);
$(window).bind("resize", ScaleSlider);
$(window).bind("orientationchange", ScaleSlider);
//responsive code end
});
</script>
<!-- sliderh style begin -->
<style>
/* jssor slider bullet navigator skin 03 css */
/*
.jssorb03 div (normal)
.jssorb03 div:hover (normal mouseover)
.jssorb03 .av (active)
.jssorb03 .av:hover (active mouseover)
.jssorb03 .dn (mousedown)
*/
.jssorb03 {
position: absolute;
}
.jssorb03 div, .jssorb03 div:hover, .jssorb03 .av {
position: absolute;
/* size of bullet elment */
width: 21px;
height: 21px;
text-align: center;
line-height: 21px;
color: white;
font-size: 12px;
background: url(../img/b03.png) no-repeat;
overflow: hidden;
cursor: pointer;
}
.jssorb03 div { background-position: -5px -4px; }
.jssorb03 div:hover, .jssorb03 .av:hover { background-position: -35px -4px; }
.jssorb03 .av { background-position: -65px -4px; }
.jssorb03 .dn, .jssorb03 .dn:hover { background-position: -95px -4px; }
</style>
<!-- sliderh style end -->
<!-- Jssor Slider Begin -->
<!-- To move inline styles to css file/block, please specify a class name for each element. -->
<div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 809px; height: 456px; overflow: hidden; ">
<!-- Slides Container -->
<div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 809px; height: 456px;
overflow: hidden;">
<div>
<div id="sliderh1_container" style="position: relative; top: 0px; left: 0px; width: 809px;
height: 150px;">
<!-- Slides Container -->
<div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 809px; height: 150px;
overflow: hidden;">
<div><img u="image" src="../img/ancient-lady/005.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/006.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/011.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/013.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/014.jpg" /></div>
</div>
<!--#region Bullet Navigator Skin Begin -->
<!-- Help: http://www.jssor.com/development/slider-with-bullet-navigator-jquery.html -->
<!-- bullet navigator container -->
<div u="navigator" class="jssorb03" style="bottom: 10px; right: 10px;">
<!-- bullet navigator item prototype -->
<div u="prototype"><div u="numbertemplate"></div></div>
</div>
<!--#endregion Bullet Navigator Skin End -->
</div>
</div>
<div>
<div id="sliderh2_container" style="position: relative; top: 0px; left: 0px; width: 809px;
height: 150px;">
<!-- Slides Container -->
<div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 809px; height: 150px;
overflow: hidden;">
<div><img u="image" src="../img/ancient-lady/020.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/021.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/022.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/024.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/025.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/027.jpg" /></div>
</div>
<!--#region Bullet Navigator Skin Begin -->
<!-- Help: http://www.jssor.com/development/slider-with-bullet-navigator-jquery.html -->
<!-- bullet navigator container -->
<div u="navigator" class="jssorb03" style="bottom: 10px; right: 10px;">
<!-- bullet navigator item prototype -->
<div u="prototype"><div u="numbertemplate"></div></div>
</div>
<!--#endregion Bullet Navigator Skin End -->
</div>
</div>
<div>
<div id="sliderh3_container" style="position: relative; top: 0px; left: 0px; width: 809px;
height: 150px;">
<!-- Slides Container -->
<div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 809px; height: 150px;
overflow: hidden;">
<div><img u="image" src="../img/ancient-lady/029.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/030.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/031.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/032.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/034.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/038.jpg" /></div>
</div>
<!--#region Bullet Navigator Skin Begin -->
<!-- Help: http://www.jssor.com/development/slider-with-bullet-navigator-jquery.html -->
<!-- bullet navigator container -->
<div u="navigator" class="jssorb03" style="bottom: 10px; right: 10px;">
<!-- bullet navigator item prototype -->
<div u="prototype"><div u="numbertemplate"></div></div>
</div>
<!--#endregion Bullet Navigator Skin End -->
</div>
</div>
<div>
<div id="sliderh4_container" style="position: relative; top: 0px; left: 0px; width: 809px;
height: 150px;">
<!-- Slides Container -->
<div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 809px; height: 150px;
overflow: hidden;">
<div><img u="image" src="../img/ancient-lady/039.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/043.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/044.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/047.jpg" /></div>
<div><img u="image" src="../img/ancient-lady/050.jpg" /></div>
</div>
<!--#region Bullet Navigator Skin Begin -->
<!-- Help: http://www.jssor.com/development/slider-with-bullet-navigator-jquery.html -->
<!-- bullet navigator container -->
<div u="navigator" class="jssorb03" style="bottom: 10px; right: 10px;">
<!-- bullet navigator item prototype -->
<div u="prototype"><div u="numbertemplate"></div></div>
</div>
<!--#endregion Bullet Navigator Skin End -->
</div>
</div>
</div>
<!--#region Bullet Navigator Skin Begin -->
<!-- Help: http://www.jssor.com/development/slider-with-bullet-navigator-jquery.html -->
<style>
/* jssor slider bullet navigator skin 02 css */
/*
.jssorb02 div (normal)
.jssorb02 div:hover (normal mouseover)
.jssorb02 .av (active)
.jssorb02 .av:hover (active mouseover)
.jssorb02 .dn (mousedown)
*/
.jssorb02 {
position: absolute;
}
.jssorb02 div, .jssorb02 div:hover, .jssorb02 .av {
position: absolute;
/* size of bullet elment */
width: 21px;
height: 21px;
text-align: center;
line-height: 21px;
color: white;
font-size: 12px;
background: url(../img/b02.png) no-repeat;
overflow: hidden;
cursor: pointer;
}
.jssorb02 div { background-position: -5px -5px; }
.jssorb02 div:hover, .jssorb02 .av:hover { background-position: -35px -5px; }
.jssorb02 .av { background-position: -65px -5px; }
.jssorb02 .dn, .jssorb02 .dn:hover { background-position: -95px -5px; }
</style>
<!-- bullet navigator container -->
<div u="navigator" class="jssorb02" style="bottom: 16px; left: 6px;">
<!-- bullet navigator item prototype -->
<div u="prototype"><div u="numbertemplate"></div></div>
</div>
<!--#endregion Bullet Navigator Skin End -->
<a style="display: none" href="http://www.jssor.com">Slider Javascript</a>
</div>
<!-- Jssor Slider End -->
</body>
</html> | {
"content_hash": "4e0abffa6fa07ae6ab7ffb2e250bf3c7",
"timestamp": "",
"source": "github",
"line_count": 280,
"max_line_length": 347,
"avg_line_length": 69.05357142857143,
"alnum_prop": 0.5004913369537108,
"repo_name": "deshpandeaditya/jqueryforpoorvi",
"id": "b53dcabf13e8c987bbda9a2cebf646eef7fcda36",
"size": "19337",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demos-jquery/grid-slider.source.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1599137"
},
{
"name": "JavaScript",
"bytes": "262425"
},
{
"name": "Shell",
"bytes": "15015"
}
],
"symlink_target": ""
} |
package ru.job4j;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test class Paint.
*
* @author Alexander Mezgin
* @version 1
* @since 20.11.2016
*/
public class PaintTest {
/**
* Test pyramid(int h) with correct height.
*/
@Test
public void whenAddHeightEqualsTwoThenReturnPyramid() {
final Paint paint = new Paint();
final String checked = " ^ \n\r ^ ^ \n\r";
final int h = 2;
final String result = paint.pyramid(h);
assertThat(result, is(checked));
}
/**
* Test pyramid(int h) with incorrect height.
*/
@Test
public void whenAddIncorrectHeightThenReturnError() {
final Paint paint = new Paint();
final String checked = "You can't build a pyramid with that height!";
final int h = -2;
final String result = paint.pyramid(h);
assertThat(result, is(checked));
}
} | {
"content_hash": "981690befca4af65b99a2c66c434aab1",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 71,
"avg_line_length": 19.977777777777778,
"alnum_prop": 0.6618464961067854,
"repo_name": "amezgin/amezgin",
"id": "cc10ed4eff04d0490eeb7cab73187db46f052e41",
"size": "899",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chapter_001/Loops/paint/src/test/java/ru/job4j/PaintTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "36230"
},
{
"name": "Java",
"bytes": "753225"
},
{
"name": "Roff",
"bytes": "4030"
},
{
"name": "XSLT",
"bytes": "532"
}
],
"symlink_target": ""
} |
package com.flaptor.util;
/**
* This enum simply represents the possible states of a class that
* can be stopped with an intermediate "stopping" state.
* @see Stoppable
*/
public enum RunningState {
RUNNING,
STOPPING,
STOPPED
}
| {
"content_hash": "ced2b01bb424ca1d40cf59945ad486c1",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 66,
"avg_line_length": 17.642857142857142,
"alnum_prop": 0.7004048582995951,
"repo_name": "zkmake520/Android_Search",
"id": "e4be43f16b5314cd64fcb2a6a750bf0ed94cd395",
"size": "823",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "indextank-engine-master/flaptor-util/com/flaptor/util/RunningState.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "24855"
},
{
"name": "C++",
"bytes": "751650"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "57441"
},
{
"name": "Java",
"bytes": "2427431"
},
{
"name": "Makefile",
"bytes": "13107"
},
{
"name": "Python",
"bytes": "48970"
},
{
"name": "Shell",
"bytes": "7563"
},
{
"name": "Smalltalk",
"bytes": "1100"
},
{
"name": "Thrift",
"bytes": "15876"
}
],
"symlink_target": ""
} |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Umbraco.Cms.Core.Trees;
using Umbraco.Cms.Web.Common.ModelBinders;
namespace Umbraco.Cms.Web.BackOffice.Trees;
/// <summary>
/// Represents an TreeNodeController
/// </summary>
public interface ITreeNodeController
{
/// <summary>
/// Gets an individual tree node
/// </summary>
/// <param name="id"></param>
/// <param name="queryStrings"></param>
/// <returns></returns>
ActionResult<TreeNode?> GetTreeNode(
string id,
[ModelBinder(typeof(HttpQueryStringModelBinder))]
FormCollection? queryStrings
);
}
| {
"content_hash": "ec1a07c489fa9690420c76eac6b5da18",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 57,
"avg_line_length": 26.708333333333332,
"alnum_prop": 0.6739469578783152,
"repo_name": "abryukhov/Umbraco-CMS",
"id": "2ec1e7f5200a104a482fad5f55c7ed68a7e226f6",
"size": "641",
"binary": false,
"copies": "5",
"ref": "refs/heads/v10/contrib",
"path": "src/Umbraco.Web.BackOffice/Trees/ITreeNodeController.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "16182634"
},
{
"name": "CSS",
"bytes": "20943"
},
{
"name": "Dockerfile",
"bytes": "1349"
},
{
"name": "HTML",
"bytes": "1376922"
},
{
"name": "JavaScript",
"bytes": "4774243"
},
{
"name": "Less",
"bytes": "744095"
},
{
"name": "Smalltalk",
"bytes": "1"
},
{
"name": "TypeScript",
"bytes": "186621"
}
],
"symlink_target": ""
} |
package net.dontdrinkandroot.example.angularrestspringsecurity;
public class JsonViews {
public static class User {
}
public static class Admin extends User {
}
}
| {
"content_hash": "b56661ddb1a458b60fca0c6050d435fd",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 63,
"avg_line_length": 15.545454545454545,
"alnum_prop": 0.7719298245614035,
"repo_name": "edenchen123/front-end-security-POC",
"id": "2705aecc83e7ce024431fff3297980ce30f7298c",
"size": "171",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/net/dontdrinkandroot/example/angularrestspringsecurity/JsonViews.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1268"
},
{
"name": "Java",
"bytes": "27002"
},
{
"name": "JavaScript",
"bytes": "825559"
},
{
"name": "Shell",
"bytes": "52"
}
],
"symlink_target": ""
} |
<?php
/* TwigBundle:Exception:error.rdf.twig */
class __TwigTemplate_34abca1b26ee80fa906cb43afcd897b0270a94756103c54a80b237254085b074 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$this->env->loadTemplate("TwigBundle:Exception:error.xml.twig")->display($context);
}
public function getTemplateName()
{
return "TwigBundle:Exception:error.rdf.twig";
}
public function getDebugInfo()
{
return array ( 19 => 1,);
}
}
| {
"content_hash": "a8be5e1932f26094104ed5960f45fa5b",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 107,
"avg_line_length": 23.322580645161292,
"alnum_prop": 0.6251728907330567,
"repo_name": "Grugg/Symfony",
"id": "f7b0f905df228dfed63555a29f9c43d262eb49cb",
"size": "723",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/cache/dev/twig/34/ab/ca1b26ee80fa906cb43afcd897b0270a94756103c54a80b237254085b074.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15716"
},
{
"name": "PHP",
"bytes": "43740"
},
{
"name": "Shell",
"bytes": "333"
}
],
"symlink_target": ""
} |
@implementation Framework2PublicClass1
- (NSString *)passAlongFramework1RandomString {
Framework1PublicClass1 *f1c1 = [[Framework1PublicClass1 alloc] init];
return [f1c1 createRandomString];
}
@end
| {
"content_hash": "f8b0fae2a98311f2e5f0390231826aac",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 73,
"avg_line_length": 26,
"alnum_prop": 0.7836538461538461,
"repo_name": "khawkins/KHCocoaPodsFramework2",
"id": "456fcba6569ce31105ac219414b8248ded60218b",
"size": "470",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "KHCocoaPodsFramework2/KHCocoaPodsFramework2/Framework2PublicClass1.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "2380"
}
],
"symlink_target": ""
} |
package org.zstack.sdk;
import java.util.HashMap;
import java.util.Map;
import org.zstack.sdk.*;
public class UpdateAccountAction extends AbstractAction {
private static final HashMap<String, Parameter> parameterMap = new HashMap<>();
private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>();
public static class Result {
public ErrorCode error;
public org.zstack.sdk.UpdateAccountResult value;
public Result throwExceptionIfError() {
if (error != null) {
throw new ApiException(
String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details)
);
}
return this;
}
}
@Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String uuid;
@Param(required = false, maxLength = 255, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String password;
@Param(required = false, maxLength = 255, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String name;
@Param(required = false, maxLength = 2048, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String description;
@Param(required = false, maxLength = 255, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String oldPassword;
@Param(required = false)
public java.util.List systemTags;
@Param(required = false)
public java.util.List userTags;
@Param(required = false)
public String sessionId;
@Param(required = false)
public String accessKeyId;
@Param(required = false)
public String accessKeySecret;
@Param(required = false)
public String requestIp;
@NonAPIParam
public long timeout = -1;
@NonAPIParam
public long pollingInterval = -1;
private Result makeResult(ApiResult res) {
Result ret = new Result();
if (res.error != null) {
ret.error = res.error;
return ret;
}
org.zstack.sdk.UpdateAccountResult value = res.getResult(org.zstack.sdk.UpdateAccountResult.class);
ret.value = value == null ? new org.zstack.sdk.UpdateAccountResult() : value;
return ret;
}
public Result call() {
ApiResult res = ZSClient.call(this);
return makeResult(res);
}
public void call(final Completion<Result> completion) {
ZSClient.call(this, new InternalCompletion() {
@Override
public void complete(ApiResult res) {
completion.complete(makeResult(res));
}
});
}
protected Map<String, Parameter> getParameterMap() {
return parameterMap;
}
protected Map<String, Parameter> getNonAPIParameterMap() {
return nonAPIParameterMap;
}
protected RestInfo getRestInfo() {
RestInfo info = new RestInfo();
info.httpMethod = "PUT";
info.path = "/accounts/{uuid}";
info.needSession = true;
info.needPoll = true;
info.parameterName = "updateAccount";
return info;
}
}
| {
"content_hash": "b005c796d9662b7508620418c3bd8b3c",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 128,
"avg_line_length": 29.68141592920354,
"alnum_prop": 0.6320810971973763,
"repo_name": "zstackorg/zstack",
"id": "ff9178a1d6efaff820107bc66527a9de8356c44c",
"size": "3354",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "sdk/src/main/java/org/zstack/sdk/UpdateAccountAction.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "54952"
},
{
"name": "Batchfile",
"bytes": "1132"
},
{
"name": "Groovy",
"bytes": "832169"
},
{
"name": "Java",
"bytes": "15798995"
},
{
"name": "Shell",
"bytes": "152829"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SurfnetSSO.Platform.WP8")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SurfnetSSO.Platform.WP8")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | {
"content_hash": "88d509f5bd38b6f0ab8ee6a05b8b5cb2",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 84,
"avg_line_length": 36.6551724137931,
"alnum_prop": 0.7431796801505174,
"repo_name": "ajmdonker/nonweb-sso-windows",
"id": "1e12da69b4a3ce9aebd678bb5e0998fee38cd5d8",
"size": "1066",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "csharp/library/SurfnetSSO.Platform.WP8/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "40112"
},
{
"name": "CSS",
"bytes": "276"
},
{
"name": "HTML",
"bytes": "2159"
},
{
"name": "JavaScript",
"bytes": "21229"
}
],
"symlink_target": ""
} |
/*
Buffer VCF records and perform operations on the buffer
*/
#ifndef __VCFBUF_H__
#define __VCFBUF_H__
#include <htslib/vcf.h>
typedef struct _vcfbuf_t vcfbuf_t;
// Modes of operation
typedef enum
{
VCFBUF_LD_MAX, // vcfbuf_max_ld() stops at the first record that exceeds the threshold
VCFBUF_RAND_MISSING, // randomize rather than ignore missing genotypes
VCFBUF_SKIP_FILTER, // skip sites with FILTER diferent from "PASS" or "."
VCFBUF_NSITES, // leave at max this many sites in the window
VCFBUF_AF_TAG, // use this INFO tag with LD_NSITES
VCFBUF_OVERLAP_WIN, // keep only overlapping variants in the window
}
vcfbuf_opt_t;
#define vcfbuf_set_opt(buf,type,key,value) { type tmp = value; vcfbuf_set(buf, key, (void*)&tmp); }
void vcfbuf_set(vcfbuf_t *buf, vcfbuf_opt_t key, void *value);
/*
* vcfbuf_init() - init buffer
* @win: number of sites (>0) or bp (<0)
*/
vcfbuf_t *vcfbuf_init(bcf_hdr_t *hdr, int win);
void vcfbuf_destroy(vcfbuf_t *buf);
/*
* vcfbuf_push() - push a new site for analysis
* @swap: if set, do not create a copy, but return a substitute
*/
bcf1_t *vcfbuf_push(vcfbuf_t *buf, bcf1_t *rec, int swap);
bcf1_t *vcfbuf_flush(vcfbuf_t *buf, int flush_all);
/*
* vcfbuf_nsites() - return the number of sites in the buffer
*/
int vcfbuf_nsites(vcfbuf_t *buf);
/*
* vcfbuf_max_ld() - return a record that has maximum D or first record exceeding the threshold
* @ld: will be filled with the maximum D found
*/
bcf1_t *vcfbuf_max_ld(vcfbuf_t *buf, bcf1_t *rec, double *ld);
#endif
| {
"content_hash": "57479effa0c4e59574ce7e0724280512",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 99,
"avg_line_length": 28.17543859649123,
"alnum_prop": 0.6606475716064757,
"repo_name": "kyleabeauchamp/pysam",
"id": "5494323df8f522a12a715c0e7c8e19e931879c0f",
"size": "2795",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "bcftools/vcfbuf.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7844435"
},
{
"name": "C++",
"bytes": "39716"
},
{
"name": "M4",
"bytes": "23683"
},
{
"name": "Makefile",
"bytes": "34656"
},
{
"name": "Perl",
"bytes": "42945"
},
{
"name": "Python",
"bytes": "1030265"
},
{
"name": "Roff",
"bytes": "26944"
},
{
"name": "Scilab",
"bytes": "2872"
},
{
"name": "Shell",
"bytes": "20201"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "bfb1e7aafce15a53aa6bf7a27fed812f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "f791f00131834f07ca6dfb190631817804d72400",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Moraceae/Cephalotrophis/Cephalotrophis puberula/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'Deep Dive Chat' });
}; | {
"content_hash": "94b09fbbe4b921c1e05260dfdd42ecb7",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 51,
"avg_line_length": 14.625,
"alnum_prop": 0.5811965811965812,
"repo_name": "gurunate/deepdivechat",
"id": "f923fa1a3e522254185297a6a7c626c300d12679",
"size": "117",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "routes/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1715"
},
{
"name": "JavaScript",
"bytes": "24330"
}
],
"symlink_target": ""
} |
// Originally submitted to OSEHRA 2/21/2017 by DSS, Inc.
// Authored by DSS, Inc. 2014-2017
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VA.Gov.Artemis.CDA.Common
{
/// <summary>
///
/// </summary>
public class CdaTelephoneList: List<CdaTelephone>
{
public TEL[] ToTelArray()
{
List<TEL> returnList = new List<TEL>();
if (this.Count == 0)
returnList.Add(new TEL() { nullFlavor = "UNK" });
else
foreach (CdaTelephone cdaTel in this)
returnList.Add(cdaTel.ToTEL());
return returnList.ToArray();
}
}
}
| {
"content_hash": "4df5ba936a857ef1daef79fdecb90478",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 65,
"avg_line_length": 24.6,
"alnum_prop": 0.5691056910569106,
"repo_name": "VHAINNOVATIONS/Maternity-Tracker",
"id": "b4f1d30145e5cb2963cd2b4019bf83e513c89a9d",
"size": "740",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dashboard/va.gov.artemis.cda/Common/CdaTelephoneList.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "220"
},
{
"name": "Batchfile",
"bytes": "236"
},
{
"name": "C#",
"bytes": "3516881"
},
{
"name": "CSS",
"bytes": "28312"
},
{
"name": "JavaScript",
"bytes": "64911"
},
{
"name": "M",
"bytes": "5874308"
},
{
"name": "Pascal",
"bytes": "1610351"
},
{
"name": "XSLT",
"bytes": "119415"
}
],
"symlink_target": ""
} |
package org.symphonyoss.symphony.clients.impl;
import org.symphonyoss.client.SymphonyClientConfig;
import org.symphonyoss.client.SymphonyClientConfigID;
import org.symphonyoss.client.exceptions.ShareException;
import org.symphonyoss.client.model.SymAuth;
import org.symphonyoss.client.model.SymShareArticle;
import org.symphonyoss.symphony.agent.api.ShareApi;
import org.symphonyoss.symphony.agent.invoker.ApiClient;
import org.symphonyoss.symphony.agent.invoker.ApiException;
import org.symphonyoss.symphony.agent.model.ShareContent;
import org.symphonyoss.symphony.clients.ShareClient;
import javax.ws.rs.client.Client;
/**
* @author Frank Tarsillo on 10/22/2016.
*/
public class ShareClientImpl implements ShareClient {
private final SymAuth symAuth;
private final ApiClient apiClient;
/**
* Init
*
* @param symAuth Authorization model containing session and key tokens
* @param config Symphony Client Config
*/
public ShareClientImpl(SymAuth symAuth, SymphonyClientConfig config) {
this(symAuth, config, null);
}
/**
* If you need to override HttpClient. Important for handling individual client certs.
*
* @param symAuth Authorization model containing session and key tokens
* @param config Symphony client config
* @param httpClient Custom HTTP client
*/
public ShareClientImpl(SymAuth symAuth, SymphonyClientConfig config, Client httpClient) {
this.symAuth = symAuth;
//Get Service client to query for userID.
apiClient = org.symphonyoss.symphony.agent.invoker.Configuration.getDefaultApiClient();
if (httpClient != null)
apiClient.setHttpClient(httpClient);
apiClient.setBasePath(config.get(SymphonyClientConfigID.POD_URL));
}
@Override
public void shareArticle(String streamId, SymShareArticle article) throws ShareException {
ShareApi shareApi = new ShareApi(apiClient);
ShareContent shareContent = new ShareContent();
shareContent.setContent(SymShareArticle.toShareArticle(article));
shareContent.setType("com.symphony.sharing.article");
try {
shareApi.v3StreamSidSharePost(streamId, symAuth.getSessionToken().getToken(), shareContent, symAuth.getKeyToken().getToken());
} catch (ApiException e) {
throw new ShareException(e);
}
}
}
| {
"content_hash": "41fc55c08381a7bbc0f035535a4235e7",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 138,
"avg_line_length": 29.524390243902438,
"alnum_prop": 0.7240809582817018,
"repo_name": "symphonyoss/symphony-java-client",
"id": "f8ce2bed7acc509705db5cfe57aa513c5bad9a03",
"size": "3294",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "symphony-client/src/main/java/org/symphonyoss/symphony/clients/impl/ShareClientImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "695383"
},
{
"name": "Shell",
"bytes": "1987"
}
],
"symlink_target": ""
} |
require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper'))
describe Doodle, "doodle_context" do
temporary_constants :Foo, :Bar do
before :each do
class ::Child < Doodle
has :name
has :dad do
# there is an important difference between a block argument
# and a Proc object (proc/lambda) argument
# - a proc/lamba is treated as a literal argument, i.e. the
# - value is set to a Proc
# - a block argument, on the other hand, is instance
# evaluated during initialization
# - consequences
# - can only be done in init block
# - somewhat subtle difference (from programmer's point of
# view) between a proc and a block
# Also note re: Doodle.parent - its value is only valid
# during initialization - this is a way to capture that
# value for use later
init { doodle.parent }
end
end
class Parent < Child
has :children, :collect => Child
end
end
it 'should provide a means to find out the current parent of an item in initialization block' do
dad = Parent 'Conn' do
child 'Sean'
child 'Paul'
end
sean = dad.children[0]
sean.dad.name.should_be 'Conn'
sean.doodle.parent.name.should_be 'Conn'
end
end
end
| {
"content_hash": "03a127cf2e17f5cf9c0e0795f362f62e",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 100,
"avg_line_length": 30.955555555555556,
"alnum_prop": 0.592964824120603,
"repo_name": "seanohalpin/doodle",
"id": "1bfa668f7d3703ea4ee405e39ac245c7db78dd9b",
"size": "1393",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/doodle_context_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "352275"
},
{
"name": "Shell",
"bytes": "109"
}
],
"symlink_target": ""
} |
Release History
===============
14.0.1 (2016-01-21)
-------------------
* Upgrade from pip 8.0.0 to 8.0.2.
* Fix the default of ``--(no-)download`` to default to downloading.
14.0.0 (2016-01-19)
-------------------
* **BACKWARDS INCOMPATIBLE** Drop support for Python 3.2.
* Upgrade setuptools to 19.4
* Upgrade wheel to 0.26.0
* Upgrade pip to 8.0.0
* Upgrade argparse to 1.4.0
* Added support for ``python-config`` script (:pull:`798`)
* Updated activate.fish (:pull:`589`) (:pull:`799`)
* Account for a ``site.pyo`` correctly in some python implementations (:pull:`759`)
* Properly restore an empty PS1 (:issue:`407`)
* Properly remove ``pydoc`` when deactivating
* Remove workaround for very old Mageia / Mandriva linuxes (:pull:`472`)
* Added a space after virtualenv name in the prompt: ``(env) $PS1``
* Make sure not to run a --user install when creating the virtualenv (:pull:`803`)
* Remove virtualenv file's path from directory when executing with a new
python. Fixes issue :issue:`779`, :issue:`763` (:pull:`805`)
* Remove use of () in .bat files so ``Program Files (x86)`` works :issue:`35`
* Download new releases of the preinstalled software from PyPI when there are
new releases available. This behavior can be disabled using
``--no-download``.
* Make ``--no-setuptools``, ``--no-pip``, and ``--no-wheel`` independent of
each other.
13.1.2 (2015-08-23)
-------------------
* Upgrade pip to 7.1.2.
13.1.1 (2015-08-20)
-------------------
* Upgrade pip to 7.1.1.
* Upgrade setuptools to 18.2.
* Make the activate script safe to use when bash is running with ``-u``.
13.1.0 (2015-06-30)
-------------------
* Upgrade pip to 7.1.0
* Upgrade setuptools to 18.0.1
13.0.3 (2015-06-01)
-------------------
* Upgrade pip to 7.0.3
13.0.2 (2015-06-01)
-------------------
* Upgrade pip to 7.0.2
* Upgrade setuptools to 17.0
13.0.1 (2015-05-22)
-------------------
* Upgrade pip to 7.0.1
13.0.0 (2015-05-21)
-------------------
* Automatically install wheel when creating a new virutalenv. This can be
disabled by using the ``--no-wheel`` option.
* Don't trust the current directory as a location to discover files to install
packages from.
* Upgrade setuptools to 16.0.
* Upgrade pip to 7.0.0.
12.1.1 (2015-04-07)
-------------------
* Upgrade pip to 6.1.1
12.1.0 (2015-04-07)
-------------------
* Upgrade setuptools to 15.0
* Upgrade pip to 6.1.0
12.0.7 (2015-02-04)
-------------------
* Upgrade pip to 6.0.8
12.0.6 (2015-01-28)
-------------------
* Upgrade pip to 6.0.7
* Upgrade setuptools to 12.0.5
12.0.5 (2015-01-03)
-------------------
* Upgrade pip to 6.0.6
* Upgrade setuptools to 11.0
12.0.4 (2014-12-23)
-------------------
* Revert the fix to ``-p`` on Debian based pythons as it was broken in other
situations.
* Revert several sys.path changes new in 12.0 which were breaking virtualenv.
12.0.3 (2014-12-23)
-------------------
* Fix an issue where Debian based Pythons would fail when using -p with the
host Python.
* Upgrade pip to 6.0.3
12.0.2 (2014-12-23)
-------------------
* Upgraded pip to 6.0.2
12.0.1 (2014-12-22)
-------------------
* Upgraded pip to 6.0.1
12.0 (2014-12-22)
-----------------
* **PROCESS** Version numbers are now simply ``X.Y`` where the leading ``1``
has been dropped.
* Split up documentation into structured pages
* Now using pytest framework
* Correct sys.path ordering for debian, issue #461
* Correctly throws error on older Pythons, issue #619
* Allow for empty $PATH, pull #601
* Don't set prompt if $env:VIRTUAL_ENV_DISABLE_PROMPT is set for Powershell
* Updated setuptools to 7.0
1.11.6 (2014-05-16)
-------------------
* Updated setuptools to 3.6
* Updated pip to 1.5.6
1.11.5 (2014-05-03)
-------------------
* Updated setuptools to 3.4.4
* Updated documentation to use https://virtualenv.pypa.io/
* Updated pip to 1.5.5
1.11.4 (2014-02-21)
-------------------
* Updated pip to 1.5.4
1.11.3 (2014-02-20)
-------------------
* Updated setuptools to 2.2
* Updated pip to 1.5.3
1.11.2 (2014-01-26)
-------------------
* Fixed easy_install installed virtualenvs by updated pip to 1.5.2
1.11.1 (2014-01-20)
-------------------
* Fixed an issue where pip and setuptools were not getting installed when using
the ``--system-site-packages`` flag.
* Updated setuptools to fix an issue when installed with easy_install
* Fixed an issue with Python 3.4 and sys.stdout encoding being set to ascii
* Upgraded pip to v1.5.1
* Upgraded setuptools to v2.1
1.11 (2014-01-02)
-----------------
* **BACKWARDS INCOMPATIBLE** Switched to using wheels for the bundled copies of
setuptools and pip. Using sdists is no longer supported - users supplying
their own versions of pip/setuptools will need to provide wheels.
* **BACKWARDS INCOMPATIBLE** Modified the handling of ``--extra-search-dirs``.
This option now works like pip's ``--find-links`` option, in that it adds
extra directories to search for compatible wheels for pip and setuptools.
The actual wheel selected is chosen based on version and compatibility, using
the same algorithm as ``pip install setuptools``.
* Fixed #495, --always-copy was failing (#PR 511)
* Upgraded pip to v1.5
* Upgraded setuptools to v1.4
1.10.1 (2013-08-07)
-------------------
* **New Signing Key** Release 1.10.1 is using a different key than normal with
fingerprint: 7C6B 7C5D 5E2B 6356 A926 F04F 6E3C BCE9 3372 DCFA
* Upgraded pip to v1.4.1
* Upgraded setuptools to v0.9.8
1.10 (2013-07-23)
-----------------
* **BACKWARDS INCOMPATIBLE** Dropped support for Python 2.5. The minimum
supported Python version is now Python 2.6.
* **BACKWARDS INCOMPATIBLE** Using ``virtualenv.py`` as an isolated script
(i.e. without an associated ``virtualenv_support`` directory) is no longer
supported for security reasons and will fail with an error.
Along with this, ``--never-download`` is now always pinned to ``True``, and
is only being maintained in the short term for backward compatibility
(Pull #412).
* **IMPORTANT** Switched to the new setuptools (v0.9.7) which has been merged
with Distribute_ again and works for Python 2 and 3 with one codebase.
The ``--distribute`` and ``--setuptools`` options are now no-op.
* Updated to pip 1.4.
* Added support for PyPy3k
* Added the option to use a version number with the ``-p`` option to get the
system copy of that Python version (Windows only)
* Removed embedded ``ez_setup.py``, ``distribute_setup.py`` and
``distribute_from_egg.py`` files as part of switching to merged setuptools.
* Fixed ``--relocatable`` to work better on Windows.
* Fixed issue with readline on Windows.
.. _Distribute: https://pypi.python.org/pypi/distribute
1.9.1 (2013-03-08)
------------------
* Updated to pip 1.3.1 that fixed a major backward incompatible change of
parsing URLs to externally hosted packages that got accidentily included
in pip 1.3.
1.9 (2013-03-07)
----------------
* Unset VIRTUAL_ENV environment variable in deactivate.bat (Pull #364)
* Upgraded distribute to 0.6.34.
* Added ``--no-setuptools`` and ``--no-pip`` options (Pull #336).
* Fixed Issue #373. virtualenv-1.8.4 was failing in cygwin (Pull #382).
* Fixed Issue #378. virtualenv is now "multiarch" aware on debian/ubuntu (Pull #379).
* Fixed issue with readline module path on pypy and OSX (Pull #374).
* Made 64bit detection compatible with Python 2.5 (Pull #393).
1.8.4 (2012-11-25)
------------------
* Updated distribute to 0.6.31. This fixes #359 (numpy install regression) on
UTF-8 platforms, and provides a workaround on other platforms:
``PYTHONIOENCODING=utf8 pip install numpy``.
* When installing virtualenv via curl, don't forget to filter out arguments
the distribute setup script won't understand. Fixes #358.
* Added some more integration tests.
* Removed the unsupported embedded setuptools egg for Python 2.4 to reduce
file size.
1.8.3 (2012-11-21)
------------------
* Fixed readline on OS X. Thanks minrk
* Updated distribute to 0.6.30 (improves our error reporting, plus new
distribute features and fixes). Thanks Gabriel (g2p)
* Added compatibility with multiarch Python (Python 3.3 for example). Added an
integration test. Thanks Gabriel (g2p)
* Added ability to install distribute from a user-provided egg, rather than the
bundled sdist, for better speed. Thanks Paul Moore.
* Make the creation of lib64 symlink smarter about already-existing symlink,
and more explicit about full paths. Fixes #334 and #330. Thanks Jeremy Orem.
* Give lib64 site-dir preference over lib on 64-bit systems, to avoid wrong
32-bit compiles in the venv. Fixes #328. Thanks Damien Nozay.
* Fix a bug with prompt-handling in ``activate.csh`` in non-interactive csh
shells. Fixes #332. Thanks Benjamin Root for report and patch.
* Make it possible to create a virtualenv from within a Python
3.3. pyvenv. Thanks Chris McDonough for the report.
* Add optional --setuptools option to be able to switch to it in case
distribute is the default (like in Debian).
1.8.2 (2012-09-06)
------------------
* Updated the included pip version to 1.2.1 to fix regressions introduced
there in 1.2.
1.8.1 (2012-09-03)
------------------
* Fixed distribute version used with `--never-download`. Thanks michr for
report and patch.
* Fix creating Python 3.3 based virtualenvs by unsetting the
``__PYVENV_LAUNCHER__`` environment variable in subprocesses.
1.8 (2012-09-01)
----------------
* **Dropped support for Python 2.4** The minimum supported Python version is
now Python 2.5.
* Fix `--relocatable` on systems that use lib64. Fixes #78. Thanks Branden
Rolston.
* Symlink some additional modules under Python 3. Fixes #194. Thanks Vinay
Sajip, Ian Clelland, and Stefan Holek for the report.
* Fix ``--relocatable`` when a script uses ``__future__`` imports. Thanks
Branden Rolston.
* Fix a bug in the config option parser that prevented setting negative
options with environment variables. Thanks Ralf Schmitt.
* Allow setting ``--no-site-packages`` from the config file.
* Use ``/usr/bin/multiarch-platform`` if available to figure out the include
directory. Thanks for the patch, Mika Laitio.
* Fix ``install_name_tool`` replacement to work on Python 3.X.
* Handle paths of users' site-packages on Mac OS X correctly when changing
the prefix.
* Updated the embedded version of distribute to 0.6.28 and pip to 1.2.
1.7.2 (2012-06-22)
------------------
* Updated to distribute 0.6.27.
* Fix activate.fish on OS X. Fixes #8. Thanks David Schoonover.
* Create a virtualenv-x.x script with the Python version when installing, so
virtualenv for multiple Python versions can be installed to the same
script location. Thanks Miki Tebeka.
* Restored ability to create a virtualenv with a path longer than 78
characters, without breaking creation of virtualenvs with non-ASCII paths.
Thanks, Bradley Ayers.
* Added ability to create virtualenvs without having installed Apple's
developers tools (using an own implementation of ``install_name_tool``).
Thanks Mike Hommey.
* Fixed PyPy and Jython support on Windows. Thanks Konstantin Zemlyak.
* Added pydoc script to ease use. Thanks Marc Abramowitz. Fixes #149.
* Fixed creating a bootstrap script on Python 3. Thanks Raul Leal. Fixes #280.
* Fixed inconsistency when having set the ``PYTHONDONTWRITEBYTECODE`` env var
with the --distribute option or the ``VIRTUALENV_USE_DISTRIBUTE`` env var.
``VIRTUALENV_USE_DISTRIBUTE`` is now considered again as a legacy alias.
1.7.1.2 (2012-02-17)
--------------------
* Fixed minor issue in `--relocatable`. Thanks, Cap Petschulat.
1.7.1.1 (2012-02-16)
--------------------
* Bumped the version string in ``virtualenv.py`` up, too.
* Fixed rST rendering bug of long description.
1.7.1 (2012-02-16)
------------------
* Update embedded pip to version 1.1.
* Fix `--relocatable` under Python 3. Thanks Doug Hellmann.
* Added environ PATH modification to activate_this.py. Thanks Doug
Napoleone. Fixes #14.
* Support creating virtualenvs directly from a Python build directory on
Windows. Thanks CBWhiz. Fixes #139.
* Use non-recursive symlinks to fix things up for posix_local install
scheme. Thanks michr.
* Made activate script available for use with msys and cygwin on Windows.
Thanks Greg Haskins, Cliff Xuan, Jonathan Griffin and Doug Napoleone.
Fixes #176.
* Fixed creation of virtualenvs on Windows when Python is not installed for
all users. Thanks Anatoly Techtonik for report and patch and Doug
Napoleone for testing and confirmation. Fixes #87.
* Fixed creation of virtualenvs using -p in installs where some modules
that ought to be in the standard library (e.g. `readline`) are actually
installed in `site-packages` next to `virtualenv.py`. Thanks Greg Haskins
for report and fix. Fixes #167.
* Added activation script for Powershell (signed by Jannis Leidel). Many
thanks to Jason R. Coombs.
1.7 (2011-11-30)
----------------
* Gave user-provided ``--extra-search-dir`` priority over default dirs for
finding setuptools/distribute (it already had priority for finding pip).
Thanks Ethan Jucovy.
* Updated embedded Distribute release to 0.6.24. Thanks Alex Gronholm.
* Made ``--no-site-packages`` behavior the default behavior. The
``--no-site-packages`` flag is still permitted, but displays a warning when
used. Thanks Chris McDonough.
* New flag: ``--system-site-packages``; this flag should be passed to get the
previous default global-site-package-including behavior back.
* Added ability to set command options as environment variables and options
in a ``virtualenv.ini`` file.
* Fixed various encoding related issues with paths. Thanks Gunnlaugur Thor Briem.
* Made ``virtualenv.py`` script executable.
1.6.4 (2011-07-21)
------------------
* Restored ability to run on Python 2.4, too.
1.6.3 (2011-07-16)
------------------
* Restored ability to run on Python < 2.7.
1.6.2 (2011-07-16)
------------------
* Updated embedded distribute release to 0.6.19.
* Updated embedded pip release to 1.0.2.
* Fixed #141 - Be smarter about finding pkg_resources when using the
non-default Python interpreter (by using the ``-p`` option).
* Fixed #112 - Fixed path in docs.
* Fixed #109 - Corrected doctests of a Logger method.
* Fixed #118 - Fixed creating virtualenvs on platforms that use the
"posix_local" install scheme, such as Ubuntu with Python 2.7.
* Add missing library to Python 3 virtualenvs (``_dummy_thread``).
1.6.1 (2011-04-30)
------------------
* Start to use git-flow.
* Added support for PyPy 1.5
* Fixed #121 -- added sanity-checking of the -p argument. Thanks Paul Nasrat.
* Added progress meter for pip installation as well as setuptools. Thanks Ethan
Jucovy.
* Added --never-download and --search-dir options. Thanks Ethan Jucovy.
1.6
---
* Added Python 3 support! Huge thanks to Vinay Sajip and Vitaly Babiy.
* Fixed creation of virtualenvs on Mac OS X when standard library modules
(readline) are installed outside the standard library.
* Updated bundled pip to 1.0.
1.5.2
-----
* Moved main repository to Github: https://github.com/pypa/virtualenv
* Transferred primary maintenance from Ian to Jannis Leidel, Carl Meyer and Brian Rosner
* Fixed a few more pypy related bugs.
* Updated bundled pip to 0.8.2.
* Handed project over to new team of maintainers.
* Moved virtualenv to Github at https://github.com/pypa/virtualenv
1.5.1
-----
* Added ``_weakrefset`` requirement for Python 2.7.1.
* Fixed Windows regression in 1.5
1.5
---
* Include pip 0.8.1.
* Add support for PyPy.
* Uses a proper temporary dir when installing environment requirements.
* Add ``--prompt`` option to be able to override the default prompt prefix.
* Fix an issue with ``--relocatable`` on Windows.
* Fix issue with installing the wrong version of distribute.
* Add fish and csh activate scripts.
1.4.9
-----
* Include pip 0.7.2
1.4.8
-----
* Fix for Mac OS X Framework builds that use
``--universal-archs=intel``
* Fix ``activate_this.py`` on Windows.
* Allow ``$PYTHONHOME`` to be set, so long as you use ``source
bin/activate`` it will get unset; if you leave it set and do not
activate the environment it will still break the environment.
* Include pip 0.7.1
1.4.7
-----
* Include pip 0.7
1.4.6
-----
* Allow ``activate.sh`` to skip updating the prompt (by setting
``$VIRTUAL_ENV_DISABLE_PROMPT``).
1.4.5
-----
* Include pip 0.6.3
* Fix ``activate.bat`` and ``deactivate.bat`` under Windows when
``PATH`` contained a parenthesis
1.4.4
-----
* Include pip 0.6.2 and Distribute 0.6.10
* Create the ``virtualenv`` script even when Setuptools isn't
installed
* Fix problem with ``virtualenv --relocate`` when ``bin/`` has
subdirectories (e.g., ``bin/.svn/``); from Alan Franzoni.
* If you set ``$VIRTUALENV_DISTRIBUTE`` then virtualenv will use
Distribute by default (so you don't have to remember to use
``--distribute``).
1.4.3
-----
* Include pip 0.6.1
1.4.2
-----
* Fix pip installation on Windows
* Fix use of stand-alone ``virtualenv.py`` (and boot scripts)
* Exclude ~/.local (user site-packages) from environments when using
``--no-site-packages``
1.4.1
-----
* Include pip 0.6
1.4
---
* Updated setuptools to 0.6c11
* Added the --distribute option
* Fixed packaging problem of support-files
1.3.4
-----
* Virtualenv now copies the actual embedded Python binary on
Mac OS X to fix a hang on Snow Leopard (10.6).
* Fail more gracefully on Windows when ``win32api`` is not installed.
* Fix site-packages taking precedent over Jython's ``__classpath__``
and also specially handle the new ``__pyclasspath__`` entry in
``sys.path``.
* Now copies Jython's ``registry`` file to the virtualenv if it exists.
* Better find libraries when compiling extensions on Windows.
* Create ``Scripts\pythonw.exe`` on Windows.
* Added support for the Debian/Ubuntu
``/usr/lib/pythonX.Y/dist-packages`` directory.
* Set ``distutils.sysconfig.get_config_vars()['LIBDIR']`` (based on
``sys.real_prefix``) which is reported to help building on Windows.
* Make ``deactivate`` work on ksh
* Fixes for ``--python``: make it work with ``--relocatable`` and the
symlink created to the exact Python version.
1.3.3
-----
* Use Windows newlines in ``activate.bat``, which has been reported to help
when using non-ASCII directory names.
* Fixed compatibility with Jython 2.5b1.
* Added a function ``virtualenv.install_python`` for more fine-grained
access to what ``virtualenv.create_environment`` does.
* Fix `a problem <https://bugs.launchpad.net/virtualenv/+bug/241581>`_
with Windows and paths that contain spaces.
* If ``/path/to/env/.pydistutils.cfg`` exists (or
``/path/to/env/pydistutils.cfg`` on Windows systems) then ignore
``~/.pydistutils.cfg`` and use that other file instead.
* Fix ` a problem
<https://bugs.launchpad.net/virtualenv/+bug/340050>`_ picking up
some ``.so`` libraries in ``/usr/local``.
1.3.2
-----
* Remove the ``[install] prefix = ...`` setting from the virtualenv
``distutils.cfg`` -- this has been causing problems for a lot of
people, in rather obscure ways.
* If you use a boot script it will attempt to import ``virtualenv``
and find a pre-downloaded Setuptools egg using that.
* Added platform-specific paths, like ``/usr/lib/pythonX.Y/plat-linux2``
1.3.1
-----
* Real Python 2.6 compatibility. Backported the Python 2.6 updates to
``site.py``, including `user directories
<http://docs.python.org/dev/whatsnew/2.6.html#pep-370-per-user-site-packages-directory>`_
(this means older versions of Python will support user directories,
whether intended or not).
* Always set ``[install] prefix`` in ``distutils.cfg`` -- previously
on some platforms where a system-wide ``distutils.cfg`` was present
with a ``prefix`` setting, packages would be installed globally
(usually in ``/usr/local/lib/pythonX.Y/site-packages``).
* Sometimes Cygwin seems to leave ``.exe`` off ``sys.executable``; a
workaround is added.
* Fix ``--python`` option.
* Fixed handling of Jython environments that use a
jython-complete.jar.
1.3
---
* Update to Setuptools 0.6c9
* Added an option ``virtualenv --relocatable EXISTING_ENV``, which
will make an existing environment "relocatable" -- the paths will
not be absolute in scripts, ``.egg-info`` and ``.pth`` files. This
may assist in building environments that can be moved and copied.
You have to run this *after* any new packages installed.
* Added ``bin/activate_this.py``, a file you can use like
``execfile("path_to/activate_this.py",
dict(__file__="path_to/activate_this.py"))`` -- this will activate
the environment in place, similar to what `the mod_wsgi example
does <http://code.google.com/p/modwsgi/wiki/VirtualEnvironments>`_.
* For Mac framework builds of Python, the site-packages directory
``/Library/Python/X.Y/site-packages`` is added to ``sys.path``, from
Andrea Rech.
* Some platform-specific modules in Macs are added to the path now
(``plat-darwin/``, ``plat-mac/``, ``plat-mac/lib-scriptpackages``),
from Andrea Rech.
* Fixed a small Bashism in the ``bin/activate`` shell script.
* Added ``__future__`` to the list of required modules, for Python
2.3. You'll still need to backport your own ``subprocess`` module.
* Fixed the ``__classpath__`` entry in Jython's ``sys.path`` taking
precedent over virtualenv's libs.
1.2
---
* Added a ``--python`` option to select the Python interpreter.
* Add ``warnings`` to the modules copied over, for Python 2.6 support.
* Add ``sets`` to the module copied over for Python 2.3 (though Python
2.3 still probably doesn't work).
1.1.1
-----
* Added support for Jython 2.5.
1.1
---
* Added support for Python 2.6.
* Fix a problem with missing ``DLLs/zlib.pyd`` on Windows. Create
* ``bin/python`` (or ``bin/python.exe``) even when you run virtualenv
with an interpreter named, e.g., ``python2.4``
* Fix MacPorts Python
* Added --unzip-setuptools option
* Update to Setuptools 0.6c8
* If the current directory is not writable, run ez_setup.py in ``/tmp``
* Copy or symlink over the ``include`` directory so that packages will
more consistently compile.
1.0
---
* Fix build on systems that use ``/usr/lib64``, distinct from
``/usr/lib`` (specifically CentOS x64).
* Fixed bug in ``--clear``.
* Fixed typos in ``deactivate.bat``.
* Preserve ``$PYTHONPATH`` when calling subprocesses.
0.9.2
-----
* Fix include dir copying on Windows (makes compiling possible).
* Include the main ``lib-tk`` in the path.
* Patch ``distutils.sysconfig``: ``get_python_inc`` and
``get_python_lib`` to point to the global locations.
* Install ``distutils.cfg`` before Setuptools, so that system
customizations of ``distutils.cfg`` won't effect the installation.
* Add ``bin/pythonX.Y`` to the virtualenv (in addition to
``bin/python``).
* Fixed an issue with Mac Framework Python builds, and absolute paths
(from Ronald Oussoren).
0.9.1
-----
* Improve ability to create a virtualenv from inside a virtualenv.
* Fix a little bug in ``bin/activate``.
* Actually get ``distutils.cfg`` to work reliably.
0.9
---
* Added ``lib-dynload`` and ``config`` to things that need to be
copied over in an environment.
* Copy over or symlink the ``include`` directory, so that you can
build packages that need the C headers.
* Include a ``distutils`` package, so you can locally update
``distutils.cfg`` (in ``lib/pythonX.Y/distutils/distutils.cfg``).
* Better avoid downloading Setuptools, and hitting PyPI on environment
creation.
* Fix a problem creating a ``lib64/`` directory.
* Should work on MacOSX Framework builds (the default Python
installations on Mac). Thanks to Ronald Oussoren.
0.8.4
-----
* Windows installs would sometimes give errors about ``sys.prefix`` that
were inaccurate.
* Slightly prettier output.
0.8.3
-----
* Added support for Windows.
0.8.2
-----
* Give a better warning if you are on an unsupported platform (Mac
Framework Pythons, and Windows).
* Give error about running while inside a workingenv.
* Give better error message about Python 2.3.
0.8.1
-----
Fixed packaging of the library.
0.8
---
Initial release. Everything is changed and new!
| {
"content_hash": "f4b9922a4acd88a2b9fd1d61f5b1b275",
"timestamp": "",
"source": "github",
"line_count": 916,
"max_line_length": 91,
"avg_line_length": 26.558951965065503,
"alnum_prop": 0.6908089444261756,
"repo_name": "Leonnash21/flask_heroku",
"id": "5529c40c7374742c03131f41ef26ec67b2feec81",
"size": "24328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/changes.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1231"
},
{
"name": "C#",
"bytes": "8440"
},
{
"name": "CSS",
"bytes": "167702"
},
{
"name": "F#",
"bytes": "2310"
},
{
"name": "Forth",
"bytes": "506"
},
{
"name": "GLSL",
"bytes": "1040"
},
{
"name": "HTML",
"bytes": "3428"
},
{
"name": "JavaScript",
"bytes": "48122"
},
{
"name": "Makefile",
"bytes": "2399"
},
{
"name": "Mask",
"bytes": "969"
},
{
"name": "PowerShell",
"bytes": "8175"
},
{
"name": "Python",
"bytes": "631680"
},
{
"name": "Shell",
"bytes": "16222"
},
{
"name": "Tcl",
"bytes": "2173292"
}
],
"symlink_target": ""
} |
using System;
using Xamarin.Forms.CustomAttributes;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using Xamarin.Forms.Internals;
#if UITEST
using Xamarin.UITest.iOS;
using Xamarin.UITest;
using NUnit.Framework;
#endif
namespace Xamarin.Forms.Controls
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Bugzilla, 21177, "Using a UICollectionView in a ViewRenderer results in issues with selection")]
public class Bugzilla21177 : TestContentPage
{
public class CollectionView : View
{
public event EventHandler<int> ItemSelected;
public void InvokeItemSelected(int index)
{
if (ItemSelected != null)
{
ItemSelected.Invoke(this, index);
}
}
}
protected override void Init()
{
var view = new CollectionView() { AutomationId = "view" };
view.ItemSelected += View_ItemSelected;
Content = view;
}
private void View_ItemSelected(object sender, int e)
{
DisplayAlert("Success", "Success", "Cancel");
}
#if UITEST && __IOS__
[Test]
public void Bugzilla21177Test()
{
RunningApp.WaitForElement(q => q.Marked("#1"));
RunningApp.Tap(q => q.Marked("#1"));
RunningApp.WaitForElement(q => q.Marked("Success"));
}
#endif
}
}
| {
"content_hash": "af4054161b6da56bdb151d7bff184d50",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 117,
"avg_line_length": 22.345454545454544,
"alnum_prop": 0.7030105777054516,
"repo_name": "xjpeter/Xamarin.Forms",
"id": "f97934f8566265e4a37f4a1112eaad6ff83d35ff",
"size": "1231",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Bugzilla21177.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1991"
},
{
"name": "C#",
"bytes": "6039333"
},
{
"name": "CSS",
"bytes": "3290"
},
{
"name": "HTML",
"bytes": "591"
},
{
"name": "Java",
"bytes": "2022"
},
{
"name": "JavaScript",
"bytes": "167"
},
{
"name": "Makefile",
"bytes": "3794"
},
{
"name": "PowerShell",
"bytes": "8514"
},
{
"name": "Shell",
"bytes": "1748"
}
],
"symlink_target": ""
} |
import numpy as np
from astropy.units import UnitsError, UnitConversionError, Unit
from astropy import log
from .nddata import NDData
from .nduncertainty import NDUncertainty
from .mixins.ndslicing import NDSlicingMixin
from .mixins.ndarithmetic import NDArithmeticMixin
from .mixins.ndio import NDIOMixin
from .flag_collection import FlagCollection
__all__ = ['NDDataArray']
class NDDataArray(NDArithmeticMixin, NDSlicingMixin, NDIOMixin, NDData):
"""
An ``NDData`` object with arithmetic. This class is functionally equivalent
to ``NDData`` in astropy versions prior to 1.0.
The key distinction from raw numpy arrays is the presence of
additional metadata such as uncertainties, a mask, units, flags,
and/or a coordinate system.
See also: http://docs.astropy.org/en/stable/nddata/
Parameters
-----------
data : `~numpy.ndarray` or `NDData`
The actual data contained in this `NDData` object. Not that this
will always be copies by *reference* , so you should make copy
the ``data`` before passing it in if that's the desired behavior.
uncertainty : `~astropy.nddata.NDUncertainty`, optional
Uncertainties on the data.
mask : `~numpy.ndarray`-like, optional
Mask for the data, given as a boolean Numpy array or any object that
can be converted to a boolean Numpy array with a shape
matching that of the data. The values must be ``False`` where
the data is *valid* and ``True`` when it is not (like Numpy
masked arrays). If ``data`` is a numpy masked array, providing
``mask`` here will causes the mask from the masked array to be
ignored.
flags : `~numpy.ndarray`-like or `~astropy.nddata.FlagCollection`, optional
Flags giving information about each pixel. These can be specified
either as a Numpy array of any type (or an object which can be converted
to a Numpy array) with a shape matching that of the
data, or as a `~astropy.nddata.FlagCollection` instance which has a
shape matching that of the data.
wcs : undefined, optional
WCS-object containing the world coordinate system for the data.
.. warning::
This is not yet defined because the discussion of how best to
represent this class's WCS system generically is still under
consideration. For now just leave it as None
meta : `dict`-like object, optional
Metadata for this object. "Metadata" here means all information that
is included with this object but not part of any other attribute
of this particular object. e.g., creation date, unique identifier,
simulation parameters, exposure time, telescope name, etc.
unit : `~astropy.units.UnitBase` instance or str, optional
The units of the data.
Raises
------
ValueError :
If the `uncertainty` or `mask` inputs cannot be broadcast (e.g., match
shape) onto ``data``.
"""
def __init__(self, data, *args, flags=None, **kwargs):
# Initialize with the parent...
super().__init__(data, *args, **kwargs)
# ...then reset uncertainty to force it to go through the
# setter logic below. In base NDData all that is done is to
# set self._uncertainty to whatever uncertainty is passed in.
self.uncertainty = self._uncertainty
# Same thing for mask.
self.mask = self._mask
# Initial flags because it is no longer handled in NDData
# or NDDataBase.
if isinstance(data, NDDataArray):
if flags is None:
flags = data.flags
else:
log.info("Overwriting NDDataArrays's current "
"flags with specified flags")
self.flags = flags
# Implement uncertainty as NDUncertainty to support propagation of
# uncertainties in arithmetic operations
@property
def uncertainty(self):
return self._uncertainty
@uncertainty.setter
def uncertainty(self, value):
if value is not None:
if isinstance(value, NDUncertainty):
class_name = self.__class__.__name__
if not self.unit and value._unit:
# Raise an error if uncertainty has unit and data does not
raise ValueError("Cannot assign an uncertainty with unit "
"to {} without "
"a unit".format(class_name))
self._uncertainty = value
self._uncertainty.parent_nddata = self
else:
raise TypeError("Uncertainty must be an instance of "
"a NDUncertainty object")
else:
self._uncertainty = value
# Override unit so that we can add a setter.
@property
def unit(self):
return self._unit
@unit.setter
def unit(self, value):
from . import conf
try:
if self._unit is not None and conf.warn_setting_unit_directly:
log.info('Setting the unit directly changes the unit without '
'updating the data or uncertainty. Use the '
'.convert_unit_to() method to change the unit and '
'scale values appropriately.')
except AttributeError:
# raised if self._unit has not been set yet, in which case the
# warning is irrelevant
pass
if value is None:
self._unit = None
else:
self._unit = Unit(value)
# Implement mask in a way that converts nicely to a numpy masked array
@property
def mask(self):
if self._mask is np.ma.nomask:
return None
else:
return self._mask
@mask.setter
def mask(self, value):
# Check that value is not either type of null mask.
if (value is not None) and (value is not np.ma.nomask):
mask = np.array(value, dtype=np.bool_, copy=False)
if mask.shape != self.data.shape:
raise ValueError("dimensions of mask do not match data")
else:
self._mask = mask
else:
# internal representation should be one numpy understands
self._mask = np.ma.nomask
@property
def shape(self):
"""
shape tuple of this object's data.
"""
return self.data.shape
@property
def size(self):
"""
integer size of this object's data.
"""
return self.data.size
@property
def dtype(self):
"""
`numpy.dtype` of this object's data.
"""
return self.data.dtype
@property
def ndim(self):
"""
integer dimensions of this object's data
"""
return self.data.ndim
@property
def flags(self):
return self._flags
@flags.setter
def flags(self, value):
if value is not None:
if isinstance(value, FlagCollection):
if value.shape != self.shape:
raise ValueError("dimensions of FlagCollection does not match data")
else:
self._flags = value
else:
flags = np.array(value, copy=False)
if flags.shape != self.shape:
raise ValueError("dimensions of flags do not match data")
else:
self._flags = flags
else:
self._flags = value
def __array__(self):
"""
This allows code that requests a Numpy array to use an NDData
object as a Numpy array.
"""
if self.mask is not None:
return np.ma.masked_array(self.data, self.mask)
else:
return np.array(self.data)
def __array_prepare__(self, array, context=None):
"""
This ensures that a masked array is returned if self is masked.
"""
if self.mask is not None:
return np.ma.masked_array(array, self.mask)
else:
return array
def convert_unit_to(self, unit, equivalencies=[]):
"""
Returns a new `NDData` object whose values have been converted
to a new unit.
Parameters
----------
unit : `astropy.units.UnitBase` instance or str
The unit to convert to.
equivalencies : list of equivalence pairs, optional
A list of equivalence pairs to try if the units are not
directly convertible. See :ref:`unit_equivalencies`.
Returns
-------
result : `~astropy.nddata.NDData`
The resulting dataset
Raises
------
UnitsError
If units are inconsistent.
"""
if self.unit is None:
raise ValueError("No unit specified on source data")
data = self.unit.to(unit, self.data, equivalencies=equivalencies)
if self.uncertainty is not None:
uncertainty_values = self.unit.to(unit, self.uncertainty.array,
equivalencies=equivalencies)
# should work for any uncertainty class
uncertainty = self.uncertainty.__class__(uncertainty_values)
else:
uncertainty = None
if self.mask is not None:
new_mask = self.mask.copy()
else:
new_mask = None
# Call __class__ in case we are dealing with an inherited type
result = self.__class__(data, uncertainty=uncertainty,
mask=new_mask,
wcs=self.wcs,
meta=self.meta, unit=unit)
return result
| {
"content_hash": "b6db4979b1e5d817c39c67ade58e4fec",
"timestamp": "",
"source": "github",
"line_count": 286,
"max_line_length": 88,
"avg_line_length": 34.52097902097902,
"alnum_prop": 0.582801580066849,
"repo_name": "bsipocz/astropy",
"id": "a230151d918666471f8803f18b339dcbd17703b7",
"size": "10000",
"binary": false,
"copies": "3",
"ref": "refs/heads/hacking",
"path": "astropy/nddata/compat.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "442627"
},
{
"name": "C++",
"bytes": "1057"
},
{
"name": "HTML",
"bytes": "1172"
},
{
"name": "Objective-C",
"bytes": "615"
},
{
"name": "Python",
"bytes": "9395160"
},
{
"name": "TeX",
"bytes": "853"
}
],
"symlink_target": ""
} |
<?php
class Controller_Invit extends Controller_Frontend{
// 揭晓列表
public function action_index() {
$view = View::forge('invit/index');
$this->template->title = "邀请有礼";
$this->template->layout = $view;
}
// 邀请
public function action_invit() {
$id = $this->param('id');
is_null($id) and Response::redirect('/');
Session::set('invit_id', base64_decode($id));
Response::redirect('/');
}
}
| {
"content_hash": "cf1bc3dfc393e1c34b1efa39c85b463f",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 53,
"avg_line_length": 21.565217391304348,
"alnum_prop": 0.5181451612903226,
"repo_name": "lextel/evolution",
"id": "73fb6107f73f9da546b00b36103e3716c723f344",
"size": "516",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fuel/app/classes/controller/invit.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "402179"
},
{
"name": "JavaScript",
"bytes": "5721533"
},
{
"name": "PHP",
"bytes": "6671170"
}
],
"symlink_target": ""
} |
$(document).ready(function() {
// Edit
$('[data-toggle=summernote]').each(function(){
$(this).summernote({
height: 300,
lang: 'zh-CN',
});
});
//Form Submit for IE Browser
$('button[type=\'submit\']').on('click', function() {
$("form[id*='form-']").submit();
});
// Highlight any found errors
$('.text-danger').each(function() {
var element = $(this).parent().parent();
if (element.hasClass('form-group')) {
element.addClass('has-error');
}
});
// Set last page opened on the menu
$('#menu a[href]').on('click', function() {
sessionStorage.setItem('menu', $(this).attr('href'));
});
if (!sessionStorage.getItem('menu')) {
$('#menu #dashboard').addClass('active');
} else {
// Sets active and open to selected page in the left column menu.
$('#menu a[href=\'' + sessionStorage.getItem('menu') + '\']').parents('li').addClass('active open');
}
if (localStorage.getItem('column-left') == 'active') {
$('#button-menu i').replaceWith('<i class="fa fa-dedent fa-lg"></i>');
$('#column-left').addClass('active');
// Slide Down Menu
$('#menu li.active').has('ul').children('ul').addClass('collapse in');
$('#menu li').not('.active').has('ul').children('ul').addClass('collapse');
} else {
$('#button-menu i').replaceWith('<i class="fa fa-indent fa-lg"></i>');
$('#menu li li.active').has('ul').children('ul').addClass('collapse in');
$('#menu li li').not('.active').has('ul').children('ul').addClass('collapse');
}
// Menu button
$('#button-menu').on('click', function() {
// Checks if the left column is active or not.
if ($('#column-left').hasClass('active')) {
localStorage.setItem('column-left', '');
$('#button-menu i').replaceWith('<i class="fa fa-indent fa-lg"></i>');
$('#column-left').removeClass('active');
$('#menu > li > ul').removeClass('in collapse');
$('#menu > li > ul').removeAttr('style');
} else {
localStorage.setItem('column-left', 'active');
$('#button-menu i').replaceWith('<i class="fa fa-dedent fa-lg"></i>');
$('#column-left').addClass('active');
// Add the slide down to open menu items
$('#menu li.open').has('ul').children('ul').addClass('collapse in');
$('#menu li').not('.open').has('ul').children('ul').addClass('collapse');
}
});
// Menu
$('#menu').find('li').has('ul').children('a').on('click', function() {
if ($('#column-left').hasClass('active')) {
$(this).parent('li').toggleClass('open').children('ul').collapse('toggle');
$(this).parent('li').siblings().removeClass('open').children('ul.in').collapse('hide');
} else if (!$(this).parent().parent().is('#menu')) {
$(this).parent('li').toggleClass('open').children('ul').collapse('toggle');
$(this).parent('li').siblings().removeClass('open').children('ul.in').collapse('hide');
}
});
// tooltips on hover
$('[data-toggle=\'tooltip\']').tooltip({
container: 'body',
html: true
});
// Makes tooltips work on ajax generated content
$(document).ajaxStop(function() {
$('[data-toggle=\'tooltip\']').tooltip({
container: 'body'
});
});
$('[data-toggle=\'tooltip\']').on('remove', function() {
$(this).tooltip('destroy');
});
$(document).on('click','[data-toggle=\'tooltip\']',function(e){
$('body > .tooltip').remove();
});
});
// Autocomplete */
(function($) {
$.fn.autocomplete = function(option) {
return this.each(function() {
this.timer = null;
this.items = new Array();
$.extend(this, option);
$(this).attr('autocomplete', 'off');
// Focus
$(this).on('focus', function() {
this.request();
});
// Blur
$(this).on('blur', function() {
setTimeout(function(object) {
object.hide();
}, 200, this);
});
// Keydown
$(this).on('keydown', function(event) {
switch (event.keyCode) {
case 27: // escape
this.hide();
break;
default:
this.request();
break;
}
});
// Click
this.click = function(event) {
event.preventDefault();
value = $(event.target).parent().attr('data-value');
if (value && this.items[value]) {
this.select(this.items[value]);
}
}
// Show
this.show = function() {
var pos = $(this).position();
$(this).siblings('ul.dropdown-menu').css({
top: pos.top + $(this).outerHeight(),
left: pos.left
});
$(this).siblings('ul.dropdown-menu').show();
}
// Hide
this.hide = function() {
$(this).siblings('ul.dropdown-menu').hide();
}
// Request
this.request = function() {
clearTimeout(this.timer);
this.timer = setTimeout(function(object) {
object.source($(object).val(), $.proxy(object.response, object));
}, 200, this);
}
// Response
this.response = function(json) {
html = '';
if (json.length) {
for (i = 0; i < json.length; i++) {
this.items[json[i]['value']] = json[i];
}
for (i = 0; i < json.length; i++) {
if (!json[i]['category']) {
html += '<li data-value="' + json[i]['value'] + '"><a href="#">' + json[i]['label'] + '</a></li>';
}
}
// Get all the ones with a categories
var category = new Array();
for (i = 0; i < json.length; i++) {
if (json[i]['category']) {
if (!category[json[i]['category']]) {
category[json[i]['category']] = new Array();
category[json[i]['category']]['name'] = json[i]['category'];
category[json[i]['category']]['item'] = new Array();
}
category[json[i]['category']]['item'].push(json[i]);
}
}
for (i in category) {
html += '<li class="dropdown-header">' + category[i]['name'] + '</li>';
for (j = 0; j < category[i]['item'].length; j++) {
html += '<li data-value="' + category[i]['item'][j]['value'] + '"><a href="#"> ' + category[i]['item'][j]['label'] + '</a></li>';
}
}
}
if (html) {
this.show();
} else {
this.hide();
}
$(this).siblings('ul.dropdown-menu').html(html);
}
$(this).after('<ul class="dropdown-menu"></ul>');
$(this).siblings('ul.dropdown-menu').delegate('a', 'click', $.proxy(this.click, this));
});
}
})(window.jQuery);
/* Image Mnanger */
(function($) {
$(document).delegate('a[data-toggle=\'image\']', 'click', function(e) {
e.preventDefault();
$('.popover').popover('hide', function() {
$('.popover').remove();
});
var element = this;
$(element).popover({
html: true,
placement: 'right',
trigger: 'manual',
content: function() {
return '<button type="button" id="button-image" class="btn btn-primary"><i class="fa fa-pencil"></i></button> <button type="button" id="button-clear" class="btn btn-danger"><i class="fa fa-trash-o"></i></button>';
}
});
$(element).popover('show');
$('#button-image').on('click', function() {
$('#modal-image').remove();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/admin/image?target=' + $(element).parent().find('input').attr('id') + '&thumb=' + $(element).attr('id'),
dataType: 'html',
beforeSend: function() {
$('#button-image i').replaceWith('<i class="fa fa-circle-o-notch fa-spin"></i>');
$('#button-image').prop('disabled', true);
},
complete: function() {
$('#button-image i').replaceWith('<i class="fa fa-pencil"></i>');
$('#button-image').prop('disabled', false);
},
success: function(html) {
$('#modal-filemanager').remove();
$('body').append('<div id="modal-image" class="modal">' + html + '</div>');
$('#modal-image').modal('show');
}
});
$(element).popover('hide', function() {
$('.popover').remove();
});
});
$('#button-clear').on('click', function() {
$(element).find('img').attr('src', $(element).find('img').attr('data-placeholder'));
$(element).parent().find('input').attr('value', '');
$(element).popover('hide', function() {
$('.popover').remove();
});
});
});
})(window.jQuery); | {
"content_hash": "392f856c93d54b93bbaf29643dc9add2",
"timestamp": "",
"source": "github",
"line_count": 242,
"max_line_length": 229,
"avg_line_length": 41.99173553719008,
"alnum_prop": 0.4370202716000787,
"repo_name": "kaiwh/laravel-admin",
"id": "439d95ed674849764d1d6938a0d0f1d31f29da49",
"size": "10162",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Commands/stubs/install/public/vendor/admin/js/common.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "52132"
}
],
"symlink_target": ""
} |
title: "Apache Beam 2.28.0"
date: 2021-02-22 12:00:00 -0800
categories:
- blog
authors:
- chamikara
---
<!--
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.
-->
We are happy to present the new 2.28.0 release of Apache Beam. This release includes both improvements and new functionality.
See the [download page](/get-started/downloads/#2280-2021-02-13) for this release.
For more information on changes in 2.28.0, check out the
[detailed release notes](https://issues.apache.org/jira/secure/ReleaseNote.jspa?projectId=12319527&version=12349499).
## Highlights
* Many improvements related to Parquet support ([BEAM-11460](https://issues.apache.org/jira/browse/BEAM-11460), [BEAM-8202](https://issues.apache.org/jira/browse/BEAM-8202), and [BEAM-11526](https://issues.apache.org/jira/browse/BEAM-11526))
* Hash Functions in BeamSQL ([BEAM-10074](https://issues.apache.org/jira/browse/BEAM-10074))
* Hash functions in ZetaSQL ([BEAM-11624](https://issues.apache.org/jira/browse/BEAM-11624))
* Create ApproximateDistinct using HLL Impl ([BEAM-10324](https://issues.apache.org/jira/browse/BEAM-10324))
## I/Os
* SpannerIO supports using BigDecimal for Numeric fields ([BEAM-11643](https://issues.apache.org/jira/browse/BEAM-11643))
* Add Beam schema support to ParquetIO ([BEAM-11526](https://issues.apache.org/jira/browse/BEAM-11526))
* Support ParquetTable Writer ([BEAM-8202](https://issues.apache.org/jira/browse/BEAM-8202))
* GCP BigQuery sink (streaming inserts) uses runner determined sharding ([BEAM-11408](https://issues.apache.org/jira/browse/BEAM-11408))
* PubSub support types: TIMESTAMP, DATE, TIME, DATETIME ([BEAM-11533](https://issues.apache.org/jira/browse/BEAM-11533))
## New Features / Improvements
* ParquetIO add methods _readGenericRecords_ and _readFilesGenericRecords_ can read files with an unknown schema. See [PR-13554](https://github.com/apache/beam/pull/13554) and ([BEAM-11460](https://issues.apache.org/jira/browse/BEAM-11460))
* Added support for thrift in KafkaTableProvider ([BEAM-11482](https://issues.apache.org/jira/browse/BEAM-11482))
* Added support for HadoopFormatIO to skip key/value clone ([BEAM-11457](https://issues.apache.org/jira/browse/BEAM-11457))
* Support Conversion to GenericRecords in Convert.to transform ([BEAM-11571](https://issues.apache.org/jira/browse/BEAM-11571)).
* Support writes for Parquet Tables in Beam SQL ([BEAM-8202](https://issues.apache.org/jira/browse/BEAM-8202)).
* Support reading Parquet files with unknown schema ([BEAM-11460](https://issues.apache.org/jira/browse/BEAM-11460))
* Support user configurable Hadoop Configuration flags for ParquetIO ([BEAM-11527](https://issues.apache.org/jira/browse/BEAM-11527))
* Expose commit_offset_in_finalize and timestamp_policy to ReadFromKafka ([BEAM-11677](https://issues.apache.org/jira/browse/BEAM-11677))
* S3 options does not provided to boto3 client while using FlinkRunner and Beam worker pool container ([BEAM-11799](https://issues.apache.org/jira/browse/BEAM-11799))
* HDFS not deduplicating identical configuration paths ([BEAM-11329](https://issues.apache.org/jira/browse/BEAM-11329))
* Hash Functions in BeamSQL ([BEAM-10074](https://issues.apache.org/jira/browse/BEAM-10074))
* Create ApproximateDistinct using HLL Impl ([BEAM-10324](https://issues.apache.org/jira/browse/BEAM-10324))
* Add Beam schema support to ParquetIO ([BEAM-11526](https://issues.apache.org/jira/browse/BEAM-11526))
* Add a Deque Encoder ([BEAM-11538](https://issues.apache.org/jira/browse/BEAM-11538))
* Hash functions in ZetaSQL ([BEAM-11624](https://issues.apache.org/jira/browse/BEAM-11624))
* Refactor ParquetTableProvider ([](https://issues.apache.org/jira/browse/))
* Add JVM properties to JavaJobServer ([BEAM-8344](https://issues.apache.org/jira/browse/BEAM-8344))
* Single source of truth for supported Flink versions ([](https://issues.apache.org/jira/browse/))
* Use metric for Python BigQuery streaming insert API latency logging ([BEAM-11018](https://issues.apache.org/jira/browse/BEAM-11018))
* Use metric for Java BigQuery streaming insert API latency logging ([BEAM-11032](https://issues.apache.org/jira/browse/BEAM-11032))
* Upgrade Flink runner to Flink versions 1.12.1 and 1.11.3 ([BEAM-11697](https://issues.apache.org/jira/browse/BEAM-11697))
* Upgrade Beam base image to use Tensorflow 2.4.1 ([BEAM-11762](https://issues.apache.org/jira/browse/BEAM-11762))
* Create Beam GCP BOM ([BEAM-11665](https://issues.apache.org/jira/browse/BEAM-11665))
## Breaking Changes
* The Java artifacts "beam-sdks-java-io-kinesis", "beam-sdks-java-io-google-cloud-platform", and
"beam-sdks-java-extensions-sql-zetasql" declare Guava 30.1-jre dependency (It was 25.1-jre in Beam 2.27.0).
This new Guava version may introduce dependency conflicts if your project or dependencies rely
on removed APIs. If affected, ensure to use an appropriate Guava version via `dependencyManagement` in Maven and
`force` in Gradle.
## List of Contributors
According to git shortlog, the following people contributed to the 2.28.0 release. Thank you to all contributors!
Ahmet Altay, Alex Amato, Alexey Romanenko, Allen Pradeep Xavier, Anant Damle, Artur Khanin,
Boyuan Zhang, Brian Hulette, Chamikara Jayalath, Chris Roth, Costi Ciudatu, Damon Douglas,
Daniel Collins, Daniel Oliveira, David Cavazos, David Huntsperger, Elliotte Rusty Harold,
Emily Ye, Etienne Chauchot, Etta Rapp, Evan Palmer, Eyal, Filip Krakowski, Fokko Driesprong,
Heejong Lee, Ismaël Mejía, janeliulwq, Jan Lukavský, John Edmonds, Jozef Vilcek, Kenneth Knowles
Ke Wu, kileys, Kyle Weaver, MabelYC, masahitojp, Masato Nakamura, Milena Bukal, Miraç Vuslat Başaran,
Nelson Osacky, Niel Markwick, Ning Kang, omarismail94, Pablo Estrada, Piotr Szuberski,
ramazan-yapparov, Reuven Lax, Reza Rokni, rHermes, Robert Bradshaw, Robert Burke, Robert Gruener,
Romster, Rui Wang, Sam Whittle, shehzaadn-vd, Siyuan Chen, Sonam Ramchand, Tobiasz Kędzierski,
Tomo Suzuki, tszerszen, tvalentyn, Tyson Hamilton, Udi Meiri, Xinbin Huang, Yichi Zhang,
Yifan Mai, yoshiki.obata, Yueyang Qiu, Yusaku Matsuki
| {
"content_hash": "e38c9c1959f11537e8261c4a0b298357",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 241,
"avg_line_length": 77.80952380952381,
"alnum_prop": 0.7734088127294981,
"repo_name": "axbaretto/beam",
"id": "531ff514f6194afb7b10dcd7221ff2f0e7408b55",
"size": "6546",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "website/www/site/content/en/blog/beam-2.28.0.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1598"
},
{
"name": "Batchfile",
"bytes": "3220"
},
{
"name": "C",
"bytes": "1339873"
},
{
"name": "C++",
"bytes": "1132901"
},
{
"name": "CSS",
"bytes": "124283"
},
{
"name": "Dockerfile",
"bytes": "23950"
},
{
"name": "FreeMarker",
"bytes": "7428"
},
{
"name": "Go",
"bytes": "2795906"
},
{
"name": "Groovy",
"bytes": "187109"
},
{
"name": "HTML",
"bytes": "238575"
},
{
"name": "Java",
"bytes": "39085315"
},
{
"name": "JavaScript",
"bytes": "1221326"
},
{
"name": "Jupyter Notebook",
"bytes": "7396"
},
{
"name": "Makefile",
"bytes": "354938"
},
{
"name": "Python",
"bytes": "51449019"
},
{
"name": "Roff",
"bytes": "70716"
},
{
"name": "Ruby",
"bytes": "4159"
},
{
"name": "Shell",
"bytes": "351541"
},
{
"name": "TeX",
"bytes": "70920"
},
{
"name": "Thrift",
"bytes": "1118"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/locations/specific-locations/scriptural-locations/sinai-desert" xmlns:sem="http://marklogic.com/semantics">
<sem:triple>
<sem:subject>http://www.lds.org/vrl/locations/specific-locations/scriptural-locations/sinai-desert</sem:subject>
<sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
<sem:object datatype="xsd:string" xml:lang="eng">Sinai Desert</sem:object>
</sem:triple>
<sem:triple>
<sem:subject>http://www.lds.org/vrl/locations/specific-locations/scriptural-locations/sinai-desert</sem:subject>
<sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
<sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
</sem:triple>
<sem:triple>
<sem:subject>http://www.lds.org/vrl/locations/specific-locations/scriptural-locations/sinai-desert</sem:subject>
<sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
<sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
</sem:triple>
</sem:triples>
| {
"content_hash": "a0e3e41d2ed083567a15e3a6c3d63933",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 148,
"avg_line_length": 62.166666666666664,
"alnum_prop": 0.7327971403038427,
"repo_name": "freshie/ml-taxonomies",
"id": "02700611c3b6b6e5b2dc5368a7b4cfedb964f5c0",
"size": "1119",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "roxy/data/gospel-topical-explorer-v2/taxonomies/vrl/locations/specific-locations/scriptural-locations/sinai-desert.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4422"
},
{
"name": "CSS",
"bytes": "38665"
},
{
"name": "HTML",
"bytes": "356"
},
{
"name": "JavaScript",
"bytes": "411651"
},
{
"name": "Ruby",
"bytes": "259121"
},
{
"name": "Shell",
"bytes": "7329"
},
{
"name": "XQuery",
"bytes": "857170"
},
{
"name": "XSLT",
"bytes": "13753"
}
],
"symlink_target": ""
} |
/*
check_snmp_qnap_volspace - plugin to check free space on Qnap volume.
Version: 1.0
Author: Nicola Sarobba <[email protected]>
Date: 2015-02-16
*/
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"github.com/nicsar/nagutils"
)
// snmpwalk command.
const snmpwalk = "/usr/bin/snmpwalk"
// Default timeout for SNMP.
const timeoutdfl = 10
// SNMP OID Syste Volume Table.
const SystemVolumeTableOID = "1.3.6.1.4.1.24681.1.2.17"
// SNMP OID Index of System Volume Table.
const SysVolumeIndexOID = ".1.3.6.1.4.1.24681.1.2.17.1.1"
// SystemVolumeEntry summarize an entry of the System volume table.
type SystemVolumeEntry struct {
SysVolumeDescr string
SysVolumeTotalSize string
SysVolumeFreeSize string
SysVolumeStatus string // abnormal, invalid, unmounted, synchronyzing
}
// ConvUnit converts unit of TotalSize and FreeSize in MB.
func (s *SystemVolumeEntry) ConvUnit() {
if s.SysVolumeStatus == "Ready" {
result, _ := convertUnit(s.SysVolumeTotalSize, "MB")
s.SysVolumeTotalSize = result
result, _ = convertUnit(s.SysVolumeFreeSize, "MB")
s.SysVolumeFreeSize = result
}
}
// UoM returns the unit of measure used by the system volume entry.
func (s *SystemVolumeEntry) UoM() string {
splittedT := strings.Split(s.SysVolumeTotalSize, " ")
return splittedT[1]
}
// convertUnit converts 'vaule' to 'dunit'. 'value' is something like "8.44 TB".
func convertUnit(value string, dunit string) (string, error) {
splitted := strings.Split(value, " ")
svalue := splitted[0]
sunit := splitted[1]
var v float64
var err error
if v, err = strconv.ParseFloat(svalue, 64); err != nil {
return "", fmt.Errorf("convertUnit: %s", err)
}
if sunit == dunit {
return fmt.Sprintf("%f %s", v, sunit), nil
} else if sunit == "MB" && dunit == "GB" { // MB to GB
return fmt.Sprintf("%f GB", v/1000), nil
} else if sunit == "MB" && dunit == "TB" { // MB to TB
return fmt.Sprintf("%f TB", v/1000000), nil
} else if sunit == "GB" && dunit == "TB" { // GB to TB
return fmt.Sprintf("%f TB", v/1000), nil
} else if sunit == "GB" && dunit == "MB" { // GB to MB
return fmt.Sprintf("%f MB", v*1000), nil
} else if sunit == "TB" && dunit == "GB" { // TB to GB
return fmt.Sprintf("%f GB", v*1000), nil
} else if sunit == "TB" && dunit == "MB" { // TB to MB
return fmt.Sprintf("%f MB", v*1000000), nil
}
return "", fmt.Errorf("Unknown unit: %s", sunit)
}
// usage prints the command usage and flag defaults.
var usage = func() {
var basename string = nagutils.Basename(os.Args[0])
fmt.Fprintf(os.Stderr, "Usage: %s -H <host> [-C <snmp_community>] [-p <port>] [-t <timeout>]\n", basename)
flag.PrintDefaults()
}
func main() {
optHost := flag.String("H", "", "name or IP address of host to check")
optCommty := flag.String("C", "public", "community name for the host's SNMP agent")
optPort := flag.String("p", "161", "SNMP port")
optW := flag.Int("w", 80, "percent of space volume used to generate WARNING state")
optC := flag.Int("c", 90, "percent of space volume used to generate CRITICAL state")
optPerf := flag.Bool("f", false, "perfparse compatible output")
optTimeout := flag.Int("t", timeoutdfl, "timeout for SNMP in seconds")
flag.Parse()
if flag.NFlag() < 3 {
usage()
os.Exit(nagutils.Errors["UNKNOWN"])
}
if *optHost == "" {
usage()
os.Exit(nagutils.Errors["UNKNOWN"])
}
if *optTimeout <= 0 {
*optTimeout = timeoutdfl
}
argTimeout := "-t" + strconv.Itoa(*optTimeout)
var argHost string
if *optPort != "161" {
argHost = *optHost + ":" + *optPort
} else {
argHost = *optHost
}
cmd := exec.Command(snmpwalk, "-v2c", "-c", *optCommty, "-r0", "-On", argTimeout, argHost, SystemVolumeTableOID)
snmpOut, err := cmd.CombinedOutput()
if err != nil {
fmt.Printf("%s", snmpOut)
nagutils.NagiosExit(nagutils.Errors["UNKNOWN"], err.Error())
}
lines := strings.Split(fmt.Sprintf("%s", snmpOut), "\n")
// Get the number of system volume entries.
nentries := tableEntries(lines)
var sysvolentries []SystemVolumeEntry
if sysvolentries, err = extractData(lines, nentries); err != nil {
_ = sysvolentries
nagutils.NagiosExit(nagutils.Errors["UNKNOWN"], err.Error())
}
var totsz, freesz float64
var exitVal nagutils.ExitVal
exitVal.Status = nagutils.Errors["OK"]
outMsg := ""
outPerf := ""
for i := 0; i < nentries; i++ {
// If volume status is different from "Ready", it could be impossible to get size information.
if sysvolentries[i].SysVolumeStatus != "Ready" {
exitVal.Status = nagutils.Errors["CRITICAL"]
outMsg = sysvolentries[i].SysVolumeDescr + " status " + sysvolentries[i].SysVolumeStatus
exitVal.Problems = append(exitVal.Problems, outMsg)
} else {
// Let's assure that SysVolumeTotalSize and SysVolumeFreeSize are of same unit.
sysvolentries[i].ConvUnit()
if totsz, err = size2Float(sysvolentries[i].SysVolumeTotalSize); err != nil {
// Exit!
nagutils.NagiosExit(nagutils.Errors["UNKNOWN"], err.Error())
}
if freesz, err = size2Float(sysvolentries[i].SysVolumeFreeSize); err != nil {
// Exit!
nagutils.NagiosExit(nagutils.Errors["UNKNOWN"], err.Error())
}
used := int(nagutils.Round(usedPercent(totsz, freesz)))
if used > *optW && used < *optC { // WARNING
if exitVal.Status != nagutils.Errors["CRITICAL"] {
exitVal.Status = nagutils.Errors["WARNING"]
}
outMsg = sysvolentries[i].SysVolumeDescr + " above warning threshold"
outPerf = fmt.Sprintf("'%s'=%.2f%s;%v;%v;0;%.2f",
sysvolentries[i].SysVolumeDescr,
nagutils.RoundPlus(totsz-freesz, 2),
sysvolentries[i].UoM(),
int(nagutils.Round(percent(totsz, *optW))),
int(nagutils.Round(percent(totsz, *optC))),
totsz,
)
exitVal.Problems = append(exitVal.Problems, outMsg)
exitVal.PerfData = append(exitVal.PerfData, outPerf)
} else if used > *optC { // CRITICAL
exitVal.Status = nagutils.Errors["CRITICAL"]
if i != 0 {
outPerf += " "
}
outMsg = sysvolentries[i].SysVolumeDescr + " above critical threshold"
outPerf = fmt.Sprintf("'%s'=%.2f%s;%v;%v;0;%.2f",
sysvolentries[i].SysVolumeDescr,
nagutils.RoundPlus(totsz-freesz, 2),
sysvolentries[i].UoM(),
int(nagutils.Round(percent(totsz, *optW))),
int(nagutils.Round(percent(totsz, *optC))),
totsz,
)
exitVal.Problems = append(exitVal.Problems, outMsg)
exitVal.PerfData = append(exitVal.PerfData, outPerf)
} else { // System Volume entry OK.
outPerf = fmt.Sprintf("'%s'=%.2f%s;%v;%v;0;%.2f",
sysvolentries[i].SysVolumeDescr,
nagutils.RoundPlus(totsz-freesz, 2),
sysvolentries[i].UoM(),
int(nagutils.Round(percent(totsz, *optW))),
int(nagutils.Round(percent(totsz, *optC))),
totsz,
)
exitVal.PerfData = append(exitVal.PerfData, outPerf)
}
}
} // End for.
// OK status.
if exitVal.Status == nagutils.Errors["OK"] {
msg := "volumes free space Ok - volumes status Ok"
if *optPerf == true {
msg += exitVal.PerfData2Str()
}
nagutils.NagiosExit(exitVal.Status, msg)
}
// WARNING or CRITICAL status.
if exitVal.Status == nagutils.Errors["WARNING"] || exitVal.Status == nagutils.Errors["CRITICAL"] {
msg := exitVal.Problems2Str()
if *optPerf == true {
msg += exitVal.PerfData2Str()
}
nagutils.NagiosExit(exitVal.Status, msg)
}
// We should never get here.
nagutils.NagiosExit(nagutils.Errors["UNKNOWN"], "maybe a plugin bug")
}
// ** Functions **
// tableEntries returns the number of entries in SystemVolumeTable table.
func tableEntries(lines []string) int {
entries := 0
for _, line := range lines {
// .1.3.6.1.4.1.24681.1.2.17.1.1.1 = INTEGER: 1
splitted := strings.Split(line, "=")
if strings.Contains(splitted[0], SysVolumeIndexOID) {
entries++
} else {
break
}
}
return entries
}
// extractData returns a slice of all the system volume entries found.
// 'lines' are the result of snmpwalk.
// 'nentries' are the number of entries in Sysvolume table.
func extractData(lines []string, nentries int) ([]SystemVolumeEntry, error) {
var sysvolentries []SystemVolumeEntry
descr := lines[nentries : nentries*2]
totalsz := lines[nentries*3 : (nentries*3)+nentries]
freesz := lines[nentries*4 : (nentries*4)+nentries]
status := lines[nentries*5 : (nentries*5)+nentries]
var out1, out2, out3, out4 string
var err error
for i := 0; i < nentries; i++ {
if out1, err = extractDataValue(descr[i]); err != nil {
return nil, err
}
if out2, err = extractDataValue(totalsz[i]); err != nil {
return nil, err
}
if out3, err = extractDataValue(freesz[i]); err != nil {
return nil, err
}
if out4, err = extractDataValue(status[i]); err != nil {
return nil, err
}
sysvolentry := SystemVolumeEntry{out1, out2, out3, out4}
sysvolentries = append(sysvolentries, sysvolentry)
}
return sysvolentries, nil
}
// extractDataValue returns a string containing the string value of the snmp oid line
// stripped of '"'.
func extractDataValue(snmpln string) (string, error) {
splitted := strings.Split(snmpln, "= STRING: ")
if len(splitted) != 2 {
return "", fmt.Errorf("SNMP line: bad format of: %s", snmpln)
}
s := strings.Trim(splitted[1], "\"")
return s, nil
}
// size2float convert the string "10.77 TB" in float64 10.77.
func size2Float(size string) (float64, error) {
splitted := strings.Split(size, " ")
f, err := strconv.ParseFloat(splitted[0], 64)
if err != nil {
return -1, fmt.Errorf("Bad size value: %s", size)
}
return f, nil
}
// usedPercent returns a float representing the percentage of used space.
func usedPercent(tot float64, free float64) float64 {
used := tot - free
percent := (used * 100) / tot
return nagutils.RoundPlus(percent, 2)
}
// percent returns percentual value of 'n'.
func percent(n float64, prc int) float64 {
return (n / 100.0) * float64(prc)
}
| {
"content_hash": "7530f95eda52656ebad51b43037a91c5",
"timestamp": "",
"source": "github",
"line_count": 308,
"max_line_length": 113,
"avg_line_length": 31.90909090909091,
"alnum_prop": 0.6672771672771672,
"repo_name": "nicsar/check_snmp_qnap_volspace",
"id": "fc6cdbee1d84482f35212a156a56ffdd111ba57e",
"size": "9828",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "check_snmp_qnap_volspace.go",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Go",
"bytes": "17922"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
Oesterr. Bot. Z. 29:118. 1879
#### Original name
null
### Remarks
null | {
"content_hash": "d496af9cb23facb759490397749b223c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 11.615384615384615,
"alnum_prop": 0.695364238410596,
"repo_name": "mdoering/backbone",
"id": "1c336ab2a9836310e4e42c6468853b805b41e121",
"size": "205",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Onagraceae/Epilobium/Epilobium valdiviense/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package de.tudarmstadt.ukp.clarin.webanno.webapp.security.page;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.springframework.security.core.context.SecurityContextHolder;
import de.tudarmstadt.ukp.clarin.webanno.webapp.page.login.LoginPage;
/**
* Panel used to log in or log out.
*
* @author Richard Eckart de Castilho
*/
public class LogInOutPanel
extends Panel
{
private static final long serialVersionUID = 4194429035097444753L;
public LogInOutPanel(String id)
{
super(id);
initialize();
}
public LogInOutPanel(String id, IModel<?> model)
{
super(id, model);
initialize();
}
@SuppressWarnings("serial")
private void initialize()
{
// TODO well, is there another way to not anonymously semi-login?
if (isSignedInAnonymously()) {
AuthenticatedWebSession.get().signOut();
}
add(new Label("usernameLink")
{
@Override
protected void onConfigure()
{
super.onConfigure();
if (AuthenticatedWebSession.get().isSignedIn()) {
setDefaultModel(new Model<String>(SecurityContextHolder.getContext()
.getAuthentication().getName()));
}
setVisible(AuthenticatedWebSession.get().isSignedIn());
}
});
add(new Link<Void>("login")
{
@Override
protected void onConfigure()
{
super.onConfigure();
setVisible(!AuthenticatedWebSession.get().isSignedIn());
}
@Override
public void onClick()
{
setResponsePage(LoginPage.class);
}
});
add(new Link<Void>("logout")
{
@Override
protected void onConfigure()
{
super.onConfigure();
setVisible(AuthenticatedWebSession.get().isSignedIn());
}
@Override
public void onClick()
{
AuthenticatedWebSession.get().signOut();
setResponsePage(getApplication().getHomePage());
}
});
}
private boolean isSignedInAnonymously()
{
AuthenticatedWebSession session = AuthenticatedWebSession.get();
return session.isSignedIn() && session.getRoles().hasRole("ROLE_ANONYMOUS");
}
}
| {
"content_hash": "ac937e14f5fcde6daa0662db0a57f803",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 78,
"avg_line_length": 22.79591836734694,
"alnum_prop": 0.7139659803043867,
"repo_name": "guard0g/webanno",
"id": "e4bd17d44a30650c74dc2dc79ed0ea68fa6f0a7e",
"size": "3081",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "webanno-webapp-home/security/page/LogInOutPanel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "63311"
},
{
"name": "HTML",
"bytes": "107674"
},
{
"name": "Java",
"bytes": "2160179"
},
{
"name": "JavaScript",
"bytes": "424576"
}
],
"symlink_target": ""
} |
"""
Installation script for Quantum's development virtualenv
"""
import os
import subprocess
import sys
ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
VENV = os.path.join(ROOT, '.venv')
PIP_REQUIRES = os.path.join(ROOT, 'tools', 'pip-requires')
PY_VERSION = "python%s.%s" % (sys.version_info[0], sys.version_info[1])
VENV_EXISTS = bool(os.path.exists(VENV))
def die(message, *args):
print >> sys.stderr, message % args
sys.exit(1)
def run_command(cmd, redirect_output=True, check_exit_code=True):
"""
Runs a command in an out-of-process shell, returning the
output of that command. Working directory is ROOT.
"""
if redirect_output:
stdout = subprocess.PIPE
else:
stdout = None
proc = subprocess.Popen(cmd, cwd=ROOT, stdout=stdout)
output = proc.communicate()[0]
if check_exit_code and proc.returncode != 0:
raise Exception('Command "%s" failed.\n%s' % (' '.join(cmd), output))
return output
HAS_EASY_INSTALL = bool(run_command(['which', 'easy_install'],
check_exit_code=False).strip())
HAS_VIRTUALENV = bool(run_command(['which', 'virtualenv'],
check_exit_code=False).strip())
def check_dependencies():
"""Make sure virtualenv is in the path."""
if not HAS_VIRTUALENV:
raise Exception('Virtualenv not found. ' + \
'Try installing python-virtualenv')
print 'done.'
def create_virtualenv(venv=VENV, install_pip=False):
"""Creates the virtual environment and installs PIP only into the
virtual environment
"""
print 'Creating venv...',
install = ['virtualenv', '-q', venv]
run_command(install)
print 'done.'
print 'Installing pip in virtualenv...',
if install_pip and \
not run_command(['tools/with_venv.sh', 'easy_install',
'pip>1.0']):
die("Failed to install pip.")
print 'done.'
def install_dependencies(venv=VENV):
print 'Installing dependencies with pip (this can take a while)...'
run_command(['tools/with_venv.sh', 'pip', 'install', '-E', venv, '-r',
PIP_REQUIRES], redirect_output=False)
# Tell the virtual env how to "import quantum"
pthfile = os.path.join(venv, "lib", PY_VERSION, "site-packages",
"quantum.pth")
f = open(pthfile, 'w')
f.write("%s\n" % ROOT)
def print_help():
help = """
Quantum development environment setup is complete.
Quantum development uses virtualenv to track and manage Python dependencies
while in development and testing.
To activate the Quantum virtualenv for the extent of your current shell
session you can run:
$ source .venv/bin/activate
Or, if you prefer, you can run commands in the virtualenv on a case by case
basis by running:
$ tools/with_venv.sh <your command>
Also, make test will automatically use the virtualenv.
"""
print help
def main(argv):
check_dependencies()
create_virtualenv()
install_dependencies()
print_help()
if __name__ == '__main__':
main(sys.argv)
| {
"content_hash": "4880c9d9c4a538fae2d1640c4790de48",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 77,
"avg_line_length": 28.205357142857142,
"alnum_prop": 0.6293130737575182,
"repo_name": "rcbops/quantum-buildpackage",
"id": "040adbfe8b99c2de2854a6f922ef7369a8534413",
"size": "3992",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tools/install_venv.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "60525"
},
{
"name": "Python",
"bytes": "872355"
},
{
"name": "Shell",
"bytes": "7516"
}
],
"symlink_target": ""
} |
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class HostVmfsVolume extends HostFileSystemVolume {
public int blockSizeMb;
public int maxBlocks;
public int majorVersion;
public String version;
public String uuid;
public HostScsiDiskPartition[] extent;
public boolean vmfsUpgradable;
public HostForceMountedInfo forceMountedInfo;
public Boolean ssd;
public Boolean local;
public int getBlockSizeMb() {
return this.blockSizeMb;
}
public int getMaxBlocks() {
return this.maxBlocks;
}
public int getMajorVersion() {
return this.majorVersion;
}
public String getVersion() {
return this.version;
}
public String getUuid() {
return this.uuid;
}
public HostScsiDiskPartition[] getExtent() {
return this.extent;
}
public boolean isVmfsUpgradable() {
return this.vmfsUpgradable;
}
public HostForceMountedInfo getForceMountedInfo() {
return this.forceMountedInfo;
}
public Boolean getSsd() {
return this.ssd;
}
public Boolean getLocal() {
return this.local;
}
public void setBlockSizeMb(int blockSizeMb) {
this.blockSizeMb = blockSizeMb;
}
public void setMaxBlocks(int maxBlocks) {
this.maxBlocks = maxBlocks;
}
public void setMajorVersion(int majorVersion) {
this.majorVersion = majorVersion;
}
public void setVersion(String version) {
this.version = version;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public void setExtent(HostScsiDiskPartition[] extent) {
this.extent = extent;
}
public void setVmfsUpgradable(boolean vmfsUpgradable) {
this.vmfsUpgradable = vmfsUpgradable;
}
public void setForceMountedInfo(HostForceMountedInfo forceMountedInfo) {
this.forceMountedInfo = forceMountedInfo;
}
public void setSsd(Boolean ssd) {
this.ssd = ssd;
}
public void setLocal(Boolean local) {
this.local = local;
}
} | {
"content_hash": "8f8b8972a824060904fb0e7f5f38d3e6",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 76,
"avg_line_length": 21.392156862745097,
"alnum_prop": 0.6475710357470211,
"repo_name": "n4ybn/yavijava",
"id": "a280a8c742ad203e4043e7cfd4549a7684b2f9f8",
"size": "3822",
"binary": false,
"copies": "5",
"ref": "refs/heads/gradle",
"path": "src/main/java/com/vmware/vim25/HostVmfsVolume.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Groovy",
"bytes": "14019"
},
{
"name": "Java",
"bytes": "8544369"
}
],
"symlink_target": ""
} |
(function() {
var JSONStorage, LocalStorage, QUOTA_EXCEEDED_ERR, StorageEvent, events, fs, path, _emptyDirectory, _rm,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__hasProp = {}.hasOwnProperty;
path = require('path');
fs = require('fs');
events = require('events');
_emptyDirectory = function(target) {
var p, _i, _len, _ref, _results;
_ref = fs.readdirSync(target);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
p = _ref[_i];
_results.push(_rm(path.join(target, p)));
}
return _results;
};
_rm = function(target) {
if (fs.statSync(target).isDirectory()) {
_emptyDirectory(target);
return fs.rmdirSync(target);
} else {
return fs.unlinkSync(target);
}
};
QUOTA_EXCEEDED_ERR = (function(_super) {
__extends(QUOTA_EXCEEDED_ERR, _super);
function QUOTA_EXCEEDED_ERR(_at_message) {
this.message = _at_message != null ? _at_message : 'Unknown error.';
if (Error.captureStackTrace != null) {
Error.captureStackTrace(this, this.constructor);
}
this.name = this.constructor.name;
}
QUOTA_EXCEEDED_ERR.prototype.toString = function() {
return this.name + ": " + this.message;
};
return QUOTA_EXCEEDED_ERR;
})(Error);
StorageEvent = (function() {
function StorageEvent(_at_key, _at_oldValue, _at_newValue, _at_url, _at_storageArea) {
this.key = _at_key;
this.oldValue = _at_oldValue;
this.newValue = _at_newValue;
this.url = _at_url;
this.storageArea = _at_storageArea != null ? _at_storageArea : 'localStorage';
}
return StorageEvent;
})();
LocalStorage = (function(_super) {
var MetaKey, createMap;
__extends(LocalStorage, _super);
function LocalStorage(_at_location, _at_quota) {
this.location = _at_location;
this.quota = _at_quota != null ? _at_quota : 5 * 1024 * 1024;
if (!(this instanceof LocalStorage)) {
return new LocalStorage(this.location, this.quota);
}
this.length = 0;
this.bytesInUse = 0;
this.keys = [];
this.metaKeyMap = createMap();
this.eventUrl = "pid:" + process.pid;
this._init();
this.QUOTA_EXCEEDED_ERR = QUOTA_EXCEEDED_ERR;
}
MetaKey = (function() {
function MetaKey(_at_key, _at_index) {
this.key = _at_key;
this.index = _at_index;
if (!(this instanceof MetaKey)) {
return new MetaKey(this.key, this.index);
}
}
return MetaKey;
})();
createMap = function() {
var Map;
Map = function() {};
Map.prototype = Object.create(null);
return new Map();
};
LocalStorage.prototype._init = function() {
var index, k, stat, _MetaKey, _decodedKey, _i, _keys, _len;
if (fs.existsSync(this.location)) {
if (!fs.statSync(this.location).isDirectory()) {
throw new Error("A file exists at the location '" + this.location + "' when trying to create/open localStorage");
}
}
this.bytesInUse = 0;
this.length = 0;
if (!fs.existsSync(this.location)) {
fs.mkdirSync(this.location);
return;
}
_keys = fs.readdirSync(this.location);
for (index = _i = 0, _len = _keys.length; _i < _len; index = ++_i) {
k = _keys[index];
_decodedKey = decodeURIComponent(k);
this.keys.push(_decodedKey);
_MetaKey = new MetaKey(k, index);
this.metaKeyMap[_decodedKey] = _MetaKey;
stat = this.getStat(k);
if ((stat != null ? stat.size : void 0) != null) {
_MetaKey.size = stat.size;
this.bytesInUse += stat.size;
}
}
return this.length = _keys.length;
};
LocalStorage.prototype.setItem = function(key, value) {
var encodedKey, evnt, existsBeforeSet, filename, hasListeners, metaKey, oldLength, oldValue, valueString, valueStringLength;
hasListeners = events.EventEmitter.listenerCount(this, 'storage');
oldValue = null;
if (hasListeners) {
oldValue = this.getItem(key);
}
key = key.toString();
encodedKey = encodeURIComponent(key);
filename = path.join(this.location, encodedKey);
valueString = value.toString();
valueStringLength = valueString.length;
metaKey = this.metaKeyMap[key];
existsBeforeSet = !!metaKey;
if (existsBeforeSet) {
oldLength = metaKey.size;
} else {
oldLength = 0;
}
if (this.bytesInUse - oldLength + valueStringLength > this.quota) {
throw new QUOTA_EXCEEDED_ERR();
}
fs.writeFileSync(filename, valueString, 'utf8');
if (!existsBeforeSet) {
metaKey = new MetaKey(encodedKey, (this.keys.push(key)) - 1);
metaKey.size = valueStringLength;
this.metaKeyMap[key] = metaKey;
this.length += 1;
this.bytesInUse += valueStringLength;
}
if (hasListeners) {
evnt = new StorageEvent(key, oldValue, value, this.eventUrl);
return this.emit('storage', evnt);
}
};
LocalStorage.prototype.getItem = function(key) {
var filename, metaKey;
key = key.toString();
metaKey = this.metaKeyMap[key];
if (!!metaKey) {
filename = path.join(this.location, metaKey.key);
return fs.readFileSync(filename, 'utf8');
} else {
return null;
}
};
LocalStorage.prototype.getStat = function(key) {
var filename;
key = key.toString();
filename = path.join(this.location, encodeURIComponent(key));
if (fs.existsSync(filename)) {
return fs.statSync(filename);
} else {
return null;
}
};
LocalStorage.prototype.removeItem = function(key) {
var evnt, filename, hasListeners, k, meta, metaKey, oldValue, v, _ref;
key = key.toString();
metaKey = this.metaKeyMap[key];
if (!!metaKey) {
hasListeners = events.EventEmitter.listenerCount(this, 'storage');
oldValue = null;
if (hasListeners) {
oldValue = this.getItem(key);
}
delete this.metaKeyMap[key];
this.length -= 1;
this.bytesInUse -= metaKey.size;
filename = path.join(this.location, metaKey.key);
this.keys.splice(metaKey.index, 1);
_ref = this.metaKeyMap;
for (k in _ref) {
v = _ref[k];
meta = this.metaKeyMap[k];
if (meta.index > metaKey.index) {
meta.index -= 1;
}
}
_rm(filename);
if (hasListeners) {
evnt = new StorageEvent(key, oldValue, null, this.eventUrl);
return this.emit('storage', evnt);
}
}
};
LocalStorage.prototype.key = function(n) {
return this.keys[n];
};
LocalStorage.prototype.clear = function() {
var evnt;
_emptyDirectory(this.location);
this.metaKeyMap = createMap();
this.keys = [];
this.length = 0;
this.bytesInUse = 0;
if (events.EventEmitter.listenerCount(this, 'storage')) {
evnt = new StorageEvent(null, null, null, this.eventUrl);
return this.emit('storage', evnt);
}
};
LocalStorage.prototype.getBytesInUse = function() {
return this.bytesInUse;
};
LocalStorage.prototype._deleteLocation = function() {
_rm(this.location);
this.metaKeyMap = {};
this.keys = [];
this.length = 0;
return this.bytesInUse = 0;
};
return LocalStorage;
})(events.EventEmitter);
JSONStorage = (function(_super) {
__extends(JSONStorage, _super);
function JSONStorage() {
return JSONStorage.__super__.constructor.apply(this, arguments);
}
JSONStorage.prototype.setItem = function(key, value) {
var newValue;
newValue = JSON.stringify(value);
return JSONStorage.__super__.setItem.call(this, key, newValue);
};
JSONStorage.prototype.getItem = function(key) {
return JSON.parse(JSONStorage.__super__.getItem.call(this, key));
};
return JSONStorage;
})(LocalStorage);
exports.LocalStorage = LocalStorage;
exports.JSONStorage = JSONStorage;
exports.QUOTA_EXCEEDED_ERR = QUOTA_EXCEEDED_ERR;
}).call(this);
| {
"content_hash": "65f02d1a0b76573f6cd72837b6e0d5dd",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 292,
"avg_line_length": 30.11660777385159,
"alnum_prop": 0.5895811334037311,
"repo_name": "jphacks/TK_23",
"id": "d7703b3cfbea0e2d84951348077c7683d8900e41",
"size": "8558",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/node_modules/node-localstorage/LocalStorage.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "380"
},
{
"name": "HTML",
"bytes": "14483"
},
{
"name": "JavaScript",
"bytes": "8554"
}
],
"symlink_target": ""
} |
"""A module containing tests for the library implementation of accessing resources."""
import collections
from decimal import Decimal
import os
import re
import pytest
import iati.constants
import iati.resources
import iati.utilities
import iati.validator
import iati.version
import iati.tests.resources
class TestResourceConstants:
"""A container for tests relating to checks of resource constants."""
@pytest.mark.parametrize('folder_path', [
iati.resources.BASE_PATH_STANDARD,
iati.resources.BASE_PATH_LIB_DATA
])
def test_base_folders_valid_values(self, folder_path):
"""Test that constants that should be folder paths 2-levels deep are paths that are 2-levels deep, rooted at the base folder.
The contents of the second component is tested in test_folder_names_valid_values()
"""
path_components = folder_path.split(os.path.sep)
assert len(path_components) == 2
assert path_components[0] == iati.resources.BASE_PATH
@pytest.mark.parametrize('folder_name', [
iati.resources.BASE_PATH,
iati.resources.BASE_PATH_STANDARD.split(os.path.sep).pop(),
iati.resources.BASE_PATH_LIB_DATA.split(os.path.sep).pop(),
iati.resources.PATH_CODELISTS,
iati.resources.PATH_SCHEMAS,
iati.resources.PATH_RULESETS,
iati.resources.PATH_VERSION_INDEPENDENT
])
def test_folder_names_valid_values(self, folder_name):
"""Test that constants that should be folder names are lower case strings separated by underscores."""
folder_name_regex = re.compile(r'^([a-z]+_)*[a-z]+$')
assert re.match(folder_name_regex, folder_name)
@pytest.mark.parametrize('file_name', [
iati.resources.FILE_CODELIST_MAPPING,
iati.resources.FILE_RULESET_SCHEMA_NAME,
iati.resources.FILE_RULESET_STANDARD_NAME,
iati.resources.FILE_SCHEMA_ACTIVITY_NAME,
iati.resources.FILE_SCHEMA_ORGANISATION_NAME
])
def test_file_names_valid_values(self, file_name):
"""Test that constants that should be file names are lower case strings separated by hyphens or underscores."""
file_name_regex = re.compile(r'^([a-z]+[\-_])*[a-z]+$')
assert re.match(file_name_regex, file_name)
@pytest.mark.parametrize('file_extension', [
iati.resources.FILE_CODELIST_EXTENSION,
iati.resources.FILE_DATA_EXTENSION,
iati.resources.FILE_RULESET_EXTENSION,
iati.resources.FILE_SCHEMA_EXTENSION
])
def test_file_extensions_valid_values(self, file_extension):
"""Test that constants that should be file extensions are a dot followed by a lower case string."""
file_extension_regex = re.compile(r'^\.[a-z]+$')
assert re.match(file_extension_regex, file_extension)
class TestResourceFilesystemPaths:
"""A container for tests relating to specific filesystem paths."""
def test_resource_filesystem_path(self, filename_no_meaning):
"""Check that resource file names are found correctly."""
base_path = iati.resources.resource_filesystem_path('')
full_path = iati.resources.resource_filesystem_path(filename_no_meaning)
assert len(full_path) > len(filename_no_meaning)
assert full_path.startswith(base_path)
assert full_path.endswith(filename_no_meaning)
assert os.path.abspath(full_path) == full_path
def test_resource_filesystem_path_folders(self, folderpath_no_meaning):
"""Check that resource folder names are found correctly."""
base_path = iati.resources.resource_filesystem_path('')
full_path = iati.resources.resource_filesystem_path(folderpath_no_meaning)
assert len(full_path) > len(folderpath_no_meaning)
assert full_path.startswith(base_path)
assert full_path.endswith(folderpath_no_meaning)
assert os.path.abspath(full_path) + os.path.sep == full_path
def test_resource_filesystem_path_empty_path(self, filepath_empty):
"""Check that the base resource folder is located when given an empty filepath."""
full_path = iati.resources.resource_filesystem_path(filepath_empty)
assert full_path != ''
assert os.path.isdir(full_path)
class TestResourceLibData:
"""A container for tests relating to handling paths for pyIATI library-specific data."""
def test_create_lib_data_path(self, filename_no_meaning):
"""Check that library data can be located."""
full_path = iati.resources.create_lib_data_path(filename_no_meaning)
assert iati.resources.BASE_PATH_LIB_DATA in full_path
assert full_path.endswith(filename_no_meaning)
class TestResourceHandlingInvalidPaths:
"""A container for tests relating to handling paths that are invalid and being passed to functions that are version-independent."""
@pytest.fixture(params=[
iati.resources.create_lib_data_path,
iati.resources.resource_filesystem_path
])
def resource_func(self, request):
"""A resource function that takes in file paths as an input."""
return request.param
def test_create_lib_data_path_empty_path(self, filepath_empty):
"""Check that a ValueError is raised when given an empty filepath."""
with pytest.raises(ValueError):
iati.resources.create_lib_data_path(filepath_empty)
def test_create_lib_data_path_valueerr(self, filepath_invalid_value, resource_func):
"""Check that functions cause a value error when given a string that cannot be a filepath."""
with pytest.raises(ValueError):
resource_func(filepath_invalid_value)
def test_create_lib_data_path_typeerr(self, filepath_invalid_type, resource_func):
"""Check that functions cause a type error when given a path of an incorrect type."""
with pytest.raises(TypeError):
resource_func(filepath_invalid_type)
class TestResourcePathComponents:
"""A container for tests relating to generation of component parts of a resource path."""
@pytest.mark.parametrize('version, expected_version_foldername', [
('2.03', '2-03'),
('2.02', '2-02'),
('2.01', '2-01'),
('1.05', '1-05'),
('1.04', '1-04'),
('1.03', '1-03'),
('1.02', '1-02'),
('1.01', '1-01'),
('2.2.0', '2-03'),
('2.1.10', '2-02'),
('2.0.5', '2-01'),
('1.4.4', '1-05'),
('1.3.3', '1-04'),
('1.2.2', '1-03'),
('1.1.1', '1-02'),
('1.1.0', '1-02'),
('1.0.0', '1-01'),
(Decimal('1.05'), '1-05'),
(Decimal('1.04'), '1-04'),
(Decimal('1.03'), '1-03'),
(Decimal('1.02'), '1-02'),
(Decimal('1.01'), '1-01'),
(iati.Version('2.03'), '2-03'),
(iati.Version('2.02'), '2-02'),
(iati.Version('2.01'), '2-01'),
(iati.Version('1.05'), '1-05'),
(iati.Version('1.04'), '1-04'),
(iati.Version('1.03'), '1-03'),
(iati.Version('1.02'), '1-02'),
(iati.Version('1.01'), '1-01'),
('1', '1'),
('2', '2'),
(iati.version.STANDARD_VERSION_ANY, iati.resources.PATH_VERSION_INDEPENDENT)
])
@pytest.mark.latest_version('2.03')
def test_folder_name_for_version_generation_known(self, version, expected_version_foldername):
"""Check that the correct folder name is returned for known version numbers."""
folder_name = iati.resources.folder_name_for_version(version)
assert expected_version_foldername == folder_name
def test_folder_name_for_version_generation_unknown(self, std_ver_all_mixedinst_valid_unknown):
"""Check that a ValueError is raised when trying to create a folder name for an unknown version."""
with pytest.raises(ValueError):
iati.resources.folder_name_for_version(std_ver_all_mixedinst_valid_unknown)
def test_folder_name_for_version_valueerr(self, std_ver_all_uninst_valueerr):
"""Check that a version of the Standard of the correct type, but an incorrect value raises a ValueError."""
with pytest.raises(ValueError):
iati.resources.folder_name_for_version(std_ver_all_uninst_valueerr)
def test_folder_name_for_version_typeerr(self, std_ver_all_uninst_typeerr):
"""Check that a version of the Standard of the correct type, but an incorrect value raises a TypeError."""
with pytest.raises(TypeError):
iati.resources.folder_name_for_version(std_ver_all_uninst_typeerr)
def test_folder_name_for_version_requires_version(self):
"""Check that a version must be specified when requesting a folder name for a version (there is no default)."""
with pytest.raises(TypeError):
iati.resources.folder_name_for_version() # pylint: disable=no-value-for-parameter
class TestResoucePathCreationEntireStandard:
"""A container for tests relating to generating entire filepaths for any part of the Standard."""
def test_folder_path_for_version_known(self, std_ver_any_mixedinst_valid_known):
"""Check that expected components are present within folder paths for data for known versions of the IATI Standard."""
expected_components = ['resources', 'standard', iati.resources.BASE_PATH_STANDARD]
version_folder = iati.resources.folder_name_for_version(std_ver_any_mixedinst_valid_known)
full_path = iati.resources.folder_path_for_version(std_ver_any_mixedinst_valid_known)
assert version_folder in full_path
for component in expected_components:
assert component in full_path
def test_folder_path_for_version_unknown_valueerr(self, std_ver_all_mixedinst_valid_unknown):
"""Check that a ValueError is raised when trying to create a path for an unknown version of the IATI Standard."""
with pytest.raises(ValueError):
iati.resources.folder_path_for_version(std_ver_all_mixedinst_valid_unknown)
def test_folder_path_for_version_typeerr(self, std_ver_all_uninst_typeerr):
"""Check that a TypeError is raised when trying to create a folder path for a value of a type that cannot be a version number."""
with pytest.raises(TypeError):
iati.resources.folder_path_for_version(std_ver_all_uninst_typeerr)
def test_folder_path_for_version_requires_version(self):
"""Check that a version must be specified when requesting a folder path for a version (there is no default)."""
with pytest.raises(TypeError):
iati.resources.folder_path_for_version() # pylint: disable=no-value-for-parameter
def test_path_for_version_known(self, filename_no_meaning, std_ver_any_mixedinst_valid_known):
"""Check that expected components are present within absolute paths for data for known versions of the IATI Standard."""
relative_path = iati.resources.folder_path_for_version(std_ver_any_mixedinst_valid_known)
abs_path = iati.resources.path_for_version(filename_no_meaning, std_ver_any_mixedinst_valid_known)
assert abs_path.startswith(os.path.sep)
assert relative_path in abs_path
assert abs_path.endswith(filename_no_meaning)
def test_path_for_version_empty_path(self, filepath_empty, std_ver_any_mixedinst_valid_known):
"""Check that expected components are present within an absolute path for an empty path within a version folder."""
relative_path = iati.resources.folder_path_for_version(std_ver_any_mixedinst_valid_known)
abs_path = iati.resources.path_for_version(filepath_empty, std_ver_any_mixedinst_valid_known)
assert abs_path.startswith(os.path.sep)
assert relative_path in abs_path
assert abs_path.split(os.path.sep).pop() == filepath_empty
# there are not currently folders for integer resource versions
if isinstance(std_ver_any_mixedinst_valid_known, iati.Version) or std_ver_any_mixedinst_valid_known == iati.version.STANDARD_VERSION_ANY:
assert os.path.isdir(abs_path)
def test_path_for_version_unknown_ver_valueerr(self, filename_no_meaning_single, std_ver_all_mixedinst_valid_unknown):
"""Check that a ValueError is raised when trying to create a path for an unknown version of the IATI Standard."""
with pytest.raises(ValueError):
iati.resources.path_for_version(filename_no_meaning_single, std_ver_all_mixedinst_valid_unknown)
def test_path_for_version_unknown_ver_typeerr(self, filename_no_meaning_single, std_ver_all_uninst_typeerr):
"""Check that a TypeError is raised when trying to create a folder path for a value of a type that cannot be a version number."""
with pytest.raises(TypeError):
iati.resources.path_for_version(filename_no_meaning_single, std_ver_all_uninst_typeerr)
def test_path_for_version_requires_version(self, filename_no_meaning_single):
"""Check that a version must be specified when requesting a path for a version (there is no default)."""
with pytest.raises(TypeError):
iati.resources.path_for_version(filename_no_meaning_single) # pylint: disable=no-value-for-parameter
def test_path_for_version_path_valueerr(self, filepath_invalid_value, std_ver_minor_inst_valid_single):
"""Check that a ValueError is raised when trying to create a path from a string that cannot be a filepath."""
with pytest.raises(ValueError):
iati.resources.path_for_version(filepath_invalid_value, std_ver_minor_inst_valid_single)
def test_path_for_version_path_typeerr(self, filepath_invalid_type, std_ver_minor_inst_valid_single):
"""Check that a TypeError is raised when trying to create an absolute path from a path of an incorrect type."""
with pytest.raises(TypeError):
iati.resources.path_for_version(filepath_invalid_type, std_ver_minor_inst_valid_single)
class TestResourcePathCreationCodelistMapping:
"""A container for tests relating to creating Codelist Mapping File paths."""
def test_create_codelist_mapping_path_minor(self, std_ver_minor_mixedinst_valid_known):
"""Check that there is a single Codelist Mapping File for minor versions."""
version_folder = iati.resources.folder_name_for_version(std_ver_minor_mixedinst_valid_known)
path = iati.resources.create_codelist_mapping_path(std_ver_minor_mixedinst_valid_known)
assert isinstance(path, str)
assert path.endswith(iati.resources.FILE_CODELIST_MAPPING + iati.resources.FILE_CODELIST_EXTENSION)
assert version_folder in path
def test_create_codelist_mapping_path_major(self, std_ver_major_uninst_valid_known):
"""Check that requesting a Codelist Mapping File for a major version returns the same path as for the last minor within the major."""
minor_version = max(iati.version.versions_for_integer(std_ver_major_uninst_valid_known))
path_major = iati.resources.create_codelist_mapping_path(std_ver_major_uninst_valid_known)
path_minor = iati.resources.create_codelist_mapping_path(minor_version)
assert path_major == path_minor
def test_create_codelist_mapping_path_version_independent(self):
"""Check that a ValueError is raised when requesting a version-independent Codelist Mapping File."""
with pytest.raises(ValueError):
iati.resources.create_codelist_mapping_path(iati.version.STANDARD_VERSION_ANY)
def test_create_codelist_mapping_path_unknown(self, std_ver_all_mixedinst_valid_unknown):
"""Check that a ValueError is raised when requesting a Codelist Mapping file for an unknown version of the Standard."""
with pytest.raises(ValueError):
iati.resources.create_codelist_mapping_path(std_ver_all_mixedinst_valid_unknown)
def test_create_codelist_mapping_path_no_version(self):
"""Check that specifying a version of the Standard to create a Codelist Mapping path for is required."""
with pytest.raises(TypeError):
iati.resources.create_codelist_mapping_path() # pylint: disable=no-value-for-parameter
def test_create_codelist_mapping_path_typerr(self, std_ver_all_uninst_typeerr):
"""Check that a TypeError is raised when using a generation function to create a Codelist Mapping path from a version of an incorrect type."""
with pytest.raises(TypeError):
iati.resources.create_codelist_mapping_path(std_ver_all_uninst_typeerr)
class TestResourcePathCreationCoreComponents:
"""A container for tests relating to path creation for core components in the IATI Standard.
Core components include Codelists, Rulesets and Schemas.
Each of these should act equivalently across different version and path inputs since their parameters are the same.
Schemas are available at more versions than Rulesets, though this is not an issue since the create_x_path() functions do not check whether a path actually exists.
"""
@pytest.fixture(params=[
iati.resources.create_codelist_path,
iati.resources.create_ruleset_path,
iati.resources.create_schema_path
])
def func_to_test(self, request):
"""Return a function to test."""
return request.param
@pytest.fixture(params=[
iati.resources.create_ruleset_path,
iati.resources.create_schema_path
])
def func_to_test_decimalised_integers(self, request):
"""Return a function to test that treats integers as the latest minor within the major."""
return request.param
@pytest.fixture(params=[
(iati.resources.create_codelist_path, iati.resources.FILE_CODELIST_EXTENSION, iati.resources.PATH_CODELISTS),
(iati.resources.create_ruleset_path, iati.resources.FILE_RULESET_EXTENSION, iati.resources.PATH_RULESETS),
(iati.resources.create_schema_path, iati.resources.FILE_SCHEMA_EXTENSION, iati.resources.PATH_SCHEMAS)
])
def func_plus_expected_data(self, request):
"""Return a tuple containing a function to test, plus the extension and a component that should be present in the returned path."""
output = collections.namedtuple('output', 'func_to_test expected_extension expected_component')
return output(func_to_test=request.param[0], expected_extension=request.param[1], expected_component=request.param[2])
def test_create_path_minor_known(self, filename_no_meaning, std_ver_minor_independent_mixedinst_valid_known, func_plus_expected_data):
"""Check that the expected components are present in a path from a generation function at a known minor or independent version of the Standard."""
version_folder = iati.resources.folder_name_for_version(std_ver_minor_independent_mixedinst_valid_known)
full_path = func_plus_expected_data.func_to_test(filename_no_meaning, std_ver_minor_independent_mixedinst_valid_known)
assert isinstance(full_path, str)
assert full_path.endswith(filename_no_meaning + func_plus_expected_data.expected_extension)
assert version_folder in full_path
assert func_plus_expected_data.expected_component in full_path
def test_create_path_major_known_codelists(self, filename_no_meaning_single, std_ver_major_uninst_valid_known):
"""Check that a generation function returns a value for a major version.
This is relevant to Codelists, but not other components. These are tested separately.
"""
version_folder = iati.resources.folder_name_for_version(std_ver_major_uninst_valid_known)
full_path = iati.resources.create_codelist_path(filename_no_meaning_single, std_ver_major_uninst_valid_known)
assert isinstance(full_path, str)
assert full_path.endswith(filename_no_meaning_single + iati.resources.FILE_CODELIST_EXTENSION)
assert os.path.sep + version_folder + os.path.sep in full_path
assert iati.resources.PATH_CODELISTS in full_path
def test_create_path_major_known_decimalised_integers(self, filename_no_meaning_single, std_ver_major_uninst_valid_known, func_to_test_decimalised_integers):
"""Check that a generation function returns the same value for a major version as the last minor within the major.
This is relevant to some Standard components, though not all. As such, it uses a different fixture to other functions in this class.
"""
minor_version = max(iati.version.versions_for_integer(std_ver_major_uninst_valid_known))
major_path = func_to_test_decimalised_integers(filename_no_meaning_single, std_ver_major_uninst_valid_known)
minor_path = func_to_test_decimalised_integers(filename_no_meaning_single, minor_version)
assert major_path == minor_path
def test_create_path_no_version(self, filename_no_meaning_single, func_to_test):
"""Check that specifying a version of the Standard to create a path for is required."""
with pytest.raises(TypeError):
func_to_test(filename_no_meaning_single)
def test_create_path_unknown(self, filename_no_meaning_single, std_ver_all_mixedinst_valid_unknown, func_to_test):
"""Check that a ValueError is raised when using a generation function to create a path for a at an unknown version of the Standard."""
with pytest.raises(ValueError):
func_to_test(filename_no_meaning_single, std_ver_all_mixedinst_valid_unknown)
def test_create_path_ver_typerr(self, filename_no_meaning_single, std_ver_all_uninst_typeerr, func_to_test):
"""Check that a TypeError is raised when using a generation function to create a path from a version of an incorrect type."""
with pytest.raises(TypeError):
func_to_test(filename_no_meaning_single, std_ver_all_uninst_typeerr)
def test_create_path_path_valueerr(self, filepath_invalid_value, std_ver_minor_inst_valid_single, func_to_test):
"""Check that a ValueError is raised when providing a generation function a path to work from that is a string that cannot be a filepath."""
with pytest.raises(ValueError):
func_to_test(filepath_invalid_value, std_ver_minor_inst_valid_single)
def test_create_path_path_typeerr(self, filepath_invalid_type, std_ver_minor_inst_valid_single, func_to_test):
"""Check that a TypeError is raised when providing a generation function a path to work from that is of a type that cannot be a filepath."""
with pytest.raises(TypeError):
func_to_test(filepath_invalid_type, std_ver_minor_inst_valid_single)
class TestResourceGetCodelistPaths:
"""A container for get_codelist_paths() tests."""
def test_find_codelist_paths(self, codelist_lengths_by_version):
"""Check that all codelist paths are being found.
This covers major, minor and version-independent.
"""
decimalised_version = iati.version._decimalise_integer(codelist_lengths_by_version.version) # pylint: disable=protected-access
expected_root = iati.resources.path_for_version(iati.resources.PATH_CODELISTS, decimalised_version)
paths = iati.resources.get_codelist_paths(codelist_lengths_by_version.version)
assert len(paths) == len(set(paths))
assert len(paths) == codelist_lengths_by_version.expected_length
for path in paths:
assert path[-4:] == iati.resources.FILE_CODELIST_EXTENSION
assert expected_root in path
assert os.path.isfile(path)
def test_get_codelist_mapping_paths_independent(self):
"""Test getting a list of version-independent Codelist files.
Todo:
Look to better determine how to access the different categories of Codelist.
"""
result = iati.resources.get_codelist_paths(iati.version.STANDARD_VERSION_ANY)
assert result == []
def test_get_codelist_paths_minor_partsupport(self, std_ver_minor_mixedinst_valid_partsupport):
"""Test getting a list of Codelist paths. The requested version is partially supported by pyIATI."""
result = iati.resources.get_codelist_paths(std_ver_minor_mixedinst_valid_partsupport)
assert result == []
def test_get_codelist_paths_minor_unknown(self, std_ver_all_mixedinst_valid_unknown):
"""Test getting a list of Codelist paths. The requested version is not known by pyIATI."""
result = iati.resources.get_codelist_paths(std_ver_all_mixedinst_valid_unknown)
assert result == []
class TestResourceGetCodelistMappingPaths:
"""A container for get_codelist_mapping_paths() tests.
Note:
This class contains very similar tests to the equivalent for Rulesets. They are different because the Ruleset creation function takes two arguments, not one.
"""
def test_get_codelist_mapping_paths_minor_fullsupport(self, std_ver_minor_mixedinst_valid_fullsupport):
"""Test getting a list of Codelist Mapping paths. The requested version is fully supported by pyIATI."""
result = iati.resources.get_codelist_mapping_paths(std_ver_minor_mixedinst_valid_fullsupport)
assert len(result) == 1
assert result[0] == iati.resources.create_codelist_mapping_path(std_ver_minor_mixedinst_valid_fullsupport)
assert os.path.isfile(result[0])
def test_get_codelist_mapping_paths_independent(self):
"""Test getting a list of version-independent Codelist Mapping files."""
result = iati.resources.get_codelist_mapping_paths(iati.version.STANDARD_VERSION_ANY)
assert result == []
def test_get_codelist_mapping_paths_minor_partsupport(self, std_ver_minor_mixedinst_valid_partsupport):
"""Test getting a list of Codelist Mapping paths. The requested version is partially supported by pyIATI."""
result = iati.resources.get_codelist_mapping_paths(std_ver_minor_mixedinst_valid_partsupport)
assert result == []
def test_get_codelist_mapping_paths_minor_unknown(self, std_ver_all_mixedinst_valid_unknown):
"""Test getting a list of Codelist Mapping paths. The requested version is not known by pyIATI."""
result = iati.resources.get_codelist_mapping_paths(std_ver_all_mixedinst_valid_unknown)
assert result == []
def test_get_codelist_mapping_paths_major_known(self, std_ver_major_uninst_valid_known):
"""Test getting a list of Codelist Mapping paths. The requested version is a known integer version. The list should contain paths for each supported minor within the major."""
supported_versions_at_major = [version for version in iati.version.versions_for_integer(std_ver_major_uninst_valid_known) if version in iati.version.STANDARD_VERSIONS_SUPPORTED]
expected_path_count = len(supported_versions_at_major)
result = iati.resources.get_codelist_mapping_paths(std_ver_major_uninst_valid_known)
assert len(result) == expected_path_count
for version in supported_versions_at_major:
assert iati.resources.create_codelist_mapping_path(version) in result
class TestResourceGetRulesetPaths:
"""A container for get_ruleset_paths() tests."""
def test_get_ruleset_paths_minor_fullsupport(self, std_ver_minor_mixedinst_valid_fullsupport):
"""Test getting a list of Ruleset paths. The requested version is fully supported by pyIATI."""
result = iati.resources.get_ruleset_paths(std_ver_minor_mixedinst_valid_fullsupport)
assert len(result) == 1
assert result[0] == iati.resources.create_ruleset_path(iati.resources.FILE_RULESET_STANDARD_NAME, std_ver_minor_mixedinst_valid_fullsupport)
assert os.path.isfile(result[0])
def test_get_ruleset_paths_independent(self):
"""Test getting a list of version-independent standard Rulesets."""
result = iati.resources.get_ruleset_paths(iati.version.STANDARD_VERSION_ANY)
assert result == []
def test_get_ruleset_paths_minor_partsupport(self, std_ver_minor_mixedinst_valid_partsupport):
"""Test getting a list of Ruleset paths. The requested version is partially supported by pyIATI."""
result = iati.resources.get_ruleset_paths(std_ver_minor_mixedinst_valid_partsupport)
assert result == []
def test_get_ruleset_paths_minor_unknown(self, std_ver_all_mixedinst_valid_unknown):
"""Test getting a list of Ruleset paths. The requested version is not known by pyIATI."""
result = iati.resources.get_ruleset_paths(std_ver_all_mixedinst_valid_unknown)
assert result == []
def test_get_ruleset_paths_major_known(self, std_ver_major_uninst_valid_known):
"""Test getting a list of Ruleset paths. The requested version is a known integer version. The list should contain paths for each supported minor within the major."""
supported_versions_at_major = [version for version in iati.version.versions_for_integer(std_ver_major_uninst_valid_known) if version in iati.version.STANDARD_VERSIONS_SUPPORTED]
expected_path_count = len(supported_versions_at_major)
result = iati.resources.get_ruleset_paths(std_ver_major_uninst_valid_known)
assert len(result) == expected_path_count
for version in supported_versions_at_major:
assert iati.resources.create_ruleset_path(iati.resources.FILE_RULESET_STANDARD_NAME, version) in result
class TestResourceGetSchemaPaths:
"""A container for get_x_schema_paths() tests."""
@pytest.fixture(params=[
(iati.resources.get_activity_schema_paths, iati.resources.FILE_SCHEMA_ACTIVITY_NAME),
(iati.resources.get_organisation_schema_paths, iati.resources.FILE_SCHEMA_ORGANISATION_NAME)
])
def func_and_name(self, request):
"""Return a named tuple containing a function to generate the paths for a type of Schema, plus the name of the Schema."""
output = collections.namedtuple('output', 'func schema_name')
return output(func=request.param[0], schema_name=request.param[1])
@pytest.fixture(params=[
iati.resources.get_all_schema_paths,
iati.resources.get_activity_schema_paths,
iati.resources.get_organisation_schema_paths
])
def schema_path_func_all(self, request):
"""Return a function that returns a list of paths for Schema resources."""
return request.param
def test_get_schema_paths_minor_known(self, std_ver_minor_mixedinst_valid_known, func_and_name):
"""Test getting a list of Org or Activity Schema paths. The requested version is known by pyIATI."""
result = func_and_name.func(std_ver_minor_mixedinst_valid_known)
assert len(result) == 1
assert result[0] == iati.resources.create_schema_path(func_and_name.schema_name, std_ver_minor_mixedinst_valid_known)
assert os.path.isfile(result[0])
def test_get_schema_paths_minor_unknown(self, std_ver_all_mixedinst_valid_unknown, schema_path_func_all):
"""Test getting a list of Org or Activity Schema paths. The requested version is not known by pyIATI."""
result = schema_path_func_all(std_ver_all_mixedinst_valid_unknown)
assert result == []
def test_get_schema_paths_independent(self, schema_path_func_all):
"""Test getting a list of version-independent Org or Activity Schemas."""
result = schema_path_func_all(iati.version.STANDARD_VERSION_ANY)
assert result == []
def test_get_schema_paths_major_known(self, std_ver_major_uninst_valid_known, func_and_name):
"""Test getting a list of Org or Activity Schema paths. The requested version is a known integer version. The list should contain paths for each supported minor within the major."""
versions_at_major = [version for version in iati.version.versions_for_integer(std_ver_major_uninst_valid_known)]
expected_path_count = len(versions_at_major)
result = func_and_name.func(std_ver_major_uninst_valid_known)
assert len(result) == expected_path_count
for version in versions_at_major:
assert iati.resources.create_schema_path(func_and_name.schema_name, version) in result
def test_get_all_schema_paths_minor_known(self, std_ver_minor_mixedinst_valid_known):
"""Test getting a list of all Schema paths. The requested version is known by pyIATI."""
activity_path = iati.resources.get_activity_schema_paths(std_ver_minor_mixedinst_valid_known)[0]
org_path = iati.resources.get_organisation_schema_paths(std_ver_minor_mixedinst_valid_known)[0]
result = iati.resources.get_all_schema_paths(std_ver_minor_mixedinst_valid_known)
assert len(result) == 2
assert activity_path in result
assert org_path in result
def test_get_all_schema_paths_major_known(self, std_ver_major_uninst_valid_known):
"""Test getting a list of all Schema paths. The requested version is a known integer version. The list should contain paths for each supported minor within the major."""
versions_at_major = [version for version in iati.version.versions_for_integer(std_ver_major_uninst_valid_known)]
expected_path_count = len(versions_at_major) * 2
activity_paths = iati.resources.get_activity_schema_paths(std_ver_major_uninst_valid_known)
org_paths = iati.resources.get_organisation_schema_paths(std_ver_major_uninst_valid_known)
result = iati.resources.get_all_schema_paths(std_ver_major_uninst_valid_known)
assert len(result) == expected_path_count
for path in activity_paths:
assert path in result
for path in org_paths:
assert path in result
class TestResourceGetPathsNotAVersion:
"""A container for get_*_paths() tests where the function is provided a value that cannot represent a version."""
@pytest.fixture(params=[
iati.resources.get_codelist_paths,
iati.resources.get_codelist_mapping_paths,
iati.resources.get_ruleset_paths,
iati.resources.get_all_schema_paths,
iati.resources.get_activity_schema_paths,
iati.resources.get_organisation_schema_paths
])
def func_to_test(self, request):
"""Return a function to test the behavior of. The function takes a single argument, which takes a value that can represent a version number."""
return request.param
def test_get_x_path_valueerr(self, std_ver_all_uninst_valueerr, func_to_test):
"""Check that a ValueError is raised when requesting paths for an value that cannot be a version of the Standard."""
with pytest.raises(ValueError):
func_to_test(std_ver_all_uninst_valueerr)
def test_get_x_path_no_version(self, func_to_test):
"""Check that a TypeError is raised when requesting paths without specifying a version."""
with pytest.raises(TypeError):
func_to_test()
def test_get_x_path_typerr(self, std_ver_all_uninst_typeerr, func_to_test):
"""Check that a TypeError is raised when requesting paths for a version of an incorrect type."""
with pytest.raises(TypeError):
func_to_test(std_ver_all_uninst_typeerr)
class TestResourceTestDataFolders:
"""A container for tests relating to resource folders."""
@pytest.mark.parametrize('version, expected_num_paths', [
('2.03', 323),
('2.02', 237),
('2.01', 217),
('1.05', 17),
('1.04', 17),
('1.03', 17),
('1.02', 17),
('1.01', 16),
('1', 0),
('2', 0),
(iati.version.STANDARD_VERSION_ANY, 0)
])
@pytest.mark.latest_version('2.03')
def test_get_test_data_paths_in_folder(self, version, expected_num_paths):
"""Check that test data is being found in specified subfolders.
Look for the number of paths in the `ssot-activity-xml-fail` folder.
"""
paths = iati.tests.resources.get_test_data_paths_in_folder('ssot-activity-xml-fail', version)
assert len(paths) == expected_num_paths
| {
"content_hash": "5697c6aad0478b8cbaf4d0ba30309004",
"timestamp": "",
"source": "github",
"line_count": 687,
"max_line_length": 189,
"avg_line_length": 52.41048034934498,
"alnum_prop": 0.6968005332444592,
"repo_name": "IATI/iati.core",
"id": "36ee80c695f37c99b96335d3d3427961a6eae8fa",
"size": "36006",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iati/tests/test_resources.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "861"
},
{
"name": "Python",
"bytes": "126390"
},
{
"name": "Shell",
"bytes": "538"
}
],
"symlink_target": ""
} |
<?php
/**
* URLs for scripts and stylesheets, minified if possible.
*
* @version 2014.10.07
* @author Inpsyde GmbH, toscho
* @license GPL
*/
class Mlp_Asset_Url implements Mlp_Asset_Url_Interface {
/**
* @type string
*/
private $url = '';
/**
* File version
*
* @type string
*/
private $version = '';
/**
* Constructor
*
* @param string $file_name The normal name like 'backend.css'
* @param string $dir_path Local path to the directory with the file.
* @param string $dir_url Public URL for $dir_path.
*/
public function __construct( $file_name, $dir_path, $dir_url ) {
$this->url = $this->build_url( $file_name, $dir_path, $dir_url );
}
/**
* Returns an URL
*
* @return string
*/
public function __toString() {
return $this->url;
}
/**
* @return string
*/
public function get_version() {
return $this->version;
}
/**
* Check path and minify
*
* @see Mlp_Asset_Url::__construct()
* @param string $file_name
* @param string $dir_path
* @param string $dir_url
* @return string
*/
private function build_url( $file_name, $dir_path, $dir_url ) {
$dir_path = rtrim( $dir_path, '/' );
$dir_url = rtrim( $dir_url, '/' );
$file_name = $this->maybe_minify( $file_name, $dir_path );
$file_path = "$dir_path/$file_name";
if ( ! is_readable( $file_path ) )
return '';
$this->version = filemtime( $file_path );
return "$dir_url/$file_name";
}
/**
* Minify if debug mode is on and minified file exists
*
* @param string $file_name
* @param string $dir_path
* @return string
*/
private function maybe_minify( $file_name, $dir_path ) {
// We do not minify in debug mode
if ( $this->is_debug_mode() )
return $file_name;
$minified_file_name = $this->get_minified_file_name( $file_name );
if ( $minified_file_name === $file_name )
return $file_name;
if ( ! is_readable( "$dir_path/$minified_file_name" ) )
return $file_name;;
return $minified_file_name;
}
/**
* @return bool
*/
private function is_debug_mode() {
if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG )
return TRUE;
return defined( 'MULTILINGUALPRESS_DEBUG' ) && MULTILINGUALPRESS_DEBUG;
}
/**
* Add '.min.' to file name
*
* @param string $file_name
* @return string
*/
private function get_minified_file_name( $file_name ) {
// This is already a minified file.
if ( FALSE !== strpos( $file_name, '.min.' ) )
return $file_name;
// The file might have a name like 'plugin.admin.network.css'
$parts = explode( '.', $file_name );
$extension = array_pop( $parts );
return join( '.', $parts ) . ".min.$extension";
}
} | {
"content_hash": "72b932827f0d329e902750bdebec4bb4",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 73,
"avg_line_length": 20.242424242424242,
"alnum_prop": 0.6017964071856288,
"repo_name": "FabriPalladino/parapendiomatese",
"id": "d965a3db0209795e1b9c42e4fbb959af073de9a0",
"size": "2672",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "web/app/plugins/multilingual-press/inc/assets/Mlp_Asset_Url.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2486508"
},
{
"name": "HTML",
"bytes": "24390"
},
{
"name": "JavaScript",
"bytes": "3790787"
},
{
"name": "PHP",
"bytes": "16010627"
},
{
"name": "Ruby",
"bytes": "1169"
}
],
"symlink_target": ""
} |
require 'hmac-sha1'
require 'faraday'
require 'quickblox_api/version'
require 'quickblox_api/encoder'
require 'quickblox_api/helpers'
require 'quickblox_api/config'
require 'quickblox_api/base_client'
require 'quickblox_api/client'
require 'quickblox_api/user_client'
module QuickbloxApi
def self.client(opts)
QuickbloxApi::Client.new(secrets: opts)
end
def self.user_client(opts)
QuickbloxApi::UserClient.new(opts)
end
end
| {
"content_hash": "814da208a11d0650bbdbd9d874c1522f",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 43,
"avg_line_length": 22.15,
"alnum_prop": 0.7697516930022573,
"repo_name": "abscondite/quickblox_api",
"id": "cebc0a5e6712e0b4c9a1241112cc8ba3db1becbf",
"size": "443",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/quickblox_api.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "6854"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
title: ams8
type: products
image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png
heading: s8
description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj
main:
heading: Foo Bar BAz
description: |-
***This is i a thing***kjh hjk kj
# Blah Blah
## Blah
### Baah
image1:
alt: kkkk
---
| {
"content_hash": "41cd70e1562772f23fe86a56a45acdb7",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 61,
"avg_line_length": 22.2,
"alnum_prop": 0.6636636636636637,
"repo_name": "pblack/kaldi-hugo-cms-template",
"id": "597823ef3144ff14f6f05f64066f0c327e9de2f7",
"size": "337",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "site/content/pages2/ams8.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "94394"
},
{
"name": "HTML",
"bytes": "18889"
},
{
"name": "JavaScript",
"bytes": "10014"
}
],
"symlink_target": ""
} |
title: Rifinito
body_classes: 'header-image fullwidth'
twitterenable: true
twittercardoptions: summary
facebookenable: true
---
I nostri articoli rifiniti sono molteplici: spalle e gropponi da cintura, gropponi per borsetteria, gropponi, spalle e mezzi vitelli per arredo e fondine. | {
"content_hash": "da92296b72e4f79e4c2d2bef8048b7e2",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 154,
"avg_line_length": 35.375,
"alnum_prop": 0.8162544169611308,
"repo_name": "filippomasoni/lascarpa",
"id": "63ddd56859599bdc944087f3ddbf5ec017bda412",
"size": "287",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "user/pages/04.articoli/03.rifinito/product.it.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "508751"
},
{
"name": "HTML",
"bytes": "357018"
},
{
"name": "JavaScript",
"bytes": "2041384"
},
{
"name": "Logos",
"bytes": "831"
},
{
"name": "PHP",
"bytes": "1632647"
},
{
"name": "Shell",
"bytes": "596"
},
{
"name": "XSLT",
"bytes": "827"
}
],
"symlink_target": ""
} |
//
// QuickSort.cs
//
// Authors:
// Alejandro Serrano "Serras" ([email protected])
// Marek Safar <[email protected]>
// Jb Evain ([email protected])
//
// (C) 2007 - 2008 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
namespace Devdog.General.ThirdParty.UniLinq
{
class QuickSort<TElement>
{
TElement[] elements;
int[] indexes;
SortContext<TElement> context;
QuickSort (IEnumerable<TElement> source, SortContext<TElement> context)
{
List<TElement> temp = new List<TElement>();
foreach (TElement element in source) {
temp.Add (element);
}
this.elements = temp.ToArray ();
this.indexes = CreateIndexes (elements.Length);
this.context = context;
}
static int [] CreateIndexes (int length)
{
var indexes = new int [length];
for (int i = 0; i < length; i++)
indexes [i] = i;
return indexes;
}
void PerformSort ()
{
// If the source contains just zero or one element, there's no need to sort
if (elements.Length <= 1)
return;
context.Initialize (elements);
// Then sorts the elements according to the collected
// key values and the selected ordering
Array.Sort<int> (indexes, context);
}
public static IEnumerable<TElement> Sort (IEnumerable<TElement> source, SortContext<TElement> context)
{
var sorter = new QuickSort<TElement> (source, context);
sorter.PerformSort ();
for (int i = 0; i < sorter.elements.Length; i++)
yield return sorter.elements [sorter.indexes [i]];
}
}
}
| {
"content_hash": "2240278f94efb64ee9809164ce11f153",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 104,
"avg_line_length": 30.476744186046513,
"alnum_prop": 0.7085082029759634,
"repo_name": "djspider117/jacked",
"id": "45ed8fadff0bddd8cba44e6351630d8026b135a9",
"size": "2623",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Jacked/Assets/Devdog/General/ThirdParty/UniLinq/QuickSort.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2069234"
},
{
"name": "GLSL",
"bytes": "1074889"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotSpatial.Projections;
using Microsoft.SqlServer.Types;
namespace SqlServerSpatial.Toolkit
{
public static class SqlGeometryReprojection
{
public static SqlGeometry ReprojectTo(this SqlGeometry geom, int destinationEpsgCode)
{
Func<double[], double[]> reprojectionFunc = SqlGeometryReprojection.Identity;
if (geom.STSrid.Value != destinationEpsgCode)
{
// Defines the starting coordiante system
ProjectionInfo pStart = ProjectionInfo.FromEpsgCode(geom.STSrid.Value);
// Defines the starting coordiante system
ProjectionInfo pEnd = ProjectionInfo.FromEpsgCode(destinationEpsgCode);
reprojectionFunc = pts => SqlGeometryReprojection.ReprojectPoint(pts, 0, pStart, pEnd);
}
GeometryToGeometrySink sink = new GeometryToGeometrySink(destinationEpsgCode, pts => reprojectionFunc(pts));
geom.Populate(sink);
return sink.ConstructedGeometry;
}
public static SqlGeometry ReprojectTo(this SqlGeometry geom, ProjectionInfo destination)
{
Func<double[], double[]> reprojectionFunc = SqlGeometryReprojection.Identity;
// Defines the starting coordiante system
ProjectionInfo pStart = ProjectionInfo.FromEpsgCode(geom.STSrid.Value);
// Defines the starting coordiante system
ProjectionInfo pEnd = destination;
reprojectionFunc = pts => SqlGeometryReprojection.ReprojectPoint(pts, 0, pStart, pEnd);
GeometryToGeometrySink sink = new GeometryToGeometrySink(destination.AuthorityCode, pts => reprojectionFunc(pts));
geom.Populate(sink);
return sink.ConstructedGeometry;
}
private static double[] ReprojectPoint(double[] sourcePoint, double z, ProjectionInfo sourceProj, ProjectionInfo destProj)
{
// Calls the reproject function that will transform the input location to the output locaiton
Reproject.ReprojectPoints(sourcePoint, new double[] { z }, sourceProj, destProj, 0, 1);
return sourcePoint;
}
private static double[] Identity(double[] sourcePoint)
{
return sourcePoint;
}
}
internal class GeometryToGeometrySink : IGeometrySink110
{
#region IGeometrySink Membres
private readonly SqlGeometryBuilder _builder;
private Func<double[], double[]> _reprojectionFunc;
public GeometryToGeometrySink(int srid, Func<double[], double[]> reprojectionFunc)
{
_builder = new SqlGeometryBuilder();
_builder.SetSrid(srid);
_reprojectionFunc = reprojectionFunc;
}
void IGeometrySink.AddLine(double x, double y, double? z, double? m)
{
double[] pts = new double[] { x, y };
pts = _reprojectionFunc(pts);
_builder.AddLine(pts[0], pts[1]);
}
void IGeometrySink.BeginFigure(double x, double y, double? z, double? m)
{
double[] pts = new double[] { x, y };
pts = _reprojectionFunc(pts);
_builder.BeginFigure(pts[0], pts[1]);
}
void IGeometrySink.BeginGeometry(OpenGisGeometryType type)
{
_builder.BeginGeometry(type);
}
void IGeometrySink.EndFigure()
{
_builder.EndFigure();
}
void IGeometrySink.EndGeometry()
{
_builder.EndGeometry();
}
void IGeometrySink.SetSrid(int srid)
{
}
void IGeometrySink110.AddCircularArc(double x1, double y1, double? z1, double? m1, double x2, double y2, double? z2, double? m2)
{
throw new NotImplementedException();
}
#endregion
public SqlGeometry ConstructedGeometry
{
get
{
return _builder.ConstructedGeometry.MakeValidIfInvalid();
}
}
}
}
| {
"content_hash": "dc23cd2bc985093e4bb307ab5a964bc1",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 130,
"avg_line_length": 28.271317829457363,
"alnum_prop": 0.7107211406635591,
"repo_name": "xfischer/SqlServerSpatialTypes.Toolkit",
"id": "229518e34c40aa415e4947215f4dde958e0a2ab7",
"size": "3649",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "SqlServerSpatial.Toolkit/Viewers/GDI/SqlGeometryReprojection.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "191"
},
{
"name": "C#",
"bytes": "125775"
}
],
"symlink_target": ""
} |
class Group < ApplicationRecord
has_many :collection_matrices
end
| {
"content_hash": "2373e82933fdd56fca7425b6f409e45d",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 31,
"avg_line_length": 22.666666666666668,
"alnum_prop": 0.8088235294117647,
"repo_name": "ScottKolo/suitesparse-matrix-collection-website",
"id": "859f0f39db3264df45cbc84a825cf76670ca0154",
"size": "99",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/group.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Gherkin",
"bytes": "30797"
},
{
"name": "HTML",
"bytes": "4588"
},
{
"name": "Haml",
"bytes": "72048"
},
{
"name": "JavaScript",
"bytes": "860"
},
{
"name": "MATLAB",
"bytes": "14677"
},
{
"name": "Ruby",
"bytes": "6922119"
},
{
"name": "SCSS",
"bytes": "7462"
},
{
"name": "Shell",
"bytes": "152"
},
{
"name": "TeX",
"bytes": "3015"
}
],
"symlink_target": ""
} |
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/* Tabulator v4.6.2 (c) Oliver Folkerd */
var Filter = function Filter(table) {
this.table = table; //hold Tabulator object
this.filterList = []; //hold filter list
this.headerFilters = {}; //hold column filters
this.headerFilterColumns = []; //hold columns that use header filters
this.prevHeaderFilterChangeCheck = "";
this.prevHeaderFilterChangeCheck = "{}";
this.changed = false; //has filtering changed since last render
};
//initialize column header filter
Filter.prototype.initializeColumn = function (column, value) {
var self = this,
field = column.getField(),
params;
//handle successfull value change
function success(value) {
var filterType = column.modules.filter.tagType == "input" && column.modules.filter.attrType == "text" || column.modules.filter.tagType == "textarea" ? "partial" : "match",
type = "",
filterChangeCheck = "",
filterFunc;
if (typeof column.modules.filter.prevSuccess === "undefined" || column.modules.filter.prevSuccess !== value) {
column.modules.filter.prevSuccess = value;
if (!column.modules.filter.emptyFunc(value)) {
column.modules.filter.value = value;
switch (_typeof(column.definition.headerFilterFunc)) {
case "string":
if (self.filters[column.definition.headerFilterFunc]) {
type = column.definition.headerFilterFunc;
filterFunc = function filterFunc(data) {
var params = column.definition.headerFilterFuncParams || {};
var fieldVal = column.getFieldValue(data);
params = typeof params === "function" ? params(value, fieldVal, data) : params;
return self.filters[column.definition.headerFilterFunc](value, fieldVal, data, params);
};
} else {
console.warn("Header Filter Error - Matching filter function not found: ", column.definition.headerFilterFunc);
}
break;
case "function":
filterFunc = function filterFunc(data) {
var params = column.definition.headerFilterFuncParams || {};
var fieldVal = column.getFieldValue(data);
params = typeof params === "function" ? params(value, fieldVal, data) : params;
return column.definition.headerFilterFunc(value, fieldVal, data, params);
};
type = filterFunc;
break;
}
if (!filterFunc) {
switch (filterType) {
case "partial":
filterFunc = function filterFunc(data) {
var colVal = column.getFieldValue(data);
if (typeof colVal !== 'undefined' && colVal !== null) {
return String(colVal).toLowerCase().indexOf(String(value).toLowerCase()) > -1;
} else {
return false;
}
};
type = "like";
break;
default:
filterFunc = function filterFunc(data) {
return column.getFieldValue(data) == value;
};
type = "=";
}
}
self.headerFilters[field] = { value: value, func: filterFunc, type: type };
} else {
delete self.headerFilters[field];
}
filterChangeCheck = JSON.stringify(self.headerFilters);
if (self.prevHeaderFilterChangeCheck !== filterChangeCheck) {
self.prevHeaderFilterChangeCheck = filterChangeCheck;
self.changed = true;
self.table.rowManager.filterRefresh();
}
}
return true;
}
column.modules.filter = {
success: success,
attrType: false,
tagType: false,
emptyFunc: false
};
this.generateHeaderFilterElement(column);
};
Filter.prototype.generateHeaderFilterElement = function (column, initialValue, reinitialize) {
var _this = this;
var self = this,
success = column.modules.filter.success,
field = column.getField(),
filterElement,
editor,
editorElement,
cellWrapper,
typingTimer,
searchTrigger,
params;
//handle aborted edit
function cancel() {}
if (column.modules.filter.headerElement && column.modules.filter.headerElement.parentNode) {
column.contentElement.removeChild(column.modules.filter.headerElement.parentNode);
}
if (field) {
//set empty value function
column.modules.filter.emptyFunc = column.definition.headerFilterEmptyCheck || function (value) {
return !value && value !== "0";
};
filterElement = document.createElement("div");
filterElement.classList.add("tabulator-header-filter");
//set column editor
switch (_typeof(column.definition.headerFilter)) {
case "string":
if (self.table.modules.edit.editors[column.definition.headerFilter]) {
editor = self.table.modules.edit.editors[column.definition.headerFilter];
if ((column.definition.headerFilter === "tick" || column.definition.headerFilter === "tickCross") && !column.definition.headerFilterEmptyCheck) {
column.modules.filter.emptyFunc = function (value) {
return value !== true && value !== false;
};
}
} else {
console.warn("Filter Error - Cannot build header filter, No such editor found: ", column.definition.editor);
}
break;
case "function":
editor = column.definition.headerFilter;
break;
case "boolean":
if (column.modules.edit && column.modules.edit.editor) {
editor = column.modules.edit.editor;
} else {
if (column.definition.formatter && self.table.modules.edit.editors[column.definition.formatter]) {
editor = self.table.modules.edit.editors[column.definition.formatter];
if ((column.definition.formatter === "tick" || column.definition.formatter === "tickCross") && !column.definition.headerFilterEmptyCheck) {
column.modules.filter.emptyFunc = function (value) {
return value !== true && value !== false;
};
}
} else {
editor = self.table.modules.edit.editors["input"];
}
}
break;
}
if (editor) {
cellWrapper = {
getValue: function getValue() {
return typeof initialValue !== "undefined" ? initialValue : "";
},
getField: function getField() {
return column.definition.field;
},
getElement: function getElement() {
return filterElement;
},
getColumn: function getColumn() {
return column.getComponent();
},
getRow: function getRow() {
return {
normalizeHeight: function normalizeHeight() {}
};
}
};
params = column.definition.headerFilterParams || {};
params = typeof params === "function" ? params.call(self.table) : params;
editorElement = editor.call(this.table.modules.edit, cellWrapper, function () {}, success, cancel, params);
if (!editorElement) {
console.warn("Filter Error - Cannot add filter to " + field + " column, editor returned a value of false");
return;
}
if (!(editorElement instanceof Node)) {
console.warn("Filter Error - Cannot add filter to " + field + " column, editor should return an instance of Node, the editor returned:", editorElement);
return;
}
//set Placeholder Text
if (field) {
self.table.modules.localize.bind("headerFilters|columns|" + column.definition.field, function (value) {
editorElement.setAttribute("placeholder", typeof value !== "undefined" && value ? value : self.table.modules.localize.getText("headerFilters|default"));
});
} else {
self.table.modules.localize.bind("headerFilters|default", function (value) {
editorElement.setAttribute("placeholder", typeof self.column.definition.headerFilterPlaceholder !== "undefined" && self.column.definition.headerFilterPlaceholder ? self.column.definition.headerFilterPlaceholder : value);
});
}
//focus on element on click
editorElement.addEventListener("click", function (e) {
e.stopPropagation();
editorElement.focus();
});
editorElement.addEventListener("focus", function (e) {
var left = _this.table.columnManager.element.scrollLeft;
if (left !== _this.table.rowManager.element.scrollLeft) {
_this.table.rowManager.scrollHorizontal(left);
_this.table.columnManager.scrollHorizontal(left);
}
});
//live update filters as user types
typingTimer = false;
searchTrigger = function searchTrigger(e) {
if (typingTimer) {
clearTimeout(typingTimer);
}
typingTimer = setTimeout(function () {
success(editorElement.value);
}, self.table.options.headerFilterLiveFilterDelay);
};
column.modules.filter.headerElement = editorElement;
column.modules.filter.attrType = editorElement.hasAttribute("type") ? editorElement.getAttribute("type").toLowerCase() : "";
column.modules.filter.tagType = editorElement.tagName.toLowerCase();
if (column.definition.headerFilterLiveFilter !== false) {
if (!(column.definition.headerFilter === 'autocomplete' || column.definition.headerFilter === 'tickCross' || (column.definition.editor === 'autocomplete' || column.definition.editor === 'tickCross') && column.definition.headerFilter === true)) {
editorElement.addEventListener("keyup", searchTrigger);
editorElement.addEventListener("search", searchTrigger);
//update number filtered columns on change
if (column.modules.filter.attrType == "number") {
editorElement.addEventListener("change", function (e) {
success(editorElement.value);
});
}
//change text inputs to search inputs to allow for clearing of field
if (column.modules.filter.attrType == "text" && this.table.browser !== "ie") {
editorElement.setAttribute("type", "search");
// editorElement.off("change blur"); //prevent blur from triggering filter and preventing selection click
}
}
//prevent input and select elements from propegating click to column sorters etc
if (column.modules.filter.tagType == "input" || column.modules.filter.tagType == "select" || column.modules.filter.tagType == "textarea") {
editorElement.addEventListener("mousedown", function (e) {
e.stopPropagation();
});
}
}
filterElement.appendChild(editorElement);
column.contentElement.appendChild(filterElement);
if (!reinitialize) {
self.headerFilterColumns.push(column);
}
}
} else {
console.warn("Filter Error - Cannot add header filter, column has no field set:", column.definition.title);
}
};
//hide all header filter elements (used to ensure correct column widths in "fitData" layout mode)
Filter.prototype.hideHeaderFilterElements = function () {
this.headerFilterColumns.forEach(function (column) {
if (column.modules.filter && column.modules.filter.headerElement) {
column.modules.filter.headerElement.style.display = 'none';
}
});
};
//show all header filter elements (used to ensure correct column widths in "fitData" layout mode)
Filter.prototype.showHeaderFilterElements = function () {
this.headerFilterColumns.forEach(function (column) {
if (column.modules.filter && column.modules.filter.headerElement) {
column.modules.filter.headerElement.style.display = '';
}
});
};
//programatically set focus of header filter
Filter.prototype.setHeaderFilterFocus = function (column) {
if (column.modules.filter && column.modules.filter.headerElement) {
column.modules.filter.headerElement.focus();
} else {
console.warn("Column Filter Focus Error - No header filter set on column:", column.getField());
}
};
//programmatically get value of header filter
Filter.prototype.getHeaderFilterValue = function (column) {
if (column.modules.filter && column.modules.filter.headerElement) {
return column.modules.filter.headerElement.value;
} else {
console.warn("Column Filter Error - No header filter set on column:", column.getField());
}
};
//programatically set value of header filter
Filter.prototype.setHeaderFilterValue = function (column, value) {
if (column) {
if (column.modules.filter && column.modules.filter.headerElement) {
this.generateHeaderFilterElement(column, value, true);
column.modules.filter.success(value);
} else {
console.warn("Column Filter Error - No header filter set on column:", column.getField());
}
}
};
Filter.prototype.reloadHeaderFilter = function (column) {
if (column) {
if (column.modules.filter && column.modules.filter.headerElement) {
this.generateHeaderFilterElement(column, column.modules.filter.value, true);
} else {
console.warn("Column Filter Error - No header filter set on column:", column.getField());
}
}
};
//check if the filters has changed since last use
Filter.prototype.hasChanged = function () {
var changed = this.changed;
this.changed = false;
return changed;
};
//set standard filters
Filter.prototype.setFilter = function (field, type, value) {
var self = this;
self.filterList = [];
if (!Array.isArray(field)) {
field = [{ field: field, type: type, value: value }];
}
self.addFilter(field);
};
//add filter to array
Filter.prototype.addFilter = function (field, type, value) {
var self = this;
if (!Array.isArray(field)) {
field = [{ field: field, type: type, value: value }];
}
field.forEach(function (filter) {
filter = self.findFilter(filter);
if (filter) {
self.filterList.push(filter);
self.changed = true;
}
});
if (this.table.options.persistence && this.table.modExists("persistence", true) && this.table.modules.persistence.config.filter) {
this.table.modules.persistence.save("filter");
}
};
Filter.prototype.findFilter = function (filter) {
var self = this,
column;
if (Array.isArray(filter)) {
return this.findSubFilters(filter);
}
var filterFunc = false;
if (typeof filter.field == "function") {
filterFunc = function filterFunc(data) {
return filter.field(data, filter.type || {}); // pass params to custom filter function
};
} else {
if (self.filters[filter.type]) {
column = self.table.columnManager.getColumnByField(filter.field);
if (column) {
filterFunc = function filterFunc(data) {
return self.filters[filter.type](filter.value, column.getFieldValue(data));
};
} else {
filterFunc = function filterFunc(data) {
return self.filters[filter.type](filter.value, data[filter.field]);
};
}
} else {
console.warn("Filter Error - No such filter type found, ignoring: ", filter.type);
}
}
filter.func = filterFunc;
return filter.func ? filter : false;
};
Filter.prototype.findSubFilters = function (filters) {
var self = this,
output = [];
filters.forEach(function (filter) {
filter = self.findFilter(filter);
if (filter) {
output.push(filter);
}
});
return output.length ? output : false;
};
//get all filters
Filter.prototype.getFilters = function (all, ajax) {
var output = [];
if (all) {
output = this.getHeaderFilters();
}
if (ajax) {
output.forEach(function (item) {
if (typeof item.type == "function") {
item.type = "function";
}
});
}
output = output.concat(this.filtersToArray(this.filterList, ajax));
return output;
};
//filter to Object
Filter.prototype.filtersToArray = function (filterList, ajax) {
var _this2 = this;
var output = [];
filterList.forEach(function (filter) {
var item;
if (Array.isArray(filter)) {
output.push(_this2.filtersToArray(filter, ajax));
} else {
item = { field: filter.field, type: filter.type, value: filter.value };
if (ajax) {
if (typeof item.type == "function") {
item.type = "function";
}
}
output.push(item);
}
});
return output;
};
//get all filters
Filter.prototype.getHeaderFilters = function () {
var self = this,
output = [];
for (var key in this.headerFilters) {
output.push({ field: key, type: this.headerFilters[key].type, value: this.headerFilters[key].value });
}
return output;
};
//remove filter from array
Filter.prototype.removeFilter = function (field, type, value) {
var self = this;
if (!Array.isArray(field)) {
field = [{ field: field, type: type, value: value }];
}
field.forEach(function (filter) {
var index = -1;
if (_typeof(filter.field) == "object") {
index = self.filterList.findIndex(function (element) {
return filter === element;
});
} else {
index = self.filterList.findIndex(function (element) {
return filter.field === element.field && filter.type === element.type && filter.value === element.value;
});
}
if (index > -1) {
self.filterList.splice(index, 1);
self.changed = true;
} else {
console.warn("Filter Error - No matching filter type found, ignoring: ", filter.type);
}
});
if (this.table.options.persistence && this.table.modExists("persistence", true) && this.table.modules.persistence.config.filter) {
this.table.modules.persistence.save("filter");
}
};
//clear filters
Filter.prototype.clearFilter = function (all) {
this.filterList = [];
if (all) {
this.clearHeaderFilter();
}
this.changed = true;
if (this.table.options.persistence && this.table.modExists("persistence", true) && this.table.modules.persistence.config.filter) {
this.table.modules.persistence.save("filter");
}
};
//clear header filters
Filter.prototype.clearHeaderFilter = function () {
var self = this;
this.headerFilters = {};
self.prevHeaderFilterChangeCheck = "{}";
this.headerFilterColumns.forEach(function (column) {
column.modules.filter.value = null;
column.modules.filter.prevSuccess = undefined;
self.reloadHeaderFilter(column);
});
this.changed = true;
};
//search data and return matching rows
Filter.prototype.search = function (searchType, field, type, value) {
var self = this,
activeRows = [],
filterList = [];
if (!Array.isArray(field)) {
field = [{ field: field, type: type, value: value }];
}
field.forEach(function (filter) {
filter = self.findFilter(filter);
if (filter) {
filterList.push(filter);
}
});
this.table.rowManager.rows.forEach(function (row) {
var match = true;
filterList.forEach(function (filter) {
if (!self.filterRecurse(filter, row.getData())) {
match = false;
}
});
if (match) {
activeRows.push(searchType === "data" ? row.getData("data") : row.getComponent());
}
});
return activeRows;
};
//filter row array
Filter.prototype.filter = function (rowList, filters) {
var self = this,
activeRows = [],
activeRowComponents = [];
if (self.table.options.dataFiltering) {
self.table.options.dataFiltering.call(self.table, self.getFilters());
}
if (!self.table.options.ajaxFiltering && (self.filterList.length || Object.keys(self.headerFilters).length)) {
rowList.forEach(function (row) {
if (self.filterRow(row)) {
activeRows.push(row);
}
});
} else {
activeRows = rowList.slice(0);
}
if (self.table.options.dataFiltered) {
activeRows.forEach(function (row) {
activeRowComponents.push(row.getComponent());
});
self.table.options.dataFiltered.call(self.table, self.getFilters(), activeRowComponents);
}
return activeRows;
};
//filter individual row
Filter.prototype.filterRow = function (row, filters) {
var self = this,
match = true,
data = row.getData();
self.filterList.forEach(function (filter) {
if (!self.filterRecurse(filter, data)) {
match = false;
}
});
for (var field in self.headerFilters) {
if (!self.headerFilters[field].func(data)) {
match = false;
}
}
return match;
};
Filter.prototype.filterRecurse = function (filter, data) {
var self = this,
match = false;
if (Array.isArray(filter)) {
filter.forEach(function (subFilter) {
if (self.filterRecurse(subFilter, data)) {
match = true;
}
});
} else {
match = filter.func(data);
}
return match;
};
//list of available filters
Filter.prototype.filters = {
//equal to
"=": function _(filterVal, rowVal, rowData, filterParams) {
return rowVal == filterVal ? true : false;
},
//less than
"<": function _(filterVal, rowVal, rowData, filterParams) {
return rowVal < filterVal ? true : false;
},
//less than or equal to
"<=": function _(filterVal, rowVal, rowData, filterParams) {
return rowVal <= filterVal ? true : false;
},
//greater than
">": function _(filterVal, rowVal, rowData, filterParams) {
return rowVal > filterVal ? true : false;
},
//greater than or equal to
">=": function _(filterVal, rowVal, rowData, filterParams) {
return rowVal >= filterVal ? true : false;
},
//not equal to
"!=": function _(filterVal, rowVal, rowData, filterParams) {
return rowVal != filterVal ? true : false;
},
"regex": function regex(filterVal, rowVal, rowData, filterParams) {
if (typeof filterVal == "string") {
filterVal = new RegExp(filterVal);
}
return filterVal.test(rowVal);
},
//contains the string
"like": function like(filterVal, rowVal, rowData, filterParams) {
if (filterVal === null || typeof filterVal === "undefined") {
return rowVal === filterVal ? true : false;
} else {
if (typeof rowVal !== 'undefined' && rowVal !== null) {
return String(rowVal).toLowerCase().indexOf(filterVal.toLowerCase()) > -1;
} else {
return false;
}
}
},
//in array
"in": function _in(filterVal, rowVal, rowData, filterParams) {
if (Array.isArray(filterVal)) {
return filterVal.indexOf(rowVal) > -1;
} else {
console.warn("Filter Error - filter value is not an array:", filterVal);
return false;
}
}
};
Tabulator.prototype.registerModule("filter", Filter); | {
"content_hash": "7b3796efbac7f5c39027ba6c84dbf3de",
"timestamp": "",
"source": "github",
"line_count": 766,
"max_line_length": 269,
"avg_line_length": 28.0065274151436,
"alnum_prop": 0.6750104880436303,
"repo_name": "cdnjs/cdnjs",
"id": "a4d6d9945dba0b4fa359f46b0ddad89b1b1d2c60",
"size": "21453",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/tabulator/4.6.2/js/modules/filter.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
def func_1(apple, my_list):
if apple<10:
# Do something
my_list.append(apple)
return my_list[1:]
def func_2(spongebob, squarepants):
"""A less messy function"""
for char in spongebob:
if char in squarepants:
return char
unused=1
return None
| {
"content_hash": "f00177f73ab6b3b3555738296fc8c0f4",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 35,
"avg_line_length": 25.166666666666668,
"alnum_prop": 0.5927152317880795,
"repo_name": "edx/diff-cover",
"id": "08991bc7eede1d7399bda54bfa86a0b4adce1ea6",
"size": "302",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "diff_cover/tests/fixtures/violations_test_file.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "355"
},
{
"name": "Python",
"bytes": "178159"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
tools:context="com.example.administrator.bookcrossingapp.activity.ExchangeBookDetailsActivity">
<ImageView
android:layout_width="140dp"
android:layout_height="194dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:background="@drawable/book_yinying"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.038"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022" />
<ImageView
android:id="@+id/img_pic"
android:layout_width="137dp"
android:layout_height="191dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.038"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022"
app:srcCompat="@drawable/book_image" />
<ImageView
android:id="@+id/img_icon"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.786"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.041" />
<TextView
android:id="@+id/tv_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
android:textColor="#000"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.772"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.187" />
<TextView
android:id="@+id/tv_sharelist"
android:layout_width="90dp"
android:layout_height="32dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="@drawable/detail_button"
android:gravity="center"
android:text="ShareList"
android:textColor="#fff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.618"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.25" />
<TextView
android:id="@+id/tv_bookdetail_chat"
android:layout_width="90dp"
android:layout_height="32dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="@drawable/detail_button"
android:gravity="center"
android:text="Chat"
android:textColor="#fff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.618"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.317" />
<TextView
android:id="@+id/tv_wantlist"
android:layout_width="90dp"
android:layout_height="32dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="@drawable/detail_button"
android:gravity="center"
android:text="WantList"
android:textColor="#fff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.97"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.25" />
<TextView
android:id="@+id/tv_bookdetail_want"
android:layout_width="90dp"
android:layout_height="32dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="@drawable/detail_button"
android:gravity="center"
android:text="Want"
android:textColor="#fff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.97"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.317" />
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="0dp"
android:layout_height="338dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.963">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_weight="0"
android:elevation="1dp"
android:text=" BookName :"
android:textColor="@android:color/black"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_bookname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView"
android:textColor="#222222"
android:textSize="16sp"
tools:text="666666666666666666666666666666666666666666" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_weight="0"
android:text=" Author :"
android:textColor="@android:color/black"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_author"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:elevation="1dp"
android:text="TextView"
android:textColor="#222222"
android:textSize="16sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_weight="0"
android:elevation="1dp"
android:text=" Press :"
android:textColor="@android:color/black"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_press"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:elevation="1dp"
android:text="TextView"
android:textColor="#222222"
android:textSize="16sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_weight="0"
android:elevation="1dp"
android:text=" Classify :"
android:textColor="@android:color/black"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_classify"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:elevation="1dp"
android:text=""
android:textColor="#222222"
android:textSize="16sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:elevation="0dp"
android:text="Recommend :"
android:textColor="@android:color/black"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_recommend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:elevation="1dp"
android:text="TextView"
android:textColor="#222222"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
| {
"content_hash": "a7169606a7ad87ab577a2e6590f9aa57",
"timestamp": "",
"source": "github",
"line_count": 330,
"max_line_length": 103,
"avg_line_length": 38.56969696969697,
"alnum_prop": 0.6052011313639221,
"repo_name": "BookCrossingTeam/BookCrossingAPP",
"id": "59221d21f341d2e5bd1c7dc03f1788679f2115bc",
"size": "12728",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/activity_exchange_book_details.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "377795"
}
],
"symlink_target": ""
} |
package dao
import (
"context"
"encoding/base64"
"encoding/json"
"io"
"os"
"strings"
"go-common/library/ecode"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
)
// authConfig get Auth Config.
func (d *Dao) authConfig() (authStr string, err error) {
authConfig := types.AuthConfig{
Username: d.c.BiliHub.Username,
Password: d.c.BiliHub.Password,
ServerAddress: d.c.BiliHub.HostName,
}
var encodedJSON []byte
if encodedJSON, err = json.Marshal(authConfig); err != nil {
return
}
authStr = base64.URLEncoding.EncodeToString(encodedJSON)
return
}
// ImagePull Image Pull.
func (d *Dao) ImagePull(imageName string) (err error) {
var (
out io.ReadCloser
authStr string
)
if authStr, err = d.authConfig(); err != nil {
return
}
if out, err = d.dockerClient.ImagePull(context.TODO(), imageName, types.ImagePullOptions{RegistryAuth: authStr}); err != nil {
err = ecode.MerlinImagePullErr
return
}
defer out.Close()
io.Copy(os.Stdout, out)
return
}
// ImagePush Image Push.
func (d *Dao) ImagePush(imageName string) (err error) {
var (
out io.ReadCloser
authStr string
)
if authStr, err = d.authConfig(); err != nil {
return
}
if out, err = d.dockerClient.ImagePush(context.TODO(), imageName, types.ImagePushOptions{RegistryAuth: authStr}); err != nil {
err = ecode.MerlinImagePushErr
return
}
defer out.Close()
io.Copy(os.Stdout, out)
return
}
// ImageTag Image Tag.
func (d *Dao) ImageTag(imageSrcName, imageTagName string) (err error) {
err = d.dockerClient.ImageTag(context.TODO(), imageSrcName, imageTagName)
return
}
// ImageRemove Image Remove.
func (d *Dao) ImageRemove(imageID string) (err error) {
_, err = d.dockerClient.ImageRemove(context.TODO(), imageID, types.ImageRemoveOptions{Force: true, PruneChildren: true})
return
}
// ImageGetID Image Get ID.
func (d *Dao) ImageGetID(imageName string) (imageID string, err error) {
var images []types.ImageSummary
if images, err = d.dockerClient.ImageList(context.TODO(), types.ImageListOptions{}); err != nil {
return
}
for _, image := range images {
for _, tag := range image.RepoTags {
if tag == imageName {
imageID = image.ID
return
}
}
}
return
}
// ImageGetAll Image Get All.
func (d *Dao) ImageGetAll() (imageNames []string, err error) {
var images []types.ImageSummary
if images, err = d.dockerClient.ImageList(context.Background(), types.ImageListOptions{Filters: filters.NewArgs()}); err != nil {
return
}
for _, image := range images {
for _, tag := range image.RepoTags {
if strings.Contains(tag, d.c.BiliHub.HostName) {
imageNames = append(imageNames, tag)
}
}
}
return
}
| {
"content_hash": "127856b69106f97bc7dc317e2cf1a87d",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 130,
"avg_line_length": 21.943548387096776,
"alnum_prop": 0.6898199191473723,
"repo_name": "LQJJ/demo",
"id": "4ceee4daa64483f6e7a56ceb9f709861f938e7e6",
"size": "2721",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "126-go-common-master/app/admin/ep/merlin/dao/docker.go",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5910716"
},
{
"name": "C++",
"bytes": "113072"
},
{
"name": "CSS",
"bytes": "10791"
},
{
"name": "Dockerfile",
"bytes": "934"
},
{
"name": "Go",
"bytes": "40121403"
},
{
"name": "Groovy",
"bytes": "347"
},
{
"name": "HTML",
"bytes": "359263"
},
{
"name": "JavaScript",
"bytes": "545384"
},
{
"name": "Makefile",
"bytes": "6671"
},
{
"name": "Mathematica",
"bytes": "14565"
},
{
"name": "Objective-C",
"bytes": "14900720"
},
{
"name": "Objective-C++",
"bytes": "20070"
},
{
"name": "PureBasic",
"bytes": "4152"
},
{
"name": "Python",
"bytes": "4490569"
},
{
"name": "Ruby",
"bytes": "44850"
},
{
"name": "Shell",
"bytes": "33251"
},
{
"name": "Swift",
"bytes": "463286"
},
{
"name": "TSQL",
"bytes": "108861"
}
],
"symlink_target": ""
} |
dojo.require("dojox.data.JsonRestStore");
//Clear put/delete records file, so we can always start with a brand new store.
dojo.xhrPost({url: 'test_tree_jsonRestStore.php', sync: true});
var store = new dojox.data.JsonRestStore({
idAttribute: 'id',
target: 'test_tree_jsonRestStore.php'
});
store.fetch({
start: 0,
onComplete: function(items){
var children = store.getValues(items[3], 'children').slice();
console.log('children: ', children);
children = dojo.filter(children, function(child){
return false;
});
store.setValues(items[3], 'children', children);
store.setValues(items[4], 'children', children);
store.save({
onComplete: function(){
store.fetch({
query: {parentId: 'item-4-2'},
start: 0,
onComplete: function(items){
console.log('lazy tree:', items);
}
});
}
});
}
});
| {
"content_hash": "aa64e9a4a39214d139330ee3a1240883",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 79,
"avg_line_length": 24.285714285714285,
"alnum_prop": 0.6529411764705882,
"repo_name": "algogr/Site",
"id": "9844c698682c0f2ace3de6a4d12f7141f55a213a",
"size": "850",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "web/js/dojo/gridx/tests/support/stores/test_tree_jsonRestStore.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "626444"
},
{
"name": "JavaScript",
"bytes": "19615915"
},
{
"name": "PHP",
"bytes": "230491"
},
{
"name": "Ruby",
"bytes": "2179"
},
{
"name": "Shell",
"bytes": "1599"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
NUB Generator [implicit canonical]
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "1eca86df386af6d65b7078c21ddca6ee",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 34,
"avg_line_length": 9.923076923076923,
"alnum_prop": 0.6976744186046512,
"repo_name": "mdoering/backbone",
"id": "48b1c88466224000189478ee3bfd2b0882406c58",
"size": "160",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/incertae sedis/Homalopom/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
echo "------------- Start to build ContainerFS -------------"
if [ ! -d "./build" ]; then
mkdir ./build
else
rm -rf ./build/*
fi
for dir in ./proto/mp ./proto/dp ./proto/kvp ./proto/vp
do
pushd $dir
make
popd
done
cd ./cmd
for dir in `ls`
do
pushd $dir
go build -ldflags "-X github.com/tiglabs/containerfs/utils.Release=`git tag|head -n 1` -X github.com/tiglabs/containerfs/utils.Build=`git rev-parse HEAD`" -o cfs-$dir
cp cfs-$dir ../../build
rm -rf cfs-$dir
popd
done
echo "------------- build end -------------"
| {
"content_hash": "eee32607abe80e7fd190ce2b66ef0572",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 168,
"avg_line_length": 20.807692307692307,
"alnum_prop": 0.5859519408502772,
"repo_name": "ipdcode/containerfs",
"id": "0058d5a0dca9f2e9b25203380001a57fe8f345a7",
"size": "553",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "make.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2539"
},
{
"name": "CSS",
"bytes": "1817"
},
{
"name": "Go",
"bytes": "45773131"
},
{
"name": "HTML",
"bytes": "9035816"
},
{
"name": "Java",
"bytes": "11693"
},
{
"name": "JavaScript",
"bytes": "5858"
},
{
"name": "Makefile",
"bytes": "87128"
},
{
"name": "PHP",
"bytes": "932"
},
{
"name": "PowerShell",
"bytes": "4261"
},
{
"name": "Python",
"bytes": "1453551"
},
{
"name": "Roff",
"bytes": "16008"
},
{
"name": "Ruby",
"bytes": "11898"
},
{
"name": "SaltStack",
"bytes": "55799"
},
{
"name": "Shell",
"bytes": "1655859"
}
],
"symlink_target": ""
} |
<?php
namespace SleepingOwl\Admin\Form\Element;
use Illuminate\Database\Eloquent\Model;
use Request;
use Illuminate\Database\Eloquent\Collection;
class MultiSelect extends Select
{
/**
* @var bool
*/
protected $taggable = false;
/**
* @var bool
*/
protected $deleteRelatedItem = false;
/**
* @return string
*/
public function getName()
{
return $this->name.'[]';
}
/**
* @return array
*/
public function getValue()
{
$value = parent::getValue();
if ($value instanceof Collection && $value->count() > 0) {
$value = $value->pluck($value->first()->getKeyName())->all();
}
if ($value instanceof Collection) {
$value = $value->toArray();
}
return $value;
}
/**
* @return bool
*/
public function isTaggable()
{
return $this->taggable;
}
/**
* @return $this
*/
public function taggable()
{
$this->taggable = true;
return $this;
}
/**
* @return bool
*/
public function isDeleteRelatedItem()
{
return $this->deleteRelatedItem;
}
/**
* @return $this
*/
public function deleteRelatedItem()
{
$this->deleteRelatedItem = true;
return $this;
}
/**
* @return array
*/
public function toArray()
{
$attributes = [
'id' => $this->getName(),
'class' => 'form-control input-select',
'multiple',
];
if ($this->isReadonly()) {
$attributes['disabled'] = 'disabled';
}
if ($this->isTaggable()) {
$attributes['class'] .= ' input-taggable';
}
return [
'tagable' => $this->isTaggable(),
'attributes' => $attributes,
] + parent::toArray();
}
public function save()
{
if (is_null($this->getModelForOptions())) {
parent::save();
}
}
public function afterSave()
{
if (is_null($this->getModelForOptions())) {
return;
}
$attribute = $this->getAttribute();
if (is_null(Request::input($this->getPath()))) {
$values = [];
} else {
$values = $this->getValue();
}
$relation = $this->getModel()->{$attribute}();
if ($relation instanceof \Illuminate\Database\Eloquent\Relations\BelongsToMany) {
foreach ($values as $i => $value) {
if (! array_key_exists($value, $this->getOptions()) and $this->isTaggable()) {
$model = clone $this->getModelForOptions();
$model->{$this->getDisplay()} = $value;
$model->save();
$values[$i] = $model->getKey();
}
}
$relation->sync($values);
} elseif ($relation instanceof \Illuminate\Database\Eloquent\Relations\HasMany) {
foreach ($relation->get() as $item) {
if (! in_array($item->getKey(), $values)) {
if ($this->isDeleteRelatedItem()) {
$item->delete();
} else {
$item->{$relation->getPlainForeignKey()} = null;
$item->save();
}
}
}
foreach ($values as $i => $value) {
/** @var Model $model */
$model = clone $this->getModelForOptions();
$item = $model->find($value);
if (is_null($item)) {
if (! $this->isTaggable()) {
continue;
}
$model->{$this->getDisplay()} = $value;
$item = $model;
}
$relation->save($item);
}
}
}
}
| {
"content_hash": "4dc7a634c0f09fe0fabb3bdb89501e3d",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 94,
"avg_line_length": 23.069767441860463,
"alnum_prop": 0.44783266129032256,
"repo_name": "Malezha/SleepingOwlAdmin",
"id": "7317468140ecfe2d488151a3da67a17c6aaeab94",
"size": "3968",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "src/Form/Element/MultiSelect.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "222570"
},
{
"name": "HTML",
"bytes": "33092"
},
{
"name": "JavaScript",
"bytes": "1271261"
},
{
"name": "PHP",
"bytes": "409755"
}
],
"symlink_target": ""
} |
package org.chocosolver.graphsolver.cstrs.cost.trees;
import org.chocosolver.graphsolver.variables.GraphEventType;
import org.chocosolver.graphsolver.variables.UndirectedGraphVar;
import org.chocosolver.graphsolver.variables.delta.GraphDeltaMonitor;
import org.chocosolver.memory.IEnvironment;
import org.chocosolver.memory.IStateInt;
import org.chocosolver.solver.constraints.Propagator;
import org.chocosolver.solver.constraints.PropagatorPriority;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.variables.IntVar;
import org.chocosolver.util.ESat;
import org.chocosolver.util.objects.setDataStructures.ISet;
import org.chocosolver.util.procedure.PairProcedure;
/**
* Compute the cost of the graph by summing edge costs
* - For minimization problem
*/
public class PropTreeCostSimple extends Propagator<UndirectedGraphVar> {
//***********************************************************************************
// VARIABLES
//***********************************************************************************
protected UndirectedGraphVar g;
private GraphDeltaMonitor gdm;
private PairProcedure edgeEnf, edgeRem;
protected int n;
protected IntVar sum;
protected int[][] distMatrix;
private IStateInt minSum, maxSum;
//***********************************************************************************
// CONSTRUCTORS
//***********************************************************************************
public PropTreeCostSimple(UndirectedGraphVar graph, IntVar obj, int[][] costMatrix) {
super(new UndirectedGraphVar[]{graph}, PropagatorPriority.LINEAR, true);
g = graph;
sum = obj;
n = g.getNbMaxNodes();
distMatrix = costMatrix;
IEnvironment environment = graph.getEnvironment();
minSum = environment.makeInt(0);
maxSum = environment.makeInt(0);
gdm = g.monitorDelta(this);
edgeEnf = (i, j) -> minSum.add(distMatrix[i][j]);
edgeRem = (i, j) -> maxSum.add(-distMatrix[i][j]);
}
//***********************************************************************************
// METHODS
//***********************************************************************************
@Override
public void propagate(int evtmask) throws ContradictionException {
int min = 0;
int max = 0;
for (int i = 0; i < n; i++) {
ISet nei = g.getPotNeighOf(i);
for (int j : nei) {
if (i <= j) {
max += distMatrix[i][j];
if (g.getMandNeighOf(i).contains(j)) {
min += distMatrix[i][j];
}
}
}
}
gdm.unfreeze();
minSum.set(min);
maxSum.set(max);
sum.updateLowerBound(min, this);
sum.updateUpperBound(max, this);
}
@Override
public void propagate(int idxVarInProp, int mask) throws ContradictionException {
gdm.freeze();
gdm.forEachArc(edgeEnf, GraphEventType.ADD_ARC);
gdm.forEachArc(edgeRem, GraphEventType.REMOVE_ARC);
gdm.unfreeze();
sum.updateLowerBound(minSum.get(), this);
sum.updateUpperBound(maxSum.get(), this);
}
@Override
public int getPropagationConditions(int vIdx) {
return GraphEventType.REMOVE_ARC.getMask() + GraphEventType.ADD_ARC.getMask();
}
@Override
public ESat isEntailed() {
int min = 0;
int max = 0;
for (int i = 0; i < n; i++) {
ISet nei = g.getPotNeighOf(i);
for (int j : nei) {
if (i <= j) {
max += distMatrix[i][j];
if (g.getMandNeighOf(i).contains(j)) {
min += distMatrix[i][j];
}
}
}
}
if (min > sum.getUB() || max < sum.getLB()) {
return ESat.FALSE;
}
if (min == max) {
return ESat.TRUE;
} else {
return ESat.UNDEFINED;
}
}
}
| {
"content_hash": "8335ddcd91b2a424acf3146649c96e3a",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 86,
"avg_line_length": 30.016806722689076,
"alnum_prop": 0.601063829787234,
"repo_name": "chocoteam/choco-graph",
"id": "5105ef1dc2952515faff5ac666cb13f9783850cb",
"size": "5178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/chocosolver/graphsolver/cstrs/cost/trees/PropTreeCostSimple.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "662938"
}
],
"symlink_target": ""
} |
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<mvc:annotation-driven></mvc:annotation-driven>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.springapp, com.simon.declare"/>
<context:property-placeholder location="classpath:/jdbc.properties"></context:property-placeholder>
<mvc:resources mapping="/js/**" location="WEB-INF/resources/js/"></mvc:resources>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"></property>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"></entry>
<entry key="xml" value="application/xml"></entry>
<entry key="htm" value="text/html"></entry>
</map>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"></bean>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<property name="marshaller">
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true"/>
</bean>
</property>
</bean>
</list>
</property>
<property name="ignoreAcceptHeader" value="true"></property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClass" value="${jdbc.driverClass}" />
<property name="minPoolSize" value="3" />
<property name="maxPoolSize" value="10" />
<property name="maxIdleTime" value="0" />
<property name="acquireIncrement" value="3" />
<property name="maxStatements" value="1000" />
<property name="initialPoolSize" value="3" />
<property name="idleConnectionTestPeriod" value="30" />
<property name="acquireRetryAttempts" value="30" />
<property name="breakAfterAcquireFailure" value="true" />
<property name="testConnectionOnCheckout" value="false" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:/hibernate.cfg.xml"></property>
<property name="packagesToScan">
<list>
<value>com.springapp.entity</value>
</list>
</property>
</bean>
<!--<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"></bean>-->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config expose-proxy="true">
<!-- 只对业务逻辑层实施事务 -->
<aop:pointcut id="txPointcut" expression="execution(* com.springapp.service.*.*(..))" />
<!-- Advisor定义,切入点和通知分别为txPointcut、txAdvice -->
<aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/>
</aop:config>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans> | {
"content_hash": "9645572937ccf24ab90eaddc8cd37519",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 108,
"avg_line_length": 48.59803921568628,
"alnum_prop": 0.6413153116804519,
"repo_name": "shihaoking/SpringMvc",
"id": "58db53cabefd6ff7bd81d8d80651db39d38122ea",
"size": "5005",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "target/SpringMvc/WEB-INF/mvc-dispatcher-servlet.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "14271"
},
{
"name": "JavaScript",
"bytes": "168"
},
{
"name": "Shell",
"bytes": "169"
}
],
"symlink_target": ""
} |
<!-- Extend the layout and add our own stylesheet -->
{% extends "!layout.html" %}
{% block extrahead %}
<link href="{{ pathto("_static/css/remotestorage.css", True) }}" rel="stylesheet" type="text/css">
{% endblock %}
| {
"content_hash": "ab448ad52b6ac5c99bb0bdb239dd54f2",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 100,
"avg_line_length": 44.2,
"alnum_prop": 0.6470588235294118,
"repo_name": "theWebalyst/remotestorage.js",
"id": "17e689483499735051b0e0705b2f1f2a3376664b",
"size": "221",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/_templates/layout.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "528825"
},
{
"name": "Shell",
"bytes": "404"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:camel="http://camel.apache.org/schema/spring"
xmlns:hz="http://www.hazelcast.com/schema/spring"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring-2.15.2.xsd
http://www.hazelcast.com/schema/spring http://www.hazelcast.com/schema/spring/hazelcast-spring-3.0.xsd">
<hz:hazelcast id="hazelcastInstance">
<hz:config>
<hz:group name="${hazelcast.group.name}" password="${hazelcast.group.password}" />
<hz:network port="${hazelcast.network.port}" public-address="#{'${hazelcast.network.publicAddress}'.isEmpty() ? null : '${hazelcast.network.publicAddress}'}">
<hz:join>
<hz:multicast enabled="${hazelcast.network.join.multicast.enabled}" multicast-group="${hazelcast.network.join.multicast.group}" multicast-port="${hazelcast.network.join.multicast.port}" />
<hz:tcp-ip enabled="#{!'${hazelcast.network.join.tcp_ip.members}'.isEmpty()}">
<hz:members>#{'${hazelcast.network.join.tcp_ip.members}'.isEmpty() ? '127.0.0.1' : '${hazelcast.network.join.tcp_ip.members}'}</hz:members>
</hz:tcp-ip>
</hz:join>
</hz:network>
</hz:config>
</hz:hazelcast>
<bean id="multipartMessageIdempotentRepository" class="org.apache.camel.processor.idempotent.hazelcast.HazelcastIdempotentRepository">
<constructor-arg ref="hazelcastInstance" />
<constructor-arg value="processed-multipart-messages" />
</bean>
<bean id="distributionEnvelopeIdempotentRepository" class="org.apache.camel.processor.idempotent.hazelcast.HazelcastIdempotentRepository">
<constructor-arg ref="hazelcastInstance" />
<constructor-arg value="processed-distribution-envelopes" />
</bean>
</beans>
| {
"content_hash": "ab1d769fab4652d41bd747919b6db8e2",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 193,
"avg_line_length": 60,
"alnum_prop": 0.7181818181818181,
"repo_name": "nhs-ciao/ciao-transport-spine",
"id": "d1757895ff707ca119127fed376ec1eb63992b58",
"size": "1980",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ciao-transport-spine/src/main/resources/META-INF/spring/repositories/hazelcast.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "14343"
},
{
"name": "Java",
"bytes": "491252"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.