text
stringlengths
2
1.04M
meta
dict
from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('expenses.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
{ "content_hash": "0efe738b48617aa4a52e09f56337c09e", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 67, "avg_line_length": 32.5, "alnum_prop": 0.7446153846153846, "repo_name": "asyncee/home-bookkeeping-sample", "id": "acfe22c2de42a8a3ce032c2847b421311d65db03", "size": "325", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sampleproject/urls.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1944" }, { "name": "HTML", "bytes": "9139" }, { "name": "Python", "bytes": "23727" }, { "name": "Shell", "bytes": "217" } ], "symlink_target": "" }
package com.bitgirder.lang; import com.bitgirder.validation.Inputs; import com.bitgirder.validation.State; public abstract class AbstractCompletion< V > implements Completion< V > { private final static Inputs inputs = new Inputs(); private final static State state = new State(); // both of these could be null (indicating a successful response of 'null') private final V res; private final Throwable th; protected AbstractCompletion( V res, Throwable th ) { this.res = res; this.th = th; } public final boolean isOk() { return th == null; } private void checkState( String callName, boolean wantOk ) { boolean isOk = isOk(); if ( isOk != wantOk ) { state.createFail( callName, "called with isOk() returning", isOk ); } } public final Throwable getThrowable() { checkState( "getException()", false ); return th; } public final V getResult() { checkState( "getResult()", true ); return res; } public final V get() throws Exception { if ( isOk() ) return res; else { if ( th instanceof Exception ) throw (Exception) th; else throw (Error) th; } } // subclasses can override @Override public String toString() { return Strings.inspect( this, true, "res", res, "th", th ).toString(); } }
{ "content_hash": "c80228163b112757a6af507b96edc7ea", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 79, "avg_line_length": 19.28395061728395, "alnum_prop": 0.5492957746478874, "repo_name": "bitgirder/bitgirder-main", "id": "cc2a21b922555e4168cac07bde66cfe8d3d56ab5", "size": "1562", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/java/lib/src/com/bitgirder/lang/AbstractCompletion.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "1182953" }, { "name": "Java", "bytes": "1608793" }, { "name": "JavaScript", "bytes": "11638" }, { "name": "Ruby", "bytes": "342315" } ], "symlink_target": "" }
/** * Created by urielbertoche on 03/07/15. */ 'use strict'; var request = require('request'); var lastModified = new Date(); lastModified.setMinutes(-120); var options = { url: '', headers: { 'User-Agent': 'urielb', 'If-Modified-Since': lastModified.toUTCString() } }; function GitOrg (org) { this.members_url = 'https://api.github.com/orgs/'+org+'/members'; } GitOrg.prototype.getMembers = function(callback) { options.url = this.members_url; // Connect to Github API and returns the same result as an inner API var req = request(options, function (error, response, body) { if (!error && response.statusCode == 200) { callback(body); } }); } module.exports = { GitOrg: GitOrg, methods: { getMembers: function (req, res) { var organization = req.params.organization; var org = new GitOrg(organization); res.writeHead(200, {"Content-Type": "application/json"}); var mocked_json = require('../../../mocks/search-vtex'); //return org.getMembers(res.end.bind(res)); return res.end(JSON.stringify(mocked_json)); } } };
{ "content_hash": "5b7d239d4fddfd31f5448eb937ef094c", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 70, "avg_line_length": 23.1875, "alnum_prop": 0.637915543575921, "repo_name": "urielb/dev-shop", "id": "c205cfce54b64193190c4e9e7d7ac64d73f99b9e", "size": "1113", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/api/git/organization.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2061" }, { "name": "HTML", "bytes": "1685" }, { "name": "JavaScript", "bytes": "26969" } ], "symlink_target": "" }
package fr.bourgmapper.tub.data.repository.datasource; import android.content.Context; import android.support.annotation.NonNull; import javax.inject.Inject; import javax.inject.Singleton; import fr.bourgmapper.tub.data.cache.StopCache; import fr.bourgmapper.tub.data.net.RestApi; import fr.bourgmapper.tub.data.net.RestApiImpl; /** * Factory that creates different implementations of {@link StopDataStore}. */ @Singleton public class StopDataStoreFactory { private final Context context; private final StopCache stopCache; @Inject StopDataStoreFactory(@NonNull Context context, @NonNull StopCache stopCache) { this.context = context.getApplicationContext(); this.stopCache = stopCache; } /** * Create {@link StopDataStore} from a stop stopId. */ public StopDataStore create(long stopId) { StopDataStore stopDataStore; if (!this.stopCache.isExpired() && this.stopCache.isCached(stopId)) { stopDataStore = new DiskStopDataStore(this.stopCache); } else { stopDataStore = createCloudDataStore(); } return stopDataStore; } /** * Create {@link StopDataStore} to retrieve data from the Cloud. */ public StopDataStore createCloudDataStore() { final RestApi restApi = new RestApiImpl(); return new CloudStopDataStore(restApi, this.stopCache); } }
{ "content_hash": "39fed2a055db57728db1564a70a971a0", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 82, "avg_line_length": 27.686274509803923, "alnum_prop": 0.6983002832861189, "repo_name": "axellebot/Tub-Android", "id": "687d0658c20bb555ba25e8dc9934968a875d9565", "size": "1412", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "data/src/main/java/fr/bourgmapper/tub/data/repository/datasource/StopDataStoreFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "164725" } ], "symlink_target": "" }
from dtreeviz.utils import * import numpy as np import pandas as pd import graphviz from pathlib import Path from sklearn import tree from graphviz.backend import run, view import matplotlib.pyplot as plt from dtreeviz.shadow import * from numbers import Number import matplotlib.patches as patches from mpl_toolkits.mplot3d import Axes3D import tempfile from os import getpid, makedirs from sys import platform as PLATFORM from colour import Color YELLOW = "#fefecd" # "#fbfbd0" # "#FBFEB0" GREEN = "#cfe2d4" DARKBLUE = '#313695' BLUE = '#4575b4' DARKGREEN = '#006400' LIGHTORANGE = '#fee090' LIGHTBLUE = '#a6bddb' GREY = '#444443' WEDGE_COLOR = GREY #'orange' HIGHLIGHT_COLOR = '#D67C03' # How many bins should we have based upon number of classes NUM_BINS = [0, 0, 10, 9, 8, 6, 6, 6, 5, 5, 5] # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 color_blind_friendly_colors = [ None, # 0 classes None, # 1 class ["#FEFEBB","#a1dab4"], # 2 classes ["#FEFEBB","#D9E6F5",'#a1dab4'], # 3 classes ["#FEFEBB","#D9E6F5",'#a1dab4','#fee090'], # 4 ["#FEFEBB","#D9E6F5",'#a1dab4','#41b6c4','#fee090'], # 5 ["#FEFEBB",'#c7e9b4','#41b6c4','#2c7fb8','#fee090','#f46d43'], # 6 ["#FEFEBB",'#c7e9b4','#7fcdbb','#41b6c4','#225ea8','#fdae61','#f46d43'], # 7 ["#FEFEBB",'#edf8b1','#c7e9b4','#7fcdbb','#1d91c0','#225ea8','#fdae61','#f46d43'], # 8 ["#FEFEBB",'#c7e9b4','#41b6c4','#74add1','#4575b4','#313695','#fee090','#fdae61','#f46d43'], # 9 ["#FEFEBB",'#c7e9b4','#41b6c4','#74add1','#4575b4','#313695','#fee090','#fdae61','#f46d43','#d73027'] # 10 ] class DTreeViz: def __init__(self,dot): self.dot = dot def _repr_svg_(self): return self.svg() def svg(self): """Render tree as svg and return svg text.""" tmp = tempfile.gettempdir() svgfilename = f"{tmp}/DTreeViz_{getpid()}.svg" self.save(svgfilename) with open(svgfilename, encoding='UTF-8') as f: svg = f.read() return svg def view(self): tmp = tempfile.gettempdir() svgfilename = f"{tmp}/DTreeViz_{getpid()}.svg" self.save(svgfilename) view(svgfilename) def save(self, filename): """ Save the svg of this tree visualization into filename argument. Mac platform can save any file type (.pdf, .png, .svg). Other platforms would fail with errors. See https://github.com/parrt/dtreeviz/issues/4 """ path = Path(filename) if not path.parent.exists: makedirs(path.parent) g = graphviz.Source(self.dot, format='svg') dotfilename = g.save(directory=path.parent.as_posix(), filename=path.stem) if PLATFORM=='darwin': # dot seems broken in terms of fonts if we use -Tsvg. Force users to # brew install graphviz with librsvg (else metrics are off) and # use -Tsvg:cairo which fixes bug and also automatically embeds images format = path.suffix[1:] # ".svg" -> "svg" etc... cmd = ["dot", f"-T{format}:cairo", "-o", filename, dotfilename] # print(' '.join(cmd)) stdout, stderr = run(cmd, capture_output=True, check=True, quiet=False) else: if not filename.endswith(".svg"): raise (Exception(f"{PLATFORM} can only save .svg files: {filename}")) # Gen .svg file from .dot but output .svg has image refs to other files #orig_svgfilename = filename.replace('.svg', '-orig.svg') cmd = ["dot", "-Tsvg", "-o", filename, dotfilename] # print(' '.join(cmd)) stdout, stderr = run(cmd, capture_output=True, check=True, quiet=False) # now merge in referenced SVG images to make all-in-one file with open(filename, encoding='UTF-8') as f: svg = f.read() svg = inline_svg_images(svg) with open(filename, "w", encoding='UTF-8') as f: f.write(svg) def rtreeviz_univar(ax, x_train: (pd.Series, np.ndarray), # 1 vector of X data y_train: (pd.Series, np.ndarray), max_depth, feature_name: str, target_name: str, fontsize: int = 14, show={'title','splits'}): if isinstance(x_train, pd.Series): x_train = x_train.values if isinstance(y_train, pd.Series): y_train = y_train.values y_range = (min(y_train), max(y_train)) # same y axis for all overall_feature_range = (np.min(x_train), np.max(x_train)) t = tree.DecisionTreeRegressor(max_depth=max_depth) t.fit(x_train.reshape(-1,1), y_train) shadow_tree = ShadowDecTree(t, x_train.reshape(-1,1), y_train, feature_names=[feature_name]) splits = [] for node in shadow_tree.internal: splits.append(node.split()) splits = sorted(splits) bins = [overall_feature_range[0]] + splits + [overall_feature_range[1]] means = [] for i in range(len(bins) - 1): left = bins[i] right = bins[i + 1] inrange = y_train[(x_train >= left) & (x_train < right)] means.append(np.mean(inrange)) ax.scatter(x_train, y_train, marker='o', alpha=.4, c=BLUE, edgecolor=GREY, lw=.3) if 'splits' in show: for split in splits: ax.plot([split, split], [*y_range], '--', color='grey', linewidth=.7) prevX = overall_feature_range[0] for i, m in enumerate(means): split = overall_feature_range[1] if i < len(splits): split = splits[i] ax.plot([prevX, split], [m, m], '-', color='#f46d43', linewidth=2) prevX = split ax.tick_params(axis='both', which='major', width=.3, labelcolor=GREY, labelsize=fontsize) if 'title' in show: title = f"Regression tree depth {max_depth}, training $R^2$={t.score(x_train.reshape(-1,1),y_train):.3f}" plt.title(title, fontsize=fontsize, color=GREY) plt.xlabel(feature_name, fontsize=fontsize) plt.ylabel(target_name, fontsize=fontsize) def rtreeviz_bivar_heatmap(ax, X_train, y_train, max_depth, feature_names, fontsize=14, ticks_fontsize=12, show={'title'} ) -> tree.DecisionTreeClassifier: """ Show tesselated 2D feature space for bivariate regression tree. X_train can have lots of features but features lists indexes of 2 features to train tree with. """ if isinstance(X_train,pd.DataFrame): X_train = X_train.values if isinstance(y_train, pd.Series): y_train = y_train.values rt = tree.DecisionTreeRegressor(max_depth=max_depth) rt.fit(X_train, y_train) n_colors_in_map = 100 y_lim = np.min(y_train), np.max(y_train) y_range = y_lim[1] - y_lim[0] color_map = list(str(c) for c in Color("#c7e9b4").range_to(Color("#081d58"), n_colors_in_map)) shadow_tree = ShadowDecTree(rt, X_train, y_train, feature_names=feature_names) tesselation = shadow_tree.tesselation() for node,bbox in tesselation: pred = node.prediction() color = color_map[int(((pred - y_lim[0]) / y_range) * (n_colors_in_map-1))] x = bbox[0] y = bbox[1] w = bbox[2]-bbox[0] h = bbox[3]-bbox[1] rect = patches.Rectangle((x, y), w, h, 0, linewidth=.3, alpha=.5, edgecolor=GREY, facecolor=color) ax.add_patch(rect) colors = [color_map[int(((y-y_lim[0])/y_range)*(n_colors_in_map-1))] for y in y_train] x, y, z = X_train[:,0], X_train[:,1], y_train ax.scatter(x, y, marker='o', alpha=.95, c=colors, edgecolor=GREY, lw=.3) ax.set_xlabel(f"{feature_names[0]}", fontsize=fontsize, fontname="Arial", color=GREY) ax.set_ylabel(f"{feature_names[1]}", fontsize=fontsize, fontname="Arial", color=GREY) ax.tick_params(axis='both', which='major', width=.3, labelcolor=GREY, labelsize=ticks_fontsize) if 'title' in show: accur = rt.score(X_train, y_train) title = f"Regression tree depth {max_depth}, training $R^2$={accur:.3f}" plt.title(title, fontsize=fontsize, color=GREY) return None def rtreeviz_bivar_3D(ax, X_train, y_train, max_depth, feature_names, target_name, fontsize=14, ticks_fontsize=10, azim=0, elev=0, dist=7, show={'title'} ) -> tree.DecisionTreeClassifier: """ Show 3D feature space for bivariate regression tree. X_train can have lots of features but features lists indexes of 2 features to train tree with. """ if isinstance(X_train,pd.DataFrame): X_train = X_train.values if isinstance(y_train, pd.Series): y_train = y_train.values n_colors_in_map = 100 ax.view_init(elev=elev, azim=azim) ax.dist=dist def plane(node, bbox): x = np.linspace(bbox[0], bbox[2], 2) y = np.linspace(bbox[1], bbox[3], 2) xx, yy = np.meshgrid(x, y) z = np.full(xx.shape, node.prediction()) # print(f"{node.prediction()}->{int(((node.prediction()-y_lim[0])/y_range)*(n_colors_in_map-1))}, lim {y_lim}") # print(f"{color_map[int(((node.prediction()-y_lim[0])/y_range)*(n_colors_in_map-1))]}") ax.plot_surface(xx, yy, z, alpha=.85, shade=False, color=color_map[int(((node.prediction()-y_lim[0])/y_range)*(n_colors_in_map-1))], edgecolor=GREY, lw=.3) rt = tree.DecisionTreeRegressor(max_depth=max_depth) rt.fit(X_train, y_train) y_lim = np.min(y_train), np.max(y_train) y_range = y_lim[1] - y_lim[0] color_map = list(str(c) for c in Color("#c7e9b4").range_to(Color("#081d58"), n_colors_in_map)) colors = [color_map[int(((y-y_lim[0])/y_range)*(n_colors_in_map-1))] for y in y_train] shadow_tree = ShadowDecTree(rt, X_train, y_train, feature_names=feature_names) tesselation = shadow_tree.tesselation() for node, bbox in tesselation: plane(node, bbox) x, y, z = X_train[:, 0], X_train[:, 1], y_train ax.scatter(x, y, z, marker='o', alpha=.7, edgecolor=GREY, lw=.3, c=colors) ax.set_xlabel(f"{feature_names[0]}", fontsize=fontsize, fontname="Arial", color=GREY) ax.set_ylabel(f"{feature_names[1]}", fontsize=fontsize, fontname="Arial", color=GREY) ax.set_zlabel(f"{target_name}", fontsize=fontsize, fontname="Arial", color=GREY) ax.tick_params(axis='both', which='major', width=.3, labelcolor=GREY, labelsize=ticks_fontsize) if 'title' in show: accur = rt.score(X_train, y_train) title = f"Regression tree depth {max_depth}, training $R^2$={accur:.3f}" plt.title(title, fontsize=fontsize) return None def ctreeviz_univar(ax, x_train, y_train, max_depth, feature_name, class_names, target_name, fontsize=14, nbins=25, gtype='strip', show={'title','legend','splits'}): if isinstance(x_train, pd.Series): x_train = x_train.values if isinstance(y_train, pd.Series): y_train = y_train.values # ax.set_facecolor('#F9F9F9') ct = tree.DecisionTreeClassifier(max_depth=max_depth) ct.fit(x_train.reshape(-1, 1), y_train) shadow_tree = ShadowDecTree(ct, x_train.reshape(-1, 1), y_train, feature_names=[feature_name], class_names=class_names) n_classes = shadow_tree.nclasses() overall_feature_range = (np.min(x_train), np.max(x_train)) class_values = shadow_tree.unique_target_values color_values = color_blind_friendly_colors[n_classes] colors = {v: color_values[i] for i, v in enumerate(class_values)} X_colors = [colors[cl] for cl in class_values] ax.set_xlabel(f"{feature_name}", fontsize=fontsize, fontname="Arial", color=GREY) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.yaxis.set_visible(False) ax.spines['left'].set_visible(False) ax.spines['bottom'].set_linewidth(.3) r = overall_feature_range[1] - overall_feature_range[0] dot_w = 25 X_hist = [x_train[y_train == cl] for cl in class_values] binwidth = r / nbins if gtype == 'barstacked': hist, bins, barcontainers = ax.hist(X_hist, color=X_colors, align='mid', histtype='barstacked', bins=np.arange(overall_feature_range[0], overall_feature_range[ 1] + binwidth, binwidth), label=class_names) for patch in barcontainers: for rect in patch.patches: rect.set_linewidth(.5) rect.set_edgecolor(GREY) ax.set_xlim(*overall_feature_range) ax.set_xticks(overall_feature_range) ax.set_yticks([0, max([max(h) for h in hist])]) elif gtype == 'strip': # user should pass in short and wide fig sigma = .013 mu = .08 class_step = .08 dot_w = 20 ax.set_ylim(0, mu + n_classes*class_step) for i, bucket in enumerate(X_hist): y_noise = np.random.normal(mu+i*class_step, sigma, size=len(bucket)) ax.scatter(bucket, y_noise, alpha=.7, marker='o', s=dot_w, c=colors[i], edgecolors=GREY, lw=.3) ax.tick_params(axis='both', which='major', width=.3, labelcolor=GREY, labelsize=fontsize) splits = [] for node in shadow_tree.internal: splits.append(node.split()) splits = sorted(splits) bins = [ax.get_xlim()[0]] + splits + [ax.get_xlim()[1]] pred_box_height = .07 * ax.get_ylim()[1] preds = [] for i in range(len(bins) - 1): left = bins[i] right = bins[i + 1] inrange = y_train[(x_train >= left) & (x_train < right)] values, counts = np.unique(inrange, return_counts=True) pred = values[np.argmax(counts)] rect = patches.Rectangle((left, 0), (right - left), pred_box_height, linewidth=.3, edgecolor=GREY, facecolor=colors[pred]) ax.add_patch(rect) preds.append(pred) if 'legend' in show: add_classifier_legend(ax, class_names, class_values, colors, target_name) if 'title' in show: accur = ct.score(x_train.reshape(-1, 1), y_train) title = f"Classifier tree depth {max_depth}, training accuracy={accur*100:.2f}%" plt.title(title, fontsize=fontsize, color=GREY) if 'splits' in show: for split in splits: plt.plot([split, split], [*ax.get_ylim()], '--', color='grey', linewidth=1) def ctreeviz_bivar(ax, X_train, y_train, max_depth, feature_names, class_names, target_name, fontsize=14, show={'title','legend','splits'}): """ Show tesselated 2D feature space for bivariate classification tree. X_train can have lots of features but features lists indexes of 2 features to train tree with. """ if isinstance(X_train,pd.DataFrame): X_train = X_train.values if isinstance(y_train, pd.Series): y_train = y_train.values ct = tree.DecisionTreeClassifier(max_depth=max_depth) ct.fit(X_train, y_train) shadow_tree = ShadowDecTree(ct, X_train, y_train, feature_names=feature_names, class_names=class_names) tesselation = shadow_tree.tesselation() n_classes = shadow_tree.nclasses() class_values = shadow_tree.unique_target_values color_values = color_blind_friendly_colors[n_classes] colors = {v: color_values[i] for i, v in enumerate(class_values)} if 'splits' in show: for node,bbox in tesselation: x = bbox[0] y = bbox[1] w = bbox[2]-bbox[0] h = bbox[3]-bbox[1] rect = patches.Rectangle((x, y), w, h, 0, linewidth=.3, alpha=.4, edgecolor=GREY, facecolor=colors[node.prediction()]) ax.add_patch(rect) dot_w = 25 X_hist = [X_train[y_train == cl] for cl in class_values] for i, h in enumerate(X_hist): ax.scatter(h[:,0], h[:,1], alpha=1, marker='o', s=dot_w, c=colors[i], edgecolors=GREY, lw=.3) ax.set_xlabel(f"{feature_names[0]}", fontsize=fontsize, fontname="Arial", color=GREY) ax.set_ylabel(f"{feature_names[1]}", fontsize=fontsize, fontname="Arial", color=GREY) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_linewidth(.3) if 'legend' in show: add_classifier_legend(ax, class_names, class_values, colors, target_name) if 'title' in show: accur = ct.score(X_train, y_train) title = f"Classifier tree depth {max_depth}, training accuracy={accur*100:.2f}%" plt.title(title, fontsize=fontsize, color=GREY) return None def add_classifier_legend(ax, class_names, class_values, colors, target_name): # add boxes for legend boxes = [] for i, c in enumerate(class_values): box = patches.Rectangle((0, 0), 20, 10, linewidth=.4, edgecolor=GREY, facecolor=colors[c], label=class_names[c]) boxes.append(box) leg = ax.legend(handles=boxes, frameon=True, shadow=False, fancybox=True, title=target_name, handletextpad=.35, borderpad=.8, bbox_to_anchor=(1.0, 1.0), edgecolor=GREY) leg.get_frame().set_linewidth(.5) leg.get_title().set_color(GREY) leg.get_title().set_fontsize(10) leg.get_title().set_fontweight('bold') for text in leg.get_texts(): text.set_color(GREY) text.set_fontsize(10) def dtreeviz(tree_model: (tree.DecisionTreeRegressor, tree.DecisionTreeClassifier), X_train: (pd.DataFrame, np.ndarray), y_train: (pd.Series, np.ndarray), feature_names: List[str], target_name: str, class_names: (Mapping[Number, str], List[str]) = None, # required if classifier precision: int = 2, orientation: ('TD', 'LR') = "TD", show_root_edge_labels: bool = True, show_node_labels: bool = False, fancy: bool = True, histtype: ('bar', 'barstacked', 'strip') = 'barstacked', highlight_path: List[int] = [], X: np.ndarray = None, max_X_features_LR: int = 10, max_X_features_TD: int = 20) \ -> DTreeViz: """ Given a decision tree regressor or classifier, create and return a tree visualization using the graphviz (DOT) language. :param tree_model: A DecisionTreeRegressor or DecisionTreeClassifier that has been fit to X_train, y_train. :param X_train: A data frame or 2-D matrix of feature vectors used to train the model. :param y_train: A pandas Series or 1-D vector with target values or classes. :param feature_names: A list of the feature names. :param target_name: The name of the target variable. :param class_names: [For classifiers] A dictionary or list of strings mapping class value to class name. :param precision: When displaying floating-point numbers, how many digits to display after the decimal point. Default is 2. :param orientation: Is the tree top down, "TD", or left to right, "LR"? :param show_root_edge_labels: Include < and >= on the edges emanating from the root? :param show_node_labels: Add "Node id" to top of each node in graph for educational purposes :param fancy: :param histtype: [For classifiers] Either 'bar' or 'barstacked' to indicate histogram type. We find that 'barstacked' looks great up to about. four classes. :param highlight_path: A list of node IDs to highlight, default is []. Useful for emphasizing node(s) in tree for discussion. If X argument given then this is ignored. :type highlight_path: List[int] :param X: Instance to run down the tree; derived path to highlight from this vector. Show feature vector with labels underneath leaf reached. highlight_path is ignored if X is not None. :type np.ndarray :param max_X_features_LR: If len(X) exceeds this limit for LR layout, display only those features used to guide X vector down tree. Helps when len(X) is large. Default is 10. :param max_X_features_TD: If len(X) exceeds this limit for TD layout, display only those features used to guide X vector down tree. Helps when len(X) is large. Default is 25. :return: A string in graphviz DOT language that describes the decision tree. """ def node_name(node : ShadowDecTreeNode) -> str: return f"node{node.id}" def split_node(name, node_name, split): if fancy: labelgraph = node_label(node) if show_node_labels else '' html = f"""<table border="0"> {labelgraph} <tr> <td><img src="{tmp}/node{node.id}_{getpid()}.svg"/></td> </tr> </table>""" else: html = f"""<font face="Helvetica" color="#444443" point-size="12">{name}@{split}</font>""" if node.id in highlight_path: gr_node = f'{node_name} [margin="0" shape=box penwidth=".5" color="{HIGHLIGHT_COLOR}" style="dashed" label=<{html}>]' else: gr_node = f'{node_name} [margin="0" shape=none label=<{html}>]' return gr_node def regr_leaf_node(node, label_fontsize: int = 12): # always generate fancy regr leaves for now but shrink a bit for nonfancy. labelgraph = node_label(node) if show_node_labels else '' html = f"""<table border="0"> {labelgraph} <tr> <td><img src="{tmp}/leaf{node.id}_{getpid()}.svg"/></td> </tr> </table>""" if node.id in highlight_path: return f'leaf{node.id} [margin="0" shape=box penwidth=".5" color="{HIGHLIGHT_COLOR}" style="dashed" label=<{html}>]' else: return f'leaf{node.id} [margin="0" shape=box penwidth="0" label=<{html}>]' def class_leaf_node(node, label_fontsize: int = 12): labelgraph = node_label(node) if show_node_labels else '' html = f"""<table border="0" CELLBORDER="0"> {labelgraph} <tr> <td><img src="{tmp}/leaf{node.id}_{getpid()}.svg"/></td> </tr> </table>""" if node.id in highlight_path: return f'leaf{node.id} [margin="0" shape=box penwidth=".5" color="{HIGHLIGHT_COLOR}" style="dashed" label=<{html}>]' else: return f'leaf{node.id} [margin="0" shape=box penwidth="0" label=<{html}>]' def node_label(node): return f'<tr><td CELLPADDING="0" CELLSPACING="0"><font face="Helvetica" color="{GREY}" point-size="14"><i>Node {node.id}</i></font></td></tr>' def class_legend_html(): return f""" <table border="0" cellspacing="0" cellpadding="0"> <tr> <td border="0" cellspacing="0" cellpadding="0"><img src="{tmp}/legend_{getpid()}.svg"/></td> </tr> </table> """ def class_legend_gr(): if not shadow_tree.isclassifier(): return "" return f""" subgraph cluster_legend {{ style=invis; legend [penwidth="0" margin="0" shape=box margin="0.03" width=.1, height=.1 label=< {class_legend_html()} >] }} """ def instance_html(path, label_fontsize: int = 11): headers = [] features_used = [node.feature() for node in path[:-1]] # don't include leaf display_X = X display_feature_names = feature_names highlight_feature_indexes = features_used if (orientation=='TD' and len(X)>max_X_features_TD) or\ (orientation == 'LR' and len(X) > max_X_features_LR): # squash all features down to just those used display_X = [X[i] for i in features_used] + ['...'] display_feature_names = [node.feature_name() for node in path[:-1]] + ['...'] highlight_feature_indexes = range(0,len(features_used)) for i,name in enumerate(display_feature_names): color = GREY if i in highlight_feature_indexes: color = HIGHLIGHT_COLOR headers.append(f'<td cellpadding="1" align="right" bgcolor="white"><font face="Helvetica" color="{color}" point-size="{label_fontsize}"><b>{name}</b></font></td>') values = [] for i,v in enumerate(display_X): color = GREY if i in highlight_feature_indexes: color = HIGHLIGHT_COLOR if isinstance(v,int) or isinstance(v, str): disp_v = v else: disp_v = myround(v, precision) values.append(f'<td cellpadding="1" align="right" bgcolor="white"><font face="Helvetica" color="{color}" point-size="{label_fontsize}">{disp_v}</font></td>') return f""" <table border="0" cellspacing="0" cellpadding="0"> <tr> {''.join(headers)} </tr> <tr> {''.join(values)} </tr> </table> """ def instance_gr(): if X is None: return "" pred, path = shadow_tree.predict(X) leaf = f"leaf{path[-1].id}" if shadow_tree.isclassifier(): edge_label = f" Prediction<br/> {path[-1].prediction_name()}" else: edge_label = f" Prediction<br/> {myround(path[-1].prediction(), precision)}" return f""" subgraph cluster_instance {{ style=invis; X_y [penwidth="0.3" margin="0" shape=box margin="0.03" width=.1, height=.1 label=< {instance_html(path)} >] }} {leaf} -> X_y [dir=back; penwidth="1.2" color="{HIGHLIGHT_COLOR}" label=<<font face="Helvetica" color="{GREY}" point-size="{11}">{edge_label}</font>>] """ if orientation=="TD": ranksep = ".2" nodesep = "0.1" else: if fancy: ranksep = ".22" nodesep = "0.1" else: ranksep = ".05" nodesep = "0.09" tmp = tempfile.gettempdir() # tmp = "/tmp" shadow_tree = ShadowDecTree(tree_model, X_train, y_train, feature_names=feature_names, class_names=class_names) if X is not None: pred, path = shadow_tree.predict(X) highlight_path = [n.id for n in path] n_classes = shadow_tree.nclasses() color_values = color_blind_friendly_colors[n_classes] # Fix the mapping from target value to color for entire tree colors = None if shadow_tree.isclassifier(): class_values = shadow_tree.unique_target_values colors = {v:color_values[i] for i,v in enumerate(class_values)} y_range = (min(y_train)*1.03, max(y_train)*1.03) # same y axis for all if shadow_tree.isclassifier(): # draw_legend_boxes(shadow_tree, f"{tmp}/legend") draw_legend(shadow_tree, target_name, f"{tmp}/legend_{getpid()}.svg") if isinstance(X_train,pd.DataFrame): X_train = X_train.values if isinstance(y_train,pd.Series): y_train = y_train.values # Find max height (count) for any bar in any node if shadow_tree.isclassifier(): nbins = get_num_bins(histtype, n_classes) node_heights = shadow_tree.get_split_node_heights(X_train, y_train, nbins=nbins) internal = [] for node in shadow_tree.internal: if fancy: if shadow_tree.isclassifier(): class_split_viz(node, X_train, y_train, filename=f"{tmp}/node{node.id}_{getpid()}.svg", precision=precision, colors=colors, histtype=histtype, node_heights=node_heights, X = X, highlight_node=node.id in highlight_path) else: regr_split_viz(node, X_train, y_train, filename=f"{tmp}/node{node.id}_{getpid()}.svg", target_name=target_name, y_range=y_range, precision=precision, X=X, highlight_node=node.id in highlight_path) nname = node_name(node) gr_node = split_node(node.feature_name(), nname, split=myround(node.split(), precision)) internal.append(gr_node) leaves = [] for node in shadow_tree.leaves: if shadow_tree.isclassifier(): class_leaf_viz(node, colors=color_values, filename=f"{tmp}/leaf{node.id}_{getpid()}.svg") leaves.append( class_leaf_node(node) ) else: # for now, always gen leaf regr_leaf_viz(node, y_train, target_name=target_name, filename=f"{tmp}/leaf{node.id}_{getpid()}.svg", y_range=y_range, precision=precision) leaves.append( regr_leaf_node(node) ) show_edge_labels = False all_llabel = '&lt;' if show_edge_labels else '' all_rlabel = '&ge;' if show_edge_labels else '' root_llabel = '&lt;' if show_root_edge_labels else '' root_rlabel = '&ge;' if show_root_edge_labels else '' edges = [] # non leaf edges with > and <= for node in shadow_tree.internal: nname = node_name(node) if node.left.isleaf(): left_node_name ='leaf%d' % node.left.id else: left_node_name = node_name(node.left) if node.right.isleaf(): right_node_name ='leaf%d' % node.right.id else: right_node_name = node_name(node.right) llabel = all_llabel rlabel = all_rlabel if node==shadow_tree.root: llabel = root_llabel rlabel = root_rlabel lcolor = rcolor = GREY lpw = rpw = "0.3" if node.left.id in highlight_path: lcolor = HIGHLIGHT_COLOR lpw = "1.2" if node.right.id in highlight_path: rcolor = HIGHLIGHT_COLOR rpw = "1.2" edges.append( f'{nname} -> {left_node_name} [penwidth={lpw} color="{lcolor}" label=<{llabel}>]' ) edges.append( f'{nname} -> {right_node_name} [penwidth={rpw} color="{rcolor}" label=<{rlabel}>]' ) edges.append(f""" {{ rank=same; {left_node_name} -> {right_node_name} [style=invis] }} """) newline = "\n\t" dot = f""" digraph G {{ splines=line; nodesep={nodesep}; ranksep={ranksep}; rankdir={orientation}; margin=0.0; node [margin="0.03" penwidth="0.5" width=.1, height=.1]; edge [arrowsize=.4 penwidth="0.3"] {newline.join(internal)} {newline.join(edges)} {newline.join(leaves)} {class_legend_gr()} {instance_gr()} }} """ return DTreeViz(dot) def class_split_viz(node: ShadowDecTreeNode, X_train: np.ndarray, y_train: np.ndarray, colors: Mapping[int, str], node_heights, filename: str = None, ticks_fontsize: int = 8, label_fontsize: int = 9, precision=1, histtype: ('bar', 'barstacked', 'strip') = 'barstacked', X : np.array = None, highlight_node : bool = False ): height_range = (.5, 1.5) h = prop_size(n=node_heights[node.id], counts=node_heights.values(), output_range=height_range) figsize=(3.3, h) fig, ax = plt.subplots(1, 1, figsize=figsize) feature_name = node.feature_name() # Get X, y data for all samples associated with this node. X_feature = X_train[:, node.feature()] X_feature, y_train = X_feature[node.samples()], y_train[node.samples()] n_classes = node.shadow_tree.nclasses() nbins = get_num_bins(histtype, n_classes) overall_feature_range = (np.min(X_train[:, node.feature()]), np.max(X_train[:, node.feature()])) overall_feature_range_wide = (overall_feature_range[0]-overall_feature_range[0]*.08, overall_feature_range[1]+overall_feature_range[1]*.05) ax.set_xlabel(f"{feature_name}", fontsize=label_fontsize, fontname="Arial", color=GREY) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_linewidth(.3) ax.spines['bottom'].set_linewidth(.3) class_names = node.shadow_tree.class_names r = overall_feature_range[1]-overall_feature_range[0] class_values = node.shadow_tree.unique_target_values X_hist = [X_feature[y_train == cl] for cl in class_values] if histtype=='strip': ax.yaxis.set_visible(False) ax.spines['left'].set_visible(False) sigma = .013 mu = .05 class_step = .08 dot_w = 20 ax.set_ylim(0, mu + n_classes * class_step) for i, bucket in enumerate(X_hist): alpha = .6 if len(bucket) > 10 else 1 y_noise = np.random.normal(mu + i * class_step, sigma, size=len(bucket)) ax.scatter(bucket, y_noise, alpha=alpha, marker='o', s=dot_w, c=colors[i], edgecolors=GREY, lw=.3) else: X_colors = [colors[cl] for cl in class_values] binwidth = r / nbins hist, bins, barcontainers = ax.hist(X_hist, color=X_colors, align='mid', histtype=histtype, bins=np.arange(overall_feature_range[0],overall_feature_range[1] + binwidth, binwidth), label=class_names) # Alter appearance of each bar for patch in barcontainers: for rect in patch.patches: rect.set_linewidth(.5) rect.set_edgecolor(GREY) ax.set_yticks([0,max([max(h) for h in hist])]) ax.set_xlim(*overall_feature_range_wide) ax.set_xticks(overall_feature_range) ax.tick_params(axis='both', which='major', width=.3, labelcolor=GREY, labelsize=ticks_fontsize) def wedge(ax,x,color): xmin, xmax = ax.get_xlim() ymin, ymax = ax.get_ylim() xr = xmax - xmin yr = ymax - ymin hr = h / (height_range[1] - height_range[0]) th = yr * .15 * 1 / hr # convert to graph coordinates (ugh) tw = xr * .018 tipy = -0.1 * yr * .15 * 1 / hr tria = np.array( [[x, tipy], [x - tw, -th], [x + tw, -th]]) t = patches.Polygon(tria, facecolor=color) t.set_clip_on(False) ax.add_patch(t) ax.text(node.split(), -2 * th, f"{myround(node.split(),precision)}", horizontalalignment='center', fontsize=ticks_fontsize, color=GREY) wedge(ax, node.split(), color=WEDGE_COLOR) if highlight_node: wedge(ax, X[node.feature()], color=HIGHLIGHT_COLOR) if filename is not None: plt.savefig(filename, bbox_inches='tight', pad_inches=0) plt.close() def class_leaf_viz(node : ShadowDecTreeNode, colors : List[str], filename: str): size = prop_size(node.nsamples(), counts=node.shadow_tree.leaf_sample_counts(), output_range=(1.01, 1.5)) # we visually need n=1 and n=9 to appear different but diff between 300 and 400 is no big deal size = np.sqrt(np.log(size)) counts = node.class_counts() draw_piechart(counts, size=size, colors=colors, filename=filename, label=f"n={node.nsamples()}") def regr_split_viz(node: ShadowDecTreeNode, X_train: np.ndarray, y_train: np.ndarray, target_name: str, filename: str = None, y_range=None, ticks_fontsize: int = 8, label_fontsize: int = 9, precision=1, X : np.array = None, highlight_node : bool = False): figsize = (2.5, 1.1) fig, ax = plt.subplots(1, 1, figsize=figsize) ax.tick_params(colors=GREY) feature_name = node.feature_name() ax.set_xlabel(f"{feature_name}", fontsize=label_fontsize, fontname="Arial", color=GREY) ax.set_ylim(y_range) if node==node.shadow_tree.root: ax.set_ylabel(target_name, fontsize=label_fontsize, fontname="Arial", color=GREY) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_linewidth(.3) ax.spines['bottom'].set_linewidth(.3) ax.tick_params(axis='both', which='major', width=.3, labelcolor=GREY, labelsize=ticks_fontsize) # Get X, y data for all samples associated with this node. X_feature = X_train[:,node.feature()] X_feature, y_train = X_feature[node.samples()], y_train[node.samples()] overall_feature_range = (np.min(X_train[:,node.feature()]), np.max(X_train[:,node.feature()])) ax.set_xlim(*overall_feature_range) xmin, xmax = overall_feature_range xr = xmax - xmin xticks = list(overall_feature_range) if node.split()>xmin+.10*xr and node.split()<xmax-.1*xr: # don't show split if too close to axis ends xticks += [node.split()] ax.set_xticks(xticks) ax.scatter(X_feature, y_train, s=5, c=BLUE, alpha=.4, lw=.3) left, right = node.split_samples() left = y_train[left] right = y_train[right] split = node.split() ax.plot([overall_feature_range[0],split],[np.mean(left),np.mean(left)],'--', color='k', linewidth=1) ax.plot([split,split],[*y_range],'--', color='k', linewidth=1) ax.plot([split,overall_feature_range[1]],[np.mean(right),np.mean(right)],'--', color='k', linewidth=1) def wedge(ax,x,color): ymin, ymax = ax.get_ylim() xr = xmax - xmin yr = ymax - ymin hr = figsize[1] th = yr * .1 tw = xr * .018 tipy = ymin tria = np.array([[x, tipy], [x - tw, ymin-th], [x + tw, ymin-th]]) t = patches.Polygon(tria, facecolor=color) t.set_clip_on(False) ax.add_patch(t) wedge(ax, node.split(), color=WEDGE_COLOR) if highlight_node: wedge(ax, X[node.feature()], color=HIGHLIGHT_COLOR) plt.tight_layout() if filename is not None: plt.savefig(filename, bbox_inches='tight', pad_inches=0) plt.close() def regr_leaf_viz(node : ShadowDecTreeNode, y : (pd.Series,np.ndarray), target_name, filename:str=None, y_range=None, precision=1, label_fontsize: int = 9, ticks_fontsize: int = 8): samples = node.samples() y = y[samples] figsize = (.75, .8) fig, ax = plt.subplots(1, 1, figsize=figsize) ax.tick_params(colors=GREY) m = np.mean(y) ax.set_ylim(y_range) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_linewidth(.3) ax.set_xticks([]) # ax.set_yticks(y_range) ticklabelpad = plt.rcParams['xtick.major.pad'] ax.annotate(f"{target_name}={myround(m,precision)}\nn={len(y)}", xy=(.5, 0), xytext=(.5, -.5*ticklabelpad), ha='center', va='top', xycoords='axes fraction', textcoords='offset points', fontsize = label_fontsize, fontname = "Arial", color = GREY) ax.tick_params(axis='y', which='major', width=.3, labelcolor=GREY, labelsize=ticks_fontsize) mu = .5 sigma = .08 X = np.random.normal(mu, sigma, size=len(y)) ax.set_xlim(0, 1) alpha = .25 ax.scatter(X, y, s=5, c='#225ea8', alpha=alpha, lw=.3) ax.plot([0,len(node.samples())],[m,m],'--', color=GREY, linewidth=1) plt.tight_layout() if filename is not None: plt.savefig(filename, bbox_inches='tight', pad_inches=0) plt.close() def draw_legend(shadow_tree, target_name, filename): n_classes = shadow_tree.nclasses() class_values = shadow_tree.unique_target_values class_names = shadow_tree.class_names color_values = color_blind_friendly_colors[n_classes] colors = {v:color_values[i] for i,v in enumerate(class_values)} boxes = [] for i, c in enumerate(class_values): box = patches.Rectangle((0, 0), 20, 10, linewidth=.4, edgecolor=GREY, facecolor=colors[c], label=class_names[c]) boxes.append(box) fig, ax = plt.subplots(1, 1, figsize=(1,1)) leg = ax.legend(handles=boxes, frameon=True, shadow=False, fancybox=True, loc='center', title=target_name, handletextpad=.35, borderpad=.8, edgecolor=GREY) leg.get_frame().set_linewidth(.5) leg.get_title().set_color(GREY) leg.get_title().set_fontsize(10) leg.get_title().set_fontweight('bold') for text in leg.get_texts(): text.set_color(GREY) text.set_fontsize(10) ax.set_xlim(0,20) ax.set_ylim(0,10) ax.axis('off') ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) if filename is not None: plt.savefig(filename, bbox_inches='tight', pad_inches=0) plt.close() def draw_piechart(counts,size,colors,filename,label=None): n_nonzero = np.count_nonzero(counts) i = np.nonzero(counts)[0][0] if n_nonzero==1: counts = [counts[i]] colors = [colors[i]] tweak = size * .01 fig, ax = plt.subplots(1, 1, figsize=(size, size)) ax.axis('equal') # ax.set_xlim(0 - tweak, size + tweak) # ax.set_ylim(0 - tweak, size + tweak) ax.set_xlim(0, size-10*tweak) ax.set_ylim(0, size-10*tweak) # frame=True needed for some reason to fit pie properly (ugh) # had to tweak the crap out of this to get tight box around piechart :( wedges, _ = ax.pie(counts, center=(size/2-6*tweak,size/2-6*tweak), radius=size/2, colors=colors, shadow=False, frame=True) for w in wedges: w.set_linewidth(.5) w.set_edgecolor(GREY) ax.axis('off') ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) if label is not None: ax.text(size/2-6*tweak, -10*tweak, label, horizontalalignment='center', verticalalignment='top', fontsize=9, color=GREY, fontname="Arial") # plt.tight_layout() plt.savefig(filename, bbox_inches='tight', pad_inches=0) plt.close() def prop_size(n, counts, output_range = (0.00, 0.3)): min_samples = min(counts) max_samples = max(counts) sample_count_range = max_samples - min_samples if sample_count_range>0: zero_to_one = (n - min_samples) / sample_count_range return zero_to_one * (output_range[1] - output_range[0]) + output_range[0] else: return output_range[0] def get_num_bins(histtype, n_classes): bins = NUM_BINS[n_classes] if histtype == 'barstacked': bins *= 2 return bins global dot_already_tested if dot_already_tested: return dot_already_tested = True tmp = tempfile.gettempdir() dotfilename = f"{tmp}/testing_svg_{getpid()}.dot" with open(dotfilename, "w") as f: f.write("digraph G { A -> B }\n") svgfilename = f"{tmp}/testing_svg_{getpid()}.svg" cmd = ["dot", "-Tsvg:cairo", "-o", svgfilename, dotfilename] print(' '.join(cmd)) ok = True try: os.execlp("dot", "dot", "-Tsvg:cairo", "-o", svgfilename, dotfilename) # run(cmd, capture_output=False, check=False, quiet=True) except: ok = False return ok
{ "content_hash": "0444097d6cd37a66719732c993eb0e47", "timestamp": "", "source": "github", "line_count": 1167, "max_line_length": 175, "avg_line_length": 38.54070265638389, "alnum_prop": 0.5619094203704116, "repo_name": "parrt/AniML", "id": "bf925007fbf715facf431890c125a1b499e23ac4", "size": "44977", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dtreeviz/trees.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "135146" }, { "name": "Kotlin", "bytes": "38472" }, { "name": "Python", "bytes": "15012" } ], "symlink_target": "" }
<?php namespace Symfony\Component\Validator\Tests\Constraints; use PHPUnit\Framework\TestCase; use Symfony\Component\Validator\Constraints\PositiveOrZero; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Mapping\Loader\AnnotationLoader; /** * @requires PHP 8 */ class PositiveOrZeroTest extends TestCase { public function testAttributes() { $metadata = new ClassMetadata(PositiveOrZeroDummy::class); $loader = new AnnotationLoader(); self::assertTrue($loader->loadClassMetadata($metadata)); [$aConstraint] = $metadata->properties['a']->getConstraints(); self::assertSame(0, $aConstraint->value); self::assertNull($aConstraint->propertyPath); self::assertSame(['Default', 'PositiveOrZeroDummy'], $aConstraint->groups); [$bConstraint] = $metadata->properties['b']->getConstraints(); self::assertSame('myMessage', $bConstraint->message); self::assertSame(['foo'], $bConstraint->groups); } } class PositiveOrZeroDummy { #[PositiveOrZero] private $a; #[PositiveOrZero(message: 'myMessage', groups: ['foo'])] private $b; }
{ "content_hash": "b9637d45100acfed89b53391ac858772", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 83, "avg_line_length": 28.634146341463413, "alnum_prop": 0.6942078364565588, "repo_name": "MatTheCat/symfony", "id": "520366eb5eca40f844653f5476810cda4e0960b4", "size": "1403", "binary": false, "copies": "7", "ref": "refs/heads/5.x", "path": "src/Symfony/Component/Validator/Tests/Constraints/PositiveOrZeroTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "49627" }, { "name": "HTML", "bytes": "16735" }, { "name": "Hack", "bytes": "26" }, { "name": "JavaScript", "bytes": "27689" }, { "name": "PHP", "bytes": "37422081" }, { "name": "Shell", "bytes": "3153" }, { "name": "Twig", "bytes": "382292" } ], "symlink_target": "" }
<?php /** * Upgrades logger constants. * * @package symfony * @subpackage task * @author Fabien Potencier <fabien.potencier@symfony-project.com> * @version SVN: $Id$ */ class sfLoggerUpgrade extends sfUpgrade { public function upgrade() { $phpFinder = $this->getFinder('file')->name('*.php'); foreach ($phpFinder->in($this->getProjectClassDirectories()) as $file) { $content = file_get_contents($file); $content = preg_replace('/SF_LOG_([A-Z]+)/', 'sfLogger::$1', $content, -1, $count); if ($count) { $this->logSection('logger', sprintf('Migrating %s', $file)); file_put_contents($file, $content); } } } }
{ "content_hash": "493baaac8ac68aba5625d8fca6c93030", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 89, "avg_line_length": 23.166666666666668, "alnum_prop": 0.5899280575539568, "repo_name": "ahoy-jon/symfony-1.2", "id": "3f4b7c14306411d5dc60c62d82404575143cc4ab", "size": "940", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "lib/task/project/upgrade1.1/sfLoggerUpgrade.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "222212" }, { "name": "PHP", "bytes": "6916325" }, { "name": "Shell", "bytes": "7584" } ], "symlink_target": "" }
<?php namespace Ai\GalleryBundle\EventListener; use Ai\GalleryBundle\Entity\Image; use Ai\GalleryBundle\Services\ImageManager; use Doctrine\ORM\Event\LifecycleEventArgs; class ImageListener { private $imageManager; /** * @param ImageManager $imageManager */ public function __construct(ImageManager $imageManager) { $this->imageManager = $imageManager; } /** * @param LifecycleEventArgs $args */ public function postPersist(LifecycleEventArgs $args) { $entity = $args->getObject(); if ($entity instanceof Image) { $this->uploadImage($entity); } } /** * @param LifecycleEventArgs $args */ public function postUpdate(LifecycleEventArgs $args) { $entity = $args->getObject(); if ($entity instanceof Image) { $this->uploadImage($entity); } } /** * @param LifecycleEventArgs $args */ public function postRemove(LifecycleEventArgs $args) { $entity = $args->getEntity(); if($entity instanceof Image) { //Remove image file $this->imageManager->removeFile(ImageManager::TYPE_IMAGE, $entity->getImage()); } } /** * Upload album image file * * @param Image $image */ protected function uploadImage(Image $image) { //Upload album icon from orphanage $this->imageManager->orphanageUploads(ImageManager::TYPE_IMAGE, $image->getImage()); } }
{ "content_hash": "d57c35d47a9f08b95701d5c8a7b8d35b", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 92, "avg_line_length": 22.426470588235293, "alnum_prop": 0.600655737704918, "repo_name": "ruslana-net/ai-gallery", "id": "668aa27d6758c232ade8edd8811f97c379f38943", "size": "1525", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Ai/GalleryBundle/EventListener/ImageListener.php", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
[![Gem Version](https://badge.fury.io/rb/reactive_support.svg)](http://badge.fury.io/rb/reactive_support) [![Build Status](https://travis-ci.org/danascheider/reactive_support.svg?branch=master)](https://travis-ci.org/danascheider/reactive_support) [![Coverage Status](https://img.shields.io/coveralls/danascheider/reactive_support.svg)](https://coveralls.io/r/danascheider/reactive_support) [![Code Climate](https://codeclimate.com/github/danascheider/reactive_support/badges/gpa.svg)](https://codeclimate.com/github/danascheider/reactive_support) [![Inline docs](http://inch-ci.org/github/danascheider/reactive_support.svg?branch=master)](http://inch-ci.org/github/danascheider/reactive_support) The ReactiveSupport gem provides a re-implementation of certain [ActiveSupport](https://github.com/rails/activesupport) methods, allowing them to be used outside of the Rails ecosystem. This gem can be used in any kind of project and is not dependent on any frameworks, gemsets, etc. To add ReactiveSupport to your project, add this to your Gemfile and run `bundle install`: <pre><code>gem 'reactive_support', '~> 0.5.0'</code></pre> To install locally: <pre><code>sudo gem install reactive_support</code></pre> Or if you're using RVM: <pre><code>gem install reactive_support</code></pre> You can also point your Gemfile to this repo: <pre><code>gem 'reactive_support', '~> 0.5.0.beta', git: 'https://github.com/danascheider/reactive_support.git</code></pre> Like ActiveSupport, ReactiveSupport is designed to load only the code you are actually using in your app. For that reason, you will need to specify in your project files exactly what you're using. For example, in Canto, I have the following requires: <pre><code>require 'reactive_support/core_ext/object/blank' require 'reactive_support/core_ext/object/inclusion' require 'reactive_support/core_ext/object/try'</code></pre> I do have plans to add the ability to require the entire gem, or broader parts of it, in the future. This would also be a welcome contribution to the project if you're interested. Please note that version 0.1.2 is the earliest available version of ReactiveSupport. ### Usage In its current version, ReactiveSupport adds methods to several core Ruby classes (including `Object`), so once required, its methods can be used on any object within your project. Currently, ReactiveSupport's methods are a strict subset of ActiveSupport's. (This may change in future versions, or most saliently, if ActiveSupport's API changes.) That means that, while not all ActiveSupport methods are available, those that are can, as of September 2014, be found in ActiveSupport's API documentation with no functional differences. (This is true of ReactiveSupport 0.1.x and ActiveSupport 4.1.6.) ### FAQ ##### Why not just use ActiveSupport? There are three main reasons why you might prefer ReactiveSupport over ActiveSupport: 1. Stability: ReactiveSupport is intended to work independently of Rails' rapidly changing ecosystem. ReactiveSupport methods are guaranteed not to be transferred to other Rails modules or refactored out. While ActiveSupport may be used independently of Rails, its developers are still primarily focused on its place within Rails. ReactiveSupport solves that problem. 2. Simplicity: ReactiveSupport can be added to other projects without additional abstraction layers, and it has no dependencies outside the development and test groups. You don't have to worry about configuration, compatibility with other gems*, or conflicting dependencies. 3. Transparency: Rails is an enormous gem, and gets larger and more complex with each major version. It is also opinionated, facilitating some development approaches while making others inordinately difficult. ReactiveSupport is not large or complicated. Any developer can read the documentation, or even the code itself, and know exactly what he or she is dealing with. \* I would not recommend using it in conjunction with ActiveSupport, though. ##### This doesn't have very many methods. What gives? ReactiveSupport is a spinoff from my other project, [Canto](https://github.com/danascheider/canto). Consequently, the methods it includes are primarily those that I have found a use for in Canto. As Canto grows, and as I have time, I will add more of ActiveSupport's numerous useful methods to ReactiveSupport. In the meantime, I welcome contributions and will respond quickly to pull requests. ##### Is ReactiveSupport being maintained? Yes. Since stability is one of the main advantages of ReactiveSupport, I will be taking an "if it ain't broke, don't fix it" approach to maintaining it. An absence of recent contributions should not be taken to mean it has fallen off my radar. ##### Can I use ReactiveSupport in a Sinatra project/Puppet module/system utility/etc.? Yes. ReactiveSupport is agnostic to the characteristics of your app, and there is no reason it cannot be used in any app where you feel it will be useful. ##### What versions of Ruby are supported? ReactiveSupport version 0.1 supports Ruby versions >= 1.9.3. Additional Rubies may be supported in the future. Adding such support would be a welcome contribution to the project. ### Contributing Contributions are welcome and I will respond promptly to all issue reports and pull requests. Here are some guidelines to get started; I also encourage you to read the full CONTRIBUTING.md file to ensure your pull request will be accepted as is: * Include passing RSpec tests with your pull request. I aim for 100% test coverage. * Run the whole test suite before you make your PR. Make sure your changes don't break the rest of the gem. * Make sure your changes are consistent with the functionality of ActiveSupport. Users should be able to learn about a ReactiveSupport method by reading the ActiveSupport docs for the corresponding ActiveSupport method. * Don't add any new dependencies to ReactiveSupport, or methods that are specific to a particular framework, gemset, or type of app. * Include documentation. ReactiveSupport uses [Inch CI](http://inch-ci.org) to evaluate the quality of documentation. Please help make it easy for others to use and contribute to this project. * Keep ReactiveSupport principles - stability, simplicity, and transparency - in mind. Ideally, contributions should uphold these principles while expanding or enhancing functionality. ### Resources * The [Rails guides](http://guides.rubyonrails.org/active_support_core_extensions.html) on ActiveRecord give information about each of ReactiveSupport's methods. * Those interested in contributing to ReactiveSupport are encouraged read up on [Travis CI](http://travis-ci.org), [Coveralls](http://coveralls.io), [CodeClimate](http://codeclimate.com), and [Inch CI](http://inch-ci.org). * Check out ReactiveSupport at [Rubygems.org](http://rubygems.org/gems/reactive_support)!
{ "content_hash": "fa5fb6ea366bf45555d4f70bb15b2d50", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 696, "avg_line_length": 67.99029126213593, "alnum_prop": 0.7759531629301728, "repo_name": "danascheider/reactive_support", "id": "6e64d7ff12c0e96666a295b434a8849a38005852", "size": "7023", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "40528" } ], "symlink_target": "" }
Public Class frmTemp Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click Dim dblTempF, dblTempC As Double If IsNumeric(txtTempF.Text) Then dblTempF = CDbl(txtTempF.Text) dblTempC = Math.Round(FtoC(dblTempF), 2) txtTempC.Text = CStr(dblTempC) + " " + Chr(176) + "C" Else MessageBox.Show("Invalid Temperature", "ERROR") End If End Sub Function FtoC(temp As Double) As Double Return (5 / 9) * (temp - 32) End Function End Class
{ "content_hash": "02aea4bc1a5f14d8ad05b6bf42337164", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 91, "avg_line_length": 31.61111111111111, "alnum_prop": 0.6098418277680141, "repo_name": "patkub/visual-basic-intro", "id": "27a84688f77cf0bc0d0e51d63191f306c9fe130e", "size": "571", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Temperature/Temperature/frmTemp.vb", "mode": "33188", "license": "mit", "language": [ { "name": "Visual Basic", "bytes": "373539" } ], "symlink_target": "" }
package org.apache.flink.table.runtime.join import org.apache.flink.api.common.state._ import org.apache.flink.api.common.typeinfo.TypeInformation import org.apache.flink.api.java.tuple.{Tuple2 => JTuple2} import org.apache.flink.configuration.Configuration import org.apache.flink.table.api.StreamQueryConfig import org.apache.flink.table.runtime.types.CRow import org.apache.flink.types.Row import org.apache.flink.util.Collector /** * Connect data for left stream and right stream. Base class for stream non-window outer Join. * * @param leftType the input type of left stream * @param rightType the input type of right stream * @param genJoinFuncName the function code of other non-equi condition * @param genJoinFuncCode the function name of other non-equi condition * @param isLeftJoin the type of join, whether it is the type of left join * @param queryConfig the configuration for the query to generate */ abstract class NonWindowOuterJoin( leftType: TypeInformation[Row], rightType: TypeInformation[Row], genJoinFuncName: String, genJoinFuncCode: String, isLeftJoin: Boolean, queryConfig: StreamQueryConfig) extends NonWindowJoin( leftType, rightType, genJoinFuncName, genJoinFuncCode, queryConfig) { // result row, all fields from right will be null. Used for output when there is no matched rows. protected var leftResultRow: Row = _ // result row, all fields from left will be null. Used for output when there is no matched rows. protected var rightResultRow: Row = _ override def open(parameters: Configuration): Unit = { super.open(parameters) val arity = leftType.getArity + rightType.getArity leftResultRow = new Row(arity) rightResultRow = new Row(arity) LOG.debug(s"Instantiating NonWindowOuterJoin") } /** * Join current row with other side rows. Preserve current row if there are no matched rows * from other side. The RowWrapper has been reset before we call preservedJoin and we also * assume that the current change of cRowWrapper is equal to value.change. * * @param inputRow the input row * @param inputRowFromLeft the flag indicat whether input row is from left * @param otherSideState the other side state * @return the number of matched rows */ def preservedJoin( inputRow: Row, inputRowFromLeft: Boolean, otherSideState: MapState[Row, JTuple2[Long, Long]]): Long = { val otherSideIterator = otherSideState.iterator() while (otherSideIterator.hasNext) { val otherSideEntry = otherSideIterator.next() val otherSideRow = otherSideEntry.getKey val otherSideCntAndExpiredTime = otherSideEntry.getValue // join cRowWrapper.setTimes(otherSideCntAndExpiredTime.f0) callJoinFunction(inputRow, inputRowFromLeft, otherSideRow, cRowWrapper) // clear expired data. Note: clear after join to keep closer to the original semantics if (stateCleaningEnabled && curProcessTime >= otherSideCntAndExpiredTime.f1) { otherSideIterator.remove() } } val joinCnt = cRowWrapper.getEmitCnt // The result is NULL from the other side, if there is no match. if (joinCnt == 0) { cRowWrapper.setTimes(1) collectAppendNull(inputRow, inputRowFromLeft, cRowWrapper) } joinCnt } /** * Join current row with other side rows. Retract previous output row if matched condition * changed, i.e, matched condition is changed from matched to unmatched or vice versa. The * RowWrapper has been reset before we call retractJoin and we also assume that the current * change of cRowWrapper is equal to value.change. */ def retractJoin( value: CRow, inputRowFromLeft: Boolean, currentSideState: MapState[Row, JTuple2[Long, Long]], otherSideState: MapState[Row, JTuple2[Long, Long]]): Unit = { val inputRow = value.row val otherSideIterator = otherSideState.iterator() // approximate number of record in current side. We only check whether number equals to 0, 1 // or bigger val recordNum: Long = approxiRecordNumInState(currentSideState) while (otherSideIterator.hasNext) { val otherSideEntry = otherSideIterator.next() val otherSideRow = otherSideEntry.getKey val otherSideCntAndExpiredTime = otherSideEntry.getValue cRowWrapper.setTimes(otherSideCntAndExpiredTime.f0) // retract previous preserved record append with null if (recordNum == 1 && value.change) { cRowWrapper.setChange(false) collectAppendNull(otherSideRow, !inputRowFromLeft, cRowWrapper) // recover for the next iteration cRowWrapper.setChange(true) } // do normal join callJoinFunction(inputRow, inputRowFromLeft, otherSideRow, cRowWrapper) // output preserved record append with null if have to if (!value.change && recordNum == 0) { cRowWrapper.setChange(true) collectAppendNull(otherSideRow, !inputRowFromLeft, cRowWrapper) // recover for the next iteration cRowWrapper.setChange(false) } // clear expired data. Note: clear after join to keep closer to the original semantics if (stateCleaningEnabled && curProcessTime >= otherSideCntAndExpiredTime.f1) { otherSideIterator.remove() } } } /** * Return approximate number of records in corresponding state. Only check if record number is * 0, 1 or bigger. */ def approxiRecordNumInState(currentSideState: MapState[Row, JTuple2[Long, Long]]): Long = { var recordNum = 0L val it = currentSideState.iterator() while(it.hasNext && recordNum < 2) { recordNum += it.next().getValue.f0 } recordNum } /** * Append input row with default null value if there is no match and Collect. */ def collectAppendNull( inputRow: Row, inputFromLeft: Boolean, out: Collector[Row]): Unit = { var i = 0 if (inputFromLeft) { while (i < inputRow.getArity) { leftResultRow.setField(i, inputRow.getField(i)) i += 1 } out.collect(leftResultRow) } else { while (i < inputRow.getArity) { val idx = rightResultRow.getArity - inputRow.getArity + i rightResultRow.setField(idx, inputRow.getField(i)) i += 1 } out.collect(rightResultRow) } } }
{ "content_hash": "2cef53e6b6edd1549130b937bd596482", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 99, "avg_line_length": 37.36046511627907, "alnum_prop": 0.7002801120448179, "repo_name": "mylog00/flink", "id": "0018a16bc23ac90a5a43f1b82c46afb44aa5a3af", "size": "7231", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flink-libraries/flink-table/src/main/scala/org/apache/flink/table/runtime/join/NonWindowOuterJoin.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5666" }, { "name": "CSS", "bytes": "18100" }, { "name": "Clojure", "bytes": "81015" }, { "name": "CoffeeScript", "bytes": "91220" }, { "name": "Dockerfile", "bytes": "9788" }, { "name": "HTML", "bytes": "86821" }, { "name": "Java", "bytes": "40279802" }, { "name": "JavaScript", "bytes": "8267" }, { "name": "Python", "bytes": "249644" }, { "name": "Scala", "bytes": "7501313" }, { "name": "Shell", "bytes": "391588" } ], "symlink_target": "" }
package com.googlecode.objectify.cache; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * <p> * A Future<?> wrapper that executes an abstract method with the result at some point after * the data becomes available. A "best effort" is made to ensure execution, but it may be * left untriggered until the end of a request. * </p> * * <p> * Notification will happen ONCE: * </p> * * <ul> * <li>After get() is called</li> * <li>When the future is done and isDone() is called</li> * <li>At the end of a request that has the AsyncCacheFilter enabled.</li> * </ul> * * <p>Use the AsyncCacheFilter for normal requests. For situations where a filter is not appropriate * (ie, the remote api) be sure to call PendingFutures.completeAllPendingFutures() manually.</p> * * <p>Note that if you are using this with Objectify, you probably want to use ObjectifyFilter.complete() * rather than PendingFutures or AsyncCacheFilter static methods.</p> * * @author Jeff Schnitzer <jeff@infohazard.org> */ abstract public class TriggerFuture<T> implements Future<T> { /** Wrap the raw Future<?> */ protected Future<T> raw; /** If we have run the trigger() method already */ boolean triggered = false; /** Wrap a normal Future<?> */ public TriggerFuture(Future<T> raw) { this.raw = raw; // We now need to register ourself so that we'll get checked at future API calls PendingFutures.addPending(this); } /** * This method will be called ONCE upon completion of the future, successful or not. * Beware that this.get() may throw an exception. */ abstract protected void trigger(); /* (non-Javadoc) * @see java.util.concurrent.Future#cancel(boolean) */ @Override public boolean cancel(boolean mayInterruptIfRunning) { throw new UnsupportedOperationException("This makes my head spin. Don't do it."); } /* (non-Javadoc) * @see java.util.concurrent.Future#isCancelled() */ @Override public boolean isCancelled() { return this.raw.isCancelled(); } /** * This version also checks to see if we are done and we still need to call the trigger. * If so, it calls it. * * @see java.util.concurrent.Future#isDone() */ @Override public boolean isDone() { boolean done = this.raw.isDone(); if (!triggered && done) { this.triggered = true; PendingFutures.removePending(this); this.trigger(); } return done; } /* (non-Javadoc) * @see java.util.concurrent.Future#get() */ @Override public T get() throws InterruptedException, ExecutionException { try { return this.raw.get(); } finally { this.isDone(); } } /* (non-Javadoc) * @see java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit) */ @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { try { return this.raw.get(timeout, unit); } finally { this.isDone(); } } }
{ "content_hash": "66d91e0987d22a8048044ee7daf8560b", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 108, "avg_line_length": 26.838983050847457, "alnum_prop": 0.6703504894221661, "repo_name": "qickrooms/objectify-appengine", "id": "523ee3474ac61b1caaf6af6ce19079afa90fd756", "size": "3167", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "src/main/java/com/googlecode/objectify/cache/TriggerFuture.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "821394" } ], "symlink_target": "" }
package net.sourceforge.javydreamercsw.validation.manager.web.execution; import static com.validation.manager.core.ContentProvider.TRANSLATOR; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import org.jodconverter.OfficeDocumentConverter; import org.jodconverter.office.LocalOfficeManager; import org.jodconverter.office.OfficeException; import org.jodconverter.office.OfficeManager; import org.openide.util.Lookup; import org.vaadin.easyuploads.MultiFileUpload; import org.vaadin.teemu.wizards.Wizard; import org.vaadin.teemu.wizards.WizardStep; import com.vaadin.data.Validator.InvalidValueException; import com.vaadin.data.fieldgroup.BeanFieldGroup; import com.vaadin.data.util.converter.StringToDoubleConverter; import com.vaadin.data.validator.DoubleRangeValidator; import com.vaadin.event.FieldEvents.TextChangeEvent; import com.vaadin.icons.VaadinIcons; import com.vaadin.server.Resource; import com.vaadin.server.Sizeable; import com.vaadin.shared.ui.datefield.Resolution; import com.vaadin.ui.AbstractField; import com.vaadin.ui.AbstractTextField; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.CheckBox; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Component; import com.vaadin.ui.DateField; import com.vaadin.ui.Field; import com.vaadin.ui.FormLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Notification; import com.vaadin.ui.Panel; import com.vaadin.ui.TextArea; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import com.vaadin.ui.themes.ValoTheme; import com.validation.manager.core.DataBaseManager; import com.validation.manager.core.api.internationalization.InternationalizationProvider; import com.validation.manager.core.db.AttachmentType; import com.validation.manager.core.db.DataEntryProperty; import com.validation.manager.core.db.ExecutionResult; import com.validation.manager.core.db.ExecutionStep; import com.validation.manager.core.db.ExecutionStepAnswer; import com.validation.manager.core.db.ExecutionStepHasAttachment; import com.validation.manager.core.db.ExecutionStepHasIssue; import com.validation.manager.core.db.IssueType; import com.validation.manager.core.db.ReviewResult; import com.validation.manager.core.db.controller.ExecutionResultJpaController; import com.validation.manager.core.db.controller.IssueTypeJpaController; import com.validation.manager.core.db.controller.ReviewResultJpaController; import com.validation.manager.core.server.core.AttachmentServer; import com.validation.manager.core.server.core.AttachmentTypeServer; import com.validation.manager.core.server.core.DataEntryServer; import com.validation.manager.core.server.core.ExecutionResultServer; import com.validation.manager.core.server.core.ExecutionStepServer; import com.validation.manager.core.server.core.IssueServer; import com.validation.manager.core.server.core.ReviewResultServer; import com.validation.manager.core.server.core.VMSettingServer; import de.steinwedel.messagebox.ButtonOption; import de.steinwedel.messagebox.ButtonType; import de.steinwedel.messagebox.MessageBox; import net.sourceforge.javydreamercsw.validation.manager.web.ValidationManagerUI; import net.sourceforge.javydreamercsw.validation.manager.web.component.ByteToStringConverter; import net.sourceforge.javydreamercsw.validation.manager.web.component.VMWindow; import net.sourceforge.javydreamercsw.validation.manager.web.file.IFileDisplay; import net.sourceforge.javydreamercsw.validation.manager.web.file.PDFDisplay; import tm.kod.widgets.numberfield.NumberField; /** * * @author Javier A. Ortiz Bultron javier.ortiz.78@gmail.com */ public class ExecutionWizardStep implements WizardStep { private final Wizard w; private final ExecutionStepServer step; private final ComboBox result = new ComboBox(TRANSLATOR.translate("general.result")); private final ComboBox review = new ComboBox(TRANSLATOR.translate("quality.review")); private final ComboBox issueType = new ComboBox(TRANSLATOR.translate("issue.type")); private Button attach; private Button bug; private Button comment; private DateField start; private DateField end; private DateField reviewDate; private static final Logger LOG = Logger.getLogger(ExecutionWizardStep.class.getSimpleName()); private boolean reviewer = false; private final List<AbstractField> fields = new ArrayList<>(); public ExecutionWizardStep(Wizard w, ExecutionStep step, boolean reviewer) { this.reviewer = reviewer; this.w = w; this.step = new ExecutionStepServer(step); issueType.setSizeFull(); issueType.setReadOnly(false); issueType.setRequired(true); issueType.setRequiredError(TRANSLATOR.translate("missing.type")); IssueTypeJpaController it = new IssueTypeJpaController(DataBaseManager .getEntityManagerFactory()); it.findIssueTypeEntities().forEach(type -> { String item = Lookup.getDefault().lookup(InternationalizationProvider.class) .translate(type.getTypeName()); issueType.addItem(type); issueType.setItemCaption(type, item); switch (type.getId()) { case 1: issueType.setItemIcon(type, VaadinIcons.BUG); break; case 2: issueType.setItemIcon(type, VaadinIcons.EYE); break; case 3: issueType.setItemIcon(type, VaadinIcons.QUESTION); break; } if (type.getTypeName().equals("observation.name")) { issueType.setValue(type); } }); result.setReadOnly(false); result.setRequired(true); result.setRequiredError(TRANSLATOR.translate("missing.result")); result.setTextInputAllowed(false); review.setReadOnly(false); review.setRequired(true); review.setRequiredError(TRANSLATOR.translate("missing.reviiew.result")); review.setTextInputAllowed(false); ReviewResultJpaController c2 = new ReviewResultJpaController(DataBaseManager .getEntityManagerFactory()); c2.findReviewResultEntities().forEach(r -> { String item = Lookup.getDefault().lookup(InternationalizationProvider.class) .translate(r.getReviewName()); review.addItem(r.getReviewName()); review.setItemCaption(r.getReviewName(), item); Resource icon; switch (r.getId()) { case 1: icon = VaadinIcons.CHECK; break; case 2: icon = VaadinIcons.CLOSE; break; default: icon = VaadinIcons.CLOCK; break; } review.setItemIcon(r.getReviewName(), icon); }); ExecutionResultJpaController c = new ExecutionResultJpaController(DataBaseManager .getEntityManagerFactory()); c.findExecutionResultEntities().forEach(r -> { String item = Lookup.getDefault().lookup(InternationalizationProvider.class) .translate(r.getResultName()); result.addItem(r.getResultName()); result.setItemCaption(r.getResultName(), item); Resource icon; switch (r.getId()) { case 1: icon = VaadinIcons.CHECK; break; case 2: icon = VaadinIcons.CLOSE; break; case 3: icon = VaadinIcons.PAUSE; break; default: icon = VaadinIcons.CLOCK; break; } result.setItemIcon(r.getResultName(), icon); }); } @Override public String getCaption() { return getExecutionStep().getStep().getTestCase().getName() + " " + TRANSLATOR.translate("general.step") + ":" + getExecutionStep().getStep().getStepSequence(); } @Override public Component getContent() { Panel form = new Panel(TRANSLATOR.translate("step.detail")); if (getExecutionStep().getExecutionStart() == null) { //Set the start date. getExecutionStep().setExecutionStart(new Date()); } FormLayout layout = new FormLayout(); form.setContent(layout); form.addStyleName(ValoTheme.FORMLAYOUT_LIGHT); BeanFieldGroup binder = new BeanFieldGroup(getExecutionStep().getStep().getClass()); binder.setItemDataSource(getExecutionStep().getStep()); TextArea text = new TextArea(TRANSLATOR.translate("general.text")); text.setConverter(new ByteToStringConverter()); binder.bind(text, "text"); text.setSizeFull(); layout.addComponent(text); Field notes = binder.buildAndBind(TRANSLATOR.translate("general.notes"), "notes", TextArea.class); notes.setSizeFull(); layout.addComponent(notes); if (getExecutionStep().getExecutionStart() != null) { start = new DateField(TRANSLATOR.translate("start.date")); start.setResolution(Resolution.SECOND); start.setDateFormat(VMSettingServer.getSetting("date.format") .getStringVal()); start.setValue(getExecutionStep().getExecutionStart()); start.setReadOnly(true); layout.addComponent(start); } if (getExecutionStep().getExecutionEnd() != null) { end = new DateField(TRANSLATOR.translate("end.date")); end.setDateFormat(VMSettingServer.getSetting("date.format") .getStringVal()); end.setResolution(Resolution.SECOND); end.setValue(getExecutionStep().getExecutionEnd()); end.setReadOnly(true); layout.addComponent(end); } binder.setReadOnly(true); //Space to record result if (getExecutionStep().getResultId() != null) { result.setValue(getExecutionStep().getResultId().getResultName()); } layout.addComponent(result); if (reviewer) {//Space to record review if (getExecutionStep().getReviewResultId() != null) { review.setValue(getExecutionStep().getReviewResultId().getReviewName()); } layout.addComponent(review); } //Add Reviewer name if (getExecutionStep().getReviewer() != null) { TextField reviewerField = new TextField(TRANSLATOR .translate("general.reviewer")); reviewerField.setValue(getExecutionStep().getReviewer().getFirstName() + " " + getExecutionStep().getReviewer().getLastName()); reviewerField.setReadOnly(true); layout.addComponent(reviewerField); } if (getExecutionStep().getReviewDate() != null) { reviewDate = new DateField(TRANSLATOR .translate("review.date")); reviewDate.setDateFormat(VMSettingServer.getSetting("date.format") .getStringVal()); reviewDate.setResolution(Resolution.SECOND); reviewDate.setValue(getExecutionStep().getReviewDate()); reviewDate.setReadOnly(true); layout.addComponent(reviewDate); } if (VMSettingServer.getSetting("show.expected.result").getBoolVal()) { TextArea expectedResult = new TextArea(TRANSLATOR.translate("expected.result")); expectedResult.setConverter(new ByteToStringConverter()); binder.bind(expectedResult, "expectedResult"); expectedResult.setSizeFull(); layout.addComponent(expectedResult); } //Add the fields fields.clear(); getExecutionStep().getStep().getDataEntryList().forEach(de -> { switch (de.getDataEntryType().getId()) { case 1://String TextField tf = new TextField(TRANSLATOR .translate(de.getEntryName())); tf.setRequired(true); tf.setData(de.getEntryName()); if (VMSettingServer.getSetting("show.expected.result") .getBoolVal()) { //Add expected result DataEntryProperty stringCase = DataEntryServer .getProperty(de, "property.match.case"); DataEntryProperty r = DataEntryServer .getProperty(de, "property.expected.result"); if (r != null && !r.getPropertyValue().equals("null")) { String error = TRANSLATOR.translate("expected.result") + ": " + r.getPropertyValue(); tf.setRequiredError(error); tf.setRequired(DataEntryServer .getProperty(de, "property.required") .getPropertyValue().equals("true")); tf.addValidator((Object val) -> { //We have an expected result and a match case requirement if (stringCase != null && stringCase.getPropertyValue().equals("true") ? !((String) val).equals(r.getPropertyValue()) : !((String) val).equalsIgnoreCase(r.getPropertyValue())) { throw new InvalidValueException(error); } }); } } fields.add(tf); //Set value if already recorded updateValue(tf); layout.addComponent(tf); break; case 2://Numeric NumberField field = new NumberField(TRANSLATOR .translate(de.getEntryName())); field.setSigned(true); field.setUseGrouping(true); field.setGroupingSeparator(','); field.setDecimalSeparator('.'); field.setConverter(new StringToDoubleConverter()); field.setRequired(DataEntryServer .getProperty(de, "property.required") .getPropertyValue().equals("true")); field.setData(de.getEntryName()); Double min = null, max = null; for (DataEntryProperty prop : de.getDataEntryPropertyList()) { String value = prop.getPropertyValue(); if (prop.getPropertyName().equals("property.max")) { try { max = Double.parseDouble(value); } catch (NumberFormatException ex) { //Leave as null } } else if (prop.getPropertyName().equals("property.min")) { try { min = Double.parseDouble(value); } catch (NumberFormatException ex) { //Leave as null } } } //Add expected result if (VMSettingServer.getSetting("show.expected.result") .getBoolVal() && (min != null || max != null)) { String error = TRANSLATOR .translate("error.out.of.range") + " " + (min == null ? " " : (TRANSLATOR.translate("property.min") + ": " + min)) + " " + (max == null ? "" : (TRANSLATOR .translate("property.max") + ": " + max)); field.setRequiredError(error); field.addValidator(new DoubleRangeValidator(error, min, max)); } fields.add(field); //Set value if already recorded updateValue(field); layout.addComponent(field); break; case 3://Boolean CheckBox cb = new CheckBox(TRANSLATOR .translate(de.getEntryName())); cb.setData(de.getEntryName()); cb.setRequired(DataEntryServer .getProperty(de, "property.required") .getPropertyValue().equals("true")); if (VMSettingServer.getSetting("show.expected.result") .getBoolVal()) { DataEntryProperty r = DataEntryServer.getProperty(de, "property.expected.result"); if (r != null) { //Add expected result String error = TRANSLATOR.translate("expected.result") + ": " + r.getPropertyValue(); cb.addValidator((Object val) -> { if (!val.toString().equals(r.getPropertyValue())) { throw new InvalidValueException(error); } }); } } fields.add(cb); //Set value if already recorded updateValue(cb); layout.addComponent(cb); break; case 4://Attachment Label l = new Label(TRANSLATOR .translate(de.getEntryName())); layout.addComponent(l); break; default: LOG.log(Level.SEVERE, "Unexpected field type: {0}", de.getDataEntryType().getId()); } }); //Add the Attachments HorizontalLayout attachments = new HorizontalLayout(); attachments.setCaption(TRANSLATOR.translate("general.attachment")); HorizontalLayout comments = new HorizontalLayout(); comments.setCaption(TRANSLATOR.translate("general.comments")); HorizontalLayout issues = new HorizontalLayout(); issues.setCaption(TRANSLATOR.translate("general.issue")); int commentCounter = 0; int issueCounter = 0; for (ExecutionStepHasIssue ei : getExecutionStep().getExecutionStepHasIssueList()) { issueCounter++; Button a = new Button("Issue #" + issueCounter); a.setIcon(VaadinIcons.BUG); a.addClickListener((Button.ClickEvent event) -> { displayIssue(new IssueServer(ei.getIssue())); }); a.setEnabled(!step.getLocked()); issues.addComponent(a); } for (ExecutionStepHasAttachment attachment : getExecutionStep().getExecutionStepHasAttachmentList()) { switch (attachment.getAttachment().getAttachmentType().getType()) { case "comment": { //Comments go in a different section commentCounter++; Button a = new Button("Comment #" + commentCounter); a.setIcon(VaadinIcons.CLIPBOARD_TEXT); a.addClickListener((Button.ClickEvent event) -> { if (!step.getLocked()) { //Prompt if user wants this removed MessageBox mb = getDeletionPrompt(attachment); mb.open(); } else { displayComment(new AttachmentServer(attachment .getAttachment().getAttachmentPK())); } }); a.setEnabled(!step.getLocked()); comments.addComponent(a); break; } default: { Button a = new Button(attachment.getAttachment().getFileName()); a.setEnabled(!step.getLocked()); a.setIcon(VaadinIcons.PAPERCLIP); a.addClickListener((Button.ClickEvent event) -> { if (!step.getLocked()) { //Prompt if user wants this removed MessageBox mb = getDeletionPrompt(attachment); mb.open(); } else { displayAttachment( new AttachmentServer(attachment.getAttachment() .getAttachmentPK())); } }); attachments.addComponent(a); break; } } } if (attachments.getComponentCount() > 0) { layout.addComponent(attachments); } if (comments.getComponentCount() > 0) { layout.addComponent(comments); } if (issues.getComponentCount() > 0) { layout.addComponent(issues); } //Add the menu HorizontalLayout hl = new HorizontalLayout(); attach = new Button(TRANSLATOR.translate("add.attachment")); attach.setIcon(VaadinIcons.PAPERCLIP); attach.addClickListener((Button.ClickEvent event) -> { //Show dialog to upload file. Window dialog = new VMWindow(TRANSLATOR.translate("attach.file")); VerticalLayout vl = new VerticalLayout(); MultiFileUpload multiFileUpload = new MultiFileUpload() { @Override protected void handleFile(File file, String fileName, String mimeType, long length) { try { LOG.log(Level.FINE, "Received file {1} at: {0}", new Object[] { file.getAbsolutePath(), fileName }); //Process the file //Create the attachment AttachmentServer a = new AttachmentServer(); a.addFile(file, fileName); //Overwrite the default file name set in addFile. It'll be a temporary file name a.setFileName(fileName); a.write2DB(); //Now add it to this Execution Step if (getExecutionStep().getExecutionStepHasAttachmentList() == null) { getExecutionStep().setExecutionStepHasAttachmentList(new ArrayList<>()); } getExecutionStep().addAttachment(a); getExecutionStep().write2DB(); w.updateCurrentStep(); } catch (Exception ex) { LOG.log(Level.SEVERE, "Error creating attachment!", ex); } } }; multiFileUpload.setCaption(TRANSLATOR.translate("select.files.attach")); vl.addComponent(multiFileUpload); dialog.setContent(vl); dialog.setHeight(25, Sizeable.Unit.PERCENTAGE); dialog.setWidth(25, Sizeable.Unit.PERCENTAGE); ValidationManagerUI.getInstance().addWindow(dialog); }); hl.addComponent(attach); bug = new Button(TRANSLATOR.translate("create.issue")); bug.setIcon(VaadinIcons.BUG); bug.addClickListener((Button.ClickEvent event) -> { displayIssue(new IssueServer()); }); hl.addComponent(bug); comment = new Button(TRANSLATOR.translate("add.comment")); comment.setIcon(VaadinIcons.CLIPBOARD_TEXT); comment.addClickListener((Button.ClickEvent event) -> { AttachmentServer as = new AttachmentServer(); //Get comment type AttachmentType type = AttachmentTypeServer .getTypeForExtension("comment"); as.setAttachmentType(type); displayComment(as); }); hl.addComponent(comment); step.update(); attach.setEnabled(!step.getLocked()); bug.setEnabled(!step.getLocked()); comment.setEnabled(!step.getLocked()); result.setEnabled(!step.getLocked()); layout.addComponent(hl); return layout; } private void displayIssue(IssueServer is) { Panel form = new Panel(TRANSLATOR.translate("general.issue")); FormLayout layout = new FormLayout(); form.setContent(layout); if (is.getIssuePK() == null) { //Set creation date is.setCreationTime(new Date()); } BeanFieldGroup binder = new BeanFieldGroup(is.getClass()); binder.setItemDataSource(is); Field title = binder.buildAndBind(TRANSLATOR.translate("general.summary"), "title", TextField.class); title.setSizeFull(); layout.addComponent(title); Field desc = binder.buildAndBind(TRANSLATOR.translate("general.description"), "description", TextArea.class); desc.setSizeFull(); layout.addComponent(desc); DateField creation = (DateField) binder .buildAndBind(TRANSLATOR.translate("creation.time"), "creationTime", DateField.class); creation.setReadOnly(true); creation.setDateFormat(VMSettingServer.getSetting("date.format") .getStringVal()); creation.setResolution(Resolution.SECOND); layout.addComponent(creation); //Add the result layout.addComponent(issueType); if (is.getIssueType() != null) { issueType.setValue(is.getIssueType().getTypeName()); } //Lock if being created issueType.setReadOnly(is.getIssueType() == null); MessageBox mb = MessageBox.create(); mb.setData(is); mb.asModal(true) .withMessage(layout) .withButtonAlignment(Alignment.MIDDLE_CENTER) .withOkButton(() -> { try { //Create the attachment IssueServer issue = (IssueServer) mb.getData(); issue.setDescription(((TextArea) desc).getValue().trim()); issue.setIssueType((IssueType) issueType.getValue()); issue.setCreationTime(creation.getValue()); issue.setTitle((String) title.getValue()); boolean toAdd = issue.getIssuePK() == null; issue.write2DB(); if (toAdd) { //Now add it to this Execution Step if (getExecutionStep().getExecutionStepHasIssueList() == null) { getExecutionStep().setExecutionStepHasIssueList(new ArrayList<>()); } getExecutionStep().addIssue(issue, ValidationManagerUI .getInstance().getUser()); getExecutionStep().write2DB(); } w.updateCurrentStep(); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } }, ButtonOption.focus(), ButtonOption.icon(VaadinIcons.CHECK), ButtonOption.disable()) .withCancelButton(ButtonOption.icon(VaadinIcons.CLOSE)); mb.getWindow().setCaption(TRANSLATOR.translate("issue.detail")); mb.getWindow().setIcon(ValidationManagerUI.SMALL_APP_ICON); ((TextArea) desc).addTextChangeListener((TextChangeEvent event1) -> { //Enable if there is a description change. mb.getButton(ButtonType.OK) .setEnabled(!step.getLocked() && !event1.getText().trim().isEmpty()); }); ((TextField) title).addTextChangeListener((TextChangeEvent event1) -> { //Enable if there is a title change. mb.getButton(ButtonType.OK) .setEnabled(!step.getLocked() && !event1.getText().trim().isEmpty()); }); mb.open(); } private void displayComment(AttachmentServer as) { Panel form = new Panel(TRANSLATOR.translate("general.comment")); FormLayout layout = new FormLayout(); form.setContent(layout); BeanFieldGroup binder = new BeanFieldGroup(as.getClass()); binder.setItemDataSource(as); Field desc = binder.buildAndBind(TRANSLATOR.translate("general.text"), "textValue", TextArea.class); desc.setSizeFull(); layout.addComponent(desc); MessageBox mb = MessageBox.create(); mb.setData(as); mb.asModal(true) .withMessage(desc) .withButtonAlignment(Alignment.MIDDLE_CENTER) .withOkButton(() -> { try { //Create the attachment AttachmentServer a = (AttachmentServer) mb.getData(); a.setTextValue(((TextArea) desc).getValue().trim()); boolean toAdd = a.getAttachmentPK() == null; a.write2DB(); if (toAdd) { //Now add it to this Execution Step if (getExecutionStep().getExecutionStepHasAttachmentList() == null) { getExecutionStep().setExecutionStepHasAttachmentList(new ArrayList<>()); } getExecutionStep().addAttachment(a); getExecutionStep().write2DB(); } w.updateCurrentStep(); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } }, ButtonOption.focus(), ButtonOption.icon(VaadinIcons.CHECK), ButtonOption.disable()) .withCancelButton(ButtonOption.icon(VaadinIcons.CLOSE)); mb.getWindow().setCaption(TRANSLATOR.translate("enter.comment")); mb.getWindow().setIcon(ValidationManagerUI.SMALL_APP_ICON); ((TextArea) desc).addTextChangeListener((TextChangeEvent event1) -> { //Enable only when there is a comment. mb.getButton(ButtonType.OK) .setEnabled(!step.getLocked() && !event1.getText().trim().isEmpty()); }); mb.open(); } @Override public boolean onAdvance() { //Can only proceed after the current step is executed and documented. String answer = ((String) result.getValue()); String answer2 = ((String) review.getValue()); boolean pass = true; if (answer == null) { Notification.show(TRANSLATOR.translate("unable.to.proceed"), result.getRequiredError(), Notification.Type.WARNING_MESSAGE); } else if (reviewer && answer2 == null) { Notification.show(TRANSLATOR.translate("unable.to.proceed"), review.getRequiredError(), Notification.Type.WARNING_MESSAGE); } else { //Check all fields for answers for (AbstractField field : fields) { if (field.isRequired() && !(field instanceof CheckBox) && field.isEmpty()) { Notification.show(TRANSLATOR.translate("unable.to.proceed"), field.getRequiredError(), Notification.Type.WARNING_MESSAGE); pass = false; } } if (pass) { try { //Save the result ExecutionResult newResult = ExecutionResultServer .getResult(answer); ReviewResult newReview = ReviewResultServer.getReview(answer2); getExecutionStep().setExecutionStart(start.getValue()); if (getExecutionStep().getResultId() == null || !Objects.equals(getExecutionStep().getResultId().getId(), newResult.getId())) { getExecutionStep().setResultId(newResult); //Set end date to null to reflect update getExecutionStep().setExecutionEnd(null); } if (reviewer && (getExecutionStep().getReviewResultId() == null || !Objects.equals(getExecutionStep() .getReviewResultId().getId(), newReview.getId()))) { getExecutionStep().setReviewResultId(newReview); getExecutionStep().setReviewer(ValidationManagerUI .getInstance().getUser()); } if (getExecutionStep().getExecutionEnd() == null) { getExecutionStep().setExecutionEnd(new Date()); } if (reviewer && getExecutionStep().getReviewDate() == null) { getExecutionStep().setReviewDate(new Date()); } if (getExecutionStep().getExecutionStepAnswerList() == null) { getExecutionStep().setExecutionStepAnswerList(new ArrayList<>()); } if (getExecutionStep().getExecutionStepHasVmUserList() == null) { getExecutionStep().setExecutionStepHasVmUserList(new ArrayList<>()); } getExecutionStep().getExecutionStepAnswerList().clear(); for (AbstractField field : fields) { //The field has the field name as data if (field.getData() == null) { pass = false; LOG.log(Level.SEVERE, "Field missing data! {0}", field); } else { String fieldName = (String) field.getData(); ExecutionStepAnswer stepAnswer = new ExecutionStepAnswer(getExecutionStep() .getExecutionStepPK() .getTestCaseExecutionId(), getExecutionStep().getExecutionStepPK() .getStepId(), getExecutionStep().getExecutionStepPK() .getStepTestCaseId() ); stepAnswer.setExecutionStep(getExecutionStep().getEntity()); stepAnswer.setFieldName(fieldName); stepAnswer.setFieldAnswer(field.getValue().toString()); getExecutionStep().getExecutionStepAnswerList() .add(stepAnswer); } } } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } } } boolean validAnswer = result.getValue() != null && !((String) result.getValue()).trim().isEmpty(); boolean validReview = review.getValue() != null && !((String) review.getValue()).trim().isEmpty(); return reviewer ? validReview && validAnswer : validAnswer && pass; } @Override public boolean onBack() { return getExecutionStep().getStep().getStepSequence() > 1; } /** * @return the step */ public ExecutionStepServer getExecutionStep() { return step; } public static boolean getPDFRendering(File source, File dest) throws IllegalStateException { OfficeManager officeManager = null; try { File home = new File(VMSettingServer.getSetting("openoffice.home") .getStringVal()); int port = VMSettingServer .getSetting("openoffice.port").getIntVal(); if (!home.isDirectory() || !home.exists()) { LOG.log(Level.WARNING, "Unable to find OpenOffice and/or LibreOffice " + "installation at: {0}", home); Notification.show(TRANSLATOR.translate("unable.to.render.pdf.title"), TRANSLATOR.translate("unable.to.render.pdf.message"), Notification.Type.ERROR_MESSAGE); return false; } if (port <= 0) { LOG.log(Level.WARNING, "Unable to find OpenOffice and/or LibreOffice " + "installation at port: {0}", port); Notification.show(TRANSLATOR.translate("unable.to.render.pdf.title"), TRANSLATOR.translate("unable.to.render.pdf.port"), Notification.Type.ERROR_MESSAGE); return false; } // Connect to an OpenOffice.org instance running on available port try { officeManager = LocalOfficeManager.builder() .portNumbers(port) .officeHome(home) .build(); officeManager.start(); OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager); converter.convert(source, dest); // close the connection officeManager.stop(); return true; } catch (IllegalStateException ise) { //Looks like OpenOffice or LibreOffice is not installed LOG.log(Level.WARNING, "Unable to find OpenOffice and/or LibreOffice " + "installation.", ise); } } catch (OfficeException e) { if (officeManager != null) { try { officeManager.stop(); } catch (OfficeException ex) { LOG.log(Level.SEVERE, null, ex); } } LOG.log(Level.SEVERE, null, e); } return false; } private void displayAttachment(AttachmentServer attachment) { String name = attachment.getFileName(); byte[] bytes = attachment.getFile(); boolean ableToDisplay = false; try { for (IFileDisplay fd : Lookup.getDefault() .lookupAll(IFileDisplay.class)) { if (fd.supportFile(new File(name))) { ValidationManagerUI.getInstance() .addWindow(fd.getViewer(fd.loadFile(name, bytes))); ableToDisplay = true; break; } } if (!ableToDisplay) { //Convert file to pfd PDFDisplay pdf = new PDFDisplay(); File source = pdf.loadFile(name, bytes); File dest = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + name.substring(0, name.lastIndexOf(".")) + ".pdf"); getPDFRendering(source, dest); if (dest.exists()) { ValidationManagerUI.getInstance().addWindow(pdf.getViewer(dest)); ableToDisplay = true; } } } catch (IOException ex) { LOG.log(Level.SEVERE, "Error loading attachment file: " + name, ex); } if (!ableToDisplay) { Notification.show(TRANSLATOR.translate("unable.to.render.pdf.title"), TRANSLATOR.translate("unable.to.render.pdf.message"), Notification.Type.ERROR_MESSAGE); } } private MessageBox getDeletionPrompt(Object data) { MessageBox mb = MessageBox.createQuestion(); mb.setData(data); mb.asModal(true) .withMessage(new Label(TRANSLATOR.translate("remove.item.title"))) .withButtonAlignment(Alignment.MIDDLE_CENTER) .withYesButton(() -> { try { if (mb.getData() instanceof ExecutionStepHasAttachment) { getExecutionStep().removeAttachment(new AttachmentServer( ((ExecutionStepHasAttachment) mb.getData()) .getAttachment().getAttachmentPK())); } if (mb.getData() instanceof ExecutionStepHasIssue) { getExecutionStep().removeIssue(new IssueServer( ((ExecutionStepHasIssue) mb.getData()) .getIssue())); } getExecutionStep().write2DB(); getExecutionStep().update(); w.updateCurrentStep(); } catch (Exception ex) { LOG.log(Level.SEVERE, null, ex); } }, ButtonOption.focus(), ButtonOption.icon(VaadinIcons.CHECK)) .withNoButton(() -> { if (mb.getData() instanceof ExecutionStepHasAttachment) { ExecutionStepHasAttachment esha = (ExecutionStepHasAttachment) mb.getData(); if (esha.getAttachment().getAttachmentType().getType().equals("comment")) { displayComment(new AttachmentServer(esha .getAttachment().getAttachmentPK())); } else { displayAttachment(new AttachmentServer(esha .getAttachment().getAttachmentPK())); } } if (mb.getData() instanceof ExecutionStepHasIssue) { ExecutionStepHasIssue eshi = (ExecutionStepHasIssue) mb.getData(); displayIssue(new IssueServer(eshi.getIssue())); } }, ButtonOption.icon(VaadinIcons.CLOSE)); mb.getWindow().setCaption(TRANSLATOR.translate("issue.detail")); mb.getWindow().setIcon(ValidationManagerUI.SMALL_APP_ICON); return mb; } private void updateValue(AbstractField field) { if (field.getData() != null) { //Look for the answer in the database getExecutionStep().getExecutionStepAnswerList().forEach(answer -> { if (answer.getFieldName().equals(field.getData())) { if (field instanceof AbstractTextField) {//This includes NumberField field.setValue(answer.getFieldAnswer()); } else if (field instanceof CheckBox) { field.setValue(answer.getFieldAnswer().equals("true")); } } }); } else { LOG.log(Level.SEVERE, "Field missing data! {0}", field); } } }
{ "content_hash": "76070681ea6464d6825d4e44724b0a32", "timestamp": "", "source": "github", "line_count": 1119, "max_line_length": 93, "avg_line_length": 37.23949955317248, "alnum_prop": 0.5714285714285714, "repo_name": "javydreamercsw/validation-manager", "id": "ddc5384587b1368dd982a79eded963076f913179", "size": "42319", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Validation-Manager-Web/src/main/java/net/sourceforge/javydreamercsw/validation/manager/web/execution/ExecutionWizardStep.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "321386" }, { "name": "Java", "bytes": "3213112" }, { "name": "SCSS", "bytes": "2735" } ], "symlink_target": "" }
namespace Nancy.Routing.Constraints { using System; /// <summary> /// Constraint for <see cref="DateTime"/> route segments. /// </summary> public class DateTimeRouteSegmentConstraint : RouteSegmentConstraintBase<DateTime> { /// <summary> /// Gets the name of the constraint. /// </summary> /// <value>The constraint's name.</value> public override string Name { get { return "datetime"; } } /// <summary> /// Tries to match the given segment against the constraint. /// </summary> /// <param name="constraint">The constraint.</param> /// <param name="segment">The segment to match.</param> /// <param name="matchedValue">The matched value.</param> /// <returns> /// <see langword="true"/> if the segment matches the constraint, <see langword="false"/> otherwise. /// </returns> protected override bool TryMatch(string constraint, string segment, out DateTime matchedValue) { return DateTime.TryParse(segment, out matchedValue); } } }
{ "content_hash": "40aeaf0f004489500e4582d3c9942d45", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 108, "avg_line_length": 35.515151515151516, "alnum_prop": 0.5716723549488054, "repo_name": "asbjornu/Nancy", "id": "463023c0c51a4591815443fb7120eb73c261469e", "size": "1174", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "src/Nancy/Routing/Constraints/DateTimeRouteSegmentConstraint.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "4017019" }, { "name": "CSS", "bytes": "6309" }, { "name": "HTML", "bytes": "68714" }, { "name": "JavaScript", "bytes": "68780" }, { "name": "Liquid", "bytes": "20122" }, { "name": "PowerShell", "bytes": "3148" }, { "name": "Ruby", "bytes": "13945" }, { "name": "Shell", "bytes": "1931" }, { "name": "Visual Basic", "bytes": "80" } ], "symlink_target": "" }
This example purely consists of additional documentation and examples of the `deparse()` method of RiveScript. ## Relevant Methods * `object rs.deparse()` This method exports the current in-memory representation of the RiveScript brain as a JSON-serializable data structure. See [Schema](#schema) for the format of this data structure. * `string rs.stringify([object deparsed])` This method converts a data structure like the one from `deparse()` into plain text RiveScript source code. By default (with no argument passed), this will use the current in-memory representation of the RiveScript brain. For example, if you loaded a directory of RiveScript files and then called `stringify()` you would get a large text blob that contains all the source code of all the files from that directory. Note, however, that the formatting of the original reply data might be lost because the output from `stringify()` is working backwards from the in-memory representation, so for example, comments in the original source code aren't preserved and places where `^Continue` was used will instead result in one single line of code in the output. If you pass in a data structure formatted the same way as the one `deparse()` returns, you can stringify that code instead. This way you could programmatically generate RiveScript data (for example, from a custom user interface for authoring bots) and convert it into valid RiveScript source code using this method. * `void write(string filename[, object deparsed])` This method is the next logical extension of `stringify()`: to write the RiveScript source code to a file on disk. This method is only available from a Node environment where the program has access to write to the filesystem. From a web environment, you'd need to use `stringify()` to get the RiveScript source and use another method to save it (e.g. sending it in an Ajax request to a server-side script). Like the `stringify()` method, this defaults to using the current in-memory reply data, but you can pass your own deparse-compatible data structure as the second argument. ## Schema The data structure returned by `deparse()` looks like this, annotated: ```yaml begin: global: map of key/value pairs for `! global` global variable definitions var: map of key/value pairs for `! var` bot variable definitions sub: map of key/value pairs for `! sub` substitution definitions person: map of key/value pairs for `! person` substitution definitions array: map of `! array` names to arrays of their values triggers: array of trigger data (see below) topics: map of topic names -> array of trigger data under that topic inherits: map of topic names -> map of topics that it inherits includes: map of topic names -> map of topics that it includes objects: source codes of JavaScript object macros* ``` The trigger data is stored in arrays underneath `begin.triggers` (for those in the `> begin` block) and `topics.$NAME` for triggers under a particular topic, with the default topic being named "random". Each trigger is an object with the following schema: ```yaml trigger: the plain text trigger reply: array of the plain text `-Reply` commands, or `[]` condition: array of the plain text `*Condition` commands, or `[]` redirect: the text of the `@Redirect` command, or `null` previous: the text of the `%Previous` command, or `null` ``` \* The `objects` data might contain the source code of JavaScript or CoffeeScript object macros, but currently seems to be somewhat buggy; macros defined in JavaScript source code using `rs.setSubrotuine()` will probably appear here, but it doesn't seem to stringify objects defined inside the RiveScript source code. I don't recommend relying on this data from `deparse()`. The schema of the objects would look like: ```yaml javascript: # the name of the handler, `javascript` or `coffeescript` _objects: map of object name -> Function object ``` ## Examples Here are some example code snippets that show what the deparsed data structure looks like. * JavaScript Code ```javascript var bot = new RiveScript(); bot.loadFile("example.rive", function() { bot.sortReplies(); var deparsed = bot.deparse(); console.log(JSON.stringify(deparsed, null, 2)); } ``` * RiveScript Code (`example.rive`) ```rivescript ! version = 1.0 ! var name = Aiden ! var age = 5 ! sub what's = what is ! array colors = red blue green yellow cyan magenta black white > begin + request - {ok} < begin + hello bot - Hello human. + hi robot @ hello bot + my name is * - <set name=<formal>>Nice to meet you, <get name>. - <set name=<formal>>Hello, <get name>. + what is my name * <get name> != undefined => Your name is <get name>. - You didn't tell me your name. > topic game-global + help - How to play... < topic > topic game-room-1 inherits game-global + look - You're in a room labeled "1". < topic > object reverse javascript var msg = args.join(" "); return msg.split("").reverse().join(""); < object + say * in reverse - <call>reverse <star></call> ``` * JSON output: ```javascript { "begin": { "global": {}, "var": { "name": "Aiden", "age": "5" }, "sub": { "what's": "what is" }, "person": {}, "array": { "colors": [ "red", "blue", "green", "yellow", "cyan", "magenta", "black", "white" ] }, "triggers": [ { "trigger": "request", "reply": [ "{ok}" ], "condition": [], "redirect": null, "previous": null } ] }, "topics": { "random": [ { "trigger": "hello bot", "reply": [ "Hello human." ], "condition": [], "redirect": null, "previous": null }, { "trigger": "hi robot", "reply": [], "condition": [], "redirect": "hello bot", "previous": null }, { "trigger": "my name is *", "reply": [ "<set name=<formal>>Nice to meet you, <get name>.", "<set name=<formal>>Hello, <get name>." ], "condition": [], "redirect": null, "previous": null }, { "trigger": "what is my name", "reply": [ "You didn't tell me your name." ], "condition": [ "<get name> != undefined => Your name is <get name>." ], "redirect": null, "previous": null }, { "trigger": "say * in reverse", "reply": [ "<call>reverse <star></call>" ], "condition": [], "redirect": null, "previous": null } ], "game-global": [ { "trigger": "help", "reply": [ "How to play..." ], "condition": [], "redirect": null, "previous": null } ], "game-room-1": [ { "trigger": "look", "reply": [ "You're in a room labeled \"1\"." ], "condition": [], "redirect": null, "previous": null } ] }, "inherits": { "__begin__": {}, "random": {}, "game-global": {}, "game-room-1": { "game-global": 1 } }, "includes": { "__begin__": {}, "random": {}, "game-global": {}, "game-room-1": {} }, "objects": { "javascript": { "_objects": { "reverse": [Function] } } } } ```
{ "content_hash": "aa1cb068755c66cdd9e84e2aa6a7097f", "timestamp": "", "source": "github", "line_count": 284, "max_line_length": 80, "avg_line_length": 27.764084507042252, "alnum_prop": 0.587571337983513, "repo_name": "rundexter/rivescript-js", "id": "024cd988a0050e235ecd9e1322050e9936f10e1a", "size": "7907", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "eg/deparse/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "829" }, { "name": "CoffeeScript", "bytes": "270943" }, { "name": "HTML", "bytes": "3297" }, { "name": "JavaScript", "bytes": "45164" }, { "name": "Perl", "bytes": "239" }, { "name": "Python", "bytes": "2979" }, { "name": "Shell", "bytes": "197" } ], "symlink_target": "" }
namespace NLog.UnitTests.LayoutRenderers.Wrappers { using NLog; using NLog.LayoutRenderers.Wrappers; using NLog.Layouts; using NLog.Targets; using System; using System.Collections.Generic; using Xunit; public class ReplaceTests : NLogTestBase { [Fact] public void ReplaceTestWithSimpleRegEx() { MappedDiagnosticsContext.Clear(); MappedDiagnosticsContext.Set("foo", "\r\nfoo\rbar\nbar\tbar bar \n bar"); SimpleLayout l = @"${replace:inner=${mdc:foo}:searchFor=\\r\\n|\\s:replaceWith= :regex=true}"; var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(" foo bar bar bar bar bar", result); } [Fact] public void ReplaceTestWithSimpleRegExFromConfig() { MappedDiagnosticsContext.Clear(); var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <targets> <target name='d1' type='Debug' layout='${replace:inner=${message}:searchFor=\\r\\n|\\s:replaceWith= :regex=true}' /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var result = layout.Render(new LogEventInfo(LogLevel.Info, "Test", "\r\nfoo\rbar\nbar\tbar bar \n bar")); Assert.Equal(" foo bar bar bar bar bar", result); } [Fact] public void ReplaceTestWithSimpleRegExFromConfig2() { MappedDiagnosticsContext.Clear(); var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <variable name=""whitespace"" value=""\\r\\n|\\s"" /> <variable name=""oneLineMessage"" value=""${replace:inner=${message}:searchFor=${whitespace}:replaceWith= :regex=true}"" /> <targets> <target name=""d1"" type=""Debug"" layout=""${oneLineMessage}"" /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var result = layout.Render(new LogEventInfo(LogLevel.Info, "Test", "\r\nfoo\rbar\nbar\tbar bar \n bar")); Assert.Equal(" foo bar bar bar bar bar", result); } [Fact] public void ReplaceTestWithComplexRegEx() { MappedDiagnosticsContext.Clear(); var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <variable name=""searchExp"" value=""(?&lt;!\\d[ -]*)(?\:(?&lt;digits&gt;\\d)[ -]*)\{8,16\}(?=(\\d[ -]*)\{3\}(\\d)(?![ -]\\d))"" /> <variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=X:replaceGroupName=digits:regex=true:ignorecase=true}"" /> <targets> <target name=""d1"" type=""Debug"" layout=""${message1}"" /> </targets> <rules> <logger name=""*"" minlevel=""Trace"" writeTo=""d1"" /> </rules> </nlog>"); var d1 = configuration.FindTargetByName("d1") as DebugTarget; Assert.NotNull(d1); var layout = d1.Layout as SimpleLayout; Assert.NotNull(layout); var testCases = new List<Tuple<string, string>> { Tuple.Create("1234", "1234"), Tuple.Create("1234-5678-1234-5678", "XXXX-XXXX-XXXX-5678"), }; foreach (var testCase in testCases) { var result = layout.Render(new LogEventInfo(LogLevel.Info, "Test", testCase.Item1)); Assert.Equal(testCase.Item2, result); } } [Fact] public void ReplaceNamedGroupTests() { var pattern = @"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]*\d))"; var groupName = @"digits"; var regex = new System.Text.RegularExpressions.Regex( pattern, System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase); var testCases = new List<Tuple<string, string, string>> { Tuple.Create("1234", "1234", "X"), Tuple.Create("1234-5678-1234-5678", "XXXX-XXXX-XXXX-5678", "X"), Tuple.Create("1234 5678 1234 5678", "XXXX XXXX XXXX 5678", "X"), Tuple.Create("1234567812345678", "XXXXXXXXXXXX5678", "X"), Tuple.Create("ABCD-1234-5678-1234-5678", "ABCD-XXXX-XXXX-XXXX-5678", "X"), Tuple.Create("1234-5678-1234-5678-ABCD", "XXXX-XXXX-XXXX-5678-ABCD", "X"), Tuple.Create("ABCD-1234-5678-1234-5678-ABCD", "ABCD-XXXX-XXXX-XXXX-5678-ABCD", "X"), Tuple.Create("ABCD-1234-5678-1234-5678-ABCD", "ABCD-XXXXXXXX-XXXXXXXX-XXXXXXXX-5678-ABCD", "XX"), }; foreach (var testCase in testCases) { var input = testCase.Item1; var replacement = testCase.Item3; var result = regex.Replace( input, m => ReplaceLayoutRendererWrapper.ReplaceNamedGroup(input, groupName, replacement, m)); Assert.Equal(testCase.Item2, result); } } } }
{ "content_hash": "3130f6a1e560d5634c854c22a6dd8a86", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 160, "avg_line_length": 38, "alnum_prop": 0.5634779516358464, "repo_name": "ie-zero/NLog", "id": "992b386aac26210b1ef39fcbcb358f59448f9049", "size": "7290", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/NLog.UnitTests/LayoutRenderers/Wrappers/ReplaceTests.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "623" }, { "name": "C#", "bytes": "5114924" }, { "name": "Perl", "bytes": "1590" }, { "name": "PowerShell", "bytes": "7258" } ], "symlink_target": "" }
cargo install wasm-pack wasm-pack build cd www npm install npm run start
{ "content_hash": "6986d54a1041902ae67fa11ff99cae7c", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 23, "avg_line_length": 14.6, "alnum_prop": 0.8082191780821918, "repo_name": "codetojoy/gists", "id": "2e6539f908598ae74db01c2643a085ce30de75c7", "size": "86", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "rust/wasm_sandbox_jul_2020/go.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "46260" }, { "name": "COBOL", "bytes": "15628" }, { "name": "CSS", "bytes": "3829" }, { "name": "Dart", "bytes": "28274" }, { "name": "Dockerfile", "bytes": "19" }, { "name": "Gherkin", "bytes": "3390" }, { "name": "Go", "bytes": "18007" }, { "name": "Groovy", "bytes": "32124" }, { "name": "HTML", "bytes": "13400" }, { "name": "Java", "bytes": "185190" }, { "name": "JavaScript", "bytes": "73794" }, { "name": "PowerShell", "bytes": "4196" }, { "name": "Python", "bytes": "19980" }, { "name": "Rust", "bytes": "106229" }, { "name": "Scala", "bytes": "484" }, { "name": "Shell", "bytes": "37667" }, { "name": "TypeScript", "bytes": "1182" } ], "symlink_target": "" }
<html> <head> <title>User agent detail - Mozilla/5.0 (Linux; U; Android 2.3.6; En-us; Cloudfone Thrill 400g Build/VENUS_00.03.150.H1105) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Mozilla/5.0 (Linux; U; Android 2.3.6; En-us; Cloudfone Thrill 400g Build/VENUS_00.03.150.H1105) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>ua-parser/uap-core<br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td> </td><td> </td><td style="border-left: 1px solid #555">Cloudfone</td><td>Cloudfone Thrill 400g</td><td></td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a> <!-- Modal Structure --> <div id="modal-test" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Testsuite result detail</h4> <p><pre><code class="php">Array ( [user_agent_string] => Mozilla/5.0 (Linux; U; Android 2.3.6; En-us; Cloudfone Thrill 400g Build/VENUS_00.03.150.H1105) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 [family] => Cloudfone Thrill 400g [brand] => Cloudfone [model] => Cloudfone Thrill 400g ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td><td>Android 4.0</td><td>WebKit </td><td>Android 2.3</td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.018</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-215ac98d-ccf8-4615-916e-5a819d6a59c9">Detail</a> <!-- Modal Structure --> <div id="modal-215ac98d-ccf8-4615-916e-5a819d6a59c9" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.2\.3.* build\/.*\).*applewebkit\/.*\(.*khtml,.*like gecko.*\).*version\/4\.0.*safari.*$/ [browser_name_pattern] => mozilla/5.0 (*linux*android?2.3* build/*)*applewebkit/*(*khtml,*like gecko*)*version/4.0*safari* [parent] => Android Browser 4.0 [comment] => Android Browser 4.0 [browser] => Android [browser_type] => Browser [browser_bits] => 32 [browser_maker] => Google Inc [browser_modus] => unknown [version] => 4.0 [majorver] => 4 [minorver] => 0 [platform] => Android [platform_version] => 2.3 [platform_description] => Android OS [platform_bits] => 32 [platform_maker] => Google Inc [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [javascript] => 1 [vbscript] => [javaapplets] => 1 [activexcontrols] => [ismobiledevice] => 1 [istablet] => [issyndicationreader] => [crawler] => [cssversion] => 3 [aolversion] => 0 [device_name] => general Mobile Phone [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => touchscreen [device_code_name] => general Mobile Phone [device_brand_name] => unknown [renderingengine_name] => WebKit [renderingengine_version] => unknown [renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3. [renderingengine_maker] => Apple Inc ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.0</small></td><td>Android Browser 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661">Detail</a> <!-- Modal Structure --> <div id="modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => Android [browser] => Android Browser [version] => 4.0 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small></td><td>Android Webkit 4.0</td><td><i class="material-icons">close</i></td><td>Android 2.3.6</td><td style="border-left: 1px solid #555">Generic</td><td>Android 2.3</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.28503</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc">Detail</a> <!-- Modal Structure --> <div id="modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 480 [is_mobile] => 1 [type] => mobile-browser [mobile_brand] => Generic [mobile_model] => Android 2.3 [version] => 4.0 [is_android] => 1 [browser_name] => Android Webkit [operating_system_family] => Android [operating_system_version] => 2.3.6 [is_ios] => [producer] => Google Inc. [operating_system] => Android 2.3.x Gingerbread [mobile_screen_width] => 320 [mobile_browser] => Android Webkit ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.5.2</small></td><td>Android Browser </td><td>WebKit </td><td>Android 2.3</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.006</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-21638055-738d-46ba-a1b1-f5114bc26475">Detail</a> <!-- Modal Structure --> <div id="modal-21638055-738d-46ba-a1b1-f5114bc26475" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => Array ( [type] => browser [name] => Android Browser [short_name] => AN [version] => [engine] => WebKit ) [operatingSystem] => Array ( [name] => Android [short_name] => AND [version] => 2.3 [platform] => ) [device] => Array ( [brand] => [brandName] => [model] => [device] => [deviceName] => ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => 1 [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => [isTablet] => [isTV] => [isDesktop] => [isMobile] => 1 [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.0</small></td><td>Navigator 4.0</td><td><i class="material-icons">close</i></td><td>Android 2.3.6</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c">Detail</a> <!-- Modal Structure --> <div id="modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>SinergiBrowserDetector result detail</h4> <p><pre><code class="php">Array ( [browser] => Sinergi\BrowserDetector\Browser Object ( [userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 2.3.6; En-us; Cloudfone Thrill 400g Build/VENUS_00.03.150.H1105) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 ) [name:Sinergi\BrowserDetector\Browser:private] => Navigator [version:Sinergi\BrowserDetector\Browser:private] => 4.0 [isRobot:Sinergi\BrowserDetector\Browser:private] => [isChromeFrame:Sinergi\BrowserDetector\Browser:private] => ) [operatingSystem] => Sinergi\BrowserDetector\Os Object ( [name:Sinergi\BrowserDetector\Os:private] => Android [version:Sinergi\BrowserDetector\Os:private] => 2.3.6 [isMobile:Sinergi\BrowserDetector\Os:private] => 1 [userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 2.3.6; En-us; Cloudfone Thrill 400g Build/VENUS_00.03.150.H1105) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 ) ) [device] => Sinergi\BrowserDetector\Device Object ( [name:Sinergi\BrowserDetector\Device:private] => unknown [userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; U; Android 2.3.6; En-us; Cloudfone Thrill 400g Build/VENUS_00.03.150.H1105) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 ) ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UAParser<br /><small>v3.4.5</small></td><td>Android 2.3.6</td><td><i class="material-icons">close</i></td><td>Android 2.3.6</td><td style="border-left: 1px solid #555">Cloudfone</td><td>Cloudfone Thrill 400g</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.002</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b">Detail</a> <!-- Modal Structure --> <div id="modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => 2 [minor] => 3 [patch] => 6 [family] => Android ) [os] => UAParser\Result\OperatingSystem Object ( [major] => 2 [minor] => 3 [patch] => 6 [patchMinor] => [family] => Android ) [device] => UAParser\Result\Device Object ( [brand] => Cloudfone [model] => Cloudfone Thrill 400g [family] => Cloudfone Thrill 400g ) [originalUserAgent] => Mozilla/5.0 (Linux; U; Android 2.3.6; En-us; Cloudfone Thrill 400g Build/VENUS_00.03.150.H1105) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small></td><td>Android Webkit Browser </td><td><i class="material-icons">close</i></td><td>Android 2.3.6</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.09501</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4">Detail</a> <!-- Modal Structure --> <div id="modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentStringCom result detail</h4> <p><pre><code class="php">stdClass Object ( [agent_type] => Browser [agent_name] => Android Webkit Browser [agent_version] => -- [os_type] => Android [os_name] => Android [os_versionName] => [os_versionNumber] => 2.3.6 [os_producer] => [os_producerURL] => [linux_distibution] => Null [agent_language] => English - United States [agent_languageTag] => En-us ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small></td><td>Android Browser 4.0</td><td>WebKit 533.1</td><td>Android 2.3.6</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.44104</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9795f66f-7271-430e-973a-a5c0e14dc35a">Detail</a> <!-- Modal Structure --> <div id="modal-9795f66f-7271-430e-973a-a5c0e14dc35a" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => Android [simple_sub_description_string] => [simple_browser_string] => Android Browser 4 on Android (Gingerbread) [browser_version] => 4 [extra_info] => Array ( ) [operating_platform] => [extra_info_table] => stdClass Object ( [System Build] => Venus ) [layout_engine_name] => WebKit [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => android-browser [operating_system_version] => Gingerbread [simple_operating_platform_string] => [is_abusive] => [layout_engine_version] => 533.1 [browser_capabilities] => Array ( ) [operating_platform_vendor_name] => [operating_system] => Android (Gingerbread) [operating_system_version_full] => 2.3.6 [operating_platform_code] => [browser_name] => Android Browser [operating_system_name_code] => android [user_agent] => Mozilla/5.0 (Linux; U; Android 2.3.6; En-us; Cloudfone Thrill 400g Build/VENUS_00.03.150.H1105) AppleWebKit/533.1 (KHTML, Like Gecko) Version/4.0 Mobile Safari/533.1 [browser_version_full] => 4.0 [browser] => Android Browser 4 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>2.0.10</small></td><td>Android Browser </td><td>Webkit 533.1</td><td>Android 2.3.6</td><td style="border-left: 1px solid #555">Cloudfone</td><td>Thrill 400g</td><td>mobile:smart</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.012</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4">Detail</a> <!-- Modal Structure --> <div id="modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [name] => Android Browser ) [engine] => Array ( [name] => Webkit [version] => 533.1 ) [os] => Array ( [name] => Android [version] => 2.3.6 ) [device] => Array ( [type] => mobile [subtype] => smart [manufacturer] => Cloudfone [model] => Thrill 400g ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small></td><td>Safari 4.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>smartphone</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-3f285ff5-314b-4db4-9948-54572e92e7b6">Detail</a> <!-- Modal Structure --> <div id="modal-3f285ff5-314b-4db4-9948-54572e92e7b6" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Woothee result detail</h4> <p><pre><code class="php">Array ( [name] => Safari [vendor] => Apple [version] => 4.0 [category] => smartphone [os] => Android [os_version] => 2.3.6 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Wurfl<br /><small>1.6.4</small></td><td>Android Webkit 2.3</td><td><i class="material-icons">close</i></td><td>Android 2.3</td><td style="border-left: 1px solid #555"></td><td></td><td>Smartphone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.047</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-1a1aee36-7ce7-4111-a391-8e2c501f1532">Detail</a> <!-- Modal Structure --> <div id="modal-1a1aee36-7ce7-4111-a391-8e2c501f1532" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => true [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => false [is_largescreen] => false [is_mobile] => true [is_robot] => false [is_smartphone] => true [is_touchscreen] => true [is_wml_preferred] => false [is_xhtmlmp_preferred] => false [is_html_preferred] => true [advertised_device_os] => Android [advertised_device_os_version] => 2.3 [advertised_browser] => Android Webkit [advertised_browser_version] => 2.3 [complete_device_name] => Generic Android 2.3 [form_factor] => Smartphone [is_phone] => true [is_app_webview] => false ) [all] => Array ( [brand_name] => Generic [model_name] => Android 2.3 [unique] => true [ununiqueness_handler] => [is_wireless_device] => true [device_claims_web_support] => true [has_qwerty_keyboard] => true [can_skip_aligned_link_row] => true [uaprof] => [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => Android [mobile_browser] => Android Webkit [mobile_browser_version] => [device_os_version] => 2.3 [pointing_method] => touchscreen [release_date] => 2010_november [marketing_name] => [model_extra_info] => [nokia_feature_pack] => 0 [can_assign_phone_number] => true [is_tablet] => false [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => true [softkey_support] => false [table_support] => true [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => true [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => true [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => true [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => wtai://wp/mc; [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => false [xhtml_honors_bgcolor] => true [xhtml_supports_forms_in_table] => true [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => false [xhtml_select_as_radiobutton] => false [xhtml_select_as_popup] => false [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => true [xhtml_supports_css_cell_table_coloring] => true [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => true [xhtml_document_title_support] => true [xhtml_preferred_charset] => iso-8859-1 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => tel: [xhtmlmp_preferred_mime_type] => text/html [xhtml_table_support] => true [xhtml_send_sms_string] => sms: [xhtml_send_mms_string] => mms: [xhtml_file_upload] => supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => full [xhtml_avoid_accesskeys] => true [xhtml_can_embed_video] => none [ajax_support_javascript] => true [ajax_manipulate_css] => true [ajax_support_getelementbyid] => true [ajax_support_inner_html] => true [ajax_xhr_type] => standard [ajax_manipulate_dom] => true [ajax_support_events] => true [ajax_support_event_listener] => true [ajax_preferred_geoloc_api] => w3c_api [xhtml_support_level] => 4 [preferred_markup] => html_web_4_0 [wml_1_1] => false [wml_1_2] => false [wml_1_3] => false [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => true [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => true [html_web_4_0] => true [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 320 [resolution_height] => 480 [columns] => 60 [max_image_width] => 320 [max_image_height] => 400 [rows] => 40 [physical_screen_width] => 34 [physical_screen_height] => 50 [dual_orientation] => true [density_class] => 1.0 [wbmp] => true [bmp] => false [epoc_bmp] => false [gif_animated] => false [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => true [transparent_png_index] => true [svgt_1_1] => false [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 65536 [webp_lossy_support] => false [webp_lossless_support] => false [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => false [wta_voice_call] => false [wta_phonebook] => false [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 384 [wifi] => true [sdio] => false [vpn] => false [has_cellular_radio] => true [max_deck_size] => 2000000 [max_url_length_in_requests] => 256 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => true [inline_support] => false [oma_support] => true [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => true [streaming_3gpp] => true [streaming_mp4] => true [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => 10 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => 2 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => 3.0 [streaming_acodec_amr] => nb [streaming_acodec_aac] => lc [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => progressive_download [wap_push_support] => false [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => true [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 0 [mms_max_height] => 0 [mms_max_width] => 0 [built_in_recorder] => false [built_in_camera] => true [mms_jpeg_baseline] => false [mms_jpeg_progressive] => false [mms_gif_static] => false [mms_gif_animated] => false [mms_png] => false [mms_bmp] => false [mms_wbmp] => false [mms_amr] => false [mms_wav] => false [mms_midi_monophonic] => false [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => false [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => false [mms_jad] => false [mms_vcard] => false [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => true [wav] => false [mmf] => false [smf] => false [mld] => false [midi_monophonic] => false [midi_polyphonic] => false [sp_midi] => false [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => false [au] => false [amr] => false [awb] => false [aac] => true [mp3] => true [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => true [css_supports_width_as_percentage] => true [css_border_image] => webkit [css_rounded_corners] => webkit [css_gradient] => none [css_spriting] => true [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => true [progressive_download] => true [playback_vcodec_h263_0] => 10 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => 0 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => 3.0 [playback_real_media] => none [playback_3gpp] => true [playback_3g2] => false [playback_mp4] => true [playback_mov] => false [playback_acodec_amr] => nb [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => true [html_preferred_dtd] => html4 [viewport_supported] => true [viewport_width] => device_width_token [viewport_userscalable] => no [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => full [image_inlining] => true [is_smarttv] => false [is_console] => false [nfc_support] => false [ux_full_desktop] => false [jqm_grade] => A [is_sencha_touch_ok] => false [controlcap_is_smartphone] => default [controlcap_is_ios] => default [controlcap_is_android] => default [controlcap_is_robot] => default [controlcap_is_app] => default [controlcap_advertised_device_os] => default [controlcap_advertised_device_os_version] => default [controlcap_advertised_browser] => default [controlcap_advertised_browser_version] => default [controlcap_is_windows_phone] => default [controlcap_is_full_desktop] => default [controlcap_is_largescreen] => default [controlcap_is_mobile] => default [controlcap_is_touchscreen] => default [controlcap_is_wml_preferred] => default [controlcap_is_xhtmlmp_preferred] => default [controlcap_is_html_preferred] => default [controlcap_form_factor] => default [controlcap_complete_device_name] => default ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-02-13 13:39:58</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
{ "content_hash": "d9eb37e5cdb6667415690f30f32ae826", "timestamp": "", "source": "github", "line_count": 1122, "max_line_length": 765, "avg_line_length": 41.655080213903744, "alnum_prop": 0.5399790316023707, "repo_name": "ThaDafinser/UserAgentParserComparison", "id": "641af72f1abdcdf5c60c1274d23d743df4f7c5a5", "size": "46738", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "v4/user-agent-detail/cf/a4/cfa47458-3dd3-4650-96c2-fbbd6c2dc0d7.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2060859160" } ], "symlink_target": "" }
... ![CC BY-SA 4.0](cc-by-sa-80x15.png "Creative Commons Attribution-ShareAlike 4.0 International")
{ "content_hash": "7ca237284896381afc4a091b2bb2b4b6", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 95, "avg_line_length": 33.666666666666664, "alnum_prop": 0.7227722772277227, "repo_name": "jpommerening/midiboy", "id": "d2090128c5abeca26fc49968a9e356a2ecf13aee", "size": "114", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/schematic.md", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "12985" }, { "name": "Makefile", "bytes": "582" } ], "symlink_target": "" }
<?php /** * Created by PhpStorm. * User: gseidel * Date: 2019-09-06 * Time: 12:58 */ namespace Enhavo\Bundle\CommentBundle\Model; use Doctrine\Common\Collections\Collection; interface ThreadInterface { /** * @param CommentSubjectInterface|null $subject * @return mixed */ public function setSubject(?CommentSubjectInterface $subject); /** * @return CommentSubjectInterface|null */ public function getSubject(): ?CommentSubjectInterface; /** * @param CommentInterface $comment */ public function addComment(CommentInterface $comment); /** * @param CommentInterface $comment */ public function removeComment(CommentInterface $comment); /** * @return CommentInterface[]|Collection */ public function getComments(): Collection; /** * @return bool */ public function isEnable(): bool; /** * @param bool $enable */ public function setEnable(bool $enable): void; }
{ "content_hash": "1662eba12d7e4c89736c2ceeeac14bca", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 66, "avg_line_length": 20.06, "alnum_prop": 0.6420737786640079, "repo_name": "npakai/enhavo", "id": "1c7124c2b169967a0e3f0e6a00d6125c432c5a26", "size": "1003", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/Enhavo/Bundle/CommentBundle/Model/ThreadInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "81970" }, { "name": "Dockerfile", "bytes": "2165" }, { "name": "Gherkin", "bytes": "11978" }, { "name": "HTML", "bytes": "195018" }, { "name": "JavaScript", "bytes": "3103" }, { "name": "Makefile", "bytes": "233" }, { "name": "PHP", "bytes": "2118492" }, { "name": "Ruby", "bytes": "1164" }, { "name": "Shell", "bytes": "579" }, { "name": "TypeScript", "bytes": "14563" } ], "symlink_target": "" }
$(document).ready(function() { $('#school_content').hide(); $('#project_content').hide(); $('#school').removeClass('active'); $('#projects').removeClass('active'); $('#home').click(function() { $('#school_content').hide(); $('#project_content').hide(); $('#home').addClass('active'); $('#school').removeClass('active'); $('#projects').removeClass('active'); }); $('#school').click(function() { $('#school_content').show(); $('#project_content').hide(); $('#home').removeClass('active'); $('#school').addClass('active'); $('#projects').removeClass('active'); }); $('#projects').click(function() { $('#school_content').hide(); $('#project_content').show(); $('#home').removeClass('active'); $('#school').removeClass('active'); $('#projects').addClass('active'); }); });
{ "content_hash": "6580ef7d04852283c98a48df7e9d08c7", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 39, "avg_line_length": 26.161290322580644, "alnum_prop": 0.5721331689272503, "repo_name": "jordanbang/jordanbang.github.io", "id": "e1551e264e95dc05c2bd9eba189ecb8808beff03", "size": "811", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "custom.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "68852" }, { "name": "HTML", "bytes": "58170" }, { "name": "JavaScript", "bytes": "53349" }, { "name": "Ruby", "bytes": "2179" } ], "symlink_target": "" }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "bindings/core/v8/ScriptStreamer.h" #include "bindings/core/v8/ScriptSourceCode.h" #include "bindings/core/v8/ScriptStreamerThread.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8BindingForTesting.h" #include "bindings/core/v8/V8ScriptRunner.h" #include "core/dom/Element.h" #include "core/dom/PendingScript.h" #include "core/frame/Settings.h" #include "platform/heap/Handle.h" #include "platform/testing/UnitTestHelpers.h" #include "public/platform/Platform.h" #include "public/platform/WebScheduler.h" #include "testing/gtest/include/gtest/gtest.h" #include <v8.h> namespace blink { namespace { class ScriptStreamingTest : public ::testing::Test { public: ScriptStreamingTest() : m_loadingTaskRunner(Platform::current()->currentThread()->scheduler()->loadingTaskRunner()) , m_scope(v8::Isolate::GetCurrent()) , m_settings(Settings::create()) , m_resourceRequest("http://www.streaming-test.com/") , m_resource(ScriptResource::create(m_resourceRequest, "UTF-8")) , m_pendingScript(PendingScript::create(0, m_resource.get())) { m_resource->setLoading(true); m_pendingScript = PendingScript::create(0, m_resource.get()); ScriptStreamer::setSmallScriptThresholdForTesting(0); } ScriptState* getScriptState() const { return m_scope.getScriptState(); } v8::Isolate* isolate() const { return m_scope.isolate(); } PendingScript* getPendingScript() const { return m_pendingScript.get(); } protected: void appendData(const char* data) { m_resource->appendData(data, strlen(data)); // Yield control to the background thread, so that V8 gets a chance to // process the data before the main thread adds more. Note that we // cannot fully control in what kind of chunks the data is passed to V8 // (if V8 is not requesting more data between two appendData calls, it // will get both chunks together). testing::yieldCurrentThread(); } void appendPadding() { for (int i = 0; i < 10; ++i) { appendData(" /* this is padding to make the script long enough, so " "that V8's buffer gets filled and it starts processing " "the data */ "); } } void finish() { m_resource->finish(); m_resource->setLoading(false); } void processTasksUntilStreamingComplete() { while (ScriptStreamerThread::shared()->isRunningTask()) { testing::runPendingTasks(); } // Once more, because the "streaming complete" notification might only // now be in the task queue. testing::runPendingTasks(); } WebTaskRunner* m_loadingTaskRunner; // NOT OWNED V8TestingScope m_scope; OwnPtr<Settings> m_settings; // The Resource and PendingScript where we stream from. These don't really // fetch any data outside the test; the test controls the data by calling // ScriptResource::appendData. ResourceRequest m_resourceRequest; RefPtrWillBePersistent<ScriptResource> m_resource; OwnPtrWillBePersistent<PendingScript> m_pendingScript; }; class TestScriptResourceClient : public ScriptResourceClient { public: TestScriptResourceClient() : m_finished(false) { } void notifyFinished(Resource*) override { m_finished = true; } String debugName() const override { return "TestScriptResourceClient"; } bool finished() const { return m_finished; } private: bool m_finished; }; #if OS(MACOSX) && defined(ADDRESS_SANITIZER) // TODO(marja): Fix this test, http://crbug.com/572987 #define MAYBE_CompilingStreamedScript DISABLED_CompilingStreamedScript #else #define MAYBE_CompilingStreamedScript CompilingStreamedScript #endif TEST_F(ScriptStreamingTest, MAYBE_CompilingStreamedScript) { // Test that we can successfully compile a streamed script. ScriptStreamer::startStreaming(getPendingScript(), ScriptStreamer::ParsingBlocking, m_settings.get(), m_scope.getScriptState(), m_loadingTaskRunner); TestScriptResourceClient client; getPendingScript()->watchForLoad(&client); appendData("function foo() {"); appendPadding(); appendData("return 5; }"); appendPadding(); appendData("foo();"); EXPECT_FALSE(client.finished()); finish(); // Process tasks on the main thread until the streaming background thread // has completed its tasks. processTasksUntilStreamingComplete(); EXPECT_TRUE(client.finished()); bool errorOccurred = false; ScriptSourceCode sourceCode = getPendingScript()->getSource(KURL(), errorOccurred); EXPECT_FALSE(errorOccurred); EXPECT_TRUE(sourceCode.streamer()); v8::TryCatch tryCatch(isolate()); v8::Local<v8::Script> script; EXPECT_TRUE(V8ScriptRunner::compileScript(sourceCode, isolate()).ToLocal(&script)); EXPECT_FALSE(tryCatch.HasCaught()); } TEST_F(ScriptStreamingTest, CompilingStreamedScriptWithParseError) { // Test that scripts with parse errors are handled properly. In those cases, // the V8 side typically finished before loading finishes: make sure we // handle it gracefully. ScriptStreamer::startStreaming(getPendingScript(), ScriptStreamer::ParsingBlocking, m_settings.get(), m_scope.getScriptState(), m_loadingTaskRunner); TestScriptResourceClient client; getPendingScript()->watchForLoad(&client); appendData("function foo() {"); appendData("this is the part which will be a parse error"); // V8 won't realize the parse error until it actually starts parsing the // script, and this happens only when its buffer is filled. appendPadding(); EXPECT_FALSE(client.finished()); // Force the V8 side to finish before the loading. processTasksUntilStreamingComplete(); EXPECT_FALSE(client.finished()); finish(); EXPECT_TRUE(client.finished()); bool errorOccurred = false; ScriptSourceCode sourceCode = getPendingScript()->getSource(KURL(), errorOccurred); EXPECT_FALSE(errorOccurred); EXPECT_TRUE(sourceCode.streamer()); v8::TryCatch tryCatch(isolate()); v8::Local<v8::Script> script; EXPECT_FALSE(V8ScriptRunner::compileScript(sourceCode, isolate()).ToLocal(&script)); EXPECT_TRUE(tryCatch.HasCaught()); } TEST_F(ScriptStreamingTest, CancellingStreaming) { // Test that the upper layers (PendingScript and up) can be ramped down // while streaming is ongoing, and ScriptStreamer handles it gracefully. ScriptStreamer::startStreaming(getPendingScript(), ScriptStreamer::ParsingBlocking, m_settings.get(), m_scope.getScriptState(), m_loadingTaskRunner); TestScriptResourceClient client; getPendingScript()->watchForLoad(&client); appendData("function foo() {"); // In general, we cannot control what the background thread is doing // (whether it's parsing or waiting for more data). In this test, we have // given it so little data that it's surely waiting for more. // Simulate cancelling the network load (e.g., because the user navigated // away). EXPECT_FALSE(client.finished()); getPendingScript()->stopWatchingForLoad(); getPendingScript()->releaseElementAndClear(); m_pendingScript = nullptr; // This will destroy m_resource. m_resource = nullptr; // The V8 side will complete too. This should not crash. We don't receive // any results from the streaming and the client doesn't get notified. processTasksUntilStreamingComplete(); EXPECT_FALSE(client.finished()); } TEST_F(ScriptStreamingTest, SuppressingStreaming) { // If we notice during streaming that there is a code cache, streaming // is suppressed (V8 doesn't parse while the script is loading), and the // upper layer (ScriptResourceClient) should get a notification when the // script is loaded. ScriptStreamer::startStreaming(getPendingScript(), ScriptStreamer::ParsingBlocking, m_settings.get(), m_scope.getScriptState(), m_loadingTaskRunner); TestScriptResourceClient client; getPendingScript()->watchForLoad(&client); appendData("function foo() {"); appendPadding(); CachedMetadataHandler* cacheHandler = m_resource->cacheHandler(); EXPECT_TRUE(cacheHandler); cacheHandler->setCachedMetadata(V8ScriptRunner::tagForCodeCache(cacheHandler), "X", 1, CachedMetadataHandler::CacheLocally); appendPadding(); finish(); processTasksUntilStreamingComplete(); EXPECT_TRUE(client.finished()); bool errorOccurred = false; ScriptSourceCode sourceCode = getPendingScript()->getSource(KURL(), errorOccurred); EXPECT_FALSE(errorOccurred); // ScriptSourceCode doesn't refer to the streamer, since we have suppressed // the streaming and resumed the non-streaming code path for script // compilation. EXPECT_FALSE(sourceCode.streamer()); } TEST_F(ScriptStreamingTest, EmptyScripts) { // Empty scripts should also be streamed properly, that is, the upper layer // (ScriptResourceClient) should be notified when an empty script has been // loaded. ScriptStreamer::startStreaming(getPendingScript(), ScriptStreamer::ParsingBlocking, m_settings.get(), m_scope.getScriptState(), m_loadingTaskRunner); TestScriptResourceClient client; getPendingScript()->watchForLoad(&client); // Finish the script without sending any data. finish(); // The finished notification should arrive immediately and not be cycled // through a background thread. EXPECT_TRUE(client.finished()); bool errorOccurred = false; ScriptSourceCode sourceCode = getPendingScript()->getSource(KURL(), errorOccurred); EXPECT_FALSE(errorOccurred); EXPECT_FALSE(sourceCode.streamer()); } TEST_F(ScriptStreamingTest, SmallScripts) { // Small scripts shouldn't be streamed. ScriptStreamer::setSmallScriptThresholdForTesting(100); ScriptStreamer::startStreaming(getPendingScript(), ScriptStreamer::ParsingBlocking, m_settings.get(), m_scope.getScriptState(), m_loadingTaskRunner); TestScriptResourceClient client; getPendingScript()->watchForLoad(&client); appendData("function foo() { }"); finish(); // The finished notification should arrive immediately and not be cycled // through a background thread. EXPECT_TRUE(client.finished()); bool errorOccurred = false; ScriptSourceCode sourceCode = getPendingScript()->getSource(KURL(), errorOccurred); EXPECT_FALSE(errorOccurred); EXPECT_FALSE(sourceCode.streamer()); } #if OS(MACOSX) && defined(ADDRESS_SANITIZER) // TODO(marja): Fix this test, http://crbug.com/572987 #define MAYBE_ScriptsWithSmallFirstChunk DISABLED_ScriptsWithSmallFirstChunk #else #define MAYBE_ScriptsWithSmallFirstChunk ScriptsWithSmallFirstChunk #endif TEST_F(ScriptStreamingTest, MAYBE_ScriptsWithSmallFirstChunk) { // If a script is long enough, if should be streamed, even if the first data // chunk is small. ScriptStreamer::setSmallScriptThresholdForTesting(100); ScriptStreamer::startStreaming(getPendingScript(), ScriptStreamer::ParsingBlocking, m_settings.get(), m_scope.getScriptState(), m_loadingTaskRunner); TestScriptResourceClient client; getPendingScript()->watchForLoad(&client); // This is the first data chunk which is small. appendData("function foo() { }"); appendPadding(); appendPadding(); appendPadding(); finish(); processTasksUntilStreamingComplete(); EXPECT_TRUE(client.finished()); bool errorOccurred = false; ScriptSourceCode sourceCode = getPendingScript()->getSource(KURL(), errorOccurred); EXPECT_FALSE(errorOccurred); EXPECT_TRUE(sourceCode.streamer()); v8::TryCatch tryCatch(isolate()); v8::Local<v8::Script> script; EXPECT_TRUE(V8ScriptRunner::compileScript(sourceCode, isolate()).ToLocal(&script)); EXPECT_FALSE(tryCatch.HasCaught()); } #if OS(MACOSX) && defined(ADDRESS_SANITIZER) // TODO(marja): Fix this test, http://crbug.com/572987 #define MAYBE_EncodingChanges DISABLED_EncodingChanges #else #define MAYBE_EncodingChanges EncodingChanges #endif TEST_F(ScriptStreamingTest, MAYBE_EncodingChanges) { // It's possible that the encoding of the Resource changes after we start // loading it. m_resource->setEncoding("windows-1252"); ScriptStreamer::startStreaming(getPendingScript(), ScriptStreamer::ParsingBlocking, m_settings.get(), m_scope.getScriptState(), m_loadingTaskRunner); TestScriptResourceClient client; getPendingScript()->watchForLoad(&client); m_resource->setEncoding("UTF-8"); // \xec\x92\x81 are the raw bytes for \uc481. appendData("function foo() { var foob\xec\x92\x81r = 13; return foob\xec\x92\x81r; } foo();"); finish(); processTasksUntilStreamingComplete(); EXPECT_TRUE(client.finished()); bool errorOccurred = false; ScriptSourceCode sourceCode = getPendingScript()->getSource(KURL(), errorOccurred); EXPECT_FALSE(errorOccurred); EXPECT_TRUE(sourceCode.streamer()); v8::TryCatch tryCatch(isolate()); v8::Local<v8::Script> script; EXPECT_TRUE(V8ScriptRunner::compileScript(sourceCode, isolate()).ToLocal(&script)); EXPECT_FALSE(tryCatch.HasCaught()); } #if OS(MACOSX) && defined(ADDRESS_SANITIZER) // TODO(marja): Fix this test, http://crbug.com/572987 #define MAYBE_EncodingFromBOM DISABLED_EncodingFromBOM #else #define MAYBE_EncodingFromBOM EncodingFromBOM #endif TEST_F(ScriptStreamingTest, MAYBE_EncodingFromBOM) { // Byte order marks should be removed before giving the data to V8. They // will also affect encoding detection. m_resource->setEncoding("windows-1252"); // This encoding is wrong on purpose. ScriptStreamer::startStreaming(getPendingScript(), ScriptStreamer::ParsingBlocking, m_settings.get(), m_scope.getScriptState(), m_loadingTaskRunner); TestScriptResourceClient client; getPendingScript()->watchForLoad(&client); // \xef\xbb\xbf is the UTF-8 byte order mark. \xec\x92\x81 are the raw bytes // for \uc481. appendData("\xef\xbb\xbf function foo() { var foob\xec\x92\x81r = 13; return foob\xec\x92\x81r; } foo();"); finish(); processTasksUntilStreamingComplete(); EXPECT_TRUE(client.finished()); bool errorOccurred = false; ScriptSourceCode sourceCode = getPendingScript()->getSource(KURL(), errorOccurred); EXPECT_FALSE(errorOccurred); EXPECT_TRUE(sourceCode.streamer()); v8::TryCatch tryCatch(isolate()); v8::Local<v8::Script> script; EXPECT_TRUE(V8ScriptRunner::compileScript(sourceCode, isolate()).ToLocal(&script)); EXPECT_FALSE(tryCatch.HasCaught()); } } // namespace } // namespace blink
{ "content_hash": "a0c1751986e079f2700d6053c8b1e5c6", "timestamp": "", "source": "github", "line_count": 384, "max_line_length": 153, "avg_line_length": 38.661458333333336, "alnum_prop": 0.719318334905025, "repo_name": "highweb-project/highweb-webcl-html5spec", "id": "8f91bcfe6a1c539b470a96a0ed4e5c85e30f1ab4", "size": "14846", "binary": false, "copies": "1", "ref": "refs/heads/highweb-20160310", "path": "third_party/WebKit/Source/bindings/core/v8/ScriptStreamerTest.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <title>Uses of Interface org.apache.poi.ss.formula.functions.Function3Arg (POI API Documentation)</title> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.apache.poi.ss.formula.functions.Function3Arg (POI API Documentation)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/poi/ss/formula/functions/Function3Arg.html" title="interface in org.apache.poi.ss.formula.functions">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/poi/ss/formula/functions//class-useFunction3Arg.html" target="_top">FRAMES</a></li> <li><a href="Function3Arg.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface org.apache.poi.ss.formula.functions.Function3Arg" class="title">Uses of Interface<br>org.apache.poi.ss.formula.functions.Function3Arg</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../org/apache/poi/ss/formula/functions/Function3Arg.html" title="interface in org.apache.poi.ss.formula.functions">Function3Arg</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.poi.ss.formula.functions">org.apache.poi.ss.formula.functions</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.poi.ss.formula.functions"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/apache/poi/ss/formula/functions/Function3Arg.html" title="interface in org.apache.poi.ss.formula.functions">Function3Arg</a> in <a href="../../../../../../../org/apache/poi/ss/formula/functions/package-summary.html">org.apache.poi.ss.formula.functions</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../../org/apache/poi/ss/formula/functions/package-summary.html">org.apache.poi.ss.formula.functions</a> that implement <a href="../../../../../../../org/apache/poi/ss/formula/functions/Function3Arg.html" title="interface in org.apache.poi.ss.formula.functions">Function3Arg</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/Complex.html" title="class in org.apache.poi.ss.formula.functions">Complex</a></strong></code> <div class="block">Implementation for Excel COMPLEX () function.<p/> <p/> <b>Syntax</b>:<br/> <b>COMPLEX </b>(<b>real_num</b>,<b>i_num</b>,<b>suffix </b> )<br/> <p/> Converts real and imaginary coefficients into a complex number of the form x + yi or x + yj.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/DateFunc.html" title="class in org.apache.poi.ss.formula.functions">DateFunc</a></strong></code> <div class="block">Implementation for the Excel function DATE</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/Days360.html" title="class in org.apache.poi.ss.formula.functions">Days360</a></strong></code> <div class="block">Calculates the number of days between two dates based on a 360-day year (twelve 30-day months), which is used in some accounting calculations.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/FinanceFunction.html" title="class in org.apache.poi.ss.formula.functions">FinanceFunction</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/Fixed.html" title="class in org.apache.poi.ss.formula.functions">Fixed</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/Fixed3ArgFunction.html" title="class in org.apache.poi.ss.formula.functions">Fixed3ArgFunction</a></strong></code> <div class="block">Convenience base class for functions that must take exactly three arguments.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/Hlookup.html" title="class in org.apache.poi.ss.formula.functions">Hlookup</a></strong></code> <div class="block">Implementation of the HLOOKUP() function.<p/> HLOOKUP finds a column in a lookup table by the first row value and returns the value from another row.<br/> <b>Syntax</b>:<br/> <b>HLOOKUP</b>(<b>lookup_value</b>, <b>table_array</b>, <b>row_index_num</b>, range_lookup)<p/> <b>lookup_value</b> The value to be found in the first column of the table array.<br/> <b>table_array</b> An area reference for the lookup data.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/IfFunc.html" title="class in org.apache.poi.ss.formula.functions">IfFunc</a></strong></code> <div class="block">Implementation for the Excel function IF</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/Index.html" title="class in org.apache.poi.ss.formula.functions">Index</a></strong></code> <div class="block">Implementation for the Excel function INDEX</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/Lookup.html" title="class in org.apache.poi.ss.formula.functions">Lookup</a></strong></code> <div class="block">Implementation of Excel function LOOKUP.<p/> LOOKUP finds an index row in a lookup table by the first column value and returns the value from another column.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/Match.html" title="class in org.apache.poi.ss.formula.functions">Match</a></strong></code> <div class="block">Implementation for the MATCH() Excel function.<p/> <b>Syntax:</b><br/> <b>MATCH</b>(<b>lookup_value</b>, <b>lookup_array</b>, match_type)<p/> Returns a 1-based index specifying at what position in the <b>lookup_array</b> the specified <b>lookup_value</b> is found.<p/> Specific matching behaviour can be modified with the optional <b>match_type</b> parameter.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/Rank.html" title="class in org.apache.poi.ss.formula.functions">Rank</a></strong></code> <div class="block">Returns the rank of a number in a list of numbers.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/Substitute.html" title="class in org.apache.poi.ss.formula.functions">Substitute</a></strong></code> <div class="block">An implementation of the SUBSTITUTE function:<P/> Substitutes text in a text string with new text, some number of times.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/Sumif.html" title="class in org.apache.poi.ss.formula.functions">Sumif</a></strong></code> <div class="block">Implementation for the Excel function SUMIF</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/TimeFunc.html" title="class in org.apache.poi.ss.formula.functions">TimeFunc</a></strong></code> <div class="block">Implementation for the Excel function TIME</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../../org/apache/poi/ss/formula/functions/Vlookup.html" title="class in org.apache.poi.ss.formula.functions">Vlookup</a></strong></code> <div class="block">Implementation of the VLOOKUP() function.<p/> VLOOKUP finds a row in a lookup table by the first column value and returns the value from another column.<br/> <b>Syntax</b>:<br/> <b>VLOOKUP</b>(<b>lookup_value</b>, <b>table_array</b>, <b>col_index_num</b>, range_lookup)<p/> <b>lookup_value</b> The value to be found in the first column of the table array.<br/> <b>table_array</b> An area reference for the lookup data.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/poi/ss/formula/functions/Function3Arg.html" title="interface in org.apache.poi.ss.formula.functions">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/poi/ss/formula/functions//class-useFunction3Arg.html" target="_top">FRAMES</a></li> <li><a href="Function3Arg.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright 2014 The Apache Software Foundation or its licensors, as applicable.</i> </small></p> </body> </html>
{ "content_hash": "e1f286385fe8797106abb744bd406a70", "timestamp": "", "source": "github", "line_count": 277, "max_line_length": 378, "avg_line_length": 48.03610108303249, "alnum_prop": 0.6537652186983316, "repo_name": "RyoSaeba69/Bio-info", "id": "97e7af3a3398b845f005c99fb07c2ec6f72068c0", "size": "13306", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "mylib/poi-3.11/docs/apidocs/org/apache/poi/ss/formula/functions/class-use/Function3Arg.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23219" }, { "name": "HTML", "bytes": "75463818" }, { "name": "Java", "bytes": "98240" } ], "symlink_target": "" }
package com.me; import org.codehaus.groovy.transform.GroovyASTTransformationClass; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @GroovyASTTransformationClass("com.me.impl.DeepCopyASTTransformation") public @interface DeepCopy { }
{ "content_hash": "84b1cbb3a6d45d5e8b4b8ae890b5ac36", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 70, "avg_line_length": 29, "alnum_prop": 0.8405172413793104, "repo_name": "adrianbk/s3-checksums", "id": "68162a2dad0fb79d9055d818337d869f0303469a", "size": "464", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/me/DeepCopy.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "3768" }, { "name": "Java", "bytes": "5412" } ], "symlink_target": "" }
layout: post title: "How to broadcast a message from outside SignalR hub" subtitle: "How to broadcast a message from outside SignalR hub" date: 2013-10-08 01:09 author: "Anuraj" comments: true categories: [.Net, .Net 4.0, ASP.Net MVC] tags: [.Net, .Net 4.0, C#.Net, SignalR] header-img: "img/post-bg-01.jpg" --- Broadcasting a message from SignalR hub is pretty straight forward, but sometimes you may need to do the same from outside the hub, like from MVC controller or a Web Page. This snippet will help you to broadcast messages from outside hub. {% highlight CSharp %} var context = GlobalHost.ConnectionManager.GetHubContext<MySampleHub>(); Context.Clients.All.Notify("Notification from Server"); {% endhighlight %} In this MySampleHub is the SignalR hub class and Notify is the Hub method. Happy Programming
{ "content_hash": "6ba17929845e428bcd40af07e62d43d2", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 172, "avg_line_length": 37.27272727272727, "alnum_prop": 0.7609756097560976, "repo_name": "anuraj/anuraj.github.io", "id": "c50be6983b5763158fe08657cf48c72ab3ec5c45", "size": "824", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "_posts/2013-10-08-how-to-broadcast-a-message-from-outside-signalr-hub.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "4385" } ], "symlink_target": "" }
<?php namespace Anomaly\Streams\Platform\Application\Console\Command; use Anomaly\Streams\Platform\Application\Application; use Anomaly\Streams\Platform\Addon\Addon; use Illuminate\Filesystem\Filesystem; use Illuminate\Console\Command; class PublishConfig { /** * The console command. * * @var Command */ protected $command; /** * Create a new PublishConfig instance. * * @param Command $command */ public function __construct(Command $command) { $this->command = $command; } /** * Handle the command. * * @param Filesystem $filesystem * @param Application $application * @return string */ public function handle(Filesystem $filesystem, Application $application) { $destination = $application->getResourcesPath('streams/config'); if (is_dir($destination) && !$this->command->option('force')) { return $this->command->error("The $destination directory already exists."); } $filesystem->copyDirectory(__DIR__ . '/../../../../resources/config', $destination); $this->command->info("Published $destination"); } }
{ "content_hash": "ab2fc20dc8da80bad93208025e261bb3", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 92, "avg_line_length": 25.847826086956523, "alnum_prop": 0.6265769554247267, "repo_name": "whuailin/dogdie", "id": "c9358a9b51d2c0106e4b9f0142beccc1744862d6", "size": "1189", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/anomaly/streams-platform/src/Application/Console/Command/PublishConfig.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "844" }, { "name": "CSS", "bytes": "429966" }, { "name": "HTML", "bytes": "163598" }, { "name": "JavaScript", "bytes": "14794853" }, { "name": "PHP", "bytes": "2184793" }, { "name": "Vue", "bytes": "559" } ], "symlink_target": "" }
angular.module('starter.services.feedback', []) .factory('Feedback', function($http,HOST) { var Feedback={ addFeedback:function(content){ return $http.post(HOST+'/feedback',{ content:content }).then(function(result){ return result.data; }).then(function(result) { if (result.err === 0) { return true; } else { return false; } }); } } return Feedback; });
{ "content_hash": "94f0115204747e36a3398391df811a79", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 47, "avg_line_length": 17.041666666666668, "alnum_prop": 0.6039119804400978, "repo_name": "yhaoao/tushuo-client", "id": "c4f8a5e282c65f7b8592e152e0dfed55e26fcebf", "size": "409", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "www/tushuo/app/services/feedback.js", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "5024" }, { "name": "C++", "bytes": "5083" }, { "name": "CSS", "bytes": "722052" }, { "name": "Java", "bytes": "9251" }, { "name": "JavaScript", "bytes": "2049143" }, { "name": "Objective-C", "bytes": "15050" } ], "symlink_target": "" }
package com.thoughtworks.go.config.parts; import com.thoughtworks.go.config.*; import com.thoughtworks.go.config.remote.PartialConfig; import com.thoughtworks.go.domain.WildcardScanner; import com.thoughtworks.go.domain.config.Configuration; import com.thoughtworks.go.domain.config.ConfigurationProperty; import org.jdom2.input.JDOMParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class XmlPartialConfigProvider implements PartialConfigProvider { private static final Logger LOGGER = LoggerFactory.getLogger(XmlPartialConfigProvider.class); public static final String providerName = "gocd-xml"; private final String defaultPattern = "**/*.gocd.xml"; private final MagicalGoConfigXmlLoader loader; public XmlPartialConfigProvider(MagicalGoConfigXmlLoader loader) { this.loader = loader; } @Override public PartialConfig load(File configRepoCheckoutDirectory, PartialConfigLoadContext context) { File[] allFiles = getFiles(configRepoCheckoutDirectory, context); // if context had changed files list then we could parse only new content PartialConfig[] allFragments = parseFiles(allFiles); PartialConfig partialConfig = new PartialConfig(); collectFragments(allFragments, partialConfig); return partialConfig; } @Override public String displayName() { return "GoCD XML"; } public File[] getFiles(File configRepoCheckoutDirectory, PartialConfigLoadContext context) { String pattern = defaultPattern; Configuration configuration = context.configuration(); if (configuration != null) { ConfigurationProperty explicitPattern = configuration.getProperty("pattern"); if (explicitPattern != null) { pattern = explicitPattern.getValue(); } } return getFiles(configRepoCheckoutDirectory, pattern); } private File[] getFiles(File configRepoCheckoutDirectory, String pattern) { WildcardScanner scanner = new WildcardScanner(configRepoCheckoutDirectory, pattern); return scanner.getFiles(); } private void collectFragments(PartialConfig[] allFragments, PartialConfig partialConfig) { for (PartialConfig frag : allFragments) { for (PipelineConfigs pipesInGroup : frag.getGroups()) { for (PipelineConfig pipe : pipesInGroup) { partialConfig.getGroups().addPipeline(pipesInGroup.getGroup(), pipe); } } for (EnvironmentConfig env : frag.getEnvironments()) { partialConfig.getEnvironments().add(env); } } } public PartialConfig[] parseFiles(File[] allFiles) { PartialConfig[] parts = new PartialConfig[allFiles.length]; for (int i = 0; i < allFiles.length; i++) { parts[i] = parseFile(allFiles[i]); } return parts; } public PartialConfig parseFile(File file) { FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); return loader.fromXmlPartial(inputStream, PartialConfig.class); } catch (JDOMParseException jdomex) { throw new RuntimeException("Syntax error in xml file: " + file.getName(), jdomex); } catch (IOException ioex) { throw new RuntimeException("IO error when trying to parse xml file: " + file.getName(), ioex); } catch (Exception ex) { throw new RuntimeException("Failed to parse xml file: " + file.getName(), ex); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException e) { LOGGER.error("Failed to close file: {}", file, e); } } } }
{ "content_hash": "847e35d8bd966df330af842d146212c0", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 106, "avg_line_length": 35.52252252252252, "alnum_prop": 0.6634542226730915, "repo_name": "gocd/gocd", "id": "61cbd57feb1b70c21eedde70def98a0b2ff5cf58", "size": "4544", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "config/config-server/src/main/java/com/thoughtworks/go/config/parts/XmlPartialConfigProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "474" }, { "name": "CSS", "bytes": "1578" }, { "name": "EJS", "bytes": "1626" }, { "name": "FreeMarker", "bytes": "48379" }, { "name": "Groovy", "bytes": "2439752" }, { "name": "HTML", "bytes": "275640" }, { "name": "Java", "bytes": "21175794" }, { "name": "JavaScript", "bytes": "837258" }, { "name": "NSIS", "bytes": "24216" }, { "name": "Ruby", "bytes": "426376" }, { "name": "SCSS", "bytes": "661872" }, { "name": "Shell", "bytes": "13847" }, { "name": "TypeScript", "bytes": "4435018" }, { "name": "XSLT", "bytes": "206746" } ], "symlink_target": "" }
package com.amazonaws.services.redshift.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; /** * Container for the parameters to the {@link com.amazonaws.services.redshift.AmazonRedshift#revokeSnapshotAccess(RevokeSnapshotAccessRequest) RevokeSnapshotAccess operation}. * <p> * Removes the ability of the specified AWS customer account to restore * the specified snapshot. If the account is currently restoring the * snapshot, the restore will run to completion. * </p> * <p> * For more information about working with snapshots, go to * <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html"> Amazon Redshift Snapshots </a> * in the <i>Amazon Redshift Cluster Management Guide</i> . * </p> * * @see com.amazonaws.services.redshift.AmazonRedshift#revokeSnapshotAccess(RevokeSnapshotAccessRequest) */ public class RevokeSnapshotAccessRequest extends AmazonWebServiceRequest implements Serializable, Cloneable { /** * The identifier of the snapshot that the account can no longer access. */ private String snapshotIdentifier; /** * The identifier of the cluster the snapshot was created from. This * parameter is required if your IAM user has a policy containing a * snapshot resource element that specifies anything other than * for the * cluster name. */ private String snapshotClusterIdentifier; /** * The identifier of the AWS customer account that can no longer restore * the specified snapshot. */ private String accountWithRestoreAccess; /** * The identifier of the snapshot that the account can no longer access. * * @return The identifier of the snapshot that the account can no longer access. */ public String getSnapshotIdentifier() { return snapshotIdentifier; } /** * The identifier of the snapshot that the account can no longer access. * * @param snapshotIdentifier The identifier of the snapshot that the account can no longer access. */ public void setSnapshotIdentifier(String snapshotIdentifier) { this.snapshotIdentifier = snapshotIdentifier; } /** * The identifier of the snapshot that the account can no longer access. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param snapshotIdentifier The identifier of the snapshot that the account can no longer access. * * @return A reference to this updated object so that method calls can be chained * together. */ public RevokeSnapshotAccessRequest withSnapshotIdentifier(String snapshotIdentifier) { this.snapshotIdentifier = snapshotIdentifier; return this; } /** * The identifier of the cluster the snapshot was created from. This * parameter is required if your IAM user has a policy containing a * snapshot resource element that specifies anything other than * for the * cluster name. * * @return The identifier of the cluster the snapshot was created from. This * parameter is required if your IAM user has a policy containing a * snapshot resource element that specifies anything other than * for the * cluster name. */ public String getSnapshotClusterIdentifier() { return snapshotClusterIdentifier; } /** * The identifier of the cluster the snapshot was created from. This * parameter is required if your IAM user has a policy containing a * snapshot resource element that specifies anything other than * for the * cluster name. * * @param snapshotClusterIdentifier The identifier of the cluster the snapshot was created from. This * parameter is required if your IAM user has a policy containing a * snapshot resource element that specifies anything other than * for the * cluster name. */ public void setSnapshotClusterIdentifier(String snapshotClusterIdentifier) { this.snapshotClusterIdentifier = snapshotClusterIdentifier; } /** * The identifier of the cluster the snapshot was created from. This * parameter is required if your IAM user has a policy containing a * snapshot resource element that specifies anything other than * for the * cluster name. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param snapshotClusterIdentifier The identifier of the cluster the snapshot was created from. This * parameter is required if your IAM user has a policy containing a * snapshot resource element that specifies anything other than * for the * cluster name. * * @return A reference to this updated object so that method calls can be chained * together. */ public RevokeSnapshotAccessRequest withSnapshotClusterIdentifier(String snapshotClusterIdentifier) { this.snapshotClusterIdentifier = snapshotClusterIdentifier; return this; } /** * The identifier of the AWS customer account that can no longer restore * the specified snapshot. * * @return The identifier of the AWS customer account that can no longer restore * the specified snapshot. */ public String getAccountWithRestoreAccess() { return accountWithRestoreAccess; } /** * The identifier of the AWS customer account that can no longer restore * the specified snapshot. * * @param accountWithRestoreAccess The identifier of the AWS customer account that can no longer restore * the specified snapshot. */ public void setAccountWithRestoreAccess(String accountWithRestoreAccess) { this.accountWithRestoreAccess = accountWithRestoreAccess; } /** * The identifier of the AWS customer account that can no longer restore * the specified snapshot. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param accountWithRestoreAccess The identifier of the AWS customer account that can no longer restore * the specified snapshot. * * @return A reference to this updated object so that method calls can be chained * together. */ public RevokeSnapshotAccessRequest withAccountWithRestoreAccess(String accountWithRestoreAccess) { this.accountWithRestoreAccess = accountWithRestoreAccess; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getSnapshotIdentifier() != null) sb.append("SnapshotIdentifier: " + getSnapshotIdentifier() + ","); if (getSnapshotClusterIdentifier() != null) sb.append("SnapshotClusterIdentifier: " + getSnapshotClusterIdentifier() + ","); if (getAccountWithRestoreAccess() != null) sb.append("AccountWithRestoreAccess: " + getAccountWithRestoreAccess() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSnapshotIdentifier() == null) ? 0 : getSnapshotIdentifier().hashCode()); hashCode = prime * hashCode + ((getSnapshotClusterIdentifier() == null) ? 0 : getSnapshotClusterIdentifier().hashCode()); hashCode = prime * hashCode + ((getAccountWithRestoreAccess() == null) ? 0 : getAccountWithRestoreAccess().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RevokeSnapshotAccessRequest == false) return false; RevokeSnapshotAccessRequest other = (RevokeSnapshotAccessRequest)obj; if (other.getSnapshotIdentifier() == null ^ this.getSnapshotIdentifier() == null) return false; if (other.getSnapshotIdentifier() != null && other.getSnapshotIdentifier().equals(this.getSnapshotIdentifier()) == false) return false; if (other.getSnapshotClusterIdentifier() == null ^ this.getSnapshotClusterIdentifier() == null) return false; if (other.getSnapshotClusterIdentifier() != null && other.getSnapshotClusterIdentifier().equals(this.getSnapshotClusterIdentifier()) == false) return false; if (other.getAccountWithRestoreAccess() == null ^ this.getAccountWithRestoreAccess() == null) return false; if (other.getAccountWithRestoreAccess() != null && other.getAccountWithRestoreAccess().equals(this.getAccountWithRestoreAccess()) == false) return false; return true; } @Override public RevokeSnapshotAccessRequest clone() { return (RevokeSnapshotAccessRequest) super.clone(); } }
{ "content_hash": "cfbd068f299b662196a1ce3e08322d84", "timestamp": "", "source": "github", "line_count": 221, "max_line_length": 175, "avg_line_length": 41.77828054298642, "alnum_prop": 0.6865590815552908, "repo_name": "trasa/aws-sdk-java", "id": "d575e5a98528d96715104d12933bc6cdc7badac3", "size": "9820", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/RevokeSnapshotAccessRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "100011199" }, { "name": "Scilab", "bytes": "2354" } ], "symlink_target": "" }
package com.cloudera.flume.handlers.thrift; import com.cloudera.flume.core.EventAck; import com.cloudera.flume.handlers.thrift.ThriftEventAck; public class ThriftEventAckAdaptor { public static ThriftEventAck convert(EventAck ea) { ThriftEventAck tea = new ThriftEventAck(); tea.ackID = ea.ackID; tea.hostList = ea.hostList; return tea; } public static EventAck convert(ThriftEventAck tea) { EventAck ea = new EventAck(); ea.ackID = tea.ackID; ea.hostList = tea.hostList; return ea; } }
{ "content_hash": "cd15c2c540394437b4d7eeb88f5e8dfb", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 57, "avg_line_length": 25.333333333333332, "alnum_prop": 0.7218045112781954, "repo_name": "yongkun/flume-0.9.3-cdh3u0-rakuten", "id": "244980f19d9b61822c3d622f2edcf6a9b52aa6e8", "size": "1323", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/java/com/cloudera/flume/handlers/thrift/ThriftEventAckAdaptor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "45614" }, { "name": "GAP", "bytes": "11388" }, { "name": "Java", "bytes": "3915817" }, { "name": "Shell", "bytes": "27255" }, { "name": "XSLT", "bytes": "49194" } ], "symlink_target": "" }
from re import findall, sub from .default_recipe_parser import recipe_parser def use_schema_org(html): if 'http://schema.org/Recipe' in str(html): return True return False class schema_org_recipe_parser(recipe_parser): def datetime_or_content(self, el): if el: if el.has_attr('datetime'): return self.parse_isoduration(el['datetime']) if el.has_attr('content'): return self.parse_isoduration(el['content']) return None else: return 0 def parse_cook_time(self): el = self.soup.find(attrs={'itemprop': 'cookTime'}) return self.datetime_or_content(el) def parse_prep_time(self): el = self.soup.find(attrs={'itemprop': 'prepTime'}) return self.datetime_or_content(el) def parse_total_time(self): el = self.soup.find(attrs={'itemprop': 'totalTime'}) return self.datetime_or_content(el) def parse_canonical_url(self): el = self.soup.find(attrs={'id': 'canonicalUrl'}) if el and el.has_attr('href'): return el['href'] def parse_image_url(self): el = self.soup.find(attrs={'itemtype': 'http://schema.org/Recipe'}) if el: el = el.find(attrs={'itemprop': 'image'}) if el and el.has_attr('src'): return el['src'] def parse_description(self): el = self.soup.find(attrs={'itemprop': 'description'}) if el: text = el.get_text() or el['content'] return text.strip() def parse_published_date(self): el = self.soup.find(attrs={'itemprop': 'datePublished'}) if el and el.has_attr('datetime'): return el.get_text() def parse_yields(self): el = self.soup.find(attrs={'itemprop': 'recipeYield'}) if el: text = el.get_text() or el['content'] y = findall(r'\d+', text.split(' ')[0]) yields = int(y[0]) or 0 yield_modifier = ' '.join(text.split(' ')[1:]) return yield_modifier, yields def parse_instructions(self): root = self.soup.find(attrs={'itemprop': 'recipeInstructions'}) res = [] for el in root.find_all('li'): t = sub(r'[\t\r\n]', '', el.get_text()) if len(t) > 2: res.append(t) return res or None def parse_ingredients(self): els = self.soup.find_all(attrs={'itemprop': 'ingredients'}) res = [] for el in els: t = el.get_text() t = sub('[\t\r\n]', '', t) t = sub("\s+", " ", t).strip() if len(t) > 2: res.append(t) return res or None def parse_name(self): el = self.soup.find(attrs={'itemprop': 'name'}) if el: return el.get_text() def parse_author(self): el = self.soup.find(attrs={'itemprop': 'author'}) if el: further = el.find(attrs={'itemprop': 'name'}) if further: return further.get_text() else: return el.get_text()
{ "content_hash": "de9eb3a6bc12ad7d2b09e257669d79ff", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 75, "avg_line_length": 31.099009900990097, "alnum_prop": 0.5278573702642471, "repo_name": "scttcper/hangry-py", "id": "7fc76dbd06982cce896223005e3336d6f72e1fe0", "size": "3141", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hangrypy/schema_org_recipe_parser.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "16843" } ], "symlink_target": "" }
@interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSString *fullURL = @"http://app.soundbounce.org/login.html"; NSURL *url = [NSURL URLWithString:fullURL]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; [_viewWeb loadRequest:requestObj]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
{ "content_hash": "041ddd26177a4ef9585c30ce785c54bc", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 65, "avg_line_length": 20.041666666666668, "alnum_prop": 0.7047817047817048, "repo_name": "viqueen/soundbounce", "id": "04239ab34a6780426e5b9efd920bcc8f998617d4", "size": "553", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/ios/Soundbounce/Soundbounce/ViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "39910" }, { "name": "C#", "bytes": "77006" }, { "name": "C++", "bytes": "144623" }, { "name": "CSS", "bytes": "151731" }, { "name": "HTML", "bytes": "26722" }, { "name": "Inno Setup", "bytes": "1684" }, { "name": "Java", "bytes": "58886" }, { "name": "JavaScript", "bytes": "336581" }, { "name": "Objective-C", "bytes": "21026" }, { "name": "Python", "bytes": "2266" }, { "name": "Shell", "bytes": "124" }, { "name": "TeX", "bytes": "157956" } ], "symlink_target": "" }
<?php namespace Intranet\MainBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\SecurityContext; class SecurityController extends Controller { public function loginAction(Request $request) { $session = $request->getSession(); //get the login error if there is one if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)){ $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR); }else { $error = $session->get(SecurityContext::AUTHENTICATION_ERROR); $session->remove(SecurityContext::AUTHENTICATION_ERROR); } $parameters = array('last_username' => $session->get(SecurityContext::LAST_USERNAME), 'error' => $error ); return $this->render("IntranetMainBundle:Security:login.html.twig", $parameters); } public function registerAction(Request $request) { $session = $request->getSession(); $accessFilter = $this->get('intranet.accessFilter'); $clientIp = $request->getClientIp(); //$clientIp = '58.146.96.0'; //india $clientIp = '92.113.48.68'; //ukraine $country = $accessFilter->getCountrySymbolByIp($clientIp); $hasAccess = $accessFilter->hasAccess($clientIp); $parameters = array( 'country' => $country, 'hasAccess' => $hasAccess); return $this->render("IntranetMainBundle:Security:register.html.twig", $parameters); } }
{ "content_hash": "2af8f4d66f7bcdab0d95fc8c4b4fbba8", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 90, "avg_line_length": 31.28301886792453, "alnum_prop": 0.6507840772014475, "repo_name": "oligarch777/intranet", "id": "1c4a12168f6d07b1c12a08adcaa5e39e24424f7e", "size": "1658", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Intranet/MainBundle/Controller/SecurityController.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "205769" }, { "name": "JavaScript", "bytes": "1339074" }, { "name": "PHP", "bytes": "313165" }, { "name": "Perl", "bytes": "189" }, { "name": "Shell", "bytes": "35" } ], "symlink_target": "" }
<?php namespace Phalcon\Traits; use Traversable; use InvalidArgumentException; /** * Phalcon\Traits\ConfigurableTrait * * Allows to define parameters which can be set by passing them to the class constructor. * These parameters should be defined in the `$configurable` array. * * @property array $configurable * @package Phalcon\Traits */ trait ConfigurableTrait { /** * Sets the parameters. * * @param Traversable|array $parameters * @return $this * * @throws InvalidArgumentException */ protected function setParameters($parameters) { if (!property_exists($this, 'configurable') || !is_array($this->configurable)) { return $this; } if (!is_array($parameters) && !($parameters instanceof Traversable)) { throw new InvalidArgumentException('The $parameters argument must be either an array or Traversable'); } foreach ($parameters as $key => $value) { if (!in_array($key, $this->configurable, true)) { continue; } $method = 'set' . ucfirst($key); if (method_exists($this, $method)) { $this->$method($value); } } return $this; } }
{ "content_hash": "4f624860c1d5b4db421f20d20f134914", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 114, "avg_line_length": 24, "alnum_prop": 0.5888364779874213, "repo_name": "mobeen122/Masjidsystem", "id": "353e98fbc69ed0a77a33a657495f526a027efe0d", "size": "2355", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/phalcon/incubator/Library/Phalcon/Traits/ConfigurableTrait.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "426" }, { "name": "CSS", "bytes": "4503013" }, { "name": "CoffeeScript", "bytes": "84343" }, { "name": "HTML", "bytes": "421629" }, { "name": "JavaScript", "bytes": "17553168" }, { "name": "PHP", "bytes": "148390" }, { "name": "Shell", "bytes": "444" }, { "name": "Volt", "bytes": "19298" } ], "symlink_target": "" }
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Iterator for maps of type double and short. * * <p>The iterator semantics for Trove's primitive maps is slightly different * from those defined in <tt>java.util.Iterator</tt>, but still well within * the scope of the pattern, as defined by Gamma, et al.</p> * * <p>This iterator does <b>not</b> implicitly advance to the next entry when * the value at the current position is retrieved. Rather, you must explicitly * ask the iterator to <tt>advance()</tt> and then retrieve either the <tt>key()</tt>, * the <tt>value()</tt> or both. This is done so that you have the option, but not * the obligation, to retrieve keys and/or values as your application requires, and * without introducing wrapper objects that would carry both. As the iteration is * stateful, access to the key/value parts of the current map entry happens in * constant time.</p> * * <p>In practice, the iterator is akin to a "search finger" that you move from * position to position. Read or write operations affect the current entry only and * do not assume responsibility for moving the finger.</p> * * <p>Here are some sample scenarios for this class of iterator:</p> * * <pre> * // accessing keys/values through an iterator: * for (TDoubleShortIterator it = map.iterator(); * it.hasNext();) { * it.advance(); * if (satisfiesCondition(it.key()) { * doSomethingWithValue(it.value()); * } * } * </pre> * * <pre> * // modifying values in-place through iteration: * for (TDoubleShortIterator it = map.iterator(); * it.hasNext();) { * it.advance(); * if (satisfiesCondition(it.key()) { * it.setValue(newValueForKey(it.key())); * } * } * </pre> * * <pre> * // deleting entries during iteration: * for (TDoubleShortIterator it = map.iterator(); * it.hasNext();) { * it.advance(); * if (satisfiesCondition(it.key()) { * it.remove(); * } * } * </pre> * * <pre> * // faster iteration by avoiding hasNext(): * TDoubleShortIterator iterator = map.iterator(); * for (int i = map.size(); i-- > 0;) { * iterator.advance(); * doSomethingWithKeyAndValue(iterator.key(), iterator.value()); * } * </pre> * * @author Eric D. Friedman * @version $Id: P2PIterator.template,v 1.1 2006/11/10 23:28:00 robeden Exp $ */ public class TDoubleShortIterator extends TPrimitiveIterator { /** the collection being iterated over */ private final TDoubleShortHashMap _map; /** * Creates an iterator over the specified map */ public TDoubleShortIterator(TDoubleShortHashMap map) { super(map); this._map = map; } /** * Moves the iterator forward to the next entry in the underlying map. * * @throws java.util.NoSuchElementException if the iterator is already exhausted */ public void advance() { moveToNextIndex(); } /** * Provides access to the key of the mapping at the iterator's position. * Note that you must <tt>advance()</tt> the iterator at least once * before invoking this method. * * @return the key of the entry at the iterator's current position. */ public double key() { return _map._set[_index]; } /** * Provides access to the value of the mapping at the iterator's position. * Note that you must <tt>advance()</tt> the iterator at least once * before invoking this method. * * @return the value of the entry at the iterator's current position. */ public short value() { return _map._values[_index]; } /** * Replace the value of the mapping at the iterator's position with the * specified value. Note that you must <tt>advance()</tt> the iterator at * least once before invoking this method. * * @param val the value to set in the current entry * @return the old value of the entry. */ public short setValue(short val) { short old = value(); _map._values[_index] = val; return old; } }// TDoubleShortIterator
{ "content_hash": "b690f1d85050ca8837f8e6534980ad60", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 86, "avg_line_length": 34.14, "alnum_prop": 0.6346416715485257, "repo_name": "jgaltidor/VarJ", "id": "f6a321079d36402d6aa602a8c79bcbe514352215", "size": "5121", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "analyzed_libs/trove-2.1.0/src/gnu/trove/TDoubleShortIterator.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2125" }, { "name": "CSS", "bytes": "9913" }, { "name": "Emacs Lisp", "bytes": "12570" }, { "name": "Java", "bytes": "31711742" }, { "name": "JavaScript", "bytes": "3251" }, { "name": "Makefile", "bytes": "257" }, { "name": "Perl", "bytes": "5179" }, { "name": "Prolog", "bytes": "292" }, { "name": "Python", "bytes": "1080" }, { "name": "Scala", "bytes": "42424" }, { "name": "Shell", "bytes": "43707" }, { "name": "TeX", "bytes": "372287" } ], "symlink_target": "" }
require "spec_helper" RSpec.describe PgParty::Adapter::PostgreSQLMethods do let(:decorator) { instance_double(PgParty::AdapterDecorator) } let(:adapter_class) do Class.new do include PgParty::Adapter::PostgreSQLMethods end end before do allow(PgParty::AdapterDecorator).to receive(:new).with(adapter).and_return(decorator) end subject(:adapter) { adapter_class.new } describe "#create_range_partition" do subject { adapter.create_range_partition(:parent, partition_key: :id) } it "delegates to decorator" do expect(decorator).to receive(:create_range_partition).with(:parent, partition_key: :id) subject end end describe "#create_list_partition" do subject { adapter.create_list_partition(:parent, partition_key: :id) } it "delegates to decorator" do expect(decorator).to receive(:create_list_partition).with(:parent, partition_key: :id) subject end end describe "#create_hash_partition" do subject { adapter.create_hash_partition(:parent, partition_key: :id) } it "delegates to decorator" do expect(decorator).to receive(:create_hash_partition).with(:parent, partition_key: :id) subject end end describe "#create_range_partition_of" do subject { adapter.create_range_partition_of(:parent, start_range: 1, end_range: 10) } it "delegates to decorator" do expect(decorator).to receive(:create_range_partition_of).with(:parent, start_range: 1, end_range: 10) subject end end describe "#create_list_partition_of" do subject { adapter.create_list_partition_of(:parent, values: [1, 2, 3]) } it "delegates to decorator" do expect(decorator).to receive(:create_list_partition_of).with(:parent, values: [1, 2, 3]) subject end end describe "#create_hash_partition_of" do subject { adapter.create_hash_partition_of(:parent, modulus: 2, remainder: 0) } it "delegates to decorator" do expect(decorator).to receive(:create_hash_partition_of).with(:parent, modulus: 2, remainder: 0) subject end end describe "#create_default_partition_of" do subject { adapter.create_default_partition_of(:parent) } it "delegates to decorator" do expect(decorator).to receive(:create_default_partition_of).with(:parent) subject end end describe "#create_table_like" do subject { adapter.create_table_like(:table_a, :table_b) } it "delegates to decorator" do expect(decorator).to receive(:create_table_like).with(:table_a, :table_b) subject end end describe "#attach_range_partition" do subject { adapter.attach_range_partition(:parent, :child, start_range: 1, end_range: 10) } it "delegates to decorator" do expect(decorator).to receive(:attach_range_partition).with(:parent, :child, start_range: 1, end_range: 10) subject end end describe "#attach_list_partition" do subject { adapter.attach_list_partition(:parent, :child, values: [1, 2, 3]) } it "delegates to decorator" do expect(decorator).to receive(:attach_list_partition).with(:parent, :child, values: [1, 2, 3]) subject end end describe "#attach_hash_partition" do subject { adapter.attach_hash_partition(:parent, :child, modulus: 2, remainder: 0) } it "delegates to decorator" do expect(decorator).to receive(:attach_hash_partition).with(:parent, :child, modulus: 2, remainder: 0) subject end end describe "#attach_default_partition" do subject { adapter.attach_default_partition(:parent, :child) } it "delegates to decorator" do expect(decorator).to receive(:attach_default_partition).with(:parent, :child) subject end end describe "#detach_partition" do subject { adapter.detach_partition(:parent, :child) } it "delegates to decorator" do expect(decorator).to receive(:detach_partition).with(:parent, :child) subject end end describe "#parent_for_table_name" do subject { adapter.parent_for_table_name(:table_name, traverse: true) } it "delegates to decorator" do expect(decorator).to receive(:parent_for_table_name).with(:table_name, traverse: true) subject end end describe "#partitions_for_table_name" do subject { adapter.partitions_for_table_name(:table_name, include_subpartitions: true) } it "delegates to decorator" do expect(decorator).to receive(:partitions_for_table_name).with(:table_name, include_subpartitions: true) subject end end describe "#add_index_on_all_partitions" do subject { adapter.add_index_on_all_partitions(:table_name, [:columns], unique: true, in_threads: 2) } it "delegates to decorator" do expect(decorator).to receive(:add_index_on_all_partitions) .with(:table_name, [:columns], unique: true, in_threads: 2) subject end end describe "#table_partitioned?" do subject { adapter.table_partitioned?(:table_name) } it "delegates to decorator" do expect(decorator).to receive(:table_partitioned?) .with(:table_name) subject end end end
{ "content_hash": "06a485bcb11a8d1aea318f28ad583c15", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 112, "avg_line_length": 30.380116959064328, "alnum_prop": 0.6746871992300288, "repo_name": "rkrage/pg_party", "id": "6a5ad98ee0189252f416f67be2b9e67d50637496", "size": "5226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/adapter/postgresql_methods_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "969" }, { "name": "Ruby", "bytes": "178578" }, { "name": "Shell", "bytes": "48" } ], "symlink_target": "" }
/* */ var Tokenizer = require("./Tokenizer"); var formTags = { input: true, option: true, optgroup: true, select: true, button: true, datalist: true, textarea: true }; var openImpliesClose = { tr: { tr: true, th: true, td: true }, th: {th: true}, td: { thead: true, td: true }, body: { head: true, link: true, script: true }, li: {li: true}, p: {p: true}, h1: {p: true}, h2: {p: true}, h3: {p: true}, h4: {p: true}, h5: {p: true}, h6: {p: true}, select: formTags, input: formTags, output: formTags, button: formTags, datalist: formTags, textarea: formTags, option: {option: true}, optgroup: {optgroup: true} }; var voidElements = { __proto__: null, area: true, base: true, basefont: true, br: true, col: true, command: true, embed: true, frame: true, hr: true, img: true, input: true, isindex: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true, path: true, circle: true, ellipse: true, line: true, rect: true, use: true, stop: true, polyline: true, polygone: true }; var re_nameEnd = /\s|\//; function Parser(cbs, options) { this._options = options || {}; this._cbs = cbs || {}; this._tagname = ""; this._attribname = ""; this._attribvalue = ""; this._attribs = null; this._stack = []; this.startIndex = 0; this.endIndex = null; this._lowerCaseTagNames = "lowerCaseTags" in this._options ? !!this._options.lowerCaseTags : !this._options.xmlMode; this._lowerCaseAttributeNames = "lowerCaseAttributeNames" in this._options ? !!this._options.lowerCaseAttributeNames : !this._options.xmlMode; this._tokenizer = new Tokenizer(this._options, this); if (this._cbs.onparserinit) this._cbs.onparserinit(this); } require("util").inherits(Parser, require("events").EventEmitter); Parser.prototype._updatePosition = function(initialOffset) { if (this.endIndex === null) { if (this._tokenizer._sectionStart <= initialOffset) { this.startIndex = 0; } else { this.startIndex = this._tokenizer._sectionStart - initialOffset; } } else this.startIndex = this.endIndex + 1; this.endIndex = this._tokenizer.getAbsoluteIndex(); }; Parser.prototype.ontext = function(data) { this._updatePosition(1); this.endIndex--; if (this._cbs.ontext) this._cbs.ontext(data); }; Parser.prototype.onopentagname = function(name) { if (this._lowerCaseTagNames) { name = name.toLowerCase(); } this._tagname = name; if (!this._options.xmlMode && name in openImpliesClose) { for (var el; (el = this._stack[this._stack.length - 1]) in openImpliesClose[name]; this.onclosetag(el)) ; } if (this._options.xmlMode || !(name in voidElements)) { this._stack.push(name); } if (this._cbs.onopentagname) this._cbs.onopentagname(name); if (this._cbs.onopentag) this._attribs = {}; }; Parser.prototype.onopentagend = function() { this._updatePosition(1); if (this._attribs) { if (this._cbs.onopentag) this._cbs.onopentag(this._tagname, this._attribs); this._attribs = null; } if (!this._options.xmlMode && this._cbs.onclosetag && this._tagname in voidElements) { this._cbs.onclosetag(this._tagname); } this._tagname = ""; }; Parser.prototype.onclosetag = function(name) { this._updatePosition(1); if (this._lowerCaseTagNames) { name = name.toLowerCase(); } if (this._stack.length && (!(name in voidElements) || this._options.xmlMode)) { var pos = this._stack.lastIndexOf(name); if (pos !== -1) { if (this._cbs.onclosetag) { pos = this._stack.length - pos; while (pos--) this._cbs.onclosetag(this._stack.pop()); } else this._stack.length = pos; } else if (name === "p" && !this._options.xmlMode) { this.onopentagname(name); this._closeCurrentTag(); } } else if (!this._options.xmlMode && (name === "br" || name === "p")) { this.onopentagname(name); this._closeCurrentTag(); } }; Parser.prototype.onselfclosingtag = function() { if (this._options.xmlMode || this._options.recognizeSelfClosing) { this._closeCurrentTag(); } else { this.onopentagend(); } }; Parser.prototype._closeCurrentTag = function() { var name = this._tagname; this.onopentagend(); if (this._stack[this._stack.length - 1] === name) { if (this._cbs.onclosetag) { this._cbs.onclosetag(name); } this._stack.pop(); } }; Parser.prototype.onattribname = function(name) { if (this._lowerCaseAttributeNames) { name = name.toLowerCase(); } this._attribname = name; }; Parser.prototype.onattribdata = function(value) { this._attribvalue += value; }; Parser.prototype.onattribend = function() { if (this._cbs.onattribute) this._cbs.onattribute(this._attribname, this._attribvalue); if (this._attribs && !Object.prototype.hasOwnProperty.call(this._attribs, this._attribname)) { this._attribs[this._attribname] = this._attribvalue; } this._attribname = ""; this._attribvalue = ""; }; Parser.prototype._getInstructionName = function(value) { var idx = value.search(re_nameEnd), name = idx < 0 ? value : value.substr(0, idx); if (this._lowerCaseTagNames) { name = name.toLowerCase(); } return name; }; Parser.prototype.ondeclaration = function(value) { if (this._cbs.onprocessinginstruction) { var name = this._getInstructionName(value); this._cbs.onprocessinginstruction("!" + name, "!" + value); } }; Parser.prototype.onprocessinginstruction = function(value) { if (this._cbs.onprocessinginstruction) { var name = this._getInstructionName(value); this._cbs.onprocessinginstruction("?" + name, "?" + value); } }; Parser.prototype.oncomment = function(value) { this._updatePosition(4); if (this._cbs.oncomment) this._cbs.oncomment(value); if (this._cbs.oncommentend) this._cbs.oncommentend(); }; Parser.prototype.oncdata = function(value) { this._updatePosition(1); if (this._options.xmlMode || this._options.recognizeCDATA) { if (this._cbs.oncdatastart) this._cbs.oncdatastart(); if (this._cbs.ontext) this._cbs.ontext(value); if (this._cbs.oncdataend) this._cbs.oncdataend(); } else { this.oncomment("[CDATA[" + value + "]]"); } }; Parser.prototype.onerror = function(err) { if (this._cbs.onerror) this._cbs.onerror(err); }; Parser.prototype.onend = function() { if (this._cbs.onclosetag) { for (var i = this._stack.length; i > 0; this._cbs.onclosetag(this._stack[--i])) ; } if (this._cbs.onend) this._cbs.onend(); }; Parser.prototype.reset = function() { if (this._cbs.onreset) this._cbs.onreset(); this._tokenizer.reset(); this._tagname = ""; this._attribname = ""; this._attribs = null; this._stack = []; if (this._cbs.onparserinit) this._cbs.onparserinit(this); }; Parser.prototype.parseComplete = function(data) { this.reset(); this.end(data); }; Parser.prototype.write = function(chunk) { this._tokenizer.write(chunk); }; Parser.prototype.end = function(chunk) { this._tokenizer.end(chunk); }; Parser.prototype.pause = function() { this._tokenizer.pause(); }; Parser.prototype.resume = function() { this._tokenizer.resume(); }; Parser.prototype.parseChunk = Parser.prototype.write; Parser.prototype.done = Parser.prototype.end; module.exports = Parser;
{ "content_hash": "1dcfbfb8706501b98fd867ecd9f27339", "timestamp": "", "source": "github", "line_count": 279, "max_line_length": 144, "avg_line_length": 26.630824372759857, "alnum_prop": 0.6394347240915209, "repo_name": "npelletm/np-jdanyow-skeleton-navigation", "id": "8370ce953dfaffd587eed711ea17ecc835275e73", "size": "7430", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "jspm_packages/npm/htmlparser2@3.8.2/lib/Parser.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "120600" }, { "name": "CoffeeScript", "bytes": "2294" }, { "name": "HTML", "bytes": "27504" }, { "name": "JavaScript", "bytes": "4314806" }, { "name": "LiveScript", "bytes": "3914" }, { "name": "Makefile", "bytes": "880" } ], "symlink_target": "" }
$(window).scroll(function() { if ($(".navbar").offset().top > 50) { $(".navbar-fixed-top.transform").addClass("top-nav-collapse"); } else { $(".navbar-fixed-top.transform").removeClass("top-nav-collapse"); } }); $('.navbar-nav').children().click(function () { var navbar = $('.navbar-main-collapse'); navbar.removeClass('in'); navbar.addClass('collapse'); navbar.css('height', '1px'); }); //jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('.page-scroll a').bind('click', function(event) { var $anchor = $(this); var targetEl = $($anchor.data('target')); if (targetEl.length === 0) return; $('html, body').stop().animate({ scrollTop: targetEl.offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); //var myOptions = { // zoom: 15, // center: new google.maps.LatLng(53.385873, -1.471471), // mapTypeId: google.maps.MapTypeId.ROADMAP, //}; //var map = new google.maps.Map(document.getElementById('map'), myOptions); function initializeMap(id) { "use strict"; var image = '/Content/swetugg-2016/img/icon-map.png'; var overlayTitle = 'Swetugg 2016'; var locations = [ //point number 1 // ['Swetugg 2016', 'Stockholm', '59.326142', '17.9875455'], ['Swetugg 2016', 'Stockholm', 59.2910932, 18.0836 ] ]; id = (id === undefined) ? 'map' : id; var map = new google.maps.Map(document.getElementById(id), { mapTypeId: google.maps.MapTypeId.ROADMAP, scrollwheel: false, zoomControl: true, zoomControlOptions: { style: google.maps.ZoomControlStyle.LARGE, position: google.maps.ControlPosition.LEFT_CENTER }, streetViewControl: true, scaleControl: false, zoom: 11, }); var myLatlng; var marker, i; var bounds = new google.maps.LatLngBounds(); var infowindow = new google.maps.InfoWindow({ content: "loading..." }); for (i = 0; i < locations.length; i++) { if (locations[i][2] !== undefined && locations[i][3] !== undefined) { var content = '<div class="infoWindow">' + locations[i][0] + '<br>' + locations[i][1] + '</div>'; (function (content) { myLatlng = new google.maps.LatLng(locations[i][2], locations[i][3]); marker = new google.maps.Marker({ position: myLatlng, icon: image, title: overlayTitle, map: map }); google.maps.event.addListener(marker, 'click', (function () { return function () { infowindow.setContent(content); infowindow.open(map, this); }; })(this, i)); if (locations.length > 1) { bounds.extend(myLatlng); map.fitBounds(bounds); } else { map.setCenter(myLatlng); } })(content); } else { var geocoder = new google.maps.Geocoder(); var info = locations[i][0]; var addr = locations[i][1]; var latLng = locations[i][1]; (function (info, addr) { geocoder.geocode({ 'address': latLng }, function (results) { myLatlng = results[0].geometry.location; marker = new google.maps.Marker({ position: myLatlng, icon: image, title: overlayTitle, map: map }); var $content = '<div class="infoWindow">' + info + '<br>' + addr + '</div>'; google.maps.event.addListener(marker, 'click', (function () { return function () { infowindow.setContent($content); infowindow.open(map, this); }; })(this, i)); if (locations.length > 1) { bounds.extend(myLatlng); map.fitBounds(bounds); } else { map.setCenter(myLatlng); } }); })(info, addr); } } }
{ "content_hash": "fcdb7391c1ff56d176221a836aa84174", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 109, "avg_line_length": 31.232876712328768, "alnum_prop": 0.47412280701754383, "repo_name": "andlju/swetugg-web", "id": "cca25981b9fb0d199a895f990be3f25cb7d519ed", "size": "4602", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Swetugg.Web/Content/swetugg-2016/js/swetugg.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "102" }, { "name": "C#", "bytes": "322280" }, { "name": "CSS", "bytes": "120184" }, { "name": "HTML", "bytes": "741217" }, { "name": "JavaScript", "bytes": "531997" }, { "name": "Less", "bytes": "124156" }, { "name": "PowerShell", "bytes": "2218" } ], "symlink_target": "" }
package com.dragon.proto; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; public class ProtoServer { public static void main(String[] args) throws Exception { int port = 8081; EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); try { bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new MyChannelInitializer()); ChannelFuture future = bootstrap.bind(port).sync(); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
{ "content_hash": "b93212cfd655e76aa78f79dce445ea8f", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 80, "avg_line_length": 31.666666666666668, "alnum_prop": 0.7730994152046784, "repo_name": "dragonphoenix/proto-java-csharp", "id": "346f1b58d2aa86cacd14565623d51e4b36aa44d4", "size": "855", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "proto/src/main/java/com/dragon/proto/ProtoServer.java", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2395527" }, { "name": "Java", "bytes": "10108" }, { "name": "Protocol Buffer", "bytes": "3343" }, { "name": "Python", "bytes": "1464" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MtaTrainTime.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
{ "content_hash": "6502a451fae193715f709169198c99b9", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 151, "avg_line_length": 35.56666666666667, "alnum_prop": 0.5820056232427366, "repo_name": "Redder/MTA-Train-Time", "id": "d290f148590b3cf70475fcf067842c95a7fba084", "size": "1069", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MtaTrainTime/Properties/Settings.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "9155" }, { "name": "Shell", "bytes": "15321" } ], "symlink_target": "" }
package com.amazonaws.services.lambda.model; import com.amazonaws.AmazonServiceException; /** * <p> * You have exceeded your maximum total code size per account. * <a href="http://docs.aws.amazon.com/lambda/latest/dg/limits.html"> Limits </a> * * </p> */ public class CodeStorageExceededException extends AmazonServiceException { private static final long serialVersionUID = 1L; private String type; /** * Constructs a new CodeStorageExceededException with the specified error * message. * * @param message Describes the error encountered. */ public CodeStorageExceededException(String message) { super(message); } /** * Returns the value of the Type property for this object. * * @return The value of the Type property for this object. */ public String getType() { return type; } /** * Sets the value of the Type property for this object. * * @param type The new value for this object's Type property. */ public void setType(String type) { this.type = type; } }
{ "content_hash": "2440d88c2188edb34c549fde6e7b0e72", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 81, "avg_line_length": 25.065217391304348, "alnum_prop": 0.6279271465741544, "repo_name": "mhurne/aws-sdk-java", "id": "39076809b13033bcb3f0f0ed0a8c4bf949cfd1f4", "size": "1740", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/CodeStorageExceededException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "123790" }, { "name": "Java", "bytes": "110875821" }, { "name": "Scilab", "bytes": "3561" } ], "symlink_target": "" }
from highcharts.views.bar import HighChartsBarView # noqa from highcharts.views.line import HighChartsLineView # noqa from highcharts.views.area import HighChartsAreaView # noqa
{ "content_hash": "809c6174e7526e62721400b8cb4bd0ab", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 60, "avg_line_length": 60.333333333333336, "alnum_prop": 0.8342541436464088, "repo_name": "vivek8943/django-highcharts", "id": "0a34164cb17f43f1ad83539f56dadb61b43b03c2", "size": "181", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "highcharts/views/__init__.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "1305446" }, { "name": "Python", "bytes": "16121" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" ?> <class name="PinJoint2D" inherits="Joint2D" category="Core" version="3.0.alpha.custom_build"> <brief_description> Pin Joint for 2D Shapes. </brief_description> <description> Pin Joint for 2D Rigid Bodies. It pins 2 bodies (rigid or static) together, or a single body to a fixed position in space. </description> <tutorials> </tutorials> <demos> </demos> <methods> <method name="get_softness" qualifiers="const"> <return type="float"> </return> <description> </description> </method> <method name="set_softness"> <return type="void"> </return> <argument index="0" name="softness" type="float"> </argument> <description> </description> </method> </methods> <members> <member name="softness" type="float" setter="set_softness" getter="get_softness"> The higher this value, the more the bond to the pinned partner can flex. </member> </members> <constants> </constants> </class>
{ "content_hash": "45c12fbaa1238de7babe9d82d2b18211", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 124, "avg_line_length": 27.166666666666668, "alnum_prop": 0.6768916155419223, "repo_name": "ageazrael/godot", "id": "009b0ec2f29da0be1d536c19d422c60d2e4ff88b", "size": "978", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "doc/classes/PinJoint2D.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "50004" }, { "name": "C#", "bytes": "175588" }, { "name": "C++", "bytes": "17913784" }, { "name": "GLSL", "bytes": "1271" }, { "name": "Java", "bytes": "499031" }, { "name": "JavaScript", "bytes": "9580" }, { "name": "Makefile", "bytes": "451" }, { "name": "Objective-C", "bytes": "2644" }, { "name": "Objective-C++", "bytes": "169356" }, { "name": "Python", "bytes": "311752" }, { "name": "Shell", "bytes": "11043" } ], "symlink_target": "" }
extern "C" { #include <sys/types.h> } #include <iostream> #include <atf-c++.hpp> #include "utils/defs.hpp" using utils::auto_array; namespace { /// Mock class to capture calls to the new and delete operators. class test_array { public: /// User-settable cookie to disambiguate instances of this class. int m_value; /// The current balance of existing test_array instances. static ssize_t m_nblocks; /// Captures invalid calls to new on an array. /// /// \param unused_size The amount of memory to allocate, in bytes. /// /// \return Nothing; this always fails the test case. void* operator new(const size_t UTILS_UNUSED_PARAM(size)) { ATF_FAIL("New called but should have been new[]"); return new int(5); } /// Obtains memory for a new instance and increments m_nblocks. /// /// \param size The amount of memory to allocate, in bytes. /// /// \return A pointer to the allocated memory. /// /// \throw std::bad_alloc If the memory cannot be allocated. void* operator new[](const size_t size) { void* mem = ::operator new(size); m_nblocks++; std::cout << "Allocated 'test_array' object " << mem << "\n"; return mem; } /// Captures invalid calls to delete on an array. /// /// \param unused_mem The pointer to the memory to be deleted. /// /// \return Nothing; this always fails the test case. void operator delete(void* UTILS_UNUSED_PARAM(mem)) { ATF_FAIL("Delete called but should have been delete[]"); } /// Deletes a previously allocated array and decrements m_nblocks. /// /// \param mem The pointer to the memory to be deleted. void operator delete[](void* mem) { std::cout << "Releasing 'test_array' object " << mem << "\n"; if (m_nblocks == 0) ATF_FAIL("Unbalanced delete[]"); m_nblocks--; ::operator delete(mem); } }; ssize_t test_array::m_nblocks = 0; } // anonymous namespace ATF_TEST_CASE(scope); ATF_TEST_CASE_HEAD(scope) { set_md_var("descr", "Tests the automatic scope handling in the " "auto_array smart pointer class"); } ATF_TEST_CASE_BODY(scope) { ATF_REQUIRE_EQ(test_array::m_nblocks, 0); { auto_array< test_array > t(new test_array[10]); ATF_REQUIRE_EQ(test_array::m_nblocks, 1); } ATF_REQUIRE_EQ(test_array::m_nblocks, 0); } ATF_TEST_CASE(copy); ATF_TEST_CASE_HEAD(copy) { set_md_var("descr", "Tests the auto_array smart pointer class' copy " "constructor"); } ATF_TEST_CASE_BODY(copy) { ATF_REQUIRE_EQ(test_array::m_nblocks, 0); { auto_array< test_array > t1(new test_array[10]); ATF_REQUIRE_EQ(test_array::m_nblocks, 1); { auto_array< test_array > t2(t1); ATF_REQUIRE_EQ(test_array::m_nblocks, 1); } ATF_REQUIRE_EQ(test_array::m_nblocks, 0); } ATF_REQUIRE_EQ(test_array::m_nblocks, 0); } ATF_TEST_CASE(copy_ref); ATF_TEST_CASE_HEAD(copy_ref) { set_md_var("descr", "Tests the auto_array smart pointer class' copy " "constructor through the auxiliary ref object"); } ATF_TEST_CASE_BODY(copy_ref) { ATF_REQUIRE_EQ(test_array::m_nblocks, 0); { auto_array< test_array > t1(new test_array[10]); ATF_REQUIRE_EQ(test_array::m_nblocks, 1); { auto_array< test_array > t2 = t1; ATF_REQUIRE_EQ(test_array::m_nblocks, 1); } ATF_REQUIRE_EQ(test_array::m_nblocks, 0); } ATF_REQUIRE_EQ(test_array::m_nblocks, 0); } ATF_TEST_CASE(get); ATF_TEST_CASE_HEAD(get) { set_md_var("descr", "Tests the auto_array smart pointer class' get " "method"); } ATF_TEST_CASE_BODY(get) { test_array* ta = new test_array[10]; auto_array< test_array > t(ta); ATF_REQUIRE_EQ(t.get(), ta); } ATF_TEST_CASE(release); ATF_TEST_CASE_HEAD(release) { set_md_var("descr", "Tests the auto_array smart pointer class' release " "method"); } ATF_TEST_CASE_BODY(release) { test_array* ta1 = new test_array[10]; { auto_array< test_array > t(ta1); ATF_REQUIRE_EQ(test_array::m_nblocks, 1); test_array* ta2 = t.release(); ATF_REQUIRE_EQ(ta2, ta1); ATF_REQUIRE_EQ(test_array::m_nblocks, 1); } ATF_REQUIRE_EQ(test_array::m_nblocks, 1); delete [] ta1; } ATF_TEST_CASE(reset); ATF_TEST_CASE_HEAD(reset) { set_md_var("descr", "Tests the auto_array smart pointer class' reset " "method"); } ATF_TEST_CASE_BODY(reset) { test_array* ta1 = new test_array[10]; test_array* ta2 = new test_array[10]; ATF_REQUIRE_EQ(test_array::m_nblocks, 2); { auto_array< test_array > t(ta1); ATF_REQUIRE_EQ(test_array::m_nblocks, 2); t.reset(ta2); ATF_REQUIRE_EQ(test_array::m_nblocks, 1); t.reset(); ATF_REQUIRE_EQ(test_array::m_nblocks, 0); } ATF_REQUIRE_EQ(test_array::m_nblocks, 0); } ATF_TEST_CASE(assign); ATF_TEST_CASE_HEAD(assign) { set_md_var("descr", "Tests the auto_array smart pointer class' " "assignment operator"); } ATF_TEST_CASE_BODY(assign) { ATF_REQUIRE_EQ(test_array::m_nblocks, 0); { auto_array< test_array > t1(new test_array[10]); ATF_REQUIRE_EQ(test_array::m_nblocks, 1); { auto_array< test_array > t2; t2 = t1; ATF_REQUIRE_EQ(test_array::m_nblocks, 1); } ATF_REQUIRE_EQ(test_array::m_nblocks, 0); } ATF_REQUIRE_EQ(test_array::m_nblocks, 0); } ATF_TEST_CASE(assign_ref); ATF_TEST_CASE_HEAD(assign_ref) { set_md_var("descr", "Tests the auto_array smart pointer class' " "assignment operator through the auxiliary ref " "object"); } ATF_TEST_CASE_BODY(assign_ref) { ATF_REQUIRE_EQ(test_array::m_nblocks, 0); { auto_array< test_array > t1(new test_array[10]); ATF_REQUIRE_EQ(test_array::m_nblocks, 1); { auto_array< test_array > t2; t2 = t1; ATF_REQUIRE_EQ(test_array::m_nblocks, 1); } ATF_REQUIRE_EQ(test_array::m_nblocks, 0); } ATF_REQUIRE_EQ(test_array::m_nblocks, 0); } ATF_TEST_CASE(access); ATF_TEST_CASE_HEAD(access) { set_md_var("descr", "Tests the auto_array smart pointer class' access " "operator"); } ATF_TEST_CASE_BODY(access) { auto_array< test_array > t(new test_array[10]); for (int i = 0; i < 10; i++) t[i].m_value = i * 2; for (int i = 0; i < 10; i++) ATF_REQUIRE_EQ(t[i].m_value, i * 2); } ATF_INIT_TEST_CASES(tcs) { ATF_ADD_TEST_CASE(tcs, scope); ATF_ADD_TEST_CASE(tcs, copy); ATF_ADD_TEST_CASE(tcs, copy_ref); ATF_ADD_TEST_CASE(tcs, get); ATF_ADD_TEST_CASE(tcs, release); ATF_ADD_TEST_CASE(tcs, reset); ATF_ADD_TEST_CASE(tcs, assign); ATF_ADD_TEST_CASE(tcs, assign_ref); ATF_ADD_TEST_CASE(tcs, access); }
{ "content_hash": "c8156f0d73c985d3d90d292e24d69fdc", "timestamp": "", "source": "github", "line_count": 286, "max_line_length": 76, "avg_line_length": 24.6993006993007, "alnum_prop": 0.5857870894677236, "repo_name": "veritas-shine/minix3-rpi", "id": "ade8c5e7b9e02813e19f16903b9231de89c78fdd", "size": "8648", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "external/bsd/kyua-cli/dist/utils/auto_array_test.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89060" }, { "name": "Arc", "bytes": "2839" }, { "name": "Assembly", "bytes": "2791293" }, { "name": "Awk", "bytes": "39398" }, { "name": "Bison", "bytes": "137952" }, { "name": "C", "bytes": "45473316" }, { "name": "C#", "bytes": "55726" }, { "name": "C++", "bytes": "577647" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "CSS", "bytes": "254" }, { "name": "Emacs Lisp", "bytes": "4528" }, { "name": "IGOR Pro", "bytes": "2975" }, { "name": "JavaScript", "bytes": "25168" }, { "name": "Logos", "bytes": "14672" }, { "name": "Lua", "bytes": "4385" }, { "name": "Makefile", "bytes": "669790" }, { "name": "Max", "bytes": "3667" }, { "name": "Objective-C", "bytes": "62068" }, { "name": "Pascal", "bytes": "40318" }, { "name": "Perl", "bytes": "100129" }, { "name": "Perl6", "bytes": "243" }, { "name": "Prolog", "bytes": "97" }, { "name": "R", "bytes": "764" }, { "name": "Rebol", "bytes": "738" }, { "name": "SAS", "bytes": "1711" }, { "name": "Shell", "bytes": "2207644" } ], "symlink_target": "" }
package org.apache.sysml.parser; import java.util.ArrayList; import java.util.HashMap; public class FunctionCallIdentifier extends DataIdentifier { private ArrayList<ParameterExpression> _paramExprs; private FunctCallOp _opcode; // stores whether internal or external private String _namespace; // namespace of the function being called (null if current namespace is to be used) /** * sets the function namespace (if specified) and name * * @param functionName the (optional) namespace information and name of function. If both namespace and name are specified, they are concatenated with "::" */ public void setFunctionName(String functionName) { _name = functionName; } public void setFunctionNamespace(String passed) { _namespace = passed; } public String getNamespace(){ return _namespace; } public ArrayList<ParameterExpression> getParamExprs(){ return _paramExprs; } @Override public Expression rewriteExpression(String prefix) { ArrayList<ParameterExpression> newParameterExpressions = new ArrayList<>(); for (ParameterExpression paramExpr : _paramExprs) newParameterExpressions.add(new ParameterExpression(paramExpr.getName(), paramExpr.getExpr().rewriteExpression(prefix))); // rewrite each output expression FunctionCallIdentifier fci = new FunctionCallIdentifier(newParameterExpressions); fci.setParseInfo(this); fci._name = this._name; fci._namespace = this._namespace; fci._opcode = this._opcode; return fci; } public FunctionCallIdentifier(){} public FunctionCallIdentifier(ArrayList<ParameterExpression> paramExpressions) { _paramExprs = paramExpressions; _opcode = null; } public FunctCallOp getOpCode() { return _opcode; } /** * Validate parse tree : Process ExtBuiltinFunction Expression is an * assignment statement * * NOTE: this does not override the normal validateExpression because it needs to pass dmlp! * * @param dmlp dml program * @param ids map of data identifiers * @param constVars map of constant identifiers * @param conditional if true, display warning for 'raiseValidateError'; if false, throw LanguageException * for 'raiseValidateError' */ public void validateExpression(DMLProgram dmlp, HashMap<String, DataIdentifier> ids, HashMap<String, ConstIdentifier> constVars, boolean conditional) { // Step 1: check the namespace exists, and that function is defined in the namespace if (dmlp.getNamespaces().get(_namespace) == null){ raiseValidateError("namespace " + _namespace + " is not defined ", conditional); } FunctionStatementBlock fblock = dmlp.getFunctionStatementBlock(_namespace, _name); if (fblock == null){ raiseValidateError("function " + _name + " is undefined in namespace " + _namespace, conditional); } // Step 2: set opcode (whether internal or external function) -- based on whether FunctionStatement // in FunctionStatementBlock is ExternalFunctionStatement or FunctionStatement if (fblock.getStatement(0) instanceof ExternalFunctionStatement) _opcode = Expression.FunctCallOp.EXTERNAL; else _opcode = Expression.FunctCallOp.INTERNAL; // Step 3: check all parameters to be either unnamed or named for functions boolean hasNamed = false, hasUnnamed = false; for( ParameterExpression paramExpr : _paramExprs ) { if (paramExpr.getName() == null) hasUnnamed = true; else hasNamed = true; } if (hasNamed && hasUnnamed){ raiseValidateError(" In DML, functions can only have named parameters " + "(e.g., name1=value1, name2=value2) or unnamed parameters (e.g, value1, value2). " + _name + " has both parameter types.", conditional); } // Step 4: validate expressions for each passed parameter and defaults for( ParameterExpression paramExpr : _paramExprs ) { if (paramExpr.getExpr() instanceof FunctionCallIdentifier) { raiseValidateError("UDF function call not supported as parameter to function call", false); } paramExpr.getExpr().validateExpression(ids, constVars, conditional); } FunctionStatement fstmt = (FunctionStatement)fblock.getStatement(0); for( Expression expDef : fstmt.getInputDefaults() ) { if( expDef != null ) expDef.validateExpression(ids, constVars, conditional); } // Step 5: constant propagation into function call statement if( !conditional ) { for( ParameterExpression paramExpr : _paramExprs ) { Expression expri = paramExpr.getExpr(); if( expri instanceof DataIdentifier && !(expri instanceof IndexedIdentifier) && constVars.containsKey(((DataIdentifier)expri).getName()) ) { //replace varname with constant in function call expression paramExpr.setExpr(constVars.get(((DataIdentifier)expri).getName())); } } } // Step 6: check correctness of number of arguments and their types if (fstmt.getInputParams().size() < _paramExprs.size()) { raiseValidateError("function " + _name + " has incorrect number of parameters. Function requires " + fstmt.getInputParams().size() + " but was called with " + _paramExprs.size(), conditional); } // Step 7: set the outputs for the function _outputs = new Identifier[fstmt.getOutputParams().size()]; for(int i=0; i < fstmt.getOutputParams().size(); i++) { _outputs[i] = new DataIdentifier(fstmt.getOutputParams().get(i)); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (_namespace != null && _namespace.length() > 0 && !_namespace.equals(DMLProgram.DEFAULT_NAMESPACE)) sb.append(_namespace + "::"); sb.append(_name); sb.append(" ( "); for (int i = 0; i < _paramExprs.size(); i++){ sb.append(_paramExprs.get(i).toString()); if (i<_paramExprs.size() - 1) sb.append(","); } sb.append(" )"); return sb.toString(); } @Override public VariableSet variablesRead() { VariableSet result = new VariableSet(); for (int i = 0; i < _paramExprs.size(); i++) result.addVariables(_paramExprs.get(i).getExpr().variablesRead()); return result; } @Override public VariableSet variablesUpdated() { VariableSet result = new VariableSet(); for (int i=0; i< _outputs.length; i++) result.addVariable( ((DataIdentifier)_outputs[i]).getName(), (DataIdentifier)_outputs[i] ); return result; } @Override public boolean multipleReturns() { return true; } }
{ "content_hash": "2f7a9a2c1f9a287e80336887a3dcda3c", "timestamp": "", "source": "github", "line_count": 185, "max_line_length": 157, "avg_line_length": 34.42162162162162, "alnum_prop": 0.7157663316582915, "repo_name": "gweidner/incubator-systemml", "id": "419bc81653d4919f1be8846bfc4710a01afc8a98", "size": "7177", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/main/java/org/apache/sysml/parser/FunctionCallIdentifier.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "31285" }, { "name": "Batchfile", "bytes": "22265" }, { "name": "C", "bytes": "8676" }, { "name": "C++", "bytes": "30804" }, { "name": "CMake", "bytes": "10312" }, { "name": "Cuda", "bytes": "30575" }, { "name": "Java", "bytes": "12895083" }, { "name": "Jupyter Notebook", "bytes": "36387" }, { "name": "Makefile", "bytes": "936" }, { "name": "Protocol Buffer", "bytes": "66399" }, { "name": "Python", "bytes": "195992" }, { "name": "R", "bytes": "667055" }, { "name": "Scala", "bytes": "186014" }, { "name": "Shell", "bytes": "152940" } ], "symlink_target": "" }
import * as dom from './dom.js'; /** * Returns true if keyCode represents a printable character * @param {Number} keyCode * @return {Boolean} */ export function isPrintableChar(keyCode) { return ((keyCode == 32) || //space (keyCode >= 48 && keyCode <= 57) || //0-9 (keyCode >= 96 && keyCode <= 111) || //numpad (keyCode >= 186 && keyCode <= 192) || //;=,-./` (keyCode >= 219 && keyCode <= 222) || //[]{}\|"' keyCode >= 226 || //special chars (229 for Asian chars) (keyCode >= 65 && keyCode <= 90)); //a-z } export function isMetaKey(_keyCode) { var metaKeys = [ keyCode.ARROW_DOWN, keyCode.ARROW_UP, keyCode.ARROW_LEFT, keyCode.ARROW_RIGHT, keyCode.HOME, keyCode.END, keyCode.DELETE, keyCode.BACKSPACE, keyCode.F1, keyCode.F2, keyCode.F3, keyCode.F4, keyCode.F5, keyCode.F6, keyCode.F7, keyCode.F8, keyCode.F9, keyCode.F10, keyCode.F11, keyCode.F12, keyCode.TAB, keyCode.PAGE_DOWN, keyCode.PAGE_UP, keyCode.ENTER, keyCode.ESCAPE, keyCode.SHIFT, keyCode.CAPS_LOCK, keyCode.ALT ]; return metaKeys.indexOf(_keyCode) != -1; } export function isCtrlKey(_keyCode) { return [keyCode.CONTROL_LEFT, 224, keyCode.COMMAND_LEFT, keyCode.COMMAND_RIGHT].indexOf(_keyCode) != -1; } /** * Converts a value to string * @param value * @return {String} */ export function stringify(value) { switch (typeof value) { case 'string': case 'number': return value + ''; case 'object': if (value === null) { return ''; } else { return value.toString(); } break; case 'undefined': return ''; default: return value.toString(); } } /** * Convert string to upper case first letter. * * @param {String} string String to convert. * @returns {String} */ export function toUpperCaseFirst(string) { return string[0].toUpperCase() + string.substr(1); } /** * Compare strings case insensitively. * * @param {...String} strings Strings to compare. * @returns {Boolean} */ export function equalsIgnoreCase(...strings) { let unique = []; let length = strings.length; while (length --) { let string = stringify(strings[length]).toLowerCase(); if (unique.indexOf(string) === -1) { unique.push(string); } } return unique.length === 1; } /** * Generate schema for passed object * * @param {Array|Object} object * @returns {Array|Object} */ export function duckSchema(object) { var schema; if (Array.isArray(object)) { schema = []; } else { schema = {}; for (var i in object) { if (object.hasOwnProperty(i)) { if (object[i] && typeof object[i] === 'object' && !Array.isArray(object[i])) { schema[i] = duckSchema(object[i]); } else if (Array.isArray(object[i])) { if (object[i].length && typeof object[i][0] === 'object' && !Array.isArray(object[i][0])) { schema[i] = [duckSchema(object[i][0])]; } else { schema[i] = []; } } else { schema[i] = null; } } } } return schema; } /** * Generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB, etc * @param index * @returns {String} */ export function spreadsheetColumnLabel(index) { var dividend = index + 1; var columnLabel = ''; var modulo; while (dividend > 0) { modulo = (dividend - 1) % 26; columnLabel = String.fromCharCode(65 + modulo) + columnLabel; dividend = parseInt((dividend - modulo) / 26, 10); } return columnLabel; } /** * Creates 2D array of Excel-like values "A1", "A2", ... * @param rowCount * @param colCount * @returns {Array} */ export function createSpreadsheetData(rowCount, colCount) { rowCount = typeof rowCount === 'number' ? rowCount : 100; colCount = typeof colCount === 'number' ? colCount : 4; var rows = [] , i , j; for (i = 0; i < rowCount; i++) { var row = []; for (j = 0; j < colCount; j++) { row.push(spreadsheetColumnLabel(j) + (i + 1)); } rows.push(row); } return rows; } export function createSpreadsheetObjectData(rowCount, colCount) { rowCount = typeof rowCount === 'number' ? rowCount : 100; colCount = typeof colCount === 'number' ? colCount : 4; var rows = [] , i , j; for (i = 0; i < rowCount; i++) { var row = {}; for (j = 0; j < colCount; j++) { row['prop' + j] = spreadsheetColumnLabel(j) + (i + 1); } rows.push(row); } return rows; } /** * Checks if value of n is a numeric one * http://jsperf.com/isnan-vs-isnumeric/4 * @param n * @returns {boolean} */ export function isNumeric(n) { var t = typeof n; return t == 'number' ? !isNaN(n) && isFinite(n) : t == 'string' ? !n.length ? false : n.length == 1 ? /\d/.test(n) : /^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) : t == 'object' ? !!n && typeof n.valueOf() == "number" && !(n instanceof Date) : false; } /** * Generates a random hex string. Used as namespace for Handsontable instance events. * @return {String} - 16 character random string: "92b1bfc74ec4" */ export function randomString() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + s4() + s4(); } /** * Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`. * Creates temporary dummy function to call it as constructor. * Described in ticket: https://github.com/handsontable/handsontable/pull/516 * @param {Object} Child child class * @param {Object} Parent parent class * @return {Object} extended Child */ export function inherit(Child, Parent) { Parent.prototype.constructor = Parent; Child.prototype = new Parent(); Child.prototype.constructor = Child; return Child; } /** * Perform shallow extend of a target object with extension's own properties * @param {Object} target An object that will receive the new properties * @param {Object} extension An object containing additional properties to merge into the target */ export function extend(target, extension) { for (var i in extension) { if (extension.hasOwnProperty(i)) { target[i] = extension[i]; } } } /** * Perform deep extend of a target object with extension's own properties * @param {Object} target An object that will receive the new properties * @param {Object} extension An object containing additional properties to merge into the target */ export function deepExtend(target, extension) { for (var key in extension) { if (extension.hasOwnProperty(key)) { if (extension[key] && typeof extension[key] === 'object') { if (!target[key]) { if (Array.isArray(extension[key])) { target[key] = []; } else { target[key] = {}; } } deepExtend(target[key], extension[key]); } else { target[key] = extension[key]; } } } } /** * Perform deep clone of an object * WARNING! Only clones JSON properties. Will cause error when `obj` contains a function, Date, etc * @param {Object} obj An object that will be cloned * @return {Object} */ export function deepClone(obj) { if (typeof obj === "object") { return JSON.parse(JSON.stringify(obj)); } else { return obj; } } /** * Checks if two objects or arrays are (deep) equal * * @param {Object|Array} object1 * @param {Object|Array} object2 * @returns {Boolean} */ export function isObjectEquals(object1, object2) { return JSON.stringify(object1) === JSON.stringify(object2); } export function getPrototypeOf(obj) { var prototype; /* jshint ignore:start */ if(typeof obj.__proto__ == "object"){ prototype = obj.__proto__; } else { var oldConstructor, constructor = obj.constructor; if (typeof obj.constructor == "function") { oldConstructor = constructor; if (delete obj.constructor){ constructor = obj.constructor; // get real constructor obj.constructor = oldConstructor; // restore constructor } } prototype = constructor ? constructor.prototype : null; // needed for IE } /* jshint ignore:end */ return prototype; } /** * Factory for columns constructors. * @param {Object} GridSettings * @param {Array} conflictList * @return {Object} ColumnSettings */ export function columnFactory(GridSettings, conflictList) { function ColumnSettings () {} inherit(ColumnSettings, GridSettings); // Clear conflict settings for (var i = 0, len = conflictList.length; i < len; i++) { ColumnSettings.prototype[conflictList[i]] = void 0; } return ColumnSettings; } export function translateRowsToColumns(input) { var i , ilen , j , jlen , output = [] , olen = 0; for (i = 0, ilen = input.length; i < ilen; i++) { for (j = 0, jlen = input[i].length; j < jlen; j++) { if (j == olen) { output.push([]); olen++; } output[j].push(input[i][j]); } } return output; } export function to2dArray(arr) { var i = 0 , ilen = arr.length; while (i < ilen) { arr[i] = [arr[i]]; i++; } } export function extendArray(arr, extension) { var i = 0 , ilen = extension.length; while (i < ilen) { arr.push(extension[i]); i++; } } /** * Determines if the given DOM element is an input field. * Notice: By 'input' we mean input, textarea and select nodes * @param element - DOM element * @returns {boolean} */ export function isInput(element) { var inputs = ['INPUT', 'SELECT', 'TEXTAREA']; return inputs.indexOf(element.nodeName) > -1 || element.contentEditable === 'true'; } /** * Determines if the given DOM element is an input field placed OUTSIDE of HOT. * Notice: By 'input' we mean input, textarea and select nodes * @param element - DOM element * @returns {boolean} */ export function isOutsideInput(element) { return isInput(element) && element.className.indexOf('handsontableInput') == -1 && element.className.indexOf('copyPaste') == -1; } export var keyCode = { MOUSE_LEFT: 1, MOUSE_RIGHT: 3, MOUSE_MIDDLE: 2, BACKSPACE: 8, COMMA: 188, INSERT: 45, DELETE: 46, END: 35, ENTER: 13, ESCAPE: 27, CONTROL_LEFT: 91, COMMAND_LEFT: 17, COMMAND_RIGHT: 93, ALT: 18, HOME: 36, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, SPACE: 32, SHIFT: 16, CAPS_LOCK: 20, TAB: 9, ARROW_RIGHT: 39, ARROW_LEFT: 37, ARROW_UP: 38, ARROW_DOWN: 40, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123, A: 65, X: 88, C: 67, V: 86 }; /** * Determines whether given object is a plain Object. * Note: String and Array are not plain Objects * @param {*} obj * @returns {boolean} */ export function isObject(obj) { return Object.prototype.toString.call(obj) == '[object Object]'; } export function pivot(arr) { var pivotedArr = []; if(!arr || arr.length === 0 || !arr[0] || arr[0].length === 0){ return pivotedArr; } var rowCount = arr.length; var colCount = arr[0].length; for(var i = 0; i < rowCount; i++){ for(var j = 0; j < colCount; j++){ if(!pivotedArr[j]){ pivotedArr[j] = []; } pivotedArr[j][i] = arr[i][j]; } } return pivotedArr; } export function proxy(fun, context) { return function () { return fun.apply(context, arguments); }; } /** * Factory that produces a function for searching methods (or any properties) which could be defined directly in * table configuration or implicitly, within cell type definition. * * For example: renderer can be defined explicitly using "renderer" property in column configuration or it can be * defined implicitly using "type" property. * * Methods/properties defined explicitly always takes precedence over those defined through "type". * * If the method/property is not found in an object, searching is continued recursively through prototype chain, until * it reaches the Object.prototype. * * * @param methodName {String} name of the method/property to search (i.e. 'renderer', 'validator', 'copyable') * @param allowUndefined {Boolean} [optional] if false, the search is continued if methodName has not been found in cell "type" * @returns {Function} */ export function cellMethodLookupFactory(methodName, allowUndefined) { allowUndefined = typeof allowUndefined == 'undefined' ? true : allowUndefined; return function cellMethodLookup (row, col) { return (function getMethodFromProperties(properties) { if (!properties){ return; //method not found } else if (properties.hasOwnProperty(methodName) && properties[methodName] !== void 0) { //check if it is own and is not empty return properties[methodName]; //method defined directly } else if (properties.hasOwnProperty('type') && properties.type) { //check if it is own and is not empty var type; if(typeof properties.type != 'string' ){ throw new Error('Cell type must be a string '); } type = translateTypeNameToObject(properties.type); if (type.hasOwnProperty(methodName)) { return type[methodName]; //method defined in type. } else if (allowUndefined) { return; //method does not defined in type (eg. validator), returns undefined } } return getMethodFromProperties(getPrototypeOf(properties)); })(typeof row == 'number' ? this.getCellMeta(row, col) : row); }; function translateTypeNameToObject(typeName) { var type = Handsontable.cellTypes[typeName]; if(typeof type == 'undefined'){ throw new Error('You declared cell type "' + typeName + '" as a string that is not mapped to a known object. ' + 'Cell type must be an object or a string mapped to an object in Handsontable.cellTypes'); } return type; } } export function isMobileBrowser(userAgent) { if(!userAgent) { userAgent = navigator.userAgent; } return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)); // Logic for checking the specific mobile browser // /* var type = type != void 0 ? type.toLowerCase() : '' , result; switch(type) { case '': result = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)); return result; break; case 'ipad': return navigator.userAgent.indexOf('iPad') > -1; break; case 'android': return navigator.userAgent.indexOf('Android') > -1; break; case 'windows': return navigator.userAgent.indexOf('IEMobile') > -1; break; default: throw new Error('Invalid isMobileBrowser argument'); break; } */ } export function isTouchSupported() { return ('ontouchstart' in window); } export function stopPropagation(event) { // ie8 //http://msdn.microsoft.com/en-us/library/ie/ff975462(v=vs.85).aspx if (typeof (event.stopPropagation) === 'function') { event.stopPropagation(); } else { event.cancelBubble = true; } } export function pageX(event) { if (event.pageX) { return event.pageX; } var scrollLeft = dom.getWindowScrollLeft(); var cursorX = event.clientX + scrollLeft; return cursorX; } export function pageY(event) { if (event.pageY) { return event.pageY; } var scrollTop = dom.getWindowScrollTop(); var cursorY = event.clientY + scrollTop; return cursorY; } export function defineGetter(object, property, value, options) { options.value = value; options.writable = options.writable === false ? false : true; options.enumerable = options.enumerable === false ? false : true; options.configurable = options.configurable === false ? false : true; Object.defineProperty(object, property, options); } // https://gist.github.com/paulirish/1579671 let lastTime = 0; let vendors = ['ms', 'moz', 'webkit', 'o']; let _requestAnimationFrame = window.requestAnimationFrame; let _cancelAnimationFrame = window.cancelAnimationFrame; for (let x = 0; x < vendors.length && !_requestAnimationFrame; ++x) { _requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; _cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; } if (!_requestAnimationFrame) { _requestAnimationFrame = function(callback) { let currTime = new Date().getTime(); let timeToCall = Math.max(0, 16 - (currTime - lastTime)); let id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } if (!_cancelAnimationFrame) { _cancelAnimationFrame = function(id) { clearTimeout(id); }; } /** * Polyfill for requestAnimationFrame * * @param {Function} callback * @returns {Number} */ export function requestAnimationFrame(callback) { return _requestAnimationFrame.call(window, callback); } /** * Polyfill for cancelAnimationFrame * * @param {Number} id */ export function cancelAnimationFrame(id) { _cancelAnimationFrame.call(window, id); } window.Handsontable = window.Handsontable || {}; // support for older versions of Handsontable Handsontable.helper = { cancelAnimationFrame, cellMethodLookupFactory, columnFactory, createSpreadsheetData, createSpreadsheetObjectData, deepClone, deepExtend, defineGetter, duckSchema, equalsIgnoreCase, extend, extendArray, getPrototypeOf, inherit, isCtrlKey, isInput, isMetaKey, isMobileBrowser, isNumeric, isObject, isObjectEquals, isOutsideInput, isPrintableChar, isTouchSupported, keyCode, pageX, pageY, pivot, proxy, randomString, requestAnimationFrame, spreadsheetColumnLabel, stopPropagation, stringify, to2dArray, toUpperCaseFirst, translateRowsToColumns };
{ "content_hash": "646fcdac3620396525cbb876fe1cd5d6", "timestamp": "", "source": "github", "line_count": 748, "max_line_length": 130, "avg_line_length": 24.15106951871658, "alnum_prop": 0.6370329366177692, "repo_name": "IntexSoft/handsontable", "id": "c77edda07f8853a34c2d87c37dec72d6d6bd56c7", "size": "18065", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/helpers.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "109442" }, { "name": "HTML", "bytes": "337352" }, { "name": "JavaScript", "bytes": "4211103" }, { "name": "PHP", "bytes": "6763" } ], "symlink_target": "" }
<?php use Illuminate\Contracts\Support\Htmlable; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Illuminate\Support\Env; use Illuminate\Support\HigherOrderTapProxy; use Illuminate\Support\Optional; if (! function_exists('append_config')) { /** * Assign high numeric IDs to a config item to force appending. * * @param array $array * @return array */ function append_config(array $array) { $start = 9999; foreach ($array as $key => $value) { if (is_numeric($key)) { $start++; $array[$start] = Arr::pull($array, $key); } } return $array; } } if (! function_exists('blank')) { /** * Determine if the given value is "blank". * * @param mixed $value * @return bool */ function blank($value) { if (is_null($value)) { return true; } if (is_string($value)) { return trim($value) === ''; } if (is_numeric($value) || is_bool($value)) { return false; } if ($value instanceof Countable) { return count($value) === 0; } return empty($value); } } if (! function_exists('class_basename')) { /** * Get the class "basename" of the given object / class. * * @param string|object $class * @return string */ function class_basename($class) { $class = is_object($class) ? get_class($class) : $class; return basename(str_replace('\\', '/', $class)); } } if (! function_exists('class_uses_recursive')) { /** * Returns all traits used by a class, its parent classes and trait of their traits. * * @param object|string $class * @return array */ function class_uses_recursive($class) { if (is_object($class)) { $class = get_class($class); } $results = []; foreach (array_reverse(class_parents($class)) + [$class => $class] as $class) { $results += trait_uses_recursive($class); } return array_unique($results); } } if (! function_exists('collect')) { /** * Create a collection from the given value. * * @param mixed $value * @return \Illuminate\Support\Collection */ function collect($value = null) { return new Collection($value); } } if (! function_exists('data_fill')) { /** * Fill in data where it's missing. * * @param mixed $target * @param string|array $key * @param mixed $value * @return mixed */ function data_fill(&$target, $key, $value) { return data_set($target, $key, $value, false); } } if (! function_exists('data_get')) { /** * Get an item from an array or object using "dot" notation. * * @param mixed $target * @param string|array|int $key * @param mixed $default * @return mixed */ function data_get($target, $key, $default = null) { if (is_null($key)) { return $target; } $key = is_array($key) ? $key : explode('.', $key); while (! is_null($segment = array_shift($key))) { if ($segment === '*') { if ($target instanceof Collection) { $target = $target->all(); } elseif (! is_array($target)) { return value($default); } $result = []; foreach ($target as $item) { $result[] = data_get($item, $key); } return in_array('*', $key) ? Arr::collapse($result) : $result; } if (Arr::accessible($target) && Arr::exists($target, $segment)) { $target = $target[$segment]; } elseif (is_object($target) && isset($target->{$segment})) { $target = $target->{$segment}; } else { return value($default); } } return $target; } } if (! function_exists('data_set')) { /** * Set an item on an array or object using dot notation. * * @param mixed $target * @param string|array $key * @param mixed $value * @param bool $overwrite * @return mixed */ function data_set(&$target, $key, $value, $overwrite = true) { $segments = is_array($key) ? $key : explode('.', $key); if (($segment = array_shift($segments)) === '*') { if (! Arr::accessible($target)) { $target = []; } if ($segments) { foreach ($target as &$inner) { data_set($inner, $segments, $value, $overwrite); } } elseif ($overwrite) { foreach ($target as &$inner) { $inner = $value; } } } elseif (Arr::accessible($target)) { if ($segments) { if (! Arr::exists($target, $segment)) { $target[$segment] = []; } data_set($target[$segment], $segments, $value, $overwrite); } elseif ($overwrite || ! Arr::exists($target, $segment)) { $target[$segment] = $value; } } elseif (is_object($target)) { if ($segments) { if (! isset($target->{$segment})) { $target->{$segment} = []; } data_set($target->{$segment}, $segments, $value, $overwrite); } elseif ($overwrite || ! isset($target->{$segment})) { $target->{$segment} = $value; } } else { $target = []; if ($segments) { data_set($target[$segment], $segments, $value, $overwrite); } elseif ($overwrite) { $target[$segment] = $value; } } return $target; } } if (! function_exists('e')) { /** * Encode HTML special characters in a string. * * @param \Illuminate\Contracts\Support\Htmlable|string $value * @param bool $doubleEncode * @return string */ function e($value, $doubleEncode = true) { if ($value instanceof Htmlable) { return $value->toHtml(); } return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', $doubleEncode); } } if (! function_exists('env')) { /** * Gets the value of an environment variable. * * @param string $key * @param mixed $default * @return mixed */ function env($key, $default = null) { return Env::get($key, $default); } } if (! function_exists('filled')) { /** * Determine if a value is "filled". * * @param mixed $value * @return bool */ function filled($value) { return ! blank($value); } } if (! function_exists('head')) { /** * Get the first element of an array. Useful for method chaining. * * @param array $array * @return mixed */ function head($array) { return reset($array); } } if (! function_exists('last')) { /** * Get the last element from an array. * * @param array $array * @return mixed */ function last($array) { return end($array); } } if (! function_exists('object_get')) { /** * Get an item from an object using "dot" notation. * * @param object $object * @param string $key * @param mixed $default * @return mixed */ function object_get($object, $key, $default = null) { if (is_null($key) || trim($key) == '') { return $object; } foreach (explode('.', $key) as $segment) { if (! is_object($object) || ! isset($object->{$segment})) { return value($default); } $object = $object->{$segment}; } return $object; } } if (! function_exists('optional')) { /** * Provide access to optional objects. * * @param mixed $value * @param callable|null $callback * @return mixed */ function optional($value = null, callable $callback = null) { if (is_null($callback)) { return new Optional($value); } elseif (! is_null($value)) { return $callback($value); } } } if (! function_exists('preg_replace_array')) { /** * Replace a given pattern with each value in the array in sequentially. * * @param string $pattern * @param array $replacements * @param string $subject * @return string */ function preg_replace_array($pattern, array $replacements, $subject) { return preg_replace_callback($pattern, function () use (&$replacements) { foreach ($replacements as $key => $value) { return array_shift($replacements); } }, $subject); } } if (! function_exists('retry')) { /** * Retry an operation a given number of times. * * @param int $times * @param callable $callback * @param int $sleep * @param callable $when * @return mixed * * @throws \Exception */ function retry($times, callable $callback, $sleep = 0, $when = null) { $attempts = 0; beginning: $attempts++; $times--; try { return $callback($attempts); } catch (Exception $e) { if ($times < 1 || ($when && ! $when($e))) { throw $e; } if ($sleep) { usleep($sleep * 1000); } goto beginning; } } } if (! function_exists('tap')) { /** * Call the given Closure with the given value then return the value. * * @param mixed $value * @param callable|null $callback * @return mixed */ function tap($value, $callback = null) { if (is_null($callback)) { return new HigherOrderTapProxy($value); } $callback($value); return $value; } } if (! function_exists('throw_if')) { /** * Throw the given exception if the given condition is true. * * @param mixed $condition * @param \Throwable|string $exception * @param array ...$parameters * @return mixed * * @throws \Throwable */ function throw_if($condition, $exception, ...$parameters) { if ($condition) { throw (is_string($exception) ? new $exception(...$parameters) : $exception); } return $condition; } } if (! function_exists('throw_unless')) { /** * Throw the given exception unless the given condition is true. * * @param mixed $condition * @param \Throwable|string $exception * @param array ...$parameters * @return mixed * @throws \Throwable */ function throw_unless($condition, $exception, ...$parameters) { if (! $condition) { throw (is_string($exception) ? new $exception(...$parameters) : $exception); } return $condition; } } if (! function_exists('trait_uses_recursive')) { /** * Returns all traits used by a trait and its traits. * * @param string $trait * @return array */ function trait_uses_recursive($trait) { $traits = class_uses($trait); foreach ($traits as $trait) { $traits += trait_uses_recursive($trait); } return $traits; } } if (! function_exists('transform')) { /** * Transform the given value if it is present. * * @param mixed $value * @param callable $callback * @param mixed $default * @return mixed|null */ function transform($value, callable $callback, $default = null) { if (filled($value)) { return $callback($value); } if (is_callable($default)) { return $default($value); } return $default; } } if (! function_exists('value')) { /** * Return the default value of the given value. * * @param mixed $value * @return mixed */ function value($value) { return $value instanceof Closure ? $value() : $value; } } if (! function_exists('windows_os')) { /** * Determine whether the current environment is Windows based. * * @return bool */ function windows_os() { return PHP_OS_FAMILY === 'Windows'; } } if (! function_exists('with')) { /** * Return the given value, optionally passed through the given callback. * * @param mixed $value * @param callable|null $callback * @return mixed */ function with($value, callable $callback = null) { return is_null($callback) ? $value : $callback($value); } }
{ "content_hash": "0fd530b01c6ad1547105fffde9532ef9", "timestamp": "", "source": "github", "line_count": 548, "max_line_length": 88, "avg_line_length": 24.045620437956206, "alnum_prop": 0.49586400546406617, "repo_name": "jerguslejko/framework", "id": "632ee0369d7818f811eea9427e91b7c4556a8324", "size": "13177", "binary": false, "copies": "1", "ref": "refs/heads/6.x", "path": "src/Illuminate/Support/helpers.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "4768" }, { "name": "HTML", "bytes": "30490" }, { "name": "Hack", "bytes": "37" }, { "name": "JavaScript", "bytes": "2966" }, { "name": "PHP", "bytes": "6141802" }, { "name": "Shell", "bytes": "3677" }, { "name": "Vue", "bytes": "552" } ], "symlink_target": "" }
package org.opensaml.saml1.core.impl; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.opensaml.common.impl.AbstractSAMLObject; import org.opensaml.saml1.core.NameIdentifier; import org.opensaml.saml1.core.Subject; import org.opensaml.saml1.core.SubjectConfirmation; import org.opensaml.xml.XMLObject; /** * Complete implementation of {@link org.opensaml.saml1.core.Subject} */ public class SubjectImpl extends AbstractSAMLObject implements Subject { /** Contains the NameIdentifier inside the Subject */ private NameIdentifier nameIdentifier; /** Contains the SubjectConfirmation inside the Subject */ private SubjectConfirmation subjectConfirmation; /** * Constructor * * @param namespaceURI the namespace the element is in * @param elementLocalName the local name of the XML element this Object represents * @param namespacePrefix the prefix for the given namespace */ protected SubjectImpl(String namespaceURI, String elementLocalName, String namespacePrefix) { super(namespaceURI, elementLocalName, namespacePrefix); } /** {@inheritDoc} */ public NameIdentifier getNameIdentifier() { return nameIdentifier; } /** {@inheritDoc} */ public void setNameIdentifier(NameIdentifier nameIdentifier) throws IllegalArgumentException { this.nameIdentifier = prepareForAssignment(this.nameIdentifier, nameIdentifier); } /** {@inheritDoc} */ public SubjectConfirmation getSubjectConfirmation() { return subjectConfirmation; } /** {@inheritDoc} */ public void setSubjectConfirmation(SubjectConfirmation subjectConfirmation) throws IllegalArgumentException { this.subjectConfirmation = prepareForAssignment(this.subjectConfirmation, subjectConfirmation); } /** {@inheritDoc} */ public List<XMLObject> getOrderedChildren() { List<XMLObject> list = new ArrayList<XMLObject>(2); if (nameIdentifier != null) { list.add(nameIdentifier); } if (subjectConfirmation != null) { list.add(subjectConfirmation); } if (list.size() == 0) { return null; } return Collections.unmodifiableList(list); } }
{ "content_hash": "bcd81d778d7c86bf020ea136edb6bbde", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 113, "avg_line_length": 30.64, "alnum_prop": 0.7049608355091384, "repo_name": "Safewhere/kombit-service-java", "id": "997045e0945c1a2d64b35462bc993a2effc7dfb2", "size": "3142", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "OpenSaml/src/org/opensaml/saml1/core/impl/SubjectImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "73985" }, { "name": "Java", "bytes": "5965174" } ], "symlink_target": "" }
package com.bourdi_bay.WindowsRemote; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.content.SharedPreferences; import com.bourdi_bay.WindowsRemote.Communication.Bluetooth.BluetoothPreferences; import com.bourdi_bay.WindowsRemote.Input.InputContract; import com.bourdi_bay.WindowsRemote.Input.InputPreferencesBuilder; import com.bourdi_bay.WindowsRemote.Utils.BluetoothUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyString; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest({BluetoothAdapter.class, SharedPreferences.class, Context.class}) public class InputPreferencesBuilderTest { static final String bluetooth_not_enabled = "not enabled"; static final String bluetooth_not_supported = "not supported"; static final String bluetooth_not_activated = "not activated"; static final String no_device_to_connect = "no connect"; private InputPreferencesBuilder mInputPreferencesBuilder; @Mock private InputContract.View mInputView; @Mock private SharedPreferences mSharedPreferences; @Mock private Context mContext; @Before public void setupSettingsPresenter() { MockitoAnnotations.initMocks(this); mInputPreferencesBuilder = new InputPreferencesBuilder(mInputView); when(mContext.getString(R.string.bluetooth_preferences_bluetooth_not_enabled)).thenReturn(bluetooth_not_enabled); when(mContext.getString(R.string.bluetooth_preferences_bluetooth_not_activated)).thenReturn(bluetooth_not_activated); when(mContext.getString(R.string.bluetooth_preferences_bluetooth_not_supported)).thenReturn(bluetooth_not_supported); when(mContext.getString(R.string.bluetooth_preferences_no_device_to_connect)).thenReturn(no_device_to_connect); when(mSharedPreferences.getBoolean(anyString(), anyBoolean())).thenReturn(true); when(mSharedPreferences.getString(anyString(), anyString())).thenReturn("Something"); } @Test public void buildBluetoothPreferences_validPreferences() { BluetoothAdapter bluetoothAdapter = BluetoothUtils.setBluetoothAvailable(true); BluetoothDevice bluetoothDevice = mock(BluetoothDevice.class); when(bluetoothAdapter.getRemoteDevice(anyString())).thenReturn(bluetoothDevice); BluetoothPreferences bluetoothPreferences = mInputPreferencesBuilder.buildBluetoothPreferences(mContext, mSharedPreferences); assertNotNull(bluetoothPreferences); assertEquals(bluetoothDevice, bluetoothPreferences.mBluetoothDevice); assertTrue(BluetoothPreferences.mLastError.isEmpty()); } @Test public void buildBluetoothPreferences_nullPreferences_notEnabled() { BluetoothUtils.setBluetoothAvailable(false); BluetoothPreferences bluetoothPreferences = mInputPreferencesBuilder.buildBluetoothPreferences(mContext, mSharedPreferences); assertNull(bluetoothPreferences); assertEquals(bluetooth_not_enabled, BluetoothPreferences.mLastError); } @Test public void buildBluetoothPreferences_nullPreferences_notSupported() { BluetoothUtils.setBluetoothNotSupported(); BluetoothPreferences bluetoothPreferences = mInputPreferencesBuilder.buildBluetoothPreferences(mContext, mSharedPreferences); assertNull(bluetoothPreferences); assertEquals(bluetooth_not_supported, BluetoothPreferences.mLastError); } @Test public void buildBluetoothPreferences_nullPreferences_notActivated() { when(mSharedPreferences.getBoolean(anyString(), anyBoolean())).thenReturn(false); BluetoothPreferences bluetoothPreferences = mInputPreferencesBuilder.buildBluetoothPreferences(mContext, mSharedPreferences); assertNull(bluetoothPreferences); assertEquals(bluetooth_not_activated, BluetoothPreferences.mLastError); } @Test public void buildBluetoothPreferences_nullPreferences_noDevicesToConnect() { BluetoothUtils.setBluetoothAvailable(true); when(mSharedPreferences.getString(anyString(), anyString())).thenReturn(null); BluetoothPreferences bluetoothPreferences = mInputPreferencesBuilder.buildBluetoothPreferences(mContext, mSharedPreferences); assertNull(bluetoothPreferences); assertEquals(no_device_to_connect, BluetoothPreferences.mLastError); } }
{ "content_hash": "a3220b6fcb10e3739298091f33b83525", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 133, "avg_line_length": 43.18103448275862, "alnum_prop": 0.7883809143541625, "repo_name": "bourdibay/WindowsRemote", "id": "1fef3426df7fd01be94934e0879704981924037e", "size": "5009", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AndroidClient/app/src/test/java/com/bourdi_bay/WindowsRemote/InputPreferencesBuilderTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1705" }, { "name": "C", "bytes": "41648" }, { "name": "C++", "bytes": "1705" }, { "name": "CMake", "bytes": "4916" }, { "name": "Java", "bytes": "90025" } ], "symlink_target": "" }
package com.tiny.demo.firstlinecode.ui.view; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import com.tiny.demo.firstlinecode.R; import com.tiny.demo.firstlinecode.base.BaseActivity; import com.tiny.demo.firstlinecode.ui.bean.StockEditBean; import com.tiny.demo.firstlinecode.ui.swipe.SwipeDeleteRecyclerViewActivity; import java.util.ArrayList; import butterknife.BindView; import butterknife.OnClick; /** * 常用控件的基本使用 */ public class UiActivity extends BaseActivity { @BindView(R.id.btn_recycler_view_drag_and_delete) Button btnRecyclerViewDragAndDelete; @BindView(R.id.btn_recycler_view_swipe) Button btnRecyclerViewSwipe; private Button btnDefault; private Button btnH; private ProgressBar pH; private ProgressBar pD; public static void actionStart(Context context) { Intent intent = new Intent(context, UiActivity.class); context.startActivity(intent); } @Override protected int setContentLayout() { return R.layout.activity_ui; } @Override protected void buildContentView() { btnDefault = findViewById(R.id.btn_progress_default); pD = findViewById(R.id.progress_default); btnDefault.setOnClickListener(v -> { if (pD.getVisibility() == View.VISIBLE) { pD.setVisibility(View.GONE); } else { pD.setVisibility(View.VISIBLE); } }); btnH = findViewById(R.id.btn_progress_horizontal); pH = findViewById(R.id.progress_horizontal); btnH.setOnClickListener(v -> { int progress = pH.getProgress(); progress = progress + 10; pH.setProgress(progress); }); //alertDialog findViewById(R.id.btn_alert_dialog).setOnClickListener(v -> { AlertDialog.Builder dialog = new AlertDialog.Builder(UiActivity.this); dialog.setTitle("This is a alert dialog"); dialog.setMessage("Something important"); dialog.setCancelable(true); dialog.setPositiveButton("ok", (dialog12, which) -> dialog12.dismiss()); dialog.setNegativeButton("cancel", (dialog1, which) -> dialog1.dismiss()); dialog.show(); }); //progress dialog findViewById(R.id.btn_progress_dialog).setOnClickListener(v -> { ProgressDialog progressDialog = new ProgressDialog(UiActivity.this); progressDialog.setTitle("This is a progress diialog!"); progressDialog.setMessage("Loading..."); progressDialog.setCancelable(true); progressDialog.show(); }); //百分比布局 findViewById(R.id.btn_percent_layout).setOnClickListener(v -> startActivity(new Intent(UiActivity.this, PercentLayoutActivity.class))); //listview的简单使用 findViewById(R.id.btn_listview).setOnClickListener(v -> ListViewActivity.actionStart(mContext)); findViewById(R.id.btn_recycle_view_vertical).setOnClickListener(v -> RecyclerViewVerticalActivity.actionStart(mContext)); findViewById(R.id.btn_recycle_view_horizontal).setOnClickListener(v -> RecyclerViewHorizontalActivity.actionStart(mContext)); findViewById(R.id.btn_recycle_view_flow).setOnClickListener(v -> RecyclerViewFlowActivity.actionStart(mContext)); findViewById(R.id.btn_recycle_view_grid).setOnClickListener(v -> startActivity(new Intent(mContext, RecycleViewGridActivity.class))); //ViewFipper findViewById(R.id.btn_view_fipper).setOnClickListener(v -> startActivity(new Intent(mContext, ViewFlipperActivity.class))); findViewById(R.id.btn_recycler_view_multiple_item).setOnClickListener(v -> startActivity(new Intent(mContext, RecyclerViewMultiItemActivity1.class))); findViewById(R.id.btn_recycler_view_multiple_item_bravh).setOnClickListener(v -> startActivity(new Intent(mContext, RecyclerViewMultiItemBravhActivity.class))); } @Override protected void initViewData() { } @OnClick(R.id.btn_recycler_view_drag_and_delete) public void onViewClicked() { ArrayList<StockEditBean> list = new ArrayList<>(); for (int j = 0; j < 100; j++) { StockEditBean bean = new StockEditBean(); bean.setCode("60000" + j); bean.setName("猫了个咪" + j); bean.setChecked(false); list.add(bean); } Bundle bundle = new Bundle(); bundle.putParcelableArrayList(DragRecyclerViewActivity.STOCK_LIST, list); activitySwitchWithBundle(DragRecyclerViewActivity.class, bundle); } @OnClick(R.id.btn_recycler_view_swipe) public void onRecyclerViewSwipeClicked() { activitySwitch(SwipeDeleteRecyclerViewActivity.class); } @OnClick(R.id.btn_expandable_listview) public void onExpandableListViewClicked() { activitySwitch(ExpandableListViewActivity.class); } }
{ "content_hash": "a9f8165da78afe3559ab436e13ea13f4", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 168, "avg_line_length": 38.803030303030305, "alnum_prop": 0.6844982428738774, "repo_name": "tinyvampirepudge/Android_Basis_Demo", "id": "0bf843d3c7d4336ec97b21278135d625d479568d", "size": "5168", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Android_Basis_Demo/app/src/main/java/com/tiny/demo/firstlinecode/ui/view/UiActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "4434358" } ], "symlink_target": "" }
/** * Annotations and supporting classes for declarative cache management. * Hooked into Spring's cache interception infrastructure via * {@link org.springframework.cache.interceptor.CacheOperationSource}. */ @NonNullApi @NonNullFields package org.springframework.cache.annotation; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
{ "content_hash": "13c0422189eb1cc211b3ceb8f255fd3a", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 71, "avg_line_length": 34.36363636363637, "alnum_prop": 0.8227513227513228, "repo_name": "spring-projects/spring-framework", "id": "0a53f33ac3b4000eec3484ac5098ee85932eac6c", "size": "378", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spring-context/src/main/java/org/springframework/cache/annotation/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "32003" }, { "name": "CSS", "bytes": "1019" }, { "name": "Dockerfile", "bytes": "257" }, { "name": "FreeMarker", "bytes": "30820" }, { "name": "Groovy", "bytes": "6902" }, { "name": "HTML", "bytes": "1203" }, { "name": "Java", "bytes": "43939386" }, { "name": "JavaScript", "bytes": "280" }, { "name": "Kotlin", "bytes": "571613" }, { "name": "PLpgSQL", "bytes": "305" }, { "name": "Python", "bytes": "254" }, { "name": "Ruby", "bytes": "1060" }, { "name": "Shell", "bytes": "5374" }, { "name": "Smarty", "bytes": "700" }, { "name": "XSLT", "bytes": "2945" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "432fb49d9eaf5c51f2bd3ae262ba73e6", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "7e9e2c5155917945f77048e7582110af74c9ae64", "size": "211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Rhodophyta/Florideophyceae/Nemaliales/Galaxauraceae/Galaxaura/Galaxaura rugosa/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.kuali.kfs.module.cam.businessobject; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.ACCOUNT_NUMBER; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.AMOUNT; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.CHART_OF_ACCOUNTS_CODE; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.DOCUMENT_NUMBER; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.DOCUMENT_POSTING_DATE; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.DOCUMENT_TYPE_CODE; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.FINANCIAL_OBJECT_CODE; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.ORGANIZATION_REFERENCE_ID; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.ORIGINATION_CODE; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.PROJECT_CODE; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.PURCHASE_ORDER; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.REQUISITION_NUMBER; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.SUB_ACCOUNT_NUMBER; import static org.kuali.kfs.module.cam.CamsPropertyConstants.AssetPaymentDetail.SUB_OBJECT_CODE; import org.kuali.kfs.sys.businessobject.AccountingLineParserBase; public class AssetPaymentAccountingLineParser extends AccountingLineParserBase { protected static final String[] AP_FORMAT = { CHART_OF_ACCOUNTS_CODE, ACCOUNT_NUMBER, SUB_ACCOUNT_NUMBER, FINANCIAL_OBJECT_CODE, SUB_OBJECT_CODE, PROJECT_CODE, ORGANIZATION_REFERENCE_ID, AMOUNT, PURCHASE_ORDER, REQUISITION_NUMBER, ORIGINATION_CODE, DOCUMENT_NUMBER, DOCUMENT_TYPE_CODE, DOCUMENT_POSTING_DATE }; public AssetPaymentAccountingLineParser() { super(); } /** * * @see org.kuali.kfs.sys.businessobject.AccountingLineParserBase#getSourceAccountingLineFormat() */ @Override public String[] getSourceAccountingLineFormat() { return removeChartFromFormatIfNeeded(AP_FORMAT); } }
{ "content_hash": "ef98d15a3865f9ec1bd1ad6d849876b9", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 154, "avg_line_length": 52.63636363636363, "alnum_prop": 0.7979274611398963, "repo_name": "Ariah-Group/Finance", "id": "c6df5d50597f3380d062ee012774aab90e8e7fbe", "size": "2934", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "af_webapp/src/main/java/org/kuali/kfs/module/cam/businessobject/AssetPaymentAccountingLineParser.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BindingDemos")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BindingDemos")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "c0a71a40e2080b1f82e1c3bdb5d228d1", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 98, "avg_line_length": 43.27272727272727, "alnum_prop": 0.7071428571428572, "repo_name": "raisaurabh777/WPF", "id": "6ea70ff16b3f16c8f2a9a03ccb5d8f09d147c0bc", "size": "2383", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BindingTutorials/BindingDemos/BindingDemos/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "47833" } ], "symlink_target": "" }
var zrUtil = require('zrender/lib/core/util'); var graphic = require('../../util/graphic'); var formatUtil = require('../../util/format'); var layout = require('../../util/layout'); var echarts = require('../../echarts'); var VisualMapping = require('../../visual/VisualMapping'); module.exports = echarts.extendComponentView({ type: 'visualMap', /** * @readOnly * @type {Object} */ autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1}, init: function (ecModel, api) { /** * @readOnly * @type {module:echarts/model/Global} */ this.ecModel = ecModel; /** * @readOnly * @type {module:echarts/ExtensionAPI} */ this.api = api; /** * @readOnly * @type {module:echarts/component/visualMap/visualMapModel} */ this.visualMapModel; }, /** * @protected */ render: function (visualMapModel, ecModel, api, payload) { this.visualMapModel = visualMapModel; if (visualMapModel.get('show') === false) { this.group.removeAll(); return; } this.doRender.apply(this, arguments); }, /** * @protected */ renderBackground: function (group) { var visualMapModel = this.visualMapModel; var padding = formatUtil.normalizeCssArray(visualMapModel.get('padding') || 0); var rect = group.getBoundingRect(); group.add(new graphic.Rect({ z2: -1, // Lay background rect on the lowest layer. silent: true, shape: { x: rect.x - padding[3], y: rect.y - padding[0], width: rect.width + padding[3] + padding[1], height: rect.height + padding[0] + padding[2] }, style: { fill: visualMapModel.get('backgroundColor'), stroke: visualMapModel.get('borderColor'), lineWidth: visualMapModel.get('borderWidth') } })); }, /** * @protected * @param {number} targetValue can be Infinity or -Infinity * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize' * @param {Object} [opts] * @param {string=} [opts.forceState] Specify state, instead of using getValueState method. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget. * @return {*} Visual value. */ getControllerVisual: function (targetValue, visualCluster, opts) { opts = opts || {}; var forceState = opts.forceState; var visualMapModel = this.visualMapModel; var visualObj = {}; // Default values. if (visualCluster === 'symbol') { visualObj.symbol = visualMapModel.get('itemSymbol'); } if (visualCluster === 'color') { var defaultColor = visualMapModel.get('contentColor'); visualObj.color = defaultColor; } function getter(key) { return visualObj[key]; } function setter(key, value) { visualObj[key] = value; } var mappings = visualMapModel.controllerVisuals[ forceState || visualMapModel.getValueState(targetValue) ]; var visualTypes = VisualMapping.prepareVisualTypes(mappings); zrUtil.each(visualTypes, function (type) { var visualMapping = mappings[type]; if (opts.convertOpacityToAlpha && type === 'opacity') { type = 'colorAlpha'; visualMapping = mappings.__alphaForOpacity; } if (VisualMapping.dependsOn(type, visualCluster)) { visualMapping && visualMapping.applyVisual( targetValue, getter, setter ); } }); return visualObj[visualCluster]; }, /** * @protected */ positionGroup: function (group) { var model = this.visualMapModel; var api = this.api; layout.positionElement( group, model.getBoxLayoutParams(), {width: api.getWidth(), height: api.getHeight()} ); }, /** * @protected * @abstract */ doRender: zrUtil.noop });
{ "content_hash": "3b284e396bae8439020e0f406e69a91b", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 103, "avg_line_length": 31.681818181818183, "alnum_prop": 0.4875999180159869, "repo_name": "angustas/company", "id": "af4407271d3b1e49c6061e5c7c7ee3cd6d83ad21", "size": "4879", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "node_modules/echarts/lib/component/visualMap/VisualMapView.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "333" }, { "name": "CSS", "bytes": "506507" }, { "name": "HTML", "bytes": "6167" }, { "name": "JavaScript", "bytes": "4843688" }, { "name": "PHP", "bytes": "1754384" } ], "symlink_target": "" }
package com.amazon.dtasdk.serializer; public class SerializationException extends Exception { private static final long serialVersionUID = -3095196341869438153L; public SerializationException(String message) { super(message); } public SerializationException(Throwable cause) { super(cause); } public SerializationException(String message, Throwable cause) { super(message, cause); } }
{ "content_hash": "ff61fa4cd317b148d89895b1e04a83e4", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 71, "avg_line_length": 24.5, "alnum_prop": 0.7165532879818595, "repo_name": "amzn/amazon-instant-access-sdk-java", "id": "e63c6f71bec134c67c6a73ce7403b0956fa7f46d", "size": "1028", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/amazon/dtasdk/serializer/SerializationException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "251312" }, { "name": "Shell", "bytes": "66" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "6ba8c9b0b533bac148a4bf2b67ddec2e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "0118fb24855020a96b3d40a492a9daf0b8dd7566", "size": "194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Lactuca/Lactuca acanthifolia/ Syn. Scariola acanthifolia/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.commons.net.util; import java.io.Serializable; import java.util.EventListener; import java.util.Iterator; import java.util.concurrent.CopyOnWriteArrayList; /** */ public class ListenerList implements Serializable, Iterable<EventListener> { private static final long serialVersionUID = -1934227607974228213L; private final CopyOnWriteArrayList<EventListener> __listeners; public ListenerList() { __listeners = new CopyOnWriteArrayList<EventListener>(); } public void addListener(EventListener listener) { __listeners.add(listener); } public void removeListener(EventListener listener) { __listeners.remove(listener); } public int getListenerCount() { return __listeners.size(); } /** * Return an {@link Iterator} for the {@link EventListener} instances. * * @return an {@link Iterator} for the {@link EventListener} instances * @since 2.0 * TODO Check that this is a good defensive strategy */ // @Override public Iterator<EventListener> iterator() { return __listeners.iterator(); } }
{ "content_hash": "84858e04f81a79de4faf713f05e75b7a", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 74, "avg_line_length": 22.96078431372549, "alnum_prop": 0.6660973526900086, "repo_name": "codolutions/commons-net", "id": "178f3ba4817823077719049cc1fa3433cc48e88a", "size": "1973", "binary": false, "copies": "4", "ref": "refs/heads/trunk", "path": "src/main/java/org/apache/commons/net/util/ListenerList.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2102078" }, { "name": "Shell", "bytes": "157" } ], "symlink_target": "" }
$:.push File.expand_path("../../../../vendor/addressable-2.2.6/lib", __FILE__) $:.push File.expand_path("../../../../vendor/libwebsocket-0.1.0/lib", __FILE__) require "addressable/uri" require "socket" require "libwebsocket" module WebSocket class SimpleClient def initialize(url, params = {}) @hs ||= LibWebSocket::OpeningHandshake::Client.new(:url => url, :version => params[:version]) @frame ||= LibWebSocket::Frame.new @socket = TCPSocket.new(@hs.url.host, @hs.url.port || 80) @socket.write(@hs.to_s) @socket.flush loop do data = @socket.getc next if data.nil? result = @hs.parse(data.chr) raise @hs.error unless result if @hs.done? @handshaked = true break end end end def send(data) raise "no handshake!" unless @handshaked data = @frame.new(data).to_s @socket.write data @socket.flush end def receive raise "no handshake!" unless @handshaked data = @socket.gets("\xff") @frame.append(data) messages = [] while message = @frame.next messages << message end messages end def socket @socket end def close @socket.close end end end
{ "content_hash": "a89c1a43a32db18b817296d5d863bee3", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 99, "avg_line_length": 19.430555555555557, "alnum_prop": 0.5253752680486061, "repo_name": "boblail/tsatsiki", "id": "c9bbc6d13b45288d9a1f0abc3a2b52857fa781fc", "size": "1485", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/tsatsiki/web_socket/simple_client.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "5823" }, { "name": "Ruby", "bytes": "88215" } ], "symlink_target": "" }
package de.tum.in.schlichter.shoprx.importer; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import de.tum.in.schlichter.shoprx.R; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import au.com.bytecode.opencsv.CSVReader; import de.tum.in.schlichter.androidutils.Lists; import de.tum.in.schlichter.shoprx.context.model.Company; import de.tum.in.schlichter.shoprx.context.model.DayOfTheWeek; import de.tum.in.schlichter.shoprx.context.model.Temperature; import de.tum.in.schlichter.shoprx.context.model.TimeOfTheDay; import de.tum.in.schlichter.shoprx.context.model.Weather; import de.tum.in.schlichter.shoprx.loaders.ShopLoader; import de.tum.in.schlichter.shoprx.provider.ShoprContract.ContextItemRelation; import de.tum.in.schlichter.shoprx.provider.ShoprContract.Items; import de.tum.in.schlichter.shoprx.provider.ShoprContract.Shops; /** * Imports items or shops from a CSV file into the database. */ public class CsvImportTask extends AsyncTask<Void, Integer, String> { public enum Type { IMPORT_SHOPS, IMPORT_ITEMS, IMPORT_CONTEXT } private static final String TAG = "Importer"; private Context mContext; private Uri mUri; private Type mType; private InputStream mInputStream; public CsvImportTask(Context context, Uri uri, CsvImportTask.Type type) { mContext = context; mUri = uri; mType = type; } @Override protected void onPreExecute() { Toast.makeText(mContext, R.string.action_import, Toast.LENGTH_SHORT).show(); // get input stream on main thread to avoid it being cleaned up Log.d(TAG, "Opening file."); try { mInputStream = mContext.getContentResolver().openInputStream(mUri); } catch (FileNotFoundException e) { Log.e(TAG, "Could not open file. " + e.getMessage()); } } @Override protected String doInBackground(Void... params) { if (mInputStream == null) { return "Input stream is null."; } CSVReader reader = new CSVReader(new InputStreamReader(mInputStream)); // read shops line by line Log.d(TAG, "Reading values."); ArrayList<ContentValues> newValues = Lists.newArrayList(); try { String[] firstLine = reader.readNext(); // skip first line if (firstLine == null) { return "No data."; } if ((mType == Type.IMPORT_ITEMS && firstLine.length != 11) || mType == Type.IMPORT_SHOPS && firstLine.length != 9 || mType == Type.IMPORT_CONTEXT && firstLine.length != 6) { Log.d(TAG, "Invalid column count."); return "Invalid column count."; } int numberOfShops = 0; if (mType == Type.IMPORT_ITEMS){ ShopLoader loader = new ShopLoader(mContext); numberOfShops = loader.loadInBackground().size(); } else if (mType == Type.IMPORT_SHOPS){ numberOfShops = 1; } Log.d(TAG, "Importing the following CSV schema: " + Arrays.toString(firstLine)); String[] line; Random random = new Random(123456); // seed to get fixed // distribution int id = 1; while ((line = reader.readNext()) != null) { ContentValues values = new ContentValues(); switch (mType) { case IMPORT_CONTEXT: values.put(ContextItemRelation.REF_ITEM_ID, line[0]); values.put(ContextItemRelation.CONTEXT_TIME, TimeOfTheDay.getTimeOfTheDay(line[1]).getTime()); values.put(ContextItemRelation.CONTEXT_DAY, DayOfTheWeek.getDay(line[2]).getDay()); values.put(ContextItemRelation.CONTEXT_TEMPERATURE, Temperature.getTemperature(line[3]).getDegrees()); values.put(ContextItemRelation.CONTEXT_HUMIDITY, Weather.getWeather(line[4]).getWeatherIndicator()); values.put(ContextItemRelation.CONTEXT_COMPANY, Company.getCompany(line[5]).getCompanyType()); break; case IMPORT_SHOPS: // add values for one shop values.put(Shops._ID, numberOfShops); //Ensures that we have all IDs even though there might be some missing in the CSV. values.put(Shops.NAME, line[1]); values.put(Shops.OPENING_HOURS, line[2]); values.put(Shops.LAT, line[5]); values.put(Shops.LONG, line[6]); values.put(Shops.CROWDED, random.nextInt(5)); // Every fifth shop will be crowded numberOfShops++; break; case IMPORT_ITEMS: // add values for one item values.put(Items._ID, id); int shopID = id % numberOfShops + 1; // 0 is inclusive but n exclusive, we start at 1 with our IDs values.put(Shops.REF_SHOP_ID, shopID); values.put(Items.COLOR, line[2]); values.put(Items.PRICE, line[3]); values.put(Items.SEASON, line[4]); values.put(Items.IMAGE_URL, line[5]); values.put(Items.NAME, line[6]); values.put(Items.BRAND, line[7]); values.put(Items.SEX, line[8]); if (line.length==11)values.put(Items.ISTRENDY, line[10]); else values.put(Items.ISTRENDY, 0); //Increment id id++; //Do some really bad string operations! String clothingType = line[9].replace("womens-clothing-", "").replace("mens-clothing-", "").replace("mens-",""); if (clothingType.substring(clothingType.length() - 2).equals("es") && !clothingType.equals("blouses") && ! clothingType.endsWith("hoodies")){ clothingType = clothingType.substring(0, clothingType.length() - 2); } else if (clothingType.charAt(clothingType.length()-1) == 's' && !clothingType.equalsIgnoreCase("Jeans") && !clothingType.equalsIgnoreCase("trousers") && !clothingType.equalsIgnoreCase("shorts")) { clothingType = clothingType.substring(0, clothingType.length() - 1); } if (clothingType.startsWith("jumpers-")){ clothingType = clothingType.replace("jumpers-",""); } clothingType = Character.toUpperCase(clothingType.charAt(0)) + clothingType.substring(1); values.put(Items.CLOTHING_TYPE, clothingType); int stock = random.nextInt(40); // Every 40th-item will have 0 in stock. That makes about 100 items per 4000 items in the case base if (stock > 10){ stock = (stock % 10) + 1; //Modulo 10 in order to achieve an roughly equal distribution but only with every 40th-item being not in stock } values.put(Items.STOCK, stock); break; } newValues.add(values); } } catch (IOException e) { Log.e(TAG, "Could not read file. " + e.getMessage()); return "Could not read file. " + e.getMessage(); } finally { try { reader.close(); } catch (IOException e) { Log.e(TAG, "Could not close file. " + e.getMessage()); } } Log.d("Number of items", "" + newValues.size()); Uri uri; switch (mType) { case IMPORT_CONTEXT: uri = ContextItemRelation.CONTENT_URI; break; case IMPORT_SHOPS: uri = Shops.CONTENT_URI; break; case IMPORT_ITEMS: uri = Items.CONTENT_URI; break; default: return "Invalid import type."; } // clear existing table Log.d(TAG, "Clearing existing data."); mContext.getContentResolver().delete(uri, null, null); // insert into database in one transaction Log.d(TAG, "Inserting new data..."); ContentValues[] valuesArray = new ContentValues[newValues.size()]; valuesArray = newValues.toArray(valuesArray); mContext.getContentResolver().bulkInsert(uri, valuesArray); Log.d(TAG, "Inserting new data...DONE"); return null; } @Override protected void onPostExecute(String result) { Toast.makeText( mContext, result == null ? mContext.getString(R.string.import_successful) : mContext.getString(R.string.import_failed) + " " + result, Toast.LENGTH_SHORT).show(); } }
{ "content_hash": "0fb632d563f0756ff1d8783ace5b9451", "timestamp": "", "source": "github", "line_count": 226, "max_line_length": 222, "avg_line_length": 42.26548672566372, "alnum_prop": 0.5584170854271356, "repo_name": "Spieldichein/ShoprX", "id": "d743ed8c40efddad226b1d5bc3fa3fce9dfd1cc6", "size": "9552", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Android/ShoprX/src/main/java/de/tum/in/schlichter/shoprx/importer/CsvImportTask.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "719827" } ], "symlink_target": "" }
require 'test_helper' class CompaniesControllerTest < ActionController::TestCase setup do @company = companies(:company_1) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:companies) end #test "should get new" do #get :new #assert_response :success #end #test "should create company" do #assert_difference('Company.count') do #post :create, company: { average_rating: @company.average_rating, name: @company.name, phone_number: @company.phone_number } #end #assert_redirected_to company_path(assigns(:company)) #end test "should show company" do get :show, id: @company assert_response :success end #test "should get edit" do #get :edit, id: @company #assert_response :success #end #test "should update company" do #patch :update, id: @company, company: { average_rating: @company.average_rating, name: @company.name, phone_number: @company.phone_number } #assert_redirected_to company_path(assigns(:company)) #end #test "should destroy company" do #assert_difference('Company.count', -1) do #delete :destroy, id: @company #end #assert_redirected_to companies_path #end end
{ "content_hash": "543e4ccd5cb40bde661353f8e54891ac", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 144, "avg_line_length": 25.346938775510203, "alnum_prop": 0.6803542673107891, "repo_name": "TaxiDash/ServerV2", "id": "e69fb227f6c28b2478ba8b9d89ac48714c2946f4", "size": "1242", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/controllers/companies_controller_test.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4095" }, { "name": "CoffeeScript", "bytes": "2954" }, { "name": "JavaScript", "bytes": "664" }, { "name": "Ruby", "bytes": "151641" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width" /> <link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" /> <title>Intellectual Property | Android Developers</title> <!-- STYLESHEETS --> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto"> <link href="../../../assets/css/default.css" rel="stylesheet" type="text/css"> <!-- JAVASCRIPT --> <script src="http://www.google.com/jsapi" type="text/javascript"></script> <script src="../../../assets/js/android_3p-bundle.js" type="text/javascript"></script> <script type="text/javascript"> var toRoot = "../../../"; var devsite = false; </script> <script src="../../../assets/js/docs.js" type="text/javascript"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-5831155-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body class="gc-documentation distribute" itemscope itemtype="http://schema.org/Article"> <a name="top"></a> <!-- Header --> <div id="header"> <div class="wrap" id="header-wrap"> <div class="col-3 logo"> <a href="../../../index.html"> <img src="../../../assets/images/dac_logo.png" width="123" height="25" alt="Android Developers" /> </a> <div class="btn-quicknav" id="btn-quicknav"> <a href="#" class="arrow-inactive">Quicknav</a> <a href="#" class="arrow-active">Quicknav</a> </div> </div> <ul class="nav-x col-9"> <li class="design"> <a href="../../../design/index.html" zh-tw-lang="設計" zh-cn-lang="设计" ru-lang="Проектирование" ko-lang="디자인" ja-lang="設計" es-lang="Diseñar" >Design</a></li> <li class="develop"><a href="../../../develop/index.html" zh-tw-lang="開發" zh-cn-lang="开发" ru-lang="Разработка" ko-lang="개발" ja-lang="開発" es-lang="Desarrollar" >Develop</a></li> <li class="distribute last"><a href="../../../distribute/index.html" zh-tw-lang="發佈" zh-cn-lang="分发" ru-lang="Распространение" ko-lang="배포" ja-lang="配布" es-lang="Distribuir" >Distribute</a></li> </ul> <!-- New Search --> <div class="menu-container"> <div class="moremenu"> <div id="more-btn"></div> </div> <div class="morehover" id="moremenu"> <div class="top"></div> <div class="mid"> <div class="header">Links</div> <ul> <li><a href="https://play.google.com/apps/publish/">Google Play Developer Console</a></li> <li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li> <li><a href="../../../about/index.html">About Android</a></li> </ul> <div class="header">Android Sites</div> <ul> <li><a href="http://www.android.com">Android.com</a></li> <li class="active"><a>Android Developers</a></li> <li><a href="http://source.android.com">Android Open Source Project</a></li> </ul> <br class="clearfix" /> </div> <div class="bottom"></div> </div> <div class="search" id="search-container"> <div class="search-inner"> <div id="search-btn"></div> <div class="left"></div> <form onsubmit="return submit_search()"> <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q" onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)" onkeydown="return search_changed(event, true, '../../../')" onkeyup="return search_changed(event, false, '../../../')" /> </form> <div class="right"></div> <a class="close hide">close</a> <div class="left"></div> <div class="right"></div> </div> </div> <div class="search_filtered_wrapper reference"> <div class="suggest-card reference no-display"> <ul class="search_filtered"> </ul> </div> </div> <div class="search_filtered_wrapper docs"> <div class="suggest-card dummy no-display">&nbsp;</div> <div class="suggest-card develop no-display"> <ul class="search_filtered"> </ul> <div class="child-card guides no-display"> </div> <div class="child-card training no-display"> </div> </div> <div class="suggest-card design no-display"> <ul class="search_filtered"> </ul> </div> <div class="suggest-card distribute no-display"> <ul class="search_filtered"> </ul> </div> </div> </div> <!-- /New Search> <!-- Expanded quicknav --> <div id="quicknav" class="col-9"> <ul> <li class="design"> <ul> <li><a href="../../../design/index.html">Get Started</a></li> <li><a href="../../../design/style/index.html">Style</a></li> <li><a href="../../../design/patterns/index.html">Patterns</a></li> <li><a href="../../../design/building-blocks/index.html">Building Blocks</a></li> <li><a href="../../../design/downloads/index.html">Downloads</a></li> <li><a href="../../../design/videos/index.html">Videos</a></li> </ul> </li> <li class="develop"> <ul> <li><a href="../../../training/index.html" zh-tw-lang="訓練課程" zh-cn-lang="培训" ru-lang="Курсы" ko-lang="교육" ja-lang="トレーニング" es-lang="Capacitación" >Training</a></li> <li><a href="../../../guide/components/index.html" zh-tw-lang="API 指南" zh-cn-lang="API 指南" ru-lang="Руководства по API" ko-lang="API 가이드" ja-lang="API ガイド" es-lang="Guías de la API" >API Guides</a></li> <li><a href="../../../reference/packages.html" zh-tw-lang="參考資源" zh-cn-lang="参考" ru-lang="Справочник" ko-lang="참조문서" ja-lang="リファレンス" es-lang="Referencia" >Reference</a></li> <li><a href="../../../tools/index.html" zh-tw-lang="相關工具" zh-cn-lang="工具" ru-lang="Инструменты" ko-lang="도구" ja-lang="ツール" es-lang="Herramientas" >Tools</a> <ul><li><a href="../../../sdk/index.html">Get the SDK</a></li></ul> </li> <li><a href="../../../google/index.html">Google Services</a> </li> </ul> </li> <li class="distribute last"> <ul> <li><a href="../../../distribute/index.html">Google Play</a></li> <li><a href="../../../distribute/googleplay/publish/index.html">Publishing</a></li> <li><a href="../../../distribute/googleplay/promote/index.html">Promoting</a></li> <li><a href="../../../distribute/googleplay/quality/index.html">App Quality</a></li> <li><a href="../../../distribute/googleplay/spotlight/index.html">Spotlight</a></li> <li><a href="../../../distribute/open.html">Open Distribution</a></li> </ul> </li> </ul> </div> <!-- /Expanded quicknav --> </div> </div> <!-- /Header --> <div id="searchResults" class="wrap" style="display:none;"> <h2 id="searchTitle">Results</h2> <div id="leftSearchControl" class="search-control">Loading...</div> </div> <div class="wrap clearfix" id="body-content"> <div class="col-3" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement"> <div id="devdoc-nav" class="scroll-pane"> <a class="totop" href="#top" data-g-event="left-nav-top">to top</a> <ul id="nav"> <li class="nav-section"> <div class="nav-section-header"><a href="../../../distribute/index.html">Google Play</a></div> <ul> <li><a href="../../../distribute/googleplay/about/visibility.html">Visibility</a></li> <li><a href="../../../distribute/googleplay/about/monetizing.html">Monetizing</a></li> <li><a href="../../../distribute/googleplay/about/distribution.html">Distribution</a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../distribute/googleplay/publish/index.html">Publishing</a></div> <ul> <li><a href="../../../distribute/googleplay/publish/register.html">Get Started</a></li> <li><a href="../../../distribute/googleplay/publish/console.html">Developer Console</a></li> <li><a href="../../../distribute/googleplay/publish/localizing.html">Localization Checklist</a></li> <li><a href="../../../distribute/googleplay/publish/preparing.html">Launch Checklist</a></li> </ul> </li> <!-- <li class="nav-section"> <div class="nav-section-header"> <a href="../../../distribute/googleplay/developer-console.html">The Developer Console</a> </div> <ul> <li class="nav-section"><a href="../../../distribute/googleplay/register.html">Get Started</a></li> <li><a href="../../../distribute/googleplay/distribution-controls.html">Managing Distribution</a></li> <li><a href="../../../distribute/googleplay/pricing-billing.html">Pricing and Billing</a></li> <li><a href="../../../distribute/googleplay/app-data.html">Reviewing App Data</a></li> <li><a href="../../../distribute/googleplay/advanced-options.html">Advanced Options</a></li> <li><a href="../../../distribute/googleplay/publishing.html">Publishing and Updating</a></li> </ul> </li> end of Developer Console --> <li class="nav-section"> <div class="nav-section-header"><a href="../../../distribute/googleplay/promote/index.html">Promoting</a> </div> <ul> <!-- <li><a href="../../../distribute/googleplay/promote/product-pages.html">Your Product Pages</a></li> --> <li><a href="../../../distribute/googleplay/promote/linking.html">Linking to Your Products</a></li> <li><a href="../../../distribute/googleplay/promote/badges.html">Google Play Badges</a></li> <li><a href="../../../distribute/promote/device-art.html">Device Art Generator</a></li> <li><a href="../../../distribute/googleplay/promote/brand.html">Brand Guidelines</a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../distribute/googleplay/quality/index.html">App Quality</a></div> <ul> <li><a href="../../../distribute/googleplay/quality/core.html">Core App Quality</a></li> <li><a href="../../../distribute/googleplay/quality/tablet.html">Tablet App Quality</a></li> <li><a href="../../../distribute/googleplay/strategies/app-quality.html">Improving App Quality</a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../distribute/googleplay/policies/index.html">Policies</a></div> <ul> <li><a href="../../../distribute/googleplay/policies/spam.html">Spam</a></li> <li><a href="../../../distribute/googleplay/policies/ip.html">Intellectual<br />Property</a></li> <li><a href="../../../distribute/googleplay/policies/ads.html">Ads</a></li> </ul> </li> <!-- <li class="nav-section"> <div class="nav-section-header"><a href="../../../distribute/googleplay/after.html"> After Launch</a> </div> <ul> <li><a href="../../../distribute/googleplay/errors.html.html">Reviewing Errors</a></li> <li><a href="../../../distribute/googleplay/reviews.html">Tracking User Reviews</a></li> <li><a href="../../../distribute/googleplay/supporting-users.html">Supporting Users</a></li> </ul> </li> --> <li class="nav-section"> <div class="nav-section-header"><a href="../../../distribute/googleplay/spotlight/index.html">Spotlight</a></div> <ul> <li><a href="../../../distribute/googleplay/spotlight/tablets.html">Tablet Stories</a></li> <li><a href="../../../distribute/googleplay/spotlight/games.html">Game Stories</a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../distribute/googleplay/edu/index.html">Google Play for Education</a></div> <ul> <li><a href="../../../distribute/googleplay/edu/about.html">About</a></li> <li><a href="../../../distribute/googleplay/edu/start.html">Get Started</a></li> <li><a href="../../../distribute/googleplay/edu/guidelines.html">Guidelines</a></li> <li><a href="../../../distribute/googleplay/edu/contact.html">Sign Up</a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header empty"><a href="../../../distribute/open.html">Open Distribution</a></div> </li> </ul> </div> </div> <!-- end side-nav --> <script> $(document).ready(function() { scrollIntoView("devdoc-nav"); }); </script> <div class="col-13" id="doc-col" > <h1 itemprop="name" >Intellectual Property</h1> <div id="jd-content"> <div class="jd-descr" itemprop="articleBody"> <div id="qv-wrapper"> <div id="qv"> <h2>In This Document</h2> <ol> <li><a href="#copyright">Copyright Infringement</a></li> <li><a href="#impersonation">Impersonation</a></li> <li><a href="#trademarks">Trademark Infringement</a></li> <li><a href="#other">DDA 4.4 Prohibited Actions</a></li> </ol> <h2>More Resources</h2> <ol> <li><a href="http://play.google.com/about/developer-content-policy.html" target="_policies">Developer Program Policies</a></li> <li><a href="http://www.android.com/us/developer-distribution-agreement.html#showlanguages" target="_policies">Developer Distribution Agreement</a></li> </ol> </div> </div> <p> Google Play policies protect your intellectual property (IP) as well as that of other app developers and content creators in the store. The policies and their enforcements help ensure proper use of copyright, trademarks, and developer identity in Google Play. </p> <p> As an app developer, these IP policies benefit you. At the same time, it's your responsibility to ensure that your app does not violate the IP of other developers or content creators. Violations of IP-related policy may result in suspension of your apps from the store and termination of your developer account. </p> <p> This document introduces several key areas of IP-related policy that you should understand before publishing on Google Play. In each area you'll find best practices and examples to help you avoid common types of mistakes and violations. </p> <p> For more information about Google Play policies that apply to your apps and content, please see the <a href= "http://play.google.com/about/developer-content-policy.html" target= "_policies">Developer Program Policies</a> and <a href= "http://play.google.com/about/developer-distribution-agreement.html" target= "_policies">Developer Distribution Agreement</a>. </p> <h2 id="copyright">Copyright Infringement</h2> <p> Copyright is the legal right granted to an author or creator for a literary, dramatic or artistic piece of work. As soon as you create an original piece of work and fix it in a tangible medium, the work is automatically protected by copyright law and you are the owner of the copyright. Likewise, when other people create content, they may own the copyrights for those works. </p> <div class="sidebox-wrapper"> <div class="sidebox"> <h2>How to report infringements</h2> <p>If you feel your copyright is being infringed, you may file a Digital Millenium Copyright Act (DMCA) request. Please see <a href="http://support.google.com/bin/request.py?&product=androidmarket&contact_type=lr_dmca" target="_policies">copyright procedures</a> for more information.</p> </div> </div> <p> Copyright infringement is an improper or unauthorized use of a copyrighted work. If you publish an app in Google Play that uses another party's copyrighted works improperly or without permission, your apps can be suspended and your developer account terminated. </p> <p> As you design your app and prepare for publishing, make sure to review Google Play policies and analyze all of your content. If your app uses or links to another party's original work, make sure that your app is not infringing on copyright. Not all uses of another party’s work are infringements on copyright, and the rules vary by country and can be complex. </p> <p> If you are unsure whether your use of another party's work infringes on a copyright, consider getting legal advice before publishing, or simply request permission to use the work from the copyright owner. </p> <p> Here are some guidelines to help you avoid copyright infringement policy violations: </p> <ul> <li> <strong>Respect copyright laws</strong>&mdash;Do not let your app infringe on the copyrights of others. That includes linking to other apps or web sites that contain obviously infringing material (please refer to the <a href=" ../../../distribute/googleplay/policies/spam.html#webview-spam">Spam in WebViews</a> guidelines), and using icons or images that are obvious infringements. </li> <li> <strong>Know your app's content</strong>&mdash;Before you publish, look for content that may be protected by trademark or copyright in your app and get legal advice if necessary. Protected work could typically include product names, brands, images, music, and similar works. </li> <li> <strong>Create original work</strong>&mdash;If you’re not sure whether something will violate another party's copyright, the safest approach is to create something that's completely original, such as images or audio that you’ve created yourself. When you create your own original content, you rarely have to worry about infringing on existing copyright. </li> <li> <strong>Ask permission to use copyrighted work</strong>&mdash;If you want to use another party's copyrighted work in your app, you should ask for permission from the work's creator or copyright owner and include appropriate copyright attribution. </li> </ul> <p> A common misunderstanding is believing that your app may use copyrighted content without permission, provided that you clearly indicate that your app is not the "official" app that readers may be familiar with. That is not the case. Even if you let users know that your app is "unofficial", it still violates Google Play policies if it uses or links to copyrighted content without permission. Also, this type of "unofficial" app may violate <a href="#impersonation">impersonation policies</a>. </p> <p> The example app below shows an app that uses screenshots/images of known artists without their authorization and lists popular songs. The combination of these may induce users to download music ringtones that infringe on copyright. This is a violation of Google Play policy. </p> <div class="example-block bad" style="width:100%;float:none;margin:.5em auto 2em 0;"> <div class="heading">Images and downloads that violate copyright</div> <img src="../../../images/gp-policy-ip-copyright-violation.png"> </div> <h2 id="impersonation">Impersonation</h2> <p> Impersonation is when an app attempts to imply a relationship to another app or developer, where no relationship actually exists. </p> <p> For example, if your app displays the brand, icon, or title from another app in order to get to users to download your app, you are leading users to believe that your app is developed by the same entity as the other app and offers similar content or experience. This is an impersonation of the other app and developer, and it is a violation of Google Play policy. If you publish apps that violate impersonation policies, your apps can be suspended and your developer account terminated. </p> <p> No matter what type of app you offer or what your motivation, don’t try to imply an endorsement or relationship to another company or product where none exists. Don’t try to establish your app as the "official" version of another party's work by prominently featuring their brand names or trademarks in your app title or description. </p> <p> Even if your app description states that your app is an "unofficial" version, the use of the other app's branding, trademarks, and other content still can violate policy by presenting content that isn’t yours. </p> <p> Here are some guidelines: </p> <ul> <li> <strong>Don't pretend to be someone else</strong>&mdash; Don't represent that your content is produced by another company or organization if that is not the case. </li> <li> <strong>Don't support infringing sites or apps</strong>&mdash; Don't divert users or provide links to any other site that mimics Google Play or represents itself as another application or service. </li> <li> <strong>Don't use another app's branding</strong>&mdash; Don’t try to pass off your app as the official version of someone else’s property by using a person or entity (or brand) name in your app title or description. </li> </ul> <p> Below is an example of an "unofficial" app that violates Google Play policy by impersonating another company and an existing product. Specifically: </p> <ul> <li>The example app has a name and icon that appear to be impersonating an existing product. </li> <li>The example developer name implies an endorsement or relationship to another company and their products where none exists. </li> </ul> <div class="example-block bad" style="width:100%;float:none;margin:.5em auto 2em 0;"> <div class="heading">App name, icon, and developer name that impersonate another</div> <img src="../../../images/gp-policy-ip-impersonation-violation.png"> </div> <h2 id="trademarks">Trademark Infringement</h2> <p> A trademark is a brand that uniquely identifies a product and distinguishes it from other products. It can be a word, name, symbol, or combination of those that is intended to identify the source of the product. A trademark is specifically acquired by a company or other entity through a legal process and once acquired gives the owner exclusive rights to the trademark usage. </p> <div class="sidebox-wrapper"> <div class="sidebox"> <h2>How to report infringements</h2> <p>If you feel your trademark is being infringed, you can request a content review. See <a href="http://support.google.com/bin/static.py?&ts=1114905&page=ts.cs" target="_policies">Removing content from Google</a> for more information.</p> </div> </div> <p> Trademark infringement is improper or unauthorized use of a trademark. Google Play policies prohibit apps that infringe trademarks. If you publish apps in Google Play that use another party's trademarks, your apps can be suspended and your developer account terminated. </p> <p> As you design your app and prepare for publishing, make sure to review Google Play policies and analyze all of your content. If your app uses a trademark not owned by you, or if you are not sure whether a brand is a trademark, you should get legal advice before publishing. As with copyright, the rules vary by country and can be complex. </p> <p> Here are some guidelines for avoiding trademark infringement policy violations: </p> <ul> <li> <strong>Understand and follow trademark laws</strong>&mdash;Don't let your app infringe on the trademarks of others. </li> <li> <strong>Know your app's content</strong>&mdash;Before you publish, look for brands and potential trademarks used in your app and store listing and get legal advice if necessary. </li> <li> <strong>Use a distinct name</strong>&mdash;Don't give your app a name that is confusingly similar to another company's trademark. </li> <li> <strong>Don't use trademarks to imply a relationship</strong>&mdash;Don't describe your app using another company's trademarks in a way that implies an endorsement by or affiliation with the other company. </li> <li> <strong>Use a distinct app icon and logo</strong>&mdash;Don't use a modified version of another company’s trademarked logo. </li> </ul> <p> A common misunderstanding is believing that your app may use a brand or trademark without permission, provided you clearly indicate that the app is not the "official" or original app. That is not the case. Even if you let users know that your app is "unofficial", it still violates Google Play policies if it uses another party's trademarks. Also, this type of "unofficial" app may violate <a href="#impersonation">impersonation policies</a>. </p> <p> Below is an example app that violates Google Play policies by infringing on another party's trademarks. Specifically: </p> <ul> <li>The example app name is confusingly similar to another party's trademark.</li> <li>The example app icon is a modified version of a another party's logo.</li> </ul> <div class="example-block bad" style="width:100%;float:none;margin:.5em auto 2em 0;"> <div class="heading">App name and icon that infringe trademarks</div> <img src="../../../images/gp-policy-ip-trademark-violation.png"> </div> <h2 id="other">DDA 4.4 Prohibited Actions</h2> <p> When you publish an app on Google Play, you agree to the terms of the Developer Distribution Agreement (DDA). Section 4.4 of the DDA prohibits certain types of actions on your part. For reference, you agree that you will not engage in any activity with the Market, including the development or distribution of Products, that interferes with, disrupts, damages, or accesses in an unauthorized manner the devices, servers, networks, or other properties or services of any third party including, but not limited to, Android users, Google or any mobile network operator. </p> <p> For details, please refer to the complete <a href= "http://play.google.com/about/developer-distribution-agreement.html" target= "_policies">Developer Distribution Agreement</a>. </p> </div> <div class="content-footer layout-content-row" itemscope itemtype="http://schema.org/SiteNavigationElement"> <div class="layout-content-col col-9" style="padding-top:4px"> <div class="g-plusone" data-size="medium"></div> </div> <div class="paging-links layout-content-col col-4"> </div> </div> </div> <!-- end jd-content --> <div id="footer" class="wrap" > <div id="copyright"> Except as noted, this content is licensed under <a href="http://creativecommons.org/licenses/by/2.5/"> Creative Commons Attribution 2.5</a>. For details and restrictions, see the <a href="../../../license.html">Content License</a>. </div> <div id="footerlinks"> <p> <a href="../../../about/index.html">About Android</a>&nbsp;&nbsp;|&nbsp; <a href="../../../legal.html">Legal</a>&nbsp;&nbsp;|&nbsp; <a href="../../../support.html">Support</a> </p> </div> </div> <!-- end footer --> </div><!-- end doc-content --> </div> <!-- end body-content --> </body> </html>
{ "content_hash": "c20eec6abe9949c555fe8e89505b8988", "timestamp": "", "source": "github", "line_count": 859, "max_line_length": 159, "avg_line_length": 34.19557625145518, "alnum_prop": 0.614012391911214, "repo_name": "AzureZhao/android-developer-cn", "id": "4c477b6164da047872ae8589aee9523de05b8ae9", "size": "29625", "binary": false, "copies": "2", "ref": "refs/heads/4.4.zh_cn", "path": "distribute/googleplay/policies/ip.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "225261" }, { "name": "HTML", "bytes": "481791360" }, { "name": "JavaScript", "bytes": "640571" } ], "symlink_target": "" }
#import "ORKOrderedTask.h" #import "ORKHelpers.h" #import "ORKVisualConsentStep.h" #import "ORKStep_Private.h" #import "ORKAnswerFormat_Internal.h" #import "ORKActiveStep.h" #import "ORKActiveStep_Internal.h" #import "ORKAudioStepViewController.h" #import "ORKWalkingTaskStepViewController.h" #import "ORKTappingIntervalStep.h" #import "ORKCountdownStepViewController.h" #import "ORKFitnessStepViewController.h" #import "ORKCompletionStep.h" #import "ORKSpatialSpanMemoryStepViewController.h" #import "ORKDefines_Private.h" #import "ORKAudioStep.h" #import "ORKCountdownStep.h" #import "ORKFitnessStep.h" #import "ORKWalkingTaskStep.h" #import "ORKSpatialSpanMemoryStep.h" #import "ORKAccelerometerRecorder.h" #import "ORKAudioRecorder.h" ORKTaskProgress ORKTaskProgressMake(NSUInteger current, NSUInteger total) { return (ORKTaskProgress){.current=current, .total=total}; } @implementation ORKOrderedTask { NSString *_identifier; } - (instancetype)initWithIdentifier:(NSString *)identifier steps:(NSArray *)steps { self = [super init]; if (self) { if ( nil == identifier) { @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"identifier can not be nil." userInfo:nil]; } _identifier = [identifier copy]; _steps = steps; } return self; } - (instancetype)copyWithZone:(NSZone *)zone { ORKOrderedTask *task = [[[self class] allocWithZone:zone] init]; task->_identifier = [_identifier copy]; task->_steps = ORKArrayCopyObjects(_steps); return task; } - (BOOL)isEqual:(id)object { if ([self class] != [object class]) { return NO; } __typeof(self) castObject = object; return (ORKEqualObjects(self.identifier, castObject.identifier) && ORKEqualObjects(self.steps, castObject.steps)); } - (NSUInteger)hash { return [_identifier hash] ^ [_steps hash]; } #pragma mark - ORKTask - (NSString *)identifier { return _identifier; } - (NSUInteger)indexOfStep:(ORKStep *)step { NSUInteger index = [_steps indexOfObject:step]; if (index == NSNotFound) { NSArray *identifiers = [_steps valueForKey:@"identifier"]; index = [identifiers indexOfObject:step.identifier]; } return index; } - (ORKStep *)stepAfterStep:(ORKStep *)step withResult:(ORKTaskResult *)result { NSArray *steps = _steps; if (steps.count <= 0) { return nil; } ORKStep *currentStep = step; ORKStep *nextStep = nil; if (currentStep == nil) { nextStep = steps[0]; } else { NSUInteger index = [self indexOfStep:step]; if (NSNotFound != index && index != (steps.count-1)) { nextStep = steps[index+1]; } } return nextStep; } - (ORKStep *)stepBeforeStep:(ORKStep *)step withResult:(ORKTaskResult *)result { NSArray *steps = _steps; if (steps.count <= 0) { return nil; } ORKStep *currentStep = step; ORKStep *nextStep = nil; if (currentStep == nil) { nextStep = nil; } else { NSUInteger index = [self indexOfStep:step]; if (NSNotFound != index && index != 0) { nextStep = steps[index-1]; } } return nextStep; } - (ORKStep *)stepWithIdentifier:(NSString *)identifier { __block ORKStep *step = nil; [_steps enumerateObjectsUsingBlock:^(ORKStep *obj, NSUInteger idx, BOOL *stop) { if ([obj.identifier isEqualToString:identifier]) { step = obj; *stop = YES; } }]; return step; } - (ORKTaskProgress)progressOfCurrentStep:(ORKStep *)step withResult:(ORKTaskResult *)taskResult { ORKTaskProgress progress; progress.current = [self indexOfStep:step]; progress.total = [_steps count]; if (! [step showsProgress]) { progress.total = 0; } return progress; } - (NSSet *)requestedHealthKitTypesForReading { NSMutableSet *healthTypes = [NSMutableSet set]; for (ORKStep *step in self.steps) { if ([step isKindOfClass:[ORKFormStep class]]) { ORKFormStep *formStep = (ORKFormStep *)step; for (ORKFormItem *formItem in formStep.formItems) { ORKAnswerFormat *answerFormat = [formItem answerFormat]; HKObjectType *objType = [answerFormat healthKitObjectType]; if (objType) { [healthTypes addObject:objType]; } } } else if ([step isKindOfClass:[ORKQuestionStep class]]) { HKObjectType *objType = [[(ORKQuestionStep *)step answerFormat] healthKitObjectType]; if (objType) { [healthTypes addObject:objType]; } } else if ([step isKindOfClass:[ORKActiveStep class]]) { ORKActiveStep *activeStep = (ORKActiveStep *)step; [healthTypes unionSet:[activeStep requestedHealthKitTypesForReading]]; } } return [healthTypes count] ? healthTypes : nil; } - (NSSet *)requestedHealthKitTypesForWriting { return nil; } - (ORKPermissionMask)requestedPermissions { ORKPermissionMask mask = ORKPermissionNone; for (ORKStep *step in self.steps) { if ([step isKindOfClass:[ORKActiveStep class]]) { mask |= [(ORKActiveStep *)step requestedPermissions]; } } return mask; } - (BOOL)providesBackgroundAudioPrompts { BOOL providesAudioPrompts = NO; for (ORKStep *step in self.steps) { if ([step isKindOfClass:[ORKActiveStep class]]) { ORKActiveStep *activeStep = (ORKActiveStep *)step; if ([activeStep hasVoice] || [activeStep hasCountDown]) { providesAudioPrompts = YES; break; } } } return providesAudioPrompts; } #pragma mark - NSSecureCoding + (BOOL)supportsSecureCoding { return YES; } - (void)encodeWithCoder:(NSCoder *)aCoder { ORK_ENCODE_OBJ(aCoder, identifier); ORK_ENCODE_OBJ(aCoder, steps); } - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if (self) { ORK_DECODE_OBJ_CLASS(aDecoder, identifier, NSString); ORK_DECODE_OBJ_ARRAY(aDecoder, steps, ORKStep); for (ORKStep *step in _steps) { if ([step isKindOfClass:[ORKStep class]]) { [step setTask:self]; } } } return self; } #pragma mark - Predefined static NSString * const ORKInstruction0StepIdentifier = @"instruction"; static NSString * const ORKInstruction1StepIdentifier = @"instruction1"; static NSString * const ORKCountdownStepIdentifier = @"countdown"; static NSString * const ORKAudioStepIdentifier = @"audio"; static NSString * const ORKTappingStepIdentifier = @"tapping"; static NSString * const ORKConclusionStepIdentifier = @"conclusion"; static NSString * const ORKFitnessWalkStepIdentifier = @"fitness.walk"; static NSString * const ORKFitnessRestStepIdentifier = @"fitness.rest"; static NSString * const ORKShortWalkOutboundStepIdentifier = @"walking.outbound"; static NSString * const ORKShortWalkReturnStepIdentifier = @"walking.return"; static NSString * const ORKShortWalkRestStepIdentifier = @"walking.rest"; static NSString * const ORKSpatialSpanMemoryStepIdentifier = @"cognitive.memory.spatialspan"; static NSString * const ORKAudioRecorderIdentifier = @"audio"; static NSString * const ORKAccelerometerRecorderIdentifier = @"accelerometer"; static NSString * const ORKPedometerRecorderIdentifier = @"pedometer"; static NSString * const ORKDeviceMotionRecorderIdentifier = @"deviceMotion"; static NSString * const ORKLocationRecorderIdentifier = @"location"; static NSString * const ORKHeartRateRecorderIdentifier = @"heartRate"; + (ORKCompletionStep *)makeCompletionStep { ORKCompletionStep *step = [[ORKCompletionStep alloc] initWithIdentifier:ORKConclusionStepIdentifier]; step.title = ORKLocalizedString(@"TASK_COMPLETE_TITLE", nil); step.text = ORKLocalizedString(@"TASK_COMPLETE_TEXT", nil); step.shouldTintImages = YES; return step; } static void ORKStepArrayAddStep(NSMutableArray *array, ORKStep *step) { [step validateParameters]; [array addObject:step]; } + (ORKOrderedTask *)twoFingerTappingIntervalTaskWithIdentifier:(NSString *)identifier intendedUseDescription:(NSString *)intendedUseDescription duration:(NSTimeInterval)duration options:(ORKPredefinedTaskOption)options { NSString *durationString = [ORKDurationStringFormatter() stringFromTimeInterval:duration]; NSMutableArray *steps = [NSMutableArray array]; if (! (options & ORKPredefinedTaskOptionExcludeInstructions)) { { ORKInstructionStep *step = [[ORKInstructionStep alloc] initWithIdentifier:ORKInstruction0StepIdentifier]; step.title = ORKLocalizedString(@"TAPPING_TASK_TITLE", nil); step.text = intendedUseDescription; step.detailText = ORKLocalizedString(@"TAPPING_INTRO_TEXT", nil); NSString *imageName = @"phonetapping"; if (! [[[NSLocale preferredLanguages] firstObject] hasPrefix:@"en"]) { imageName = [imageName stringByAppendingString:@"_notap"]; } step.image = [UIImage imageNamed:imageName inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil]; step.shouldTintImages = YES; ORKStepArrayAddStep(steps, step); } { ORKInstructionStep *step = [[ORKInstructionStep alloc] initWithIdentifier:ORKInstruction1StepIdentifier]; step.title = ORKLocalizedString(@"TAPPING_TASK_TITLE", nil); NSString *template = ORKLocalizedString(@"TAPPING_INTRO_TEXT_2_FORMAT", nil); step.text = [NSString stringWithFormat:template, durationString]; step.detailText = ORKLocalizedString(@"TAPPING_CALL_TO_ACTION", nil); UIImage *im1 = [UIImage imageNamed:@"handtapping01" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil]; UIImage *im2 = [UIImage imageNamed:@"handtapping02" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil]; step.image = [UIImage animatedImageWithImages:@[im1, im2] duration:1]; step.shouldTintImages = YES; ORKStepArrayAddStep(steps, step); } } { NSMutableArray *recorderConfigurations = [NSMutableArray arrayWithCapacity:5]; if (! (ORKPredefinedTaskOptionExcludeAccelerometer & options)) { [recorderConfigurations addObject:[[ORKAccelerometerRecorderConfiguration alloc] initWithIdentifier:ORKAccelerometerRecorderIdentifier frequency:100]]; } ORKTappingIntervalStep *step = [[ORKTappingIntervalStep alloc] initWithIdentifier:ORKTappingStepIdentifier]; step.title = ORKLocalizedString(@"TAPPING_INSTRUCTION", nil); step.stepDuration = duration; step.shouldContinueOnFinish = YES; step.recorderConfigurations = recorderConfigurations; ORKStepArrayAddStep(steps, step); } if (! (options & ORKPredefinedTaskOptionExcludeConclusion)) { ORKInstructionStep *step = [self makeCompletionStep]; ORKStepArrayAddStep(steps, step); } ORKOrderedTask *task = [[ORKOrderedTask alloc] initWithIdentifier:identifier steps:[steps copy]]; return task; } + (ORKOrderedTask *)audioTaskWithIdentifier:(NSString *)identifier intendedUseDescription:(NSString *)intendedUseDescription speechInstruction:(NSString *)speechInstruction shortSpeechInstruction:(NSString *)shortSpeechInstruction duration:(NSTimeInterval)duration recordingSettings:(NSDictionary *)recordingSettings options:(ORKPredefinedTaskOption)options { NSDictionary *defaultRecordingSettings = @{ AVFormatIDKey : @(kAudioFormatAppleLossless), AVNumberOfChannelsKey : @(2), AVSampleRateKey: @(44100.0) }; recordingSettings = recordingSettings ? : defaultRecordingSettings; if (options & ORKPredefinedTaskOptionExcludeAudio) { @throw [NSException exceptionWithName:NSGenericException reason:@"Audio collection cannot be excluded from audio task" userInfo:nil]; } NSMutableArray *steps = [NSMutableArray array]; if (! (options & ORKPredefinedTaskOptionExcludeInstructions)) { { ORKInstructionStep *step = [[ORKInstructionStep alloc] initWithIdentifier:ORKInstruction0StepIdentifier]; step.title = ORKLocalizedString(@"AUDIO_TASK_TITLE", nil); step.text = intendedUseDescription; step.detailText = ORKLocalizedString(@"AUDIO_INTENDED_USE", nil); step.image = [UIImage imageNamed:@"phonewaves" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil]; step.shouldTintImages = YES; ORKStepArrayAddStep(steps, step); } { ORKInstructionStep *step = [[ORKInstructionStep alloc] initWithIdentifier:ORKInstruction1StepIdentifier]; step.title = ORKLocalizedString(@"AUDIO_TASK_TITLE", nil); step.text = speechInstruction?:ORKLocalizedString(@"AUDIO_INTRO_TEXT",nil); step.detailText = ORKLocalizedString(@"AUDIO_CALL_TO_ACTION", nil); step.image = [UIImage imageNamed:@"phonesoundwaves" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil]; step.shouldTintImages = YES; ORKStepArrayAddStep(steps, step); } } { ORKCountdownStep *step = [[ORKCountdownStep alloc] initWithIdentifier:ORKCountdownStepIdentifier]; step.stepDuration = 5.0; // Collect audio during the countdown step too, to provide a baseline. step.recorderConfigurations = @[[[ORKAudioRecorderConfiguration alloc] initWithIdentifier:ORKAudioRecorderIdentifier recorderSettings:recordingSettings]]; ORKStepArrayAddStep(steps, step); } { ORKAudioStep *step = [[ORKAudioStep alloc] initWithIdentifier:ORKAudioStepIdentifier]; step.title = shortSpeechInstruction ? : ORKLocalizedString(@"AUDIO_INSTRUCTION", nil); step.recorderConfigurations = @[[[ORKAudioRecorderConfiguration alloc] initWithIdentifier:ORKAudioRecorderIdentifier recorderSettings:recordingSettings]]; step.duration = duration; step.shouldContinueOnFinish = YES; ORKStepArrayAddStep(steps, step); } if (! (options & ORKPredefinedTaskOptionExcludeConclusion)) { ORKInstructionStep *step = [self makeCompletionStep]; ORKStepArrayAddStep(steps, step); } ORKOrderedTask *task = [[ORKOrderedTask alloc] initWithIdentifier:identifier steps:steps]; return task; } + (NSDateComponentsFormatter *)textTimeFormatter { NSDateComponentsFormatter *formatter = [NSDateComponentsFormatter new]; formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleSpellOut; // Exception list: Korean, Chinese (all), Thai, and Vietnamese. NSArray *nonSpelledOutLanguages = @[@"ko", @"zh", @"th", @"vi", @"ja"]; NSString *currentLanguage = [[[NSBundle mainBundle] preferredLocalizations] firstObject]; NSString *currentLanguageCode = [NSLocale componentsFromLocaleIdentifier:currentLanguage][NSLocaleLanguageCode]; if ((currentLanguageCode != nil) && [nonSpelledOutLanguages containsObject:currentLanguageCode]) { formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull; } formatter.allowedUnits = NSCalendarUnitMinute | NSCalendarUnitSecond; formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropAll; return formatter; } + (ORKOrderedTask *)fitnessCheckTaskWithIdentifier:(NSString *)identifier intendedUseDescription:(NSString *)intendedUseDescription walkDuration:(NSTimeInterval)walkDuration restDuration:(NSTimeInterval)restDuration options:(ORKPredefinedTaskOption)options { NSDateComponentsFormatter *formatter = [self textTimeFormatter]; NSMutableArray *steps = [NSMutableArray array]; if (! (options & ORKPredefinedTaskOptionExcludeInstructions)) { { ORKInstructionStep *step = [[ORKInstructionStep alloc] initWithIdentifier:ORKInstruction0StepIdentifier]; step.title = ORKLocalizedString(@"FITNESS_TASK_TITLE", nil); step.text = intendedUseDescription ? : [NSString stringWithFormat:ORKLocalizedString(@"FITNESS_INTRO_TEXT_FORMAT", nil), [formatter stringFromTimeInterval:walkDuration]]; step.image = [UIImage imageNamed:@"heartbeat" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil]; step.shouldTintImages = YES; ORKStepArrayAddStep(steps, step); } { ORKInstructionStep *step = [[ORKInstructionStep alloc] initWithIdentifier:ORKInstruction1StepIdentifier]; step.title = ORKLocalizedString(@"FITNESS_TASK_TITLE", nil); step.text = [NSString stringWithFormat:ORKLocalizedString(@"FITNESS_INTRO_2_TEXT_FORMAT", nil), [formatter stringFromTimeInterval:walkDuration], [formatter stringFromTimeInterval:restDuration]]; step.image = [UIImage imageNamed:@"walkingman" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil]; step.shouldTintImages = YES; ORKStepArrayAddStep(steps, step); } } { ORKCountdownStep * step = [[ORKCountdownStep alloc] initWithIdentifier:ORKCountdownStepIdentifier]; step.stepDuration = 5.0; ORKStepArrayAddStep(steps, step); } HKUnit *bpmUnit = [[HKUnit countUnit] unitDividedByUnit:[HKUnit minuteUnit]]; HKQuantityType *heartRateType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate]; { if (walkDuration > 0) { NSMutableArray *recorderConfigurations = [NSMutableArray arrayWithCapacity:5]; if (! (ORKPredefinedTaskOptionExcludePedometer & options)) { [recorderConfigurations addObject:[[ORKPedometerRecorderConfiguration alloc] initWithIdentifier:ORKPedometerRecorderIdentifier]]; } if (! (ORKPredefinedTaskOptionExcludeAccelerometer & options)) { [recorderConfigurations addObject:[[ORKAccelerometerRecorderConfiguration alloc] initWithIdentifier:ORKAccelerometerRecorderIdentifier frequency:100]]; } if (! (ORKPredefinedTaskOptionExcludeDeviceMotion & options)) { [recorderConfigurations addObject:[[ORKDeviceMotionRecorderConfiguration alloc] initWithIdentifier:ORKDeviceMotionRecorderIdentifier frequency:100]]; } if (! (ORKPredefinedTaskOptionExcludeLocation & options)) { [recorderConfigurations addObject:[[ORKLocationRecorderConfiguration alloc] initWithIdentifier:ORKLocationRecorderIdentifier]]; } if (! (ORKPredefinedTaskOptionExcludeHeartRate & options)) { [recorderConfigurations addObject:[[ORKHealthQuantityTypeRecorderConfiguration alloc] initWithIdentifier:ORKHeartRateRecorderIdentifier healthQuantityType:heartRateType unit:bpmUnit]]; } ORKFitnessStep *fitnessStep = [[ORKFitnessStep alloc] initWithIdentifier:ORKFitnessWalkStepIdentifier]; fitnessStep.stepDuration = walkDuration; fitnessStep.title = [NSString stringWithFormat:ORKLocalizedString(@"FITNESS_WALK_INSTRUCTION_FORMAT", nil), [formatter stringFromTimeInterval:walkDuration]]; fitnessStep.spokenInstruction = fitnessStep.title; fitnessStep.recorderConfigurations = recorderConfigurations; fitnessStep.shouldShowDefaultTimer = NO; fitnessStep.shouldContinueOnFinish = YES; fitnessStep.optional = NO; fitnessStep.shouldStartTimerAutomatically = YES; fitnessStep.shouldTintImages = YES; fitnessStep.image = [UIImage imageNamed:@"walkingman" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil]; fitnessStep.shouldVibrateOnStart = YES; fitnessStep.shouldPlaySoundOnStart = YES; ORKStepArrayAddStep(steps, fitnessStep); } if (restDuration > 0) { NSMutableArray *recorderConfigurations = [NSMutableArray arrayWithCapacity:5]; if (! (ORKPredefinedTaskOptionExcludeAccelerometer & options)) { [recorderConfigurations addObject:[[ORKAccelerometerRecorderConfiguration alloc] initWithIdentifier:ORKAccelerometerRecorderIdentifier frequency:100]]; } if (! (ORKPredefinedTaskOptionExcludeDeviceMotion & options)) { [recorderConfigurations addObject:[[ORKDeviceMotionRecorderConfiguration alloc] initWithIdentifier:ORKDeviceMotionRecorderIdentifier frequency:100]]; } if (! (ORKPredefinedTaskOptionExcludeHeartRate & options)) { [recorderConfigurations addObject:[[ORKHealthQuantityTypeRecorderConfiguration alloc] initWithIdentifier:ORKHeartRateRecorderIdentifier healthQuantityType:heartRateType unit:bpmUnit]]; } ORKFitnessStep *stillStep = [[ORKFitnessStep alloc] initWithIdentifier:ORKFitnessRestStepIdentifier]; stillStep.stepDuration = restDuration; stillStep.title = [NSString stringWithFormat:ORKLocalizedString(@"FITNESS_SIT_INSTRUCTION_FORMAT", nil), [formatter stringFromTimeInterval:restDuration]]; stillStep.spokenInstruction = stillStep.title; stillStep.recorderConfigurations = recorderConfigurations; stillStep.shouldShowDefaultTimer = NO; stillStep.shouldContinueOnFinish = YES; stillStep.optional = NO; stillStep.shouldStartTimerAutomatically = YES; stillStep.shouldTintImages = YES; stillStep.image = [UIImage imageNamed:@"sittingman" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil]; stillStep.shouldVibrateOnStart = YES; stillStep.shouldPlaySoundOnStart = YES; stillStep.shouldPlaySoundOnFinish = YES; stillStep.shouldVibrateOnFinish = YES; ORKStepArrayAddStep(steps, stillStep); } } if (! (options & ORKPredefinedTaskOptionExcludeConclusion)) { ORKInstructionStep *step = [self makeCompletionStep]; ORKStepArrayAddStep(steps, step); } ORKOrderedTask *task = [[ORKOrderedTask alloc] initWithIdentifier:identifier steps:steps]; return task; } + (ORKOrderedTask *)shortWalkTaskWithIdentifier:(NSString *)identifier intendedUseDescription:(NSString *)intendedUseDescription numberOfStepsPerLeg:(NSInteger)numberOfStepsPerLeg restDuration:(NSTimeInterval)restDuration options:(ORKPredefinedTaskOption)options { NSDateComponentsFormatter *formatter = [self textTimeFormatter]; NSMutableArray *steps = [NSMutableArray array]; if (! (options & ORKPredefinedTaskOptionExcludeInstructions)) { { ORKInstructionStep *step = [[ORKInstructionStep alloc] initWithIdentifier:ORKInstruction0StepIdentifier]; step.title = ORKLocalizedString(@"WALK_TASK_TITLE", nil); step.text = intendedUseDescription; step.detailText = ORKLocalizedString(@"WALK_INTRO_TEXT", nil); step.shouldTintImages = YES; ORKStepArrayAddStep(steps, step); } { ORKInstructionStep *step = [[ORKInstructionStep alloc] initWithIdentifier:ORKInstruction1StepIdentifier]; step.title = ORKLocalizedString(@"WALK_TASK_TITLE", nil); step.text = [NSString stringWithFormat:ORKLocalizedString(@"WALK_INTRO_2_TEXT_%ld", nil),numberOfStepsPerLeg]; step.detailText = ORKLocalizedString(@"WALK_INTRO_2_DETAIL", nil); step.image = [UIImage imageNamed:@"pocket" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil]; step.shouldTintImages = YES; ORKStepArrayAddStep(steps, step); } } { ORKCountdownStep * step = [[ORKCountdownStep alloc] initWithIdentifier:ORKCountdownStepIdentifier]; step.stepDuration = 5.0; ORKStepArrayAddStep(steps, step); } { { NSMutableArray *recorderConfigurations = [NSMutableArray array]; if (! (ORKPredefinedTaskOptionExcludePedometer & options)) { [recorderConfigurations addObject:[[ORKPedometerRecorderConfiguration alloc] initWithIdentifier:ORKPedometerRecorderIdentifier]]; } if (! (ORKPredefinedTaskOptionExcludeAccelerometer & options)) { [recorderConfigurations addObject:[[ORKAccelerometerRecorderConfiguration alloc] initWithIdentifier:ORKAccelerometerRecorderIdentifier frequency:100]]; } if (! (ORKPredefinedTaskOptionExcludeDeviceMotion & options)) { [recorderConfigurations addObject:[[ORKDeviceMotionRecorderConfiguration alloc] initWithIdentifier:ORKDeviceMotionRecorderIdentifier frequency:100]]; } ORKWalkingTaskStep *walkingStep = [[ORKWalkingTaskStep alloc] initWithIdentifier:ORKShortWalkOutboundStepIdentifier]; walkingStep.numberOfStepsPerLeg = numberOfStepsPerLeg; walkingStep.title = [NSString stringWithFormat:ORKLocalizedString(@"WALK_OUTBOUND_INSTRUCTION_FORMAT", nil), (long long)numberOfStepsPerLeg]; walkingStep.spokenInstruction = walkingStep.title; walkingStep.recorderConfigurations = recorderConfigurations; walkingStep.shouldShowDefaultTimer = NO; walkingStep.shouldContinueOnFinish = YES; walkingStep.optional = NO; walkingStep.shouldStartTimerAutomatically = YES; walkingStep.stepDuration = numberOfStepsPerLeg * 1.5; // fallback duration in case no step count walkingStep.shouldVibrateOnStart = YES; walkingStep.shouldPlaySoundOnStart = YES; ORKStepArrayAddStep(steps, walkingStep); } { NSMutableArray *recorderConfigurations = [NSMutableArray array]; if (! (ORKPredefinedTaskOptionExcludePedometer & options)) { [recorderConfigurations addObject:[[ORKPedometerRecorderConfiguration alloc] initWithIdentifier:ORKPedometerRecorderIdentifier]]; } if (! (ORKPredefinedTaskOptionExcludeAccelerometer & options)) { [recorderConfigurations addObject:[[ORKAccelerometerRecorderConfiguration alloc] initWithIdentifier:ORKAccelerometerRecorderIdentifier frequency:100]]; } if (! (ORKPredefinedTaskOptionExcludeDeviceMotion & options)) { [recorderConfigurations addObject:[[ORKDeviceMotionRecorderConfiguration alloc] initWithIdentifier:ORKDeviceMotionRecorderIdentifier frequency:100]]; } ORKWalkingTaskStep *walkingStep = [[ORKWalkingTaskStep alloc] initWithIdentifier:ORKShortWalkReturnStepIdentifier]; walkingStep.numberOfStepsPerLeg = numberOfStepsPerLeg; walkingStep.title = [NSString stringWithFormat:ORKLocalizedString(@"WALK_RETURN_INSTRUCTION_FORMAT", nil), (long long)numberOfStepsPerLeg]; walkingStep.spokenInstruction = walkingStep.title; walkingStep.recorderConfigurations = recorderConfigurations; walkingStep.shouldShowDefaultTimer = NO; walkingStep.shouldContinueOnFinish = YES; walkingStep.shouldStartTimerAutomatically = YES; walkingStep.optional = NO; walkingStep.stepDuration = numberOfStepsPerLeg * 1.5; // fallback duration in case no step count walkingStep.shouldVibrateOnStart = YES; walkingStep.shouldPlaySoundOnStart = YES; ORKStepArrayAddStep(steps, walkingStep); } if (restDuration > 0) { NSMutableArray *recorderConfigurations = [NSMutableArray array]; if (! (ORKPredefinedTaskOptionExcludeAccelerometer & options)) { [recorderConfigurations addObject:[[ORKAccelerometerRecorderConfiguration alloc] initWithIdentifier:ORKAccelerometerRecorderIdentifier frequency:100]]; } if (! (ORKPredefinedTaskOptionExcludeDeviceMotion & options)) { [recorderConfigurations addObject:[[ORKDeviceMotionRecorderConfiguration alloc] initWithIdentifier:ORKDeviceMotionRecorderIdentifier frequency:100]]; } ORKFitnessStep *activeStep = [[ORKFitnessStep alloc] initWithIdentifier:ORKShortWalkRestStepIdentifier]; activeStep.recorderConfigurations = recorderConfigurations; NSString *durationString = [formatter stringFromTimeInterval:restDuration]; activeStep.title = [NSString stringWithFormat:ORKLocalizedString(@"WALK_STAND_INSTRUCTION_FORMAT", nil), durationString]; activeStep.spokenInstruction = [NSString stringWithFormat:ORKLocalizedString(@"WALK_STAND_VOICE_INSTRUCTION_FORMAT", nil), durationString]; activeStep.shouldStartTimerAutomatically = YES; activeStep.stepDuration = restDuration; activeStep.shouldShowDefaultTimer = NO; activeStep.shouldContinueOnFinish = YES; activeStep.optional = NO; activeStep.shouldVibrateOnStart = YES; activeStep.shouldPlaySoundOnStart = YES; activeStep.shouldVibrateOnFinish = YES; activeStep.shouldPlaySoundOnFinish = YES; ORKStepArrayAddStep(steps, activeStep); } } if (! (options & ORKPredefinedTaskOptionExcludeConclusion)) { ORKInstructionStep *step = [self makeCompletionStep]; ORKStepArrayAddStep(steps, step); } ORKOrderedTask *task = [[ORKOrderedTask alloc] initWithIdentifier:identifier steps:steps]; return task; } + (ORKOrderedTask *)spatialSpanMemoryTaskWithIdentifier:(NSString *)identifier intendedUseDescription:(NSString *)intendedUseDescription initialSpan:(NSInteger)initialSpan minimumSpan:(NSInteger)minimumSpan maximumSpan:(NSInteger)maximumSpan playSpeed:(NSTimeInterval)playSpeed maxTests:(NSInteger)maxTests maxConsecutiveFailures:(NSInteger)maxConsecutiveFailures customTargetImage:(UIImage *)customTargetImage customTargetPluralName:(NSString *)customTargetPluralName requireReversal:(BOOL)requireReversal options:(ORKPredefinedTaskOption)options { NSString *targetPluralName = customTargetPluralName ? : ORKLocalizedString(@"SPATIAL_SPAN_MEMORY_TARGET_PLURAL", nil); NSMutableArray *steps = [NSMutableArray array]; if (! (options & ORKPredefinedTaskOptionExcludeInstructions)) { { ORKInstructionStep *step = [[ORKInstructionStep alloc] initWithIdentifier:ORKInstruction0StepIdentifier]; step.title = ORKLocalizedString(@"SPATIAL_SPAN_MEMORY_TITLE", nil); step.text = intendedUseDescription; step.detailText = [NSString stringWithFormat:ORKLocalizedString(@"SPATIAL_SPAN_MEMORY_INTRO_TEXT_%@", nil),targetPluralName]; step.image = [UIImage imageNamed:@"phone-memory" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil]; step.shouldTintImages = YES; ORKStepArrayAddStep(steps, step); } { ORKInstructionStep *step = [[ORKInstructionStep alloc] initWithIdentifier:ORKInstruction1StepIdentifier]; step.title = ORKLocalizedString(@"SPATIAL_SPAN_MEMORY_TITLE", nil); step.text = [NSString stringWithFormat:requireReversal ? ORKLocalizedString(@"SPATIAL_SPAN_MEMORY_INTRO_2_TEXT_REVERSE_%@", nil) : ORKLocalizedString(@"SPATIAL_SPAN_MEMORY_INTRO_2_TEXT_%@", nil), targetPluralName, targetPluralName]; step.detailText = ORKLocalizedString(@"SPATIAL_SPAN_MEMORY_CALL_TO_ACTION", nil); if (! customTargetImage) { step.image = [UIImage imageNamed:@"memory-second-screen" inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil]; } else { step.image = customTargetImage; } step.shouldTintImages = YES; ORKStepArrayAddStep(steps, step); } } { ORKSpatialSpanMemoryStep *step = [[ORKSpatialSpanMemoryStep alloc] initWithIdentifier:ORKSpatialSpanMemoryStepIdentifier]; step.title = nil; step.text = nil; step.initialSpan = initialSpan; step.minimumSpan = minimumSpan; step.maximumSpan = maximumSpan; step.playSpeed = playSpeed; step.maxTests = maxTests; step.maxConsecutiveFailures = maxConsecutiveFailures; step.customTargetImage = customTargetImage; step.customTargetPluralName = customTargetPluralName; step.requireReversal = requireReversal; ORKStepArrayAddStep(steps, step); } if (! (options & ORKPredefinedTaskOptionExcludeConclusion)) { ORKInstructionStep *step = [self makeCompletionStep]; ORKStepArrayAddStep(steps, step); } ORKOrderedTask *task = [[ORKOrderedTask alloc] initWithIdentifier:identifier steps:steps]; return task; } @end
{ "content_hash": "3a9876de0be6d0c87e407312002ee196", "timestamp": "", "source": "github", "line_count": 759, "max_line_length": 244, "avg_line_length": 48.01449275362319, "alnum_prop": 0.6402601322613396, "repo_name": "getaaron/zombie", "id": "0d7884f03e48c2dcd337af1d663b99a5cccf33ef", "size": "38122", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "zombie/Pods/ResearchKit/ResearchKit/Common/ORKOrderedTask.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "14297" }, { "name": "C++", "bytes": "5911" }, { "name": "Objective-C", "bytes": "1850311" }, { "name": "Ruby", "bytes": "40" }, { "name": "Shell", "bytes": "6253" }, { "name": "Swift", "bytes": "12922" } ], "symlink_target": "" }
#ifndef NANO_HTTP_RESPONSE_H #define NANO_HTTP_RESPONSE_H #include <nanohttp/nanohttp-stream.h> #include <nanohttp/nanohttp-common.h> #include <nanohttp/nanohttp-mime.h> /* response object */ typedef struct hresponse { http_version_t version; int errcode; char desc[RESPONSE_MAX_DESC_SIZE]; hpair_t *header; http_input_stream_t *in; content_type_t *content_type; attachments_t *attachments; char root_part_id[150]; } hresponse_t; #ifdef __cplusplus extern "C" { #endif herror_t hresponse_new_from_socket(hsocket_t *sock, hresponse_t ** out); void hresponse_free(hresponse_t * res); #ifdef __cplusplus } #endif #endif
{ "content_hash": "112e8b395517d81095c0b3f249fe28fd", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 72, "avg_line_length": 18.34285714285714, "alnum_prop": 0.721183800623053, "repo_name": "Exhar/open-one-time-password--credential-provider", "id": "622ef638d5ec7babf203ea589d43e9d690ddc7e4", "size": "1720", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/libopenotp-1.0/nanohttp/nanohttp-response.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "409898" }, { "name": "C++", "bytes": "111989" }, { "name": "Objective-C", "bytes": "771" } ], "symlink_target": "" }
<?php namespace NAE\PlateformBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('nae_plateform'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
{ "content_hash": "4a9dcbc04e491da97600d08557c75370", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 131, "avg_line_length": 31.379310344827587, "alnum_prop": 0.6945054945054945, "repo_name": "Juba95/newart", "id": "5078ee980ffea7d7070bc5e03edb61b071c89ad9", "size": "910", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/NAE/PlateformBundle/DependencyInjection/Configuration.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "173646" }, { "name": "JavaScript", "bytes": "315446" }, { "name": "PHP", "bytes": "100471" }, { "name": "Shell", "bytes": "1345" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>cs::geographic</title> <link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../index.html" title="Chapter&#160;1.&#160;Geometry"> <link rel="up" href="../cs.html" title="Coordinate Systems"> <link rel="prev" href="cs_spherical_equatorial.html" title="cs::spherical_equatorial"> <link rel="next" href="../core.html" title="Core Metafunctions"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="cs_spherical_equatorial.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../cs.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../core.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="geometry.reference.cs.cs_geographic"></a><a class="link" href="cs_geographic.html" title="cs::geographic">cs::geographic</a> </h4></div></div></div> <p> <a class="indexterm" name="idp108890608"></a><a class="indexterm" name="idp108891264"></a> Geographic coordinate system, in degree or in radian. </p> <h6> <a name="geometry.reference.cs.cs_geographic.h0"></a> <span class="phrase"><a name="geometry.reference.cs.cs_geographic.description"></a></span><a class="link" href="cs_geographic.html#geometry.reference.cs.cs_geographic.description">Description</a> </h6> <p> Defines the geographic coordinate system where points are defined in two angles and usually known as lat,long or lo,la or phi,lambda </p> <h6> <a name="geometry.reference.cs.cs_geographic.h1"></a> <span class="phrase"><a name="geometry.reference.cs.cs_geographic.synopsis"></a></span><a class="link" href="cs_geographic.html#geometry.reference.cs.cs_geographic.synopsis">Synopsis</a> </h6> <p> </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> <span class="identifier">DegreeOrRadian</span><span class="special">&gt;</span> <span class="keyword">struct</span> <span class="identifier">cs</span><span class="special">::</span><span class="identifier">geographic</span> <span class="special">{</span> <span class="comment">// ...</span> <span class="special">};</span> </pre> <p> </p> <h6> <a name="geometry.reference.cs.cs_geographic.h2"></a> <span class="phrase"><a name="geometry.reference.cs.cs_geographic.template_parameter_s_"></a></span><a class="link" href="cs_geographic.html#geometry.reference.cs.cs_geographic.template_parameter_s_">Template parameter(s)</a> </h6> <div class="informaltable"><table class="table"> <colgroup> <col> <col> </colgroup> <thead><tr> <th> <p> Parameter </p> </th> <th> <p> Description </p> </th> </tr></thead> <tbody><tr> <td> <p> typename DegreeOrRadian </p> </td> <td> </td> </tr></tbody> </table></div> <h6> <a name="geometry.reference.cs.cs_geographic.h3"></a> <span class="phrase"><a name="geometry.reference.cs.cs_geographic.header"></a></span><a class="link" href="cs_geographic.html#geometry.reference.cs.cs_geographic.header">Header</a> </h6> <p> Either </p> <p> <code class="computeroutput"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">geometry</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span></code> </p> <p> Or </p> <p> <code class="computeroutput"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">geometry</span><span class="special">/</span><span class="identifier">core</span><span class="special">/</span><span class="identifier">cs</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span></code> </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2009-2018 Barend Gehrels, Bruno Lalande, Mateusz Loskot, Adam Wulkiewicz, Oracle and/or its affiliates<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="cs_spherical_equatorial.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../cs.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../core.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "9eff99e64fbbeaab87bbfe31bd6d807a", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 457, "avg_line_length": 53.983050847457626, "alnum_prop": 0.6086342229199372, "repo_name": "nawawi/poedit", "id": "172cf22f9899360da38cefbed41a4686df50d915", "size": "6370", "binary": false, "copies": "5", "ref": "refs/heads/stable", "path": "deps/boost/libs/geometry/doc/html/geometry/reference/cs/cs_geographic.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "48113" }, { "name": "C++", "bytes": "1284178" }, { "name": "Inno Setup", "bytes": "11180" }, { "name": "M4", "bytes": "103958" }, { "name": "Makefile", "bytes": "9507" }, { "name": "Objective-C", "bytes": "16519" }, { "name": "Objective-C++", "bytes": "14681" }, { "name": "Python", "bytes": "6594" }, { "name": "Ruby", "bytes": "292" }, { "name": "Shell", "bytes": "11982" } ], "symlink_target": "" }
package cc.brino.Brpp; /** * * Classe principal do programa * * @author Mateus Berardo de Souza Terra * @contributors * @version 18/11/2016 */ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.nio.file.Paths; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import javax.swing.JFrame; import javax.swing.SwingUtilities; import org.json.simple.parser.ParseException; import cc.brino.Brpp.IDEui.BrppIDEFrame; import cc.brino.Brpp.Pref.PrefManager; import cc.brino.Brpp.Utils.FileUtils; import cc.brino.Brpp.Utils.JSONUtils; import cc.brino.Brpp.Utils.KeywordManagerUtils; import cc.brino.Brpp.Utils.LanguageVersionUtils; import cc.brino.Brpp.Utils.VersionUtils; import cc.brino.Brpp.compiler.BrppCompiler; public class BrppCompilerMain { private static String path; private static final String currentRelativePath = Paths.get("") .toAbsolutePath() .toString(); private static final File destDir = Paths.get(currentRelativePath, "Arduino", "libraries").toFile(); private static final Logger logger = Logger.getLogger(BrppCompilerMain.class.getName()); private static Logger l; private static Logger l2; private static FileHandler fh = null; private static FileHandler fh2 = null; private static BrppIDEFrame frame; public static void init() { try { fh = new FileHandler("brino.log", false); fh2 = new FileHandler("lib/detailedLog.log", false); } catch (SecurityException | IOException e) { e.printStackTrace(); } l = Logger.getLogger(""); l2 = Logger.getLogger(""); fh.setFormatter(new SimpleFormatter()); fh2.setFormatter(new SimpleFormatter()); l.addHandler(fh); l2.addHandler(fh2); l2.setLevel(Level.CONFIG); l.setLevel(Level.WARNING); } public static void main(String[] args) { BrppCompilerMain.init(); final String[] getArgs = args; // cria o diretorio do Brino logger.log(Level.CONFIG, "Criando o diretorio do Brino"); File dir = new File(FileUtils.getBrinodirectory()); dir.mkdirs(); // cria o diretorio do Brino logger.log(Level.CONFIG, "Criando o diretorio de bibliotecas do Brino"); File libDir = new File(Paths.get(FileUtils.getBrinodirectory(), "bibliotecas").toAbsolutePath().toString()); libDir.mkdirs(); // salva o diretorio do brino logger.log(Level.INFO, "Path set to: " + currentRelativePath); setPath(currentRelativePath); try { logger.log(Level.CONFIG, "Configurando preferências"); PrefManager.setPrefs(); logger.log(Level.CONFIG, "Configurando lingua"); JSONUtils.config(currentRelativePath); logger.log(Level.CONFIG, "Configurando bibliotecas"); FileUtils.copyFolder(libDir, destDir); logger.log(Level.CONFIG, "Processando bibliotecas para highlight"); KeywordManagerUtils.processLibraries(); logger.log(Level.CONFIG, "Atualizando lingua"); LanguageVersionUtils.updateLanguages(); logger.log(Level.CONFIG, "Verificando versao"); VersionUtils.checkVersion(); } catch (FileNotFoundException fnfe) { logger.log(Level.SEVERE, "Erro ao configurar o programa! Arquivo não encontrado : \n", fnfe); } catch (UnknownHostException uhe) { logger.log(Level.CONFIG, "Nao ha internet. Nao foi possivel atualizar a lingua!\n", uhe); } catch (MalformedURLException mue) { logger.log(Level.SEVERE, "Erro ao acessar a URL da lingua!\n", mue); } catch (IOException ioe) { logger.log(Level.SEVERE, "Erro ao configurar o programa!\n", ioe); } catch (ParseException pe) { logger.log(Level.SEVERE, "Erro ao fazer o parse da lingua!\n", pe); } catch (NullPointerException npe) { logger.log(Level.SEVERE, "Erro ao mover bibliotecas!\n", npe); } catch (URISyntaxException e) { logger.log(Level.SEVERE, "Erro ao abrir página de downloads!\n", e); } SwingUtilities.invokeLater(new Runnable() { public void run() { frame = new BrppIDEFrame("Brino " + BrppCompiler.version); frame.setSize(500, 600); frame.setLocation(100, 30); logger.log(Level.CONFIG, "Inicializando frame"); frame.setVisible(true); if (getArgs.length > 0) { String filePath = getArgs[0]; FileUtils.abrirFile(filePath, BrppIDEFrame.getTextArea(), true); } } }); } public static String getPath() { return path; } public static JFrame getDialog() { // TODO Auto-generated method stub return frame; } public static void setPath(String path) { BrppCompilerMain.path = path; } }
{ "content_hash": "df41239a9c1c62dec8f9da548bdad2bc", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 89, "avg_line_length": 29.754716981132077, "alnum_prop": 0.7159162967660114, "repo_name": "StarFruitBrasil/Brino", "id": "8cf159bfe7e72ec22eaa3e7cdf9891767dcb99c9", "size": "5874", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Br++/src/main/java/cc/brino/Brpp/BrppCompilerMain.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "95319" } ], "symlink_target": "" }
from nose.tools import * from tictactoe.ai_strategies.easy import Easy from tictactoe.game_board import GameBoard def easy_strategy_makes_any_opening_move_test(): ai = Easy("X", "O") board = GameBoard() move = ai.make_move(board) assert_equal(True, move in list(range(0, 9))) def easy_strategy_makes_move_in_nearly_full_board_test(): ai = Easy("X", "O") board = GameBoard() board.play_move("X", 0) board.play_move("O", 2) board.play_move("X", 3) board.play_move("O", 4) board.play_move("X", 5) board.play_move("O", 6) board.play_move("X", 7) board.play_move("O", 8) assert_equal(1, ai.make_move(board))
{ "content_hash": "ff47dccbe657311ae3c1ec38bb7a0411", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 57, "avg_line_length": 29.130434782608695, "alnum_prop": 0.6268656716417911, "repo_name": "rickerbh/tictactoe_py", "id": "5fafd2cc86fc794c471809424b92edfe213a2f85", "size": "670", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/ai_easy_strategy_tests.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "120" }, { "name": "Python", "bytes": "37602" } ], "symlink_target": "" }
package org.apache.syncope.client.console.panels; import java.io.Serializable; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.apache.syncope.client.console.policies.PolicyRuleWrapper; import org.apache.syncope.client.console.reports.ReportletWrapper; import org.apache.syncope.client.console.wizards.WizardMgtPanel; import org.apache.syncope.client.ui.commons.Constants; import org.apache.syncope.client.ui.commons.status.StatusBean; import org.apache.syncope.client.ui.commons.wizards.any.AnyWrapper; import org.apache.syncope.common.keymaster.client.api.model.Domain; import org.apache.syncope.common.lib.Attr; import org.apache.syncope.common.lib.to.EntityTO; import org.apache.syncope.common.lib.to.JobTO; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.PageReference; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.ResourceModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Toggle panel. * * @param <T> model object type */ public abstract class TogglePanel<T extends Serializable> extends WizardMgtPanel<T> { private static final long serialVersionUID = -2025535531121434056L; protected static final Logger LOG = LoggerFactory.getLogger(TogglePanel.class); protected static final int HEADER_FIRST_ABBREVIATION = 25; private enum Status { INACTIVE, ACTIVE } private static final String LABEL_DATA_VALUE = "data-value"; private enum ToggleMenuCSS { CLASS("toggle-menu"), CLASS_ACTIVE("active-toggle-menu"), CLASS_INACTIVE("active-toggle-menu"); private final String value; ToggleMenuCSS(final String value) { this.value = value; } public String value() { return value; } } private final WebMarkupContainer container; private Status status = Status.INACTIVE; private final Label header; private final String activeId; public TogglePanel(final String id, final PageReference pageRef) { this(id, id, pageRef); } public TogglePanel(final String id, final String markupId, final PageReference pageRef) { super(id, true); this.activeId = markupId; String containerID = StringUtils.isBlank(markupId) ? id : markupId; setRenderBodyOnly(true); setOutputMarkupId(true); disableContainerAutoRefresh(); setPageRef(pageRef); container = new WebMarkupContainer("togglePanelContainer"); super.addInnerObject(container.setMarkupId(containerID)); header = new Label("label", StringUtils.EMPTY); header.add(new AttributeModifier("title", new ResourceModel("copy_to_clipboard.title"))); header.setOutputMarkupId(true); container.add(header); container.add(new AjaxLink<Void>("close") { private static final long serialVersionUID = 5538299138211283825L; @Override public void onClick(final AjaxRequestTarget target) { toggle(target, false); } }.add(new AjaxEventBehavior(Constants.ON_CLICK) { private static final long serialVersionUID = -9027652037484739586L; @Override protected String findIndicatorId() { return StringUtils.EMPTY; } @Override protected void onEvent(final AjaxRequestTarget target) { // do nothing } })); } /** * Add object inside the main container. * * @param childs components to be added. * @return the current panel instance. */ @Override public TogglePanel<T> addInnerObject(final Component... childs) { container.addOrReplace(childs); return this; } protected void setHeader(final AjaxRequestTarget target, final String header) { this.header.setDefaultModelObject(Optional.ofNullable(header). map(s -> StringUtils.abbreviate(s, HEADER_FIRST_ABBREVIATION)).orElse(StringUtils.EMPTY)); target.add(this.header); } public void close(final AjaxRequestTarget target) { toggle(target, false); } @SuppressWarnings("cast") protected String getTargetKey(final Serializable modelObject) { final String key; if (modelObject == null) { key = new ResourceModel("actions", StringUtils.EMPTY).getObject(); } else if (modelObject instanceof EntityTO) { key = ((EntityTO) modelObject).getKey(); } else if (modelObject instanceof AnyWrapper) { key = ((AnyWrapper<?>) modelObject).getInnerObject().getKey(); } else if (modelObject instanceof Attr) { key = ((Attr) modelObject).getSchema(); } else if (modelObject instanceof ConfParam) { key = ((ConfParam) modelObject).getSchema(); } else if (modelObject instanceof StatusBean) { key = StringUtils.isNotBlank(((StatusBean) modelObject).getResource()) ? ((StatusBean) modelObject).getResource() : ((StatusBean) modelObject).getKey(); } else if (modelObject instanceof PolicyRuleWrapper) { key = ((PolicyRuleWrapper) modelObject).getConf().getName(); } else if (modelObject instanceof ReportletWrapper) { key = ((ReportletWrapper) modelObject).getConf().getName(); } else if (modelObject instanceof JobTO) { key = ((JobTO) modelObject).getRefKey() == null ? ((JobTO) modelObject).getRefDesc() : ((JobTO) modelObject).getRefKey(); } else if (modelObject instanceof ToggleableTarget) { key = ((ToggleableTarget) modelObject).getKey(); } else if (modelObject instanceof Domain) { key = ((Domain) modelObject).getKey(); } else { key = new ResourceModel("actions", StringUtils.EMPTY).getObject(); } return key; } protected void updateLabelKeyValue(final Serializable modelObject) { header.add(new AttributeModifier(LABEL_DATA_VALUE, getTargetKey(modelObject))); } /** * Force toggle via java. To be used when the onclick has been intercepted before. * Also, set key value in label name for copy-to-clipboard feature. * * @param target ajax request target. * @param modelObject model object * @param toggle toggle action. */ public void toggle(final AjaxRequestTarget target, final Serializable modelObject, final boolean toggle) { updateLabelKeyValue(modelObject); toggle(target, toggle); } /** * Force toggle via java. To be used when the onclick has been intercepted before. * * @param target ajax request target. * @param toggle toggle action. */ public void toggle(final AjaxRequestTarget target, final boolean toggle) { final String selector = String.format("$(\"div#%s\")", activeId); if (toggle) { if (status == Status.INACTIVE) { target.add(TogglePanel.this.container); target.appendJavaScript( selector + ".toggle(\"slow\");" + selector + ".attr(\"class\", \"" + ToggleMenuCSS.CLASS.value() + ' ' + ToggleMenuCSS.CLASS_ACTIVE.value() + "\");"); status = Status.ACTIVE; } else if (status == Status.ACTIVE) { // useful when handling action menu after refreshing (ref. SYNCOPE-1134) target.appendJavaScript( selector + ".not(':visible')" + ".toggle(\"slow\")" + ".removeClass(\"" + ToggleMenuCSS.CLASS_INACTIVE.value() + "\")" + ".addClass(\"" + ToggleMenuCSS.CLASS_ACTIVE.value() + "y\");"); } } else if (status == Status.ACTIVE) { target.appendJavaScript( selector + ".toggle(\"slow\");" + selector + ".attr(\"class\", \"" + ToggleMenuCSS.CLASS.value() + ' ' + ToggleMenuCSS.CLASS_INACTIVE.value() + "\");"); status = Status.INACTIVE; } } }
{ "content_hash": "aab8621169dc534183ba82b2a399ca63", "timestamp": "", "source": "github", "line_count": 226, "max_line_length": 110, "avg_line_length": 37.530973451327434, "alnum_prop": 0.6374675784013204, "repo_name": "apache/syncope", "id": "5f8d8aff7b83317cbc832510805ffb03e86d1bb1", "size": "9289", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "client/idrepo/console/src/main/java/org/apache/syncope/client/console/panels/TogglePanel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1932" }, { "name": "Batchfile", "bytes": "1044" }, { "name": "CSS", "bytes": "44883" }, { "name": "Dockerfile", "bytes": "8716" }, { "name": "Groovy", "bytes": "78474" }, { "name": "HTML", "bytes": "549487" }, { "name": "Java", "bytes": "13523162" }, { "name": "JavaScript", "bytes": "36620" }, { "name": "PLpgSQL", "bytes": "20311" }, { "name": "SCSS", "bytes": "65724" }, { "name": "Shell", "bytes": "6231" }, { "name": "TSQL", "bytes": "11632" }, { "name": "XSLT", "bytes": "5158" } ], "symlink_target": "" }
/* This file contains all of the code running in the background that makes resumeBuilder.js possible. We call these helper functions because they support your code in this course. */ var HTMLbioPic = '<img src="%data%" alt="Picture of me">'; var HTMLheaderName = '<h1 id="name">%data%</h1>'; var HTMLheaderRole = '<h5 id="title">%data%</h5>'; var HTMLmobile = '<li><a><i class="fa fa-mobile fa-fw fa-lg fading"></i>%data%</a></li>'; var HTMLlocation = '<li><a href="#" target="_blank"><i class="fa fa-map-marker fa-fw fa-lg fading"></i>%data%</a></li>'; var HTMLemail = '<li><a><i class="fa fa-envelope-o fa-fw fa-lg fading"></i>%data%</a></li>'; var HTMLfacebook = '<li><hr></li><li><a href="#" target="_blank"><i class="fa fa-facebook fa-fw fa-lg fa-lg"></i>Facebook</a></li>'; var HTMLgplus = '<li><a href="#" target="_blank"><i class="fa fa-google-plus fa-fw fa-lg"></i>Google</a></li>'; var HTMLtwitter = '<li><a href="#" target="_blank"><i class="fa fa-twitter fa-fw fa-lg"></i>Twitter</a></li>'; var HTMLlinkedin = '<li><a href="#" target="_blank"><i class="fa fa-linkedin fa-fw fa-lg"></i>LinkedIn</a></li>'; var HTMLgithub = '<li><a href="#" target="_blank"><i class="fa fa-github fa-fw fa-lg"></i>Github</a></li>'; var HTMLprojects = '<li><hr></li><li><a href="#"><i class="fa fa-briefcase fa-fw fa-lg"></i>Projects</a></li>'; var HTMLclasses = '<li><a href="#"><i class="fa fa-graduation-cap fa-fw fa-lg"></i>Online courses</a></li>'; var HTMLcertificates = '<li><a href="#"><i class="fa fa-certificate fa-fw fa-lg"></i>Certificates</a></li>'; var HTMLlanguageStart = '<li><hr></li><li><i class="fa fa-code fa-fw fa-lg fading"></i>Languages used</li><ul id="lang"></ul>'; var HTMLlanguage = '<li class="tag">%data%</li>'; var HTMLshareStart = '<li><i class="fa fa-share-alt fa-fw fa-lg fading"></i>Share this project</li><ul id="share"></ul>'; var HTMLshareFB = '<i onclick=fbShare() class="fa fa-facebook fa-fw fa-lg fa-lg"></i>'; var HTMLshareTT = '<i onclick=ttShare() class="fa fa-twitter fa-fw fa-lg fa-lg"></i>'; var HTMLfork = '<li><a href="#" target="_blank"><i class="fa fa-code-fork fa-fw fa-lg fading"></i>Fork me on Github</a></li>'; //var HTMLcontactGeneric = '<li class="flex-item"><span class="orange-text">%contact%</span><span class="white-text">%data%</span></li>'; //var HTMLwelcomeMsg = '<span class="welcome-message">%data%</span>'; var HTMLskillsStart = '<h3 id="skills-h3">Skills at a Glance:</h3><ul id="skills" class="flex-box"></ul>'; var HTMLskills = '<li class="flex-item"><span class="white-text">%data%</span></li>'; var HeaderFacebook = '<li><a href="#" target="_blank"><img src="images/facebook.svg" alt="facebook social icon" width="48" height="48"></a></li>'; var HeaderTwitter = '<li><a href="#" target="_blank"><img src="images/twitter.svg" alt="twitter social icon" width="48" height="48"></a></li>'; var HeaderLinkedin = '<li><a href="#" target="_blank"><img src="images/linked_in.svg" alt="linkedin social icon" width="48" height="48"></a></li>'; var HTMLworkStart = '<div class="work-entry"></div>'; var HTMLworkEmployer = '<a href="#">%data%'; var HTMLworkTitle = ' - %data%</a>'; var HTMLworkDates = '<div class="date-text">%data%</div>'; var HTMLworkLocation = '<div class="location-text">%data%</div>'; var HTMLworkDescription = '<p><br>%data%</p>'; var HTMLprojectStart = '<div class="item" onclick="%fn%"></div>'; var HTMLprojectImage = '<img src="%data%" alt="Chania" width="460" height="345">'; var HTMLcarouselStart = '<div class="carousel-caption"></div>'; var HTMLprojectTitle = '<h5>%data%</h5>'; var HTMLprojectDescription = '<p>%data%</p>'; var HTMLprojectDates = '<p>%data%</p>'; var HTMLschoolStart = '<div class="education-entry"></div>'; var HTMLschoolName = '<a href="#">%data%'; var HTMLschoolDegree = ' -- %data%</a>'; var HTMLschoolDates = '<div class="date-text">%data%</div>'; var HTMLschoolLocation = '<div class="location-text">%data%</div>'; var HTMLschoolMajor = '<em><br>Major: %data%</em>'; var HTMLonlineClassStart = '<div class="class-entry"><h3>Online Classes</h3><a href="http://roozeppe.github.io/under-construction/">MORE</a></div>'; var HTMLonlineTitle = '<a href="#" target="_blank">%data%'; var HTMLonlineSchool = ' - %data%</a>'; var HTMLonlineDates = '<div class="date-text">%data%</div>'; var HTMLcertificateStart = '<div class="cert-entry"><h3>Certifications</h3></div>'; var HTMLcertTitle = '<a href="#" target="_blank">%data%'; var HTMLcertDates = ' - %data%</a>'; var HTMLcertSchool = '<h5>%data%</h5>'; var HTMLcertImage = '<img src=%data% alt=Sapshot of my certification.' var internationalizeButton = '<button>Internationalize</button>'; var googleMap = '<div id="map"></div>'; // Facebook pop-up function. function fbShare() { window.open("https://www.facebook.com/sharer/sharer.php?u=http://roozeppe.github.io/", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=5,left=5,width=600,height=600"); }; // Twitter pop-up function. function ttShare() { window.open("https://twitter.com/intent/tweet?text=Check%20out%20Roozeppe's%20Resume&url=http://roozeppe.github.io/&hashtags=happycoding&via=roozeppejp", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=5,left=5,width=600,height=600"); }; // Project pages functions. function frog_page () { window.open("http://roozeppe.github.io/frontend-nanodegree-arcade-game/") }; function grayscale_page () { window.open("http://roozeppe.github.io/grayscale/") }; function meme_page () { window.open("http://roozeppe.github.io/meme-maker/") } /* The International Name challenge in Lesson 2 where you'll create a function that will need this helper code to run. Don't delete! It hooks up your code to the button you'll be appending. */ $(document).ready(function() { $('button').click(function() { var iName = inName() || function(){}; $('#name').html(iName); }); }); /* The next few lines about clicks are for the Collecting Click Locations quiz in Lesson 2. */ clickLocations = []; function logClicks(x,y) { clickLocations.push( { x: x, y: y } ); console.log('x location: ' + x + '; y location: ' + y); } $(document).click(function(loc) { // your code goes here! var x = loc.pageX; var y = loc.pageY; logClicks(x,y); }); /* This is the fun part. Here's where we generate the custom Google Map for the website. See the documentation below for more details. https://developers.google.com/maps/documentation/javascript/reference */ var map; // declares a global map variable /* Start here! initializeMap() is called when page is loaded. */ function initializeMap() { var locations; var mapOptions = { disableDefaultUI: true }; /* For the map to be displayed, the googleMap var must be appended to #mapDiv in resumeBuilder.js. */ map = new google.maps.Map(document.querySelector('#map'), mapOptions); /* locationFinder() returns an array of every location string from the JSONs written for bio, education, and work. */ function locationFinder() { // initializes an empty array var locations = []; // adds the single location property from bio to the locations array locations.push(bio.contacts.location); // iterates through school locations and appends each location to // the locations array. Note that forEach is used for array iteration // as described in the Udacity FEND Style Guide: // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop education.schools.forEach(function(school){ locations.push(school.location); }); // iterates through work locations and appends each location to // the locations array. Note that forEach is used for array iteration // as described in the Udacity FEND Style Guide: // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop work.jobs.forEach(function(job){ locations.push(job.location); }); return locations; } /* createMapMarker(placeData) reads Google Places search results to create map pins. placeData is the object returned from search results containing information about a single location. */ function createMapMarker(placeData) { // The next lines save location data from the search result object to local variables var lat = placeData.geometry.location.lat(); // latitude from the place service var lon = placeData.geometry.location.lng(); // longitude from the place service var name = placeData.formatted_address; // name of the place from the place service var bounds = window.mapBounds; // current boundaries of the map window // marker is an object with additional data about the pin for a single location var marker = new google.maps.Marker({ map: map, position: placeData.geometry.location, title: name }); // infoWindows are the little helper windows that open when you click // or hover over a pin on a map. They usually contain more information // about a location. var infoWindow = new google.maps.InfoWindow({ content: name }); // hmmmm, I wonder what this is about... google.maps.event.addListener(marker, 'click', function() { // your code goes here! infoWindow.open(map, marker); }); // this is where the pin actually gets added to the map. // bounds.extend() takes in a map location object bounds.extend(new google.maps.LatLng(lat, lon)); // fit the map to the new marker map.fitBounds(bounds); // center the map map.setCenter(bounds.getCenter()); } /* callback(results, status) makes sure the search returned results for a location. If so, it creates a new map marker for that location. */ function callback(results, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { createMapMarker(results[0]); } } /* pinPoster(locations) takes in the array of locations created by locationFinder() and fires off Google place searches for each location */ function pinPoster(locations) { // creates a Google place search service object. PlacesService does the work of // actually searching for location data. var service = new google.maps.places.PlacesService(map); // Iterates through the array of locations, creates a search object for each location locations.forEach(function(place){ // the search request object var request = { query: place }; // Actually searches the Google Maps API for location data and runs the callback // function with the search results after each search. service.textSearch(request, callback); }); } // Sets the boundaries of the map based on pin locations window.mapBounds = new google.maps.LatLngBounds(); // locations is an array of location strings returned from locationFinder() locations = locationFinder(); // pinPoster(locations) creates pins on the map for each location in // the locations array pinPoster(locations); } /* Uncomment the code below when you're ready to implement a Google Map! */ // Calls the initializeMap() function when the page loads window.addEventListener('load', initializeMap); // Vanilla JS way to listen for resizing of the window // and adjust map bounds window.addEventListener('resize', function(e) { //Make sure the map bounds get updated on page resize map.fitBounds(mapBounds); });
{ "content_hash": "c3e99cf9819b5d76a913c271c508bfec", "timestamp": "", "source": "github", "line_count": 296, "max_line_length": 156, "avg_line_length": 39.75, "alnum_prop": 0.661907190209077, "repo_name": "Roozeppe/roozeppe.github.io", "id": "797614e74e69332db0c92cf205def63c55fff297", "size": "11766", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "js/helper.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8092" }, { "name": "HTML", "bytes": "7309" }, { "name": "JavaScript", "bytes": "294484" } ], "symlink_target": "" }
package org.apache.beam.sdk.testing; import static com.google.common.base.Preconditions.checkState; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Strings; import com.google.common.collect.FluentIterable; import com.google.common.collect.Maps; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import javax.annotation.Nullable; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.PipelineResult; import org.apache.beam.sdk.annotations.Internal; import org.apache.beam.sdk.io.FileSystems; import org.apache.beam.sdk.metrics.MetricNameFilter; import org.apache.beam.sdk.metrics.MetricResult; import org.apache.beam.sdk.metrics.MetricsEnvironment; import org.apache.beam.sdk.metrics.MetricsFilter; import org.apache.beam.sdk.options.ApplicationNameOptions; import org.apache.beam.sdk.options.PipelineOptions; import org.apache.beam.sdk.options.PipelineOptions.CheckEnabled; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.options.ValueProvider; import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider; import org.apache.beam.sdk.runners.TransformHierarchy; import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.util.common.ReflectHelpers; import org.junit.experimental.categories.Category; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * A creator of test pipelines that can be used inside of tests that can be configured to run * locally or against a remote pipeline runner. * * <p>It is recommended to tag hand-selected tests for this purpose using the {@link * ValidatesRunner} {@link Category} annotation, as each test run against a pipeline runner will * utilize resources of that pipeline runner. * * <p>In order to run tests on a pipeline runner, the following conditions must be met: * * <ul> * <li>System property "beamTestPipelineOptions" must contain a JSON delimited list of pipeline * options. For example: * <pre>{@code [ * "--runner=TestDataflowRunner", * "--project=mygcpproject", * "--stagingLocation=gs://mygcsbucket/path" * ]}</pre> * Note that the set of pipeline options required is pipeline runner specific. * <li>Jars containing the SDK and test classes must be available on the classpath. * </ul> * * <p>Use {@link PAssert} for tests, as it integrates with this test harness in both direct and * remote execution modes. For example: * * <pre><code> * {@literal @Rule} * public final transient TestPipeline p = TestPipeline.create(); * * {@literal @Test} * {@literal @Category}(NeedsRunner.class) * public void myPipelineTest() throws Exception { * final PCollection&lt;String&gt; pCollection = pipeline.apply(...) * PAssert.that(pCollection).containsInAnyOrder(...); * pipeline.run(); * } * </code></pre> * * <p>For pipeline runners, it is required that they must throw an {@link AssertionError} containing * the message from the {@link PAssert} that failed. * * <p>See also the <a href="https://beam.apache.org/contribute/testing/">Testing</a> documentation * section. */ public class TestPipeline extends Pipeline implements TestRule { private final PipelineOptions options; private static class PipelineRunEnforcement { @SuppressWarnings("WeakerAccess") protected boolean enableAutoRunIfMissing; protected final Pipeline pipeline; protected boolean runAttempted; private PipelineRunEnforcement(final Pipeline pipeline) { this.pipeline = pipeline; } protected void enableAutoRunIfMissing(final boolean enable) { enableAutoRunIfMissing = enable; } protected void beforePipelineExecution() { runAttempted = true; } protected void afterPipelineExecution() {} protected void afterUserCodeFinished() { if (!runAttempted && enableAutoRunIfMissing) { pipeline.run().waitUntilFinish(); } } } private static class PipelineAbandonedNodeEnforcement extends PipelineRunEnforcement { // Null until the pipeline has been run @Nullable private List<TransformHierarchy.Node> runVisitedNodes; private final Predicate<TransformHierarchy.Node> isPAssertNode = node -> node.getTransform() instanceof PAssert.GroupThenAssert || node.getTransform() instanceof PAssert.GroupThenAssertForSingleton || node.getTransform() instanceof PAssert.OneSideInputAssert; private static class NodeRecorder extends PipelineVisitor.Defaults { private final List<TransformHierarchy.Node> visited = new ArrayList<>(); @Override public void leaveCompositeTransform(final TransformHierarchy.Node node) { visited.add(node); } @Override public void visitPrimitiveTransform(final TransformHierarchy.Node node) { visited.add(node); } } private PipelineAbandonedNodeEnforcement(final TestPipeline pipeline) { super(pipeline); runVisitedNodes = null; } private List<TransformHierarchy.Node> recordPipelineNodes(final Pipeline pipeline) { final NodeRecorder nodeRecorder = new NodeRecorder(); pipeline.traverseTopologically(nodeRecorder); return nodeRecorder.visited; } private boolean isEmptyPipeline(final Pipeline pipeline) { final IsEmptyVisitor isEmptyVisitor = new IsEmptyVisitor(); pipeline.traverseTopologically(isEmptyVisitor); return isEmptyVisitor.isEmpty(); } private void verifyPipelineExecution() { if (!isEmptyPipeline(pipeline)) { if (!runAttempted && !enableAutoRunIfMissing) { throw new PipelineRunMissingException("The pipeline has not been run."); } else { final List<TransformHierarchy.Node> pipelineNodes = recordPipelineNodes(pipeline); if (pipelineRunSucceeded() && !visitedAll(pipelineNodes)) { final boolean hasDanglingPAssert = FluentIterable.from(pipelineNodes) .filter(Predicates.not(Predicates.in(runVisitedNodes))) .anyMatch(isPAssertNode); if (hasDanglingPAssert) { throw new AbandonedNodeException("The pipeline contains abandoned PAssert(s)."); } else { throw new AbandonedNodeException("The pipeline contains abandoned PTransform(s)."); } } } } } private boolean visitedAll(final List<TransformHierarchy.Node> pipelineNodes) { return runVisitedNodes.equals(pipelineNodes); } private boolean pipelineRunSucceeded() { return runVisitedNodes != null; } @Override protected void afterPipelineExecution() { runVisitedNodes = recordPipelineNodes(pipeline); super.afterPipelineExecution(); } @Override protected void afterUserCodeFinished() { super.afterUserCodeFinished(); verifyPipelineExecution(); } } /** * An exception thrown in case an abandoned {@link org.apache.beam.sdk.transforms.PTransform} is * detected, that is, a {@link org.apache.beam.sdk.transforms.PTransform} that has not been run. */ public static class AbandonedNodeException extends RuntimeException { AbandonedNodeException(final String msg) { super(msg); } } /** An exception thrown in case a test finishes without invoking {@link Pipeline#run()}. */ public static class PipelineRunMissingException extends RuntimeException { PipelineRunMissingException(final String msg) { super(msg); } } /** System property used to set {@link TestPipelineOptions}. */ public static final String PROPERTY_BEAM_TEST_PIPELINE_OPTIONS = "beamTestPipelineOptions"; static final String PROPERTY_USE_DEFAULT_DUMMY_RUNNER = "beamUseDummyRunner"; private static final ObjectMapper MAPPER = new ObjectMapper() .registerModules(ObjectMapper.findModules(ReflectHelpers.findClassLoader())); @SuppressWarnings("OptionalUsedAsFieldOrParameterType") private Optional<? extends PipelineRunEnforcement> enforcement = Optional.absent(); /** * Creates and returns a new test pipeline. * * <p>Use {@link PAssert} to add tests, then call {@link Pipeline#run} to execute the pipeline and * check the tests. */ public static TestPipeline create() { return fromOptions(testingPipelineOptions()); } public static TestPipeline fromOptions(PipelineOptions options) { return new TestPipeline(options); } private TestPipeline(final PipelineOptions options) { super(options); this.options = options; } @Override public PipelineOptions getOptions() { return this.options; } @Override public Statement apply(final Statement statement, final Description description) { return new Statement() { private void setDeducedEnforcementLevel() { // if the enforcement level has not been set by the user do auto-inference if (!enforcement.isPresent()) { final boolean annotatedWithNeedsRunner = FluentIterable.from(description.getAnnotations()) .filter(Annotations.Predicates.isAnnotationOfType(Category.class)) .anyMatch(Annotations.Predicates.isCategoryOf(NeedsRunner.class, true)); final boolean crashingRunner = CrashingRunner.class.isAssignableFrom(options.getRunner()); checkState( !(annotatedWithNeedsRunner && crashingRunner), "The test was annotated with a [@%s] / [@%s] while the runner " + "was set to [%s]. Please re-check your configuration.", NeedsRunner.class.getSimpleName(), ValidatesRunner.class.getSimpleName(), CrashingRunner.class.getSimpleName()); enableAbandonedNodeEnforcement(annotatedWithNeedsRunner || !crashingRunner); } } @Override public void evaluate() throws Throwable { options.as(ApplicationNameOptions.class).setAppName(getAppName(description)); setDeducedEnforcementLevel(); // statement.evaluate() essentially runs the user code contained in the unit test at hand. // Exceptions thrown during the execution of the user's test code will propagate here, // unless the user explicitly handles them with a "catch" clause in his code. If the // exception is handled by a user's "catch" clause, is does not interrupt the flow and // we move on to invoking the configured enforcements. // If the user does not handle a thrown exception, it will propagate here and interrupt // the flow, preventing the enforcement(s) from being activated. // The motivation for this is avoiding enforcements over faulty pipelines. statement.evaluate(); enforcement.get().afterUserCodeFinished(); } }; } /** * Runs this {@link TestPipeline}, unwrapping any {@code AssertionError} that is raised during * testing. */ @Override public PipelineResult run() { return run(getOptions()); } /** Like {@link #run} but with the given potentially modified options. */ @Override public PipelineResult run(PipelineOptions options) { checkState( enforcement.isPresent(), "Is your TestPipeline declaration missing a @Rule annotation? Usage: " + "@Rule public final transient TestPipeline pipeline = TestPipeline.create();"); final PipelineResult pipelineResult; try { enforcement.get().beforePipelineExecution(); PipelineOptions updatedOptions = MAPPER.convertValue(MAPPER.valueToTree(options), PipelineOptions.class); updatedOptions .as(TestValueProviderOptions.class) .setProviderRuntimeValues(StaticValueProvider.of(providerRuntimeValues)); pipelineResult = super.run(updatedOptions); verifyPAssertsSucceeded(this, pipelineResult); } catch (RuntimeException exc) { Throwable cause = exc.getCause(); if (cause instanceof AssertionError) { throw (AssertionError) cause; } else { throw exc; } } // If we reach this point, the pipeline has been run and no exceptions have been thrown during // its execution. enforcement.get().afterPipelineExecution(); return pipelineResult; } /** Implementation detail of {@link #newProvider}, do not use. */ @Internal public interface TestValueProviderOptions extends PipelineOptions { ValueProvider<Map<String, Object>> getProviderRuntimeValues(); void setProviderRuntimeValues(ValueProvider<Map<String, Object>> runtimeValues); } /** * Returns a new {@link ValueProvider} that is inaccessible before {@link #run}, but will be * accessible while the pipeline runs. */ public <T> ValueProvider<T> newProvider(T runtimeValue) { String uuid = UUID.randomUUID().toString(); providerRuntimeValues.put(uuid, runtimeValue); return ValueProvider.NestedValueProvider.of( options.as(TestValueProviderOptions.class).getProviderRuntimeValues(), new GetFromRuntimeValues<T>(uuid)); } private final Map<String, Object> providerRuntimeValues = Maps.newHashMap(); private static class GetFromRuntimeValues<T> implements SerializableFunction<Map<String, Object>, T> { private final String key; private GetFromRuntimeValues(String key) { this.key = key; } @Override public T apply(Map<String, Object> input) { return (T) input.get(key); } } /** * Enables the abandoned node detection. Abandoned nodes are <code>PTransforms</code>, <code> * PAsserts</code> included, that were not executed by the pipeline runner. Abandoned nodes are * most likely to occur due to the one of the following scenarios: * * <ul> * <li>Lack of a <code>pipeline.run()</code> statement at the end of a test. * <li>Addition of PTransforms after the pipeline has already run. * </ul> * * Abandoned node detection is automatically enabled when a real pipeline runner (i.e. not a * {@link CrashingRunner}) and/or a {@link NeedsRunner} or a {@link ValidatesRunner} annotation * are detected. */ public TestPipeline enableAbandonedNodeEnforcement(final boolean enable) { enforcement = enable ? Optional.of(new PipelineAbandonedNodeEnforcement(this)) : Optional.of(new PipelineRunEnforcement(this)); return this; } /** * If enabled, a <code>pipeline.run()</code> statement will be added automatically in case it is * missing in the test. */ public TestPipeline enableAutoRunIfMissing(final boolean enable) { enforcement.get().enableAutoRunIfMissing(enable); return this; } @Override public String toString() { return "TestPipeline#" + options.as(ApplicationNameOptions.class).getAppName(); } /** Creates {@link PipelineOptions} for testing. */ public static PipelineOptions testingPipelineOptions() { try { @Nullable String beamTestPipelineOptions = System.getProperty(PROPERTY_BEAM_TEST_PIPELINE_OPTIONS); PipelineOptions options = Strings.isNullOrEmpty(beamTestPipelineOptions) ? PipelineOptionsFactory.create() : PipelineOptionsFactory.fromArgs( MAPPER.readValue(beamTestPipelineOptions, String[].class)) .as(TestPipelineOptions.class); // If no options were specified, set some reasonable defaults if (Strings.isNullOrEmpty(beamTestPipelineOptions)) { // If there are no provided options, check to see if a dummy runner should be used. String useDefaultDummy = System.getProperty(PROPERTY_USE_DEFAULT_DUMMY_RUNNER); if (!Strings.isNullOrEmpty(useDefaultDummy) && Boolean.valueOf(useDefaultDummy)) { options.setRunner(CrashingRunner.class); } } options.setStableUniqueNames(CheckEnabled.ERROR); FileSystems.setDefaultPipelineOptions(options); return options; } catch (IOException e) { throw new RuntimeException( "Unable to instantiate test options from system property " + PROPERTY_BEAM_TEST_PIPELINE_OPTIONS + ":" + System.getProperty(PROPERTY_BEAM_TEST_PIPELINE_OPTIONS), e); } } /** Returns the class + method name of the test. */ private String getAppName(Description description) { String methodName = description.getMethodName(); Class<?> testClass = description.getTestClass(); if (testClass.isMemberClass()) { return String.format( "%s$%s-%s", testClass.getEnclosingClass().getSimpleName(), testClass.getSimpleName(), methodName); } else { return String.format("%s-%s", testClass.getSimpleName(), methodName); } } /** * Verifies all {{@link PAssert PAsserts}} in the pipeline have been executed and were successful. * * <p>Note this only runs for runners which support Metrics. Runners which do not should verify * this in some other way. See: https://issues.apache.org/jira/browse/BEAM-2001 */ public static void verifyPAssertsSucceeded(Pipeline pipeline, PipelineResult pipelineResult) { if (MetricsEnvironment.isMetricsSupported()) { long expectedNumberOfAssertions = (long) PAssert.countAsserts(pipeline); long successfulAssertions = 0; Iterable<MetricResult<Long>> successCounterResults = pipelineResult .metrics() .queryMetrics( MetricsFilter.builder() .addNameFilter(MetricNameFilter.named(PAssert.class, PAssert.SUCCESS_COUNTER)) .build()) .getCounters(); for (MetricResult<Long> counter : successCounterResults) { if (counter.getAttempted() > 0) { successfulAssertions++; } } assertThat( String.format( "Expected %d successful assertions, but found %d.", expectedNumberOfAssertions, successfulAssertions), successfulAssertions, is(expectedNumberOfAssertions)); } } private static class IsEmptyVisitor extends PipelineVisitor.Defaults { private boolean empty = true; public boolean isEmpty() { return empty; } @Override public void visitPrimitiveTransform(TransformHierarchy.Node node) { empty = false; } } }
{ "content_hash": "9aee1a124de6ac594141321963d9e455", "timestamp": "", "source": "github", "line_count": 518, "max_line_length": 100, "avg_line_length": 36.29150579150579, "alnum_prop": 0.6983882121389435, "repo_name": "rangadi/incubator-beam", "id": "dfbd9b52a5f47eaff90cac471d4f047d149f6985", "size": "19604", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "sdks/java/core/src/main/java/org/apache/beam/sdk/testing/TestPipeline.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "50057" }, { "name": "Java", "bytes": "11779709" }, { "name": "Protocol Buffer", "bytes": "55082" }, { "name": "Python", "bytes": "2864316" }, { "name": "Shell", "bytes": "44966" } ], "symlink_target": "" }
package hydra; import hydra.log.LogPrms; import java.io.*; import java.util.*; import perffmwk.*; import util.*; /** * This class acts as a handy place for logging results to files. */ public class ResultLogger { ////////////////////////////////////////////////////////////////////////////// // TASK RESULTS ////////////////////////////////////////////////////////////////////////////// /** * Used by clients to log the task result in the client log. See * {@link RemoteTestModule#executeTask(int,int,int)}. */ protected static void logTaskResult( TestTask task, TestTaskResult result ) { String header = "Task result: " + task.toShortString() + ": "; if ( result.getErrorStatus() ) { Log.getLogWriter().severe( header + result.getErrorString() ); } else { Log.getLogWriter().info( header + result.getResult() ); } } /** * Used by master to log the task result reported by a client in the master * log. See {@link BaseTaskScheduler#reportResult}. Also writes the error, * if any, to the error file. */ protected static void logTaskResult( ClientRecord client, TestTask task, TestTaskResult result ) { String header = "Result for " + client + ": " + task.toShortString() + ": "; if ( result.getErrorStatus() ) { Log.getLogWriter().severe( header + result.getErrorString() ); String err = "CLIENT " + client + "\n" + task.toShortString() + "\n" + result.getErrorString(); writeErrorFile( err ); } else { Log.getLogWriter().info( header + result.getResult() ); } } /** * Used by master to log a client-reported hang in the master log. See * {@link BaseTaskScheduler#reportResult}. Also writes the hang to the * hang file. */ protected static void logHangResult( ClientRecord client, TestTask task, TestTaskResult result ) { String header = "Result for " + client + ": " + task.toShortString() + ": "; if ( result.getErrorStatus() ) { Log.getLogWriter().severe( header + result.getErrorString() ); String err = "CLIENT " + client + "\n" + task.toShortString() + "\n" + result.getErrorString(); writeErrorFile( err ); writeHangFile(); DeadlockDetection.detectDeadlocks(client); } else { throw new HydraInternalException("Attempt to log a hang with no error"); } } /** * Used by master to log a client hang in the master log. Also writes the * hang to the hang file. See {@link * BaseTaskScheduler#maxResultWaitSec(ClientRecord,long)}. */ protected static void logHangResult( ClientRecord client, TestTask task, String msg ) { String header = "Result for " + client + ": " + task.toShortString() + ": "; Log.getLogWriter().severe( header + "HANG " + msg ); String err = "CLIENT " + client + "\n" + task.toShortString() + "\n" + "HANG " + msg + "\n"; writeErrorFile( err ); writeHangFile(); DeadlockDetection.detectDeadlocks(client); } ////////////////////////////////////////////////////////////////////////////// // ERROR AND HANG FILES ////////////////////////////////////////////////////////////////////////////// private static final String ERROR_FILE = "errors.txt"; private static final Object ERROR_FILE_LOCK = new Object(); private static final String HANG_FILE = "hang.txt"; private static final Object HANG_FILE_LOCK = new Object(); private static final String divider = "----------------------------------------" + "----------------------------------------\n"; /** * Writes the message to the error file. */ static void writeErrorFile( String msg ) { synchronized( ERROR_FILE_LOCK ) { FileUtil.appendToFile( ERROR_FILE, msg + divider ); } } /** * Writes the message to the hang file. */ private static void writeHangFile() { synchronized( HANG_FILE_LOCK ) { if ( ! FileUtil.exists( HANG_FILE ) ) { FileUtil.appendToFile( HANG_FILE, "possible hang in test...processes left running..." + "see " + ERROR_FILE + " for more info\n" ); } } } /** * Used by master to report errors in resource startup and unexpected * exceptions encountered by the test harness. */ protected static void reportErr( String msg, Throwable t ) { String err = "ERROR " + msg + "\n"; if ( t != null ) { err += "\n" + TestHelper.getStackTrace(t); } Log.getLogWriter().severe( err ); err = "THREAD " + Thread.currentThread().getName() + "\n" + err; writeErrorFile( err ); } /** * Used by master to report hangs in resource startup. */ protected static void reportHang( String msg, Throwable t ) { String err = "HANG "; if ( msg == null && t != null ) { err += t.getMessage() + "\n" + TestHelper.getStackTrace(t); } else if ( msg != null && t == null ) { err += msg + "\n"; } else if ( msg != null && t != null ) { err += msg + "\n" + TestHelper.getStackTrace(t); } else { err += "no information available\n"; } Log.getLogWriter().severe( err ); err = "THREAD " + Thread.currentThread().getName() + "\n" + err; writeErrorFile( err ); writeHangFile(); DeadlockDetection.detectDeadlocks(); } /** * Used by master to report errors in the WindowTester/GFMon VM result file. */ protected static void reportErr(int pid, String msg) { String err = "CLIENT WindowTester/GFMon VM pid=" + pid + "\n" + "ERROR " + msg; writeErrorFile(err); } /** * Used by master to report hangs in the WindowTester/GFMon VM result file. */ protected static void reportHang(int pid, String msg) { String err = "CLIENT WindowTester/GFMon VM pid=" + pid + "\n" + "HANG " + msg; writeErrorFile(err); writeHangFile(); DeadlockDetection.detectDeadlocks(); } ////////////////////////////////////////////////////////////////////////////// // FINAL OUTCOME PROCESSING SUPPORT METHODS ////////////////////////////////////////////////////////////////////////////// /** * Used by master to see if the test had errors (includes hangs). */ protected static boolean hasErrorFile() { synchronized( ERROR_FILE_LOCK ) { return FileUtil.exists( ERROR_FILE ); } } /** * Used by master and clients to see if the test had a hang. */ protected static boolean hasHangFile() { synchronized( HANG_FILE_LOCK ) { return FileUtil.exists( HANG_FILE ); } } /** * Used by master to report unexpected exceptions in the test harness. * @param m The method in which the exception occurred. * @param t The exception. */ protected static void reportAsErr( String m, Throwable t ) { String err = m + " -- unexpected exception"; reportErr( err, t ); } /** * Used by master to report unexpected problems treated as hangs by the * test harness. */ protected static void reportAsHang( String msg, Throwable t ) { reportHang( msg + " -- treating as hang", t ); } ////////////////////////////////////////////////////////////////////////////// // FINAL OUTCOME PROCESSING ////////////////////////////////////////////////////////////////////////////// /** * Used by master to log the final test outcome. * @param msg The test signoff message. * @param passed Whether the test passed. */ protected static void logFinalOutcome( String msg, boolean passed ) { Log.getLogWriter().severe( msg ); if (!passed) { try { FileUtil.createNewFile(FAILED_FILE); } catch (IOException e) { String s = "Unable to create new file " + FAILED_FILE; throw new HydraRuntimeException(s, e); } } } private static final String FAILED_FILE = "failed.txt"; ////////////////////////////////////////////////////////////////////////////// // PERFORMANCE REPOR ////////////////////////////////////////////////////////////////////////////// /** * Generates the performance report and writes it out. */ protected static void generatePerformanceReportFile() { ClientDescription cd = new ClientDescription(); cd.setName( "perfreporter" ); MasterDescription md = TestConfig.getInstance().getMasterDescription(); cd.setVmDescription( md.getVmDescription() ); String heap = "-Xmx" + TestConfig.tab().stringAt( PerfReportPrms.heapSize ); String brief = "-DBrief=" + TestConfig.tab().booleanAt(PerfReportPrms.generateBriefReport, false); cd.getVmDescription().setExtraVMArgs( heap + " " + brief ); int pid = Java.java( cd, "perffmwk.PerfReporter" ); Log.getLogWriter().info( "Done generating performance report...see " + md.getVmDescription().getHostDescription().getUserDir() + File.separator + "perfreport.txt for the result." + " The performance report log is bgexec*_" + pid + ".log." ); int maxWaitSec = TestConfig.tab().intAt( PerfReportPrms.maxReportWaitSec ); HostDescription hd = cd.getVmDescription().getHostDescription(); if ( ProcessMgr.waitForDeath( hd.getHostName(), pid, maxWaitSec ) ) { Nuker.getInstance().removePID(hd, pid ); } else { Log.getLogWriter().warning( "Waited more than " + maxWaitSec + " seconds for performance report to complete, try increasing " ); } } ////////////////////////////////////////////////////////////////////////////// // MERGE LOGS ////////////////////////////////////////////////////////////////////////////// /** * Uses {@link com.gemstone.gemfire.internal.MergeLogFiles} to merge test * log files into a single file, "mergedLogs.txt". The files * are assumed to end in <code>.log</code> and reside in the master user * directory and system logs (either local or remote). * * @param passed * Did the test pass? */ public static void mergeLogFiles( boolean passed ) { String fn = "mergedLogs.txt"; String value = TestConfig.tab().stringAt( LogPrms.mergeLogFiles, "false" ); if ( value.equalsIgnoreCase("true") || (value.equalsIgnoreCase("onFailure") && !passed) ) { try { String masterUserDir = System.getProperty( "user.dir" ); List logFiles = TestFileUtil.getMergeLogFiles(masterUserDir); int pid = Java.javaMergeLogFiles( fn, logFiles ); Log.getLogWriter().info( "Done merging log files...see " + fn + " for the result." + " The merge process log is bgexec*_" + pid + ".log." ); } catch (VirtualMachineError e) { // Don't try to handle this; let thread group catch it. throw e; } catch( Throwable t ) { t.printStackTrace(); } } } }
{ "content_hash": "edda281534393482fcdd79645300be5e", "timestamp": "", "source": "github", "line_count": 316, "max_line_length": 134, "avg_line_length": 34.83860759493671, "alnum_prop": 0.5540012716868017, "repo_name": "SnappyDataInc/snappy-store", "id": "d6a37e9d4ffc43ea09d7a26157eead78ffa570b2", "size": "11674", "binary": false, "copies": "3", "ref": "refs/heads/snappy/master", "path": "tests/core/src/main/java/hydra/ResultLogger.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AGS Script", "bytes": "90653" }, { "name": "Assembly", "bytes": "738033" }, { "name": "Batchfile", "bytes": "23509" }, { "name": "C", "bytes": "298655" }, { "name": "C#", "bytes": "1338285" }, { "name": "C++", "bytes": "784695" }, { "name": "CSS", "bytes": "54987" }, { "name": "Gnuplot", "bytes": "3125" }, { "name": "HTML", "bytes": "8595527" }, { "name": "Java", "bytes": "117988027" }, { "name": "JavaScript", "bytes": "33027" }, { "name": "Makefile", "bytes": "9359" }, { "name": "Mathematica", "bytes": "92588" }, { "name": "PHP", "bytes": "869892" }, { "name": "PLSQL", "bytes": "80858" }, { "name": "PLpgSQL", "bytes": "205179" }, { "name": "Pascal", "bytes": "3707" }, { "name": "Pawn", "bytes": "93609" }, { "name": "Perl", "bytes": "196843" }, { "name": "Python", "bytes": "131049" }, { "name": "Ruby", "bytes": "26443" }, { "name": "SQLPL", "bytes": "47702" }, { "name": "Shell", "bytes": "550962" }, { "name": "SourcePawn", "bytes": "15059" }, { "name": "TSQL", "bytes": "5461819" }, { "name": "Thrift", "bytes": "55057" }, { "name": "XSLT", "bytes": "67112" }, { "name": "sed", "bytes": "6411" } ], "symlink_target": "" }
module Piwik class VisitsSummary < ApiModule available_methods %W{ get getVisits getUniqueVisitors getActions getMaxActions getBounceCount getVisitsConverted getSumVisitsLength getSumVisitsLengthPretty } scoped_methods do def converted params = {} getVisitsConverted(defaults.merge(params)).value end def summary params = {} get(defaults.merge(params)) end def count params = {} getVisits(defaults.merge(params)).value end def uniques params = {} getUniqueVisitors(defaults.merge(params)).value end def actions params = {} getActions(defaults.merge(params)).value end def max_actions params = {} getMaxActions(defaults.merge(params)).value end def bounces params = {} getBounceCount(defaults.merge(params)).value end def length params = {} getSumVisitsLength(defaults.merge(params)).value end def pretty_length params = {} getSumVisitsLengthPretty(defaults.merge(params)).value end end end end
{ "content_hash": "b9cb6b6d185681e548e5b1e8139216fb", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 62, "avg_line_length": 21.849056603773583, "alnum_prop": 0.6217616580310881, "repo_name": "Monsido/piwik-ruby-api", "id": "e73160091be38fb864fab986461b524683818345", "size": "1158", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/piwik/visits_summary.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "53785" } ], "symlink_target": "" }
namespace leveldb { void BlockHandle::EncodeTo(std::string* dst) const { // Sanity check that all fields have been set assert(offset_ != ~static_cast<uint64_t>(0)); assert(size_ != ~static_cast<uint64_t>(0)); PutVarint64(dst, offset_); PutVarint64(dst, size_); } Status BlockHandle::DecodeFrom(Slice* input) { if (GetVarint64(input, &offset_) && GetVarint64(input, &size_)) { return Status::OK(); } else { return Status::Corruption("bad block handle"); } } void Footer::EncodeTo(std::string* dst) const { #ifndef NDEBUG const size_t original_size = dst->size(); #endif metaindex_handle_.EncodeTo(dst); index_handle_.EncodeTo(dst); dst->resize(2 * BlockHandle::kMaxEncodedLength); // Padding PutFixed32(dst, static_cast<uint32_t>(kTableMagicNumber & 0xffffffffu)); PutFixed32(dst, static_cast<uint32_t>(kTableMagicNumber >> 32)); assert(dst->size() == original_size + kEncodedLength); } Status Footer::DecodeFrom(Slice* input) { const char* magic_ptr = input->data() + kEncodedLength - 8; const uint32_t magic_lo = DecodeFixed32(magic_ptr); const uint32_t magic_hi = DecodeFixed32(magic_ptr + 4); const uint64_t magic = ((static_cast<uint64_t>(magic_hi) << 32) | (static_cast<uint64_t>(magic_lo))); if (magic != kTableMagicNumber) { return Status::InvalidArgument("not an sstable (bad magic number)"); } Status result = metaindex_handle_.DecodeFrom(input); if (result.ok()) { result = index_handle_.DecodeFrom(input); } if (result.ok()) { // We skip over any leftover data (just padding for now) in "input" const char* end = magic_ptr + 8; *input = Slice(end, input->data() + input->size() - end); } return result; } Status ReadBlock(RandomAccessFile* file, const ReadOptions& options, const BlockHandle& handle, Block** block) { *block = NULL; // Read the block contents as well as the type/crc footer. // See table_builder.cc for the code that built this structure. size_t n = static_cast<size_t>(handle.size()); char* buf = new char[n + kBlockTrailerSize]; Slice contents; Status s = file->Read(handle.offset(), n + kBlockTrailerSize, &contents, buf); if (!s.ok()) { delete[] buf; return s; } if (contents.size() != n + kBlockTrailerSize) { delete[] buf; return Status::Corruption("truncated block read"); } // Check the crc of the type and the block contents const char* data = contents.data(); // Pointer to where Read put the data if (options.verify_checksums) { const uint32_t crc = crc32c::Unmask(DecodeFixed32(data + n + 1)); const uint32_t actual = crc32c::Value(data, n + 1); if (actual != crc) { delete[] buf; s = Status::Corruption("block checksum mismatch"); return s; } } switch (data[n]) { case kNoCompression: if (data != buf) { // File implementation gave us pointer to some other data. // Copy into buf[]. memcpy(buf, data, n + kBlockTrailerSize); } // Ok break; case kSnappyCompression: { std::string decompressed; if (!port::Snappy_Uncompress(data, n, &decompressed)) { delete[] buf; s = Status::Corruption("corrupted compressed block contents"); return s; } delete[] buf; // Done with uncompressed data buf = new char[decompressed.size()]; memcpy(buf, decompressed.data(), decompressed.size()); n = decompressed.size(); break; } default: delete[] buf; return Status::Corruption("bad block type"); } *block = new Block(buf, n); // Block takes ownership of buf[] return Status::OK(); } }
{ "content_hash": "519db7dbd855bd4c31b23a8536f2ffe9", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 80, "avg_line_length": 31.33613445378151, "alnum_prop": 0.6288549208903191, "repo_name": "yuandaxing/leveldb", "id": "63971dbe9380c6d9424760216d18a13e4815946d", "size": "4097", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "table/format.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1625" }, { "name": "C++", "bytes": "514899" }, { "name": "Makefile", "bytes": "3841" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><link rel="stylesheet" type="text/css" href="../styles/main.css"><script language=JavaScript src="../javascript/main.js"></script></head><body class="PopupSearchResultsPage" onLoad="NDOnLoad()"><script language=JavaScript><!-- if (browserType) {document.write("<div class=" + browserType + ">");if (browserVer) {document.write("<div class=" + browserVer + ">"); }}// --></script> <!-- Generated by Natural Docs, version 1.5 --> <!-- http://www.naturaldocs.org --> <!-- saved from url=(0026)http://www.naturaldocs.org --> <div id=Index><div class=SRStatus id=Loading>Loading...</div><table border=0 cellspacing=0 cellpadding=0><div class=SRResult id=SR_refresh><div class=IEntry><a href="../files/jstree-js.html#jstree.refresh" target=_parent class=ISymbol>refresh</a>, <span class=IParent>jstree</span></div></div><div class=SRResult id=SR_remove_undcss><div class=IEntry><a href="../files/vakata-js.html#$.vakata.css.remove_css" target=_parent class=ISymbol>remove_css</a>, <span class=IParent>$.vakata.css</span></div></div><div class=SRResult id=SR_rename_undnode><div class=IEntry><a href="../files/jstree-js.html#jstree.rename_node" target=_parent class=ISymbol>rename_node</a>, <span class=IParent>jstree</span></div></div></table><div class=SRStatus id=Searching>Searching...</div><div class=SRStatus id=NoMatches>No Matches</div><script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults", "HTML"); searchResults.Search(); --></script></div><script language=JavaScript><!-- if (browserType) {if (browserVer) {document.write("</div>"); }document.write("</div>");}// --></script></body></html>
{ "content_hash": "f2a875189b02ee46dd2618972eb96c30", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 851, "avg_line_length": 93.1, "alnum_prop": 0.7089151450053706, "repo_name": "lydianblues/jstree-rails", "id": "be1a17cb610c490629816d956a291d16f37ee82b", "size": "1862", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "docs/search/FunctionsR.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "204175" }, { "name": "Ruby", "bytes": "1086" }, { "name": "Shell", "bytes": "2952" } ], "symlink_target": "" }
namespace shell { Tracer::Tracer() : tracing_(false), first_chunk_written_(false), trace_file_(nullptr) { } Tracer::~Tracer() { } void Tracer::Start(const std::string& categories, const std::string& duration_seconds_str, const std::string& filename) { trace_duration_secs_ = 5; if (!duration_seconds_str.empty()) { CHECK(base::StringToInt(duration_seconds_str, &trace_duration_secs_)) << "Could not parse --trace-startup-duration value " << duration_seconds_str; } tracing_ = true; trace_filename_ = filename; categories_ = categories; base::trace_event::CategoryFilter category_filter(categories); base::trace_event::TraceLog::GetInstance()->SetEnabled( category_filter, base::trace_event::TraceLog::RECORDING_MODE, base::trace_event::TraceOptions(base::trace_event::RECORD_UNTIL_FULL)); } void Tracer::DidCreateMessageLoop() { if (!tracing_) return; base::MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&shell::Tracer::StopAndFlushToFile, base::Unretained(this)), base::TimeDelta::FromSeconds(trace_duration_secs_)); } void Tracer::StartCollectingFromTracingService( tracing::TraceCoordinatorPtr coordinator) { coordinator_ = coordinator.Pass(); mojo::DataPipe data_pipe; coordinator_->Start(data_pipe.producer_handle.Pass(), categories_); drainer_.reset(new mojo::common::DataPipeDrainer( this, data_pipe.consumer_handle.Pass())); } void Tracer::StopAndFlushToFile() { if (tracing_) StopTracingAndFlushToDisk(); } void Tracer::ConnectToController( mojo::InterfaceRequest<tracing::TraceController> request) { auto impl = new mojo::TraceControllerImpl(request.Pass()); impl->set_tracing_already_started(tracing_); } void Tracer::StopTracingAndFlushToDisk() { tracing_ = false; trace_file_ = fopen(trace_filename_.c_str(), "w+"); PCHECK(trace_file_); static const char kStart[] = "{\"traceEvents\":["; PCHECK(fwrite(kStart, 1, strlen(kStart), trace_file_) == strlen(kStart)); // At this point we might be connected to the tracing service, in which case // we want to tell it to stop tracing and we will send the data we've // collected in process to it. if (coordinator_) { coordinator_->StopAndFlush(); } else { // Or we might not be connected. If we aren't connected to the tracing // service we want to collect the tracing data gathered ourselves and flush // it to disk. We do this in a blocking fashion (for this thread) so we can // gather as much data as possible on shutdown. base::trace_event::TraceLog::GetInstance()->SetDisabled(); { base::WaitableEvent flush_complete_event(false, false); // TraceLog::Flush requires a message loop but we've already shut ours // down. // Spin up a new thread to flush things out. base::Thread flush_thread("mojo_shell_trace_event_flush"); flush_thread.Start(); flush_thread.message_loop()->PostTask( FROM_HERE, base::Bind(&Tracer::EndTraceAndFlush, base::Unretained(this), trace_filename_, base::Bind(&base::WaitableEvent::Signal, base::Unretained(&flush_complete_event)))); base::trace_event::TraceLog::GetInstance() ->SetCurrentThreadBlocksMessageLoop(); flush_complete_event.Wait(); } } } void Tracer::WriteFooterAndClose() { static const char kEnd[] = "]}"; PCHECK(fwrite(kEnd, 1, strlen(kEnd), trace_file_) == strlen(kEnd)); PCHECK(fclose(trace_file_) == 0); trace_file_ = nullptr; LOG(INFO) << "Wrote trace data to " << trace_filename_; } void Tracer::EndTraceAndFlush(const std::string& filename, const base::Closure& done_callback) { base::trace_event::TraceLog::GetInstance()->SetDisabled(); base::trace_event::TraceLog::GetInstance()->Flush(base::Bind( &Tracer::WriteTraceDataCollected, base::Unretained(this), done_callback)); } void Tracer::WriteTraceDataCollected( const base::Closure& done_callback, const scoped_refptr<base::RefCountedString>& events_str, bool has_more_events) { if (events_str->size()) { WriteCommaIfNeeded(); PCHECK(fwrite(events_str->data().c_str(), 1, events_str->data().length(), trace_file_) == events_str->data().length()); } if (!has_more_events && !done_callback.is_null()) done_callback.Run(); } void Tracer::OnDataAvailable(const void* data, size_t num_bytes) { const char* chars = static_cast<const char*>(data); trace_service_data_.append(chars, num_bytes); } void Tracer::OnDataComplete() { if (!trace_service_data_.empty()) { WriteCommaIfNeeded(); const char* const chars = trace_service_data_.data(); size_t num_bytes = trace_service_data_.length(); PCHECK(fwrite(chars, 1, num_bytes, trace_file_) == num_bytes); trace_service_data_ = std::string(); } drainer_.reset(); coordinator_.reset(); WriteFooterAndClose(); } void Tracer::WriteCommaIfNeeded() { if (first_chunk_written_) PCHECK(fwrite(",", 1, 1, trace_file_) == 1); first_chunk_written_ = true; } } // namespace shell
{ "content_hash": "933b0acfdf19e19c0252c007931f0fa2", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 80, "avg_line_length": 34.70666666666666, "alnum_prop": 0.6613522858240491, "repo_name": "collinjackson/mojo", "id": "329360a353cdf1dc10112ecbd620f1deef0b22bf", "size": "5662", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shell/tracer.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Bison", "bytes": "31162" }, { "name": "C", "bytes": "1870198" }, { "name": "C++", "bytes": "36473977" }, { "name": "CSS", "bytes": "1897" }, { "name": "Dart", "bytes": "508640" }, { "name": "Go", "bytes": "181090" }, { "name": "Groff", "bytes": "29030" }, { "name": "HTML", "bytes": "6258864" }, { "name": "Java", "bytes": "1187123" }, { "name": "JavaScript", "bytes": "204155" }, { "name": "Makefile", "bytes": "402" }, { "name": "Objective-C", "bytes": "74603" }, { "name": "Objective-C++", "bytes": "370763" }, { "name": "Protocol Buffer", "bytes": "1048" }, { "name": "Python", "bytes": "5515876" }, { "name": "Shell", "bytes": "143302" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
package org.springframework.security.authentication; import org.springframework.security.core.AuthenticationException; /** * Base class for authentication exceptions which are caused by a particular user account * status (locked, disabled etc). * * @author Luke Taylor */ public abstract class AccountStatusException extends AuthenticationException { public AccountStatusException(String msg) { super(msg); } public AccountStatusException(String msg, Throwable cause) { super(msg, cause); } }
{ "content_hash": "5adbfd054de7902cff9401fe4a39b263", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 89, "avg_line_length": 22.304347826086957, "alnum_prop": 0.7777777777777778, "repo_name": "rwinch/spring-security", "id": "f465f995d6ce055271f0e00d1a587f108ffa1cd3", "size": "1134", "binary": false, "copies": "5", "ref": "refs/heads/main", "path": "core/src/main/java/org/springframework/security/authentication/AccountStatusException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "3335" }, { "name": "Groovy", "bytes": "45904" }, { "name": "HTML", "bytes": "80" }, { "name": "Java", "bytes": "15052314" }, { "name": "JavaScript", "bytes": "10" }, { "name": "Kotlin", "bytes": "811144" }, { "name": "PLSQL", "bytes": "3180" }, { "name": "Python", "bytes": "129" }, { "name": "Shell", "bytes": "2307" }, { "name": "XSLT", "bytes": "2369" } ], "symlink_target": "" }
package leveldb import "github.com/kezhuw/leveldb/internal/batch" // Batch holds a collection of updates to apply atomatically to a DB. type Batch struct { batch batch.Batch } // Put adds a key/value update to batch. func (b *Batch) Put(key, value []byte) { b.batch.Put(key, value) } // Delete adds a key deletion to batch. func (b *Batch) Delete(key []byte) { b.batch.Delete(key) } // Clear clears all updates written before. func (b *Batch) Clear() { b.batch.Clear() } func (b *Batch) empty() bool { return b.batch.Empty() } func (b *Batch) err() error { return b.batch.Err() }
{ "content_hash": "73d721c043b84d4522d216a05590f043", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 69, "avg_line_length": 19.129032258064516, "alnum_prop": 0.684654300168634, "repo_name": "kezhuw/leveldb", "id": "ba5c34eadc1d1792ee81ac2eba78c9ea7c89897f", "size": "593", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "batch.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "350920" }, { "name": "Shell", "bytes": "291" } ], "symlink_target": "" }
from xml.etree import ElementTree import json import os import shutil from contextlib import contextmanager import logging from copy import deepcopy import validictory import build_steps import build_steps_local import build_steps_predicates from xcode import XcodeProject LOG = logging.getLogger(__name__) @contextmanager def cd(target_dir): 'Change directory to :param:`target_dir` as a context manager - i.e. rip off Fabric' old_dir = os.getcwd() try: os.chdir(target_dir) yield target_dir finally: os.chdir(old_dir) # Needed to prevent elementtree screwing with namespace names ElementTree.register_namespace('android', 'http://schemas.android.com/apk/res/android') ElementTree.register_namespace('tools', 'http://schemas.android.com/tools') def dict_merge(a, b): '''recursively merges dict's. not just simple a['key'] = b['key'], if both a and b have a key who's value is a dict then dict_merge is called on both values and the result stored in the returned dictionary.''' if not isinstance(b, dict): return b result = deepcopy(a) for k, v in b.iteritems(): if k in result and isinstance(result[k], dict): result[k] = dict_merge(result[k], v) else: result[k] = deepcopy(v) return result def _call_with_params(method, build_params, params): if isinstance(params, dict): return method(build_params, **params) elif isinstance(params, tuple): return method(build_params, *params) else: return method(build_params, params) def apply_module_to_osx_project(module_path, project_path, skip_framework=False, inspector_config=False, include_tests=False, local_build_steps=None, app_config=None): """Take the module in a specific folder and apply it to an xcode ios project in another folder""" if not os.path.exists(os.path.join(module_path, 'manifest.json')): LOG.warning("Failed to include module: %s" % module_path) return with open(os.path.join(module_path, 'manifest.json')) as manifest_file: manifest = json.load(manifest_file) # JS if os.path.exists(os.path.join(module_path, 'javascript', 'module.js')): with open(os.path.join(module_path, 'javascript', 'module.js')) as module_js: with open(os.path.join(project_path, 'ForgeInspector', 'assets', 'forge', 'all.js'), 'a') as alljs: alljs.write('(function () {\n') alljs.write(module_js.read()) alljs.write('\n})();') # Tests if include_tests: if os.path.exists(os.path.join(module_path, 'tests', 'fixtures')): if os.path.exists(os.path.join(project_path, 'ForgeInspector', 'assets', 'src', 'fixtures', manifest['name'])): shutil.rmtree(os.path.join(project_path, 'ForgeInspector', 'assets', 'src', 'fixtures', manifest['name'])) if not os.path.exists(os.path.join(project_path, 'ForgeInspector', 'assets', 'src', 'fixtures')): os.makedirs(os.path.join(project_path, 'ForgeInspector', 'assets', 'src', 'fixtures')) shutil.copytree(os.path.join(module_path, 'tests', 'fixtures'), os.path.join(project_path, 'ForgeInspector', 'assets', 'src', 'fixtures', manifest['name'])) if os.path.exists(os.path.join(module_path, 'tests', 'automated.js')): try: os.makedirs(os.path.join(project_path, 'ForgeInspector', 'assets', 'forge', 'tests', 'automated')) except OSError: pass shutil.copy2(os.path.join(module_path, 'tests', 'automated.js'), os.path.join(project_path, 'ForgeInspector', 'assets', 'forge', 'tests', 'automated', manifest['name']+'.js')) if os.path.exists(os.path.join(module_path, 'tests', 'interactive.js')): try: os.makedirs(os.path.join(project_path, 'ForgeInspector', 'assets', 'forge', 'tests', 'interactive')) except OSError: pass shutil.copy2(os.path.join(module_path, 'tests', 'interactive.js'), os.path.join(project_path, 'ForgeInspector', 'assets', 'forge', 'tests', 'interactive', manifest['name']+'.js')) # Add module a if we want it if not skip_framework: module_framework = os.path.join(module_path, 'osx', '%s.framework' % manifest['name']) if os.path.isdir(module_framework): shutil.copytree(module_framework, os.path.join(project_path, '%s.framework' % manifest['name'])) xcode_project = XcodeProject(os.path.join(project_path, 'ForgeInspector.xcodeproj', 'project.pbxproj')) xcode_project.add_framework(manifest['name']+'.framework', "<group>") xcode_project.add_saved_framework(manifest['name']+'.framework', "<group>") xcode_project.save() if inspector_config: # Add inspector config for module to app_config.js(on). if app_config is None: with open(os.path.join(project_path, 'ForgeInspector', 'assets', 'app_config.json')) as app_config_json: app_config = json.load(app_config_json) if os.path.exists(os.path.join(module_path, 'inspector_config.json')): with open(os.path.join(module_path, 'inspector_config.json'), "r") as inspector_config_file: inspector_config = json.load(inspector_config_file) else: inspector_config = { "modules": { manifest['name']: { "version": "exampleversion" } } } app_config = dict_merge(app_config, inspector_config) with open(os.path.join(project_path, 'ForgeInspector', 'assets', 'app_config.json'), 'w') as app_config_json: json.dump(app_config, app_config_json) with open(os.path.join(project_path, 'ForgeInspector', 'assets', 'forge', 'app_config.js'), 'w') as app_config_js: app_config_js.write("window.forge = {}; window.forge.config = %s;" % json.dumps(app_config)) # Validate config if os.path.exists(os.path.join(module_path, 'config_schema.json')) and \ "config" in app_config['modules'][manifest['name']]: with open(os.path.join(module_path, 'config_schema.json')) as schema_file: config_schema = json.load(schema_file) try: validictory.validate(app_config['modules'][manifest['name']]['config'], config_schema) except validictory.ValidationError as e: raise Exception("Validation failed for module '%s' with error: %s" % (manifest['name'], str(e))) # frameworks module_frameworks = os.path.join(module_path, 'osx', 'frameworks') if os.path.isdir(module_frameworks): if os.path.exists(os.path.join(project_path, 'ForgeModule')): xcode_project = XcodeProject(os.path.join(project_path, 'ForgeModule', 'ForgeModule.xcodeproj', 'project.pbxproj')) xcode_inspector_project = XcodeProject(os.path.join(project_path, 'ForgeInspector.xcodeproj', 'project.pbxproj')) for framework in os.listdir(module_frameworks): if framework.endswith(".framework"): shutil.copytree(os.path.join(module_frameworks, framework), os.path.join(project_path, framework)) if os.path.exists(os.path.join(project_path, 'ForgeModule')): xcode_project.add_framework(os.path.join('..', framework), '<group>') xcode_inspector_project.add_saved_framework(framework, '<group>') if os.path.exists(os.path.join(project_path, 'ForgeModule')): xcode_project.save() xcode_inspector_project.save() # build steps module_steps_path = os.path.join(module_path, 'osx', 'build_steps.json') if os.path.isfile(module_steps_path): with open(module_steps_path, 'r') as build_steps_file: module_build_steps = json.load(build_steps_file) with cd(project_path): build_params = { 'app_config': app_config, 'project_path': project_path, 'src_path': local_build_steps } for step in module_build_steps: if "do" in step: for task in step["do"]: task_func = getattr(build_steps, task, None) if task_func is not None: _call_with_params(task_func, build_params, step["do"][task]) elif local_build_steps is not None: task_func = getattr(build_steps_local, task, None) if task_func is not None: _call_with_params(task_func, build_params, step["do"][task]) if local_build_steps is None: if not os.path.exists(os.path.join(project_path, "dist", "build_steps")): os.makedirs(os.path.join(project_path, "dist", "build_steps")) shutil.copy2(module_steps_path, os.path.join(project_path, "dist", "build_steps", manifest['name'] + ".json")) def apply_module_to_ios_project(module_path, project_path, skip_a=False, inspector_config=False, include_tests=False, local_build_steps=None, app_config=None): """Take the module in a specific folder and apply it to an xcode ios project in another folder""" if not os.path.exists(os.path.join(module_path, 'manifest.json')): LOG.warning("Failed to include module: %s" % module_path) return with open(os.path.join(module_path, 'manifest.json')) as manifest_file: manifest = json.load(manifest_file) # JS if os.path.exists(os.path.join(module_path, 'javascript', 'module.js')): LOG.info("iOS module '%s': Appending module.js to all.js" % manifest['name']) with open(os.path.join(module_path, 'javascript', 'module.js')) as module_js: with open(os.path.join(project_path, 'ForgeInspector', 'assets', 'forge', 'all.js'), 'a') as alljs: alljs.write('(function () {\n') alljs.write(module_js.read()) alljs.write('\n})();') # Tests if include_tests: LOG.info("iOS module '%s': Including test files" % manifest['name']) if os.path.exists(os.path.join(module_path, 'tests', 'fixtures')): if os.path.exists(os.path.join(project_path, 'ForgeInspector', 'assets', 'src', 'fixtures', manifest['name'])): shutil.rmtree(os.path.join(project_path, 'ForgeInspector', 'assets', 'src', 'fixtures', manifest['name'])) if not os.path.exists(os.path.join(project_path, 'ForgeInspector', 'assets', 'src', 'fixtures')): os.makedirs(os.path.join(project_path, 'ForgeInspector', 'assets', 'src', 'fixtures')) shutil.copytree(os.path.join(module_path, 'tests', 'fixtures'), os.path.join(project_path, 'ForgeInspector', 'assets', 'src', 'fixtures', manifest['name'])) if os.path.exists(os.path.join(module_path, 'tests', 'automated.js')): try: os.makedirs(os.path.join(project_path, 'ForgeInspector', 'assets', 'forge', 'tests', 'automated')) except OSError: pass shutil.copy2(os.path.join(module_path, 'tests', 'automated.js'), os.path.join(project_path, 'ForgeInspector', 'assets', 'forge', 'tests', 'automated', manifest['name']+'.js')) if os.path.exists(os.path.join(module_path, 'tests', 'interactive.js')): try: os.makedirs(os.path.join(project_path, 'ForgeInspector', 'assets', 'forge', 'tests', 'interactive')) except OSError: pass shutil.copy2(os.path.join(module_path, 'tests', 'interactive.js'), os.path.join(project_path, 'ForgeInspector', 'assets', 'forge', 'tests', 'interactive', manifest['name']+'.js')) # Add module a if we want it if not skip_a: LOG.info("iOS module '%s': Including module.a" % manifest['name']) module_a = os.path.join(module_path, 'ios', 'module.a') if os.path.isfile(module_a): # Copy to libs shutil.copy2(module_a, os.path.join(project_path, manifest['name']+'.a')) # Add to xcode build xcode_project = XcodeProject(os.path.join(project_path, 'ForgeInspector.xcodeproj', 'project.pbxproj')) xcode_project.add_framework(manifest['name']+'.a', "<group>") xcode_project.save() if inspector_config: LOG.info("iOS module '%s': Including inspector config" % manifest['name']) if app_config is None: with open(os.path.join(project_path, 'ForgeInspector', 'assets', 'app_config.json')) as app_config_json: app_config = json.load(app_config_json) if os.path.exists(os.path.join(module_path, 'inspector_config.json')): with open(os.path.join(module_path, 'inspector_config.json'), "r") as inspector_config_file: inspector_config = json.load(inspector_config_file) else: inspector_config = { "modules": { manifest['name']: { "version": "exampleversion" } } } app_config = dict_merge(app_config, inspector_config) with open(os.path.join(project_path, 'ForgeInspector', 'assets', 'app_config.json'), 'w') as app_config_json: json.dump(app_config, app_config_json) with open(os.path.join(project_path, 'ForgeInspector', 'assets', 'forge', 'app_config.js'), 'w') as app_config_js: app_config_js.write("window.forge = {}; window.forge.config = %s;" % json.dumps(app_config)) # Validate config if os.path.exists(os.path.join(module_path, 'config_schema.json')) and \ "config" in app_config['modules'][manifest['name']]: with open(os.path.join(module_path, 'config_schema.json')) as schema_file: config_schema = json.load(schema_file) try: validictory.validate(app_config['modules'][manifest['name']]['config'], config_schema) except validictory.ValidationError as e: raise Exception("Validation failed for module '%s' with error: %s" % (manifest['name'], str(e))) # bundles module_bundles = os.path.join(module_path, 'ios', 'bundles') if os.path.isdir(module_bundles): LOG.info("iOS module '%s': Including bundles" % manifest['name']) xcode_project = XcodeProject(os.path.join(project_path, 'ForgeInspector.xcodeproj', 'project.pbxproj')) for bundle in os.listdir(module_bundles): if bundle.endswith(".bundle"): shutil.copytree(os.path.join(module_bundles, bundle), os.path.join(project_path, bundle)) xcode_project.add_resource(bundle) xcode_project.save() # build steps module_steps_path = os.path.join(module_path, 'ios', 'build_steps.json') if os.path.isfile(module_steps_path): LOG.info("iOS module '%s': Applying build steps" % manifest['name']) with open(module_steps_path, 'r') as build_steps_file: module_build_steps = json.load(build_steps_file) with cd(project_path): build_params = { 'app_config': app_config, 'project_path': os.path.join(project_path, "ForgeInspector"), 'src_path': local_build_steps } for step in module_build_steps: if "when" in step: should_continue = False for predicate in step["when"]: predicate_func = getattr(build_steps_predicates, predicate, None) if predicate_func is not None: if not _call_with_params(predicate_func, build_params, step["when"][predicate]): should_continue = True break else: should_continue = True break if should_continue: continue if "do" in step: for task in step["do"]: task_func = getattr(build_steps, task, None) if task_func is not None: _call_with_params(task_func, build_params, step["do"][task]) elif local_build_steps is not None: task_func = getattr(build_steps_local, task, None) if task_func is not None: _call_with_params(task_func, build_params, step["do"][task]) if local_build_steps is None: if not os.path.exists(os.path.join(project_path, "dist", "build_steps")): os.makedirs(os.path.join(project_path, "dist", "build_steps")) shutil.copy2(module_steps_path, os.path.join(project_path, "dist", "build_steps", manifest['name'] + ".json")) def apply_module_to_android_project(module_path, project_path, skip_jar=False, inspector_config=False, include_tests=False, local_build_steps=None, app_config=None): """Take the module in a specific folder and apply it to an eclipse android project in another folder""" if not os.path.exists(os.path.join(module_path, 'manifest.json')): LOG.warning("Failed to include module: %s" % module_path) return with open(os.path.join(module_path, 'manifest.json')) as manifest_file: manifest = json.load(manifest_file) # JS if os.path.exists(os.path.join(module_path, 'javascript', 'module.js')): LOG.info("Android module '%s': Appending module.js to all.js" % manifest['name']) with open(os.path.join(module_path, 'javascript', 'module.js')) as module_js: with open(os.path.join(project_path, 'assets', 'forge', 'all.js'), 'a') as alljs: alljs.write('(function () {\n') alljs.write(module_js.read()) alljs.write('\n})();') # Tests if include_tests: LOG.info("Android module '%s': Including test files" % manifest['name']) if os.path.exists(os.path.join(module_path, 'tests', 'fixtures')): if os.path.exists(os.path.join(project_path, 'assets', 'src', 'fixtures', manifest['name'])): shutil.rmtree(os.path.join(project_path, 'assets', 'src', 'fixtures', manifest['name'])) if not os.path.exists(os.path.join(project_path, 'assets', 'src', 'fixtures')): os.makedirs(os.path.join(project_path, 'assets', 'src', 'fixtures')) shutil.copytree(os.path.join(module_path, 'tests', 'fixtures'), os.path.join(project_path, 'assets', 'src', 'fixtures', manifest['name'])) if os.path.exists(os.path.join(module_path, 'tests', 'automated.js')): try: os.makedirs(os.path.join(project_path, 'assets', 'forge', 'tests', 'automated')) except OSError: pass shutil.copy2(os.path.join(module_path, 'tests', 'automated.js'), os.path.join(project_path, 'assets', 'forge', 'tests', 'automated', manifest['name']+'.js')) if os.path.exists(os.path.join(module_path, 'tests', 'interactive.js')): try: os.makedirs(os.path.join(project_path, 'assets', 'forge', 'tests', 'interactive')) except OSError: pass shutil.copy2(os.path.join(module_path, 'tests', 'interactive.js'), os.path.join(project_path, 'assets', 'forge', 'tests', 'interactive', manifest['name']+'.js')) # Add module jar if we want it if not skip_jar: LOG.info("Android module '%s': Adding module jar to libs" % manifest['name']) module_jar = os.path.join(module_path, 'android', 'module.jar') if not os.path.exists(os.path.join(project_path, 'libs')): os.makedirs(os.path.join(project_path, 'libs')) if os.path.exists(module_jar): shutil.copy2(module_jar, os.path.join(project_path, 'libs', manifest['name']+'.jar')) if inspector_config: LOG.info("Android module '%s': Including inspector config" % manifest['name']) if app_config is None: with open(os.path.join(project_path, 'assets', 'app_config.json')) as app_config_json: app_config = json.load(app_config_json) if os.path.exists(os.path.join(module_path, 'inspector_config.json')): with open(os.path.join(module_path, 'inspector_config.json'), "r") as inspector_config_file: inspector_config = json.load(inspector_config_file) else: inspector_config = { "modules": { manifest['name']: { "version": "exampleversion" } } } app_config = dict_merge(app_config, inspector_config) with open(os.path.join(project_path, 'assets', 'app_config.json'), 'w') as app_config_json: json.dump(app_config, app_config_json) with open(os.path.join(project_path, 'assets', 'forge', 'app_config.js'), 'w') as app_config_js: app_config_js.write("window.forge = {}; window.forge.config = %s;" % json.dumps(app_config)) # Validate config if os.path.exists(os.path.join(module_path, 'config_schema.json')) and \ "config" in app_config['modules'][manifest['name']]: with open(os.path.join(module_path, 'config_schema.json')) as schema_file: config_schema = json.load(schema_file) try: validictory.validate(app_config['modules'][manifest['name']]['config'], config_schema) except validictory.ValidationError as e: raise Exception("Validation failed for module '%s' with error: %s" % (manifest['name'], str(e))) # res module_res = os.path.join(module_path, 'android', 'res') if os.path.isdir(module_res): LOG.info("Android module '%s': Adding module res files" % manifest['name']) for dirpath, _, filenames in os.walk(module_res): if not os.path.exists(os.path.join(project_path, 'res', dirpath[len(module_res)+1:])): os.makedirs(os.path.join(project_path, 'res', dirpath[len(module_res)+1:])) for filename in filenames: if (filename.startswith('.')): continue if os.path.exists(os.path.join(project_path, 'res', dirpath[len(module_res)+1:], filename)): raise Exception("File '%s' already exists, module resources may only add files, not replace them." % os.path.join('res', dirpath[len(module_res)+1:], filename)) shutil.copy2(os.path.join(dirpath, filename), os.path.join(project_path, 'res', dirpath[len(module_res)+1:], filename)) # libs module_res = os.path.join(module_path, 'android', 'libs') if os.path.isdir(module_res): LOG.info("Android module '%s': Adding module lib files" % manifest['name']) for dirpath, _, filenames in os.walk(module_res): if not os.path.exists(os.path.join(project_path, 'libs', dirpath[len(module_res)+1:])): os.makedirs(os.path.join(project_path, 'libs', dirpath[len(module_res)+1:])) for filename in filenames: shutil.copy2(os.path.join(dirpath, filename), os.path.join(project_path, 'libs', dirpath[len(module_res)+1:], filename)) # build steps if os.path.isfile(os.path.join(module_path, 'android', 'build_steps.json')): LOG.info("Android module '%s': Performing build steps" % manifest['name']) with open(os.path.join(module_path, 'android', 'build_steps.json')) as build_steps_file: module_build_steps = json.load(build_steps_file) with cd(project_path): build_params = { 'app_config': app_config, 'project_path': project_path, 'src_path': local_build_steps } for step in module_build_steps: if "do" in step: for task in step["do"]: task_func = getattr(build_steps, task, None) if task_func is not None: _call_with_params(task_func, build_params, step["do"][task]) elif local_build_steps is not None: task_func = getattr(build_steps_local, task, None) if task_func is not None: _call_with_params(task_func, build_params, step["do"][task]) if local_build_steps is None: module_steps_path = os.path.join(module_path, 'android', 'build_steps.json') if not os.path.exists(os.path.join(project_path, "build_steps")): os.makedirs(os.path.join(project_path, "build_steps")) shutil.copy2(module_steps_path, os.path.join(project_path, "build_steps", manifest['name'] + ".json"))
{ "content_hash": "eda608c9e0db9558331e484a7b0265ac", "timestamp": "", "source": "github", "line_count": 455, "max_line_length": 182, "avg_line_length": 47.74285714285714, "alnum_prop": 0.6826865534226396, "repo_name": "mnaughto/trigger-statusbar", "id": "aabe67a6ce3fae762b01518426100a3027c27f6b", "size": "21723", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".trigger/module_dynamic/build.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "386" }, { "name": "CSS", "bytes": "116661" }, { "name": "D", "bytes": "1536" }, { "name": "JavaScript", "bytes": "64389" }, { "name": "Objective-C", "bytes": "28595" }, { "name": "Python", "bytes": "140312" } ], "symlink_target": "" }
import VXC = require("./VXComponent"); import VXO = require("./VXObject"); import VXM = require("./VXMenu"); import V = require("./VCL"); export declare class TListbox extends VXC.TComponent { items: VXO.TCollection<TListboxItem>; createItem(value: string, text?: string): TListboxItem; onChanged: (sender: TListbox) => void; private jListBox; create(): void; draw(reCreate: boolean): void; } export declare class TListboxItem extends VXM.TMenuItem { constructor(); private _value; Value: string; } export declare class TTreeNodeItem extends VXM.TMenuItem { constructor(); onClicked: (item: V.TTreeNodeItem) => void; private showChilds(); private hideChilds(); private select(select); create(): void; private _expanded; Expanded: boolean; private _selectable; Selectable: boolean; private parentNode; ParentNode: TTreeNodeItem; private _value; Value: string; private jItemLI; private jItemUL; private jItemI; private jItemSPAN; private jItemTEXT; private tree; } export declare class TTree extends VXC.TComponent { items: VXO.TCollection<TTreeNodeItem>; createNode(parentNode: TTreeNodeItem, value: string, text?: string): V.TTreeNodeItem; private _selectednNode; SelectedNode: TTreeNodeItem; onChanged: (sender: TTree) => void; collapseAll(): void; expandAll(): void; private createChilds(prnt); create(): void; draw(reCreate: boolean): void; }
{ "content_hash": "5527ea8ccbb713e408e8c8d4f3289a9c", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 89, "avg_line_length": 29.45098039215686, "alnum_prop": 0.6857523302263648, "repo_name": "vclteam/VCL.JS", "id": "1ff36c0343aca7c7daec338f6aec6434d070a06c", "size": "1502", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "VCL/VXListBox.d.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "79264" }, { "name": "JavaScript", "bytes": "1518816" }, { "name": "TypeScript", "bytes": "1233905" } ], "symlink_target": "" }
""" This is a simple Python GTK+3 TreeView selection snippet. See: http://python-gtk-3-tutorial.readthedocs.org/en/latest/treeview.html """ from gi.repository import Gtk as gtk # Countries, population (as in 2015) and continent. DATA_LIST = [("China", 1370130000, "Asia"), ("India", 1271980000, "Asia"), ("United States", 321107000, "America"), ("Indonesia", 255461700, "Asia"), ("Brazil", 204388000, "America"), ("Pakistan", 189936000, "Asia"), ("Nigeria", 183523000, "Africa"), ("Bangladesh", 158425000, "Asia"), ("Russia", 146267288, "Eurasia"), ("Japan", 126880000, "Asia")] # The TreeView's selection callback def on_tree_selection_changed(selection): model, treeiter = selection.get_selected() if treeiter != None: print("You selected", model[treeiter][0]) def main(): window = gtk.Window() window.set_default_size(300, 450) window.set_border_width(18) # Creating the ListStore model liststore = gtk.ListStore(str, int, str) for item in DATA_LIST: liststore.append(list(item)) # Creating the treeview and add the columns treeview = gtk.TreeView(liststore) for column_index, column_title in enumerate(["Country", "Population", "Continent"]): renderer = gtk.CellRendererText() column = gtk.TreeViewColumn(column_title, renderer, text=column_index) column.set_resizable(True) # Let the column be resizable treeview.append_column(column) # Connect to the "changed" signal select = treeview.get_selection() select.connect("changed", on_tree_selection_changed) # Scrolled window scrolled_window = gtk.ScrolledWindow() scrolled_window.set_border_width(0) scrolled_window.set_shadow_type(gtk.ShadowType.IN) # should be gtk.ShadowType.IN, gtk.ShadowType.OUT, gtk.ShadowType.ETCHED_IN or gtk.ShadowType.ETCHED_OUT scrolled_window.set_policy(gtk.PolicyType.AUTOMATIC, gtk.PolicyType.ALWAYS) # should be gtk.PolicyType.AUTOMATIC, gtk.PolicyType.ALWAYS or gtk.PolicyType.NEVER scrolled_window.add(treeview) window.add(scrolled_window) window.connect("delete-event", gtk.main_quit) # ask to quit the application when the close button is clicked window.show_all() # display the window gtk.main() # GTK+ main loop if __name__ == '__main__': main()
{ "content_hash": "2278e7b07fed76381796efc1bfb1f1f2", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 188, "avg_line_length": 38.18181818181818, "alnum_prop": 0.6365079365079365, "repo_name": "jeremiedecock/snippets", "id": "01fb3e7a735eb66d632850369d68dcc665fcb565", "size": "2629", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/pygtk/python_gtk3_pygobject/tree_view_selection.py", "mode": "33261", "license": "mit", "language": [ { "name": "AMPL", "bytes": "4294" }, { "name": "Batchfile", "bytes": "6779" }, { "name": "C", "bytes": "102107" }, { "name": "C++", "bytes": "320943" }, { "name": "CMake", "bytes": "11424" }, { "name": "CSS", "bytes": "21121" }, { "name": "Cython", "bytes": "21" }, { "name": "Dockerfile", "bytes": "1818" }, { "name": "Fortran", "bytes": "633" }, { "name": "Gnuplot", "bytes": "39999" }, { "name": "Go", "bytes": "3166" }, { "name": "Groovy", "bytes": "3009" }, { "name": "HTML", "bytes": "138995" }, { "name": "IDL", "bytes": "43" }, { "name": "Java", "bytes": "120221" }, { "name": "JavaScript", "bytes": "32342" }, { "name": "Jinja", "bytes": "206" }, { "name": "Jupyter Notebook", "bytes": "95991" }, { "name": "Lua", "bytes": "200" }, { "name": "M4", "bytes": "111" }, { "name": "MATLAB", "bytes": "31972" }, { "name": "Makefile", "bytes": "81307" }, { "name": "OpenSCAD", "bytes": "14995" }, { "name": "PHP", "bytes": "94" }, { "name": "Perl", "bytes": "46" }, { "name": "Processing", "bytes": "208" }, { "name": "Prolog", "bytes": "454" }, { "name": "Python", "bytes": "1685966" }, { "name": "R", "bytes": "76" }, { "name": "Raku", "bytes": "43" }, { "name": "Ruby", "bytes": "42" }, { "name": "Scheme", "bytes": "649" }, { "name": "Shell", "bytes": "52865" }, { "name": "Smalltalk", "bytes": "55" }, { "name": "TeX", "bytes": "1189" }, { "name": "Vue", "bytes": "49445" }, { "name": "XSLT", "bytes": "1816" } ], "symlink_target": "" }
module.exports = { // disbable logging for testing logging: false };
{ "content_hash": "dbeec651ec20890db0ece0844e208e6f", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 33, "avg_line_length": 18, "alnum_prop": 0.6944444444444444, "repo_name": "jkennedy3161/Book-Save", "id": "bb62cab67462f922a5faabc2999b29f4fd401ca4", "size": "72", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/config/testing.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10318" }, { "name": "HTML", "bytes": "17925" }, { "name": "JavaScript", "bytes": "25847" } ], "symlink_target": "" }
package com.hazelcast.internal.eviction; import com.hazelcast.spi.eviction.EvictableEntryView; /** * Interface for entries, records or whatever that can be evictable via its accessor (key or ID). * * @param <A> Type of the accessor * @param <E> Type of the {@link Evictable} value */ public interface EvictionCandidate<A, E extends Evictable> extends EvictableEntryView { /** * The accessor (key or ID) of {@link Evictable} entry or record or whatever. * * @return the accessor (key or ID) of {@link Evictable} entry or record or whatever */ A getAccessor(); /** * The value of {@link Evictable} entry or record or whatever. * * @return the value of {@link Evictable} entry or record or whatever */ E getEvictable(); }
{ "content_hash": "ba67e0bbb79bdc9cb5c25537b9280ee3", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 97, "avg_line_length": 26.5, "alnum_prop": 0.6654088050314465, "repo_name": "mesutcelik/hazelcast", "id": "6d6abb3c2f38fffdcd573d5e345ebd4b63d1aeb3", "size": "1420", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hazelcast/src/main/java/com/hazelcast/internal/eviction/EvictionCandidate.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1261" }, { "name": "C", "bytes": "353" }, { "name": "Java", "bytes": "39634706" }, { "name": "Shell", "bytes": "29479" } ], "symlink_target": "" }
.. _all-salt.thorium: =============== thorium modules =============== .. currentmodule:: salt.thorium .. autosummary:: :toctree: :template: autosummary.rst.tmpl calc check file key local reg runner status timer wheel
{ "content_hash": "bb035ad68865d275c2092b24b179af48", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 35, "avg_line_length": 12.227272727272727, "alnum_prop": 0.5278810408921933, "repo_name": "saltstack/salt", "id": "6d1396490d6db678c7ffc17d4aeb7882534fc76d", "size": "269", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/ref/thorium/all/index.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "14911" }, { "name": "C", "bytes": "1571" }, { "name": "Cython", "bytes": "1458" }, { "name": "Dockerfile", "bytes": "184" }, { "name": "Groovy", "bytes": "12318" }, { "name": "HCL", "bytes": "257" }, { "name": "HTML", "bytes": "8031" }, { "name": "Jinja", "bytes": "45598" }, { "name": "Makefile", "bytes": "713" }, { "name": "NSIS", "bytes": "76572" }, { "name": "PowerShell", "bytes": "75891" }, { "name": "Python", "bytes": "41444811" }, { "name": "Rich Text Format", "bytes": "6242" }, { "name": "Roff", "bytes": "191" }, { "name": "Ruby", "bytes": "961" }, { "name": "SaltStack", "bytes": "35856" }, { "name": "Scheme", "bytes": "895" }, { "name": "Scilab", "bytes": "1147" }, { "name": "Shell", "bytes": "524917" } ], "symlink_target": "" }
<?xml version="1.0" standalone="no"?> <!-- Openbizx Cubi Application Platform LICENSE http://code.google.com/p/openbiz-cubi/wiki/CubiLicense Copyright (c) 2005-2011, Openbiz Technology LLC Version $Id: UserWidgetDO.xml 3365 2012-05-31 06:07:55Z rockyswen@gmail.com $ --> <BizDataObj Name="UserWidgetDO" Description="" Class="BizDataObj" DBName="Default" Table="user_widget" SearchRule="" SortRule="[column], [ordering] ASC" OtherSQLRule="" Uniqueness="" Stateless="N" IdGeneration="Identity" CacheLifeTime="0"> <BizFieldList> <BizField Name="Id" Column="id" Type="Number"/> <BizField Name="user_id" Column="user_id" Type="Number"/> <BizField Name="widget" Column="widget" Length="255" Required="Y" Type="Text"/> <BizField Name="view" Column="view" Length="255" Type="Text"/> <BizField Name="column" Column="column"/> <BizField Name="ordering" Column="ordering"/> <BizField Name="config" Column="config" /> <BizField Name="status" Column="status" /> <BizField Name="module" Column="module" Join="join_widget" /> <BizField Name="title" Column="title" Join="join_widget" /> <BizField Name="description" Column="description" Join="join_widget" /> <BizField Name="configable" Column="configable" Join="join_widget"/> <BizField Name="create_by" Column="create_by" Type="Number" ValueOnCreate="{@profile:Id}"/> <BizField Name="create_time" Column="create_time" Type="Datetime" ValueOnCreate="{date('Y-m-d H:i:s')}"/> <BizField Name="update_by" Column="update_by" Type="Number" ValueOnCreate="{@profile:Id}" ValueOnUpdate="{@profile:Id}"/> <BizField Name="update_time" Column="update_time" Type="Datetime" ValueOnCreate="{date('Y-m-d H:i:s')}" ValueOnUpdate="{date('Y-m-d H:i:s')}"/> </BizFieldList> <TableJoins> <Join Name="join_widget" Table="widget" Column="name" ColumnRef="widget" JoinType="INNER JOIN"/> </TableJoins> <ObjReferences> </ObjReferences> </BizDataObj>
{ "content_hash": "c2112bd88d8709104302f980774f5501", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 239, "avg_line_length": 58.55882352941177, "alnum_prop": 0.6760421898543445, "repo_name": "openbizx/cubix", "id": "5020fa33d71abd9f09f060089e16641ffadaf19b", "size": "1991", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/common/do/UserWidgetDO.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "3860" }, { "name": "Batchfile", "bytes": "360" }, { "name": "C++", "bytes": "150671" }, { "name": "CSS", "bytes": "772991" }, { "name": "Groff", "bytes": "4695" }, { "name": "HTML", "bytes": "1217430" }, { "name": "JavaScript", "bytes": "3666710" }, { "name": "NSIS", "bytes": "7607" }, { "name": "PHP", "bytes": "2395473" }, { "name": "Shell", "bytes": "182" }, { "name": "Smarty", "bytes": "266435" }, { "name": "XSLT", "bytes": "11516" } ], "symlink_target": "" }
namespace boost_no_long_long = empty_boost; #endif int main( int, char *[] ) { return boost_no_long_long::test(); }
{ "content_hash": "74a842633750ba949b3ca4806faae5db", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 43, "avg_line_length": 15.125, "alnum_prop": 0.6446280991735537, "repo_name": "ynov/nwg", "id": "2233b376b95ff3a46a7326974f07b7e10d477630", "size": "1059", "binary": false, "copies": "21", "ref": "refs/heads/master", "path": "deps/boost/libs/config/test/no_long_long_pass.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "766" }, { "name": "C++", "bytes": "69711" }, { "name": "Makefile", "bytes": "3144" } ], "symlink_target": "" }
{% extends "base.html" %} {% load url from future %} {% block title %} PCAP Detail {% endblock %} {% block content %} <script> var pcap_md5 = "{{ pcap.md5 }}"; </script> {% if pcap %} <div id="tabnav" class="tabnav" style="font-size:90%;"> <ul style="font-size: 125%;"> <li><a href="#details_section" id="details_button"><span>Details</span></a></li> <li><a href="#analysis_section" id="analysis_button"><span>Analysis ({{ service_results|length }})</span></a></li> {% include 'services_tab_list_widget.html' %} </ul> <div id="details_section"> <span class="horizontal_menu"> <ul class="hmenu"> <li><a href="{% url 'crits.core.views.download_file' pcap.md5 %}?type=pcap">Download PCAP</a></li> {% if admin %} <li class="right"><a href="#" class="deleteClick" data-is-object="true" type="pcap" title="Delete PCAP" action='{% url "crits.pcaps.views.remove_pcap" pcap.md5 %}'>Delete PCAP</a></li> {% endif %} </ul> </span> <div class="content_box content_details"> <h3 class="titleheader"> <span>PCAP Details<span> </h3> <table class="vertical" width="100%"> <thead> </thead> <tbody> <tr> <td class='key'>ID</td> <td>{{ pcap.id }}</td> </tr> <tr> <td class='key'>Filename</td> <td>{{ pcap.filename }}<a href="{% url 'crits.core.views.download_file' pcap.md5 %}?type=pcap"><div class="ui-icon ui-icon-disk download_file"></div></a></td> </tr> <tr> <td class='key'>Created</td> <td>{{ pcap.created }}</td> </tr> <tr> <td class='key'>Length</td> <td>{{ pcap.length }}</td> </tr> <tr> <td class='key'>MD5</td> <td>{{ pcap.md5 }}</td> </tr> <tr> {% with description=pcap.description %} {% include 'description_widget.html' %} {% endwith %} <tr> <td class="key">Status <span style="float: right;" class="object_status_response"></span> </td> <td> <span class="edit" id="object_status" action="{% url 'crits.core.views.update_status' subscription.type subscription.id %}">{{pcap.status}}</span> </td> </tr> {% with sectors=pcap.sectors %} {% include "sector_widget.html" %} {% endwith %} </tr> {% with sources=pcap.source obj_id=pcap.id obj_type=subscription.type %} {% include "sources_listing_widget.html" %} {% endwith %} </tr> <tr> {% with releasability=pcap.releasability %} {% include 'releasability_list_widget.html' %} {% endwith %} </tr> </tbody> </table> </div> <div id="detail_floaters"> {% include 'details_options_widget.html' %} {% with bucket_list=pcap.bucket_list %} {% include 'bucket_list_widget.html' %} {% endwith %} </div> <div> {% with obj=pcap obj_type=subscription.type %} {% include 'tickets_listing_widget.html' %} {% endwith %} </div> <div> {% with hit=pcap col=COL_PCAPS %} {% include "campaigns_display_widget.html" %} {% endwith %} </div> <div> {% with hit=pcap col=COL_PCAPS %} {% include "locations_display_widget.html" %} {% endwith %} </div> <div> {% include 'relationships_listing_widget.html' %} </div> <div> {% include 'objects_listing_widget.html' %} </div> <div> {% include 'screenshot_widget.html' %} </div> <div> {% include "comments_listing_widget.html" %} </div> </div> {% with item=pcap %} {% include "services_analysis_section.html" with crits_type="PCAP" identifier=pcap.md5 %} {% endwith %} {% include 'services_tab_tabs_widget.html' %} </div> {% else %} <h3>PCAP not found. If you just uploaded a PCAP, try refreshing as the system might not have completed processing your upload yet.</h3> {% endif %} {% endblock %} {% block javascript_includes %} <script type="text/javascript" src="{{ STATIC_URL }}js/pcaps.js"></script> {% endblock %}
{ "content_hash": "512f838ea56ebc1b0bdf1582ab3fbb2d", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 196, "avg_line_length": 32.80882352941177, "alnum_prop": 0.5069475571492604, "repo_name": "DukeOfHazard/crits", "id": "636606dcd3a3879b24aef8c8a19bb208b071c194", "size": "4462", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "crits/pcaps/templates/pcap_detail.html", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "8694" }, { "name": "CSS", "bytes": "391710" }, { "name": "HTML", "bytes": "456073" }, { "name": "JavaScript", "bytes": "3486649" }, { "name": "Python", "bytes": "1863760" }, { "name": "SaltStack", "bytes": "2981" }, { "name": "Shell", "bytes": "10871" } ], "symlink_target": "" }
Ext.define('My.Util.SomeClass', { })
{ "content_hash": "c92c971ac68630673ee8d7294acdf92e", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 33, "avg_line_length": 20.5, "alnum_prop": 0.5853658536585366, "repo_name": "OhmzTech/AppInspector", "id": "004f1db5bea866ae348cb268a6d1cefca1c2af0a", "size": "88", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "app/test/siesta-2.0.5-lite/examples/code_coverage/lib/My/Util/SomeClass.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "1636" }, { "name": "CSS", "bytes": "11250286" }, { "name": "JavaScript", "bytes": "97834039" }, { "name": "Ruby", "bytes": "6877" }, { "name": "Shell", "bytes": "26" } ], "symlink_target": "" }
namespace Google.Cloud.AppEngine.V1.Snippets { // [START appengine_v1_generated_Applications_GetApplication_async] using Google.Cloud.AppEngine.V1; using System.Threading.Tasks; public sealed partial class GeneratedApplicationsClientSnippets { /// <summary>Snippet for GetApplicationAsync</summary> /// <remarks> /// This snippet has been automatically generated and should be regarded as a code template only. /// It will require modifications to work: /// - It may require correct/in-range values for request initialization. /// - It may require specifying regional endpoints when creating the service client as shown in /// https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint. /// </remarks> public async Task GetApplicationRequestObjectAsync() { // Create client ApplicationsClient applicationsClient = await ApplicationsClient.CreateAsync(); // Initialize request argument(s) GetApplicationRequest request = new GetApplicationRequest { Name = "", }; // Make the request Application response = await applicationsClient.GetApplicationAsync(request); } } // [END appengine_v1_generated_Applications_GetApplication_async] }
{ "content_hash": "ad239a146ccbc3931ce5862c61cc9d31", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 105, "avg_line_length": 48.07142857142857, "alnum_prop": 0.6842496285289748, "repo_name": "googleapis/google-cloud-dotnet", "id": "b99620963cd41cc1610c32a5d51952d7dde139c5", "size": "1968", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "apis/Google.Cloud.AppEngine.V1/Google.Cloud.AppEngine.V1.GeneratedSnippets/ApplicationsClient.GetApplicationRequestObjectAsyncSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "767" }, { "name": "C#", "bytes": "319820004" }, { "name": "Dockerfile", "bytes": "3415" }, { "name": "PowerShell", "bytes": "3303" }, { "name": "Python", "bytes": "2744" }, { "name": "Shell", "bytes": "65881" } ], "symlink_target": "" }
/******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, callbacks = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) /******/ callbacks.push.apply(callbacks, installedChunks[chunkId]); /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules); /******/ while(callbacks.length) /******/ callbacks.shift().call(null, __webpack_require__); /******/ }; /******/ // The module cache /******/ var installedModules = {}; /******/ // object to store loaded and loading chunks /******/ // "0" means "already loaded" /******/ // Array means "loading", array contains callbacks /******/ var installedChunks = { /******/ 0:0 /******/ }; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId, callback) { /******/ // "0" is the signal for "already loaded" /******/ if(installedChunks[chunkId] === 0) /******/ return callback.call(null, __webpack_require__); /******/ // an array means "currently loading". /******/ if(installedChunks[chunkId] !== undefined) { /******/ installedChunks[chunkId].push(callback); /******/ } else { /******/ // start chunk loading /******/ installedChunks[chunkId] = [callback]; /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.src = __webpack_require__.p + "" + chunkId + ".main.js"; /******/ head.appendChild(script); /******/ } /******/ }; /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/dist/"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__.e/* require */(1, function(__webpack_require__) { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [__webpack_require__(1), __webpack_require__(38), __webpack_require__(168), __webpack_require__(229)]; (function (React, ReactDOM, { Router, browserHistory }, Routes) { ReactDOM.render(React.createElement(Router, { history: browserHistory, routes: Routes }), document.getElementById('pdp-app')); }.apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__));}); /***/ } /******/ ]);
{ "content_hash": "eae1f5712ef1a405e3250643907a9117", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 275, "avg_line_length": 39.067961165048544, "alnum_prop": 0.5524353876739563, "repo_name": "cod3rkane/project", "id": "69dffa06817f1a4b6ed2160e9f027de84ce1843c", "size": "4024", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/dist/main.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "711" }, { "name": "CSS", "bytes": "728953" }, { "name": "HTML", "bytes": "6985" }, { "name": "JavaScript", "bytes": "1687489" }, { "name": "PHP", "bytes": "12664" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <!-- Appenders --> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p: %c - %m%n" /> </layout> </appender> <!-- Application Loggers --> <logger name="com.cayan.bobstoystore"> <level value="info" /> </logger> <!-- 3rdparty Loggers --> <logger name="org.springframework.core"> <level value="info" /> </logger> <logger name="org.springframework.beans"> <level value="info" /> </logger> <logger name="org.springframework.context"> <level value="info" /> </logger> <logger name="org.springframework.web"> <level value="info" /> </logger> <!-- Root Logger --> <root> <priority value="warn" /> <appender-ref ref="console" /> </root> </log4j:configuration>
{ "content_hash": "2d64f6c74a3f8038fc715037c903ef59", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 80, "avg_line_length": 25.4390243902439, "alnum_prop": 0.6529242569511026, "repo_name": "Cayan-LLC/developer-docs", "id": "a09fffb2d43b0a85017ba504a66b0c49d380df6f", "size": "1043", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/ecommerce/java/src/main/resources/log4j.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
FROM balenalib/beaglebone-black-debian:bullseye-run # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ netbase \ && rm -rf /var/lib/apt/lists/* # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.5.10 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.0.1 ENV SETUPTOOLS_VERSION 56.0.0 RUN set -x \ && buildDeps=' \ curl \ ' \ && 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/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \ && echo "4abc87b995e08c143de14f26d8ab6ffd9017aad400bf91bc36a802efda7fe27a Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH 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@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.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 v7 \nOS: Debian Bullseye \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.5.10, Pip v21.0.1, Setuptools v56.0.0 \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": "9ee02cd993a4e10e9c195a6515e38d8c", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 711, "avg_line_length": 52.35897435897436, "alnum_prop": 0.7083741429970617, "repo_name": "nghiant2710/base-images", "id": "08669e03bb903e45cc5781d63dacc84d3591b3ed", "size": "4105", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/python/beaglebone-black/debian/bullseye/3.5.10/run/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
package org.apache.kylin.source.hive; import org.apache.kylin.shaded.com.google.common.collect.ImmutableList; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.job.common.PatternedLogger; import org.apache.kylin.job.constant.ExecutableConstants; import org.apache.kylin.job.exception.ExecuteException; import org.apache.kylin.job.execution.AbstractExecutable; import org.apache.kylin.job.execution.ExecutableContext; import org.apache.kylin.job.execution.ExecuteResult; public class RedistributeFlatHiveTableByLivyStep extends AbstractExecutable { private final PatternedLogger stepLogger = new PatternedLogger(logger); private long computeRowCount(String database, String table) throws Exception { IHiveClient hiveClient = HiveClientFactory.getHiveClient(); return hiveClient.getHiveTableRows(database, table); } private long getDataSize(String database, String table) throws Exception { IHiveClient hiveClient = HiveClientFactory.getHiveClient(); long size = hiveClient.getHiveTableMeta(database, table).fileSize; return size; } private void redistributeTable(KylinConfig config, int numReducers) throws Exception { StringBuffer statement = new StringBuffer(); statement.append(getInitStatement()); statement.append("set mapreduce.job.reduces=" + numReducers + ";\n"); statement.append("set hive.merge.mapredfiles=false;\n"); statement.append(getRedistributeDataStatement()); stepLogger.log("Redistribute table, cmd: "); stepLogger.log(statement.toString()); MRHiveDictUtil.runLivySqlJob(stepLogger, config, ImmutableList.of(statement.toString()), getManager(), getId()); } @Override protected ExecuteResult doWork(ExecutableContext context) throws ExecuteException { KylinConfig config = getCubeSpecificConfig(); String intermediateTable = getIntermediateTable(); String database, tableName; if (intermediateTable.indexOf(".") > 0) { database = intermediateTable.substring(0, intermediateTable.indexOf(".")); tableName = intermediateTable.substring(intermediateTable.indexOf(".") + 1); } else { database = config.getHiveDatabaseForIntermediateTable(); tableName = intermediateTable; } try { long rowCount = computeRowCount(database, tableName); logger.debug("Row count of table '" + intermediateTable + "' is " + rowCount); if (rowCount == 0) { if (!config.isEmptySegmentAllowed()) { stepLogger.log("Detect upstream hive table is empty, " + "fail the job because \"kylin.job.allow-empty-segment\" = \"false\""); return new ExecuteResult(ExecuteResult.State.ERROR, stepLogger.getBufferedLog()); } else { return new ExecuteResult(ExecuteResult.State.SUCCEED, "Row count is 0, no need to redistribute"); } } int mapperInputRows = config.getHadoopJobMapperInputRows(); int numReducers = Math.round(rowCount / ((float) mapperInputRows)); numReducers = Math.max(1, numReducers); numReducers = Math.min(numReducers, config.getHadoopJobMaxReducerNumber()); stepLogger.log("total input rows = " + rowCount); stepLogger.log("expected input rows per mapper = " + mapperInputRows); stepLogger.log("num reducers for RedistributeFlatHiveTableStep = " + numReducers); redistributeTable(config, numReducers); long dataSize = getDataSize(database, tableName); getManager().addJobInfo(getId(), ExecutableConstants.HDFS_BYTES_WRITTEN, "" + dataSize); return new ExecuteResult(ExecuteResult.State.SUCCEED, stepLogger.getBufferedLog()); } catch (Exception e) { logger.error("job:" + getId() + " execute finished with exception", e); return new ExecuteResult(ExecuteResult.State.ERROR, stepLogger.getBufferedLog(), e); } } public void setInitStatement(String sql) { setParam("HiveInit", sql); } public String getInitStatement() { return getParam("HiveInit"); } public void setRedistributeDataStatement(String sql) { setParam("HiveRedistributeData", sql); } public String getRedistributeDataStatement() { return getParam("HiveRedistributeData"); } public String getIntermediateTable() { return getParam("intermediateTable"); } public void setIntermediateTable(String intermediateTable) { setParam("intermediateTable", intermediateTable); } }
{ "content_hash": "f6f00a268ef636c45999bd7d14388772", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 120, "avg_line_length": 42.517857142857146, "alnum_prop": 0.6761864762704746, "repo_name": "apache/kylin", "id": "b6730923afa5c9ab804c067be2d424594807dd93", "size": "5567", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "source-hive/src/main/java/org/apache/kylin/source/hive/RedistributeFlatHiveTableByLivyStep.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "32751" }, { "name": "C++", "bytes": "594708" }, { "name": "CSS", "bytes": "98255" }, { "name": "Dockerfile", "bytes": "28814" }, { "name": "FreeMarker", "bytes": "49504" }, { "name": "HTML", "bytes": "511983" }, { "name": "Inno Setup", "bytes": "1219521" }, { "name": "Java", "bytes": "7840516" }, { "name": "JavaScript", "bytes": "1838206" }, { "name": "Less", "bytes": "51933" }, { "name": "Python", "bytes": "113668" }, { "name": "Scala", "bytes": "704894" }, { "name": "Shell", "bytes": "215104" } ], "symlink_target": "" }
/** * \file deq_rec.h * * Qpid asynchronous store plugin library * * This file contains the code for the mrg::journal::deq_rec (journal dequeue * record) class. See class documentation for details. * * \author Kim van der Riet */ #ifndef QPID_LEGACYSTORE_JRNL_DEQ_REQ_H #define QPID_LEGACYSTORE_JRNL_DEQ_REQ_H namespace mrg { namespace journal { class deq_rec; } } #include <cstddef> #include "qpid/legacystore/jrnl/deq_hdr.h" #include "qpid/legacystore/jrnl/jrec.h" namespace mrg { namespace journal { /** * \class deq_rec * \brief Class to handle a single journal dequeue record. */ class deq_rec : public jrec { private: deq_hdr _deq_hdr; ///< Dequeue header const void* _xidp; ///< xid pointer for encoding (writing to disk) void* _buff; ///< Pointer to buffer to receive data read from disk rec_tail _deq_tail; ///< Record tail, only encoded if XID is present public: // constructor used for read operations and xid will have memory allocated deq_rec(); // constructor used for write operations, where xid already exists deq_rec(const u_int64_t rid, const u_int64_t drid, const void* const xidp, const std::size_t xidlen, const bool owi, const bool txn_coml_commit); virtual ~deq_rec(); // Prepare instance for use in reading data from journal void reset(); // Prepare instance for use in writing data to journal void reset(const u_int64_t rid, const u_int64_t drid, const void* const xidp, const std::size_t xidlen, const bool owi, const bool txn_coml_commit); u_int32_t encode(void* wptr, u_int32_t rec_offs_dblks, u_int32_t max_size_dblks); u_int32_t decode(rec_hdr& h, void* rptr, u_int32_t rec_offs_dblks, u_int32_t max_size_dblks); // Decode used for recover bool rcv_decode(rec_hdr h, std::ifstream* ifsp, std::size_t& rec_offs); inline bool is_txn_coml_commit() const { return _deq_hdr.is_txn_coml_commit(); } inline u_int64_t rid() const { return _deq_hdr._rid; } inline u_int64_t deq_rid() const { return _deq_hdr._deq_rid; } std::size_t get_xid(void** const xidpp); std::string& str(std::string& str) const; inline std::size_t data_size() const { return 0; } // This record never carries data std::size_t xid_size() const; std::size_t rec_size() const; private: virtual void chk_hdr() const; virtual void chk_hdr(u_int64_t rid) const; virtual void chk_tail() const; virtual void clean(); }; // class deq_rec } // namespace journal } // namespace mrg #endif // ifndef QPID_LEGACYSTORE_JRNL_DEQ_REQ_H
{ "content_hash": "f9434159cd769b232691b8ed25f2480a", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 92, "avg_line_length": 33.345238095238095, "alnum_prop": 0.623348803998572, "repo_name": "gregerts/debian-qpid-cpp", "id": "d870b658da6d2984e5d18b7148981cd2467cb933", "size": "3614", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/qpid/legacystore/jrnl/deq_rec.h", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
module Twilio module TaskRouter class Capability TASK_ROUTER_BASE_URL = 'https://taskrouter.twilio.com' TASK_ROUTER_VERSION = 'v1' TASK_ROUTER_WEBSOCKET_BASE_URL = 'https://event-bridge.twilio.com/v1/wschannels' REQUIRED = {required: true} OPTIONAL = {required: false} def initialize(account_sid, auth_token, workspace_sid, worker_sid) @account_sid = account_sid @auth_token = auth_token @workspace_sid = workspace_sid @worker_sid = worker_sid @policies = [] allow_websocket_requests allow_activity_list_fetch end def workspace_url "#{TASK_ROUTER_BASE_URL}/#{TASK_ROUTER_VERSION}/Workspaces/#{@workspace_sid}" end def worker_url "#{workspace_url}/Workers/#{@worker_sid}" end def allow_worker_activity_updates add_policy(worker_url, "POST", nil, {ActivitySid: REQUIRED}) end def allow_worker_fetch_attributes add_policy(worker_url, "GET") end def allow_task_reservation_updates task_url = "#{workspace_url}/Tasks/**" add_policy(task_url, "POST", nil, {ReservationStatus: REQUIRED}) end def add_policy(url, method, query_filters = nil, post_filters = nil, allowed = true) policy = { url: url, method: method, query_filter: query_filters || {}, post_filter: post_filters || {}, allow: allowed } @policies.push(policy) end def generate_token(ttl = 3600) payload = { iss: @account_sid, exp: (Time.now.to_i + ttl), version: @version, friendly_name: @worker_sid, policies: @policies, account_sid: @account_sid, worker_sid: @worker_sid, channel: @worker_sid, workspace_sid: @workspace_sid } JWT.encode payload, @auth_token end protected def allow_websocket_requests worker_url = "#{TASK_ROUTER_WEBSOCKET_BASE_URL}/#{@account_sid}/#{@worker_sid}" ['GET', 'POST'].each do |meth| add_policy(worker_url, meth) end end def allow_activity_list_fetch url = "#{workspace_url}/Activities" add_policy(url, 'GET') end end end end
{ "content_hash": "a6f5ff720c5de232ab7b173b5885bd91", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 90, "avg_line_length": 26.862068965517242, "alnum_prop": 0.5708172871202396, "repo_name": "sai43/twilio-ruby", "id": "2f11ab88cb515dbdc8882f211d74858921f8ab89", "size": "2337", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "lib/twilio-ruby/task_router/capability.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "306" }, { "name": "Ruby", "bytes": "127120" } ], "symlink_target": "" }
type browserType = typeof import("./resolve-targets-browser"); type nodeType = typeof import("./resolve-targets"); // Kind of gross, but essentially asserting that the exports of this module are the same as the // exports of index-browser, since this file may be replaced at bundle time with index-browser. ({} as any as browserType as nodeType); import type { ValidatedOptions } from "./validation/options"; import path from "path"; import getTargets from "@babel/helper-compilation-targets"; import type { Targets } from "@babel/helper-compilation-targets"; export function resolveBrowserslistConfigFile( browserslistConfigFile: string, configFileDir: string, ): string | undefined { return path.resolve(configFileDir, browserslistConfigFile); } export function resolveTargets( options: ValidatedOptions, root: string, ): Targets { // todo(flow->ts) remove any and refactor to not assign different types into same variable let targets: any = options.targets; if (typeof targets === "string" || Array.isArray(targets)) { targets = { browsers: targets }; } if (targets && targets.esmodules) { targets = { ...targets, esmodules: "intersect" }; } const { browserslistConfigFile } = options; let configFile; let ignoreBrowserslistConfig = false; if (typeof browserslistConfigFile === "string") { configFile = browserslistConfigFile; } else { ignoreBrowserslistConfig = browserslistConfigFile === false; } return getTargets(targets, { ignoreBrowserslistConfig, configFile, configPath: root, browserslistEnv: options.browserslistEnv, }); }
{ "content_hash": "59e5896a2f8b6e5e9bdcce728f5f20b9", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 95, "avg_line_length": 32.89795918367347, "alnum_prop": 0.7320099255583127, "repo_name": "ChromeDevTools/devtools-frontend", "id": "90a443ed3387fa6fa3e420bee7c6d427d5408ebd", "size": "1612", "binary": false, "copies": "9", "ref": "refs/heads/main", "path": "node_modules/@babel/core/src/config/resolve-targets.ts", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "615241" }, { "name": "Dart", "bytes": "205" }, { "name": "HTML", "bytes": "317251" }, { "name": "JavaScript", "bytes": "1401177" }, { "name": "LLVM", "bytes": "1918" }, { "name": "Makefile", "bytes": "687" }, { "name": "Python", "bytes": "133111" }, { "name": "Shell", "bytes": "1122" }, { "name": "TypeScript", "bytes": "15230731" }, { "name": "WebAssembly", "bytes": "921" } ], "symlink_target": "" }
#ifndef __STEPMOTOR_H #define __STEPMOTOR_H #include "stm32f10x.h" void MOTOR_GPIO_Config(void); void PinSet(unsigned char xx); void Pin1Set(unsigned char xx); void Pin2Set(unsigned char xx); void Pin3Set(unsigned char xx); void Pin4Set(unsigned char xx); void PinRST(void); void PinRSTL(void); void PinRSTR(void); void OPoint(); void EyePoidt(); void LastPoint(); void TEST_M(); void STEPMOTOR_Init(void); void STEPMOTOR_Test(void); void RunN(); void GetConfigL(); void GetConfigR(); void CalConfigL(); void CalConfigR(); uint8_t getN(uint8_t x); #endif /* __STEPMOTOR_H */
{ "content_hash": "b7e5ba0c4ec1f38077bf96cc677145dd", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 31, "avg_line_length": 19.3, "alnum_prop": 0.7288428324697754, "repo_name": "Google1234/ICT_LaboratoryProject_STM32", "id": "4c347f1293f8cd05787e816e017d476a7365bfca", "size": "579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "User/stepmotor/STEPMOTOR.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "125699" }, { "name": "Batchfile", "bytes": "372" }, { "name": "C", "bytes": "5225910" }, { "name": "C++", "bytes": "44673" }, { "name": "DTrace", "bytes": "222" }, { "name": "HTML", "bytes": "82364" }, { "name": "Makefile", "bytes": "125849" }, { "name": "Objective-C", "bytes": "14657" } ], "symlink_target": "" }
package mongodb import ( "log" "net/url" "time" "github.com/influxdata/telegraf" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type Server struct { Url *url.URL Session *mgo.Session lastResult *MongoStatus } func (s *Server) getDefaultTags() map[string]string { tags := make(map[string]string) tags["hostname"] = s.Url.Host return tags } func (s *Server) gatherData(acc telegraf.Accumulator) error { s.Session.SetMode(mgo.Eventual, true) s.Session.SetSocketTimeout(0) result_server := &ServerStatus{} err := s.Session.DB("admin").Run(bson.D{{"serverStatus", 1}, {"recordStats", 0}}, result_server) if err != nil { return err } result_repl := &ReplSetStatus{} err = s.Session.DB("admin").Run(bson.D{{"replSetGetStatus", 1}}, result_repl) if err != nil { log.Println("Not gathering replica set status, member not in replica set (" + err.Error() + ")") } jumbo_chunks, _ := s.Session.DB("config").C("chunks").Find(bson.M{"jumbo": true}).Count() result_cluster := &ClusterStatus{ JumboChunksCount: int64(jumbo_chunks), } result := &MongoStatus{ ServerStatus: result_server, ReplSetStatus: result_repl, ClusterStatus: result_cluster, } defer func() { s.lastResult = result }() result.SampleTime = time.Now() if s.lastResult != nil && result != nil { duration := result.SampleTime.Sub(s.lastResult.SampleTime) durationInSeconds := int64(duration.Seconds()) if durationInSeconds == 0 { durationInSeconds = 1 } data := NewMongodbData( NewStatLine(*s.lastResult, *result, s.Url.Host, true, durationInSeconds), s.getDefaultTags(), ) data.AddDefaultStats() data.flush(acc) } return nil }
{ "content_hash": "ece8b98ecd6ab182a3c889bff4364104", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 98, "avg_line_length": 23.814285714285713, "alnum_prop": 0.6802639472105579, "repo_name": "titilambert/telegraf", "id": "e4213bbafc2ff41c4747cca7ca5c30e75f735007", "size": "1667", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "plugins/inputs/mongodb/mongodb_server.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "1885495" }, { "name": "Makefile", "bytes": "3059" }, { "name": "Python", "bytes": "38977" }, { "name": "Ruby", "bytes": "1437" }, { "name": "Shell", "bytes": "11511" } ], "symlink_target": "" }
package com.abdroid.wps2; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.widget.Toast; /** * Created by bhuvanmalik on 29/08/15. */ public class GPSTracker extends Service implements LocationListener { private final Context context; public GPSTracker(Context context) { this.context = context; getLocation(); } boolean isGPSEnabled=false; boolean isNetworkEnabled=false; boolean canGetLocation=false; Location location; double latitude,longitude; private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10; private static final long MIN_TIME_BETWEEN_UPDATES=1000*60*1; protected LocationManager locationmanager; public Location getLocation(){ try { locationmanager = (LocationManager) context.getSystemService(LOCATION_SERVICE); isGPSEnabled=locationmanager.isProviderEnabled(LocationManager.GPS_PROVIDER); isNetworkEnabled=locationmanager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if(!isGPSEnabled && !isNetworkEnabled){ } else{ this.canGetLocation=true; if(isNetworkEnabled) { locationmanager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BETWEEN_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); if (locationmanager != null) { location = locationmanager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLatitude(); } } } } } catch (Exception e){ e.printStackTrace(); } return location; } public void stopUsingGPS(){ if(locationmanager!=null){ locationmanager.removeUpdates(GPSTracker.this); } } public double getLatitude(){ if(location!=null){ latitude=location.getLatitude(); } return latitude; } public double getLongitude(){ if(location!=null){ longitude=location.getLongitude(); } return longitude; } public boolean canGetLocation(){ return this.canGetLocation; } @Override public void onLocationChanged(Location location) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public IBinder onBind(Intent intent) { return null; } }
{ "content_hash": "cf50128124d6d4bc5ded71bd724c1275", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 158, "avg_line_length": 26.06779661016949, "alnum_prop": 0.6280884265279584, "repo_name": "rammohanmishra/advgps", "id": "e1804751a93e5f67fbbf54e94d76e41bc00a6bfc", "size": "3076", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/abdroid/wps2/GPSTracker.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "22684" } ], "symlink_target": "" }
A semi-interactive art exhibit by Parallelograms 1. Install Meteor (https://www.meteor.com/install) 2. Clone repo 3. In root directory of repo ```$ meteor``` 4. Navigate to localhost:3000/{{artist-last-name}}/interface and localhost:3000/{{artist-last-name}}/display
{ "content_hash": "6da0c8ab5fcac8efdd14b11dd837c6f0", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 108, "avg_line_length": 44.666666666666664, "alnum_prop": 0.753731343283582, "repo_name": "zacparker/parallelograms", "id": "2c6f329d6c6fdec3b1559c615c463fe474f63971", "size": "281", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7749" }, { "name": "HTML", "bytes": "69456" }, { "name": "JavaScript", "bytes": "40317" } ], "symlink_target": "" }