text
stringlengths
2
1.04M
meta
dict
type IEnumerable<T> = Ix.Enumerable<T>; namespace Ix.DOM { type IArrayLike<T> = { [index: number]: T, length: number }; namespace Util { export function toEnumerable<T>(arrayLike: IArrayLike<T>): IEnumerable<T> { return Ix.Enumerable.fromArray<T>(arrayLike as T[]); } } export const addClass = <T extends Element>(className: string) => (element: T) => element.classList.add(className); export const removeClass = <T extends Element>(className: string) => (element: T) => element.classList.remove(className); export const toggleClass = <T extends Element>(className: string) => (element: T) => element.classList.toggle(className); export const hasClass = <T extends Element>(className: string) => (element: T) => element.classList.contains(className); export const hasAttr = (attributeName: string) => (element: Element) => element.hasAttribute(attributeName); export const hasDataAttr = (attributeName: string) => hasAttr(`data-${attributeName}`); export function prop<T, K extends keyof T>(element: T, attributeName: K, attributeValue: T[K]): void export function prop<T, K extends keyof T>(element: T, attributeName: K): T[K] export function prop<T, K extends keyof T>(element: T, attributeName: K, attributeValue?: T[K]): void | T[K] { if (attributeValue) { return element[attributeName] = attributeValue; } return element[attributeName]; } export function attr<T extends string>(attributeName: string): (element: Element) => T | null export function attr(attributeName: string, attributeValue: string | number | boolean): (element: Element) => void export function attr<T extends string>(attributeName: string, attributeValue?: string | number | boolean): (element: Element) => void { if (attributeValue) { return (element: Element) => element.setAttribute(attributeName, attributeValue.toString()); } return (element: Element) => element.getAttribute(attributeName) as T | null; } export function attrOrThrow<T extends string>(attributeName: string) { return (element: Element) => { if (element.hasAttribute(attributeName)) { return element.getAttribute(attributeName) as T; } throw new Error(`Attribute ${attributeName} does not exist on ${element}`); }; } export const attrAsNumber = <T extends number>(attributeName: string) => (element: Element) => parseInt(attrOrThrow(attributeName)(element)) as T; export const attrAsBool = (attributeName: string) => (element: Element) => attrOrThrow(attributeName)(element).toLowerCase() == "true"; export const data = <T extends string>(dataAttributeName: string) => attrOrThrow<T>(`data-${dataAttributeName}`); export const dataAttrAsNumber = <T extends number>(dataAttributeName: string) => attrAsNumber<T>(`data-${dataAttributeName}`); export const dataAttrAsBool = (dataAttributeName: string) => attrAsBool(`data-${dataAttributeName}`); export function style<T extends SVGElement | HTMLElement>(property: keyof CSSStyleDeclaration, value: string | number): (element: T) => T export function style<T extends SVGElement | HTMLElement>(property: CSSProperties): (element: T) => T export function style<T extends SVGElement | HTMLElement>(property: (keyof CSSStyleDeclaration) | CSSProperties, value?: string | number) { let props = property as string | CSSProperties; return function (element: T) { if (typeof props === "string") { (element as HTMLElement).style[props as any] = value!.toString(); } else { for (let prop in props) { // Cast to HTMLElement as SVGElement has style property as well just not standard (element as HTMLElement).style[prop as any] = props[prop].toString(); } } return element; } } export const parents = (element: Node) => Ix.Enumerable.create(() => Ix.Enumerator.create( () => (element = element.parentNode as Node) !== null, () => element, () => { } )); export const setTextContent = <T extends HTMLElement | SVGElement>(element: T) => (text: string) => element.textContent = text; //TODO XSS.js export function setInnerHtml<T extends HTMLElement | SVGElement>(element: T) { return function (html: string | Element | Element[] | IEnumerable<Element>) { if (typeof html === 'string') { element.innerHTML = html; } else { while (element.lastChild) { element.removeChild(element.lastChild); } if (html instanceof Ix.Enumerable) { html.forEach(el => element.appendChild(el)); } else if (html instanceof Array) { html.forEach(el => element.appendChild(el)); } else { element.appendChild(html); } } } } export function children<T extends SVGElement|HTMLElement>(element: Element) { return Util.toEnumerable<T>(element.children as IArrayLike<any>); } export const remove = <T extends HTMLElement | SVGElement>(element: T) => (element.parentNode as Node).removeChild(element); export const append = <T extends HTMLElement | SVGElement>(parent: Element) => (element: T) => parent.appendChild(element); export const hide = style('display', 'none'); export const show = style('display', 'block'); export function value<T extends HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(element: T): string export function value<T extends HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(element: T, setValue: string | number): string export function value<T extends HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(element: T, setValue?: string | number): string { return setValue ? element.value = setValue.toString() : element.value; } export function valueAsNumber<T extends HTMLInputElement>(element: T): number export function valueAsNumber<T extends HTMLInputElement>(element: T, setValue: number): number export function valueAsNumber<T extends HTMLInputElement>(element: T, setValue?: number) { return setValue ? element.valueAsNumber = setValue : element.valueAsNumber; } export const elementById = <T extends HTMLElement | SVGElement>(id: string) => document.getElementById(id) as T | null; export function elementByIdOrThrow<T extends HTMLElement | SVGElement>(id: string): T { var element = document.getElementById(id); if (element) { return element as any as T; } throw new Error(`Element #${id} does not exist.`); } export function querySelector<T extends HTMLElement | SVGElement>(selector: string, root: Element | HTMLDocument = document): T | null { return root.querySelector(selector) as any as T; } export function querySelectorOrThrow<T extends HTMLElement | SVGElement>(selector: string, root: Element | HTMLDocument = document): T { var element = root.querySelector(selector); if (element) { return element as any as T; } throw new Error(`No match for ${selector} under ${root}`); } export function querySelectorAllOrThrow<T extends HTMLElement | SVGElement>(selector: string, root: Element | HTMLDocument = document): IEnumerable<T> { const elements = root.querySelectorAll(selector); if (elements.length === 0) { throw new Error(`No match for ${selector} under ${root}`); } return Util.toEnumerable<T>(elements as any); } export function querySelectorAll<T extends HTMLElement | SVGElement>(selector: string, root: Element | HTMLDocument = document): IEnumerable<T> { return Util.toEnumerable<T>(root.querySelectorAll(selector) as any); } export const ready = (func: (...args: any[]) => any) => document.readyState !== 'loading' ? func() : document.addEventListener('DOMContentLoaded', func); }
{ "content_hash": "39706658f82f3f4b1693a5a3b44ae2aa", "timestamp": "", "source": "github", "line_count": 216, "max_line_length": 157, "avg_line_length": 39.879629629629626, "alnum_prop": 0.6258416531228234, "repo_name": "ichpuchtli/Ix-DOM", "id": "f9e45ce4d404da5c7bda3fcd6345b477807d14ab", "size": "8726", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Ix-DOM.ts", "mode": "33188", "license": "mit", "language": [ { "name": "TypeScript", "bytes": "8726" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "81a5067a30eb524f36eac1522cca64e5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "14a98863529fad8a639250c43a83a8a1547d09d9", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Apiaceae/Chymsydia/Chymsydia agasylloides/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package ca.uhn.fhir.jpa.bulk.export.job; import ca.uhn.fhir.jpa.batch.config.BatchConstants; import org.slf4j.Logger; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersInvalidException; import org.springframework.batch.core.JobParametersValidator; import static org.slf4j.LoggerFactory.getLogger; public class GroupIdPresentValidator implements JobParametersValidator { private static final Logger ourLog = getLogger(GroupIdPresentValidator.class); @Override public void validate(JobParameters theJobParameters) throws JobParametersInvalidException { if (theJobParameters == null || theJobParameters.getString(BatchConstants.BULK_EXPORT_GROUP_ID_PARAMETER) == null) { throw new JobParametersInvalidException("Group Bulk Export jobs must have a " + BatchConstants.BULK_EXPORT_GROUP_ID_PARAMETER + " attribute"); } else { ourLog.debug("detected we are running in group mode with group id [{}]", theJobParameters.getString(BatchConstants.BULK_EXPORT_GROUP_ID_PARAMETER)); } } }
{ "content_hash": "cad30a42a6cdb034f1b0fe6b012427e4", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 151, "avg_line_length": 42.08, "alnum_prop": 0.8079847908745247, "repo_name": "jamesagnew/hapi-fhir", "id": "c7ccefeee021973626acb01e1e6beecf58c9148f", "size": "1711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hapi-fhir-storage/src/main/java/ca/uhn/fhir/jpa/bulk/export/job/GroupIdPresentValidator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3861" }, { "name": "CSS", "bytes": "6475" }, { "name": "Dockerfile", "bytes": "261" }, { "name": "GAP", "bytes": "25037" }, { "name": "HTML", "bytes": "246398" }, { "name": "Java", "bytes": "19418495" }, { "name": "JavaScript", "bytes": "32069" }, { "name": "Kotlin", "bytes": "3934" }, { "name": "Ruby", "bytes": "237595" }, { "name": "Shell", "bytes": "46341" } ], "symlink_target": "" }
using System; namespace Zarf.Metadata.DataAnnotations { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class ColumnAttribute : Attribute { public string Name { get; } public ColumnAttribute(string name) { Name = name; } } }
{ "content_hash": "f86091dd5ed1b1de29a32b45d57d4bac", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 95, "avg_line_length": 22.6, "alnum_prop": 0.640117994100295, "repo_name": "HastenS/zarf", "id": "dc0e61df760e744bc8609677a70ece965b3e0aa4", "size": "341", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Zarf/Metadata/DataAnnotations/ColumnAttribute.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "420119" } ], "symlink_target": "" }
package org.apache.carbondata.core.indexstore; /** * Holds the metadata info of the block. */ public class BlockMetaInfo { /** * HDFS locations of a block */ private String[] locationInfo; /** * Size of block */ private long size; public BlockMetaInfo(String[] locationInfo, long size) { this.locationInfo = locationInfo; this.size = size; } public String[] getLocationInfo() { return locationInfo; } public long getSize() { return size; } }
{ "content_hash": "83290cee7f6dceee269e7f9883fce806", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 58, "avg_line_length": 15.181818181818182, "alnum_prop": 0.6447105788423154, "repo_name": "jackylk/incubator-carbondata", "id": "a9e61848d5cb426aa0ec0bad03eb280e444a50ce", "size": "1301", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "core/src/main/java/org/apache/carbondata/core/indexstore/BlockMetaInfo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1639" }, { "name": "C++", "bytes": "110888" }, { "name": "CMake", "bytes": "1555" }, { "name": "Java", "bytes": "7172203" }, { "name": "Python", "bytes": "365111" }, { "name": "Scala", "bytes": "10579226" }, { "name": "Shell", "bytes": "7259" }, { "name": "Smalltalk", "bytes": "86" }, { "name": "Thrift", "bytes": "24309" } ], "symlink_target": "" }
MAKEFLAGS=-r # The source directory tree. srcdir := .. abs_srcdir := $(abspath $(srcdir)) # The name of the builddir. builddir_name ?= . # The V=1 flag on command line makes us verbosely print command lines. ifdef V quiet= else quiet=quiet_ endif # Specify BUILDTYPE=Release on the command line for a release build. BUILDTYPE ?= Release # Directory all our build output goes into. # Note that this must be two directories beneath src/ for unit tests to pass, # as they reach into the src/ directory for data with relative paths. builddir ?= $(builddir_name)/$(BUILDTYPE) abs_builddir := $(abspath $(builddir)) depsdir := $(builddir)/.deps # Object output directory. obj := $(builddir)/obj abs_obj := $(abspath $(obj)) # We build up a list of every single one of the targets so we can slurp in the # generated dependency rule Makefiles in one pass. all_deps := CC.target ?= clang CFLAGS.target ?= $(CFLAGS) CXX.target ?= $(CXX) CXXFLAGS.target ?= $(CXXFLAGS) LINK.target ?= $(LINK) LDFLAGS.target ?= $(LDFLAGS) AR.target ?= $(AR) # C++ apps need to be linked with g++. # # Note: flock is used to seralize linking. Linking is a memory-intensive # process so running parallel links can often lead to thrashing. To disable # the serialization, override LINK via an envrionment variable as follows: # # export LINK=g++ # # This will allow make to invoke N linker processes as specified in -jN. LINK ?= ./gyp-mac-tool flock $(builddir)/linker.lock $(CXX.target) # TODO(evan): move all cross-compilation logic to gyp-time so we don't need # to replicate this environment fallback in make as well. CC.host ?= gcc CFLAGS.host ?= CXX.host ?= g++ CXXFLAGS.host ?= LINK.host ?= $(CXX.host) LDFLAGS.host ?= AR.host ?= ar # Define a dir function that can handle spaces. # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions # "leading spaces cannot appear in the text of the first argument as written. # These characters can be put into the argument value by variable substitution." empty := space := $(empty) $(empty) # http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces replace_spaces = $(subst $(space),?,$1) unreplace_spaces = $(subst ?,$(space),$1) dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) # Flags to make gcc output dependency info. Note that you need to be # careful here to use the flags that ccache and distcc can understand. # We write to a dep file on the side first and then rename at the end # so we can't end up with a broken dep file. depfile = $(depsdir)/$(call replace_spaces,$@).d DEPFLAGS = -MMD -MF $(depfile).raw # We have to fixup the deps output in a few ways. # (1) the file output should mention the proper .o file. # ccache or distcc lose the path to the target, so we convert a rule of # the form: # foobar.o: DEP1 DEP2 # into # path/to/foobar.o: DEP1 DEP2 # (2) we want missing files not to cause us to fail to build. # We want to rewrite # foobar.o: DEP1 DEP2 \ # DEP3 # to # DEP1: # DEP2: # DEP3: # so if the files are missing, they're just considered phony rules. # We have to do some pretty insane escaping to get those backslashes # and dollar signs past make, the shell, and sed at the same time. # Doesn't work with spaces, but that's fine: .d files have spaces in # their names replaced with other characters. define fixup_dep # The depfile may not exist if the input file didn't have any #includes. touch $(depfile).raw # Fixup path as in (1). sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) # Add extra rules as in (2). # We remove slashes and replace spaces with new lines; # remove blank lines; # delete the first line and append a colon to the remaining lines. sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ grep -v '^$$' |\ sed -e 1d -e 's|$$|:|' \ >> $(depfile) rm $(depfile).raw endef # Command definitions: # - cmd_foo is the actual command to run; # - quiet_cmd_foo is the brief-output summary of the command. quiet_cmd_cc = CC($(TOOLSET)) $@ cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_cxx = CXX($(TOOLSET)) $@ cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_objc = CXX($(TOOLSET)) $@ cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_objcxx = CXX($(TOOLSET)) $@ cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # Commands for precompiled header files. quiet_cmd_pch_c = CXX($(TOOLSET)) $@ cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_m = CXX($(TOOLSET)) $@ cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # gyp-mac-tool is written next to the root Makefile by gyp. # Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd # already. quiet_cmd_mac_tool = MACTOOL $(4) $< cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) quiet_cmd_infoplist = INFOPLIST $@ cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" quiet_cmd_touch = TOUCH $@ cmd_touch = touch $@ quiet_cmd_copy = COPY $@ # send stderr to /dev/null to ignore messages when linking directories. cmd_copy = rm -rf "$@" && cp -af "$<" "$@" quiet_cmd_alink = LIBTOOL-STATIC $@ cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) # Define an escape_quotes function to escape single quotes. # This allows us to handle quotes properly as long as we always use # use single quotes and escape_quotes. escape_quotes = $(subst ','\'',$(1)) # This comment is here just to include a ' to unconfuse syntax highlighting. # Define an escape_vars function to escape '$' variable syntax. # This allows us to read/write command lines with shell variables (e.g. # $LD_LIBRARY_PATH), without triggering make substitution. escape_vars = $(subst $$,$$$$,$(1)) # Helper that expands to a shell command to echo a string exactly as it is in # make. This uses printf instead of echo because printf's behaviour with respect # to escape sequences is more portable than echo's across different shells # (e.g., dash, bash). exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' # Helper to compare the command we're about to run against the command # we logged the last time we ran the command. Produces an empty # string (false) when the commands match. # Tricky point: Make has no string-equality test function. # The kernel uses the following, but it seems like it would have false # positives, where one string reordered its arguments. # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ # $(filter-out $(cmd_$@), $(cmd_$(1)))) # We instead substitute each for the empty string into the other, and # say they're equal if both substitutions produce the empty string. # .d files contain ? instead of spaces, take that into account. command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) # Helper that is non-empty when a prerequisite changes. # Normally make does this implicitly, but we force rules to always run # so we can check their command lines. # $? -- new prerequisites # $| -- order-only dependencies prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) # Helper that executes all postbuilds until one fails. define do_postbuilds @E=0;\ for p in $(POSTBUILDS); do\ eval $$p;\ E=$$?;\ if [ $$E -ne 0 ]; then\ break;\ fi;\ done;\ if [ $$E -ne 0 ]; then\ rm -rf "$@";\ exit $$E;\ fi endef # do_cmd: run a command via the above cmd_foo names, if necessary. # Should always run for a given target to handle command-line changes. # Second argument, if non-zero, makes it do asm/C/C++ dependency munging. # Third argument, if non-zero, makes it do POSTBUILDS processing. # Note: We intentionally do NOT call dirx for depfile, since it contains ? for # spaces already and dirx strips the ? characters. define do_cmd $(if $(or $(command_changed),$(prereq_changed)), @$(call exact_echo, $($(quiet)cmd_$(1))) @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" $(if $(findstring flock,$(word 2,$(cmd_$1))), @$(cmd_$(1)) @echo " $(quiet_cmd_$(1)): Finished", @$(cmd_$(1)) ) @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) @$(if $(2),$(fixup_dep)) $(if $(and $(3), $(POSTBUILDS)), $(call do_postbuilds) ) ) endef # Declare the "all" target first so it is the default, # even though we don't have the deps yet. .PHONY: all all: # make looks for ways to re-generate included makefiles, but in our case, we # don't have a direct way. Explicitly telling make that it has nothing to do # for them makes it go faster. %.d: ; # Use FORCE_DO_CMD to force a target to run. Should be coupled with # do_cmd. .PHONY: FORCE_DO_CMD FORCE_DO_CMD: TOOLSET := target # Suffix rules, putting all outputs into $(obj). $(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) # Try building from generated source, too. $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ $(findstring $(join ^,$(prefix)),\ $(join ^,bufferutil.target.mk)))),) include bufferutil.target.mk endif ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ $(findstring $(join ^,$(prefix)),\ $(join ^,validation.target.mk)))),) include validation.target.mk endif quiet_cmd_regen_makefile = ACTION Regenerating $@ cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/Users/micheldegraaf/src/css-challenge/node_modules/webpack-dev-server/node_modules/socket.io/node_modules/socket.io-client/node_modules/ws/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/micheldegraaf/.node-gyp/0.10.30/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/micheldegraaf/.node-gyp/0.10.30" "-Dmodule_root_dir=/Users/micheldegraaf/src/css-challenge/node_modules/webpack-dev-server/node_modules/socket.io/node_modules/socket.io-client/node_modules/ws" binding.gyp Makefile: $(srcdir)/../../../../../../../../../../.node-gyp/0.10.30/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(call do_cmd,regen_makefile) # "all" is a concatenation of the "all" targets from all the included # sub-makefiles. This is just here to clarify. all: # Add in dependency-tracking rules. $(all_deps) is the list of every single # target in our tree. Only consider the ones with .d (dependency) info: d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) ifneq ($(d_files),) include $(d_files) endif
{ "content_hash": "00acf819170ef162a77ca56f00dcaa94", "timestamp": "", "source": "github", "line_count": 349, "max_line_length": 766, "avg_line_length": 39.07736389684814, "alnum_prop": 0.6532482768734419, "repo_name": "michel/css-challenge", "id": "71510a21da7d473c58f66be20ccac168eb714eaa", "size": "13968", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/webpack-dev-server/node_modules/socket.io/node_modules/socket.io-client/node_modules/ws/build/Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "143485" }, { "name": "CoffeeScript", "bytes": "10291" }, { "name": "HTML", "bytes": "17728" }, { "name": "JavaScript", "bytes": "2539" }, { "name": "Makefile", "bytes": "200" }, { "name": "Ruby", "bytes": "1609" } ], "symlink_target": "" }
from datetime import datetime, date, time, timedelta from fractions import Fraction from logging import warning from json import JSONEncoder from sys import version from decimal import Decimal from .utils import hashodict, call_with_optional_kwargs, NoPandasException, NoNumpyException class TricksEncoder(JSONEncoder): """ Encoder that runs any number of encoder functions or instances on the objects that are being encoded. Each encoder should make any appropriate changes and return an object, changed or not. This will be passes to the other encoders. """ def __init__(self, obj_encoders=None, silence_typeerror=False, primitives=False, **json_kwargs): """ :param obj_encoders: An iterable of functions or encoder instances to try. :param silence_typeerror: If set to True, ignore the TypeErrors that Encoder instances throw (default False). """ self.obj_encoders = [] if obj_encoders: self.obj_encoders = list(obj_encoders) self.silence_typeerror = silence_typeerror self.primitives = primitives super(TricksEncoder, self).__init__(**json_kwargs) def default(self, obj, *args, **kwargs): """ This is the method of JSONEncoders that is called for each object; it calls all the encoders with the previous one's output used as input. It works for Encoder instances, but they are expected not to throw `TypeError` for unrecognized types (the super method does that by default). It never calls the `super` method so if there are non-primitive types left at the end, you'll get an encoding error. """ prev_id = id(obj) for encoder in self.obj_encoders: if hasattr(encoder, 'default'): #todo: write test for this scenario (maybe ClassInstanceEncoder?) try: obj = call_with_optional_kwargs(encoder.default, obj, primitives=self.primitives) except TypeError as err: if not self.silence_typeerror: raise elif hasattr(encoder, '__call__'): obj = call_with_optional_kwargs(encoder, obj, primitives=self.primitives) else: raise TypeError('`obj_encoder` {0:} does not have `default` method and is not callable'.format(encoder)) if id(obj) == prev_id: #todo: test raise TypeError('Object of type {0:} could not be encoded by {1:} using encoders [{2:s}]'.format( type(obj), self.__class__.__name__, ', '.join(str(encoder) for encoder in self.obj_encoders))) return obj def json_date_time_encode(obj, primitives=False): """ Encode a date, time, datetime or timedelta to a string of a json dictionary, including optional timezone. :param obj: date/time/datetime/timedelta obj :return: (dict) json primitives representation of date, time, datetime or timedelta """ if primitives and isinstance(obj, (date, time, datetime)): return obj.isoformat() if isinstance(obj, datetime): dct = hashodict([('__datetime__', None), ('year', obj.year), ('month', obj.month), ('day', obj.day), ('hour', obj.hour), ('minute', obj.minute), ('second', obj.second), ('microsecond', obj.microsecond)]) if obj.tzinfo: dct['tzinfo'] = obj.tzinfo.zone elif isinstance(obj, date): dct = hashodict([('__date__', None), ('year', obj.year), ('month', obj.month), ('day', obj.day)]) elif isinstance(obj, time): dct = hashodict([('__time__', None), ('hour', obj.hour), ('minute', obj.minute), ('second', obj.second), ('microsecond', obj.microsecond)]) if obj.tzinfo: dct['tzinfo'] = obj.tzinfo.zone elif isinstance(obj, timedelta): if primitives: return obj.total_seconds() else: dct = hashodict([('__timedelta__', None), ('days', obj.days), ('seconds', obj.seconds), ('microseconds', obj.microseconds)]) else: return obj for key, val in tuple(dct.items()): if not key.startswith('__') and not val: del dct[key] return dct def class_instance_encode(obj, primitives=False): """ Encodes a class instance to json. Note that it can only be recovered if the environment allows the class to be imported in the same way. """ if isinstance(obj, list) or isinstance(obj, dict): return obj if hasattr(obj, '__class__') and hasattr(obj, '__dict__'): if not hasattr(obj, '__new__'): raise TypeError('class "{0:s}" does not have a __new__ method; '.format(obj.__class__) + ('perhaps it is an old-style class not derived from `object`; add `object` as a base class to encode it.' if (version[:2] == '2.') else 'this should not happen in Python3')) try: obj.__new__(obj.__class__) except TypeError: raise TypeError(('instance "{0:}" of class "{1:}" cannot be encoded because it\'s __new__ method ' 'cannot be called, perhaps it requires extra parameters').format(obj, obj.__class__)) mod = obj.__class__.__module__ if mod == '__main__': mod = None warning(('class {0:} seems to have been defined in the main file; unfortunately this means' ' that it\'s module/import path is unknown, so you might have to provide cls_lookup_map when ' 'decoding').format(obj.__class__)) name = obj.__class__.__name__ if hasattr(obj, '__json_encode__'): attrs = obj.__json_encode__() else: attrs = hashodict(obj.__dict__.items()) if primitives: return attrs else: return hashodict((('__instance_type__', (mod, name)), ('attributes', attrs))) return obj def json_complex_encode(obj, primitives=False): """ Encode a complex number as a json dictionary of it's real and imaginary part. :param obj: complex number, e.g. `2+1j` :return: (dict) json primitives representation of `obj` """ if isinstance(obj, complex): if primitives: return [obj.real, obj.imag] else: return hashodict(__complex__=[obj.real, obj.imag]) return obj def numeric_types_encode(obj, primitives=False): """ Encode Decimal and Fraction. :param primitives: Encode decimals and fractions as standard floats. You may lose precision. If you do this, you may need to enable `allow_nan` (decimals always allow NaNs but floats do not). """ if isinstance(obj, Decimal): if primitives: return float(obj) else: return { '__decimal__': str(obj.canonical()), } if isinstance(obj, Fraction): if primitives: return float(obj) else: return hashodict(( ('__fraction__', True), ('numerator', obj.numerator), ('denominator', obj.denominator), )) return obj class ClassInstanceEncoder(JSONEncoder): """ See `class_instance_encoder`. """ # Not covered in tests since `class_instance_encode` is recommended way. def __init__(self, obj, encode_cls_instances=True, **kwargs): self.encode_cls_instances = encode_cls_instances super(ClassInstanceEncoder, self).__init__(obj, **kwargs) def default(self, obj, *args, **kwargs): if self.encode_cls_instances: obj = class_instance_encode(obj) return super(ClassInstanceEncoder, self).default(obj, *args, **kwargs) def json_set_encode(obj, primitives=False): """ Encode python sets as dictionary with key __set__ and a list of the values. Try to sort the set to get a consistent json representation, use arbitrary order if the data is not ordinal. """ if isinstance(obj, set): try: repr = sorted(obj) except Exception: repr = list(obj) if primitives: return repr else: return hashodict(__set__=repr) return obj def pandas_encode(obj, primitives=False): from pandas import DataFrame, Series if isinstance(obj, (DataFrame, Series)): #todo: this is experimental if not getattr(pandas_encode, '_warned', False): pandas_encode._warned = True warning('Pandas dumping support in json-tricks is experimental and may change in future versions.') if isinstance(obj, DataFrame): repr = hashodict() if not primitives: repr['__pandas_dataframe__'] = hashodict(( ('column_order', tuple(obj.columns.values)), ('types', tuple(str(dt) for dt in obj.dtypes)), )) repr['index'] = tuple(obj.index.values) for k, name in enumerate(obj.columns.values): repr[name] = tuple(obj.ix[:, k].values) return repr if isinstance(obj, Series): repr = hashodict() if not primitives: repr['__pandas_series__'] = hashodict(( ('name', str(obj.name)), ('type', str(obj.dtype)), )) repr['index'] = tuple(obj.index.values) repr['data'] = tuple(obj.values) return repr return obj def nopandas_encode(obj): if ('DataFrame' in getattr(obj.__class__, '__name__', '') or 'Series' in getattr(obj.__class__, '__name__', '')) \ and 'pandas.' in getattr(obj.__class__, '__module__', ''): raise NoPandasException(('Trying to encode an object of type {0:} which appears to be ' 'a numpy array, but numpy support is not enabled, perhaps it is not installed.').format(type(obj))) return obj def numpy_encode(obj, primitives=False): """ Encodes numpy `ndarray`s as lists with meta data. Encodes numpy scalar types as Python equivalents. Special encoding is not possible, because int64 (in py2) and float64 (in py2 and py3) are subclasses of primitives, which never reach the encoder. :param primitives: If True, arrays are serialized as (nested) lists without meta info. """ from numpy import ndarray, generic if isinstance(obj, ndarray): if primitives: return obj.tolist() else: dct = hashodict(( ('__ndarray__', obj.tolist()), ('dtype', str(obj.dtype)), ('shape', obj.shape), )) if len(obj.shape) > 1: dct['Corder'] = obj.flags['C_CONTIGUOUS'] return dct elif isinstance(obj, generic): if NumpyEncoder.SHOW_SCALAR_WARNING: NumpyEncoder.SHOW_SCALAR_WARNING = False warning('json-tricks: numpy scalar serialization is experimental and may work differently in future versions') return obj.item() return obj class NumpyEncoder(ClassInstanceEncoder): """ JSON encoder for numpy arrays. """ SHOW_SCALAR_WARNING = True # show a warning that numpy scalar serialization is experimental def default(self, obj, *args, **kwargs): """ If input object is a ndarray it will be converted into a dict holding data type, shape and the data. The object can be restored using json_numpy_obj_hook. """ warning('`NumpyEncoder` is deprecated, use `numpy_encode`') #todo obj = numpy_encode(obj) return super(NumpyEncoder, self).default(obj, *args, **kwargs) def nonumpy_encode(obj): """ Raises an error for numpy arrays. """ if 'ndarray' in getattr(obj.__class__, '__name__', '') and 'numpy.' in getattr(obj.__class__, '__module__', ''): raise NoNumpyException(('Trying to encode an object of type {0:} which appears to be ' 'a pandas data stucture, but pandas support is not enabled, perhaps it is not installed.').format(type(obj))) return obj class NoNumpyEncoder(JSONEncoder): """ See `nonumpy_encode`. """ def default(self, obj, *args, **kwargs): warning('`NoNumpyEncoder` is deprecated, use `nonumpy_encode`') #todo obj = nonumpy_encode(obj) return super(NoNumpyEncoder, self).default(obj, *args, **kwargs)
{ "content_hash": "6ce554e6bf343dfbb0f881f97d6650dc", "timestamp": "", "source": "github", "line_count": 310, "max_line_length": 192, "avg_line_length": 34.906451612903226, "alnum_prop": 0.6869050919508364, "repo_name": "pannal/Subliminal.bundle", "id": "386e690e519ea42b87210e54eb3092dd3982584a", "size": "10822", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Contents/Libraries/Shared/json_tricks/encoders.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3012769" }, { "name": "Python", "bytes": "3311785" }, { "name": "Shell", "bytes": "273" } ], "symlink_target": "" }
import Ember from 'ember'; import StyleBindingsMixin from './style-bindings'; import BodyEventListener from './body-event-listener'; export default Ember.Mixin.create( StyleBindingsMixin, BodyEventListener, { layoutName: 'popover', classNames: ['popover'], classNameBindings: ['isShowing:in', 'fadeEnabled:fade', 'placement'], styleBindings: ['left', 'top', 'display', 'visibility'], targetElement: null, contentViewClass: null, fade: true, escToCancel: true, placement: 'top', display: 'block', visibility: 'hidden', debounceTime: 100, fadeEnabled: Ember.computed(function() { if (Ember.Widgets && Ember.Widgets.DISABLE_ANIMATIONS) { return false; } return this.get('fade'); }).property('fade'), left: 0, top: 0, marginTop: 23, marginLeft: 10, isShowing: false, inserted: false, title: '', content: '', _resizeHandler: null, _scrollHandler: null, _contentViewClass: Ember.computed(function() { if (this.get('contentViewClass')) { return this.get('contentViewClass'); } return Ember.View.extend({ content: Ember.computed.alias('parentView.content'), templateName: 'view-parent-view-content' }); }).property('contentViewClass'), didInsertElement: function() { this._super(); this.snapToPosition(); this.set('visibility', 'visible'); return this.set('isShowing', true); }, willDestroyElement: function() { this.$().off($.support.transition.end); return this._super(); }, bodyClick: function() { return this.hide(); }, hide: function() { var _this = this; if (this.get('isDestroyed')) { return; } this.set('isShowing', false); if (this.get('fadeEnabled')) { return this.$().one($.support.transition.end, function() { return Ember.run(_this, _this.destroy); }); } else { return Ember.run(this, this.destroy); } }, /* Calculate the offset of the given iframe relative to the top window. - Walks up the iframe chain, checking the offset of each one till it reaches top - Only works with friendly iframes. - Takes into account scrolling, but comes up with a result relative to top iframe, regardless of being visibile withing intervening frames. @param window win the iframe we're interested in (e.g. window) @param object pos an object containing the offset so far: { left: [x], top: [y] } (optional - initializes with 0,0 if undefined) @return pos object above via http://stackoverflow.com/a/9676655 */ computeFrameOffset: function(win, pos) { var found, frame, frames, rect, _i, _len; if (pos == null) { pos = { top: 0, left: 0 }; } frames = win.parent.document.getElementsByTagName("iframe"); found = false; for (_i = 0, _len = frames.length; _i < _len; _i++) { frame = frames[_i]; if (frame.contentWindow === win) { found = true; break; } } if (found) { rect = frame.getBoundingClientRect(); pos.left += rect.left; pos.top += rect.top; if (win !== top) { this.computeFrameOffset(win.parent, pos); } } return pos; }, getOffset: function($target) { var doc, pos, win; pos = $target.offset(); doc = $target[0].ownerDocument; win = doc.defaultView; return this.computeFrameOffset(win, pos); }, snapToPosition: function() { var $target, actualHeight, actualWidth, pos; $target = $(this.get('targetElement')); if ((this.get('_state') || this.get('state')) !== 'inDOM') { return; } actualWidth = this.$()[0].offsetWidth; actualHeight = this.$()[0].offsetHeight; if (Ember.isEmpty($target)) { pos = { top: this.get('top'), left: this.get('left'), width: 0, height: 0 }; } else { pos = this.getOffset($target); pos.width = $target[0].offsetWidth; pos.height = $target[0].offsetHeight; } switch (this.get('placement')) { case 'bottom': this.set('top', pos.top + pos.height); this.set('left', pos.left + pos.width / 2 - actualWidth / 2); break; case 'top': this.set('top', pos.top - actualHeight); this.set('left', pos.left + pos.width / 2 - actualWidth / 2); break; case 'top-right': this.set('top', pos.top); this.set('left', pos.left + pos.width); break; case 'top-left': this.set('top', pos.top); this.set('left', pos.left - actualWidth); break; case 'bottom-right': this.set('top', pos.top + pos.height); this.set('left', pos.left + pos.width - actualWidth); break; case 'bottom-left': this.set('top', pos.top + pos.height); this.set('left', pos.left); break; case 'left': this.set('top', pos.top - this.get('marginTop')); this.set('left', pos.left - actualWidth); break; case 'right': this.set('top', pos.top - this.get('marginTop')); this.set('left', pos.left + pos.width); break; } this.correctIfOffscreen(); if (!Ember.isEmpty($target)) { return this.positionArrow(); } }, positionArrow: function() { var $target, arrowSize, left, pos, top; $target = $(this.get('targetElement')); pos = this.getOffset($target); pos.width = $target[0].offsetWidth; pos.height = $target[0].offsetHeight; arrowSize = 22; switch (this.get('placement')) { case 'left': case 'right': top = pos.top + pos.height / 2 - this.get('top') - arrowSize / 2; return this.set('arrowStyle', "margin-top:" + top + "px;"); case 'top': case 'bottom': left = pos.left + pos.width / 2 - this.get('left') - arrowSize / 2; return this.set('arrowStyle', "margin-left:" + left + "px;"); } }, correctIfOffscreen: function() { var actualHeight, actualWidth, bodyHeight, bodyWidth; bodyWidth = $('body').width(); bodyHeight = $('body').height(); actualWidth = this.$()[0].offsetWidth; actualHeight = this.$()[0].offsetHeight; if (this.get('left') + actualWidth > bodyWidth) { this.set('left', bodyWidth - actualWidth - this.get('marginLeft')); } if (this.get('left') < 0) { this.set('left', this.get('marginLeft')); } if (this.get('top') + actualHeight > bodyHeight) { this.set('top', bodyHeight - actualHeight - this.get('marginTop')); } if (this.get('top') < 0) { return this.set('top', this.get('marginTop')); } }, keyHandler: Ember.computed(function() { var _this = this; return function(event) { if (event.keyCode === 27 && _this.get('escToCancel')) { return _this.hide(); } }; }), debounceSnapToPosition: Ember.computed(function() { var _this = this; return function() { return Ember.run.debounce(_this, _this.snapToPosition, _this.get('debounceTime')); }; }), _setupDocumentHandlers: function() { var _this = this; this._super(); if (!this._hideHandler) { this._hideHandler = function() { return _this.hide(); }; $(document).on('popover:hide', this._hideHandler); } if (!this._resizeHandler) { this._resizeHandler = this.get('debounceSnapToPosition'); $(document).on('resize', this._resizeHandler); } if (!this._scrollHandler) { this._scrollHandler = this.get('debounceSnapToPosition'); $(document).on('scroll', this._scrollHandler); } return $(document).on('keyup', this.get('keyHandler')); }, _removeDocumentHandlers: function() { this._super(); $(document).off('popover:hide', this._hideHandler); this._hideHandler = null; $(document).off('resize', this._resizeHandler); this._resizeHandler = null; $(document).off('scroll', this._scrollHandler); this._scrollHandler = null; return $(document).off('keyup', this.get('keyHandler')); } });
{ "content_hash": "9cd5cb1b103e032849b0bc69bc7203d6", "timestamp": "", "source": "github", "line_count": 263, "max_line_length": 88, "avg_line_length": 30.5893536121673, "alnum_prop": 0.5910503418272218, "repo_name": "Addepar/ember-widgets-addon", "id": "19a8c37662a23b20b852109d0f9f74e723d857a0", "size": "8045", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "addon/mixins/popover.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "52588" }, { "name": "HTML", "bytes": "43956" }, { "name": "JavaScript", "bytes": "123559" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Capture the Flag</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <link href='https://fonts.googleapis.com/css?family=Roboto:400,700,100' rel='stylesheet' type='text/css'> <script src="./jquery.js"></script> <script src="./jayex/d3.min.js"></script> <script src="./bootstrap" <script> var mpd = 68.91; var name = undefined; var lat = 0; var lon = 0; $("document").ready(function() { // check cookies if(readCookie("name") != null) { $("#intro").css("display", "none"); $("#tap").css("display", "inline"); name = readCookie("name"); } else { } $("#send").click(function() { createCookie("name", $("#name").val(), 30); $("#intro").css("display", "none"); $("#tap").css("display", "inline"); name = $("#name").val(); }); $("#tap").click(function() { navigator.geolocation.getCurrentPosition( processGeolocation, geolocationError, {enableHighAccuracy: true} ); }) }); function processGeolocation(position) { lat = position.coords.latitude; lon = position.coords.longitude; $.post("./backend.php", { "name":readCookie("name"), "latitude":position.coords.latitude, "longitude": position.coords.longitude, "timestamp": position.timestamp } , draw); } function draw(resp) { resp = JSON.parse(resp); console.log(resp); $("#texts").empty(); $("#points").empty(); drawPoint(screen.width/2, screen.height/2, name); for(var a=0;a<resp.length;a++) { if(resp[a].name == name) continue; var magx = lon-resp[a].longitude; var magy = lat-resp[a].latitude; var mag = Math.sqrt((magx*magx)+(magy*magy)); var dir = Math.atan(magy/magx); var xpos = (screen.width/2)+(Math.cos(dir)*100); var ypos = (screen.height/2)+(Math.sin(dir)*100); console.log(magx); console.log(magy); console.log((screen.width/2)-xpos); console.log((screen.height/2)-ypos); drawPoint(xpos, ypos, resp[a].name+"<br/>"+toDecimal((mag*mpd), 2)+" mi<br/>"+Math.round((unix()-(resp[a].timestamp/1000))/60)+" min"); } } function geolocationError(error) { console.log(error); document.write("ERR: "+JSON.stringify(error)); } function drawPoint(xpos, ypos, data) { d3.select("#points").append("circle").attr("cx", xpos).attr("cy", ypos).attr("r", 3).attr("fill", "black") $("#texts").append("<p style='position:absolute;left:"+(xpos-20)+"px;top:"+(ypos)+"px;'>"+data+"</p>"); } function unix() { return Math.floor(Date.now() / 1000) } function createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/"; } function readCookie(name) { var nameEQ = encodeURIComponent(name) + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length)); } return null; } function eraseCookie(name) { createCookie(name, "", -1); } function toDecimal(number, dec) { number *= Math.pow(10, dec); number = Math.round(number); number /= Math.pow(10, dec); number = number.toString(); if(number.indexOf(".") === -1 && dec != 0) { number += "."; } while(number.indexOf(".")+dec >= number.length) number += "0"; if(number.indexOf(".")+dec > number.length) number = number.substring(0, number.indexOf(".")+dec); return number; } </script> <style> * { margin: 0; padding: 0; font-family: "Roboto", sans-serif; } svg { z-index: -2; position: absolute; top: 0; left: 0; width: 100%; height: 100%; } #texts { z-index: -1; position: absolute; top: 0; left: 0; text-align: center; width: 100%; height: 100%; } #texts p { position: absolute; padding: 0; margin: 0; } </style> </head> <body> <div class="container"> <h1 class="page-header">Car Tag</h1> <div class="row"> <div class="col-xs-6"> <button type="button" class="btn btn-primary btn-large btn-block">Set Car Location</button> </div> <div class="col-xs-6"> <button type="button" class="btn btn-primary btn-large btn-block">Find Hidden Car</button> <div id="intro"> Name: <input type="text" id="name"><button type="button" id="send">Begin</button> </div> <button type="button" id="tap" style="display: none; position: absolute; top: 10px;right: 10px;">Get Location</button> <div id="texts"> </div> <svg style="z-index: -1;"> <g id="points"> </g> </svg> </div> </body> </html>
{ "content_hash": "55c64da492dc171768320a429d054e66", "timestamp": "", "source": "github", "line_count": 223, "max_line_length": 137, "avg_line_length": 22.15695067264574, "alnum_prop": 0.6069621534102408, "repo_name": "Bambusa6226/ftclist", "id": "9a5523ad5bc5d55a8df148bb030d8fbfe8a6bdeb", "size": "4941", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ct.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "66" }, { "name": "CSS", "bytes": "3186" }, { "name": "HTML", "bytes": "11242" }, { "name": "JavaScript", "bytes": "2106" }, { "name": "PHP", "bytes": "157431" } ], "symlink_target": "" }
package libkbfs import ( "context" "fmt" "reflect" "strings" "time" "github.com/keybase/client/go/protocol/keybase1" "github.com/keybase/go-codec/codec" "github.com/keybase/kbfs/kbfscodec" "github.com/keybase/kbfs/kbfscrypto" "github.com/keybase/kbfs/kbfsedits" "github.com/keybase/kbfs/kbfsmd" "github.com/keybase/kbfs/tlf" "github.com/pkg/errors" ) // op represents a single file-system remote-sync operation type op interface { AddRefBlock(ptr BlockPointer) DelRefBlock(ptr BlockPointer) AddUnrefBlock(ptr BlockPointer) DelUnrefBlock(ptr BlockPointer) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer) SizeExceptUpdates() uint64 allUpdates() []blockUpdate Refs() []BlockPointer Unrefs() []BlockPointer String() string StringWithRefs(indent string) string setWriterInfo(writerInfo) getWriterInfo() writerInfo setFinalPath(p path) getFinalPath() path setLocalTimestamp(t time.Time) getLocalTimestamp() time.Time checkValid() error deepCopy() op // checkConflict compares the function's target op with the given // op, and returns a resolution if one is needed (or nil // otherwise). The resulting action (if any) assumes that this // method's target op is the unmerged op, and the given op is the // merged op. checkConflict(ctx context.Context, renamer ConflictRenamer, mergedOp op, isFile bool) ( crAction, error) // getDefaultAction should be called on an unmerged op only after // all conflicts with the corresponding change have been checked, // and it returns the action to take against the merged branch // given that there are no conflicts. getDefaultAction(mergedPath path) crAction // AddSelfUpdate adds an update from the given pointer to itself. // This should be used when the caller doesn't yet know what the // new block ID will be, but wants to "complete" the update as a // signal to a future prepping process that the block needs to be // processed/readied, at which point the real new pointer will be // filled in. AddSelfUpdate(ptr BlockPointer) // ToEditNotification returns an edit notification if this op // needs one, otherwise it returns nil. ToEditNotification( rev kbfsmd.Revision, revTime time.Time, device kbfscrypto.VerifyingKey, uid keybase1.UID, tlfID tlf.ID) *kbfsedits.NotificationMessage } // op codes const ( createOpCode kbfscodec.ExtCode = iota + kbfscodec.ExtCodeOpsRangeStart rmOpCode renameOpCode syncOpCode setAttrOpCode resolutionOpCode rekeyOpCode gcOpCode // for deleting old blocks during an MD history truncation ) // blockUpdate represents a block that was updated to have a new // BlockPointer. // // NOTE: Don't add or modify anything in this struct without // considering how old clients will handle them. type blockUpdate struct { // TODO: Ideally, we'd omit Unref or Ref if they're // empty. However, we'd first have to verify that there's // nothing that relies on either one of these fields to always // be filled (e.g., see similar comments for the Info field on // BlockChanges.) Unref BlockPointer `codec:"u"` Ref BlockPointer `codec:"r"` } func makeBlockUpdate(unref, ref BlockPointer) (blockUpdate, error) { bu := blockUpdate{} err := bu.setUnref(unref) if err != nil { return blockUpdate{}, err } err = bu.setRef(ref) if err != nil { return blockUpdate{}, err } return bu, nil } func (u blockUpdate) checkValid() error { if u.Unref == (BlockPointer{}) { return errors.New("nil unref") } if u.Ref == (BlockPointer{}) { return errors.New("nil ref") } return nil } func (u *blockUpdate) setUnref(ptr BlockPointer) error { if ptr == (BlockPointer{}) { return errors.Errorf("setUnref called with nil ptr") } u.Unref = ptr return nil } func (u *blockUpdate) setRef(ptr BlockPointer) error { if ptr == (BlockPointer{}) { return errors.Errorf("setRef called with nil ptr") } u.Ref = ptr return nil } // list codes const ( opsListCode kbfscodec.ExtCode = iota + kbfscodec.ExtCodeListRangeStart ) type opsList []op // OpCommon are data structures needed by all ops. It is only // exported for serialization purposes. type OpCommon struct { RefBlocks []BlockPointer `codec:"r,omitempty"` UnrefBlocks []BlockPointer `codec:"u,omitempty"` Updates []blockUpdate `codec:"o,omitempty"` codec.UnknownFieldSetHandler // writerInfo is the keybase username and device that generated this // operation. // Not exported; only used during conflict resolution. writerInfo writerInfo // finalPath is the final resolved path to the node that this // operation affects in a set of MD updates. Not exported; only // used locally. finalPath path // localTimestamp should be set to the localTimestamp of the // corresponding ImmutableRootMetadata when ops need individual // timestamps. Not exported; only used locally. localTimestamp time.Time } func (oc OpCommon) deepCopy() OpCommon { ocCopy := OpCommon{} ocCopy.RefBlocks = make([]BlockPointer, len(oc.RefBlocks)) copy(ocCopy.RefBlocks, oc.RefBlocks) ocCopy.UnrefBlocks = make([]BlockPointer, len(oc.UnrefBlocks)) copy(ocCopy.UnrefBlocks, oc.UnrefBlocks) ocCopy.Updates = make([]blockUpdate, len(oc.Updates)) copy(ocCopy.Updates, oc.Updates) // TODO: if we ever need to copy the unknown fields in this // method, we'll have to change the codec interface to make it // possible. ocCopy.writerInfo = oc.writerInfo ocCopy.finalPath = oc.finalPath ocCopy.finalPath.path = make([]pathNode, len(oc.finalPath.path)) copy(ocCopy.finalPath.path, oc.finalPath.path) ocCopy.localTimestamp = oc.localTimestamp return ocCopy } // AddRefBlock adds this block to the list of newly-referenced blocks // for this op. func (oc *OpCommon) AddRefBlock(ptr BlockPointer) { oc.RefBlocks = append(oc.RefBlocks, ptr) } // DelRefBlock removes the first reference of the given block from the // list of newly-referenced blocks for this op. func (oc *OpCommon) DelRefBlock(ptr BlockPointer) { for i, ref := range oc.RefBlocks { if ptr == ref { oc.RefBlocks = append(oc.RefBlocks[:i], oc.RefBlocks[i+1:]...) break } } } // AddUnrefBlock adds this block to the list of newly-unreferenced blocks // for this op. func (oc *OpCommon) AddUnrefBlock(ptr BlockPointer) { oc.UnrefBlocks = append(oc.UnrefBlocks, ptr) } // DelUnrefBlock removes the first unreference of the given block from // the list of unreferenced blocks for this op. func (oc *OpCommon) DelUnrefBlock(ptr BlockPointer) { for i, unref := range oc.UnrefBlocks { if ptr == unref { oc.UnrefBlocks = append(oc.UnrefBlocks[:i], oc.UnrefBlocks[i+1:]...) break } } } // AddUpdate adds a mapping from an old block to the new version of // that block, for this op. func (oc *OpCommon) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer) { // Either pointer may be zero, if we're building an op that // will be fixed up later. bu := blockUpdate{oldPtr, newPtr} oc.Updates = append(oc.Updates, bu) } // AddSelfUpdate implements the op interface for OpCommon -- see the // comment in op. func (oc *OpCommon) AddSelfUpdate(ptr BlockPointer) { oc.AddUpdate(ptr, ptr) } // Refs returns a slice containing all the blocks that were initially // referenced during this op. func (oc *OpCommon) Refs() []BlockPointer { return oc.RefBlocks } // Unrefs returns a slice containing all the blocks that were // unreferenced during this op. func (oc *OpCommon) Unrefs() []BlockPointer { return oc.UnrefBlocks } func (oc *OpCommon) setWriterInfo(info writerInfo) { oc.writerInfo = info } func (oc *OpCommon) getWriterInfo() writerInfo { return oc.writerInfo } func (oc *OpCommon) setFinalPath(p path) { oc.finalPath = p } func (oc *OpCommon) getFinalPath() path { return oc.finalPath } func (oc *OpCommon) setLocalTimestamp(t time.Time) { oc.localTimestamp = t } func (oc *OpCommon) getLocalTimestamp() time.Time { return oc.localTimestamp } func (oc *OpCommon) checkUpdatesValid() error { for i, update := range oc.Updates { err := update.checkValid() if err != nil { return errors.Errorf( "update[%d]=%v got error: %v", i, update, err) } } return nil } func (oc *OpCommon) stringWithRefs(indent string) string { res := "" for i, update := range oc.Updates { res += indent + fmt.Sprintf( "Update[%d]: %v -> %v\n", i, update.Unref, update.Ref) } for i, ref := range oc.RefBlocks { res += indent + fmt.Sprintf("Ref[%d]: %v\n", i, ref) } for i, unref := range oc.UnrefBlocks { res += indent + fmt.Sprintf("Unref[%d]: %v\n", i, unref) } return res } // ToEditNotification implements the op interface for OpCommon. func (oc *OpCommon) ToEditNotification( _ kbfsmd.Revision, _ time.Time, _ kbfscrypto.VerifyingKey, _ keybase1.UID, _ tlf.ID) *kbfsedits.NotificationMessage { // Ops embedding this that can be converted should override this. return nil } // createOp is an op representing a file or subdirectory creation type createOp struct { OpCommon NewName string `codec:"n"` Dir blockUpdate `codec:"d"` Type EntryType `codec:"t"` // If true, this create op represents half of a rename operation. // This op should never be persisted. renamed bool // If true, during conflict resolution the blocks of the file will // be copied. forceCopy bool // If this is set, ths create op needs to be turned has been // turned into a symlink creation locally to avoid a cycle during // conflict resolution, and the following field represents the // text of the symlink. This op should never be persisted. crSymPath string } func newCreateOp(name string, oldDir BlockPointer, t EntryType) (*createOp, error) { co := &createOp{ NewName: name, } err := co.Dir.setUnref(oldDir) if err != nil { return nil, err } co.Type = t return co, nil } func (co *createOp) deepCopy() op { coCopy := *co coCopy.OpCommon = co.OpCommon.deepCopy() return &coCopy } func newCreateOpForRootDir() *createOp { return &createOp{ Type: Dir, } } func (co *createOp) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer) { if co.Dir == (blockUpdate{}) { panic("AddUpdate called on create op with empty Dir " + "(probably create op for root dir)") } if oldPtr == co.Dir.Unref { err := co.Dir.setRef(newPtr) if err != nil { panic(err) } return } co.OpCommon.AddUpdate(oldPtr, newPtr) } // AddSelfUpdate implements the op interface for createOp -- see the // comment in op. func (co *createOp) AddSelfUpdate(ptr BlockPointer) { co.AddUpdate(ptr, ptr) } func (co *createOp) SizeExceptUpdates() uint64 { return uint64(len(co.NewName)) } func (co *createOp) allUpdates() []blockUpdate { updates := make([]blockUpdate, len(co.Updates)) copy(updates, co.Updates) return append(updates, co.Dir) } func (co *createOp) checkValid() error { if co.NewName == "" { // Must be for root dir. return nil } err := co.Dir.checkValid() if err != nil { return errors.Errorf("createOp.Dir=%v got error: %v", co.Dir, err) } return co.checkUpdatesValid() } func (co *createOp) String() string { res := fmt.Sprintf("create %s (%s)", co.NewName, co.Type) if co.renamed { res += " (renamed)" } return res } func (co *createOp) StringWithRefs(indent string) string { res := co.String() + "\n" res += indent + fmt.Sprintf("Dir: %v -> %v\n", co.Dir.Unref, co.Dir.Ref) res += co.stringWithRefs(indent) return res } func (co *createOp) checkConflict( ctx context.Context, renamer ConflictRenamer, mergedOp op, isFile bool) (crAction, error) { switch realMergedOp := mergedOp.(type) { case *createOp: // Conflicts if this creates the same name and one of them // isn't creating a directory. sameName := (realMergedOp.NewName == co.NewName) if sameName && (realMergedOp.Type != Dir || co.Type != Dir) { if realMergedOp.Type != Dir && (co.Type == Dir || co.crSymPath != "") { // Rename the merged entry only if the unmerged one is // a directory (or to-be-sympath'd directory) and the // merged one is not. toName, err := renamer.ConflictRename( ctx, mergedOp, co.NewName) if err != nil { return nil, err } return &renameMergedAction{ fromName: co.NewName, toName: toName, symPath: co.crSymPath, }, nil } // Otherwise rename the unmerged entry (guaranteed to be a file). toName, err := renamer.ConflictRename( ctx, co, co.NewName) if err != nil { return nil, err } return &renameUnmergedAction{ fromName: co.NewName, toName: toName, symPath: co.crSymPath, }, nil } // If they are both directories, and one of them is a rename, // then we have a conflict and need to rename the renamed one. // // TODO: Implement a better merging strategy for when an // existing directory gets into a rename conflict with another // existing or new directory. if sameName && realMergedOp.Type == Dir && co.Type == Dir && (realMergedOp.renamed || co.renamed) { // Always rename the unmerged one toName, err := renamer.ConflictRename( ctx, co, co.NewName) if err != nil { return nil, err } return &copyUnmergedEntryAction{ fromName: co.NewName, toName: toName, symPath: co.crSymPath, unique: true, }, nil } } // Doesn't conflict with any rmOps, because the default action // will just re-create it in the merged branch as necessary. return nil, nil } func (co *createOp) getDefaultAction(mergedPath path) crAction { if co.forceCopy { return &renameUnmergedAction{ fromName: co.NewName, toName: co.NewName, symPath: co.crSymPath, } } return &copyUnmergedEntryAction{ fromName: co.NewName, toName: co.NewName, symPath: co.crSymPath, } } func makeBaseEditNotification( rev kbfsmd.Revision, revTime time.Time, device kbfscrypto.VerifyingKey, uid keybase1.UID, tlfID tlf.ID, et EntryType) kbfsedits.NotificationMessage { var t kbfsedits.EntryType switch et { case File, Exec: t = kbfsedits.EntryTypeFile case Dir: t = kbfsedits.EntryTypeDir case Sym: t = kbfsedits.EntryTypeSym } return kbfsedits.NotificationMessage{ Version: kbfsedits.NotificationV2, FileType: t, Time: revTime, Revision: rev, Device: device, UID: uid, FolderID: tlfID, } } func (co *createOp) ToEditNotification( rev kbfsmd.Revision, revTime time.Time, device kbfscrypto.VerifyingKey, uid keybase1.UID, tlfID tlf.ID) *kbfsedits.NotificationMessage { n := makeBaseEditNotification(rev, revTime, device, uid, tlfID, co.Type) n.Filename = co.getFinalPath().ChildPathNoPtr(co.NewName). CanonicalPathString() n.Type = kbfsedits.NotificationCreate return &n } // rmOp is an op representing a file or subdirectory removal type rmOp struct { OpCommon OldName string `codec:"n"` Dir blockUpdate `codec:"d"` RemovedType EntryType `codec:"rt"` // Indicates that the resolution process should skip this rm op. // Likely indicates the rm half of a cycle-creating rename. dropThis bool } func newRmOp(name string, oldDir BlockPointer, removedType EntryType) ( *rmOp, error) { ro := &rmOp{ OldName: name, RemovedType: removedType, } err := ro.Dir.setUnref(oldDir) if err != nil { return nil, err } return ro, nil } func (ro *rmOp) deepCopy() op { roCopy := *ro roCopy.OpCommon = ro.OpCommon.deepCopy() return &roCopy } func (ro *rmOp) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer) { if oldPtr == ro.Dir.Unref { err := ro.Dir.setRef(newPtr) if err != nil { panic(err) } return } ro.OpCommon.AddUpdate(oldPtr, newPtr) } // AddSelfUpdate implements the op interface for rmOp -- see the // comment in op. func (ro *rmOp) AddSelfUpdate(ptr BlockPointer) { ro.AddUpdate(ptr, ptr) } func (ro *rmOp) SizeExceptUpdates() uint64 { return uint64(len(ro.OldName)) } func (ro *rmOp) allUpdates() []blockUpdate { updates := make([]blockUpdate, len(ro.Updates)) copy(updates, ro.Updates) return append(updates, ro.Dir) } func (ro *rmOp) checkValid() error { err := ro.Dir.checkValid() if err != nil { return errors.Errorf("rmOp.Dir=%v got error: %v", ro.Dir, err) } return ro.checkUpdatesValid() } func (ro *rmOp) String() string { return fmt.Sprintf("rm %s", ro.OldName) } func (ro *rmOp) StringWithRefs(indent string) string { res := ro.String() + "\n" res += indent + fmt.Sprintf("Dir: %v -> %v\n", ro.Dir.Unref, ro.Dir.Ref) res += ro.stringWithRefs(indent) return res } func (ro *rmOp) checkConflict( ctx context.Context, renamer ConflictRenamer, mergedOp op, isFile bool) (crAction, error) { switch realMergedOp := mergedOp.(type) { case *createOp: if realMergedOp.NewName == ro.OldName { // Conflicts if this creates the same name. This can only // happen if the merged branch deleted the old node and // re-created it, in which case it is totally fine to drop // this rm op for the original node. return &dropUnmergedAction{op: ro}, nil } case *rmOp: if realMergedOp.OldName == ro.OldName { // Both removed the same file. return &dropUnmergedAction{op: ro}, nil } } return nil, nil } func (ro *rmOp) getDefaultAction(mergedPath path) crAction { if ro.dropThis { return &dropUnmergedAction{op: ro} } return &rmMergedEntryAction{name: ro.OldName} } func (ro *rmOp) ToEditNotification( rev kbfsmd.Revision, revTime time.Time, device kbfscrypto.VerifyingKey, uid keybase1.UID, tlfID tlf.ID) *kbfsedits.NotificationMessage { n := makeBaseEditNotification( rev, revTime, device, uid, tlfID, ro.RemovedType) n.Filename = ro.getFinalPath().ChildPathNoPtr(ro.OldName). CanonicalPathString() n.Type = kbfsedits.NotificationDelete return &n } // renameOp is an op representing a rename of a file/subdirectory from // one directory to another. If this is a rename within the same // directory, NewDir will be equivalent to blockUpdate{}. renameOp // records the moved pointer, even though it doesn't change as part of // the operation, to make it possible to track the full path of // directories for the purposes of conflict resolution. type renameOp struct { OpCommon OldName string `codec:"on"` OldDir blockUpdate `codec:"od"` NewName string `codec:"nn"` NewDir blockUpdate `codec:"nd"` Renamed BlockPointer `codec:"re"` RenamedType EntryType `codec:"rt"` // oldFinalPath is the final resolved path to the old directory // containing the renamed node. Not exported; only used locally. oldFinalPath path } func newRenameOp(oldName string, oldOldDir BlockPointer, newName string, oldNewDir BlockPointer, renamed BlockPointer, renamedType EntryType) (*renameOp, error) { ro := &renameOp{ OldName: oldName, NewName: newName, Renamed: renamed, RenamedType: renamedType, } err := ro.OldDir.setUnref(oldOldDir) if err != nil { return nil, err } // If we are renaming within a directory, let the NewDir remain empty. if oldOldDir != oldNewDir { err := ro.NewDir.setUnref(oldNewDir) if err != nil { return nil, err } } return ro, nil } func (ro *renameOp) deepCopy() op { roCopy := *ro roCopy.OpCommon = ro.OpCommon.deepCopy() return &roCopy } func (ro *renameOp) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer) { if oldPtr == ro.OldDir.Unref { err := ro.OldDir.setRef(newPtr) if err != nil { panic(err) } return } if ro.NewDir != (blockUpdate{}) && oldPtr == ro.NewDir.Unref { err := ro.NewDir.setRef(newPtr) if err != nil { panic(err) } return } ro.OpCommon.AddUpdate(oldPtr, newPtr) } // AddSelfUpdate implements the op interface for renameOp -- see the // comment in op. func (ro *renameOp) AddSelfUpdate(ptr BlockPointer) { ro.AddUpdate(ptr, ptr) } func (ro *renameOp) SizeExceptUpdates() uint64 { return uint64(len(ro.NewName) + len(ro.NewName)) } func (ro *renameOp) allUpdates() []blockUpdate { updates := make([]blockUpdate, len(ro.Updates)) copy(updates, ro.Updates) if ro.NewDir != (blockUpdate{}) { return append(updates, ro.NewDir, ro.OldDir) } return append(updates, ro.OldDir) } func (ro *renameOp) checkValid() error { err := ro.OldDir.checkValid() if err != nil { return errors.Errorf("renameOp.OldDir=%v got error: %v", ro.OldDir, err) } if ro.NewDir != (blockUpdate{}) { err = ro.NewDir.checkValid() if err != nil { return errors.Errorf("renameOp.NewDir=%v got error: %v", ro.NewDir, err) } } return ro.checkUpdatesValid() } func (ro *renameOp) String() string { return fmt.Sprintf("rename %s -> %s (%s)", ro.OldName, ro.NewName, ro.RenamedType) } func (ro *renameOp) StringWithRefs(indent string) string { res := ro.String() + "\n" res += indent + fmt.Sprintf("OldDir: %v -> %v\n", ro.OldDir.Unref, ro.OldDir.Ref) if ro.NewDir != (blockUpdate{}) { res += indent + fmt.Sprintf("NewDir: %v -> %v\n", ro.NewDir.Unref, ro.NewDir.Ref) } else { res += indent + fmt.Sprintf("NewDir: same as above\n") } res += indent + fmt.Sprintf("Renamed: %v\n", ro.Renamed) res += ro.stringWithRefs(indent) return res } func (ro *renameOp) checkConflict( ctx context.Context, renamer ConflictRenamer, mergedOp op, isFile bool) (crAction, error) { return nil, errors.Errorf("Unexpected conflict check on a rename op: %s", ro) } func (ro *renameOp) getDefaultAction(mergedPath path) crAction { return nil } func (ro *renameOp) ToEditNotification( rev kbfsmd.Revision, revTime time.Time, device kbfscrypto.VerifyingKey, uid keybase1.UID, tlfID tlf.ID) *kbfsedits.NotificationMessage { n := makeBaseEditNotification( rev, revTime, device, uid, tlfID, ro.RenamedType) n.Filename = ro.getFinalPath().ChildPathNoPtr(ro.NewName). CanonicalPathString() n.Type = kbfsedits.NotificationRename n.Params = &kbfsedits.NotificationParams{ OldFilename: ro.oldFinalPath.ChildPathNoPtr(ro.OldName). CanonicalPathString(), } return &n } // WriteRange represents a file modification. Len is 0 for a // truncate. type WriteRange struct { Off uint64 `codec:"o"` Len uint64 `codec:"l,omitempty"` // 0 for truncates codec.UnknownFieldSetHandler } func (w WriteRange) isTruncate() bool { return w.Len == 0 } // End returns the index of the largest byte not affected by this // write. It only makes sense to call this for non-truncates. func (w WriteRange) End() uint64 { if w.isTruncate() { panic("Truncates don't have an end") } return w.Off + w.Len } // Affects returns true if the regions affected by this write // operation and `other` overlap in some way. Specifically, it // returns true if: // // - both operations are writes and their write ranges overlap; // - one operation is a write and one is a truncate, and the truncate is // within the write's range or before it; or // - both operations are truncates. func (w WriteRange) Affects(other WriteRange) bool { if w.isTruncate() { if other.isTruncate() { return true } // A truncate affects a write if it lands inside or before the // write. return other.End() > w.Off } else if other.isTruncate() { return w.End() > other.Off } // Both are writes -- do their ranges overlap? return (w.Off <= other.End() && other.End() <= w.End()) || (other.Off <= w.End() && w.End() <= other.End()) } // syncOp is an op that represents a series of writes to a file. type syncOp struct { OpCommon File blockUpdate `codec:"f"` Writes []WriteRange `codec:"w"` // If true, this says that if there is a conflict involving this // op, we should keep the unmerged name rather than construct a // conflict name (probably because the new name already // diverges from the name in the other branch). keepUnmergedTailName bool } func newSyncOp(oldFile BlockPointer) (*syncOp, error) { so := &syncOp{} err := so.File.setUnref(oldFile) if err != nil { return nil, err } so.resetUpdateState() return so, nil } func (so *syncOp) deepCopy() op { soCopy := *so soCopy.OpCommon = so.OpCommon.deepCopy() soCopy.Writes = make([]WriteRange, len(so.Writes)) copy(soCopy.Writes, so.Writes) return &soCopy } func (so *syncOp) resetUpdateState() { so.Updates = nil } func (so *syncOp) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer) { if oldPtr == so.File.Unref { err := so.File.setRef(newPtr) if err != nil { panic(err) } return } so.OpCommon.AddUpdate(oldPtr, newPtr) } // AddSelfUpdate implements the op interface for syncOp -- see the // comment in op. func (so *syncOp) AddSelfUpdate(ptr BlockPointer) { so.AddUpdate(ptr, ptr) } func (so *syncOp) addWrite(off uint64, length uint64) WriteRange { latestWrite := WriteRange{Off: off, Len: length} so.Writes = append(so.Writes, latestWrite) return latestWrite } func (so *syncOp) addTruncate(off uint64) WriteRange { latestWrite := WriteRange{Off: off, Len: 0} so.Writes = append(so.Writes, latestWrite) return latestWrite } func (so *syncOp) SizeExceptUpdates() uint64 { return uint64(len(so.Writes) * 16) } func (so *syncOp) allUpdates() []blockUpdate { updates := make([]blockUpdate, len(so.Updates)) copy(updates, so.Updates) return append(updates, so.File) } func (so *syncOp) checkValid() error { err := so.File.checkValid() if err != nil { return errors.Errorf("syncOp.File=%v got error: %v", so.File, err) } return so.checkUpdatesValid() } func (so *syncOp) String() string { var writes []string for _, r := range so.Writes { writes = append(writes, fmt.Sprintf("{off=%d, len=%d}", r.Off, r.Len)) } return fmt.Sprintf("sync [%s]", strings.Join(writes, ", ")) } func (so *syncOp) StringWithRefs(indent string) string { res := so.String() + "\n" res += indent + fmt.Sprintf("File: %v -> %v\n", so.File.Unref, so.File.Ref) res += so.stringWithRefs(indent) return res } func (so *syncOp) checkConflict( ctx context.Context, renamer ConflictRenamer, mergedOp op, isFile bool) (crAction, error) { switch mergedOp.(type) { case *syncOp: // Any sync on the same file is a conflict. (TODO: add // type-specific intelligent conflict resolvers for file // contents?) toName, err := renamer.ConflictRename( ctx, so, mergedOp.getFinalPath().tailName()) if err != nil { return nil, err } if so.keepUnmergedTailName { toName = so.getFinalPath().tailName() } return &renameUnmergedAction{ fromName: so.getFinalPath().tailName(), toName: toName, unmergedParentMostRecent: so.getFinalPath().parentPath().tailPointer(), mergedParentMostRecent: mergedOp.getFinalPath().parentPath(). tailPointer(), }, nil case *setAttrOp: // Someone on the merged path explicitly set an attribute, so // just copy the size and blockpointer over. return &copyUnmergedAttrAction{ fromName: so.getFinalPath().tailName(), toName: mergedOp.getFinalPath().tailName(), attr: []attrChange{sizeAttr}, }, nil } return nil, nil } func (so *syncOp) getDefaultAction(mergedPath path) crAction { return &copyUnmergedEntryAction{ fromName: so.getFinalPath().tailName(), toName: mergedPath.tailName(), symPath: "", } } func (so *syncOp) ToEditNotification( rev kbfsmd.Revision, revTime time.Time, device kbfscrypto.VerifyingKey, uid keybase1.UID, tlfID tlf.ID) *kbfsedits.NotificationMessage { n := makeBaseEditNotification(rev, revTime, device, uid, tlfID, File) n.Filename = so.getFinalPath().CanonicalPathString() n.Type = kbfsedits.NotificationModify var mods []kbfsedits.ModifyRange for _, w := range so.Writes { mods = append(mods, kbfsedits.ModifyRange{ Offset: w.Off, Length: w.Len, }) } n.Params = &kbfsedits.NotificationParams{ Modifies: mods, } return &n } // In the functions below. a collapsed []WriteRange is a sequence of // non-overlapping writes with strictly increasing Off, and maybe a // trailing truncate (with strictly greater Off). // coalesceWrites combines the given `wNew` with the head and tail of // the given collapsed `existingWrites` slice. For example, if the // new write is {5, 100}, and `existingWrites` = [{7,5}, {18,10}, // {98,10}], the returned write will be {5,103}. There may be a // truncate at the end of the returned slice as well. func coalesceWrites(existingWrites []WriteRange, wNew WriteRange) []WriteRange { if wNew.isTruncate() { panic("coalesceWrites cannot be called with a new truncate.") } if len(existingWrites) == 0 { return []WriteRange{wNew} } newOff := wNew.Off newEnd := wNew.End() wOldHead := existingWrites[0] wOldTail := existingWrites[len(existingWrites)-1] if !wOldTail.isTruncate() && wOldTail.End() > newEnd { newEnd = wOldTail.End() } if !wOldHead.isTruncate() && wOldHead.Off < newOff { newOff = wOldHead.Off } ret := []WriteRange{{Off: newOff, Len: newEnd - newOff}} if wOldTail.isTruncate() { ret = append(ret, WriteRange{Off: newEnd}) } return ret } // Assumes writes is already collapsed, i.e. a sequence of // non-overlapping writes with strictly increasing Off, and maybe a // trailing truncate (with strictly greater Off). func addToCollapsedWriteRange(writes []WriteRange, wNew WriteRange) []WriteRange { // Form three regions: head, mid, and tail: head is the maximal prefix // of writes less than (with respect to Off) and unaffected by wNew, // tail is the maximal suffix of writes greater than (with respect to // Off) and unaffected by wNew, and mid is everything else, i.e. the // range of writes affected by wNew. var headEnd int for ; headEnd < len(writes); headEnd++ { wOld := writes[headEnd] if wOld.Off >= wNew.Off || wNew.Affects(wOld) { break } } head := writes[:headEnd] if wNew.isTruncate() { // end is empty, since a truncate affects a suffix of writes. mid := writes[headEnd:] if len(mid) == 0 { // Truncate past the last write. return append(head, wNew) } else if mid[0].isTruncate() { if mid[0].Off < wNew.Off { // A larger new truncate causes zero-fill. zeroLen := wNew.Off - mid[0].Off if len(head) > 0 { lastHead := head[len(head)-1] if lastHead.Off+lastHead.Len == mid[0].Off { // Combine this zero-fill with the previous write. head[len(head)-1].Len += zeroLen return append(head, wNew) } } return append(head, WriteRange{Off: mid[0].Off, Len: zeroLen}, wNew) } return append(head, wNew) } else if mid[0].Off < wNew.Off { return append(head, WriteRange{ Off: mid[0].Off, Len: wNew.Off - mid[0].Off, }, wNew) } return append(head, wNew) } // wNew is a write. midEnd := headEnd for ; midEnd < len(writes); midEnd++ { wOld := writes[midEnd] if !wNew.Affects(wOld) { break } } mid := writes[headEnd:midEnd] end := writes[midEnd:] mid = coalesceWrites(mid, wNew) return append(head, append(mid, end...)...) } // collapseWriteRange returns a set of writes that represent the final // dirty state of this file after this syncOp, given a previous write // range. It coalesces overlapping dirty writes, and it erases any // writes that occurred before a truncation with an offset smaller // than its max dirty byte. // // This function assumes that `writes` has already been collapsed (or // is nil). // // NOTE: Truncates past a file's end get turned into writes by // folderBranchOps, but in the future we may have bona fide truncate // WriteRanges past a file's end. func (so *syncOp) collapseWriteRange(writes []WriteRange) ( newWrites []WriteRange) { newWrites = writes for _, wNew := range so.Writes { newWrites = addToCollapsedWriteRange(newWrites, wNew) } return newWrites } type attrChange uint16 const ( exAttr attrChange = iota mtimeAttr sizeAttr // only used during conflict resolution ) func (ac attrChange) String() string { switch ac { case exAttr: return "ex" case mtimeAttr: return "mtime" case sizeAttr: return "size" } return "<invalid attrChange>" } // setAttrOp is an op that represents changing the attributes of a // file/subdirectory with in a directory. type setAttrOp struct { OpCommon Name string `codec:"n"` Dir blockUpdate `codec:"d"` Attr attrChange `codec:"a"` File BlockPointer `codec:"f"` // If true, this says that if there is a conflict involving this // op, we should keep the unmerged name rather than construct a // conflict name (probably because the new name already // diverges from the name in the other branch). keepUnmergedTailName bool } func newSetAttrOp(name string, oldDir BlockPointer, attr attrChange, file BlockPointer) (*setAttrOp, error) { sao := &setAttrOp{ Name: name, } err := sao.Dir.setUnref(oldDir) if err != nil { return nil, err } sao.Attr = attr sao.File = file return sao, nil } func (sao *setAttrOp) deepCopy() op { saoCopy := *sao saoCopy.OpCommon = sao.OpCommon.deepCopy() return &saoCopy } func (sao *setAttrOp) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer) { if oldPtr == sao.Dir.Unref { err := sao.Dir.setRef(newPtr) if err != nil { panic(err) } return } sao.OpCommon.AddUpdate(oldPtr, newPtr) } // AddSelfUpdate implements the op interface for setAttrOp -- see the // comment in op. func (sao *setAttrOp) AddSelfUpdate(ptr BlockPointer) { sao.AddUpdate(ptr, ptr) } func (sao *setAttrOp) SizeExceptUpdates() uint64 { return uint64(len(sao.Name)) } func (sao *setAttrOp) allUpdates() []blockUpdate { updates := make([]blockUpdate, len(sao.Updates)) copy(updates, sao.Updates) return append(updates, sao.Dir) } func (sao *setAttrOp) checkValid() error { err := sao.Dir.checkValid() if err != nil { return errors.Errorf("setAttrOp.Dir=%v got error: %v", sao.Dir, err) } return sao.checkUpdatesValid() } func (sao *setAttrOp) String() string { return fmt.Sprintf("setAttr %s (%s)", sao.Name, sao.Attr) } func (sao *setAttrOp) StringWithRefs(indent string) string { res := sao.String() + "\n" res += indent + fmt.Sprintf("Dir: %v -> %v\n", sao.Dir.Unref, sao.Dir.Ref) res += indent + fmt.Sprintf("File: %v\n", sao.File) res += sao.stringWithRefs(indent) return res } func (sao *setAttrOp) checkConflict( ctx context.Context, renamer ConflictRenamer, mergedOp op, isFile bool) (crAction, error) { switch realMergedOp := mergedOp.(type) { case *setAttrOp: if realMergedOp.Attr == sao.Attr { var symPath string var causedByAttr attrChange if !isFile { // A directory has a conflict on an mtime attribute. // Create a symlink entry with the unmerged mtime // pointing to the merged entry. symPath = mergedOp.getFinalPath().tailName() causedByAttr = sao.Attr } // A set attr for the same attribute on the same file is a // conflict. fromName := sao.getFinalPath().tailName() toName, err := renamer.ConflictRename(ctx, sao, fromName) if err != nil { return nil, err } if sao.keepUnmergedTailName { toName = sao.getFinalPath().tailName() } return &renameUnmergedAction{ fromName: fromName, toName: toName, symPath: symPath, causedByAttr: causedByAttr, unmergedParentMostRecent: sao.getFinalPath().parentPath().tailPointer(), mergedParentMostRecent: mergedOp.getFinalPath().parentPath(). tailPointer(), }, nil } } return nil, nil } func (sao *setAttrOp) getDefaultAction(mergedPath path) crAction { return &copyUnmergedAttrAction{ fromName: sao.getFinalPath().tailName(), toName: mergedPath.tailName(), attr: []attrChange{sao.Attr}, } } // resolutionOp is an op that represents the block changes that took // place as part of a conflict resolution. type resolutionOp struct { OpCommon UncommittedUnrefs []BlockPointer `codec:"uu"` } func newResolutionOp() *resolutionOp { ro := &resolutionOp{} return ro } func (ro *resolutionOp) deepCopy() op { roCopy := *ro roCopy.OpCommon = ro.OpCommon.deepCopy() roCopy.UncommittedUnrefs = make([]BlockPointer, len(ro.UncommittedUnrefs)) copy(roCopy.UncommittedUnrefs, ro.UncommittedUnrefs) return &roCopy } func (ro *resolutionOp) Unrefs() []BlockPointer { return append(ro.OpCommon.Unrefs(), ro.UncommittedUnrefs...) } func (ro *resolutionOp) DelUnrefBlock(ptr BlockPointer) { ro.OpCommon.DelUnrefBlock(ptr) for i, unref := range ro.UncommittedUnrefs { if ptr == unref { ro.UncommittedUnrefs = append( ro.UncommittedUnrefs[:i], ro.UncommittedUnrefs[i+1:]...) break } } } func (ro *resolutionOp) SizeExceptUpdates() uint64 { return 0 } func (ro *resolutionOp) allUpdates() []blockUpdate { return ro.Updates } func (ro *resolutionOp) checkValid() error { return ro.checkUpdatesValid() } func (ro *resolutionOp) String() string { return "resolution" } func (ro *resolutionOp) StringWithRefs(indent string) string { res := ro.String() + "\n" res += ro.stringWithRefs(indent) return res } // AddUncommittedUnrefBlock adds this block to the list of blocks that should be // archived/deleted from the server, but which were never actually // committed successfully in an MD. Therefore, their sizes don't have // to be accounted for in any MD size accounting for the TLF. func (ro *resolutionOp) AddUncommittedUnrefBlock(ptr BlockPointer) { ro.UncommittedUnrefs = append(ro.UncommittedUnrefs, ptr) } func (ro *resolutionOp) CommittedUnrefs() []BlockPointer { return ro.OpCommon.Unrefs() } func (ro *resolutionOp) checkConflict( ctx context.Context, renamer ConflictRenamer, mergedOp op, isFile bool) (crAction, error) { return nil, nil } func (ro *resolutionOp) getDefaultAction(mergedPath path) crAction { return nil } // rekeyOp is an op that represents a rekey on a TLF. type rekeyOp struct { OpCommon } func newRekeyOp() *rekeyOp { ro := &rekeyOp{} return ro } func (ro *rekeyOp) deepCopy() op { roCopy := *ro roCopy.OpCommon = ro.OpCommon.deepCopy() return &roCopy } func (ro *rekeyOp) SizeExceptUpdates() uint64 { return 0 } func (ro *rekeyOp) allUpdates() []blockUpdate { return ro.Updates } func (ro *rekeyOp) checkValid() error { return ro.checkUpdatesValid() } func (ro *rekeyOp) String() string { return "rekey" } func (ro *rekeyOp) StringWithRefs(indent string) string { res := ro.String() + "\n" res += ro.stringWithRefs(indent) return res } func (ro *rekeyOp) checkConflict( ctx context.Context, renamer ConflictRenamer, mergedOp op, isFile bool) (crAction, error) { return nil, nil } func (ro *rekeyOp) getDefaultAction(mergedPath path) crAction { return nil } // GCOp is an op that represents garbage-collecting the history of a // folder (which may involve unreferencing blocks that previously held // operation lists. It may contain unref blocks before it is added to // the metadata ops list. type GCOp struct { OpCommon // LatestRev is the most recent MD revision that was // garbage-collected with this operation. // // The codec name overrides the one for RefBlocks in OpCommon, // which GCOp doesn't use. LatestRev kbfsmd.Revision `codec:"r"` } func newGCOp(latestRev kbfsmd.Revision) *GCOp { gco := &GCOp{ LatestRev: latestRev, } return gco } func (gco *GCOp) deepCopy() op { gcoCopy := *gco gcoCopy.OpCommon = gco.OpCommon.deepCopy() return &gcoCopy } // SizeExceptUpdates implements op. func (gco *GCOp) SizeExceptUpdates() uint64 { return bpSize * uint64(len(gco.UnrefBlocks)) } func (gco *GCOp) allUpdates() []blockUpdate { return gco.Updates } func (gco *GCOp) checkValid() error { return gco.checkUpdatesValid() } func (gco *GCOp) String() string { return fmt.Sprintf("gc %d", gco.LatestRev) } // StringWithRefs implements the op interface for GCOp. func (gco *GCOp) StringWithRefs(indent string) string { res := gco.String() + "\n" res += gco.stringWithRefs(indent) return res } // checkConflict implements op. func (gco *GCOp) checkConflict( ctx context.Context, renamer ConflictRenamer, mergedOp op, isFile bool) (crAction, error) { return nil, nil } // getDefaultAction implements op. func (gco *GCOp) getDefaultAction(mergedPath path) crAction { return nil } // invertOpForLocalNotifications returns an operation that represents // an undoing of the effect of the given op. These are intended to be // used for local notifications only, and would not be useful for // finding conflicts (for example, we lose information about the type // of the file in a rmOp that we are trying to re-create). func invertOpForLocalNotifications(oldOp op) (newOp op, err error) { switch op := oldOp.(type) { default: panic(fmt.Sprintf("Unrecognized operation: %v", op)) case *createOp: newOp, err = newRmOp(op.NewName, op.Dir.Ref, op.Type) if err != nil { return nil, err } case *rmOp: // Guess at the type, shouldn't be used for local notification // purposes. newOp, err = newCreateOp(op.OldName, op.Dir.Ref, File) if err != nil { return nil, err } case *renameOp: newDirRef := op.NewDir.Ref if op.NewDir == (blockUpdate{}) { newDirRef = op.OldDir.Ref } newOp, err = newRenameOp(op.NewName, newDirRef, op.OldName, op.OldDir.Ref, op.Renamed, op.RenamedType) if err != nil { return nil, err } case *syncOp: // Just replay the writes; for notifications purposes, they // will do the right job of marking the right bytes as // invalid. so, err := newSyncOp(op.File.Ref) if err != nil { return nil, err } so.Writes = make([]WriteRange, len(op.Writes)) copy(so.Writes, op.Writes) newOp = so case *setAttrOp: newOp, err = newSetAttrOp(op.Name, op.Dir.Ref, op.Attr, op.File) if err != nil { return nil, err } case *GCOp: newOp = newGCOp(op.LatestRev) case *resolutionOp: newOp = newResolutionOp() case *rekeyOp: newOp = newRekeyOp() } // Now reverse all the block updates. Don't bother with bare Refs // and Unrefs since they don't matter for local notification // purposes. for _, update := range oldOp.allUpdates() { newOp.AddUpdate(update.Ref, update.Unref) } return newOp, nil } // NOTE: If you're updating opPointerizer and RegisterOps, make sure // to also update opPointerizerFuture and registerOpsFuture in // ops_test.go. // Our ugorji codec cannot decode our extension types as pointers, and // we need them to be pointers so they correctly satisfy the op // interface. So this function simply converts them into pointers as // needed. func opPointerizer(iface interface{}) reflect.Value { switch op := iface.(type) { default: return reflect.ValueOf(iface) case createOp: return reflect.ValueOf(&op) case rmOp: return reflect.ValueOf(&op) case renameOp: return reflect.ValueOf(&op) case syncOp: return reflect.ValueOf(&op) case setAttrOp: return reflect.ValueOf(&op) case resolutionOp: return reflect.ValueOf(&op) case rekeyOp: return reflect.ValueOf(&op) case GCOp: return reflect.ValueOf(&op) } } // RegisterOps registers all op types with the given codec. func RegisterOps(codec kbfscodec.Codec) { codec.RegisterType(reflect.TypeOf(createOp{}), createOpCode) codec.RegisterType(reflect.TypeOf(rmOp{}), rmOpCode) codec.RegisterType(reflect.TypeOf(renameOp{}), renameOpCode) codec.RegisterType(reflect.TypeOf(syncOp{}), syncOpCode) codec.RegisterType(reflect.TypeOf(setAttrOp{}), setAttrOpCode) codec.RegisterType(reflect.TypeOf(resolutionOp{}), resolutionOpCode) codec.RegisterType(reflect.TypeOf(rekeyOp{}), rekeyOpCode) codec.RegisterType(reflect.TypeOf(GCOp{}), gcOpCode) codec.RegisterIfaceSliceType(reflect.TypeOf(opsList{}), opsListCode, opPointerizer) } // pathSortedOps sorts the ops in increasing order by path length, so // e.g. file creates come before file modifies. type pathSortedOps []op func (pso pathSortedOps) Len() int { return len(pso) } func (pso pathSortedOps) Less(i, j int) bool { return len(pso[i].getFinalPath().path) < len(pso[j].getFinalPath().path) } func (pso pathSortedOps) Swap(i, j int) { pso[i], pso[j] = pso[j], pso[i] }
{ "content_hash": "bec5f6714169cb0e4d5b0e240d85e45a", "timestamp": "", "source": "github", "line_count": 1585, "max_line_length": 84, "avg_line_length": 27.50725552050473, "alnum_prop": 0.7049702974838873, "repo_name": "keybase/kbfs", "id": "409681c61d5b77cd581d4ef4e3d98ff1a21e4081", "size": "43750", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libkbfs/ops.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "107815" }, { "name": "Dockerfile", "bytes": "557" }, { "name": "Go", "bytes": "5754731" }, { "name": "JavaScript", "bytes": "4011" }, { "name": "Makefile", "bytes": "1242" }, { "name": "Shell", "bytes": "1704" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.AspNetCore.Server.IntegrationTesting; public static class Tfm { public const string Net462 = "net462"; public const string NetCoreApp20 = "netcoreapp2.0"; public const string NetCoreApp21 = "netcoreapp2.1"; public const string NetCoreApp22 = "netcoreapp2.2"; public const string NetCoreApp30 = "netcoreapp3.0"; public const string NetCoreApp31 = "netcoreapp3.1"; public const string Net50 = "net5.0"; public const string Net60 = "net6.0"; public const string Net70 = "net7.0"; public const string Default = Net70; public static bool Matches(string tfm1, string tfm2) { return string.Equals(tfm1, tfm2, StringComparison.OrdinalIgnoreCase); } }
{ "content_hash": "a506ec14685f64af1f9acc09cb525cb4", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 77, "avg_line_length": 37.56521739130435, "alnum_prop": 0.7210648148148148, "repo_name": "aspnet/AspNetCore", "id": "9d08a3bcae9e01ff9f12f2b2d8aedd836ffe74e7", "size": "866", "binary": false, "copies": "1", "ref": "refs/heads/darc-main-3ce916a7-9d9b-4849-8f14-6703adcb3cb2", "path": "src/Hosting/Server.IntegrationTesting/src/Common/Tfm.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "109" }, { "name": "Batchfile", "bytes": "19526" }, { "name": "C", "bytes": "213916" }, { "name": "C#", "bytes": "47455169" }, { "name": "C++", "bytes": "1900454" }, { "name": "CMake", "bytes": "7955" }, { "name": "CSS", "bytes": "62326" }, { "name": "Dockerfile", "bytes": "3584" }, { "name": "F#", "bytes": "7982" }, { "name": "Groovy", "bytes": "1529" }, { "name": "HTML", "bytes": "1130653" }, { "name": "Java", "bytes": "297552" }, { "name": "JavaScript", "bytes": "2726829" }, { "name": "Lua", "bytes": "4904" }, { "name": "Makefile", "bytes": "220" }, { "name": "Objective-C", "bytes": "222" }, { "name": "PowerShell", "bytes": "241706" }, { "name": "Python", "bytes": "19476" }, { "name": "Roff", "bytes": "6044" }, { "name": "Shell", "bytes": "142293" }, { "name": "Smalltalk", "bytes": "3" }, { "name": "TypeScript", "bytes": "797435" } ], "symlink_target": "" }
require "support/shared/integration/integration_helper" require "support/shared/context/config" require "chef/knife/cookbook_upload" describe "knife cookbook upload", :workstation do include IntegrationSupport include KnifeSupport include_context "default config options" let (:cb_dir) { "#{@repository_dir}/cookbooks" } when_the_chef_server "is empty" do when_the_repository "has a cookbook" do before do file "cookbooks/x/metadata.rb", cb_metadata("x", "1.0.0") end it "knife cookbook upload uploads the cookbook" do knife("cookbook upload x -o #{cb_dir}").should_succeed stderr: <<~EOM Uploading x [1.0.0] Uploaded 1 cookbook. EOM end it "knife cookbook upload --freeze uploads and freezes the cookbook" do knife("cookbook upload x -o #{cb_dir} --freeze").should_succeed stderr: <<~EOM Uploading x [1.0.0] Uploaded 1 cookbook. EOM # Modify the file, attempt to reupload file "cookbooks/x/metadata.rb", 'name "x"; version "1.0.0"#different' knife("cookbook upload x -o #{cb_dir} --freeze").should_fail stderr: <<~EOM Uploading x [1.0.0] ERROR: Version 1.0.0 of cookbook x is frozen. Use --force to override. WARNING: Not updating version constraints for x in the environment as the cookbook is frozen. ERROR: Failed to upload 1 cookbook. EOM end end when_the_repository "has a cookbook that depends on another cookbook" do before do file "cookbooks/x/metadata.rb", cb_metadata("x", "1.0.0", "\ndepends 'y'") file "cookbooks/y/metadata.rb", cb_metadata("y", "1.0.0") end it "knife cookbook upload --include-dependencies uploads both cookbooks" do knife("cookbook upload --include-dependencies x -o #{cb_dir}").should_succeed stderr: <<~EOM Uploading x [1.0.0] Uploading y [1.0.0] Uploaded 2 cookbooks. EOM end it "knife cookbook upload fails due to missing dependencies" do knife("cookbook upload x -o #{cb_dir}").should_fail stderr: <<~EOM Uploading x [1.0.0] ERROR: Cookbook x depends on cookbooks which are not currently ERROR: being uploaded and cannot be found on the server. ERROR: The missing cookbook(s) are: 'y' version '>= 0.0.0' EOM end it "knife cookbook upload -a uploads both cookbooks" do knife("cookbook upload -a -o #{cb_dir}").should_succeed stderr: <<~EOM Uploading x [1.0.0] Uploading y [1.0.0] Uploaded all cookbooks. EOM end end end end
{ "content_hash": "672c58a397161c7b6859bce4093c56c0", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 103, "avg_line_length": 37.67567567567568, "alnum_prop": 0.6025824964131994, "repo_name": "Tensibai/chef", "id": "7e98b6ea64cdc054bddba47b494841630becc2e6", "size": "3431", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/integration/knife/cookbook_upload_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2163" }, { "name": "Dockerfile", "bytes": "345" }, { "name": "HTML", "bytes": "45095" }, { "name": "Makefile", "bytes": "1326" }, { "name": "Perl", "bytes": "64" }, { "name": "PowerShell", "bytes": "18625" }, { "name": "Python", "bytes": "54260" }, { "name": "Roff", "bytes": "781" }, { "name": "Ruby", "bytes": "9568626" }, { "name": "Shell", "bytes": "28804" } ], "symlink_target": "" }
class PlayScreen final : public State { public: explicit PlayScreen(sf::RenderWindow& window); void handleEvent(sf::Event& e) override; void update(float delta) override; void draw(sf::RenderWindow& window) override; void updateOverlay(); private: Camera _camera; Map _map; // Testing (should use a MapHandler) Player _player; sf::Clock _overlayUpdate; std::shared_ptr<MapHandler> _mapHandler; };
{ "content_hash": "ef8a510bd53839b3d8d20d59de6949d5", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 50, "avg_line_length": 29.2, "alnum_prop": 0.6917808219178082, "repo_name": "hanselrd/bubble-warrior-adventures", "id": "e31967aa447d8431021f99502d71b06be1351c8e", "size": "561", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/PlayScreen.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "68127" }, { "name": "CMake", "bytes": "36079" }, { "name": "Python", "bytes": "1072" } ], "symlink_target": "" }
import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import registerI18n from '../../../support/register-i18n'; const { Object: EmberObject, run } = Ember; moduleForComponent('form-fields/checkbox-group', 'Integration | Component | {{form-fields/checkbox-group}}', { integration: true, setup() { this.set('object', { preferences: ['dogs'] }); this.set('options', ['dogs', 'cats']); } }); test('It renders a fieldset', function(assert) { this.render(hbs`{{form-fields/checkbox-group "preferences" object=object}}`); assert.equal(this.$('fieldset').length, 1); }); test('It adds a legend with the label text', function(assert) { this.render(hbs`{{form-fields/checkbox-group "preferences" object=object}}`); assert.equal(this.$('legend').text().trim(), 'Preferences'); }); test('It renders a list of checkboxes with label for each option', function(assert) { this.render(hbs`{{form-fields/checkbox-group "preferences" object=object options=options}}`); assert.equal(this.$('ul li label input[type="checkbox"]').length, 2); }); test('The selected options is checked', function(assert) { this.render(hbs`{{form-fields/checkbox-group "preferences" object=object options=options}}`); assert.equal(this.$('input[type="checkbox"]:checked').length, 1); assert.equal(this.$('input[type="checkbox"]:checked').val(), 'dogs'); }); test('Disabled true disables all checkboxes', function(assert) { this.render(hbs`{{form-fields/checkbox-group "gender" disabled=true object=object options=options}}`); assert.equal(this.$('input[type="checkbox"]:disabled').length, 2); }); test('Clicking a checkbox updates the property', function(assert) { this.render(hbs`{{form-fields/checkbox-group "preferences" object=object options=options}}`); run(() => this.$('input:eq(1)').click()); assert.equal(this.$('input[type="checkbox"]:checked').length, 2); assert.deepEqual(this.get('object.preferences'), ['dogs', 'cats']); run(() => this.$('input:eq(0)').click()); assert.equal(this.$('input[type="checkbox"]:checked').length, 1); assert.deepEqual(this.get('object.preferences'), ['cats']); }); test('The labels are computed from the i18n service if available', function(assert) { assert.expect(2); registerI18n(this, EmberObject.extend({ t(key) { return key; } })); this.render(hbs`{{form-fields/checkbox-group "preferences" object=object options=options}}`); assert.equal(this.$('label').eq(0).text().trim(), 'preferences.dogs'); assert.equal(this.$('label').eq(1).text().trim(), 'preferences.cats'); });
{ "content_hash": "2649e4dc72c80b8ab1489b0d03c655d4", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 110, "avg_line_length": 38.34782608695652, "alnum_prop": 0.6836734693877551, "repo_name": "martndemus/ember-form-for", "id": "7654183c2baccc485b4125865ed6f725003b5eb2", "size": "2646", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/integration/components/form-fields/checkbox-group-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3363" }, { "name": "HTML", "bytes": "17713" }, { "name": "JavaScript", "bytes": "95411" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2010 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" style="@style/RtlOverlay.Widget.AppCompat.ActionBar.TitleItem"> <TextView android:id="@+id/action_bar_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="end" /> <TextView android:id="@+id/action_bar_subtitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="@dimen/abc_action_bar_subtitle_top_margin_material" android:singleLine="true" android:ellipsize="end" android:visibility="gone" /> </LinearLayout> <!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/mnc-sdk-release/frameworks/support/v7/appcompat/res/layout/abc_action_bar_title_item.xml --><!-- From: file:/C:/Users/Srdjan/AndroidStudioProjects/StudentProjekt/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/layout/abc_action_bar_title_item.xml -->
{ "content_hash": "f053fff49b2393cb6b7133927e1cc6d3", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 407, "avg_line_length": 56.91428571428571, "alnum_prop": 0.6852409638554217, "repo_name": "SrdjanCosicPrica/Google-Maps-Simple-Guide", "id": "bd4792140914d1d95a51abd93e00ab2d268d3283", "size": "1992", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/build/intermediates/res/merged/debug/layout/abc_action_bar_title_item.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1923428" } ], "symlink_target": "" }
<?php namespace JetMinds\Job\Controllers; use Flash; use BackendMenu; use Backend\Classes\Controller; use JetMinds\Job\Models\Category; /** * Categories Back-end Controller */ class Categories extends Controller { public $implement = [ 'Backend.Behaviors.FormController', 'Backend.Behaviors.ListController', 'Backend.Behaviors.ReorderController', ]; public $formConfig = 'config_form.yaml'; public $listConfig = 'config_list.yaml'; public $reorderConfig = 'config_reorder.yaml'; public $requiredPermissions = ['jetminds.job.access_categories']; public function __construct() { parent::__construct(); BackendMenu::setContext('JetMinds.Job', 'job', 'categories'); } public function index_onDelete() { if (($checkedIds = post('checked')) && is_array($checkedIds) && count($checkedIds)) { foreach ($checkedIds as $categoryId) { if ((!$category = Category::find($categoryId))) continue; $category->delete(); } Flash::success('Successfully deleted those categories.'); } return $this->listRefresh(); } }
{ "content_hash": "a3e26bb86340f09ecc6aba52e7462ce1", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 93, "avg_line_length": 25.229166666666668, "alnum_prop": 0.6118909991742362, "repo_name": "jetmindsgroup/job-plugin", "id": "0b6379fec6e4e960338697a2f8c94d6b5d13f50d", "size": "1211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "controllers/Categories.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "234" }, { "name": "HTML", "bytes": "32985" }, { "name": "JavaScript", "bytes": "592" }, { "name": "PHP", "bytes": "70256" } ], "symlink_target": "" }
package gui.transaction; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Toolkit; import java.util.ArrayList; import java.util.List; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import qora.crypto.Base58; import qora.transaction.ArbitraryTransaction; import utils.DateTimeFormat; @SuppressWarnings("serial") public class ArbitraryTransactionDetailsFrame extends JFrame { public ArbitraryTransactionDetailsFrame(ArbitraryTransaction arbitraryTransaction) { super("Qora - Transaction Details"); //ICON List<Image> icons = new ArrayList<Image>(); icons.add(Toolkit.getDefaultToolkit().getImage("images/icons/icon16.png")); icons.add(Toolkit.getDefaultToolkit().getImage("images/icons/icon32.png")); icons.add(Toolkit.getDefaultToolkit().getImage("images/icons/icon64.png")); icons.add(Toolkit.getDefaultToolkit().getImage("images/icons/icon128.png")); this.setIconImages(icons); //CLOSE setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //LAYOUT this.setLayout(new GridBagLayout()); //PADDING ((JComponent) this.getContentPane()).setBorder(new EmptyBorder(5, 5, 5, 5)); //LABEL GBC GridBagConstraints labelGBC = new GridBagConstraints(); labelGBC.insets = new Insets(0, 5, 5, 0); labelGBC.fill = GridBagConstraints.HORIZONTAL; labelGBC.anchor = GridBagConstraints.NORTHWEST; labelGBC.weightx = 0; labelGBC.gridx = 0; //DETAIL GBC GridBagConstraints detailGBC = new GridBagConstraints(); detailGBC.insets = new Insets(0, 5, 5, 0); detailGBC.fill = GridBagConstraints.HORIZONTAL; detailGBC.anchor = GridBagConstraints.NORTHWEST; detailGBC.weightx = 1; detailGBC.gridwidth = 2; detailGBC.gridx = 1; //LABEL TYPE labelGBC.gridy = 0; JLabel typeLabel = new JLabel("Type:"); this.add(typeLabel, labelGBC); //TYPE detailGBC.gridy = 0; JLabel type = new JLabel("Arbitrary Transaction"); this.add(type, detailGBC); //LABEL SIGNATURE labelGBC.gridy = 1; JLabel signatureLabel = new JLabel("Signature:"); this.add(signatureLabel, labelGBC); //SIGNATURE detailGBC.gridy = 1; JTextField signature = new JTextField(Base58.encode(arbitraryTransaction.getSignature())); signature.setEditable(false); this.add(signature, detailGBC); //LABEL REFERENCE labelGBC.gridy = 2; JLabel referenceLabel = new JLabel("Reference:"); this.add(referenceLabel, labelGBC); //REFERENCE detailGBC.gridy = 2; JTextField reference = new JTextField(Base58.encode(arbitraryTransaction.getReference())); reference.setEditable(false); this.add(reference, detailGBC); //LABEL TIMESTAMP labelGBC.gridy = 3; JLabel timestampLabel = new JLabel("Timestamp:"); this.add(timestampLabel, labelGBC); //TIMESTAMP detailGBC.gridy = 3; JLabel timestamp = new JLabel(DateTimeFormat.timestamptoString(arbitraryTransaction.getTimestamp())); this.add(timestamp, detailGBC); //LABEL SENDER labelGBC.gridy = 4; JLabel senderLabel = new JLabel("Creator:"); this.add(senderLabel, labelGBC); //SENDER detailGBC.gridy = 4; JTextField sender = new JTextField(arbitraryTransaction.getCreator().getAddress()); sender.setEditable(false); this.add(sender, detailGBC); //LABEL SERVICE labelGBC.gridy = 5; JLabel serviceLabel = new JLabel("Service ID:"); this.add(serviceLabel, labelGBC); //SERVICE detailGBC.gridy = 5; JTextField service = new JTextField(String.valueOf(arbitraryTransaction.getService())); service.setEditable(false); this.add(service, detailGBC); //LABEL FEE labelGBC.gridy = 6; JLabel feeLabel = new JLabel("Fee:"); this.add(feeLabel, labelGBC); //FEE detailGBC.gridy = 6; JTextField fee = new JTextField(arbitraryTransaction.getFee().toPlainString()); fee.setEditable(false); this.add(fee, detailGBC); //LABEL CONFIRMATIONS labelGBC.gridy = 7; JLabel confirmationsLabel = new JLabel("Confirmations:"); this.add(confirmationsLabel, labelGBC); //CONFIRMATIONS detailGBC.gridy = 7; JLabel confirmations = new JLabel(String.valueOf(arbitraryTransaction.getConfirmations())); this.add(confirmations, detailGBC); //PACK this.pack(); this.setResizable(false); this.setLocationRelativeTo(null); this.setVisible(true); } }
{ "content_hash": "1e1a89edc932d1edb815c107f41e778f", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 103, "avg_line_length": 29.477124183006534, "alnum_prop": 0.7252771618625277, "repo_name": "Bitcoinsulting/Qora", "id": "fa6348bb1fb0ac20cce374dc03dbaa25045202cd", "size": "4510", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Qora/src/gui/transaction/ArbitraryTransactionDetailsFrame.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "199489" }, { "name": "CSS", "bytes": "24240" }, { "name": "HTML", "bytes": "257977" }, { "name": "Java", "bytes": "2205104" }, { "name": "JavaScript", "bytes": "118081" }, { "name": "Shell", "bytes": "1257" } ], "symlink_target": "" }
exclude :test_establish_connection_using_3_levels_config, 'tries to load SQLite3 driver' exclude :test_establish_connection_using_3_levels_config_with_shards_and_replica, 'tries to load SQLite3 driver' exclude :test_establishing_a_connection_in_connected_to_block_uses_current_role_and_shard, 'tries to load SQLite3 driver' exclude :test_retrieves_proper_connection_with_nested_connected_to, 'tries to load SQLite3 driver' exclude :test_same_shards_across_clusters, 'tries to load SQLite3 driver' exclude :test_sharding_separation, 'tries to load SQLite3 driver' exclude :test_swapping_granular_shards_and_roles_in_a_multi_threaded_environment, 'tries to load SQLite3 driver' exclude :test_swapping_shards_and_roles_in_a_multi_threaded_environment, 'tries to load SQLite3 driver' exclude :test_swapping_shards_globally_in_a_multi_threaded_environment, 'tries to load SQLite3 driver' exclude :test_switching_connections_via_handler, 'tries to load SQLite3 driver'
{ "content_hash": "73d06e4bbc939432854c067a6041c484", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 121, "avg_line_length": 96.3, "alnum_prop": 0.8110072689511942, "repo_name": "bruceadams/activerecord-jdbc-adapter", "id": "40e0d744f7fa6fac9c48fba310f6a5db23dd9e01", "size": "1147", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "test/rails/excludes/mysql2/ActiveRecord/ConnectionAdapters/ConnectionHandlersShardingDbTest.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "112676" }, { "name": "Ruby", "bytes": "333791" }, { "name": "Shell", "bytes": "259" } ], "symlink_target": "" }
require 'spec_helper' require 'json' describe 'an API token' do include Rack::Test::Methods context 'with a valid user' do before :all do new_database end it 'requires authentication' do post_json '/token/admin', '{}' expect(last_response.status).to eq(401) end it 'returns an API token' do authorize 'admin', 'password' post_json '/token/admin', '{}' expect(last_response.status).to eq(200) res_json = JSON.parse(last_response.body) expect(res_json).to match('token' => /\A(.*)\.(.*)\.(.*)\z/) end it 'honors valid claims in the token' do nbf = 1_577_836_800 exp = 1_893_456_000 claims = { 'nbf' => nbf, 'exp' => exp } authorize 'admin', 'password' post_json '/token/admin', claims.to_json expect(last_response.status).to eq(200) res_json = JSON.parse(last_response.body) expect(res_json).to match('token' => /\A(.*)\.(.*)\.(.*)\z/) # Decode the 'claims' section of the token match = res_json['token'].match(/\A(.*)\.(.*)\.(.*)\z/) # res_header = match[1] res_claims = match[2] # res_signature = match[3] # nbf & exp should be the same as the request claims = JSON.parse(Base64.decode64(res_claims)) expect(claims).to eq('nbf' => nbf, 'exp' => exp, 'sub' => 'admin') end it 'sets the exp claim if none is given' do nbf = 1_577_836_800 claims = { 'nbf' => nbf } authorize 'admin', 'password' post_json '/token/admin', claims.to_json expect(last_response.status).to eq(200) res_json = JSON.parse(last_response.body) expect(res_json).to match('token' => /\A(.*)\.(.*)\.(.*)\z/) # Decode the 'claims' section of the token match = res_json['token'].match(/\A(.*)\.(.*)\.(.*)\z/) # res_header = match[1] res_claims = match[2] # res_signature = match[3] # nbf & exp should be the same as the request claims = JSON.parse(Base64.decode64(res_claims)) expect(claims).to match('nbf' => nbf, 'exp' => a_kind_of(Integer), 'sub' => 'admin') end it 'strips claims' do claims = { 'iss' => 'test', 'aud' => 'test', 'jti' => 'test', 'iat' => 'test', 'sub' => 'test' } authorize 'admin', 'password' post_json '/token/admin', claims.to_json expect(last_response.status).to eq(200) res_json = JSON.parse(last_response.body) expect(res_json).to match('token' => /\A(.*)\.(.*)\.(.*)\z/) # Decode the 'claims' section of the token match = res_json['token'].match(/\A(.*)\.(.*)\.(.*)\z/) # res_header = match[1] res_claims = match[2] # res_signature = match[3] # All of the claims given in the initial request should have been # stripped claims = JSON.parse(Base64.decode64(res_claims)) expect(claims).to match('sub' => 'admin', 'exp' => a_kind_of(Integer)) end end end
{ "content_hash": "2b71b3b7139a1e0317201e35dde26cad", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 90, "avg_line_length": 31.051546391752577, "alnum_prop": 0.5517928286852589, "repo_name": "Cyclid/Cyclid", "id": "da5ba57200cd90c4c4bb9136f367a2ace30240a8", "size": "3042", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/api/auth_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1788" }, { "name": "Ruby", "bytes": "505770" } ], "symlink_target": "" }
package de.hshannover.f4.trust.ifmapj.metadata; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.StringWriter; import java.util.Arrays; import java.util.Iterator; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import util.CanonicalXML; import de.hshannover.f4.trust.ifmapj.binding.IfmapStrings; import de.hshannover.f4.trust.ifmapj.log.IfmapJLog; /** * Factory for {@link Metadata} wrapper instances. */ public class MetadataWrapper { private static final XPathFactory XPATH_FACTORY = XPathFactory.newInstance(); private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance(); /** * Default namespace context which uses the prefixes 'meta' and 'ifmap' * as specified in TNC IF-MAP Binding for SOAP version 2.2. */ public static final NamespaceContext DEFAULT_NAMESPACE_CONTEXT = new NamespaceContext() { @Override public Iterator getPrefixes(String namespaceURI) { return Arrays.asList( IfmapStrings.STD_METADATA_PREFIX, IfmapStrings.BASE_PREFIX) .iterator(); } @Override public String getPrefix(String namespaceURI) { if (namespaceURI.equals(IfmapStrings.STD_METADATA_NS_URI)) { return IfmapStrings.STD_METADATA_PREFIX; } else if (namespaceURI.equals(IfmapStrings.BASE_NS_URI)) { return IfmapStrings.BASE_PREFIX; } else { return null; } } @Override public String getNamespaceURI(String prefix) { if (prefix.equals(IfmapStrings.STD_METADATA_PREFIX)) { return IfmapStrings.STD_METADATA_NS_URI; } else if (prefix.equals(IfmapStrings.BASE_PREFIX)) { return IfmapStrings.BASE_NS_URI; } else { return XMLConstants.NULL_NS_URI; } } }; /** * Create a {@link Metadata} instance for the given document. * * @param document a metadata document * @return the wrapped metadata */ public static Metadata metadata(Document document) { try { Transformer printFormatTransformer = TRANSFORMER_FACTORY.newTransformer(); printFormatTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); printFormatTransformer.setOutputProperty(OutputKeys.METHOD, "xml"); printFormatTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); printFormatTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); printFormatTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Transformer equalsTransformer = TRANSFORMER_FACTORY.newTransformer(); equalsTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); equalsTransformer.setOutputProperty(OutputKeys.INDENT, "no"); equalsTransformer.setOutputProperty(OutputKeys.METHOD, "xml"); XPath xPath = XPATH_FACTORY.newXPath(); return new MetadataWrapperImpl( document, xPath, printFormatTransformer, DEFAULT_NAMESPACE_CONTEXT, equalsTransformer); } catch (TransformerConfigurationException e) { throw new RuntimeException(e); } } /** * Wrapper implementation which uses {@link XPath} to extract values * from {@link Document} instances. */ private static class MetadataWrapperImpl implements Metadata { // TODO add lazy initialized attributes for publisherId, publishTimestamp, ... final Document mDocument; final XPath mXpath; final Transformer mPrintTransformer; final Transformer mEqualsTransformer; /** * Create a wrapper instance for the given document. * * @param document the document to wrap * @param xpath the XPATH instance for this wrapper * @param printFormatTransformer the transformer to use for pretty printing * @param namespaceContext the namespace context for XPath operations * @param equalsTransformer the transformer to use for canonical serialization */ public MetadataWrapperImpl( Document document, XPath xpath, Transformer printFormatTransformer, NamespaceContext namespaceContext, Transformer equalsTransformer) { mDocument = document; mXpath = xpath; mPrintTransformer = printFormatTransformer; mXpath.setNamespaceContext(namespaceContext); mEqualsTransformer = equalsTransformer; } /* * Evaluate the given XPATH expression on the given document. Return * the result as a string or null if an error occurred. */ private String getValueFromExpression(String expression, Document doc) { try { return mXpath.evaluate(expression, mDocument.getDocumentElement()); } catch (XPathExpressionException e) { IfmapJLog.error("could not evaluate '" + expression + "' on '" + mDocument + "'"); return null; } } @Override public String getPublisherId() { return getValueFromExpression("/*/@ifmap-publisher-id", mDocument); } @Override public String getPublishTimestamp() { return getValueFromExpression("/*/@ifmap-timestamp", mDocument); } @Override public double getPublishTimestampFraction() { String fractionString = getValueFromExpression( "/*/@ifmap-timestamp-fraction", mDocument); try { return Double.parseDouble(fractionString); } catch (NumberFormatException e) { return 0.0; } } @Override public String getTypename() { return getValueFromExpression("name(/*)", mDocument); } @Override public String getLocalname() { return getValueFromExpression("local-name(/*)", mDocument); } @Override public String getCardinality() { return getValueFromExpression("/*/@ifmap-cardinality", mDocument); } @Override public boolean isSingleValue() { return getCardinality().equals("singleValue"); } @Override public boolean isMultiValue() { return getCardinality().equals("multiValue"); } @Override public String getValueForXpathExpression(String xPathExpression) { return getValueFromExpression(xPathExpression, mDocument); } @Override public String getValueForXpathExpressionOrElse(String xPathExpression, String defaultValue) { String result = getValueForXpathExpression(xPathExpression); if (result == null) { return defaultValue; } else { return result; } } @Override public String toFormattedString() { StringWriter writer = new StringWriter(); try { mPrintTransformer.transform( new DOMSource(mDocument), new StreamResult(writer)); } catch (TransformerException e) { throw new RuntimeException(e); } return writer.toString(); } @Override public void setNamespaceContext(NamespaceContext context) { mXpath.setNamespaceContext(context); } private String toCanonicalXml() { try { XMLReader reader = XMLReaderFactory.createXMLReader(); DOMSource domSource = new DOMSource(mDocument.getFirstChild()); ByteArrayOutputStream byteArrayOutput = new ByteArrayOutputStream(); Result result = new StreamResult(byteArrayOutput); mEqualsTransformer.transform(domSource, result); ByteArrayInputStream byteArrayInput = new ByteArrayInputStream(byteArrayOutput.toByteArray()); InputSource input = new InputSource(byteArrayInput); CanonicalXML canonicalXml = new CanonicalXML(); return canonicalXml.toCanonicalXml2(reader, input, true); } catch (Exception e) { throw new RuntimeException(e); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + toCanonicalXml().hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MetadataWrapperImpl other = (MetadataWrapperImpl) obj; return other.toCanonicalXml().equals(toCanonicalXml()); } } }
{ "content_hash": "fc100106e9961fd3bcf1d870152fdd4d", "timestamp": "", "source": "github", "line_count": 279, "max_line_length": 98, "avg_line_length": 29.82078853046595, "alnum_prop": 0.7409855769230769, "repo_name": "trustathsh/ifmapj", "id": "aee2e9c2438cdb357ded5ff56993446349622d23", "size": "9774", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/de/hshannover/f4/trust/ifmapj/metadata/MetadataWrapper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "902" }, { "name": "Java", "bytes": "824997" } ], "symlink_target": "" }
Crypt Component =============== The `Crypt` component provides methods for generating random numbers and strings, also, password hashing and password hash verification and methods for encryption and decryption of strings. Internally it uses cryptographically secure methods. **Disclaimer:** The library was not reviewed by a security expert. Install the component --------------------- The best way to install the component is using Composer. This library requires that you also add a repository to your composer.json file. ```bash composer require webiny/crypt ``` For additional versions of the package, visit the [Packagist page](https://packagist.org/packages/webiny/crypt). ## Using Crypt ```php class MyClass { use Webiny\Component\Crypt\CryptTrait; function myMethod() { $this->crypt()->encrypt('to encrypt', 'secret key'); } } ``` ## Generate random integers To generate a random integer you just have to pass the range to the `Crypt` instance: ```php $randomInt = $crypt->generateRandomInt(10, 20); // e.g. 15 ``` ## Generate random strings When you want to generate random string, you have several options. You can call the general `generateRandomString` method, or you can call `generateUserReadableString` method to get a more user-readable string that doesn't contain any special characters. There is also a method called `generateHardReadableString` that, among letters and numbers, uses special characters to make the string more "harder". Here are a few examples: ```php // generate a string from a defined set of characters $randomString = $crypt->generateRandomString(5, 'abc'); // e.g. cabcc // generate a string that contains only letters (lower & upper case and numbers) $randomString = $crypt->generateUserReadableString(5); // A12uL // generate a string that can contain special characters $randomString = $crypt->generateHardReadableString(5); // &"!3g ``` ## Password hashing and validation ```php // hash password $passwordHash = $crypt->createPasswordHash('login123'); // $2y$08$GgGha6bh53ofEPnBawShwO5FA3Q8ImvPXjJzh662/OAWkjeejAJKa // (on login page) verify the hash with the correct password $passwordsMatch = $crypt->verifyPasswordHash('login123', $passwordHash); // true or false ``` ## Encrypting and decrypting strings ```php // encrypt it $encrypted = $crypt->encrypt('some data', 'abcdefgh12345678'); // decrypt it $decrypted = $crypt->decrypt($result, 'abcdefgh12345678'); // "some data" ``` ## Crypt config There are three different internal crypt libraries that you can choose from: 1. **OpenSSL** - this is the default library 2. **Sodium** - library that utilizes [paragonie/halite](https://github.com/paragonie/halite) internally for password hashing, password verification, encryption and decryption. Please note that this library is highly CPU intensive. 3. **Mcrypt** - this is the **depricated** library which will be removed once we hit PHP v7.2 To switch between libraries, just set a different `Bridge` in your configuration: ```yaml Crypt: Bridge: \Webiny\Component\Crypt\Bridge\Sodium\Crypt ``` and then in your code just call: ```php \Webiny\Components\Crypt\Crypt::setConfig($pathToYourYaml); ``` ## Custom `Crypt` driver To create a custom `Crypt` driver, first you need to create a class that implements `\Webiny\Component\Crypt\Bridge\CryptInterface`. Once you have implemented all the requested methods, you now need to change the `Bridge` path inside your component configuration. Resources --------- To run unit tests, you need to use the following command: $ cd path/to/Webiny/Component/Crypt/ $ composer.phar install $ phpunit
{ "content_hash": "f0517fcb0432eefb48911da97123d947", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 232, "avg_line_length": 32.38260869565217, "alnum_prop": 0.7306659505907627, "repo_name": "Webiny/Framework", "id": "d0d0f1b399d9700a8dd24b52c583ba2c70a8ff15", "size": "3724", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Webiny/Component/Crypt/README.md", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "1688131" }, { "name": "Smarty", "bytes": "964" } ], "symlink_target": "" }
package com.stratio.sparta.serving.api.helpers import akka.actor.{ActorRef, ActorSystem, Props} import akka.event.slf4j.SLF4JLogging import akka.io.IO import com.stratio.sparta.driver.service.StreamingContextService import com.stratio.sparta.serving.api.actor._ import com.stratio.sparta.serving.core.actor.StatusActor.AddClusterListeners import com.stratio.sparta.serving.core.actor.{FragmentActor, RequestActor, StatusActor} import com.stratio.sparta.serving.core.config.SpartaConfig import com.stratio.sparta.serving.core.constants.AkkaConstant._ import com.stratio.sparta.serving.core.curator.CuratorFactoryHolder import spray.can.Http import scala.util.{Failure, Success, Try} /** * Helper with common operations used to create a Sparta context used to run the application. */ object SpartaHelper extends SLF4JLogging { implicit var system: ActorSystem = _ /** * Initializes Sparta's akka system running an embedded http server with the REST API. * * @param appName with the name of the application. */ def initSpartaAPI(appName: String): Unit = { if (SpartaConfig.mainConfig.isDefined && SpartaConfig.apiConfig.isDefined) { val curatorFramework = CuratorFactoryHolder.getInstance() log.info("Initializing Sparta Actors System ...") system = ActorSystem(appName, SpartaConfig.mainConfig) val statusActor = system.actorOf(Props(new StatusActor(curatorFramework)), StatusActorName) val fragmentActor = system.actorOf(Props(new FragmentActor(curatorFramework)), FragmentActorName) val policyActor = system.actorOf(Props(new PolicyActor(curatorFramework, statusActor)), PolicyActorName) val executionActor = system.actorOf(Props(new RequestActor(curatorFramework)), ExecutionActorName) val streamingContextService = StreamingContextService(curatorFramework, SpartaConfig.mainConfig) val streamingContextActor = system.actorOf(Props( new LauncherActor(streamingContextService, curatorFramework)), LauncherActorName) val pluginActor = system.actorOf(Props(new PluginActor()), PluginActorName) val driverActor = system.actorOf(Props(new DriverActor()), DriverActorName) val actors = Map( StatusActorName -> statusActor, FragmentActorName -> fragmentActor, PolicyActorName -> policyActor, LauncherActorName -> streamingContextActor, PluginActorName -> pluginActor, DriverActorName -> driverActor, ExecutionActorName -> executionActor ) val controllerActor = system.actorOf(Props(new ControllerActor(actors, curatorFramework)), ControllerActorName) if (isHttpsEnabled) loadSpartaWithHttps(controllerActor) else loadSpartaWithHttp(controllerActor) statusActor ! AddClusterListeners } else log.info("Sparta Configuration is not defined") } def loadSpartaWithHttps(controllerActor: ActorRef): Unit = { import com.stratio.sparkta.serving.api.ssl.SSLSupport._ IO(Http) ! Http.Bind(controllerActor, interface = SpartaConfig.apiConfig.get.getString("host"), port = SpartaConfig.apiConfig.get.getInt("port") ) log.info("Sparta Actors System initiated correctly") } def loadSpartaWithHttp(controllerActor: ActorRef): Unit = { IO(Http) ! Http.Bind(controllerActor, interface = SpartaConfig.apiConfig.get.getString("host"), port = SpartaConfig.apiConfig.get.getInt("port") ) log.info("Sparta Actors System initiated correctly") } def isHttpsEnabled: Boolean = SpartaConfig.getSprayConfig match { case Some(config) => Try(config.getValue("ssl-encryption")) match { case Success(value) => "on".equals(value.unwrapped()) case Failure(e) => log.error("Incorrect value in ssl-encryption option, setting https disabled", e) false } case None => log.warn("Impossible to get spray config, setting https disabled") false } }
{ "content_hash": "3632a631b8ebb5a97d9ea89b019420ed", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 117, "avg_line_length": 41.89473684210526, "alnum_prop": 0.7344221105527639, "repo_name": "diegohurtado/sparta", "id": "8a52a8e2f69f0741e663b8c4373114394204585f", "size": "4599", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "serving-api/src/main/scala/com/stratio/sparta/serving/api/helpers/SpartaHelper.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "24139" }, { "name": "CSS", "bytes": "186353" }, { "name": "Gherkin", "bytes": "302566" }, { "name": "HTML", "bytes": "212757" }, { "name": "Java", "bytes": "83195" }, { "name": "JavaScript", "bytes": "879977" }, { "name": "Scala", "bytes": "1164916" }, { "name": "Shell", "bytes": "54974" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "cea63c751ec8d497a14b84541f2827d5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "54b87d16a82d255a52f5718b15e4a5966d24de35", "size": "192", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Bacillariophyta/Bacillariophyceae/Cymbellales/Cymbellaceae/Encyonopsis/Encyonopsis perfloridana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace core\http; /** * HTTPSession - not yet implemented * * @author user */ class HTTPSession { public function get($key) { $session = $_SESSION; return $session[$key]; } public function set($key, $value) { $_SESSION[$key] = $value; } }
{ "content_hash": "755a7c8a071e990171d8422beb6899d7", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 39, "avg_line_length": 12.5, "alnum_prop": 0.5466666666666666, "repo_name": "dmeikle/gossamerCMS-v3", "id": "35e6e8ff3315da13874ec9b1ac72028b6e9cc6ed", "size": "576", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/framework/core/http/HTTPSession.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6169" }, { "name": "HTML", "bytes": "1387" }, { "name": "JavaScript", "bytes": "50158" }, { "name": "PHP", "bytes": "905324" } ], "symlink_target": "" }
var clickoutside = { bind (el, binding, vnode) { binding._documentHandler = function (e) { if (el.contains(e.target)) { return false; } if (binding.expression) { vnode.context[binding.expression](); } }; document.addEventListener('click', binding._documentHandler); }, update () { }, unbind (el, binding) { document.removeEventListener('click', binding._documentHandler); } } export default clickoutside;
{ "content_hash": "9710b4de9a5ffab39823320d1478c50a", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 72, "avg_line_length": 25.80952380952381, "alnum_prop": 0.540590405904059, "repo_name": "qinshenxue/vui", "id": "df24db727b3cd9d0e3ed4ae4a2111680966e1450", "size": "542", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/directives/clickoutside.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "55965" }, { "name": "HTML", "bytes": "887" }, { "name": "JavaScript", "bytes": "16771" }, { "name": "Vue", "bytes": "48864" } ], "symlink_target": "" }
var area = getArea(); var kanaHandler = getKanaHandler(); var results = JSON.parse(sessionStorage.getItem(area+"-results")); $("#kana-back-button").click(function(){ window.location.replace(ROOT_DIR+"kana/"+area+"/trainer"); }); // sort results array by percentage correct ASC results.sort(function(a,b){ return a.correct/a.prompted - b.correct/b.prompted; }); for (i=0; i<results.length; i++) { var percentage = Math.round((results[i].correct / results[i].prompted)*100); var progressBarClass; if (percentage>=80) { progressBarClass = 'progress-bar-success'; } else if (percentage>=50) { progressBarClass = 'progress-bar-warning'; } else { progressBarClass = 'progress-bar-danger'; } var width = (percentage>=20) ? percentage : 20; var colSymbol = '<td><span class="h3">'+results[i].question+'</td>'; var colScore = '<td>'+results[i].correct+'/'+results[i].prompted+'</td>'; var colPercentage = '<td><div class="progress-bar '+progressBarClass+'" role="progressbar" aria-valuenow="'+percentage+'" aria-valuemin="0" aria-valuemax="100" style="width: '+width+'%">'+percentage+' %</div></td>'; var row = '<tr>'+colSymbol+colScore+colPercentage+'</tr>'; $(row).appendTo($("#kanaResultsTable tbody")); }
{ "content_hash": "31a0e43a9d671cbd3eb8bbb50a56a824", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 217, "avg_line_length": 36.6764705882353, "alnum_prop": 0.6696070569366479, "repo_name": "stoeffu/hiragana.ch", "id": "a39380cd7527fb3ad885551d856467da06a838a3", "size": "1247", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/js/kana/kanaresults.controller.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "289" }, { "name": "CSS", "bytes": "7578" }, { "name": "HTML", "bytes": "35421" }, { "name": "JavaScript", "bytes": "38335" }, { "name": "PHP", "bytes": "121737" } ], "symlink_target": "" }
// // FlickrExport.cs // // Author: // Lorenzo Milesi <maxxer@yetopen.it> // Stephane Delcroix <stephane@delcroix.org> // // Copyright (C) 2008-2009 Novell, Inc. // Copyright (C) 2008-2009 Lorenzo Milesi // Copyright (C) 2008-2009 Stephane Delcroix // // 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 FlickrNet; using System; using System.Collections; using System.IO; using System.Threading; using Mono.Unix; using FSpot; using FSpot.Core; using FSpot.Filters; using FSpot.Widgets; using FSpot.Utils; using FSpot.UI.Dialog; using Hyena; using Hyena.Widgets; using GtkBeans; namespace FSpot.Exporters.Flickr { public class TwentyThreeHQExport : FlickrExport { public override void Run (IBrowsableCollection selection) { Run (SupportedService.TwentyThreeHQ, selection, false); } } public class ZooomrExport : FlickrExport { public override void Run (IBrowsableCollection selection) { Run (SupportedService.Zooomr, selection, false); } } public class FlickrExport : FSpot.Extensions.IExporter { IBrowsableCollection selection; [GtkBeans.Builder.Object] Gtk.Dialog dialog; [GtkBeans.Builder.Object] Gtk.CheckButton scale_check; [GtkBeans.Builder.Object] Gtk.CheckButton tag_check; [GtkBeans.Builder.Object] Gtk.CheckButton hierarchy_check; [GtkBeans.Builder.Object] Gtk.CheckButton ignore_top_level_check; [GtkBeans.Builder.Object] Gtk.CheckButton open_check; [GtkBeans.Builder.Object] Gtk.SpinButton size_spin; [GtkBeans.Builder.Object] Gtk.ScrolledWindow thumb_scrolledwindow; [GtkBeans.Builder.Object] Gtk.Button auth_flickr; [GtkBeans.Builder.Object] Gtk.ProgressBar used_bandwidth; [GtkBeans.Builder.Object] Gtk.Button do_export_flickr; [GtkBeans.Builder.Object] Gtk.Label auth_label; [GtkBeans.Builder.Object] Gtk.RadioButton public_radio; [GtkBeans.Builder.Object] Gtk.CheckButton family_check; [GtkBeans.Builder.Object] Gtk.CheckButton friend_check; private GtkBeans.Builder builder; private string dialog_name = "flickr_export_dialog"; System.Threading.Thread command_thread; ThreadProgressDialog progress_dialog; ProgressItem progress_item; public const string EXPORT_SERVICE = "flickr/"; public const string SCALE_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "scale"; public const string SIZE_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "size"; public const string BROWSER_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "browser"; public const string TAGS_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "tags"; public const string PUBLIC_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "public"; public const string FAMILY_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "family"; public const string FRIENDS_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "friends"; public const string TAG_HIERARCHY_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "tag_hierarchy"; public const string IGNORE_TOP_LEVEL_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "ignore_top_level"; bool open; bool scale; bool is_public; bool is_friend; bool is_family; string token; int photo_index; int size; Auth auth; FlickrRemote fr; private FlickrRemote.Service current_service; string auth_text; private State state; private enum State { Disconnected, Connected, InAuth, Authorized } private State CurrentState { get { return state; } set { switch (value) { case State.Disconnected: auth_label.Text = auth_text; auth_flickr.Sensitive = true; do_export_flickr.Sensitive = false; auth_flickr.Label = Catalog.GetString ("Authorize"); used_bandwidth.Visible = false; break; case State.Connected: auth_flickr.Sensitive = true; do_export_flickr.Sensitive = false; auth_label.Text = string.Format (Catalog.GetString ("Return to this window after you have finished the authorization process on {0} and click the \"Complete Authorization\" button below"), current_service.Name); auth_flickr.Label = Catalog.GetString ("Complete Authorization"); used_bandwidth.Visible = false; break; case State.InAuth: auth_flickr.Sensitive = false; auth_label.Text = string.Format (Catalog.GetString ("Logging into {0}"), current_service.Name); auth_flickr.Label = Catalog.GetString ("Checking credentials..."); do_export_flickr.Sensitive = false; used_bandwidth.Visible = false; break; case State.Authorized: do_export_flickr.Sensitive = true; auth_flickr.Sensitive = true; auth_label.Text = System.String.Format (Catalog.GetString ("Welcome {0} you are connected to {1}"), auth.User.Username, current_service.Name); auth_flickr.Label = String.Format (Catalog.GetString ("Sign in as a different user"), auth.User.Username); used_bandwidth.Visible = !fr.Connection.PeopleGetUploadStatus().IsPro && fr.Connection.PeopleGetUploadStatus().BandwidthMax > 0; if (used_bandwidth.Visible) { used_bandwidth.Fraction = fr.Connection.PeopleGetUploadStatus().PercentageUsed; used_bandwidth.Text = string.Format (Catalog.GetString("Used {0} of your allowed {1} monthly quota"), GLib.Format.SizeForDisplay (fr.Connection.PeopleGetUploadStatus().BandwidthUsed), GLib.Format.SizeForDisplay (fr.Connection.PeopleGetUploadStatus().BandwidthMax)); } break; } state = value; } } public FlickrExport (IBrowsableCollection selection, bool display_tags) : this (SupportedService.Flickr, selection, display_tags) { } public FlickrExport (SupportedService service, IBrowsableCollection selection, bool display_tags) : this () { Run (service, selection, display_tags); } public FlickrExport () { } public virtual void Run (IBrowsableCollection selection) { Run (SupportedService.Flickr, selection, false); } public void Run (SupportedService service, IBrowsableCollection selection, bool display_tags) { this.selection = selection; this.current_service = FlickrRemote.Service.FromSupported (service); var view = new TrayView (selection); view.DisplayTags = display_tags; view.DisplayDates = false; builder = new GtkBeans.Builder (null, "flickr_export.ui", null); builder.Autoconnect (this); Dialog.Modal = false; Dialog.TransientFor = null; thumb_scrolledwindow.Add (view); HandleSizeActive (null, null); public_radio.Toggled += HandlePublicChanged; tag_check.Toggled += HandleTagChanged; hierarchy_check.Toggled += HandleHierarchyChanged; HandleTagChanged (null, null); HandleHierarchyChanged (null, null); Dialog.ShowAll (); Dialog.Response += HandleResponse; auth_flickr.Clicked += HandleClicked; auth_text = string.Format (auth_label.Text, current_service.Name); auth_label.Text = auth_text; used_bandwidth.Visible = false; LoadPreference (SCALE_KEY); LoadPreference (SIZE_KEY); LoadPreference (BROWSER_KEY); LoadPreference (TAGS_KEY); LoadPreference (TAG_HIERARCHY_KEY); LoadPreference (IGNORE_TOP_LEVEL_KEY); LoadPreference (PUBLIC_KEY); LoadPreference (FAMILY_KEY); LoadPreference (FRIENDS_KEY); LoadPreference (current_service.PreferencePath); do_export_flickr.Sensitive = false; fr = new FlickrRemote (token, current_service); if (token != null && token.Length > 0) { StartAuth (); } } public bool StartAuth () { CurrentState = State.InAuth; if (command_thread == null || ! command_thread.IsAlive) { command_thread = new Thread (new ThreadStart (CheckAuthorization)); command_thread.Start (); } return true; } public void CheckAuthorization () { AuthorizationEventArgs args = new AuthorizationEventArgs (); try { args.Auth = fr.CheckLogin (); } catch (FlickrException e) { args.Exception = e; } catch (Exception e) { HigMessageDialog md = new HigMessageDialog (Dialog, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Unable to log on"), e.Message); md.Run (); md.Destroy (); return; } ThreadAssist.ProxyToMain (() => { do_export_flickr.Sensitive = args.Auth != null; if (args.Auth != null) { token = args.Auth.Token; auth = args.Auth; CurrentState = State.Authorized; Preferences.Set (current_service.PreferencePath, token); } else { CurrentState = State.Disconnected; } }); } private class AuthorizationEventArgs : System.EventArgs { Exception e; Auth auth; public Exception Exception { get { return e; } set { e = value; } } public Auth Auth { get { return auth; } set { auth = value; } } public AuthorizationEventArgs () { } } public void HandleSizeActive (object sender, System.EventArgs args) { size_spin.Sensitive = scale_check.Active; } private void Logout () { token = null; auth = null; fr = new FlickrRemote (token, current_service); Preferences.Set (current_service.PreferencePath, String.Empty); CurrentState = State.Disconnected; } private void Login () { try { fr = new FlickrRemote (token, current_service); fr.TryWebLogin(); CurrentState = State.Connected; } catch (Exception e) { if (e is FlickrApiException && (e as FlickrApiException).Code == 98) { Logout (); Login (); } else { HigMessageDialog md = new HigMessageDialog (Dialog, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Unable to log on"), e.Message); md.Run (); md.Destroy (); CurrentState = State.Disconnected; } } } private void HandleProgressChanged (ProgressItem item) { //System.Console.WriteLine ("Changed value = {0}", item.Value); progress_dialog.Fraction = (photo_index - 1.0 + item.Value) / (double) selection.Count; } FileInfo info; private void HandleFlickrProgress (object sender, UploadProgressEventArgs args) { if (args.UploadComplete) { progress_dialog.Fraction = photo_index / (double) selection.Count; progress_dialog.ProgressText = String.Format (Catalog.GetString ("Waiting for response {0} of {1}"), photo_index, selection.Count); } progress_dialog.Fraction = (photo_index - 1.0 + (args.Bytes / (double) info.Length)) / (double) selection.Count; } private class DateComparer : IComparer { public int Compare (object left, object right) { return DateTime.Compare ((left as IPhoto).Time, (right as IPhoto).Time); } } private void Upload () { progress_item = new ProgressItem (); progress_item.Changed += HandleProgressChanged; fr.Connection.OnUploadProgress += HandleFlickrProgress; System.Collections.ArrayList ids = new System.Collections.ArrayList (); IPhoto [] photos = selection.Items; Array.Sort (photos, new DateComparer ()); for (int index = 0; index < photos.Length; index++) { try { IPhoto photo = photos [index]; progress_dialog.Message = System.String.Format ( Catalog.GetString ("Uploading picture \"{0}\""), photo.Name); progress_dialog.Fraction = photo_index / (double)selection.Count; photo_index++; progress_dialog.ProgressText = System.String.Format ( Catalog.GetString ("{0} of {1}"), photo_index, selection.Count); info = new FileInfo (photo.DefaultVersion.Uri.LocalPath); FilterSet stack = new FilterSet (); if (scale) stack.Add (new ResizeFilter ((uint)size)); string id = fr.Upload (photo, stack, is_public, is_family, is_friend); ids.Add (id); if (App.Instance.Database != null && photo is FSpot.Photo) App.Instance.Database.Exports.Create ((photo as FSpot.Photo).Id, (photo as FSpot.Photo).DefaultVersionId, ExportStore.FlickrExportType, auth.User.UserId + ":" + auth.User.Username + ":" + current_service.Name + ":" + id); } catch (System.Exception e) { progress_dialog.Message = String.Format (Catalog.GetString ("Error Uploading To {0}: {1}"), current_service.Name, e.Message); progress_dialog.ProgressText = Catalog.GetString ("Error"); Log.Exception (e); if (progress_dialog.PerformRetrySkip ()) { index--; photo_index--; } } } progress_dialog.Message = Catalog.GetString ("Done Sending Photos"); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Catalog.GetString ("Upload Complete"); progress_dialog.ButtonLabel = Gtk.Stock.Ok; if (open && ids.Count != 0) { string view_url; if (current_service.Name == "Zooomr.com") view_url = string.Format ("http://www.{0}/photos/{1}/", current_service.Name, auth.User.Username); else { view_url = string.Format ("http://www.{0}/tools/uploader_edit.gne?ids", current_service.Name); bool first = true; foreach (string id in ids) { view_url = view_url + (first ? "=" : ",") + id; first = false; } } GtkBeans.Global.ShowUri (Dialog.Screen, view_url); } } private void HandleClicked (object sender, System.EventArgs args) { switch (CurrentState) { case State.Disconnected: Login (); break; case State.Connected: StartAuth (); break; case State.InAuth: break; case State.Authorized: Logout (); Login (); break; } } private void HandlePublicChanged (object sender, EventArgs args) { bool sensitive = ! public_radio.Active; friend_check.Sensitive = sensitive; family_check.Sensitive = sensitive; } private void HandleTagChanged (object sender, EventArgs args) { hierarchy_check.Sensitive = tag_check.Active; } private void HandleHierarchyChanged (object sender, EventArgs args) { ignore_top_level_check.Sensitive = hierarchy_check.Active; } private void HandleResponse (object sender, Gtk.ResponseArgs args) { if (args.ResponseId != Gtk.ResponseType.Ok) { if (command_thread != null && command_thread.IsAlive) command_thread.Abort (); Dialog.Destroy (); return; } if (fr.CheckLogin() == null) { do_export_flickr.Sensitive = false; HigMessageDialog md = new HigMessageDialog (Dialog, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Unable to log on."), string.Format (Catalog.GetString ("F-Spot was unable to log on to {0}. Make sure you have given the authentication using {0} web browser interface."), current_service.Name)); md.Run (); md.Destroy (); return; } fr.ExportTags = tag_check.Active; fr.ExportTagHierarchy = hierarchy_check.Active; fr.ExportIgnoreTopLevel = ignore_top_level_check.Active; open = open_check.Active; scale = scale_check.Active; is_public = public_radio.Active; is_family = family_check.Active; is_friend = friend_check.Active; if (scale) size = size_spin.ValueAsInt; command_thread = new Thread (new ThreadStart (Upload)); command_thread.Name = Catalog.GetString ("Uploading Pictures"); Dialog.Destroy (); progress_dialog = new ThreadProgressDialog (command_thread, selection.Count); progress_dialog.Start (); // Save these settings for next time Preferences.Set (SCALE_KEY, scale); Preferences.Set (SIZE_KEY, size); Preferences.Set (BROWSER_KEY, open); Preferences.Set (TAGS_KEY, tag_check.Active); Preferences.Set (PUBLIC_KEY, public_radio.Active); Preferences.Set (FAMILY_KEY, family_check.Active); Preferences.Set (FRIENDS_KEY, friend_check.Active); Preferences.Set (TAG_HIERARCHY_KEY, hierarchy_check.Active); Preferences.Set (IGNORE_TOP_LEVEL_KEY, ignore_top_level_check.Active); Preferences.Set (current_service.PreferencePath, fr.Token); } void LoadPreference (string key) { switch (key) { case SCALE_KEY: if (scale_check.Active != Preferences.Get<bool> (key)) scale_check.Active = Preferences.Get<bool> (key); break; case SIZE_KEY: size_spin.Value = (double) Preferences.Get<int> (key); break; case BROWSER_KEY: if (open_check.Active != Preferences.Get<bool> (key)) open_check.Active = Preferences.Get<bool> (key); break; case TAGS_KEY: if (tag_check.Active != Preferences.Get<bool> (key)) tag_check.Active = Preferences.Get<bool> (key); break; case TAG_HIERARCHY_KEY: if (hierarchy_check.Active != Preferences.Get<bool> (key)) hierarchy_check.Active = Preferences.Get<bool> (key); break; case IGNORE_TOP_LEVEL_KEY: if (ignore_top_level_check.Active != Preferences.Get<bool> (key)) ignore_top_level_check.Active = Preferences.Get<bool> (key); break; case FlickrRemote.TOKEN_FLICKR: case FlickrRemote.TOKEN_23HQ: case FlickrRemote.TOKEN_ZOOOMR: token = Preferences.Get<string> (key); break; case PUBLIC_KEY: if (public_radio.Active != Preferences.Get<bool> (key)) public_radio.Active = Preferences.Get<bool> (key); break; case FAMILY_KEY: if (family_check.Active != Preferences.Get<bool> (key)) family_check.Active = Preferences.Get<bool> (key); break; case FRIENDS_KEY: if (friend_check.Active != Preferences.Get<bool> (key)) friend_check.Active = Preferences.Get<bool> (key); break; /* case Preferences.EXPORT_FLICKR_EMAIL: /* case Preferences.EXPORT_FLICKR_EMAIL: email_entry.Text = (string) val; break; */ } } private Gtk.Dialog Dialog { get { if (dialog == null) dialog = new Gtk.Dialog (builder.GetRawObject (dialog_name)); return dialog; } } } }
{ "content_hash": "d303e4e5a05bd3ef6683360467e6dfb1", "timestamp": "", "source": "github", "line_count": 605, "max_line_length": 216, "avg_line_length": 31.644628099173552, "alnum_prop": 0.6793940976756333, "repo_name": "nathansamson/F-Spot-Album-Exporter", "id": "353d94b501a84e461a8a137673f7c8fd25a6d148", "size": "19145", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Extensions/Exporters/FSpot.Exporters.Flickr/FSpot.Exporters.Flickr/FlickrExport.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4950" }, { "name": "C#", "bytes": "4073519" }, { "name": "JavaScript", "bytes": "10409" }, { "name": "Shell", "bytes": "17623" } ], "symlink_target": "" }
import PropTypes from 'prop-types' import React from 'react' import clsx from 'clsx' import { accessor } from '../../utils/propTypes' import EventWrapper from './EventWrapper' import EventContainerWrapper from './EventContainerWrapper' import WeekWrapper from './WeekWrapper' import { mergeComponents } from './common' /** * Creates a higher-order component (HOC) supporting drag & drop and optionally resizing * of events: * * ```js * import Calendar from 'react-big-calendar' * import withDragAndDrop from 'react-big-calendar/lib/addons/dragAndDrop' * export default withDragAndDrop(Calendar) * ``` * * Set `resizable` to false in your calendar if you don't want events to be resizable. * `resizable` is set to true by default. * * The HOC adds `onEventDrop`, `onEventResize`, and `onDragStart` callback properties if the events are * moved or resized. These callbacks are called with these signatures: * * ```js * function onEventDrop({ event, start, end, allDay }) {...} * function onEventResize(type, { event, start, end, allDay }) {...} // type is always 'drop' * function onDragStart({ event, action, direction }) {...} * ``` * * Moving and resizing of events has some subtlety which one should be aware of. * * In some situations, non-allDay events are displayed in "row" format where they * are rendered horizontally. This is the case for ALL events in a month view. It * is also occurs with multi-day events in a day or week view (unless `showMultiDayTimes` * is set). * * When dropping or resizing non-allDay events into a the header area or when * resizing them horizontally because they are displayed in row format, their * times are preserved, only their date is changed. * * If you care about these corner cases, you can examine the `allDay` param suppled * in the callback to determine how the user dropped or resized the event. * * Additionally, this HOC adds the callback props `onDropFromOutside` and `onDragOver`. * By default, the calendar will not respond to outside draggable items being dropped * onto it. However, if `onDropFromOutside` callback is passed, then when draggable * DOM elements are dropped on the calendar, the callback will fire, receiving an * object with start and end times, and an allDay boolean. * * If `onDropFromOutside` is passed, but `onDragOver` is not, any draggable event will be * droppable onto the calendar by default. On the other hand, if an `onDragOver` callback * *is* passed, then it can discriminate as to whether a draggable item is droppable on the * calendar. To designate a draggable item as droppable, call `event.preventDefault` * inside `onDragOver`. If `event.preventDefault` is not called in the `onDragOver` * callback, then the draggable item will not be droppable on the calendar. * * * ```js * function onDropFromOutside({ start, end, allDay }) {...} * function onDragOver(DragEvent: event) {...} * ``` * @param {*} Calendar * @param {*} backend */ export default function withDragAndDrop(Calendar) { class DragAndDropCalendar extends React.Component { static propTypes = { onEventDrop: PropTypes.func, onEventResize: PropTypes.func, onDragStart: PropTypes.func, onDragOver: PropTypes.func, onDropFromOutside: PropTypes.func, dragFromOutsideItem: PropTypes.func, draggableAccessor: accessor, resizableAccessor: accessor, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), resizable: PropTypes.bool, components: PropTypes.object, elementProps: PropTypes.object, step: PropTypes.number, } static defaultProps = { // TODO: pick these up from Calendar.defaultProps components: {}, draggableAccessor: null, resizableAccessor: null, resizable: true, step: 30, } static contextTypes = { dragDropManager: PropTypes.object, } static childContextTypes = { draggable: PropTypes.shape({ onStart: PropTypes.func, onEnd: PropTypes.func, onBeginAction: PropTypes.func, onDropFromOutside: PropTypes.func, dragFromOutsideItem: PropTypes.func, draggableAccessor: accessor, resizableAccessor: accessor, dragAndDropAction: PropTypes.object, }), } constructor(...args) { super(...args) const { components } = this.props this.components = mergeComponents(components, { eventWrapper: EventWrapper, eventContainerWrapper: EventContainerWrapper, weekWrapper: WeekWrapper, }) this.state = { interacting: false } } getChildContext() { return { draggable: { onStart: this.handleInteractionStart, onEnd: this.handleInteractionEnd, onBeginAction: this.handleBeginAction, onDropFromOutside: this.props.onDropFromOutside, dragFromOutsideItem: this.props.dragFromOutsideItem, draggableAccessor: this.props.draggableAccessor, resizableAccessor: this.props.resizableAccessor, dragAndDropAction: this.state, }, } } defaultOnDragOver = event => { event.preventDefault() } handleBeginAction = (event, action, direction) => { const { onDragStart } = this.props this.setState({ event, action, direction }) if (onDragStart) { onDragStart({ event, action, direction }) } } handleInteractionStart = () => { if (this.state.interacting === false) this.setState({ interacting: true }) } handleInteractionEnd = interactionInfo => { const { action, event } = this.state if (!action) return this.setState({ action: null, event: null, interacting: false, direction: null, }) if (interactionInfo == null) return interactionInfo.event = event if (action === 'move') this.props.onEventDrop(interactionInfo) if (action === 'resize') this.props.onEventResize(interactionInfo) } render() { const { selectable, elementProps, ...props } = this.props const { interacting } = this.state delete props.onEventDrop delete props.onEventResize props.selectable = selectable ? 'ignoreEvents' : false const elementPropsWithDropFromOutside = this.props.onDropFromOutside ? { ...elementProps, onDragOver: this.props.onDragOver || this.defaultOnDragOver, } : elementProps props.className = clsx( props.className, 'rbc-addons-dnd', !!interacting && 'rbc-addons-dnd-is-dragging' ) return ( <Calendar {...props} elementProps={elementPropsWithDropFromOutside} components={this.components} /> ) } } return DragAndDropCalendar }
{ "content_hash": "6afd08d4aa16afc50b30db66d9faf591", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 103, "avg_line_length": 32.857142857142854, "alnum_prop": 0.6682608695652174, "repo_name": "TeaBough/react-big-calendar", "id": "f2b7eeb5fcb7be16bd1ba0e072a26d1cbc5569d8", "size": "6900", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/addons/dragAndDrop/withDragAndDrop.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "28966" }, { "name": "JavaScript", "bytes": "229717" } ], "symlink_target": "" }
using namespace std; using namespace TgBot; bool sigintGot = false; int main() { Bot bot("PLACE YOUR TOKEN HERE"); // Thanks Pietro Falessi for code InlineKeyboardMarkup::Ptr keyboard(new InlineKeyboardMarkup); vector<InlineKeyboardButton::Ptr> row0; InlineKeyboardButton::Ptr checkButton(new InlineKeyboardButton); checkButton->text = "check"; checkButton->callbackData = "check"; row0.push_back(checkButton); keyboard->inlineKeyboard.push_back(row0); bot.getEvents().onCommand("start", [&bot, &keyboard](Message::Ptr message) { bot.getApi().sendMessage(message->chat->id, "Hi!", false, 0, keyboard); }); bot.getEvents().onCommand("check", [&bot, &keyboard](Message::Ptr message) { string response = "ok"; bot.getApi().sendMessage(message->chat->id, response, false, 0, keyboard, "Markdown"); }); bot.getEvents().onCallbackQuery([&bot, &keyboard](CallbackQuery::Ptr query) { if (StringTools::startsWith(query->data, "check")) { string response = "ok"; bot.getApi().sendMessage(query->message->chat->id, response, false, 0, keyboard, "Markdown"); } }); signal(SIGINT, [](int s) { printf("SIGINT got"); sigintGot = true; }); try { printf("Bot username: %s\n", bot.getApi().getMe()->username.c_str()); TgLongPoll longPoll(bot); while (!sigintGot) { printf("Long poll started\n"); longPoll.start(); } } catch (exception& e) { printf("error: %s\n", e.what()); } return 0; }
{ "content_hash": "4308dfabc9961819344068b235b2e51f", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 96, "avg_line_length": 29.26530612244898, "alnum_prop": 0.6820083682008368, "repo_name": "ZimmSebas/SecretHitlerBot", "id": "440f965bafc4b8f83a4acf482eeb095f2c912929", "size": "1521", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/inline-keyboard/src/main.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "29046" }, { "name": "C++", "bytes": "334235" }, { "name": "CMake", "bytes": "19993" }, { "name": "Dockerfile", "bytes": "350" }, { "name": "Makefile", "bytes": "601011" }, { "name": "Shell", "bytes": "75" } ], "symlink_target": "" }
const DOMNode = require('../../../../../lib/dom').DOMNode; const Button = require('../../../../../lib/components/input/Button').Button; const Toolbar = require('../../../../../lib/components/Toolbar').Toolbar; const tabIndex = require('../../../../tabIndex'); exports.ToolbarTop = class extends Toolbar { constructor(opts) { super(opts); this._ui = opts.ui; this._parentNode = opts.parentNode; this._soundEditor = opts.soundEditor; this.initDOM(); } initDOM() { let soundEditor = this._soundEditor; this.create( this._parentNode, { className: 'flt max-w resource-options top', children: [ this.addButton({ ref: soundEditor.setRef('undo'), uiId: soundEditor.getUIId.bind(soundEditor), tabIndex: tabIndex.SOUND_UNDO, className: 'toolbar-button', color: ' ', icon: 'icon-undo', hint: {text: 'Undo'}, disabled: true, onClick: soundEditor.onUndo.bind(soundEditor) }), { className: 'space' }, this.addButton({ ref: soundEditor.setRef('play'), uiId: soundEditor.getUIId.bind(soundEditor), tabIndex: tabIndex.SOUND_PLAY, className: 'toolbar-button', color: ' ', icon: 'icon-play', hint: {text: 'Play'}, onClick: soundEditor.onPlay.bind(soundEditor) }), // Copy, paste, delete... this.addButton({ ref: soundEditor.setRef('copy'), uiId: soundEditor.getUIId.bind(soundEditor), tabIndex: tabIndex.SOUND_COPY, className: 'toolbar-button', color: ' ', icon: 'icon-copy', hint: {text: 'Copy'}, disabled: true, onClick: soundEditor.onCopy.bind(soundEditor) }), this.addButton({ ref: soundEditor.setRef('paste'), uiId: soundEditor.getUIId.bind(soundEditor), tabIndex: tabIndex.SOUND_PASTE, className: 'toolbar-button', color: ' ', icon: 'icon-paste', hint: {text: 'Paste'}, disabled: true, onClick: soundEditor.onPaste.bind(soundEditor) }), this.addButton({ ref: soundEditor.setRef('delete'), uiId: soundEditor.getUIId.bind(soundEditor), tabIndex: tabIndex.SOUND_DELETE, className: 'toolbar-button', color: ' ', icon: 'icon-delete', hint: {text: 'Delete'}, disabled: true, onClick: soundEditor.onDelete.bind(soundEditor) }), { className: 'space' }, // Volume... this.addButton({ ref: soundEditor.setRef('volume'), uiId: soundEditor.getUIId.bind(soundEditor), tabIndex: tabIndex.SOUND_VOLUME, className: 'toolbar-button', color: ' ', icon: 'icon-volume', hint: {text: 'Change volume'}, onClick: soundEditor.onVolume.bind(soundEditor) }), this.addButton({ ref: soundEditor.setRef('fadeIn'), uiId: soundEditor.getUIId.bind(soundEditor), tabIndex: tabIndex.SOUND_FADE_IN, className: 'toolbar-button', color: ' ', icon: 'icon-fade-in', hint: {text: 'Fade in'}, onClick: soundEditor.onFadeIn.bind(soundEditor) }), this.addButton({ ref: soundEditor.setRef('fadeOut'), uiId: soundEditor.getUIId.bind(soundEditor), tabIndex: tabIndex.SOUND_FADE_OUT, className: 'toolbar-button', color: ' ', icon: 'icon-fade-out', hint: {text: 'Fade out'}, onClick: soundEditor.onFadeOut.bind(soundEditor) }) ] } ); } };
{ "content_hash": "b7b4a519f5e88c244980db3c6bf11b81", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 78, "avg_line_length": 45.436974789915965, "alnum_prop": 0.3813574995376364, "repo_name": "ArnoVanDerVegt/wheel", "id": "8e129dd607ae10d34d8d3e8976e31f2e4312b511", "size": "5562", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "js/frontend/ide/editor/editors/sound/toolbar/ToolbarTop.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "113289" }, { "name": "CSS", "bytes": "526894" }, { "name": "HTML", "bytes": "1657447" }, { "name": "JavaScript", "bytes": "4667529" }, { "name": "Rich Text Format", "bytes": "496" } ], "symlink_target": "" }
if(AOM_BUILD_CMAKE_TOOLCHAINS_ARM64_MINGW_GCC_CMAKE_) return() endif() # AOM_BUILD_CMAKE_TOOLCHAINS_ARM64_MINGW_GCC_CMAKE_ set(AOM_BUILD_CMAKE_TOOLCHAINS_ARM64_MINGW_GCC_CMAKE_ 1) set(CMAKE_SYSTEM_PROCESSOR "arm64") set(CMAKE_SYSTEM_NAME "Windows") if("${CROSS}" STREQUAL "") set(CROSS aarch64-w64-mingw32-) endif() set(CMAKE_C_COMPILER ${CROSS}gcc) set(CMAKE_CXX_COMPILER ${CROSS}g++) set(CMAKE_AR ${CROSS}ar CACHE FILEPATH Archiver) set(CMAKE_RANLIB ${CROSS}ranlib CACHE FILEPATH Indexer) # No runtime cpu detect for arm64-mingw-gcc. set(CONFIG_RUNTIME_CPU_DETECT 0 CACHE STRING "")
{ "content_hash": "9787f9eaff254f0f30c31637def31c79", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 59, "avg_line_length": 31.210526315789473, "alnum_prop": 0.7453625632377741, "repo_name": "endlessm/chromium-browser", "id": "a8e15cb3171fb82672a47bc5834d502ee98625a5", "size": "1111", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "third_party/libaom/source/libaom/build/cmake/toolchains/arm64-mingw-gcc.cmake", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> <color name="background">#E5E5E5</color> </resources>
{ "content_hash": "7552e3ed725700fae2cc7d2f2c0c800f", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 50, "avg_line_length": 36.142857142857146, "alnum_prop": 0.6758893280632411, "repo_name": "REBOOTERS/UltimateRefreshView", "id": "e79ace4d1086c8f5d7dea214547c830220069cd8", "size": "253", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values/colors.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "54011" } ], "symlink_target": "" }
FROM balenalib/var-som-mx6-debian:buster-build # A few reasons for installing distribution-provided OpenJDK: # # 1. Oracle. Licensing prevents us from redistributing the official JDK. # # 2. Compiling OpenJDK also requires the JDK to be installed, and it gets # really hairy. # # For some sample build times, see Debian's buildd logs: # https://buildd.debian.org/status/logs.php?pkg=openjdk-11 RUN apt-get update && apt-get install -y --no-install-recommends \ bzip2 \ unzip \ xz-utils \ && rm -rf /var/lib/apt/lists/* # Default to UTF-8 file.encoding ENV LANG C.UTF-8 # add a simple script that can auto-detect the appropriate JAVA_HOME value # based on whether the JDK or only the JRE is installed RUN { \ echo '#!/bin/sh'; \ echo 'set -e'; \ echo; \ echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \ } > /usr/local/bin/docker-java-home \ && chmod +x /usr/local/bin/docker-java-home # do some fancy footwork to create a JAVA_HOME that's cross-architecture-safe RUN ln -svT "/usr/lib/jvm/java-11-openjdk-$(dpkg --print-architecture)" /docker-java-home ENV JAVA_HOME /docker-java-home RUN set -ex; \ \ # deal with slim variants not having man page directories (which causes "update-alternatives" to fail) if [ ! -d /usr/share/man/man1 ]; then \ mkdir -p /usr/share/man/man1; \ fi; \ \ apt-get update; \ apt-get install -y --no-install-recommends \ openjdk-11-jdk-headless \ ; \ rm -rf /var/lib/apt/lists/*; \ \ rm -vf /usr/local/bin/java; \ \ # ca-certificates-java does not work on src:openjdk-11: (https://bugs.debian.org/914424, https://bugs.debian.org/894979, https://salsa.debian.org/java-team/ca-certificates-java/commit/813b8c4973e6c4bb273d5d02f8d4e0aa0b226c50#d4b95d176f05e34cd0b718357c532dc5a6d66cd7_54_56) keytool -importkeystore -srckeystore /etc/ssl/certs/java/cacerts -destkeystore /etc/ssl/certs/java/cacerts.jks -deststoretype JKS -srcstorepass changeit -deststorepass changeit -noprompt; \ mv /etc/ssl/certs/java/cacerts.jks /etc/ssl/certs/java/cacerts; \ /var/lib/dpkg/info/ca-certificates-java.postinst configure; \ \ # verify that "docker-java-home" returns what we expect [ "$(readlink -f "$JAVA_HOME")" = "$(docker-java-home)" ]; \ \ # update-alternatives so that future installs of other OpenJDK versions don't change /usr/bin/java update-alternatives --get-selections | awk -v home="$(readlink -f "$JAVA_HOME")" 'index($3, home) == 1 { $2 = "manual"; print | "update-alternatives --set-selections" }'; \ # ... and verify that it actually worked for one of the alternatives we care about update-alternatives --query java | grep -q 'Status: manual' # https://docs.oracle.com/javase/10/tools/jshell.htm # https://en.wikipedia.org/wiki/JShell CMD ["jshell"] CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Buster \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v11-jdk \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "83578fb9b1f68ab9f122d1c3199b8213", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 679, "avg_line_length": 50.986666666666665, "alnum_prop": 0.7154811715481172, "repo_name": "nghiant2710/base-images", "id": "8bff105c2ce6296727d375131767c3fc1d5c9b36", "size": "3845", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "balena-base-images/openjdk/var-som-mx6/debian/buster/11-jdk/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
package com.moosader.entities; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Vector2; public class Bullet extends EntityBase { /* public Sprite m_sprite; public TextureRegion m_region; public Texture m_texture; protected Vector2 m_coord; protected Vector2 m_dimen; */ protected final float m_bulletSizeMin = 5f; protected final float m_bulletSizeMax = 15f; protected float m_maxSpeed; protected float m_accelerateSpeed; protected float m_speed; protected float m_initialSpeed; protected float m_bulletChargeRate; protected BulletState m_state; protected boolean m_isPlayerBullet; public Bullet() { m_dimen = new Vector2(m_bulletSizeMin, m_bulletSizeMin); m_coord = new Vector2(0, 0); m_sprite = new Sprite(); m_maxSpeed = 300f; m_accelerateSpeed = 50f; m_speed = m_initialSpeed = 50f; m_state = BulletState.INACTIVE; } public Bullet(Bullet template) { m_dimen = new Vector2(template.m_dimen); m_coord = new Vector2(template.m_coord); m_sprite = new Sprite(template.m_sprite); m_accelerateSpeed = template.m_accelerateSpeed; m_isPlayerBullet = template.m_isPlayerBullet; m_maxSpeed = template.m_maxSpeed; m_speed = template.m_speed; m_state = template.m_state; } public void setupPlayerBullet(Sprite sprite) { reset(); m_isPlayerBullet = true; m_sprite = sprite; m_bulletChargeRate = 0.2f; } public void setupEnemyBullet(Sprite sprite, float speed) { reset(); m_isPlayerBullet = false; m_sprite = sprite; m_dimen.x = m_dimen.y = 10f; m_speed = -speed; m_initialSpeed = -speed; } public void reset() { m_dimen.x = m_bulletSizeMin; m_dimen.y = m_bulletSizeMin; //m_coord.x = m_coord.y = 0; m_speed = m_initialSpeed; m_state = BulletState.INACTIVE; updateFrame(); } public void alignWithOwner(Vector2 ownerCoord, Vector2 ownerDimen) { m_coord.x = (m_isPlayerBullet) ? ownerCoord.x + ownerDimen.x - 48f // Player coords : ownerCoord.x - 16f; // Enemy coords m_coord.y = (ownerCoord.y + ownerDimen.y/3) - (m_dimen.y/2); } public void move(float delta) { m_speed += (m_accelerateSpeed / m_dimen.x / 5); if (m_isPlayerBullet) { m_coord.x += m_speed * delta; } else { m_coord.x -= m_speed * delta; } checkBounds(); updateFrame(); } public BulletState getState() { return m_state; } public boolean isPlayerBullet() { return m_isPlayerBullet; } public float getSize() { return m_dimen.x; } public void shootingReleased() { if ( m_state == BulletState.CHARGING ) { m_state = BulletState.PROJECTILE; } else { m_state = BulletState.INACTIVE; } } public void shootingPressed() { m_state = BulletState.CHARGING; } public void setProjectile() { m_state = BulletState.PROJECTILE; } public void setInactive() { m_state = BulletState.INACTIVE; reset(); } public void charge(Vector2 ownerCoord, Vector2 ownerDimen) { m_state = BulletState.CHARGING; m_dimen.x += m_bulletChargeRate; m_dimen.y += m_bulletChargeRate; alignWithOwner(ownerCoord, ownerDimen); checkBounds(); updateFrame(); } private void checkBounds() { // Size bounds if (m_dimen.x > m_bulletSizeMax) { m_dimen.x = m_dimen.y = m_bulletSizeMax; } if (m_dimen.x < m_bulletSizeMin) { m_dimen.x = m_dimen.y = m_bulletSizeMin; } // Acceleration bounds if (m_isPlayerBullet) { if (m_speed > m_maxSpeed) { m_speed = m_maxSpeed; } } else { m_dimen.x = m_dimen.y = 10f; } if (m_speed <= 0) { m_speed = m_initialSpeed; } } public Bullet release() { m_state = BulletState.PROJECTILE; m_accelerateSpeed = m_dimen.x/5 * 10; return this; } public void updateFrame() { m_sprite.setPosition(m_coord.x, m_coord.y); m_sprite.setSize(m_dimen.x, m_dimen.y); } }
{ "content_hash": "2601c165958de94bffa8f1f2a5426259", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 69, "avg_line_length": 22.127167630057805, "alnum_prop": 0.6695402298850575, "repo_name": "Moosader/JAM-and-RAM", "id": "1490e96a8494b3d3676471b0f17257f7740df641", "size": "3828", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jam-and-ram/src/com/moosader/entities/Bullet.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "86052" } ], "symlink_target": "" }
git add . git commit -am "Deploy in Heroku" git push heroku master
{ "content_hash": "166955c8c6e5b845c3faab3824ba2e50", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 33, "avg_line_length": 22, "alnum_prop": 0.7575757575757576, "repo_name": "Ushelets/pepelats-vue", "id": "0dd6f2a9a2c022b9dd6099a3325ce2f45f228dd4", "size": "86", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deploy.sh", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7236" }, { "name": "HTML", "bytes": "206" }, { "name": "JavaScript", "bytes": "27655" }, { "name": "Shell", "bytes": "86" }, { "name": "Vue", "bytes": "7553" } ], "symlink_target": "" }
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2007 Allen Kuo This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file bspline.hpp \brief B-spline basis functions */ #ifndef quantlib_bspline_hpp #define quantlib_bspline_hpp #include <ql/types.hpp> #include <vector> namespace QuantLib { //! B-spline basis functions /*! Follows treatment and notation from: Weisstein, Eric W. "B-Spline." From MathWorld--A Wolfram Web Resource. <http://mathworld.wolfram.com/B-Spline.html> \f$ (p+1) \f$-th order B-spline (or p degree polynomial) basis functions \f$ N_{i,p}(x), i = 0,1,2 \ldots n \f$, with \f$ n+1 \f$ control points, or equivalently, an associated knot vector of size \f$ p+n+2 \f$ defined at the increasingly sorted points \f$ (x_0, x_1 \ldots x_{n+p+1}) \f$. A linear B-spline has \f$ p=1 \f$, quadratic B-spline has \f$ p=2 \f$, a cubic B-spline has \f$ p=3 \f$, etc. The B-spline basis functions are defined recursively as follows: \f[ \begin{array}{rcl} N_{i,0}(x) &=& 1 \textrm{\ if\ } x_{i} \leq x < x_{i+1} \\ &=& 0 \textrm{\ otherwise} \\ N_{i,p}(x) &=& N_{i,p-1}(x) \frac{(x - x_{i})}{ (x_{i+p-1} - x_{i})} + N_{i+1,p-1}(x) \frac{(x_{i+p} - x)}{(x_{i+p} - x_{i+1})} \end{array} \f] */ class BSpline { public: BSpline(Natural p, Natural n, const std::vector<Real>& knots); Real operator()(Natural i, Real x) const; private: // recursive definition of N, the B-spline basis function Real N(Natural i, Natural p, Real x) const; // e.g. p_=2 is a quadratic B-spline, p_=3 is a cubic B-Spline, etc. Natural p_; // n_ + 1 = "control points" = max number of basis functions Natural n_; std::vector<Real> knots_; }; } #endif
{ "content_hash": "67502f2d71bfefe378102c6a670b6217", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 79, "avg_line_length": 33.58227848101266, "alnum_prop": 0.5959291368262345, "repo_name": "applehackfoxus/Quantum-Trading", "id": "47ea5e5a0f966b401e382b6afcd67a246704aa76", "size": "2653", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "QuantLib-1.4/ql/math/bspline.hpp", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
using System; using System.Collections.Generic; using Mono.Facebook; namespace Mono.Facebook.Test { class GetEvents { static void Main(string[] args) { // create session FacebookSession session = new FacebookSession("ca9511b32569d823f1d3a942b31c6c84", "61f4712317fb7a2d12581f523c01fe71"); // create token and login with it Uri login = session.CreateToken(); System.Diagnostics.Process.Start("firefox", login.AbsoluteUri); Console.WriteLine ("Press enter after you've logged in."); Console.ReadLine (); // get session key session.GetSession (); Me me = session.GetLoggedInUser (); foreach (Event e in me.Events) { Console.WriteLine ("Event Name: {0}", e.Name); Console.WriteLine ("Attending: {0}", e.MemberList.Attending.Length); } } } }
{ "content_hash": "dcae203348e7051c00bf3b10a478841a", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 121, "avg_line_length": 26.466666666666665, "alnum_prop": 0.7065491183879093, "repo_name": "mono/facebook-sharp", "id": "4c0556edcf5370445863bbc0aa1f0e26726855b1", "size": "794", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "examples/GetEvents.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "2024" }, { "name": "C#", "bytes": "102212" }, { "name": "Shell", "bytes": "44" } ], "symlink_target": "" }
function tabIndicator() { // TODO: relocate indicator when tab activates }
{ "content_hash": "8492898963df733ed23ea70ce9f85334", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 50, "avg_line_length": 26, "alnum_prop": 0.7307692307692307, "repo_name": "YangMann/Paper", "id": "399f311218f6b08645a25630d40785055b5be6f4", "size": "78", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/tab.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "129238" }, { "name": "HTML", "bytes": "68403" }, { "name": "JavaScript", "bytes": "4244" }, { "name": "Ruby", "bytes": "1202" } ], "symlink_target": "" }
package com.rs.game.player.dialogues; import com.rs.cache.loaders.NPCDefinitions; import com.rs.game.player.actions.Slayer; import com.rs.game.player.actions.Slayer.Master; import com.rs.game.player.actions.Slayer.SlayerTask; import com.rs.utils.ShopsHandler; public class SlayerMaster extends Dialogue { private int npcId; @Override public void start() { npcId = (Integer) parameters[0]; Master master = player.getSlayerMaster(); if (master == null) player.setSlayerMaster(Master.SPRIA); sendEntityDialogue(SEND_1_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Good day, How may I help you?" }, IS_NPC, npcId, 9827); } @Override public void run(int interfaceId, int componentId) { Master master = player.getSlayerMaster(); if (npcId != master.getMaster()) stage = 2; if (stage == -1) { if (player.getSlayerTask() != null) { sendEntityDialogue(SEND_4_OPTIONS, new String[] { SEND_DEFAULT_OPTIONS_TITLE, "How many monsters do I have left?", "What do you have in your shop?", "Give me a tip.", "Nothing, Nevermind." }, IS_PLAYER, player.getIndex(), 9827); stage = 0; } else { sendEntityDialogue(SEND_4_OPTIONS, new String[] { SEND_DEFAULT_OPTIONS_TITLE, "Please give me a task.", "What do you have in your shop?", "Give me a tip.", "Nothing, Nevermind." }, IS_PLAYER, player.getIndex(), 9827); stage = 1; } } else if (stage == 0 || stage == 1) { if (componentId == 1) { SlayerTask task = player.getSlayerTask(); if (task != null && stage == 0) { sendEntityDialogue( SEND_1_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "You're current assigned to kill " + task.getName().toLowerCase() + " only " + task.getAmount() + " more to go." }, IS_NPC, npcId, 9827); } else { Slayer.submitRandomTask(player); sendEntityDialogue( SEND_1_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "Your new task is to kill " + player.getSlayerTask().getName() .toLowerCase() + "." }, IS_NPC, npcId, 9827); } stage = -1; } else if (componentId == 2) { sendEntityDialogue( SEND_1_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "I have multiple items for sale." }, IS_NPC, npcId, 9827); ShopsHandler.openShop(player, 29); stage = -1; } else if (componentId == 3) { sendEntityDialogue( SEND_1_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "I currently dont have any tips for you now." }, IS_NPC, npcId, 9827); stage = -1; } else { end(); } } else if (stage == 2) { sendEntityDialogue(SEND_3_OPTIONS, new String[] { SEND_DEFAULT_OPTIONS_TITLE, "Can you become my master?", "What do you have in your shop?", "Nothing, Nevermind." }, IS_PLAYER, player.getIndex(), 9827); stage = 3; if (stage == 3) { if (componentId == 1) { if (player.getSlayerTask() != null) { sendEntityDialogue( SEND_1_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "I cannot teach you until your slayer task is complete. Come back later." }, IS_NPC, npcId, 9827); return; } sendEntityDialogue(SEND_1_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "You are now under my wings." }, IS_NPC, npcId, 9827); player.setSlayerMaster(Master.forId(npcId)); } else if (componentId == 2) { sendEntityDialogue(SEND_1_TEXT_CHAT, new String[] { NPCDefinitions.getNPCDefinitions(npcId).name, "I have multiple items for sale." }, IS_NPC, npcId, 9827); ShopsHandler.openShop(player, 29); } else { end(); } } } } @Override public void finish() { } }
{ "content_hash": "2b8830f4bb54566c9f693060214e1eec", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 86, "avg_line_length": 30.786259541984734, "alnum_prop": 0.6109595834366477, "repo_name": "calvinlotsberg/OurScape", "id": "7a796c14dc0083b497a8eed1acd263a8a64cc51f", "size": "4033", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/rs/game/player/dialogues/SlayerMaster.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Table of contents: * [ini_read](#ini_read) * [ini_read_file](#ini_read_file) * [ini_open_file](#ini_open_file) * [ini_close_file](#ini_close_file) * [ini_write_section](#ini_write_section) * [ini_verify_utf8](#ini_verify_utf8) * [ini_write_name_value](#ini_write_name_value) * [ini_write_comment](#ini_write_comment) ## ini_read() **Definition:** ``` int ini_read(const char *str, size_t file_size, ini_event handler, void *data_structure, char comment, char equals, int allow_utf8); ``` **Description:** Parses a string with a given file size and calls a handler function when a key value pair is read. The handler should return 0 on failure and a non 0 value on success. **Parameters:** * string * file size * handler function * pointer to user data structure * comment char * equals char * allow UTF-8 flag **Return:** 0 on success; -1 on memory error and the currently parsed line number on a parsing error ## ini_read_file() **Definition:** ``` int ini_read_file(const char *path, ini_event handler, void *data_structure, char comment, char equals, enum ini_utf8_mode allow_utf8); ``` **Description:** Reads an .ini file and parses it using the user defined handler function and the data structure. The handler should return 0 on failure and a non 0 value on success. **Parameters:** * string * file size * handler function * pointer to user data structure * comment char * equals char * allow UTF-8 flag **Return:** 0 on success; -1 on memory error and the currently parsed line number on a parsing error ## ini_open_file() **Definition:** ``` int ini_open_file(struct ini_file *file, const char *path, char equals, char comment, enum ini_utf8_mode utf8_mode); ``` **Description:** Opens an .INI file for write and writes the byte order mark if needed. **Parameters:** * file pointer * path * equals character * comment character * UTF-8 mode (INI_UTF8_MODE_FORBID, INI_UTF8_MODE_ALLOW, INI_UTF8_MODE_ALLOW_WITH_BOM, INI_UTF8_MODE_ESCAPE) **Return:** 1 on success; 0 on failure ## ini_close_file() **Definition:** ``` int ini_close_file(struct ini_file *file); ``` **Description:** Closes an .INI file. The file pointer must be valid! **Parameters:** * file pointer **Return:** 1 on success; 0 on failure ## ini_write_section() **Definition:** ``` int ini_write_section(const struct ini_file *file, const char *section); ``` **Description:** Writes a section name to a file. The section and file pointers must be valid! The section name mustn't include whitespace character, other escape characters! The section name also mustn't be empty! **Parameters:** * file pointer * section name **Return:** 1 on success; 0 on failure ## ini_verify_utf8() **Definition:** ``` int ini_verify_utf8(const char *str, int allow_utf8); ``` **Description:** Verifies that a given string consists only of valid UTF-8 sequences or doesn't contain any UTF-8 sequence. **Parameters:** * string * flag whether to allow UTF-8 or not **Return:** 1 if the string is valid; 0 otherwise ## ini_write_name_value() **Definition:** ``` int ini_write_name_value(const struct ini_file *file, const char *name, const char *value); ``` **Description:** Writes a name - value pair to a file. The name and file pointers mustn't be NULL! **Parameters:** * file pointer * name * value **Return:** 1 on success; 0 on failure ## ini_write_comment() **Definition:** ``` int ini_write_comment(const struct ini_file *file, const char *comment); ``` **Description:** Writes a comment into an .INI file. The comment string and file pointers mustn't be NULL! **Parameters:** * file * comment string **Return:** 1 on success; 0 on failure
{ "content_hash": "31e803b92e9cd74cddf27b641f551899", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 135, "avg_line_length": 22.462962962962962, "alnum_prop": 0.7065127782357791, "repo_name": "kloppstock/IniParser", "id": "dbce2235e40e58329a5df0f11d8883a62eb4059b", "size": "3658", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/c_api.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "55347" }, { "name": "C++", "bytes": "111851" }, { "name": "CMake", "bytes": "624" }, { "name": "Makefile", "bytes": "830" } ], "symlink_target": "" }
package org.apache.camel.test.infra.nsq.services; import org.apache.camel.test.infra.common.services.ContainerService; import org.apache.camel.test.infra.nsq.common.NsqProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.FixedHostPortGenericContainer; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.wait.strategy.Wait; public class NsqLocalContainerService implements NsqService, ContainerService<GenericContainer> { protected static final String CONTAINER_NSQLOOKUPD_IMAGE = "nsqio/nsq:v1.2.0"; protected static final String CONTAINER_NSQLOOKUPD_NAME = "nsqlookupd"; protected static final String CONTAINER_NSQD_IMAGE = "nsqio/nsq:v1.2.0"; protected static final String CONTAINER_NSQD_NAME = "nsqd"; private static final Logger LOG = LoggerFactory.getLogger(NsqLocalContainerService.class); private GenericContainer nsqContainer; private GenericContainer nsqLookupContainer; private Network network = Network.newNetwork(); public NsqLocalContainerService() { initContainers(); } protected void initContainers() { nsqLookupContainer = new FixedHostPortGenericContainer<>(CONTAINER_NSQLOOKUPD_IMAGE) .withFixedExposedPort(4160, 4160) .withFixedExposedPort(4161, 4161) .withNetworkAliases(CONTAINER_NSQLOOKUPD_NAME) .withCommand("/nsqlookupd").withNetwork(network) .waitingFor(Wait.forLogMessage(".*TCP: listening on.*", 1)); nsqContainer = new FixedHostPortGenericContainer<>(CONTAINER_NSQD_IMAGE) .withFixedExposedPort(4150, 4150) .withFixedExposedPort(4151, 4151) .withNetworkAliases(CONTAINER_NSQD_NAME) .withCommand(String.format("/nsqd --broadcast-address=%s --lookupd-tcp-address=%s:4160", "localhost", CONTAINER_NSQLOOKUPD_NAME)) .withNetwork(network) .waitingFor(Wait.forLogMessage(".*TCP: listening on.*", 1)); } @Override public void registerProperties() { System.getProperty(NsqProperties.PRODUCER_URL, getNsqProducerUrl()); System.getProperty(NsqProperties.CONSUMER_URL, getNsqConsumerUrl()); } @Override public void initialize() { LOG.info("Trying to start the Nsq container"); nsqLookupContainer.start(); nsqContainer.start(); registerProperties(); LOG.info("Nsq producer accessible via {}", getNsqProducerUrl()); LOG.info("Nsq consumer accessible via {}", getNsqConsumerUrl()); } @Override public void shutdown() { LOG.info("Stopping the Nsq container"); nsqContainer.stop(); nsqLookupContainer.stop(); } @Override public GenericContainer getContainer() { return nsqContainer; } @Override public String getNsqProducerUrl() { return String.format("%s:%d", nsqContainer.getHost(), nsqContainer.getMappedPort(4150)); } @Override public String getNsqConsumerUrl() { return String.format("%s:%d", nsqLookupContainer.getHost(), nsqLookupContainer.getMappedPort(4161)); } }
{ "content_hash": "2b73c44f606e1849106e9c6951a64d53", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 117, "avg_line_length": 37.9080459770115, "alnum_prop": 0.6913280776228017, "repo_name": "pmoerenhout/camel", "id": "e4ceb756427ba168bbc48b1eb33abc1157e26f07", "size": "4100", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test-infra/camel-test-infra-nsq/src/test/java/org/apache/camel/test/infra/nsq/services/NsqLocalContainerService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6519" }, { "name": "Batchfile", "bytes": "1518" }, { "name": "CSS", "bytes": "30373" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "11410" }, { "name": "Groovy", "bytes": "47394" }, { "name": "HTML", "bytes": "903016" }, { "name": "Java", "bytes": "74647280" }, { "name": "JavaScript", "bytes": "90399" }, { "name": "Makefile", "bytes": "513" }, { "name": "Python", "bytes": "36" }, { "name": "Ruby", "bytes": "4802" }, { "name": "Scala", "bytes": "323982" }, { "name": "Shell", "bytes": "17120" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "288715" } ], "symlink_target": "" }
package com.ycsoft.report.component.system; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Component; import com.ycsoft.beans.system.SDataRightType; import com.ycsoft.beans.system.SOptr; import com.ycsoft.beans.system.SRole; import com.ycsoft.beans.system.SSubSystem; import com.ycsoft.business.dao.system.SDataRightTypeDao; import com.ycsoft.business.dao.system.SOptrDao; import com.ycsoft.business.dao.system.SOptrRoleDao; import com.ycsoft.business.dao.system.SResourceDao; import com.ycsoft.business.dao.system.SRoleDao; import com.ycsoft.business.dao.system.SSubSystemDao; import com.ycsoft.commons.abstracts.BaseComponent; import com.ycsoft.commons.exception.ReportException; import com.ycsoft.commons.helper.MD5; import com.ycsoft.commons.helper.StringHelper; import com.ycsoft.daos.core.JDBCException; import com.ycsoft.report.commons.ReportConstants; import com.ycsoft.report.commons.SystemConfig; import com.ycsoft.report.dao.config.QueryRepDao; import com.ycsoft.report.dao.keycon.QueryKeyValueDao; import com.ycsoft.report.dto.RepDataRight; import com.ycsoft.report.dto.RepResourceDto; import com.ycsoft.report.query.datarole.BaseDataControl; import com.ycsoft.report.query.datarole.DataRoleInit; import com.ycsoft.report.query.datarole.FuncType; import com.ycsoft.report.query.key.Impl.QueryKeyValue; import com.ycsoft.sysmanager.dto.system.SResourceDto; import com.ycsoft.sysmanager.dto.system.SRoleDto; /** * * 首页显示的管理器 * @author hh * @date Dec 29, 2009 4:02:49 PM */ @Component public class IndexComponent extends BaseComponent{ private SOptrDao sOptrDao ; private SResourceDao sResourceDao; private SRoleDao sRoleDao; private SSubSystemDao sSubSystemDao; private SOptrRoleDao sOptrRoleDao; private SDataRightTypeDao sDataRightTypeDao; private QueryKeyValueDao queryKeyValueDao; private DataRoleInit dataControl; private QueryRepDao queryRepDao; public SOptr queryOptrByloginname(String loginname) throws ReportException{ try { return queryRepDao.querySOptrByloginname(loginname); } catch (JDBCException e) { throw new ReportException(e,e.getSQL()); } } public void setQueryRepDao(QueryRepDao queryRepDao) { this.queryRepDao = queryRepDao; } /** * 报表数据权限初始化 * @param optr * @param session * @throws ReportException */ public void initDataRole(SOptr optr,HttpSession session) throws ReportException{ session.setAttribute(ReportConstants.SESSION_DATA_ROLE, dataControl.setDataRole(optr)); } /** * 获取数据权限限制内容 */ protected String queryReportDataRightCon(String optrId,String dataRightType)throws ReportException { try { List<SRole> roleList = sRoleDao.queryByOptrId(optrId,dataRightType); for (SRole role : roleList) { if (StringHelper.isNotEmpty(role.getData_right_level())) return null; else if (StringHelper.isNotEmpty(role.getRule_str())) { return role.getRule_str().replaceAll("\"", "'"); } } return null; } catch (JDBCException e) { throw new ReportException(e); } } public Map<String,RepDataRight> queryRepRoleDataMap(SOptr optr)throws Exception{ Map<String,RepDataRight> map=new HashMap<String,RepDataRight>(); for(String datarighttype:SystemConfig.getDataRightTypeList()){ String sql=queryReportDataRightCon(optr.getOptr_id(),datarighttype); if(StringHelper.isNotEmpty(sql)){ RepDataRight o=new RepDataRight(); o.setKey(datarighttype); o.setSql(sql); SDataRightType dataRight = sDataRightTypeDao.findByKey(datarighttype); String datavaluesql="select "+dataRight.getResult_column()+","+dataRight.getSelect_column() +" from "+dataRight.getTable_name()+" where "+sql; String datavalue=""; List<QueryKeyValue> list=queryKeyValueDao.findList(ReportConstants.DATABASE_SYSTEM, datavaluesql); for(int i=0;i<list.size();i++){ QueryKeyValue value=list.get(i); datavalue=datavalue+(i==0?"":"','")+ value.getId(); } o.setValue(datavalue); map.put(datarighttype, o); } } return map; } /** * 查询所有子系统定义信息 * @return * @throws Exception */ public List<SSubSystem> queryAllSubSystem(SOptr optr) throws Exception { return sSubSystemDao.queryAllSubSystem(optr); } public List<SRoleDto> getSubSystemByOptrId(String optrId) throws Exception { List<SRoleDto> list = sOptrRoleDao.queryOptrRole(optrId); if (list.size()>0) { for (int i = list.size() - 1; i >= 0; i--) { boolean ck = false; if (StringHelper.isEmpty(list.get(i).getSub_system_id())) { ck = true; } if (ck) { list.remove(i); } } }else{ throw new Exception("操作员的配置存在问题,角色中不存在子系统!"); } return list; } /** * 修改操作员密码 */ public boolean updateOptrData(String optrId,String password,String subSystemId) throws Exception{ SOptr soptr = new SOptr(); soptr.setOptr_id(optrId); int sues = -1; if (StringHelper.isNotEmpty(password)) { soptr.setPassword(MD5.EncodePassword(password)); } if (StringHelper.isNotEmpty(subSystemId)) { soptr.setLogin_sys_id(subSystemId); } sues = sOptrDao.update(soptr)[0]; if (sues>=0 || sues == -2){ return true; } return false ; } /** * 检查指定的操作员是否存在 * @param optr */ public SOptr checkOptrExists(SOptr optr)throws Exception{ if (null == optr) { return null; } SOptr _o = sOptrDao.isExists(optr.getLogin_name(), optr.getPassword()); if (null == _o) { return null; } return _o; } /** * 根据子系统id 返回对应的url,找不到返回空字符 * @param sysId * @return */ public SSubSystem querySubSystem(String sysId) throws JDBCException { return sSubSystemDao.findByKey(sysId); } /** * 取一个操作员的报表权限 * @param optr * @return * @throws ReportException */ public Integer queryRepRole(SOptr optr) throws ReportException{ try { Integer rep_role = null; SRole srole = sRoleDao.queryRepByOptrId( optr.getOptr_id()); if(optr.getLogin_name().equals("admin")) rep_role=0; else if(srole!=null) rep_role=SystemConfig.getRepDataLevel().get(srole.getData_right_level()).getItem_idx(); else rep_role=4; return rep_role; } catch (JDBCException e) { throw new ReportException(e); } } /** * 获取一个操作员对应system_key_map * @param optr * @return */ public Map<String, String> queryRepOptrSystemKeyMap(SOptr optr){ Map<String, String> systemmap = new HashMap<String, String>(); systemmap.put("#webareaid#", optr.getArea_id()); systemmap.put("#webcountyid#", optr.getCounty_id()); systemmap.put("#webdeptid#", optr.getDept_id()); systemmap.put("#weboptrid#", optr.getOptr_id()); return systemmap; } /** * 加载报表专用的资源菜单 * @param optr * @param sub_system_id * @return * @throws Exception */ public List<RepResourceDto> loadRepTabResource(SOptr optr,String sub_system_id)throws Exception{ List<RepResourceDto> list=queryRepDao.queryRepResources(optr,sub_system_id); if(BaseDataControl.getRole().hasFunc(FuncType.EDITREP)) for(RepResourceDto dto:list) dto.setRes_name(dto.getRes_name()+"_"+dto.getSort_num()); return list; } /** * 加载资源菜单 * @throws Exception */ public List<SResourceDto> loadTabResource(SOptr optr,String sub_system_id)throws Exception{ List<SResourceDto> list=sResourceDao.queryResourcesByOptr(optr,sub_system_id); if(BaseDataControl.getRole().hasFunc(FuncType.EDITREP)) for(SResourceDto dto:list) dto.setRes_name(dto.getRes_name()+"_"+dto.getSort_num()); return list; } public List<RepResourceDto> loadTabResourceID(SOptr optr,String sub_system_id)throws Exception{ List<RepResourceDto> list=queryRepDao.queryRepResources(optr,sub_system_id); for(RepResourceDto dto:list) dto.setRes_name(dto.getRes_name()+'('+dto.getRes_id()+')'); return list ; } public List<SResourceDto> queryResourcesByResType(String optrId,String subSystemId,String resType) throws Exception { return queryRepDao.queryResourcesByResType(optrId, subSystemId, resType); } public SOptrDao getSOptrDao() { return sOptrDao; } public void setSOptrDao(SOptrDao optrDao) { sOptrDao = optrDao; } public SResourceDao getSResourceDao() { return sResourceDao; } public void setSResourceDao(SResourceDao resourceDao) { sResourceDao = resourceDao; } public SRoleDao getSRoleDao() { return sRoleDao; } public void setSRoleDao(SRoleDao roleDao) { sRoleDao = roleDao; } public void setSSubSystemDao(SSubSystemDao subSystemDao) { sSubSystemDao = subSystemDao; } public void setQueryKeyValueDao(QueryKeyValueDao queryKeyValueDao) { this.queryKeyValueDao = queryKeyValueDao; } public void setSDataRightTypeDao(SDataRightTypeDao dataRightTypeDao) { sDataRightTypeDao = dataRightTypeDao; } public SOptrRoleDao getSOptrRoleDao() { return sOptrRoleDao; } public void setSOptrRoleDao(SOptrRoleDao optrRoleDao) { sOptrRoleDao = optrRoleDao; } public DataRoleInit getDataControl() { return dataControl; } public void setDataControl(DataRoleInit dataControl) { this.dataControl = dataControl; } }
{ "content_hash": "6e5ec9585dbd460861a12ebe46f54da6", "timestamp": "", "source": "github", "line_count": 322, "max_line_length": 118, "avg_line_length": 29.114906832298136, "alnum_prop": 0.7088, "repo_name": "leopardoooo/cambodia", "id": "34eb75a2a88b019dd9cc5839ad3fae7230c8ec30", "size": "9641", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "boss-report/src/main/java/com/ycsoft/report/component/system/IndexComponent.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "826" }, { "name": "CSS", "bytes": "1028439" }, { "name": "HTML", "bytes": "17547" }, { "name": "Java", "bytes": "14519872" }, { "name": "JavaScript", "bytes": "4711774" }, { "name": "Shell", "bytes": "2315" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Moderne JavaScript Entwicklung (Teil I)</title> <meta name="author" content="Thomas Pasch"> <meta name="description" content="Moderne Browser One Page Applications entwickeln Teil 1 - Grundlagen und Setup"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link rel="stylesheet" href="/assets/css/style.css"> <!-- jQuery --> <script src="/assets/js/jquery-1.11.1.min.js"></script> <!-- If the query includes 'print-pdf', include the PDF print sheet --> <script> if( window.location.search.match( /print-pdf/gi ) ) { var link = document.createElement( 'link' ); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = '/reveal.js/css/print/pdf.css'; document.getElementsByTagName( 'head' )[0].appendChild( link ); } </script> <!--[if lt IE 9]> <script src="/reveal.js/lib/js/html5shiv.js"></script> <![endif]--> </head> <body> <div class="reveal"> <div class="step"> <ul> <li>Serverseitige Ausführung von JS Code</li> <li>Ermöglicht JS ausserhalb des Browsers auszuführen</li> <li>Distribution enthält auch den <code class="highlighter-rouge">npm</code> Paketmanager</li> <li>Node ist <em>die</em> Grundlage JS Entwicklungs-Infrastruktur <br /> (Builder, Packer, Tester, Linter, …)</li> <li>Moderne JS Entwicklung ist ohne NodeJS schlicht nicht möglich</li> <li>Technisch: V8 (aus Chrome) + Module + <a href="http://libuv.org/" class="external"><code class="highlighter-rouge">libuv</code></a></li> </ul> </div> </div> </body> </html>
{ "content_hash": "77b07c138496a36accb01c3e16ec8fde", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 142, "avg_line_length": 33, "alnum_prop": 0.6872498570611778, "repo_name": "aanno/presentation-js1", "id": "019343ea609f9074979ee668b493d4f23b6ee0f6", "size": "1756", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "_site/node.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "499367" }, { "name": "HTML", "bytes": "620158" }, { "name": "JavaScript", "bytes": "433795" }, { "name": "Ruby", "bytes": "5354" }, { "name": "Shell", "bytes": "238" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; using SlimDX.Direct3D9; using mp.pddn; using VVVV.PluginInterfaces.V2; using VVVV.SkeletonInterfaces; using VVVV.Utils.VMath; namespace mp.essentials.Nodes.SkeletonV2 { [PluginInfo( Name = "MixPose", Category = "Skeleton", Version = "V2", Author = "microdee" )] public class V2SkeletonMixPose : ConfigurableDynamicPinNode<int>, IPluginEvaluate { [Config("Pose Count", DefaultValue = 2)] public IDiffSpread<int> FPoseCount; [Input("Animation Only", Order = 10000, DefaultBoolean = true)] public ISpread<bool> FAnimOnly; [Output("Skeleton")] public ISpread<ISkeleton> FOut; [Import] public IIOFactory FIOFactory; protected override void PreInitialize() { ConfigPinCopy = FPoseCount; Pins = new PinDictionary(FIOFactory); } protected override bool IsConfigDefault() { return FPoseCount[0] == 0; } protected override void OnConfigPinChanged() { var currposecount = Pins.InputPins.Count / 2; if (currposecount < FPoseCount[0]) { for (int i = currposecount; i < FPoseCount[0]; i++) { Pins.AddInput(typeof(ISkeleton), new InputAttribute($"Pose {i}") { Order = i * 2 }, obj: i); Pins.AddInput(typeof(double), new InputAttribute($"Amount {i}") { Order = i * 2 + 1, DefaultValue = 1 }, obj: i); } } if (currposecount > FPoseCount[0]) { for (int i = FPoseCount[0]; i < currposecount; i++) { Pins.RemoveInput($"Amount {i}"); Pins.RemoveInput($"Pose {i}"); } } } protected PinDictionary Pins; public void Evaluate(int SpreadMax) { if (Pins.InputPins.Count == 0 || Pins.InputSpreadMin == 0) { FOut.SliceCount = 0; return; } if (Pins.InputPins.Values.Any(pin => pin.Spread[0] == null)) return; FOut.SliceCount = Pins.InputSpreadMax; if (Pins.InputChanged) { FOut.Stream.IsChanged = true; var currposecount = Pins.InputPins.Count / 2; for (int i = 0; i < FOut.SliceCount; i++) { if (FOut[i] == null) FOut[i] = new Skeleton(); else ((ISkeleton)Pins.InputPins["Pose 0"].Spread[i]).CopyData(FOut[i]); var outSkeleton = FOut[i]; var outAmount = (double)Pins.InputPins["Amount 0"].Spread[i]; var outAmDiv = 1; for (int j = 1; j < currposecount; j++) { var currSkeleton = (ISkeleton)Pins.InputPins[$"Pose {j}"].Spread[i]; var currAmount = (double)Pins.InputPins[$"Amount {j}"].Spread[i]; foreach (var joint in outSkeleton.JointTable.Keys) { if(!currSkeleton.JointTable.ContainsKey(joint)) continue; Matrix4x4 result; if (!FAnimOnly[0]) { var currBase = currSkeleton.JointTable[joint].BaseTransform; var outBase = outSkeleton.JointTable[joint].BaseTransform; Matrix4x4Utils.Blend(outBase, currBase, outAmount / outAmDiv, currAmount, out result); outSkeleton.JointTable[joint].BaseTransform = result; } var currAnim = currSkeleton.JointTable[joint].AnimationTransform; var outAnim = outSkeleton.JointTable[joint].AnimationTransform; Matrix4x4Utils.Blend(outAnim, currAnim, outAmount / outAmDiv, currAmount, out result); outSkeleton.JointTable[joint].AnimationTransform = result; } outAmount += currAmount; outAmDiv++; } } } else { FOut.Stream.IsChanged = false; } } } }
{ "content_hash": "eccd5c52fc77c7ee2e4a408f42f5d086", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 118, "avg_line_length": 37.21875, "alnum_prop": 0.482367758186398, "repo_name": "microdee/mp.essentials", "id": "ec2ae7cbb4f17e2f1d150c9407698f8fc5518a3a", "size": "4766", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "skeleton/MixPose.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "696453" }, { "name": "HTML", "bytes": "263" } ], "symlink_target": "" }
//#include"hello.h" // #include "hello_prime.h" #include"hello_string.h" // struct sdshdr{ // unsigned int len; // unsigned int free; // char buf[];//zero length array,only allowd in struct's last element. // }; int main() { // printf("sizeof(struct sdshdr)=%zu\n",sizeof(struct sdshdr)); // test_prime(); test_strstr(); return 0; }
{ "content_hash": "a12402bfac0db35ce53fbb4dc9379c96", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 75, "avg_line_length": 20.210526315789473, "alnum_prop": 0.5755208333333334, "repo_name": "nilyang/redis-tdd-annotation", "id": "6f775ba1b1c45d2471a0a3faabcb10b44f71e9e2", "size": "441", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "zhack_c/hello_main.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2432613" }, { "name": "C++", "bytes": "2161" }, { "name": "Makefile", "bytes": "7656" }, { "name": "Ruby", "bytes": "53872" }, { "name": "Shell", "bytes": "11879" }, { "name": "Smarty", "bytes": "1023" }, { "name": "Tcl", "bytes": "363108" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "3ec1d41bc1a31b1c74b162c35eb48365", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "7a394cbef4f4c298901202ff123e443b6ab12833", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Calyptranthes/Calyptranthes multiflora/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package main import ( "flag" "fmt" "image" "image/color" "image/png" "math" "os" ) // Reading files requires checking most calls for errors. // This helper will streamline our error checks below. func check(e error) { if e != nil { fmt.Println(e) } } func FileNotFound(e error) { if e != nil { fmt.Println("Error: Source File not found!") fmt.Println(e) } } func DecodeError(e error) { if e != nil { fmt.Println("Error: File could not be opened! Please check file format. Only png is supported.") } } type Float2 struct { x float64 y float64 } /* inline float2 EncodeFloatRG( float v ) { float2 kEncodeMul = float2(1.0, 255.0); float kEncodeBit = 1.0/255.0; float2 enc = kEncodeMul * v; enc = frac (enc); enc.x -= enc.y * kEncodeBit; return enc; } */ func EncodeFloatRG(v float64) Float2 { encodeMul := Float2{1.0, 255.0} encodeBit := 1.0 / 255.0 enc := Float2{encodeMul.x * v, encodeMul.y * v} enc.x = enc.x - math.Floor(enc.x) enc.y = enc.y - math.Floor(enc.y) enc.x -= enc.y * encodeBit return enc } /* inline float DecodeFloatRG( float2 enc ) { float2 kDecodeDot = float2(1.0, 1/255.0); return dot( enc, kDecodeDot ); } func (v Vector) Dot(ov Vector) float64 { return v.X*ov.X + v.Y*ov.Y + v.Z*ov.Z } */ func DecodeFloatRG(v Float2) float64 { decodeDot := Float2{1.0, 1 / 255.0} return v.x*decodeDot.x + v.y*decodeDot.y } func Normalize(v float64) float64 { return v / 65535 } func DeNormalize(v float64) float64 { return v * 255 } func encode(filename string, outfilename string) { // filename := "CarBody_Normal.png" infile, err := os.Open(filename) FileNotFound(err) defer infile.Close() // Decode will figure out what type of image is in the file on its own. // We just have to be sure all the image packages we want are imported. src, _, err := image.Decode(infile) DecodeError(err) // Create a new image ignoring the alpha channel for color calculation bounds := src.Bounds() w, h := bounds.Max.X, bounds.Max.Y newImage := image.NewNRGBA(image.Rectangle{image.Point{0, 0}, image.Point{w, h}}) for x := 0; x < w; x++ { for y := 0; y < h; y++ { oldColor := src.At(x, y) r, g, _, _ := oldColor.RGBA() normR := float64(r) / 65535.0 normG := float64(g) / 65535.0 newr := EncodeFloatRG(normR) newg := EncodeFloatRG(normG) rrDe := DeNormalize(newr.x) rgDe := DeNormalize(newr.y) grDe := DeNormalize(newg.x) ggDe := DeNormalize(newg.y) if uint8(DeNormalize(normR))-uint8(rrDe) >= 10 { fmt.Printf("original: %v\n", normR) fmt.Printf("original as int: %v\n", uint8(DeNormalize(normR))) fmt.Printf("new: %v\n", newr.x) fmt.Printf("new as int: %v\n", uint8(DeNormalize(newr.x))) } // Set new color to current pixel newcolor := color.NRGBA{uint8(rrDe), uint8(rgDe), uint8(grDe), uint8(ggDe)} newImage.Set(x, y, newcolor) } } // Image is ready now and sits in RAM. Encode the image to the output file. outfile, err := os.Create(outfilename) check(err) defer outfile.Close() png.Encode(outfile, newImage) } var inFile string var outFile string func init() { flag.StringVar(&inFile, "source", "source.png", "Please enter the source image name") flag.StringVar(&outFile, "result", "result.png", "Please enter the result image name") flag.Parse() } func main() { encode(inFile, outFile) }
{ "content_hash": "5f7ba508e70913bf6d7cbc21bdde3b26", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 98, "avg_line_length": 23.53472222222222, "alnum_prop": 0.6491590439657716, "repo_name": "openminder/normalmap-decompositing", "id": "690bd4ce0c9212c11de8223c329a49bad0171594", "size": "3389", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "3389" } ], "symlink_target": "" }
'use strict' const { Path: { Line } } = require('paper') const { Tool } = require('./tool') const { Editor } = require('../editor') class OutletTool extends Tool { onMouseDown (ev) { if (this.editor._hitTarget) { if (this.editor.outlet) { this.editor.outlet.remove() } this.editor.outlet = this.editor._hitTarget this.editor._hitTarget = undefined this.editor.outlet.strokeColor = Editor.colors.orange if ( this.editor.inlet && this.editor.outlet.intersects(this.editor.inlet) ) { this.editor.inlet.remove() this.editor.inlet = undefined } } } onMouseMove (ev) { const hit = this.editor.pond.hitTest(ev.point) if (hit && 'location' in hit && hit.location.segment) { if (this.editor._hitTarget) { this.editor._hitTarget.remove() this.editor._hitTarget = undefined } const segment = new Line( hit.location.curve.point1, hit.location.curve.point2 ) segment.strokeCap = 'round' segment.strokeColor = Editor.colors.red segment.strokeWidth = 5 this.editor.baseLayer.addChild(segment) this.editor._hitTarget = segment } else { if (this.editor._hitTarget) { this.editor._hitTarget.remove() this.editor._hitTarget = undefined } } } } module.exports = { OutletTool }
{ "content_hash": "a0d7eb89e45894d7431635d9c94fa1e4", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 59, "avg_line_length": 23.4, "alnum_prop": 0.6018518518518519, "repo_name": "mike-brown/ponds-online", "id": "94a697d38ff021474f11acff5940e0a7e56bc854", "size": "1404", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/tools/outlet-tool.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4079" }, { "name": "HTML", "bytes": "32068" }, { "name": "JavaScript", "bytes": "63550" }, { "name": "Shell", "bytes": "1342" } ], "symlink_target": "" }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview Polymer element for displaying information about a network * in a list or summary based on ONC state properties. */ (function() { /** * TODO(stevenjb): Replace getText with a proper localization function that * handles string substitution. * Performs argument substitution, replacing %1, %2, etc in 'text' with * corresponding entries in |args|. * @param {string} text The string to perform the substitution on. * @param {?Array<string>} args The arguments to replace %1, %2, etc with. */ function getText(text, args) { var res = text; if (!args) return res; for (var i = 0; i < args.length; ++i) { var key = '%' + (i + 1); res = res.replace(key, args[i]); } return res; } /** * Returns the appropriate connection state text. * @param {string} state The connection state. * @param {string} name The name of the network. */ function getConnectionStateText(state, name) { if (state == CrOnc.ConnectionState.CONNECTED) return getText('Connected to %1', [name]); if (state == CrOnc.ConnectionState.CONNECTING) return getText('Connecting to %1...', [name]); if (state == CrOnc.ConnectionState.NOT_CONNECTED) return getText('Not Connected'); return getText(state); }; /** * Polymer class definition for 'network-list-item'. * @element network-list-item */ Polymer({ is: 'network-list-item', properties: { /** * The ONC data properties used to display the list item. * * @type {?CrOnc.NetworkStateProperties} */ networkState: { type: Object, value: null, observer: 'networkStateChanged_' }, /** * If true, the element is part of a list of networks and only displays * the network icon and name. Otherwise the element is assumed to be a * stand-alone item (e.g. as part of a summary) and displays the name * of the network type plus the network name and connection state. */ isListItem: { type: Boolean, value: false, observer: 'networkStateChanged_' }, }, /** * Polymer networkState changed method. Updates the element based on the * network state. */ networkStateChanged_: function() { if (!this.networkState) return; var network = this.networkState; var isDisconnected = network.ConnectionState == CrOnc.ConnectionState.NOT_CONNECTED; if (this.isListItem) { var name = getText(network.Name) || getText(network.Type); this.$.networkName.textContent = name; this.$.networkName.classList.toggle('connected', !isDisconnected); return; } if (network.Name && network.ConnectionState) { this.$.networkName.textContent = getText(network.Type); this.$.networkName.classList.toggle('connected', false); this.$.networkStateText.textContent = getConnectionStateText(network.ConnectionState, network.Name); this.$.networkStateText.classList.toggle('connected', !isDisconnected); return; } this.$.networkName.textContent = getText(network.Type); this.$.networkName.classList.toggle('connected', false); this.$.networkStateText.textContent = getText('Disabled'); this.$.networkStateText.classList.toggle('connected', false); if (network.Type == CrOnc.Type.CELLULAR) { if (!network.GUID) this.$.networkStateText.textContent = getText('Uninitialized'); } }, /** * @param {string} isListItem The value of this.isListItem. * @return {string} The class name based on isListItem. * @private */ isListItemClass_: function(isListItem) { return isListItem ? 'list-item' : ''; } }); })();
{ "content_hash": "bfe6d3311630cc5ec21cee22870bf242", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 77, "avg_line_length": 31.188524590163933, "alnum_prop": 0.6654402102496715, "repo_name": "Just-D/chromium-1", "id": "fb668450205f30d54c8a5c683dbb03c7badc6585", "size": "3805", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chrome/browser/resources/settings/internet_page/network_list_item.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "37073" }, { "name": "Batchfile", "bytes": "8451" }, { "name": "C", "bytes": "9517927" }, { "name": "C++", "bytes": "244067615" }, { "name": "CSS", "bytes": "944025" }, { "name": "DM", "bytes": "60" }, { "name": "Groff", "bytes": "2494" }, { "name": "HTML", "bytes": "27307576" }, { "name": "Java", "bytes": "14757472" }, { "name": "JavaScript", "bytes": "20666212" }, { "name": "Makefile", "bytes": "70864" }, { "name": "Objective-C", "bytes": "1772355" }, { "name": "Objective-C++", "bytes": "10088862" }, { "name": "PHP", "bytes": "97817" }, { "name": "PLpgSQL", "bytes": "178732" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "485040" }, { "name": "Python", "bytes": "8652947" }, { "name": "Shell", "bytes": "481276" }, { "name": "Standard ML", "bytes": "5106" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
package ca.efendi.socialcomments.web.internal.portlet; import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet; import org.osgi.service.component.annotations.Component; import javax.portlet.Portlet; @Component( immediate = true, property = { "com.liferay.portlet.css-class-wrapper=portlet-jsp", "com.liferay.portlet.display-category=category.sample", "com.liferay.portlet.header-portlet-css=/css/main.css", "com.liferay.portlet.instanceable=true", "javax.portlet.display-name=JSP Portlet No. 2", "javax.portlet.init-param.template-path=/", "javax.portlet.init-param.view-template=/view2.jsp", "javax.portlet.resource-bundle=content.Language", "javax.portlet.security-role-ref=power-user,user" }, service = Portlet.class ) public class JSPPortlet extends MVCPortlet { }
{ "content_hash": "ae04795577e951c7371dbf63936be7f2", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 64, "avg_line_length": 32.08, "alnum_prop": 0.770573566084788, "repo_name": "FuadEfendi/liferay-osgi", "id": "91542a43fed792b5ee385467f366188acd758314", "size": "802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/ca.efendi.socialcomments.web/src/main/java/ca/efendi/socialcomments/web/internal/portlet/JSPPortlet.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "19221" }, { "name": "FreeMarker", "bytes": "5966" }, { "name": "Java", "bytes": "951168" }, { "name": "JavaScript", "bytes": "498" } ], "symlink_target": "" }
class AddRestrictDeploymentOrderToProjectCiCdSettings < ActiveRecord::Migration[5.2] DOWNTIME = false def change add_column :project_ci_cd_settings, :forward_deployment_enabled, :boolean end end
{ "content_hash": "8dc8e70a898047acba9ca51a38802b94", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 84, "avg_line_length": 29.428571428571427, "alnum_prop": 0.7864077669902912, "repo_name": "mmkassem/gitlabhq", "id": "6a222ce8d516579a920f8a3b7a67abd51e499111", "size": "237", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "db/migrate/20200124143014_add_restrict_deployment_order_to_project_ci_cd_settings.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "113683" }, { "name": "CoffeeScript", "bytes": "139197" }, { "name": "Cucumber", "bytes": "119759" }, { "name": "HTML", "bytes": "447030" }, { "name": "JavaScript", "bytes": "29805" }, { "name": "Ruby", "bytes": "2417833" }, { "name": "Shell", "bytes": "14336" } ], "symlink_target": "" }
using System; namespace DotSpatial.Controls.Header { /// <summary> /// Event args of the SelectedValueChanged event. /// </summary> public class SelectedValueChangedEventArgs : EventArgs { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="SelectedValueChangedEventArgs"/> class. /// </summary> public SelectedValueChangedEventArgs() { } /// <summary> /// Initializes a new instance of the <see cref="SelectedValueChangedEventArgs"/> class. /// </summary> /// <param name="selectedItem">The selected item.</param> public SelectedValueChangedEventArgs(object selectedItem) { SelectedItem = selectedItem; } #endregion #region Properties /// <summary> /// Gets or sets the selected item. /// </summary> /// <value> /// The selected item. /// </value> public object SelectedItem { get; set; } #endregion } }
{ "content_hash": "b69b3e83dc6e621036d040b7bc376bef", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 96, "avg_line_length": 25.930232558139537, "alnum_prop": 0.5479820627802691, "repo_name": "pergerch/DotSpatial", "id": "63709ce191f623caa7d7a76e0cf3fa5ba9fa630a", "size": "1278", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Source/DotSpatial.Controls/Header/SelectedValueChangedEventArgs.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "1639" }, { "name": "Batchfile", "bytes": "1711" }, { "name": "C#", "bytes": "16400752" }, { "name": "CSS", "bytes": "490" }, { "name": "HTML", "bytes": "8176" }, { "name": "JavaScript", "bytes": "133570" }, { "name": "Smalltalk", "bytes": "412910" }, { "name": "Visual Basic .NET", "bytes": "459040" } ], "symlink_target": "" }
package io.scigraph.internal.reachability; import java.util.Collections; import java.util.Set; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.traversal.Evaluation; import org.neo4j.graphdb.traversal.Evaluator; import com.google.common.base.Predicate; final class ReachabilityEvaluator implements Evaluator { private final InMemoryReachabilityIndex inMemoryIndex; private final Direction direction; private final Predicate<Node> nodePredicate; ReachabilityEvaluator(InMemoryReachabilityIndex inMemoryIdx, Direction direction, Predicate<Node> nodePredicate) { this.inMemoryIndex = inMemoryIdx; this.direction = direction; this.nodePredicate = nodePredicate; } @Override public Evaluation evaluate(Path path) { long currentId = path.endNode().getId(); if (!nodePredicate.apply(path.endNode())) { inMemoryIndex.get(currentId); return Evaluation.EXCLUDE_AND_PRUNE; } long startId = path.startNode().getId(); // Vi InOutList listPair = inMemoryIndex.get(currentId); if (0 == path.length()) { // first node in the traverse - add itself to the in-out list listPair.getInList().add(currentId); listPair.getOutList().add(currentId); return Evaluation.INCLUDE_AND_CONTINUE; } else if (direction == Direction.INCOMING ) { // doing reverse BFS if (nodesAreConnected(currentId, startId)) { return Evaluation.EXCLUDE_AND_PRUNE; } else { listPair.getOutList().add(startId); return Evaluation.INCLUDE_AND_CONTINUE; } } else { //doing BFS if (nodesAreConnected(startId, currentId)) { // cur is w return Evaluation.EXCLUDE_AND_PRUNE; } else { listPair.getInList().add(startId); return Evaluation.INCLUDE_AND_CONTINUE; } } } boolean nodesAreConnected(long nodeIdOut, long nodeIdIn) { Set<Long> outList = inMemoryIndex.get(nodeIdOut).getOutList(); Set<Long> inList = inMemoryIndex.get(nodeIdIn).getInList(); return !Collections.disjoint(outList, inList); } }
{ "content_hash": "e4fb47a467ecbdf3a5ec82f852efc695", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 67, "avg_line_length": 31.338028169014084, "alnum_prop": 0.6791011235955056, "repo_name": "SciGraph/SciGraph", "id": "a151d41f7d825c8281779a295e0aaf02de12d02a", "size": "2851", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "SciGraph-core/src/main/java/io/scigraph/internal/reachability/ReachabilityEvaluator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "307" }, { "name": "HTML", "bytes": "5854" }, { "name": "Java", "bytes": "896391" }, { "name": "Shell", "bytes": "6588" } ], "symlink_target": "" }
<?php namespace Rodchyn\ElephantLang; use Rodchyn\ElephantLang\Parser\Parser; class Token implements \ArrayAccess { const TOKEN_OUTPUT_FORMAT = "%-4s %-3s %-7s %-14s %-s\n"; /** * @var string */ public $symbol; public $metadata = array(); public $value = null; public $absolutePosition = null; public $lineNumber = null; public $columnNumber = null; /** * @param $symbol string * @param $value * @param $absolutePosition * @param $lineNumber * @param $columnNumber */ public function __construct($symbol, $value, $absolutePosition, $lineNumber, $columnNumber) { $this->symbol = $symbol; $this->value = $value; $this->absolutePosition = $absolutePosition; $this->lineNumber = $lineNumber; $this->columnNumber = $columnNumber; $this[0] = Parser::tokenNumberByName($symbol); $this[1] = $value; $this[2] = $lineNumber; } public static function getMatchSymbol($match) { foreach ($match as $key => $value) { if (is_string($key) && $value[0] != '') return $key; } return null; } public static function FromPCREMatch($match, $textLines) { $symbol = self::getMatchSymbol($match); $value = $match[0][0]; $position = $match[0][1]; $textLine = $textLines->textLineForAbsolutePosition($position); $lineNumber = $textLine->lineNumber; $columnNumber = $position - $textLine->start + 1; return new Token($symbol, $value, $position, $lineNumber, $columnNumber); } public static function debugEscapeNewlines($string) { return str_replace("\n", '\n', $string); } public static function debugPrintColumnHeadings() { printf(static::TOKEN_OUTPUT_FORMAT, 'pos', 'len', 'lin/col', '', ''); } public function debugPrint() { $tokenLength = strlen($this->value); $value = self::debugEscapeNewlines($this->value); printf(static::TOKEN_OUTPUT_FORMAT, $this->absolutePosition, $tokenLength, $this->lineNumber . '/' . $this->columnNumber, $this->symbol, $value); } public function __toString() { return $this->symbol; } public function offsetExists($offset) { return isset($this->metadata[$offset]); } public function offsetGet($offset) { return $this->metadata[$offset]; } public function offsetSet($offset, $value) { if ($offset === null) { if (isset($value[0])) { $x = ($value instanceof yyToken) ? $value->metadata : $value; $this->metadata = array_merge($this->metadata, $x); return; } $offset = count($this->metadata); } if ($value === null) { return; } if ($value instanceof yyToken) { if ($value->metadata) { $this->metadata[$offset] = $value->metadata; } } elseif ($value) { $this->metadata[$offset] = $value; } } public function offsetUnset($offset) { unset($this->metadata[$offset]); } }
{ "content_hash": "226a750dd6d7ae02223513bcf9c0b961", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 95, "avg_line_length": 26.64516129032258, "alnum_prop": 0.5414648910411622, "repo_name": "rodchyn/elephant-lang", "id": "14c7903f99eedf2ecfe76e960fbeee96630de63d", "size": "3304", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Token.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "319213" } ], "symlink_target": "" }
require "spec_helper" describe "it should be work" do before do @config = Conf.build :test do env :production do port 666 server :env do mail 123 host "" end end env :test, :parent => :production do port 777 end end end it "should be instance of conf" do @config.should be_an_instance_of Conf::Configus end it "should be work key value" do @config.port.should == 777 end it "should be work key value with hierarchy" do @config.server.mail.should == 123 end it "should be work when value empty" do @config.server.host.should be_empty end it "should be " do @config.server.host.should be_empty end end
{ "content_hash": "9b54b82aca9f7bec10a1f2c5956b46d8", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 51, "avg_line_length": 18.35, "alnum_prop": 0.6103542234332425, "repo_name": "PlugIN73/conf", "id": "960eeb392e990e144fe51742deec6c391bd59ab3", "size": "734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/conf_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "904" } ], "symlink_target": "" }
/* (C) 2015 AARO4130 DO NOT USE PARTS OF, OR THE ENTIRE SCRIPT, AND CLAIM AS YOUR OWN WORK */ using System; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.IO; using System.Linq; using System.Text.RegularExpressions; #if UNITY_EDITOR //using UnityEditor; #endif public class OBJLoader { public static bool splitByMaterial = false; public static string[] searchPaths = new string[] { "", "%FileName%_Textures" + Path.DirectorySeparatorChar }; //structures struct OBJFace { public string materialName; public string meshName; public int[] indexes; } //functions #if UNITY_EDITOR #endif public static Vector3 ParseVectorFromCMPS(string[] cmps) { float x = float.Parse(cmps[1]); float y = float.Parse(cmps[2]); if (cmps.Length == 4) { float z = float.Parse(cmps[3]); return new Vector3(x, y, z); } return new Vector2(x, y); } public static Color ParseColorFromCMPS(string[] cmps,float scalar = 1.0f) { float Kr = float.Parse(cmps[1]) * scalar ; float Kg = float.Parse(cmps[2]) * scalar; float Kb = float.Parse(cmps[3]) * scalar; return new Color(Kr, Kg, Kb); } public static string OBJGetFilePath(string path, string basePath, string fileName) { foreach (string sp in searchPaths) { string s = sp.Replace("%FileName%", fileName); if (File.Exists(basePath + s + path)) { return basePath + s + path; } else if (File.Exists(path)) { return path; } } return null; } public static Material[] LoadMTLFile(string fn) { Material currentMaterial = null; List<Material> matlList = new List<Material>(); FileInfo mtlFileInfo = new FileInfo(fn); string baseFileName = Path.GetFileNameWithoutExtension(fn); string mtlFileDirectory = mtlFileInfo.Directory.FullName + Path.DirectorySeparatorChar; foreach (string ln in File.ReadAllLines(fn)) { string l = ln.Trim().Replace(" ", " "); string[] cmps = l.Split(' '); string data = l.Remove(0, l.IndexOf(' ') + 1); if (cmps[0] == "newmtl") { if (currentMaterial != null) { matlList.Add(currentMaterial); } currentMaterial = new Material(Shader.Find("Standard")); currentMaterial.name = data; } else if (cmps[0] == "Kd") { currentMaterial.SetColor("_Color",ParseColorFromCMPS(cmps)); } else if (cmps[0] == "map_Kd") { //TEXTURE string fpth = OBJGetFilePath(data, mtlFileDirectory,baseFileName); if (fpth != null) currentMaterial.SetTexture("_MainTex",TextureLoader.LoadTexture(fpth)); } else if (cmps[0] == "map_Bump") { //TEXTURE string fpth = OBJGetFilePath(data, mtlFileDirectory,baseFileName); if (fpth != null) { currentMaterial.SetTexture("_BumpMap", TextureLoader.LoadTexture(fpth, true)); currentMaterial.EnableKeyword("_NORMALMAP"); } } else if (cmps[0] == "Ks") { currentMaterial.SetColor("_SpecColor", ParseColorFromCMPS(cmps)); } else if (cmps[0] == "Ka") { currentMaterial.SetColor("_EmissionColor", ParseColorFromCMPS(cmps, 0.05f)); currentMaterial.EnableKeyword("_EMISSION"); } else if (cmps[0] == "d") { float visibility = float.Parse(cmps[1]); if (visibility < 1) { Color temp = currentMaterial.color; temp.a = visibility; currentMaterial.SetColor("_Color", temp); //TRANSPARENCY ENABLER currentMaterial.SetFloat("_Mode", 3); currentMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); currentMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); currentMaterial.SetInt("_ZWrite", 0); currentMaterial.DisableKeyword("_ALPHATEST_ON"); currentMaterial.EnableKeyword("_ALPHABLEND_ON"); currentMaterial.DisableKeyword("_ALPHAPREMULTIPLY_ON"); currentMaterial.renderQueue = 3000; } } else if (cmps[0] == "Ns") { float Ns = float.Parse(cmps[1]); Ns = (Ns / 1000); currentMaterial.SetFloat("_Glossiness", Ns); } } if(currentMaterial != null) { matlList.Add(currentMaterial); } return matlList.ToArray(); } public static GameObject LoadOBJFile(string fn) { Debug.Log("Executed"); string meshName = Path.GetFileNameWithoutExtension(fn); bool hasNormals = false; //OBJ LISTS List<Vector3> vertices = new List<Vector3>(); List<Vector3> normals = new List<Vector3>(); List<Vector2> uvs = new List<Vector2>(); //UMESH LISTS List<Vector3> uvertices = new List<Vector3>(); List<Vector3> unormals = new List<Vector3>(); List<Vector2> uuvs = new List<Vector2>(); //MESH CONSTRUCTION List<string> materialNames = new List<string>(); List<string> objectNames = new List<string>(); Dictionary<string,int> hashtable = new Dictionary<string, int>(); List<OBJFace> faceList = new List<OBJFace>(); string cmaterial = ""; string cmesh = "default"; //CACHE Material[] materialCache = null; //save this info for later FileInfo OBJFileInfo = new FileInfo(fn); foreach (string ln in File.ReadAllLines(fn)) { if (ln.Length > 0 && ln[0] != '#') { string l = ln.Trim().Replace(" "," "); string[] cmps = l.Split(' '); string data = l.Remove(0, l.IndexOf(' ') + 1); if (cmps[0] == "mtllib") { //load cache string pth = OBJGetFilePath(data, OBJFileInfo.Directory.FullName + Path.DirectorySeparatorChar, meshName); if (pth != null) materialCache = LoadMTLFile(pth); } else if ((cmps[0] == "g" || cmps[0] == "o") && splitByMaterial == false) { cmesh = data; if (!objectNames.Contains(cmesh)) { objectNames.Add(cmesh); } } else if (cmps[0] == "usemtl") { cmaterial = data; if (!materialNames.Contains(cmaterial)) { materialNames.Add(cmaterial); } if (splitByMaterial) { if (!objectNames.Contains(cmaterial)) { objectNames.Add(cmaterial); } } } else if (cmps[0] == "v") { //VERTEX vertices.Add(ParseVectorFromCMPS(cmps)); } else if (cmps[0] == "vn") { //VERTEX NORMAL normals.Add(ParseVectorFromCMPS(cmps)); } else if (cmps[0] == "vt") { //VERTEX UV uvs.Add(ParseVectorFromCMPS(cmps)); } else if (cmps[0] == "f") { int[] indexes = new int[cmps.Length - 1]; for (int i = 1; i < cmps.Length ; i++) { string felement = cmps[i]; int vertexIndex = -1; int normalIndex = -1; int uvIndex = -1; if (felement.Contains("//")) { //doubleslash, no UVS. string[] elementComps = felement.Split('/'); vertexIndex = int.Parse(elementComps[0]) - 1; normalIndex = int.Parse(elementComps[2]) - 1; } else if (felement.Count(x => x == '/') == 2) { //contains everything string[] elementComps = felement.Split('/'); vertexIndex = int.Parse(elementComps[0]) - 1; uvIndex = int.Parse(elementComps[1]) - 1; normalIndex = int.Parse(elementComps[2]) - 1; } else if (!felement.Contains("/")) { //just vertex inedx vertexIndex = int.Parse(felement) - 1; } else { //vertex and uv string[] elementComps = felement.Split('/'); vertexIndex = int.Parse(elementComps[0]) - 1; uvIndex = int.Parse(elementComps[1]) - 1; } string hashEntry = vertexIndex + "|" + normalIndex + "|" +uvIndex; if (hashtable.ContainsKey(hashEntry)) { indexes[i - 1] = hashtable[hashEntry]; } else { //create a new hash entry indexes[i - 1] = hashtable.Count; hashtable[hashEntry] = hashtable.Count; uvertices.Add(vertices[vertexIndex]); if (normalIndex < 0 || (normalIndex > (normals.Count - 1))) { unormals.Add(Vector3.zero); } else { hasNormals = true; unormals.Add(normals[normalIndex]); } if (uvIndex < 0 || (uvIndex > (uvs.Count - 1))) { uuvs.Add(Vector2.zero); } else { uuvs.Add(uvs[uvIndex]); } } } if (indexes.Length < 5 && indexes.Length >= 3) { OBJFace f1 = new OBJFace(); f1.materialName = cmaterial; f1.indexes = new int[] { indexes[0], indexes[1], indexes[2] }; f1.meshName = (splitByMaterial) ? cmaterial : cmesh; faceList.Add(f1); if (indexes.Length > 3) { OBJFace f2 = new OBJFace(); f2.materialName = cmaterial; f2.meshName = (splitByMaterial) ? cmaterial : cmesh; f2.indexes = new int[] { indexes[2], indexes[3], indexes[0] }; faceList.Add(f2); } } } } } if (objectNames.Count == 0) objectNames.Add("default"); //build objects GameObject parentObject = new GameObject(meshName); foreach (string obj in objectNames) { GameObject subObject = new GameObject(obj); subObject.transform.parent = parentObject.transform; subObject.transform.localScale = new Vector3(-1, 1, 1); //Create mesh Mesh m = new Mesh(); m.name = obj; //LISTS FOR REORDERING List<Vector3> processedVertices = new List<Vector3>(); List<Vector3> processedNormals = new List<Vector3>(); List<Vector2> processedUVs = new List<Vector2>(); List<int[]> processedIndexes = new List<int[]>(); Dictionary<int,int> remapTable = new Dictionary<int, int>(); //POPULATE MESH List<string> meshMaterialNames = new List<string>(); OBJFace[] ofaces = faceList.Where(x => x.meshName == obj).ToArray(); foreach (string mn in materialNames) { OBJFace[] faces = ofaces.Where(x => x.materialName == mn).ToArray(); if (faces.Length > 0) { int[] indexes = new int[0]; foreach (OBJFace f in faces) { int l = indexes.Length; System.Array.Resize(ref indexes, l + f.indexes.Length); System.Array.Copy(f.indexes, 0, indexes, l, f.indexes.Length); } meshMaterialNames.Add(mn); if (m.subMeshCount != meshMaterialNames.Count) m.subMeshCount = meshMaterialNames.Count; for (int i = 0; i < indexes.Length; i++) { int idx = indexes[i]; //build remap table if (remapTable.ContainsKey(idx)) { //ezpz indexes[i] = remapTable[idx]; } else { processedVertices.Add(uvertices[idx]); processedNormals.Add(unormals[idx]); processedUVs.Add(uuvs[idx]); remapTable[idx] = processedVertices.Count - 1; indexes[i] = remapTable[idx]; } } processedIndexes.Add(indexes); } else { } } //apply stuff m.vertices = processedVertices.ToArray(); m.normals = processedNormals.ToArray(); m.uv = processedUVs.ToArray(); for (int i = 0; i < processedIndexes.Count; i++) { m.SetTriangles(processedIndexes[i],i); } if (!hasNormals) { m.RecalculateNormals(); } m.RecalculateBounds(); ; MeshFilter mf = subObject.AddComponent<MeshFilter>(); MeshRenderer mr = subObject.AddComponent<MeshRenderer>(); Material[] processedMaterials = new Material[meshMaterialNames.Count]; for(int i=0 ; i < meshMaterialNames.Count; i++) { if (materialCache == null) { processedMaterials[i] = new Material(Shader.Find("Standard (Specular setup)")); } else { Material mfn = Array.Find(materialCache, x => x.name == meshMaterialNames[i]); ; if (mfn == null) { processedMaterials[i] = new Material(Shader.Find("Standard (Specular setup)")); } else { processedMaterials[i] = mfn; } } processedMaterials[i].name = meshMaterialNames[i]; } mr.materials = processedMaterials; mf.mesh = m; } return parentObject; } }
{ "content_hash": "7f75ac3e9bc90199adf8f7204f7046f9", "timestamp": "", "source": "github", "line_count": 448, "max_line_length": 126, "avg_line_length": 37.421875, "alnum_prop": 0.4336415150611393, "repo_name": "Bitlandia/WorldScripter", "id": "cdaa2a37e235a1e4b346e3660aa9ce195998cfc9", "size": "16767", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WorldScripter/Assets/OBJImport/OBJLoader.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "219127" } ], "symlink_target": "" }
<HTML> <HEAD> <meta charset="UTF-8"> <title>Crossword.FLAG_NO_SOLUTION - library</title> <link rel="stylesheet" href="../../../style.css"> </HEAD> <BODY> <a href="../../index.html">library</a>&nbsp;/&nbsp;<a href="../index.html">org.akop.ararat.core</a>&nbsp;/&nbsp;<a href="index.html">Crossword</a>&nbsp;/&nbsp;<a href="./-f-l-a-g_-n-o_-s-o-l-u-t-i-o-n.html">FLAG_NO_SOLUTION</a><br/> <br/> <h1>FLAG_NO_SOLUTION</h1> <a name="org.akop.ararat.core.Crossword.Companion$FLAG_NO_SOLUTION"></a> <code><span class="keyword">const</span> <span class="keyword">val </span><span class="identifier">FLAG_NO_SOLUTION</span><span class="symbol">: </span><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html"><span class="identifier">Int</span></a></code> </BODY> </HTML>
{ "content_hash": "0d1d0816310c054e1233cbf66846821a", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 276, "avg_line_length": 56.07142857142857, "alnum_prop": 0.6662420382165605, "repo_name": "pokebyte/ararat", "id": "d998a2b9f09a8434dcae71f4e0640ae76a707de1", "size": "785", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/library/org.akop.ararat.core/-crossword/-f-l-a-g_-n-o_-s-o-l-u-t-i-o-n.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "227338" } ], "symlink_target": "" }
<!-- --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>GLSL array equality test</title> <link rel="stylesheet" href="../../resources/js-test-style.css"/> <script src="../../resources/js-test-pre.js"></script> <script src="../../conformance/resources/webgl-test-utils.js"></script> </head> <body> <canvas id="canvas" width="64" height="64"> </canvas> <div id="description"></div> <div id="console"></div> <script id="vshader" type="x-shader/x-vertex">#version 300 es in vec3 aPosition; void main() { gl_Position = vec4(aPosition, 1); } </script> <script id="fshaderSimple" type="x-shader/x-fragment">#version 300 es precision mediump float; out vec4 my_FragColor; void main() { // This simple test uses the ESSL1 style array initialization in order // to be able to test array equality independently of array constructors. int a[3]; int b[3]; int c[3]; for (int i = 0; i < 3; ++i) { a[i] = i; b[i] = i; c[i] = i + 1; } bool success = (a == b) && (a != c); my_FragColor = vec4(0.0, (success ? 1.0 : 0.0), 0.0, 1.0); } </script> <script id="fshaderArrayOfStructs" type="x-shader/x-fragment">#version 300 es precision mediump float; out vec4 my_FragColor; struct S { int foo; }; void main() { // This simple test uses the ESSL1 style array initialization in order // to be able to test array equality independently of array constructors. S a[3]; S b[3]; S c[3]; for (int i = 0; i < 3; ++i) { a[i].foo = i; b[i].foo = i; c[i].foo = i + 1; } bool success = (a == b) && (a != c); my_FragColor = vec4(0.0, (success ? 1.0 : 0.0), 0.0, 1.0); } </script> <script type="text/javascript"> "use strict"; description("Comparing arrays should work."); debug(""); var wtu = WebGLTestUtils; function test() { var gl = wtu.create3DContext("canvas", undefined, 2); if (!gl) { testFailed("WebGL 2 context does not exist"); return; } wtu.setupUnitQuad(gl); debug("Testing with arrays of integers"); wtu.setupProgram(gl, ["vshader", "fshaderSimple"], ["aPosition"], undefined, true); wtu.drawUnitQuad(gl); wtu.checkCanvas(gl, [0, 255, 0, 255]); debug(""); debug("Testing with arrays of structs"); wtu.setupProgram(gl, ["vshader", "fshaderArrayOfStructs"], ["aPosition"], undefined, true); wtu.clearAndDrawUnitQuad(gl); wtu.checkCanvas(gl, [0, 255, 0, 255]); }; test(); var successfullyParsed = true; finishTest(); </script> </body> </html>
{ "content_hash": "654677037214aa4480be75d9714ee62b", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 93, "avg_line_length": 24.57843137254902, "alnum_prop": 0.6178699641005185, "repo_name": "guorendong/iridium-browser-ubuntu", "id": "ad2ed436a135944339bc0e3bec6d22c68de1ed3f", "size": "3648", "binary": false, "copies": "1", "ref": "refs/heads/ubuntu/precise", "path": "third_party/webgl/src/sdk/tests/conformance2/glsl3/array-equality.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "8402" }, { "name": "Assembly", "bytes": "256197" }, { "name": "Batchfile", "bytes": "34966" }, { "name": "C", "bytes": "15445429" }, { "name": "C++", "bytes": "276628399" }, { "name": "CMake", "bytes": "27829" }, { "name": "CSS", "bytes": "867238" }, { "name": "Emacs Lisp", "bytes": "3348" }, { "name": "Go", "bytes": "13628" }, { "name": "Groff", "bytes": "7777" }, { "name": "HTML", "bytes": "20250399" }, { "name": "Java", "bytes": "9950308" }, { "name": "JavaScript", "bytes": "13873772" }, { "name": "LLVM", "bytes": "1169" }, { "name": "Logos", "bytes": "6893" }, { "name": "Lua", "bytes": "16189" }, { "name": "Makefile", "bytes": "179129" }, { "name": "Objective-C", "bytes": "1871766" }, { "name": "Objective-C++", "bytes": "9674498" }, { "name": "PHP", "bytes": "42038" }, { "name": "PLpgSQL", "bytes": "163248" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "474121" }, { "name": "Python", "bytes": "11646662" }, { "name": "Ragel in Ruby Host", "bytes": "104923" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "1151673" }, { "name": "Standard ML", "bytes": "5034" }, { "name": "VimL", "bytes": "4075" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>reveal.js - The HTML Presentation Framework</title> <meta name="description" content="A framework for easily creating beautiful presentations using HTML"> <meta name="author" content="Hakim El Hattab"> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link rel="stylesheet" href="css/reveal.min.css"> <link rel="stylesheet" href="css/theme/default.css" id="theme"> <!-- For syntax highlighting --> <link rel="stylesheet" href="lib/css/zenburn.css"> <!-- If the query includes 'print-pdf', include the PDF print sheet --> <script> if( window.location.search.match( /print-pdf/gi ) ) { var link = document.createElement( 'link' ); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'css/print/pdf.css'; document.getElementsByTagName( 'head' )[0].appendChild( link ); } </script> <style> .done-button{ position: relative; bottom: 410px; left: 500px } .done-button:hover{ cursor: hand; cursor: pointer; } </style> <!--[if lt IE 9]> <script src="lib/js/html5shiv.js"></script> <![endif]--> </head> <body> <div class="reveal"> <!-- Any section element inside of this container is displayed as a slide --> <div class="slides"> <section> <image style="border:none;" src="http://upload.wikimedia.org/wikipedia/commons/7/79/Docker_%28container_engine%29_logo.png"> <div class="fragment"> <h1>Not</h1> <image style="border:none;" src="http://www.pantalones.net/files/2011/03/logo-dockers.jpg"> </div> <p> <small>Created by <a href="http://duncan.fedde.us">Duncan Fedde</a> / <a href="http://twitter.com/dfedde">@dfedde</a></small> </p> <aside class="notes"> Goals for this presentation: <ul> <li>make a image by hand</li> <li>make a image by dockerfile</li> <li>start an image</li> <li>handle data in a container</li> <li>handle port forwarding</li> <li>handle sharing data between containers</li> <li>provide a sample way to deploy docker on a server</li> </ul> start out by asking about background in linux source control and if admin or developer </aside> </section> <!-- <section> --> <!-- <h3 class="fragment">my name is <a href="http://duncan.fedde.us">Duncan Fedde</a></h3> --> <!-- </section> --> <section> <h2>What will we be doing Today?</h2> <ul> <li class="fragment">make a image by hand</li> <li class="fragment">make a image by dockerfile</li> <li class="fragment">start an image</li> <li class="fragment">handle data in a container</li> <li class="fragment">handle port forwarding</li> <li class="fragment">handle sharing data between containers</li> <li class="fragment">provide a sample way to deploy docker on a server</li> </ul> </section> <section> <h2>but most of all</h2> </section> <section> <h2>We will be setting up this</h2> </section> <section> <h1>AAAAAAAAAAAAAAAAHHHHHHHHHHHHHH AN EXTRA SLIDE KILL IT NOW</h1> <small class="fragment">Cue live demo</small> </section> <section> <h2>Yes... but how?</h2> <pre class="fragment"><code data-trim contenteditable> 10 I'll run a lab 20 You will pair up and try the lab on your own 30 we'll come back and discus the lab 40 GOTO 10 </code></pre> </section> <section> <h2>But First</h2> <h2 class="fragment">lets get some prereqs out of the way</h2> </section> <!-- make these prereqs --> <!-- <section> --> <!-- <h2>make a <a href="http://github.com">Github</a> account</h2> --> <!-- </section> --> <!-- --> <!-- <section> --> <!-- <h2>make a <a href="https://hub.docker.com/account/signup/">Dockerhub</a> account</h2> --> <!-- <h3>you can use your Github credentials</h3> --> <!-- </section> --> <!-- --> <!-- <section> --> <!-- <h2>make a <a onclick="login()">Done</a> session</h2> --> <!-- <h3>you can use your Github credentials</h3> --> <!-- </section> --> <!-- --> <section> <h2>What is docker?</h2> </section> <section> <h2>Docker is...</h2> <ul> <li class="fragment">Portable</li> <li class="fragment">lightweight</li> <li class="fragment">Application Containers</li> </ul> <aside class="notes"> make sure to ask about each thing </aside> </section> <section> <h2>Docker is not...</h2> <ul> <li class="fragment">A Hypervisor</li> <li class="fragment">an Automated Deployment System</li> </ul> <aside class="notes"> make sure to ask about each thing </aside> </section> <section> <h2 style="position: relative; bottom: 200px;">vocab</h2> <section> <aside class="notes"> make sure to ask about each thing </aside> </section> <section> <h2>Docker Server:</h2> The daemon that manages containers and images </section> <section> <h2>Docker CLI:</h2> The docker command </section> <section> <h2>Docker Hub:</h2> The docker image hosting service </section> <section> <h2>Image:</h2> A read only file system </section> <section> <h2>Base Image:</h2> An image without a parent </section> <section> <h2>Container:</h2> An instance of a Image </section> <section> <h2>Repository:</h2> a set of images </section> <section> <h2>Registry:</h2> a place the images are hosted(dockerhub) </section> </section> <!-- Example of nested vertical slides --> <section> <h2 style="position: relative; bottom: 430px;">Lab 1</h2> <a class="done-button" onclick="completeLab(1)">I'm Done</a> <section> <h3>get into your docker image</h3> </section> <section> TODO: this slide </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 2</h2> <a class="done-button" onclick="completeLab(2)">I'm Done</a> <section> <h3>Hello Docker</h3> </section> <section> <h2>Run echo in a container</h2> <pre><code data-trim contenteditable> docker run ubuntu /bin/echo "Hello Docker" </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> The run command <pre><code data-trim contenteditable> docker run </code></pre> </li> <li class="fragment"> The Image To Run <pre ><code data-trim contenteditable> ubuntu </code></pre> </li> <li class="fragment"> The command to run in the new container <pre ><code data-trim contenteditable> /bin/echo "Hello Docker" </code></pre> </li> <li class="fragment"> see the last container <pre ><code data-trim contenteditable> docker ps -l </code></pre> </li> </ul> </section> <section> <h2>great but can we do something useful?</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 3</h2> <a class="done-button" onclick="completeLab(3)">I'm Done</a> <section> <h3>Adding a Web Server</h3> </section> <section> <h2>Run an Interactive container</h2> <pre><code data-trim contenteditable> docker run -p 80:80 -i -t ubuntu /bin/bash # in the container apt-get update apt-get install nginx service nginx start # go look at your fancy new web site in a browser at localhost:80 # don't exit the container </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> forward the containers port 80 to the hosts port 80 <pre class="fragment"><code data-trim contenteditable> -p 80:80 </code></pre> </li> <li class="fragment"> keep STDIN open (interactive mode) <pre class="fragment"><code data-trim contenteditable> -i </code></pre> </li> <li class="fragment"> allocate a pseudo TTY <pre class="fragment"><code data-trim contenteditable> -t </code></pre> </li> <li class="fragment"> run bash in the container <pre class="fragment"><code data-trim contenteditable> /bin/bash </code></pre> </li> <li class="fragment"> install and start nginx <pre class="fragment"><code data-trim contenteditable> apt-get update apt-get install nginx service nginx start </code></pre> </li> </ul> </section> <section> <h2>well that works but do I need to to that every time?</h2> </section> </section> <section> <h2>the difference between a container and a image</h2> <image src="https://docs.docker.com/terms/images/docker-filesystems-multilayer.png"> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 4</h2> <a class="done-button" onclick="completeLab(4)">I'm Done</a> <section> <h3>the one where you make a new image</h3> </section> <section> <h2>commit your container</h2> <pre><code data-trim contenteditable> # in your container echo "daemon off;" >> /etc/nginx/nginx.conf exit # out of the docker docker ps -l docker commit `docker ps -lq` yourname/dockerclass docker run -d -P yourname/dockerclass service nginx start docker ps </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> name of the image <pre class="fragment"><code data-trim contenteditable> yourname/dockerclass </code></pre> </li> <li class="fragment"> bind all of the containers ports to a random high port on the host <pre class="fragment"><code data-trim contenteditable> docker run -P </code></pre> </li> <li class="fragment"> daemonize the container <pre class="fragment"><code data-trim contenteditable> docker run -d </code></pre> </li> <li class="fragment"> start the nginx service <pre class="fragment"><code data-trim contenteditable> service nginx start </code></pre> </li> <li class="fragment"> only return the name of the container <pre class="fragment"><code data-trim contenteditable> docker ps -q </code></pre> </li> </ul> </section> <section> <h2>cool!</h2> <h2 class="fragment">I can have a image of nginx</h2> <h2 class="fragment">but how can I keep versions of my images</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 5</h2> <a class="done-button" onclick="completeLab(5)">I'm Done</a> <section> <h3>tagging a image</h3> </section> <section> <h2>stop your container</h2> <pre><code data-trim contenteditable> docker images docker tag name_of_image yourname/dockerclass:byhand </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> add a tag to a docker image <pre class="fragment"><code data-trim contenteditable> docker tag </code></pre> </li> <li class="fragment"> add the byhand tag to the yourname/dockerclass image <pre class="fragment"><code data-trim contenteditable> yourname/dockerclass:byhand </code></pre> </li> <li class="fragment"> list all the images on a machine <pre class="fragment"><code data-trim contenteditable> docker images </code></pre> </li> </ul> </section> <section> <h2>cool!</h2> <h2 class="fragment">but how can I host my files</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 6</h2> <a class="done-button" onclick="completeLab(6)">I'm Done</a> <section> <h3>add this presentation to the container</h3> </section> <section> <h2>add these files to your container</h2> <pre><code data-trim contenteditable> docker run -i -t -p 80:80 yourname/dockerclass:byhand /bin/bash # in the container apt-get install git git clone https://github.com/dfedde/docker_workshop.git /var/www cd /var/www cp Sitefile /etc/nginx/sites-enabled/ rm /etc/nginx/sites-enabled/default nginx #look at your new site in the browser exit docker ps -l # get the name from of the container docker commit `docker ps -lq` yourname/dockerclass docker run -d -P yourname/dockerclass service nginx start #look at your new site in the browser docker images docker tag imagesname yourname/dockerclass:byhand docker ps -l </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> we used and committed the dockerclass repository <pre class="fragment"><code data-trim contenteditable> yourname/dockerclass </code></pre> </li> </ul> </section> <section> <h2>lets look at all the containers we have piling up</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 7</h2> <a class="done-button" onclick="completeLab(7)">I'm Done</a> <section> <h3>Stopping and removing a container</h3> </section> <section> <h2>stop your container</h2> <pre><code data-trim contenteditable> docker stop `docker ps -lq` docker ps -a docker rm container name </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> stops 1 or more given containers <pre class="fragment"><code data-trim contenteditable> docker stop </code></pre> </li> <li class="fragment"> removes 1 or more given container <pre class="fragment"><code data-trim contenteditable> docker rm </code></pre> </li> <li class="fragment"> return all the containers <pre class="fragment"><code data-trim contenteditable> docker ps -a </code></pre> </li> </ul> </section> <section> <h2 class="fragment">I want to share my awesome new image</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 8</h2> <a class="done-button" onclick="completeLab(8)">I'm Done</a> <section> <h3>docker hub</h3> </section> <section> <h2>push your image to docker hub</h2> <p>create a<a href ="https://hub.docker.com/account/signup/docker"> dockerhub account</a></p> <pre><code data-trim contenteditable> docker login docker push yourname/dockerclass </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> login to the registry (default docker hub) <pre class="fragment"><code data-trim contenteditable> docker login </code></pre> </li> <li class="fragment"> push the image to the registry <pre class="fragment"><code data-trim contenteditable> docker push yourname/dockerclass </code></pre> </li> </ul> </section> <section> <h2>now lets get that on the server</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 9</h2> <a class="done-button" onclick="completeLab(9)">I'm Done</a> <section> <h3>your first deploy</h3> </section> <section> <h2>deploy to your server</h2> <pre><code data-trim contenteditable> ssh sfsstudent@ip_Duncan_gave_you # password is sfsrocks docker login #if you made your repo private docker pull yourname/dockerclass docker run -p 80:80 -d yourname/dockerclass nginx # test your new server exit </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> pull the image back down <pre class="fragment"><code data-trim contenteditable> docker pull yourname/dockerclass </code></pre> </li> <li class="fragment"> run the container <pre class="fragment"><code data-trim contenteditable> docker run -p 80:80 -d yourname/dockerclass </code></pre> </li> </ul> </section> <section> <h2>but there is a better way to make images</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 10</h2> <a class="done-button" onclick="completeLab(10)">I'm Done</a> <section> <h3>forking the repo</h3> </section> <section> <h2>fork and prep my github repo</h2> <h3><a href="https://github.com/dfedde/docker_workshop"> the repo</a></h3> <ul> <li> go over to my repository click the<a href="https://github.com/dfedde/docker_workshop/fork"> fork </a>button</li> <li> go to your new repository select the Dockerfile file</li> <li> select the trashcan button</li> <li> select the commit changes button at the bottom of the page</li> <li> now run these commands</li> </ul> <pre><code data-trim contenteditable> git clone http://the.address.of/your/repo docker_workshop cd docker_workshop touch Dockerfile </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> make a copy of my repo under your namespace </li> <li class="fragment"> removed my docker file </li> <li class="fragment"> clone your repo <pre><code data-trim contenteditable> git clone http://the.address.of/your/repo docker_workshop </code></pre> </li> <li class="fragment"> make a new empty docker file <pre><code data-trim contenteditable> touch Dockerfile </code></pre> </li> </ul> </section> <section> <h2>what do I put in this new file?</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 11</h2> <a class="done-button" onclick="completeLab(11)">I'm Done</a> <section> <h3>the docker file</h3> </section> <section> <h2>build your image with a docker file</h2> <h3><a href="https://gist.github.com/6b834c64ecfdf9b3974e">Dockerfile</a></h3> <pre><code data-trim contenteditable> FROM ubuntu:14.10 RUN \ apt-get update && \ apt-get install -y nginx && \ rm -rf /var/lib/apt/lists/* && \ echo "\ndaemon off;" >> /etc/nginx/nginx.conf && \ chown -R www-data:www-data /var/lib/nginx CMD ["nginx"] EXPOSE 80 </code></pre> <pre><code data-trim contenteditable> # create a Dockerfile docker build -t yourname/dockerclass . docker run -p 80:80 -d yourname/dockerclass # go checkout your web site http://localhost </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> build the new image from ubuntu 14.10 <pre><code data-trim contenteditable> FROM ubuntu:14.10 </code></pre> </li> <li class="fragment"> run these commands on the new container <pre><code data-trim contenteditable> RUN \ apt-get update && \ apt-get install -y nginx && \ rm -rf /var/lib/apt/lists/* && \ echo "\ndaemon off;" >> /etc/nginx/nginx.conf && \ chown -R www-data:www-data /var/lib/nginx </code></pre> </li> <li class="fragment"> run the nginx comand when you run the image <pre><code data-trim contenteditable> CMD ["nginx"] </code></pre> </li> <li class="fragment"> expose port 80 to the host(the host must still bind this to a port) <pre><code data-trim contenteditable> EXPOSE 80 </code></pre> </li> <li class="fragment"> build the image from the docker file <pre><code data-trim contenteditable> docker build -t yourname/dockerclass . </code></pre> </li> </ul> </section> <section> <h2>now we can build a image on the fly but how do we get our data in there</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 12</h2> <a class="done-button" onclick="completeLab(12)">I'm Done</a> <section> <h3>copy that</h3> </section> <section> <h2>the copy command</h2> <pre><code data-trim contenteditable> FROM ubuntu:14.10 RUN \ apt-get update && \ apt-get install -y nginx && \ rm -rf /var/lib/apt/lists/* && \ echo "\ndaemon off;" >> /etc/nginx/nginx.conf && \ chown -R www-data:www-data /var/lib/nginx RUN rm /etc/nginx/sites-enabled/default COPY Sitefile /etc/nginx/sites-enabled/ COPY css/ /var/www/css COPY js/ /var/www/js COPY lib/ /var/www/lib COPY plugin/ /var/www/plugin COPY index.html /var/www/ CMD ["nginx"] EXPOSE 80 </code></pre> <pre><code data-trim contenteditable> # create a Dockerfile docker build -t yourname/dockerclass:byfile . docker run -p 80:80 -d yourname/dockerclass # go checkout your web site http://localhost </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> copy a file from the host to the image <pre><code data-trim contenteditable> COPY index.html /var/www/ </code></pre> </li> </ul> </section> <section> <h2>this works but what if we don't want our code in the image</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 13</h2> <a class="done-button" onclick="completeLab(13)">I'm Done</a> <section> <h3>using volumes</h3> </section> <section> <h2>use a named volume</h2> <pre><code data-trim contenteditable> FROM ubuntu:14.10 RUN \ apt-get update && \ apt-get install -y nginx && \ rm -rf /var/lib/apt/lists/* && \ echo "\ndaemon off;" >> /etc/nginx/nginx.conf && \ chown -R www-data:www-data /var/lib/nginx RUN rm /etc/nginx/sites-enabled/default COPY Sitefile /etc/nginx/sites-enabled/ CMD ["nginx"] EXPOSE 80 </code></pre> <pre><code data-trim contenteditable> # create a Dockerfile docker build -t yourname/dockerclass:byfile . docker run -d -p 80:80 -v $(pwd):/var/www yourname/dockerclass:byfile # go checkout your web site http://localhost </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> link the local directory in the container <pre><code data-trim contenteditable> -v $(pwd):/var/www yourname/dockerclass:byfile </code></pre> </li> <li class="fragment"> volumes don't get deleted when you remove a container </li> </ul> </section> <section> <h2>but this relies on every host having the same file structure</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 14</h2> <a class="done-button" onclick="completeLab(14)">I'm Done</a> <section> <h3>using unnamed volumes</h3> </section> <section> <h2>use a unnamed volume</h2> <pre><code data-trim contenteditable> FROM ubuntu:14.10 RUN \ apt-get update && \ apt-get install -y nginx && \ rm -rf /var/lib/apt/lists/* && \ echo "\ndaemon off;" >> /etc/nginx/nginx.conf && \ chown -R www-data:www-data /var/lib/nginx RUN rm /etc/nginx/sites-enabled/default VOLUME ["/var/www"] COPY Sitefile /etc/nginx/sites-enabled/ CMD ["nginx"] EXPOSE 80 </code></pre> <pre><code data-trim contenteditable> # create a Dockerfile docker build -t yourname/dockerclass:byfile . docker run -p 80:80 -d yourname/dockerclass:byfile # go checkout your web site http://localhost </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> link the directory on the local file system in to the container <pre><code data-trim contenteditable> VOLUME ["/var/www"] </code></pre> </li> </ul> </section> <section> <h2>but this means your code is not in the image</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 15</h2> <a class="done-button" onclick="completeLab(15)">I'm Done</a> <section> <h3>data containers</h3> </section> <section> <h2>make a data container image</h2> <pre><code data-trim contenteditable> mkdir -p images/data cd images/data touch Dockerfile </code></pre> <pre><code data-trim contenteditable> FROM ubuntu:14.10 RUN \ apt-get update && \ apt-get install -y git VOLUME ["/var/www"] CMD ["git", "clone", "http://the.address.of/your/repo", "/var/www"] </code></pre> <pre><code data-trim contenteditable> docker build -t yourname/wwwdata . docker run --name www_files yourname/wwwdata docker run --volumes-from www_files -p 80:80 -d yourname/dockerclass:byfile </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> <li class="fragment"> provide a explicit name for a container <pre><code data-trim contenteditable> --name </code></pre> </li> <li class="fragment"> share a volume between containers(even not running containers) <pre><code data-trim contenteditable> --volumes-from </code></pre> </li> </ul> </section> <section> <h2>makes the data container to smart</h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 16</h2> <a class="done-button" onclick="completeLab(16)">I'm Done</a> <section> <h3>action containers</h3> </section> <section> <h2>make an action container</h2> <pre><code data-trim contenteditable> cd ../.. mkdr -p images/git-puller cd images/git-puller touch Dockerfile </code></pre> <pre><code data-trim contenteditable> FROM ubuntu:14.10 RUN \ apt-get update && \ apt-get install -y git VOLUME ["/var/www"] ENTRYPOINT ["git", "clone" ] </code></pre> <pre><code data-trim contenteditable> docker build -t yourname/gitpuller . docker run --name www_files -v /var/www ubuntu docker run --volumes-from www_files yourname/gitpuller http://the.address.of/your/repo /var/www docker run --volumes-from www_files -p 80:80 -d yourname/dockerclass:byfile </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> </li> <li class="fragment"> the command that will be run via the run command <pre><code data-trim contenteditable> ENTRYPOINT ["git", "clone" ] </code></pre> </li> </ul> </section> <section> <h2></h2> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">Lab 17</h2> <a class="done-button" onclick="completeLab(17)">I'm Done</a> <section> <h3>final deploy</h3> </section> <section> <h2>deploy code to the server again</h2> <pre><code data-trim contenteditable> docker push yourname/dockerclass:byfile docker push yourname/gitpuller ssh sfsstudent@ip_Duncan_gave_you # password is still sfsrocks docker login #if you made your repo private docker run -d --name www_files -v /var/www ubuntu docker run --volumes-from www_files yourname/gitpuller http://the.address.of/your/repo /var/www docker run --volumes-from www_files -p 80:80 -d yourname/dockerclass:byfile # test if everything is working exit </code></pre> </section> <section> <h2>what did we just do?</h2> <ul> </ul> </section> </section> <section> <h2 style="position: relative; bottom: 430px;">extra credit</h2> <section> <h3>automated builds</h3> </section> <section> <h2>use a named volume</h2> <p> figure out how to link docker hub and git hub to build your image for you </section> </section> <section> <h2 class="fragment">now go and</h2> <image src="http://blogs.atlassian.com/wp-content/uploads/docker-all-the-things.png"> </section> </div> </div> <script src="lib/js/head.min.js"></script> <script src="js/reveal.min.js"></script> <script> // Full list of configuration options available here: // https://github.com/hakimel/reveal.js#configuration Reveal.initialize({ controls: true, progress: true, history: true, center: true, theme: Reveal.getQueryHash().theme, // available themes are in /css/theme transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/fade/none // Parallax scrolling // parallaxBackgroundImage: 'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg', // parallaxBackgroundSize: '2100px 900px', // Optional libraries used to extend on reveal.js dependencies: [ { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, { src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } }, { src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }, { src: 'http://code.jquery.com/jquery-2.1.1.min.js', async: true, condition: function() { return !!document.body.classList; } } ] }); </script> <script> function completeLab(lab) { if (lab != null) { $.ajax({ url: "http://docker_workshop.fedde.us:4567/done_with/"+lab, xhrFields: { withCredentials: true }, success: function(msg){ alert(msg); } }); } } function login() { var person = prompt("Please enter your name", "your name"); if (person != null) { $.ajax({ type: "POST", url: "http://docker_workshop.fedde.us:4567/login?name="+person, xhrFields: { withCredentials: true }, success: function(msg){ alert(msg); } }); } } </script> </body> </html>
{ "content_hash": "977a879ee0f52157a43c39305ea76032", "timestamp": "", "source": "github", "line_count": 1117, "max_line_length": 135, "avg_line_length": 31.49776186213071, "alnum_prop": 0.5348890088963419, "repo_name": "dfedde/docker_workshop", "id": "41e64e0a2ab97782a37e2e6af53682c14cff17c6", "size": "35183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "125268" }, { "name": "Dockerfile", "bytes": "666" }, { "name": "HTML", "bytes": "50185" }, { "name": "JavaScript", "bytes": "132187" } ], "symlink_target": "" }
package com.google.javascript.jscomp; import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; /** * @author nicksantos@google.com (Nick Santos) */ public class SanityCheckTest extends CompilerTestCase { private CompilerPass otherPass = null; public SanityCheckTest() { super("", false); } @Override public void setUp() { otherPass = null; } @Override protected int getNumRepetitions() { return 1; } @Override public CompilerPass getProcessor(final Compiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { otherPass.process(externs, root); (new SanityCheck(compiler, false)).process(externs, root); } }; } public void testUnnormalizeNodeTypes() throws Exception { otherPass = new CompilerPass() { @Override public void process(Node externs, Node root) { getLastCompiler().reportCodeChange(); root.getFirstChild().addChildToBack( new Node(Token.IF, new Node(Token.TRUE), new Node(Token.EMPTY))); } }; boolean exceptionCaught = false; try { test("var x = 3;", "var x=3;0;0"); } catch (IllegalStateException e) { assertTrue(e.getMessage().contains("Expected BLOCK but was EMPTY")); exceptionCaught = true; } assertTrue(exceptionCaught); } public void testUnnormalized() throws Exception { otherPass = new CompilerPass() { @Override public void process(Node externs, Node root) { getLastCompiler().setLifeCycleStage(LifeCycleStage.NORMALIZED); } }; boolean exceptionCaught = false; try { test("while(1){}", "while(1){}"); } catch (RuntimeException e) { assertTrue(e.getMessage().contains( "Normalize constraints violated:\nWHILE node")); exceptionCaught = true; } assertTrue(exceptionCaught); } public void testConstantAnnotationMismatch() throws Exception { otherPass = new CompilerPass() { @Override public void process(Node externs, Node root) { getLastCompiler().reportCodeChange(); Node name = Node.newString(Token.NAME, "x"); name.putBooleanProp(Node.IS_CONSTANT_NAME, true); root.getFirstChild().addChildToBack(new Node(Token.EXPR_RESULT, name)); getLastCompiler().setLifeCycleStage(LifeCycleStage.NORMALIZED); } }; boolean exceptionCaught = false; try { test("var x;", "var x; x;"); } catch (RuntimeException e) { assertTrue(e.getMessage().contains( "The name x is not consistently annotated as constant.")); exceptionCaught = true; } assertTrue(exceptionCaught); } }
{ "content_hash": "e3cae985557d152a33ec8f7606a1fea4", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 79, "avg_line_length": 29.294736842105262, "alnum_prop": 0.6629536471433705, "repo_name": "zombiezen/cardcpx", "id": "504ee89664c659ae076e2b8cd097aed297103223", "size": "3395", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third_party/closure-compiler/test/com/google/javascript/jscomp/SanityCheckTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1016" }, { "name": "Go", "bytes": "110895" }, { "name": "HTML", "bytes": "7712" }, { "name": "JavaScript", "bytes": "43194" }, { "name": "Makefile", "bytes": "3650" }, { "name": "Shell", "bytes": "1502" } ], "symlink_target": "" }
class Hakiri::Memcached < Hakiri::Technology def initialize(command = '') super @name = 'Memcached' end def version begin output = (@command.empty?) ? `memcached -h 2>&1 | awk 'NR == 1 { print ; }'` : `#{@command} 2>&1 | awk 'NR == 1 { print ; }'` @default_regexp.match(output)[0] rescue Exception => e puts_error(e, output) nil end end end
{ "content_hash": "69fceea20a9e5d9cef97318a622dc2d1", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 132, "avg_line_length": 23.235294117647058, "alnum_prop": 0.5620253164556962, "repo_name": "hakirisec/hakiri_toolbelt", "id": "15a5ed7d5d3e46a373f2c964299935fd536f8543", "size": "395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/hakiri/technologies/memcached.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "37230" }, { "name": "Shell", "bytes": "137" } ], "symlink_target": "" }
<div data-ng-cloak style="text-align: center;"> <div style="margin-top:100px; height: 500px; vertical-align: middle; display:inline-block" class="container-fluid"> <label> <b> Click on language to JOIN </b>: </label> <div style="overflow-y:scroll; height:300px; border: 1px solid black"> <ul style="padding: 5px"> <li ng-repeat="project in openProjects" ng-click="showModal(project, 1)" class="thumbnail"> <a ng-click="requestProjectJoin(project)"> {{project.projectName}} </a> </li> </ul> </div> <div style="margin-top:10px"> <label> <b> Don't see your project, type below to create </b>: </label> <br /> <input ng-model="languageCode" ng-change="checkLanguageAvailability()" /> <button ng-click="openNewLanguageModal()" class="btn btn-primary"> Select Language</button> <br/> <br/> <button ng-disabled="!canCreate" ng-click="createProject(false)" class="btn btn-primary"> Create Empty Project</button> <button ng-show="canCreate && languageHasGoogleTranslateData" ng-click="createProject(true)" class="btn btn-primary"> Create With Google Data</button> </div> </div> </div>
{ "content_hash": "b5c8ec17f199d0d8e93b5910f5942a08", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 163, "avg_line_length": 54.32, "alnum_prop": 0.5714285714285714, "repo_name": "sillsdev/web-cat", "id": "8dab80821e070d060dfd3b290ff7bc9bbe7904cc", "size": "1358", "binary": false, "copies": "2", "ref": "refs/heads/master-cat", "path": "src/angular-app/languageforge/semdomtrans/new-project/views/new-project-main.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "494" }, { "name": "C#", "bytes": "98094" }, { "name": "CSS", "bytes": "521996" }, { "name": "HTML", "bytes": "786056" }, { "name": "JavaScript", "bytes": "969061" }, { "name": "PHP", "bytes": "1583964" }, { "name": "Python", "bytes": "54795" }, { "name": "Ruby", "bytes": "19407" }, { "name": "Shell", "bytes": "15235" }, { "name": "TypeScript", "bytes": "1678490" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "a970c31cefadc41c1fd6399dee149688", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "373a0ea28ae93e2dd02da12c7fe2c5df677be35d", "size": "189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Melocactus/Melocactus azulensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">我的内存清理</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="title_activity_home">MainActivity</string> <string name="title_activity_setting">SettingActivity</string> <string name="title_activity_white">WhiteActivity</string> <string name="title_activity_jump">JumpActivity</string> <string name="title_activity_music">MusicActivity</string> </resources>
{ "content_hash": "4bbf7bc79235f4e53585ebdc5f945727", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 66, "avg_line_length": 40.76923076923077, "alnum_prop": 0.7169811320754716, "repo_name": "muziyouyou/ImitateAnimation", "id": "cc05a002ebefa26bc1a9690d730f75fd94668a6d", "size": "542", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "我的内存清理/res/values/strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "78873" } ], "symlink_target": "" }
<head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="{{ site.description }}"> <meta name="keyword" content="{{ site.keyword }}"> <link rel="shortcut icon" href="{{ site.baseurl }}/img/xiuc.ico"> <title>{% if page.title %}{{ page.title }} - {{ site.SEOTitle }}{% else %}{{ site.SEOTitle }}{% endif %}</title> <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}"> <!-- Bootstrap Core CSS --> <link rel="stylesheet" href="{{ "/css/bootstrap.min.css" | prepend: site.baseurl }}"> <!-- Custom CSS --> <link rel="stylesheet" href="{{ "/css/hux-blog.min.css" | prepend: site.baseurl }}"> <!-- Pygments Github CSS --> <link rel="stylesheet" href="{{ "/css/syntax.css" | prepend: site.baseurl }}"> <!-- Custom Fonts --> <!-- <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> --> <!-- Hux change font-awesome CDN to qiniu --> <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- Hux Delete, sad but pending in China <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/ css'> --> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <!-- ga & ba script hoook --> <script></script> </head>
{ "content_hash": "9dca8a9454eda193203fbac9cd4f6dfd", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 164, "avg_line_length": 48.55555555555556, "alnum_prop": 0.637070938215103, "repo_name": "froest2012/froest2012.github.io", "id": "efe086cf4cf7eb65dff61a1cf22291b76baef53e", "size": "2185", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/head.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "57679" }, { "name": "HTML", "bytes": "47488" }, { "name": "JavaScript", "bytes": "12381" } ], "symlink_target": "" }
@interface RACSignal (CustomDistinction) typedef BOOL(^PassRuleBlock)(id first, id second); - (RACSignal *)distinctBasedOnRule:(PassRuleBlock)passRuleBlock; @end
{ "content_hash": "dd077e92327ae3410b5237c5e3cc6daa", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 64, "avg_line_length": 23.571428571428573, "alnum_prop": 0.793939393939394, "repo_name": "skyylex/RFPMutex-Demonstration", "id": "743c1d5aa6dfddfdf2b6416accfe71e529547c6b", "size": "375", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ReactiveCocoa2-MutexSample/RACSignal+CustomDistinction.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "9704" }, { "name": "Ruby", "bytes": "68" } ], "symlink_target": "" }
timing-cat ========== Find out what people think of your organization 1- How to build You need to have mongodb installed. You need to modify the build.xml file and set the dir.lib variable to the directory where you have the mongodb java driver jar file.
{ "content_hash": "4a5c4c6fcc5c55feb76310df1c898594", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 132, "avg_line_length": 28.666666666666668, "alnum_prop": 0.7558139534883721, "repo_name": "EBlonkowski/timing-cat", "id": "2573d4b8aa0aa5e43f74f25e4981eeb4e4758244", "size": "258", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "28621" } ], "symlink_target": "" }
from ..layoutparser import Layoutparser from headparser import HeadParser from linkmatch import Linkmatch import re import nltk import HTMLParser class H1Parser(HeadParser): re_head = re.compile(r"(?:^|\n)\s*==\s*(.*?)\s*==\s*(?=\n)") class ItemParser(HeadParser): re_head = re.compile(r"(?:^|\n)\s*[*#]\s*(.*?)(?=\n|$)") class WikiParser(Layoutparser): re_html = re.compile(r"</?[a-zA-Z]+\s*/?>") html_parser = HTMLParser.HTMLParser() def preparse(self, text): text = Linkmatch.sub(text) text = text.replace("'''", "") text = text.replace("''", "") text = self.re_html.sub("", text) text = self.html_parser.unescape(text) return text def parseText(self, text): #TODO # verify this is a recipe -> {{recipe}} #TODO # extract metadata from {{recipesummary}} # {{recipesummary|$ignore|$servings|$time|$difficulty|$ignore...}} #TODO # Basic Format I: # == Ingredients == # *$ingredients... # == Procedure == | == Method == //ignore spaces # #$steps... | *$steps... # ignore subheadings and text # recognize == Notes, tips, and variations == # issue warnings for all other sections # Implementation: # Use a Section.parse to find all section headings # Use this array to create Section objects with headline/body d = H1Parser().parse(text).toDict() d['Ingredients'] = map(self.preparse, ItemParser().parse(d['Ingredients']).toList()) d['Procedure'] = ItemParser().parse(d['Procedure']).toList() for i, step in enumerate(d['Procedure']): d['Procedure'][i] = map(self.preparse, nltk.sent_tokenize(step)) return d # Use an Item.parse to find all items # Use this array to create Item objects #NOTE: for Procedure, also parse Sentence # -> use punkt tokenizer #NOTE: if no items in procedure, only parse Sentence # Store as Sections: # dict[section] = # store as Blocks: # Block(text, ((Item, 1), (Sentence, 4)) )
{ "content_hash": "3abdb5bf5eeae396b1ebab745a79f7ec", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 86, "avg_line_length": 27.242857142857144, "alnum_prop": 0.6507603565810173, "repo_name": "redyeti/bitsandbites", "id": "514932bd514bbaae4972aaa0ef0838b964671888", "size": "1907", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "stage2/layoutparse/wikiparser/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1090" }, { "name": "JavaScript", "bytes": "347" }, { "name": "Makefile", "bytes": "372" }, { "name": "Python", "bytes": "49932" }, { "name": "TeX", "bytes": "10988" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="Better Call Nick"> <meta name="author" content="Daniele Cappuccio"> <link rel="icon" href="./favicons/favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="./favicons/favicon.ico" type="image/x-icon" /> <title>Better Call Nick</title> <!-- Bootstrap core CSS --> <link href="./dist/css/bootstrap.min.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <link href="./assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet"> <!-- Just for debugging purposes. Don't actually copy these 2 lines! --> <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]--> <script src="./assets/js/ie-emulation-modes-warning.js"></script> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <!-- Custom styles for this template --> <link href="./carousel.css" rel="stylesheet"> </head> <!-- NAVBAR ================================================== --> <body> <div class="navbar-wrapper"> <div class="container"> <nav class="navbar navbar-inverse navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="https://bettercallnick.github.io">Better Call Nick</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="https://bettercallnick.github.io">Home</a></li> <li><a href="https://www.facebook.com/bettercallnick/">Facebook</a></li> <li><a href="https://twitter.com/nicolalampi">Twitter</a></li> <li><a href="https://www.instagram.com/alampinicola/">Instagram</a></li> <li><a href="https://www.linkedin.com/in/nicola-alampi-9288bb149/">LinkedIn</a></li> <li><a href="https://www.youtube.com/channel/UCsqQkLkDjNCtKLGyvVXTEIA">YouTube</a></li> <li><a href="./contacts.html">Contacts</a></li> <!-- <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li class="dropdown-header">Nav header</li> <li><a href="#">Separated link</a></li> <li><a href="#">One more separated link</a></li> </ul> </li> --> </ul> </div> </div> </nav> </div> </div> <div class="container marketing"> <!-- START THE FEATURETTES --> <hr class="featurette-divider"> <div class="row featurette"> <div class="col-md-7"> <img src="./imgs/british-flag.jpg" style="width:60px;length:40px"><br><br> <p class="lead"> Hi everybody, I’m Nicola, sorry, Nick, this is my name from 19th June, 2016, I was in London with the wish to become a realtor, when I met my first londoner agent, who rented me my first room in the UK. Two days later I met who is now my business partner another londoner realtor, so started my business life in UK but basicly my life in Real Estate world. During these months borned my first facebook page, its name was BETTERCALLNICK. Remember this name. September 2016 I came back in Rome, my italian city, because I had some problems, where some months later I started to work with TECNOCASA brand, the worst experience and brand of my life, but some weeks later the end of this terrible workship I met like a miracle a COLDWELL BANKER agent, I think the best real estate brand in the world, that invited me to work with them, so started my second real estate life but now in Rome. We are in June 2017 when I understood that I wanted work alone and so borned really now BETTERCALLNICK CORPORATION a real estate and guest houses brand, but now was my personal brand. It’s ok, started now to work without a support until November when I riceved a call from my actually business partner that invited me to come back in London and make a partnership between my and his company. I accepted. So started my third real estate life. But this one was my best actually choice of my life, escape to London again. I live now in London when I manage properties in Italy and in UK, with different cooperation with some brand in UK, USA and Dubai, like: -Azizi (Dubai) -Douglas Elliman (CA, USA) -Coldwell Banker (Italy and USA) -ONE PARK DRIVE (Canary Wharf, London) I am very happy now and proud of myself, I’m opened to all kind of cooperation and to speak to all people that want insert themselves in Real Estate world, but also with agencies that want cooperate with me. I say goodbye to everyone, and I hope to speak face to face with all my readers, NICK. </p><br> <img src="./imgs/italian-flag.jpg" style="width:60px;length:40px"><br><br> <p class="lead"> Salve a tutti, mi chiamo Nicola, anzi, Nick, questo è il mio nome dal 19 di Giugno del 2016, mi trovavo a Londra con il sogno di diventare un agente immobiliare, quando conobbi il primo agente locale, il quale mi affittò la mia prima stanza nel regno unito. Due giorni dopo conobbi un altro agente il quale sarebbe poi diventato il mio attuale socio in affari e quasi il “faro” del mio business, cosi cominciò la mia carriera nel mondo immobiliare in Inghilterra. Durante questi mesi nacque la mia prima pagina Facebook, il nome fu “BETTERCALLNICK”, ricordate questo nome. Nel Settembre del 2016 tornai a Roma, la mia città italiana, a causa di qualche piccolo problema da risolvere, dove pochi mesi dopo cominciai a lavorare con TECNOCASA S.p.a., la peggior esperienza professionale della mia vita con il peggior brand immobiliare che io abbia conosciuto nella mia vita, ma qualche settimana dopo questa orribile esperienza, conobbi, come un miracolo, un agente di successo di COLDWELL BANKER, un famoso brand immobiliare statunitense, a mio avviso il migliore in assoluto, il quale mi propose di collaborare con la sua agenzia, cosi inizio la mia seconda vita nel mercato immobiliare ma questa volta a Roma. Siamo nel Giugno 2017 quando capii che avevo la voglia di provare a lavorare in proprio cosi poco dopo nacque realmente la “BETTERCALLNICK CORPORATION” un brand legato strettamente all’immobiliare anche tramite il turismo, ma ora era il MIO brand. OK, cominciai a lavorare da solo senza nessun tipo di ausilio con scarsi risultati fino a Novembre quando ricevetti una chiamata dal mio attuale socio in affari il quale mi propose di tornare a Londra e creare una partnership tra la mia e la sua società. ACCETTAI. Cosi nacque la mia terza vita nel mondo immobiliare. Ma questa era attualmente la miglior occasione della mia vita, tornai a Londra nuovamente. Attualmente vivo a Londra dove gestisco immobili in Italia ed in Inghilterra, con diverse collaborazioni con brand in UK, USA e Dubai, come: -AZIZI (Dubai) -Douglas Elliman (CA,USA) -Coldwell Banker (Italia e USA) -One Park Drive (Canary Wharf, London) Ad oggi sono felice ed orgoglioso di me stesso, sono aperto ad ogni forma di collaborazione ed a parlare con chiunque sia interrato ad introdursi nel mio business o nel mercato immobiliare in generale, ma soprattutto per collaborazioni con altre agenzie ed agenti. Un saluto ad ognuno che abbia portato attenzione alla mia penna, e spero di parlare faccia a faccia con ognuno che sia interessato a questo grande, affascinante e talvolta restio mondo immobiliare, un saluto da: NICK. </p> </div> <div class="col-md-5"> <img class="featurette-image img-responsive center-block" style="border-radius:50%" src="./imgs/nick.jpeg" alt="Generic placeholder image"> </div> </div> <hr class="featurette-divider"> <!-- /END THE FEATURETTES --> <!-- FOOTER --> <footer> <p class="pull-right"><a href="https://bettercallnick.github.io">Back to top</a></p> <p>&copy; Powered by &middot; <a href="https://danielecappuccio.net">Daniele Cappuccio</a> &middot; <a href="https://opensource.org/licenses/MIT">License</a></p> </footer> </div><!-- /.container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="./assets/js/vendor/jquery.min.js"><\/script>')</script> <script src="./dist/js/bootstrap.min.js"></script> <!-- Just to make our placeholder images work. Don't actually copy the next line! --> <script src="./assets/js/vendor/holder.min.js"></script> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="./assets/js/ie10-viewport-bug-workaround.js"></script> </body> </html>
{ "content_hash": "e477db8f204fc3ce7a8803510e38f23c", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 653, "avg_line_length": 65.80124223602485, "alnum_prop": 0.6358316027940344, "repo_name": "bettercallnick/bettercallnick.github.io", "id": "7f6fba943de6ad0c78a78befdadfb5df97937bf8", "size": "10619", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "about-me.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1722" }, { "name": "CSS", "bytes": "205964" }, { "name": "HTML", "bytes": "238078" }, { "name": "JavaScript", "bytes": "263115" }, { "name": "PowerShell", "bytes": "471" } ], "symlink_target": "" }
/** * @venus-library jasmine * @venus-include ../../src/functions.js * @venus-include ../../src/RegistryInterface.js * @venus-include ../../src/Registry.js * @venus-include ../../src/Storage/ManagerFactory.js * @venus-code ../../src/Storage/Core.js */ describe('storage', function () { var Factory = function () {Sy.Storage.ManagerFactory.call(this)}, core; Factory.prototype = Object.create(Sy.Storage.ManagerFactory.prototype, { make: { value: function (name) { if (name === 'default') { return {name: 'default'}; } else { return {name: name}; } } } }); beforeEach(function () { core = new Sy.Storage.Core(); core.setManagersRegistry(new Sy.Registry()); }); it('should have a default manager set to default', function () { expect(core.defaultName).toEqual('default'); }); it('should throw if trying to set invalid registry', function () { expect(function () { core.setManagersRegistry({}); }).toThrow('Invalid registry'); }); it('should set the managers registry', function () { expect(core.setManagersRegistry(new Sy.Registry())).toEqual(core); }); it('should set a default manager name', function () { expect(core.setDefaultManager('foo')).toEqual(core); expect(core.defaultName).toEqual('foo'); }); it('should throw if trying to set invalid manager factory', function () { expect(function () { core.setManagerFactory({}); }).toThrow('Invalid manager factory'); }); it('should set the manager factory', function () { expect(core.setManagerFactory(new Sy.Storage.ManagerFactory())).toEqual(core); }); it('should return a manager with the default name if none specified', function () { var factory = new Factory(); core.setManagerFactory(factory); expect(core.getManager()).toEqual({name: 'default'}); }); it('should return a manager with the specified name', function () { var factory = new Factory(); core.setManagerFactory(factory); expect(core.getManager('foo')).toEqual({name: 'foo'}); }); it('should return the same instance when getting manager twice', function () { var factory = new Factory(), manager; core.setManagerFactory(factory); manager = core.getManager('foo'); expect(core.getManager('foo')).toEqual(manager); }); });
{ "content_hash": "416bf24ff16a1bba9b08264c1661e78c", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 87, "avg_line_length": 30.186046511627907, "alnum_prop": 0.5835901386748844, "repo_name": "Baptouuuu/Sy", "id": "d9b312606325bd42358320e551e6e1920e942669", "size": "2596", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "tests/storage/core.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "897" }, { "name": "HTML", "bytes": "14953" }, { "name": "JavaScript", "bytes": "1801695" } ], "symlink_target": "" }
FROM balenalib/raspberrypi-debian:bullseye-run ENV NODE_VERSION 14.18.3 ENV YARN_VERSION 1.22.4 RUN buildDeps='curl libatomic1' \ && set -x \ && for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \ done \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends \ && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://resin-packages.s3.amazonaws.com/node/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv6hf.tar.gz" \ && echo "788c298991c5010afe6aff8e0ccbacc0f380ddfb9a7c240bc9dacaa8427cb016 node-v$NODE_VERSION-linux-armv6hf.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-armv6hf.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-armv6hf.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v6 \nOS: Debian Bullseye \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.18.3, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "866c7b77ab003089a2252b720e45c374", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 694, "avg_line_length": 65.44444444444444, "alnum_prop": 0.7066213921901529, "repo_name": "resin-io-library/base-images", "id": "f8d4f8583e8cd349d77d83e0ce681e5c10836afc", "size": "2966", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/node/raspberrypi/debian/bullseye/14.18.3/run/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
package models import me.verticale.imgur.model.Image /** A cat factory -- literally... yep the pattern ;) */ object Cat { /** Create a new cat from the given image * * @param img Image's data * * @return A soft and warm cat */ def apply(img: Image) = new Cat(img.id.get, img.link.get, img.mp4.get, img.webm.get) } /** A cat * * @param id Cat identifier (Imgur id) * @param link Link to the GIF image * @param mp4 Link to the MP4 * @param webm Link to the WebM */ class Cat(val id: String, val link: String, val mp4: String, val webm: String)
{ "content_hash": "3beabdb3241a5c2ca179f46ec38f228c", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 86, "avg_line_length": 24.25, "alnum_prop": 0.6374570446735395, "repo_name": "CatFactoryTeam/CatShelter", "id": "aa587fbdcff1775fe8850f678081ba22e61ff469", "size": "582", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/Cat.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "1905" } ], "symlink_target": "" }
using System.Collections.Generic; using System.IO; using Reinforced.Typings.Fluent; using Xunit; namespace Reinforced.Typings.Tests.SpecificCases { public partial class SpecificTestCases { [Fact] public void ReferencesPart6ByDanielWest() { /** * Specific test case with equal folder names by Daniel West */ const string file1 = @" export namespace Reinforced.Typings.Tests.SpecificCases { export enum SomeEnum { One = 0, Two = 1 } }"; const string file2 = @" import * as Enum from '../../APIv2/Models/TimeAndAttendance/Enum'; export namespace Reinforced.Typings.Tests.SpecificCases { export class SomeViewModel { public Enum: Enum.Reinforced.Typings.Tests.SpecificCases.SomeEnum; } }"; AssertConfiguration(s => { s.Global(a => a.DontWriteWarningComment().UseModules(discardNamespaces: false)); s.ExportAsEnum<SomeEnum>().ExportTo("Areas/APIv2/Models/TimeAndAttendance/Enum.ts"); s.ExportAsClass<SomeViewModel>().WithPublicProperties().ExportTo("Areas/Reporting/Models/Model.ts"); }, new Dictionary<string, string> { { Path.Combine(TargetDir, "Areas/APIv2/Models/TimeAndAttendance/Enum.ts"), file1 }, { Path.Combine(TargetDir, "Areas/Reporting/Models/Model.ts"), file2 } }, compareComments: true); } } }
{ "content_hash": "d9a343a37c8e7eaf504e4169a59dd661", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 116, "avg_line_length": 31.19148936170213, "alnum_prop": 0.6336971350613916, "repo_name": "reinforced/Reinforced.Typings", "id": "6ae194020cc6be48bdf240ada047f408c88a7797", "size": "1466", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Reinforced.Typings.Tests/SpecificCases/SpecificTestCases.ReferencesPart6ByDanielWest.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "703383" }, { "name": "PowerShell", "bytes": "319" } ], "symlink_target": "" }
"""Tests for the install history plist plugin.""" import unittest # pylint: disable=unused-import from plaso.formatters import plist as plist_formatter from plaso.parsers import plist from plaso.parsers.plist_plugins import install_history from plaso.parsers.plist_plugins import test_lib class InstallHistoryPluginTest(test_lib.PlistPluginTestCase): """Tests for the install history plist plugin.""" def setUp(self): """Sets up the needed objects used throughout the test.""" self._plugin = install_history.InstallHistoryPlugin() self._parser = plist.PlistParser() def testProcess(self): """Tests the Process function.""" test_file = self._GetTestFilePath(['InstallHistory.plist']) plist_name = 'InstallHistory.plist' event_queue_consumer = self._ParsePlistFileWithPlugin( self._parser, self._plugin, test_file, plist_name) event_objects = self._GetEventObjectsFromQueue(event_queue_consumer) self.assertEquals(len(event_objects), 7) timestamps = [] for event_object in event_objects: timestamps.append(event_object.timestamp) expected_timestamps = frozenset([ 1384225175000000, 1388205491000000, 1388232883000000, 1388232883000000, 1388232883000000, 1388232883000000, 1390941528000000]) self.assertTrue(set(timestamps) == expected_timestamps) event_object = event_objects[0] self.assertEqual(event_object.key, u'') self.assertEqual(event_object.root, u'/item') expected_desc = ( u'Installation of [OS X 10.9 (13A603)] using [OS X Installer]. ' u'Packages: com.apple.pkg.BaseSystemBinaries, ' u'com.apple.pkg.BaseSystemResources, ' u'com.apple.pkg.Essentials, com.apple.pkg.BSD, ' u'com.apple.pkg.JavaTools, com.apple.pkg.AdditionalEssentials, ' u'com.apple.pkg.AdditionalSpeechVoices, ' u'com.apple.pkg.AsianLanguagesSupport, com.apple.pkg.MediaFiles, ' u'com.apple.pkg.JavaEssentials, com.apple.pkg.OxfordDictionaries, ' u'com.apple.pkg.X11redirect, com.apple.pkg.OSInstall, ' u'com.apple.pkg.update.compatibility.2013.001.') self.assertEqual(event_object.desc, expected_desc) expected_string = u'/item/ {}'.format(expected_desc) expected_short = expected_string[:77] + u'...' self._TestGetMessageStrings( event_object, expected_string, expected_short) if __name__ == '__main__': unittest.main()
{ "content_hash": "4ded87bd73d9066a1c2c7a122eeaea8a", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 79, "avg_line_length": 40.333333333333336, "alnum_prop": 0.7103305785123967, "repo_name": "cvandeplas/plaso", "id": "fd0a6e78207b7ad081e4fc906de2d58380e40c8c", "size": "3118", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plaso/parsers/plist_plugins/install_history_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "2812257" }, { "name": "Shell", "bytes": "22724" } ], "symlink_target": "" }
require 'fog/openstack/models/collection' require 'fog/openstack/identity/v2/models/role' module Fog module OpenStack class Identity class V2 class Roles < Fog::OpenStack::Collection model Fog::OpenStack::Identity::V2::Role def all(options = {}) load_response(service.list_roles(options), 'roles') end def get(id) service.get_role(id) end end end end end end
{ "content_hash": "a895c57a74402207f9b0cfb090741e40", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 63, "avg_line_length": 21.636363636363637, "alnum_prop": 0.5861344537815126, "repo_name": "fog/fog-openstack", "id": "4da71e466bc7956259971b6a7169bc4668d566ce", "size": "476", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/fog/openstack/identity/v2/models/roles.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "1590195" }, { "name": "Shell", "bytes": "144" } ], "symlink_target": "" }
/** * Module dependencies. */ var express = require('express'); var http = require('http'); var path = require('path'); var nconf = require('nconf'); // All paths are relative to the script root, so change the working directory to it. process.chdir(__dirname); // Set up config *before* loading sub-modules, so they can use it. nconf.argv() .env() .file('./config.json'); var wol = require('./server/routes/wol.js'); var onkyo = require('./server/routes/onkyo.js'); var userRoutes = require('./server/routes/user.js'); var app = express(); // We use the default built-in memory session store (which isn't really // production ready, but we have a loose definition of 'production'). // all environments app.set('port', process.env.PORT || nconf.get('port')); app.set('views', path.join(__dirname, 'views')); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(express.cookieParser(nconf.get('cookieSecret'))); app.use(express.session({ secret: nconf.get('cookieSecret'), cookie: { maxAge: 60000 * 60 * 24 }, // 24 hour session timeout })); app.use(app.router); // Use optimised client files in production environment. var publicDir = ('development' === app.get('env')) ? 'public' : 'public-opt'; app.use(express.static(path.join(__dirname, publicDir))); // development only if ('development' === app.get('env')) { app.use(express.errorHandler()); } // Wake-on-lan handler. app.post('/api/wol/:mac', wol.post); // Onkyo control handler. app.post('/api/onkyo/:command', onkyo.post); // User stuff. userRoutes.addRoutes(app); app.listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); });
{ "content_hash": "21b9630e317daa02118a1b8b0f737290", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 84, "avg_line_length": 28.50793650793651, "alnum_prop": 0.673162583518931, "repo_name": "simontaylor81/HomeAutomation", "id": "f00a315233085656756cc37f16d4d199084974d4", "size": "1796", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MasterServer/server.js", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "6496" }, { "name": "CSS", "bytes": "5163" }, { "name": "HTML", "bytes": "9740" }, { "name": "JavaScript", "bytes": "121326" }, { "name": "Python", "bytes": "1007" }, { "name": "Shell", "bytes": "154" } ], "symlink_target": "" }
title: Khaleesi Index decorator: basic slug: index.html ‡‡‡‡‡‡‡‡‡‡‡‡‡‡ <div class="primary"> <h4>test for order by create time, ascending order, full list.</h4> <h4>test many way of wrong variable expression syntax.</h4> <ul class="post_list"> #foreach ($post : $posts) <li title="${post:title}"> <p>$ { : } {} : ${ } ${--} ${:} ${} ${ $a{ } } ${variable:absent_var} ${page:absent_page}</p> <a href="${post:link}">${post:title}</a> <p>${post:description}</p> </li> #end </ul> <h4>test sub-directory looping.</h4> <ul class="post_list"> #foreach ($camera : $studio/cameras) <li title="${camera:subject}"> <p>subject: ${camera:subject}</p> <p>price: ${camera:price}</p> <p>Monitor Size : ${camera:MonitorSize}</p> <p>Weight: ${camera:Weight}</p> </li> #end </ul> <h4>test for order by sequence, ascending order, full list.</h4> #foreach ($theme : $themes_illustrates) ${theme:content} #end <h4>test for order by sequence, ascending order, limit 2 items.</h4> #foreach ($theme : $themes_illustrates 2) ${theme:content} #end <h4>test for order by sequence, descending order, full list.</h4> #foreach ($theme : $themes_illustrates desc) ${theme:content} #end <h4>test for order by sequence, descending order, limit 3 items.</h4> #foreach ($theme : $themes_illustrates desc 3) ${theme:content} #end </div>
{ "content_hash": "15aa2a69ecc7bdd397aee506639abd3f", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 109, "avg_line_length": 32.734693877551024, "alnum_prop": 0.5349127182044888, "repo_name": "vince-styling/khaleesi", "id": "5c3dd9c0f44cf6633f0eaf13492237dca2e9b076", "size": "1632", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/resources/test_site/_pages/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "39722" }, { "name": "JavaScript", "bytes": "892" }, { "name": "Ruby", "bytes": "55030" }, { "name": "Shell", "bytes": "1141" } ], "symlink_target": "" }
@interface ABI43_0_0EXAVPlayerData : NSObject <ABI43_0_0EXAVObject> @property (nonatomic, strong) AVQueuePlayer *player; @property (nonatomic, strong) NSURL *url; @property (nonatomic, strong) NSDictionary *headers; @property (nonatomic, strong) void (^statusUpdateCallback)(NSDictionary *); @property (nonatomic, strong) void (^metadataUpdateCallback)(NSDictionary *); @property (nonatomic, strong) void (^errorCallback)(NSString *); + (NSDictionary *)getUnloadedStatus; - (instancetype)initWithEXAV:(ABI43_0_0EXAV *)exAV withSource:(NSDictionary *)source withStatus:(NSDictionary *)parameters withLoadFinishBlock:(void (^)(BOOL success, NSDictionary *successStatus, NSString *error))loadFinishBlock; - (void)setStatus:(NSDictionary *)parameters resolver:(ABI43_0_0EXPromiseResolveBlock)resolve rejecter:(ABI43_0_0EXPromiseRejectBlock)reject; - (NSDictionary *)getStatus; - (void)replayWithStatus:(NSDictionary *)status resolver:(ABI43_0_0EXPromiseResolveBlock)resolve rejecter:(ABI43_0_0EXPromiseRejectBlock)reject; @end
{ "content_hash": "6f8c1cda44128e716f53d0354eb5faa0", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 115, "avg_line_length": 41.666666666666664, "alnum_prop": 0.7271111111111112, "repo_name": "exponentjs/exponent", "id": "cd4e42c8fd0e90fdb55d056b90e74788a57479ac", "size": "1269", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ios/versioned/sdk43/EXAV/EXAV/ABI43_0_0EXAVPlayerData.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "96902" }, { "name": "Batchfile", "bytes": "382" }, { "name": "C", "bytes": "896724" }, { "name": "C++", "bytes": "867983" }, { "name": "CSS", "bytes": "6732" }, { "name": "HTML", "bytes": "152590" }, { "name": "IDL", "bytes": "897" }, { "name": "Java", "bytes": "4588748" }, { "name": "JavaScript", "bytes": "9343259" }, { "name": "Makefile", "bytes": "8790" }, { "name": "Objective-C", "bytes": "10675806" }, { "name": "Objective-C++", "bytes": "364286" }, { "name": "Perl", "bytes": "5860" }, { "name": "Prolog", "bytes": "287" }, { "name": "Python", "bytes": "97564" }, { "name": "Ruby", "bytes": "45432" }, { "name": "Shell", "bytes": "6501" } ], "symlink_target": "" }
package com.amazonaws.services.glue.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.glue.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * GetSchemaByDefinitionRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class GetSchemaByDefinitionRequestProtocolMarshaller implements Marshaller<Request<GetSchemaByDefinitionRequest>, GetSchemaByDefinitionRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).operationIdentifier("AWSGlue.GetSchemaByDefinition") .serviceName("AWSGlue").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public GetSchemaByDefinitionRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<GetSchemaByDefinitionRequest> marshall(GetSchemaByDefinitionRequest getSchemaByDefinitionRequest) { if (getSchemaByDefinitionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<GetSchemaByDefinitionRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, getSchemaByDefinitionRequest); protocolMarshaller.startMarshalling(); GetSchemaByDefinitionRequestMarshaller.getInstance().marshall(getSchemaByDefinitionRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
{ "content_hash": "1739639b2979a45ba38a998bb8107e6e", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 158, "avg_line_length": 41.90384615384615, "alnum_prop": 0.7700780174391922, "repo_name": "aws/aws-sdk-java", "id": "0d8c6b66ff412db92977dcd169ce76c4cb18b7a1", "size": "2759", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/transform/GetSchemaByDefinitionRequestProtocolMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
require 'redcarpet' require 'active_support' require 'active_support/core_ext' require 'support-for' Dir['./lib/*'].each { |f| require f } ignore /[a-z]{2}-[A-Z]{2}$/ # Debugging set(:logging, ENV['RACK_ENV'] != 'production') activate :relative_assets set :relative_links, true set :markdown_engine, :redcarpet set :markdown, :layout_engine => :erb, :fenced_code_blocks => true, :lax_html_blocks => true, :renderer => Highlighter::HighlightedHTML.new activate :directory_indexes activate :toc activate :highlighter activate :alias def current_guide(mm_instance, current_page) path = current_page.path.gsub('.html', '') guide_path = path.split("/")[0] current_guide = mm_instance.data.pages.find do |guide| guide.url == guide_path end current_guide end def current_chapter(mm_instance, current_page) guide = current_guide(mm_instance, current_page) return unless guide path = current_page.path.gsub('.html', '') chapter_path = path.split('/')[1..-1].join('/') current_chapter = guide.pages.find do |chapter| chapter.url == chapter_path end current_chapter end ### # Build ### configure :build do set :spellcheck_allow_file, "./data/spelling-exceptions.txt" activate :spellcheck, ignore_selector: '.CodeRay', page: /^(?!.*stylesheets|.*javascript|.*fonts|.*images|.*analytics).*$/ activate :minify_css activate :minify_javascript, ignore: /.*examples.*js/ activate :html_proofer end ### # Pages ### page '404.html', directory_index: false # Don't build layouts standalone ignore '*_layout.erb' ### # Helpers ### helpers do # Workaround for content_for not working in nested layouts def partial_for(key, partial_name=nil) @partial_names ||= {} if partial_name @partial_names[key] = partial_name else @partial_names[key] end end def rendered_partial_for(key) partial_name = partial_for(key) partial(partial_name) if partial_name end def page_classes classes = super return 'not-found' if classes == '404' classes end end
{ "content_hash": "2a6e8ad2e3eeb2fcca02598262667419", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 124, "avg_line_length": 21.757894736842104, "alnum_prop": 0.6734397677793904, "repo_name": "tleskin/guides", "id": "7349d10118607944b8f45bdf4490161bd72da862", "size": "2067", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "config.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "40507" }, { "name": "HTML", "bytes": "8024" }, { "name": "JavaScript", "bytes": "1351" }, { "name": "Ruby", "bytes": "33290" } ], "symlink_target": "" }
package trikita.hut; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class UpdatePluginsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { App.actions().refresh(); } }
{ "content_hash": "b22926a22e17dc0fa19224d72baaed89", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 62, "avg_line_length": 25.5, "alnum_prop": 0.761437908496732, "repo_name": "trikita/hut", "id": "04d7cabc1890b80e64efd1d047d4f252956af669", "size": "306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/trikita/hut/UpdatePluginsReceiver.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "27663" } ], "symlink_target": "" }
<?php namespace Kahlan\Spec\Suite\Jit\Patcher; use Kahlan\Jit\Parser; use Kahlan\Jit\Patcher\Rebase; describe("Rebase", function() { describe("->process()", function() { beforeEach(function() { $this->path = 'spec/Fixture/Jit/Patcher/Rebase'; $this->patcher = new Rebase(); }); it("patches class's methods", function() { $nodes = Parser::parse(file_get_contents($this->path . '/Rebase.php')); $expected = file_get_contents($this->path . '/RebaseProcessed.php'); $actual = Parser::unparse($this->patcher->process($nodes, '/the/original/path/Rebase.php')); expect($actual)->toBe($expected); }); }); });
{ "content_hash": "851f9d9240c5c143acd29f2f390c7ea2", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 104, "avg_line_length": 26.74074074074074, "alnum_prop": 0.574792243767313, "repo_name": "m1ome/kahlan", "id": "4545cb8a2a660c07dc13e500707de04b4cb3553a", "size": "722", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/Suite/Jit/Patcher/RebaseSpec.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "50" }, { "name": "Hack", "bytes": "73" }, { "name": "PHP", "bytes": "795368" } ], "symlink_target": "" }
package com.zuehlke.carrera.comp.domain; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.zuehlke.carrera.comp.domain.util.CustomDateTimeDeserializer; import com.zuehlke.carrera.comp.domain.util.CustomDateTimeSerializer; import org.hibernate.annotations.Type; import org.joda.time.LocalDateTime; import javax.persistence.*; public class RunPerformedNotification { private String teamName; private Long sessionId; public RunPerformedNotification() { } public RunPerformedNotification(String teamName, Long sessionId ) { this.teamName = teamName; this.sessionId = sessionId; } public String getTeamName() { return teamName; } public Long getSessionId() { return sessionId; } public void setTeamName(String teamName) { this.teamName = teamName; } public void setSessionId(Long sessionId) { this.sessionId = sessionId; } }
{ "content_hash": "98a3bdb72a07c97dc6c794bc3f7af041", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 71, "avg_line_length": 25.024390243902438, "alnum_prop": 0.7290448343079922, "repo_name": "FastAndFurious/competitions", "id": "4985e692bdfa78dfcb0a885d6ca7c57de1505eff", "size": "1026", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/zuehlke/carrera/comp/domain/RunPerformedNotification.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "24139" }, { "name": "CSS", "bytes": "307267" }, { "name": "HTML", "bytes": "151392" }, { "name": "Java", "bytes": "380853" }, { "name": "JavaScript", "bytes": "141826" }, { "name": "Scala", "bytes": "10517" } ], "symlink_target": "" }
package org.apache.kafka.streams.state.internals; import org.apache.kafka.streams.errors.InvalidStateStoreException; import org.apache.kafka.streams.processor.StateStore; import org.apache.kafka.streams.processor.internals.StreamTask; import org.apache.kafka.streams.processor.internals.StreamThread; import org.apache.kafka.streams.state.QueryableStoreType; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Wrapper over StreamThread that implements StateStoreProvider */ public class StreamThreadStateStoreProvider implements StateStoreProvider { private final StreamThread streamThread; public StreamThreadStateStoreProvider(final StreamThread streamThread) { this.streamThread = streamThread; } @SuppressWarnings("unchecked") @Override public <T> List<T> stores(final String storeName, final QueryableStoreType<T> queryableStoreType) { if (streamThread.state() == StreamThread.State.DEAD) { return Collections.emptyList(); } if (!streamThread.isInitialized()) { throw new InvalidStateStoreException("the state store, " + storeName + ", may have migrated to another instance."); } final List<T> stores = new ArrayList<>(); for (StreamTask streamTask : streamThread.tasks().values()) { final StateStore store = streamTask.getStore(storeName); if (store != null && queryableStoreType.accepts(store)) { if (!store.isOpen()) { throw new InvalidStateStoreException("the state store, " + storeName + ", may have migrated to another instance."); } stores.add((T) store); } } return stores; } }
{ "content_hash": "af69dfae50048b519a4f830399b9ce74", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 135, "avg_line_length": 36.791666666666664, "alnum_prop": 0.6862967157417894, "repo_name": "airbnb/kafka", "id": "45d9898e1d928884b672fdf998afc4fa0ed2d443", "size": "2564", "binary": false, "copies": "4", "ref": "refs/heads/trunk", "path": "streams/src/main/java/org/apache/kafka/streams/state/internals/StreamThreadStateStoreProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "27418" }, { "name": "HTML", "bytes": "5443" }, { "name": "Java", "bytes": "9685753" }, { "name": "Python", "bytes": "569628" }, { "name": "Scala", "bytes": "4619584" }, { "name": "Shell", "bytes": "66776" }, { "name": "XSLT", "bytes": "7116" } ], "symlink_target": "" }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="InMemoryServiceBusTestsBase.cs" company="Epworth Consulting Ltd."> // © Epworth Consulting Ltd. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Atlas.ServiceBus.InMemory.Tests.InMemoryServiceBusTests { using Atlas.Core.Logging; using Atlas.ServiceBus.InMemory; using Atlas.ServiceBus.InMemory.Implementations; using FakeItEasy; using NUnit.Framework; public abstract class InMemoryServiceBusTestsBase { protected IMessageSubscriptionFactory MessageSubscriptionFactory { get; set; } protected IMessageServiceExchange MessageServiceExchange { get; set; } protected ILogger Logger { get; set; } [SetUp] public void SetupBeforeEachTestBase() { this.MessageSubscriptionFactory = A.Fake<IMessageSubscriptionFactory>(); this.MessageServiceExchange = A.Fake<IMessageServiceExchange>(); this.Logger = A.Fake<ILogger>(); } protected InMemoryServiceBus CreateInMemoryServiceBus() { return new InMemoryServiceBus( this.MessageSubscriptionFactory, this.MessageServiceExchange, this.Logger); } } }
{ "content_hash": "fa48d99bd9eb4d294bf8d18a89bfdf54", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 120, "avg_line_length": 34.7, "alnum_prop": 0.5806916426512968, "repo_name": "acraven/service-bus", "id": "cc2d88d2c9ded20043f249b8af0458828fa294b9", "size": "1391", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Atlas.ServiceBus.InMemory.Tests/InMemoryServiceBusTests/InMemoryServiceBusTestsBase.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "246534" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using Amazon.Runtime; namespace Amazon.IdentityManagement.Model { /// <summary> /// Returns information about the DeleteSigningCertificate response metadata. /// The DeleteSigningCertificate operation has a void result type. /// </summary> public class DeleteSigningCertificateResponse : AmazonWebServiceResponse { } }
{ "content_hash": "b671ef919e61f198d1b65309c00a62e0", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 81, "avg_line_length": 23.894736842105264, "alnum_prop": 0.7466960352422908, "repo_name": "emcvipr/dataservices-sdk-dotnet", "id": "e721159f319181dcd5cb36cfc4bd1d7f785c639d", "size": "1041", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AWSSDK/Amazon.IdentityManagement/Model/DeleteSigningCertificateResponse.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "30500772" }, { "name": "Shell", "bytes": "1726" }, { "name": "XSLT", "bytes": "337772" } ], "symlink_target": "" }
@interface CRWJSEarlyScriptManager : CRWJSInjectionManager @end #endif // IOS_WEB_PUBLIC_WEB_STATE_JS_CRW_JS_EARLY_SCRIPT_MANAGER_H_
{ "content_hash": "3774bd6c09d8d608a5785365525e69eb", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 69, "avg_line_length": 33.75, "alnum_prop": 0.7925925925925926, "repo_name": "mou4e/zirconium", "id": "8aa95cd0e02bbe059f2c707897c6045dec756096", "size": "800", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "ios/web/public/web_state/js/crw_js_early_script_manager.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "23829" }, { "name": "C", "bytes": "4115478" }, { "name": "C++", "bytes": "233013312" }, { "name": "CSS", "bytes": "931463" }, { "name": "Emacs Lisp", "bytes": "988" }, { "name": "HTML", "bytes": "28131619" }, { "name": "Java", "bytes": "9810569" }, { "name": "JavaScript", "bytes": "19670133" }, { "name": "Makefile", "bytes": "68017" }, { "name": "Objective-C", "bytes": "1475873" }, { "name": "Objective-C++", "bytes": "8640851" }, { "name": "PHP", "bytes": "97817" }, { "name": "PLpgSQL", "bytes": "171186" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "456460" }, { "name": "Python", "bytes": "7958623" }, { "name": "Shell", "bytes": "477153" }, { "name": "Standard ML", "bytes": "4965" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Demo</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="default_fragment_text">Default fragment.</string> <!-- DRAWER --> <string-array name="menu_array"> <item>Profile</item> <item>Friend List</item> <item>Photos</item> <item>Events</item> <item>Settings</item> </string-array> <string name="drawer_open">Open navigation drawer</string> <string name="drawer_close">Close navigation drawer</string> </resources>
{ "content_hash": "80859db64d05d7919eb1af4e20138ea8", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 67, "avg_line_length": 31.8, "alnum_prop": 0.6367924528301887, "repo_name": "blackcj/AndroidSupportLibrary_r18_Demo", "id": "cb41debd188155f7d4dcc94db541c9c515480991", "size": "636", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AndroidSupportLibraryDemo/src/main/res/values/strings.xml", "mode": "33261", "license": "mit", "language": [ { "name": "Groovy", "bytes": "616" }, { "name": "Java", "bytes": "8140" }, { "name": "Shell", "bytes": "7484" } ], "symlink_target": "" }
#!/usr/bin/env node function usage() { console.error('Usage : createPost.js <webid> <message> [application]'); } if (!process.argv[2]) { console.error('Webid is required'); usage(); process.exit(-1); } if (!process.argv[3]) { console.error('Message is required'); usage(); process.exit(-1); } var webid = process.argv[2]; var message = process.argv[3]; var application = process.argv[4]; /** * create a post in turtle * @param {string} webid the creator * @param {string} message the message to send * @param {string} application application that created it * @return {string} the message in turtle */ function createPost(webid, message, application) { var turtle; turtle = '<#this> '; turtle += ' <http://purl.org/dc/terms/created> "'+ new Date().toISOString() +'"^^<http://www.w3.org/2001/XMLSchema#dateTime> ;\n'; turtle += ' <http://purl.org/dc/terms/creator> <' + webid + '> ;\n'; turtle += ' <http://rdfs.org/sioc/ns#content> "'+ message.trim() +'" ;\n'; turtle += ' a <http://rdfs.org/sioc/ns#Post> ;\n'; if (application) { turtle += ' <https://w3.org/ns/solid/app#application> <' + application + '> ;\n'; } turtle += ' <http://www.w3.org/ns/mblog#author> <'+ webid +'> .\n'; return turtle; } console.log(createPost(webid, message, application));
{ "content_hash": "969d1df025b1c156d2d31b78bfe2d2e4", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 135, "avg_line_length": 29.32608695652174, "alnum_prop": 0.6108228317272053, "repo_name": "melvincarvalho/webid.im", "id": "e94ba7875603290c975aad7a2c6e1fc39666567c", "size": "1349", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bin/sendPost.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "39120" }, { "name": "HTML", "bytes": "141460" }, { "name": "JavaScript", "bytes": "81727" } ], "symlink_target": "" }
@interface UIViewController (CustomBackButton) - (void)replaceBackButton; @end
{ "content_hash": "bff22a817a67a8087c0899be5d7759ee", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 46, "avg_line_length": 16.2, "alnum_prop": 0.8024691358024691, "repo_name": "dianchang/spark", "id": "d8bef629d5e5f4a0cf7b50d5c5d368a4623bea83", "size": "256", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spark/Categories/UIViewController+CustomBackButton.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "267" }, { "name": "Objective-C", "bytes": "211031" }, { "name": "Ruby", "bytes": "319" } ], "symlink_target": "" }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="net.wtako.shouldiresign.QuestionsActivity$PlaceholderFragment"> <TextView android:id="@+id/question_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/relativeLayout" android:layout_centerHorizontal="true" android:layout_marginBottom="48dp" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" /> <RelativeLayout android:id="@+id/relativeLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_centerVertical="true"> <Button android:id="@+id/answer_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:background="@color/colorPrimaryDark" android:text="New Button" android:textColor="@color/abc_secondary_text_material_dark" /> </RelativeLayout> </RelativeLayout>
{ "content_hash": "45ce598f4a708bf6c358e7ad77d1fe42", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 82, "avg_line_length": 41.11904761904762, "alnum_prop": 0.6832657788071801, "repo_name": "Saren-Arterius/Should-I-Resign", "id": "c99a3cb0d0aff369ef6b6b6f6a6efdd819999af0", "size": "1727", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/single_answer_question.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "17487" } ], "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. */ (function () { angular .module('gbpui.transfer-table-bridge') .directive('dSelect', function () { return { restrict: 'A', scope: true, link: function ($scope, $elem, $attrs, $ctrl) { $.each($scope.tableData.available, function (index, optionObject) { var option = $("<option></option>"); option.attr("value", optionObject.id); option.append(optionObject.name); $elem.append(option); }); // This change listener watches for changes to the raw // HTML select element; since the select should be hidden, // the only possible change is the creation of a new // option using the horizon add button. $elem.change(function () { // Find the last option in the select, since the // addition is done by Horizon appending the a new // option element var option = $(this).find("option").last(); // Create a valid option object and make it available // at the end of the available list var val = { 'id': option.attr('value'), 'name': option.text() }; $scope.tableData.available.push(val); // Deallocate all the objects using the built in // transfer table controller deallocation method var toDeallocate = $scope.tableData.allocated.slice(); $.each(toDeallocate, function (index, object) { $scope.trCtrl.deallocate(object); }); // Notify the scope of the deallocations $scope.$apply(); // Allocate the new option; this mimicks te behaviour // of the normal Horizon based adding $scope.trCtrl.allocate(val); // Notify the scope of the allocation changes $scope.$apply(); }); // The directive watches for a changes in the allocated // list to dynamically set values for the hidden element. $scope.$watchCollection( function (scope) { return $scope.tableData.allocated; }, function (newValue, oldValue) { var values = $.map( newValue, function (value, index) { return value.id; }); $elem.val(values); } ); // Sets initial values as allocated when appropriate $.each($scope.initial, function (index, initialObject) { $scope.trCtrl.allocate(initialObject); }); } } }); })();
{ "content_hash": "a0e4c97bb6e277c0e8866d5b1db8d035", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 87, "avg_line_length": 43.71111111111111, "alnum_prop": 0.46568378240976105, "repo_name": "noironetworks/group-based-policy-ui", "id": "76276632ab7b483bf49e8d1f84f280fc54fdea8a", "size": "3934", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gbpui/static/dashboard/gbpui/transfer-table-bridge/d-select.directive.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "31546" }, { "name": "HTML", "bytes": "26683" }, { "name": "JavaScript", "bytes": "37600" }, { "name": "Python", "bytes": "277035" }, { "name": "SCSS", "bytes": "174" }, { "name": "Shell", "bytes": "16825" } ], "symlink_target": "" }
local socket = require"socket" local lfs = require"lfs" local debug = require"debug" module("remdebug.engine", package.seeall) _COPYRIGHT = "2006 - Kepler Project" _DESCRIPTION = "Remote Debugger for the Lua programming language" _VERSION = "1.0" local UNIX = string.sub(lfs.currentdir(),1,1) == '/' if not UNIX then local global_print = print function print(...) global_print(...) io.stdout:flush() end end -- Some 'pretty printing' code. In particular, it will try to expand tables, up to -- a specified number of elements. -- obviously table.concat is much more efficient, but requires that the table values -- be strings. function join(tbl,delim,start,finish) local n = table.getn(tbl) local res = '' local k = 0 -- this is a hack to work out if a table is 'list-like' or 'map-like' local index1 = n > 0 and tbl[1] ~= nil local index2 = n > 1 and tbl[2] ~= nil if index1 and index2 then for i,v in ipairs(tbl) do res = res..delim..tostring(v) k = k + 1 if k > finish then res = res.." ... " end end else for i,v in pairs(tbl) do res = res..delim..tostring(i)..'='..tostring(v) k = k + 1 if k > finish then res = res.." ... " end end end return string.sub(res,2) end function expand_value(val) if type(val) == 'table' then if val.__tostring then return tostring(val) else return '{'..join(val,',',1,20)..'}' end elseif type(val) == 'string' then return "'"..val.."'" else return val end end local coro_debugger local events = { BREAK = 1, WATCH = 2 } local breakpoints = {} local watches = {} local step_into = false local step_over = false local step_level = 0 local stack_level = 0 local controller_host = "localhost" local controller_port = 8171 local function set_breakpoint(file, line) if not breakpoints[file] then breakpoints[file] = {} end breakpoints[file][line] = true end local function remove_breakpoint(file, line) if breakpoints[file] then breakpoints[file][line] = nil end end local function has_breakpoint(file, line) return breakpoints[file] and breakpoints[file][line] end local function restore_vars(vars) if type(vars) ~= 'table' then return end local func = debug.getinfo(3, "f").func local i = 1 local written_vars = {} while true do local name = debug.getlocal(3, i) if not name then break end debug.setlocal(3, i, vars[name]) written_vars[name] = true i = i + 1 end i = 1 while true do local name = debug.getupvalue(func, i) if not name then break end if not written_vars[name] then debug.setupvalue(func, i, vars[name]) written_vars[name] = true end i = i + 1 end end local function capture_vars() local vars = {} local func = debug.getinfo(3, "f").func local i = 1 while true do local name, value = debug.getupvalue(func, i) if not name then break end vars[name] = value i = i + 1 end i = 1 while true do local name, value = debug.getlocal(3, i) if not name then break end vars[name] = value i = i + 1 end setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) }) return vars end local function break_dir(path) local paths = {} path = string.gsub(path, "\\", "/") for w in string.gfind(path, "[^\/]+") do table.insert(paths, w) end return paths end local function merge_paths(path1, path2) -- check if path is already absolute if UNIX then if string.sub(path2,1,1) == '/' then return path2 end else if string.sub(path2,2,2) == ':' then return path2:gsub('\\','/') end end local paths1 = break_dir(path1) local paths2 = break_dir(path2) for i, path in ipairs(paths2) do if path == ".." then table.remove(paths1, table.getn(paths1)) elseif path ~= "." then table.insert(paths1, path) end end local res = table.concat(paths1, "/") if UNIX then return "/"..res else return res end end local function debug_hook(event, line) if event == "call" then stack_level = stack_level + 1 elseif event == "return" then stack_level = stack_level - 1 else local file = debug.getinfo(2, "S").source if string.find(file, "@") == 1 then file = string.sub(file, 2) end file = merge_paths(lfs.currentdir(), file) local vars = capture_vars() table.foreach(watches, function (index, value) setfenv(value, vars) local status, res = pcall(value) if status and res then coroutine.resume(coro_debugger, events.WATCH, vars, file, line, index) end end) if step_into or (step_over and stack_level <= step_level) or has_breakpoint(file, line) then step_into = false step_over = false coroutine.resume(coro_debugger, events.BREAK, vars, file, line) restore_vars(vars) end end end --- protocol response helpers local function bad_request(server) server:send("400 Bad Request\n") -- check this! end local function OK(server,res) if res then if type(res) == 'string' then server:send("200 OK "..string.len(res).."\n") server:send(res) else server:send("200 OK "..res.."\n") end else server:send("200 OK\n") end end local function pause(server,file,line,idx_watch) if not idx_watch then server:send("202 Paused " .. file .. " " .. line .. "\n") else server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n") end end local function error(server,type,res) server:send("401 Error in "..type.." " .. string.len(res) .. "\n") server:send(res) end local function debugger_loop(server) local command local eval_env = {} while true do local line, status = server:receive() command = string.sub(line, string.find(line, "^[A-Z]+")) --~ print('engine',command) if command == "SETB" then local _, _, _, filename, line = string.find(line, "^([A-Z]+)%s+([%w%p]+)%s+(%d+)$") if filename and line then set_breakpoint(filename, tonumber(line)) OK(server) else bad_request(server) end elseif command == "DELB" then local _, _, _, filename, line = string.find(line, "^([A-Z]+)%s+([%w%p]+)%s+(%d+)$") if filename and line then remove_breakpoint(filename, tonumber(line)) OK(server) else bad_request(server) end elseif command == "EXEC" then local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$") if chunk then local func = loadstring(chunk) local status, res if func then setfenv(func, eval_env) status, res = xpcall(func, debug.traceback) end res = tostring(res) if status then OK(server,res) else error(server,"Execute",res) end else bad_request(server) end elseif command == "SETW" then local _, _, exp = string.find(line, "^[A-Z]+%s+(.+)$") if exp then local func = loadstring("return(" .. exp .. ")") local newidx = table.getn(watches) + 1 watches[newidx] = func table.setn(watches, newidx) OK(server,newidx) else bad_request(server) end elseif command == "DELW" then local _, _, index = string.find(line, "^[A-Z]+%s+(%d+)$") index = tonumber(index) if index then watches[index] = nil OK(server) else bad_request(server) end elseif command == "RUN" or command == "STEP" or command == "OVER" then OK(server) if command == "STEP" then step_into = true elseif command == "OVER" then step_over = true step_level = stack_level end local ev, vars, file, line, idx_watch = coroutine.yield() eval_env = vars if ev == events.BREAK then pause(server,file,line) elseif ev == events.WATCH then pause(server,file,line,idx_watch) else error(server,"Execution",file) end elseif command == "LOCALS" then -- new -- -- not sure why I had to hack it this way?? SJD local tmpfile = 'remdebug-tmp.txt' local f = io.open(tmpfile,'w') for k,v in pairs(eval_env) do if k:sub(1,1) ~= '(' then f:write(k,' = ',tostring(v),'\n') end end f:close() f = io.open(tmpfile,'r') local res = f:read("*a") f:close() OK(server,res) elseif command == "DETACH" then --new-- debug.sethook() OK(server) else bad_request(server) end end end coro_debugger = coroutine.create(debugger_loop) -- -- remdebug.engine.config(tab) -- Configures the engine -- function config(tab) if tab.host then controller_host = tab.host end if tab.port then controller_port = tab.port end end -- -- remdebug.engine.start() -- Tries to start the debug session by connecting with a controller -- function start() pcall(require, "remdebug.config") local server = socket.connect(controller_host, controller_port) if server then _TRACEBACK = function (message) local err = debug.traceback(message) error(server,"Execute",res) server:close() return err end debug.sethook(debug_hook, "lcr") return coroutine.resume(coro_debugger, server) end end
{ "content_hash": "adfb430c9e4792cff1d3ef373533cb8f", "timestamp": "", "source": "github", "line_count": 369, "max_line_length": 96, "avg_line_length": 25.54742547425474, "alnum_prop": 0.6004030974859447, "repo_name": "ArcherSys/ArcherSys", "id": "1dd6de5dc79662841dc2213eee63ad9fc1504920", "size": "9527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Lua/SciTE/scite-debug/remDebug/remdebug/engine.lua", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import vtkBoundingBox from './BoundingBox'; import vtkBox from './Box'; import vtkCell from './Cell'; import vtkCone from './Cone'; import vtkCylinder from './Cylinder'; import vtkDataSet from './DataSet'; import vtkDataSetAttributes from './DataSetAttributes'; import vtkITKHelper from './ITKHelper'; import vtkImageData from './ImageData'; import vtkImplicitBoolean from './ImplicitBoolean'; import vtkLine from './Line'; import vtkMolecule from './Molecule'; import vtkPiecewiseFunction from './PiecewiseFunction'; import vtkPlane from './Plane'; import vtkPointSet from './PointSet'; import vtkPolyData from './PolyData'; import vtkSelectionNode from './SelectionNode'; import vtkSphere from './Sphere'; import vtkStructuredData from './StructuredData'; import vtkTriangle from './Triangle'; export default { vtkBoundingBox, vtkBox, vtkCell, vtkCone, vtkCylinder, vtkDataSet, vtkDataSetAttributes, vtkITKHelper, vtkImageData, vtkImplicitBoolean, vtkLine, vtkMolecule, vtkPiecewiseFunction, vtkPlane, vtkPointSet, vtkPolyData, vtkSelectionNode, vtkSphere, vtkStructuredData, vtkTriangle, };
{ "content_hash": "d81a41eb3bb494dd9cd1b1621a78e56a", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 55, "avg_line_length": 26.3953488372093, "alnum_prop": 0.7638766519823789, "repo_name": "Kitware/vtk-js", "id": "f8bda9d4c2f39c19118c8bc7f51e63154571e0d9", "size": "1135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Sources/Common/DataModel/index.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "6475" }, { "name": "GLSL", "bytes": "88494" }, { "name": "HTML", "bytes": "68637" }, { "name": "JavaScript", "bytes": "4544289" }, { "name": "Python", "bytes": "75108" }, { "name": "Shell", "bytes": "4047" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_21.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.string.label.xml Template File: sources-sink-21.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using malloc() and set data pointer to a small buffer * GoodSource: Allocate using malloc() and set data pointer to a large buffer * Sink: snprintf * BadSink : Copy string to data using snprintf * Flow Variant: 21 Control flow: Flow controlled by value of a static global variable. All functions contained in one file. * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define SNPRINTF _snwprintf #else #define SNPRINTF snprintf #endif #ifndef OMITBAD /* The static variable below is used to drive control flow in the source function */ static int badStatic = 0; static wchar_t * badSource(wchar_t * data) { if(badStatic) { /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */ data = (wchar_t *)malloc(50*sizeof(wchar_t)); data[0] = L'\0'; /* null terminate */ } return data; } void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_21_bad() { wchar_t * data; data = NULL; badStatic = 1; /* true */ data = badSource(data); { wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ SNPRINTF(data, 100, L"%s", source); printWLine(data); free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* The static variables below are used to drive control flow in the source functions. */ static int goodG2B1Static = 0; static int goodG2B2Static = 0; /* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */ static wchar_t * goodG2B1Source(wchar_t * data) { if(goodG2B1Static) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = (wchar_t *)malloc(100*sizeof(wchar_t)); data[0] = L'\0'; /* null terminate */ } return data; } static void goodG2B1() { wchar_t * data; data = NULL; goodG2B1Static = 0; /* false */ data = goodG2B1Source(data); { wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ SNPRINTF(data, 100, L"%s", source); printWLine(data); free(data); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */ static wchar_t * goodG2B2Source(wchar_t * data) { if(goodG2B2Static) { /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = (wchar_t *)malloc(100*sizeof(wchar_t)); data[0] = L'\0'; /* null terminate */ } return data; } static void goodG2B2() { wchar_t * data; data = NULL; goodG2B2Static = 1; /* true */ data = goodG2B2Source(data); { wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ SNPRINTF(data, 100, L"%s", source); printWLine(data); free(data); } } void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_21_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_21_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_21_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "bcee345240fc67687d99ed0898796e79", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 124, "avg_line_length": 30.152439024390244, "alnum_prop": 0.6196157735085945, "repo_name": "maurer/tiamat", "id": "c410bed68658c540dd32d9b9773cc99ff49a1eb9", "size": "4945", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/Juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s09/CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_21.c", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/Starbuzz.iml" filepath="$PROJECT_DIR$/Starbuzz.iml" /> <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" /> </modules> </component> </project>
{ "content_hash": "c8d9d116d0203ff297622a8faa072e48", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 98, "avg_line_length": 35.5, "alnum_prop": 0.6535211267605634, "repo_name": "kunal01996/Android-Studio-Test-Projects", "id": "fe26743cdcf739901c97e68c07d29673142cf3de", "size": "355", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/modules.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "4558" } ], "symlink_target": "" }
Wireboard.CommandMap = (function(undefined) { 'use strict'; var CommandMap = function() { this.initialize.apply(this, arguments); }; CommandMap.prototype = { /** * Use event types as key and value is array containing * commands that are executed when that event occurs. * * @type {Object} */ mappings: {}, /** * @type {Wireboard.EventDispatcher} */ dispatcher: 'inject', /** * @type {Wireboard.Context} */ context: 'inject', /** * @type {injector.Injector} */ injector: null, /** * @param {injector.Injector} injector */ initialize: function(injector) { this.injector = injector; this.injector.injectInto(this); this.dispatcher.addGlobalListener(this._onEvent.bind(this)); }, /** * * @param {String} eventType * @param {Wireboard.Command} CommandClass * @return {Wireboard.CommandMap} */ map: function(eventType, CommandClass) { if (this.mappings[eventType] === undefined) { this.mappings[eventType] = []; } this.mappings[eventType].push(CommandClass); return this; }, /** * @param {Wireboard.Event} event * @private */ _onEvent: function(event) { var type = event.getType(); var typeMappings = this.mappings[type]; if (typeMappings === undefined) { return; } // Execute the command(s) that match the event type typeMappings.forEach(function(CommandClass) { this._executeCommand(CommandClass, event); }.bind(this)); }, /** * @param {Wireboard.Command|Function} CommandClass * @param {Wireboard.Event} event * @private */ _executeCommand: function(CommandClass, event) { var command = new CommandClass(event); // Inject into the command this.injector.injectInto(command); command.execute(); }, /** * @returns {String} */ toString: function() { return '[object Wireboard.CommandMap]'; } }; return CommandMap; })();
{ "content_hash": "490631c285c86ca32c905fa39592b8b8", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 72, "avg_line_length": 24.287128712871286, "alnum_prop": 0.4977578475336323, "repo_name": "laurentvd/wireboard.js", "id": "1b44c8e7fcf82b24810a62d6c7342fa0d5d339fa", "size": "2453", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/CommandMap.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "972" }, { "name": "JavaScript", "bytes": "73786" } ], "symlink_target": "" }
myproject ====== .. image:: https://travis-ci.org/mapbox/myproject.svg :target: https://travis-ci.org/mapbox/myproject .. image:: https://coveralls.io/repos/mapbox/myproject/badge.png :target: https://coveralls.io/r/mapbox/myproject A skeleton of a Python package with CLI and test suite included. .. image:: https://farm4.staticflickr.com/3951/15672691531_3037819613_o_d.png Customization quick start ------------------------- To use myproject as the start of a new project, do the following, preferably in a virtual environment. Clone the repo. .. code-block:: console git clone https://github.com/mapbox/myproject myproject cd myproject Replace all occurrences of 'myproject' with the name of your own project. (Note: the commands below require bash, find, and sed and are yet tested only on OS X.) .. code-block:: console if [ -d myproject ]; then find . -not -path './.git*' -type f -exec sed -i '' -e 's/myproject/myproject/g' {} + ; fi mv myproject myproject Then install in locally editable (``-e``) mode and run the tests. .. code-block:: console pip install -e .[test] py.test Finally, give the command line program a try. .. code-block:: console myproject --help myproject 4 To help prevent uncustomized forks of myproject from being uploaded to PyPI, I've configured the setup's upload command to dry run. Make sure to remove this configuration from `setup.cfg <https://docs.python.org/2/install/index.html#inst-config-syntax>`__ when you customize myproject. Please also note that the Travis-CI and Coveralls badge URLs and links in the README contain the string 'mapbox.' You'll need to change this to your own user or organization name and turn on the webhooks for your new project. A post on the Mapbox blog has more information about this project: https://www.mapbox.com/blog/myproject/. See also -------- Here are a few other tools for initializing Python projects. - Paste Script's `paster create <http://pythonpaste.org/script/#paster-create>`__ is one that I've used for a long time. - `cookiecutter-pypackage <https://github.com/audreyr/cookiecutter-pypackage>`__ is a Cookiecutter template for a Python package. Cookiecutter supports many languages, includes Travis configuration and much more.
{ "content_hash": "f6b1a86c4e648ff161c74f4a299b2633", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 120, "avg_line_length": 32.7, "alnum_prop": 0.7295762341633901, "repo_name": "mike-seagull/pyskel", "id": "ef73aedb614d5ed78f65164353ad34ddf2460bdf", "size": "2289", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "861" }, { "name": "Shell", "bytes": "463" } ], "symlink_target": "" }
#ifndef _SCHEDULEROBJECT_H #define _SCHEDULEROBJECT_H // condor includes #include "condor_common.h" #include "condor_classad.h" // local includes #include "Codec.h" #include "AviaryUtils.h" using namespace std; using namespace aviary::util; using namespace aviary::codec; namespace aviary { namespace job { struct SchedulerStats { // Properties string CondorPlatform; string CondorVersion; int64_t DaemonStartTime; string Pool; string System; int64_t JobQueueBirthdate; uint32_t MaxJobsRunning; string Machine; string MyAddress; string Name; // Statistics uint32_t MonitorSelfAge; double MonitorSelfCPUUsage; double MonitorSelfImageSize; uint32_t MonitorSelfRegisteredSocketCount; uint32_t MonitorSelfResidentSetSize; int64_t MonitorSelfTime; uint32_t NumUsers; uint32_t TotalHeldJobs; uint32_t TotalIdleJobs; uint32_t TotalJobAds; uint32_t TotalRemovedJobs; uint32_t TotalRunningJobs; }; class SchedulerObject { public: void update(const ClassAd &ad); bool submit(AttributeMapType& jobAdMap, string& id, string& text); bool setAttribute(string id, string name, string value, string &text); bool hold(string id, string &reason, string &text); bool release(string id, string &reason, string &text); bool remove(string id, string &reason, string &text); bool suspend(string id, string &reason, string &text); bool _continue(string id, string &reason, string &text); static SchedulerObject* getInstance(); const char* getPool() {return m_pool.c_str(); } const char* getName() {return m_name.c_str(); } ~SchedulerObject(); private: SchedulerObject(); SchedulerObject(SchedulerObject const&); SchedulerObject& operator=(SchedulerObject const&); string m_pool; string m_name; Codec* m_codec; SchedulerStats m_stats; static SchedulerObject* m_instance; }; }} /* aviary::job */ #endif /* _SCHEDULEROBJECT_H */
{ "content_hash": "a4a14f3f939191c0ff28383638a6f2bc", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 67, "avg_line_length": 23.96590909090909, "alnum_prop": 0.6666666666666666, "repo_name": "bbockelm/condor-network-accounting", "id": "12a42c8b6b650628b77124789b908eb5ac9de4eb", "size": "2710", "binary": false, "copies": "3", "ref": "refs/heads/upstream_master", "path": "src/condor_contrib/aviary/src/SchedulerObject.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3482256" }, { "name": "C++", "bytes": "20755012" }, { "name": "FORTRAN", "bytes": "110251" }, { "name": "Java", "bytes": "44326" }, { "name": "JavaScript", "bytes": "2095" }, { "name": "Objective-C", "bytes": "147675" }, { "name": "Perl", "bytes": "2203091" }, { "name": "Python", "bytes": "821585" }, { "name": "Racket", "bytes": "129" }, { "name": "Ruby", "bytes": "35030" }, { "name": "Shell", "bytes": "655454" }, { "name": "Visual Basic", "bytes": "4985" } ], "symlink_target": "" }
/** * @file * @brief HTTP Server handler * * Sample server that return a text/plain string. The content of this * is read from stdin. To see the usage help, -h or --help. */ #include <getopt.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include "soletta.h" #include "sol-http.h" #include "sol-http-server.h" #include "sol-util.h" #include "sol-util-file.h" static struct sol_http_server *server; static struct sol_fd *stdin_watch; static struct sol_buffer value; static bool on_stdin(void *data, int fd, uint32_t flags) { if (flags & (SOL_FD_FLAGS_ERR | SOL_FD_FLAGS_HUP)) { fprintf(stderr, "ERROR: Something wrong happened with file descriptor: %d\n", fd); goto err; } if (flags & SOL_FD_FLAGS_IN) { int err; value.used = 0; /* this will loop trying to read as much data as possible to buffer. */ err = sol_util_load_file_fd_buffer(fd, &value); if (err < 0) { fprintf(stderr, "ERROR: failed to read from stdin: %s\n", sol_util_strerrora(-err)); goto err; } if (value.used == 0) { /* no data usually means ^D on the terminal, quit the application */ puts("no data on stdin, quitting."); sol_quit(); } else { printf("Now serving %zd bytes:\n--BEGIN--\n%.*s\n--END--\n", value.used, SOL_STR_SLICE_PRINT(sol_buffer_get_slice(&value))); } } return true; err: sol_quit_with_code(EXIT_FAILURE); return false; } static int request_cb(void *data, struct sol_http_request *request) { int r; struct sol_http_response response = { SOL_SET_API_VERSION(.api_version = SOL_HTTP_RESPONSE_API_VERSION, ) .param = SOL_HTTP_REQUEST_PARAMS_INIT, .response_code = SOL_HTTP_STATUS_OK }; response.content = value; r = sol_http_params_add(&response.param, SOL_HTTP_REQUEST_PARAM_HEADER("Content-Type", "text/plain")); if (r < 0) fprintf(stderr, "ERROR: Could not set the 'Content-Type' header\n"); r = sol_http_server_send_response(request, &response); sol_http_params_clear(&response.param); return r; } static void startup_server(void) { char **argv = sol_argv(); int port = 8080, c, opt_idx, argc = sol_argc(); static const struct option opts[] = { { "port", required_argument, NULL, 'p' }, { "help", no_argument, NULL, 'h' }, { 0, 0, 0, 0 } }; sol_buffer_init(&value); while ((c = getopt_long(argc, argv, "p:h", opts, &opt_idx)) != -1) { switch (c) { case 'p': port = atoi(optarg); break; case 'h': default: fprintf(stderr, "Usage:\n\t%s [-p <port >]\n", argv[0]); sol_quit_with_code(EXIT_SUCCESS); return; } } /* always set stdin to non-block before we use sol_fd_add() on it, * otherwise we may block reading and it would impact the main * loop dispatching other events. */ if (sol_util_fd_set_flag(STDIN_FILENO, O_NONBLOCK) < 0) { fprintf(stderr, "ERROR: cannot set stdin to non-block.\n"); goto err_watch; } stdin_watch = sol_fd_add(STDIN_FILENO, SOL_FD_FLAGS_IN | SOL_FD_FLAGS_HUP | SOL_FD_FLAGS_ERR, on_stdin, NULL); if (!stdin_watch) { fprintf(stderr, "ERROR: Failed to watch stdin\n"); goto err_watch; } c = sol_buffer_set_slice(&value, sol_str_slice_from_str("Soletta string server, set the value using the keyboard")); if (c < 0) { fprintf(stderr, "ERROR: Failed to set buffer's value\n"); goto err_buffer; } server = sol_http_server_new(&(struct sol_http_server_config) { SOL_SET_API_VERSION(.api_version = SOL_HTTP_SERVER_CONFIG_API_VERSION, ) .port = port, }); if (!server) { fprintf(stderr, "ERROR: Failed to create the server\n"); goto err_server; } if (sol_http_server_register_handler(server, "/", request_cb, NULL) < 0) { fprintf(stderr, "ERROR: Failed to register the handler\n"); goto err_handler; } printf("HTTP server at port %d.\nDefault reply set to '%.*s'\n", port, SOL_STR_SLICE_PRINT(sol_buffer_get_slice(&value))); return; err_handler: err_server: sol_buffer_fini(&value); err_buffer: sol_fd_del(stdin_watch); err_watch: sol_quit_with_code(EXIT_FAILURE); } static void shutdown_server(void) { if (server) sol_http_server_del(server); sol_buffer_fini(&value); } SOL_MAIN_DEFAULT(startup_server, shutdown_server);
{ "content_hash": "046e07f9014509ca8309ec1c77f7a314", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 96, "avg_line_length": 27.01156069364162, "alnum_prop": 0.5867750909479992, "repo_name": "brunobottazzini/soletta", "id": "eb6ef215d0c946ea9d3be1570d340b4f78f66bc2", "size": "5349", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/samples/http/server.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "3347" }, { "name": "C", "bytes": "5615150" }, { "name": "C++", "bytes": "174422" }, { "name": "CSS", "bytes": "3953" }, { "name": "HTML", "bytes": "1623" }, { "name": "JavaScript", "bytes": "120396" }, { "name": "Makefile", "bytes": "63125" }, { "name": "NSIS", "bytes": "1388" }, { "name": "Objective-C", "bytes": "10652" }, { "name": "Python", "bytes": "230321" }, { "name": "Shell", "bytes": "8007" }, { "name": "Smarty", "bytes": "1158" }, { "name": "VimL", "bytes": "748" } ], "symlink_target": "" }