text
stringlengths
2
1.04M
meta
dict
.class public Landroid/net/wifi/WifiScanner$ParcelableScanData; .super Ljava/lang/Object; .source "WifiScanner.java" # interfaces .implements Landroid/os/Parcelable; # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/net/wifi/WifiScanner; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x9 name = "ParcelableScanData" .end annotation .annotation system Ldalvik/annotation/MemberClasses; value = { Landroid/net/wifi/WifiScanner$ParcelableScanData$1; } .end annotation # static fields .field public static final CREATOR:Landroid/os/Parcelable$Creator; .annotation system Ldalvik/annotation/Signature; value = { "Landroid/os/Parcelable$Creator", "<", "Landroid/net/wifi/WifiScanner$ParcelableScanData;", ">;" } .end annotation .end field # instance fields .field public mResults:[Landroid/net/wifi/WifiScanner$ScanData; # direct methods .method static constructor <clinit>()V .locals 1 new-instance v0, Landroid/net/wifi/WifiScanner$ParcelableScanData$1; invoke-direct {v0}, Landroid/net/wifi/WifiScanner$ParcelableScanData$1;-><init>()V sput-object v0, Landroid/net/wifi/WifiScanner$ParcelableScanData;->CREATOR:Landroid/os/Parcelable$Creator; return-void .end method .method public constructor <init>([Landroid/net/wifi/WifiScanner$ScanData;)V .locals 0 invoke-direct {p0}, Ljava/lang/Object;-><init>()V iput-object p1, p0, Landroid/net/wifi/WifiScanner$ParcelableScanData;->mResults:[Landroid/net/wifi/WifiScanner$ScanData; return-void .end method # virtual methods .method public describeContents()I .locals 1 const/4 v0, 0x0 return v0 .end method .method public getResults()[Landroid/net/wifi/WifiScanner$ScanData; .locals 1 iget-object v0, p0, Landroid/net/wifi/WifiScanner$ParcelableScanData;->mResults:[Landroid/net/wifi/WifiScanner$ScanData; return-object v0 .end method .method public writeToParcel(Landroid/os/Parcel;I)V .locals 3 iget-object v2, p0, Landroid/net/wifi/WifiScanner$ParcelableScanData;->mResults:[Landroid/net/wifi/WifiScanner$ScanData; if-eqz v2, :cond_0 iget-object v2, p0, Landroid/net/wifi/WifiScanner$ParcelableScanData;->mResults:[Landroid/net/wifi/WifiScanner$ScanData; array-length v2, v2 invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V const/4 v0, 0x0 :goto_0 iget-object v2, p0, Landroid/net/wifi/WifiScanner$ParcelableScanData;->mResults:[Landroid/net/wifi/WifiScanner$ScanData; array-length v2, v2 if-ge v0, v2, :cond_1 iget-object v2, p0, Landroid/net/wifi/WifiScanner$ParcelableScanData;->mResults:[Landroid/net/wifi/WifiScanner$ScanData; aget-object v1, v2, v0 invoke-virtual {v1, p1, p2}, Landroid/net/wifi/WifiScanner$ScanData;->writeToParcel(Landroid/os/Parcel;I)V add-int/lit8 v0, v0, 0x1 goto :goto_0 :cond_0 const/4 v2, 0x0 invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V :cond_1 return-void .end method
{ "content_hash": "143830804040288e175959ffbc985a2d", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 124, "avg_line_length": 25.40650406504065, "alnum_prop": 0.72096, "repo_name": "BatMan-Rom/ModdedFiles", "id": "bf02aa9139acb36170e9dacd45abf9799ca3cef4", "size": "3125", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "framework.jar.out/smali/android/net/wifi/WifiScanner$ParcelableScanData.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "15069" }, { "name": "HTML", "bytes": "139176" }, { "name": "Smali", "bytes": "541934400" } ], "symlink_target": "" }
@implementation UIView (myExtension) -(void)setSize:(CGSize)size { CGRect frame = self.frame; frame.size = size; self.frame = frame; } -(CGSize)size { return self.frame.size; } -(void)setX:(CGFloat)X { CGRect frame = self.frame; frame.origin.x = X; self.frame = frame; } -(CGFloat)X { return self.frame.origin.x; } -(void)setY:(CGFloat)Y { CGRect frame = self.frame; frame.origin.y = Y; self.frame = frame; } -(CGFloat)Y { return self.frame.origin.y; } -(void)setWidth:(CGFloat)width { CGRect frame = self.frame; frame.size.width = width; self.frame = frame; } -(CGFloat)width { return self.frame.size.width; } -(void)setHeight:(CGFloat)height { CGRect frame = self.frame; frame.size.height = height; self.frame = frame; } -(CGFloat)height { return self.frame.size.height; } -(void)setOrigin:(CGPoint)origin { CGRect frame = self.frame; frame.origin = origin; self.frame = frame; } -(CGPoint)origin { return self.frame.origin; } -(void)setCenterX:(CGFloat)centerX { self.center = CGPointMake(centerX, self.center.y); } -(CGFloat)centerX { return self.center.x; } -(void)setCenterY:(CGFloat)centerY { self.center = CGPointMake(self.center.x, centerY); } -(CGFloat)centerY { return self.center.y; } -(BOOL)isShowingOnKeyWindow { UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow; CGRect newRect = [keyWindow convertRect:self.frame fromView:self.superview]; //等价于 CGRect sameRect = [self convertRect:self.frame toView:keyWindow]; CGRect keyRect = keyWindow.bounds; BOOL intersects = CGRectIntersectsRect(keyRect, newRect); return !self.isHidden && self.alpha > 0.01 && self.window == keyWindow && intersects; } @end
{ "content_hash": "3455d5580eb8661842f1c0c7218bac71", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 89, "avg_line_length": 13.803030303030303, "alnum_prop": 0.6531284302963776, "repo_name": "lizihe/creatGitHub", "id": "1d4faa6c6fce2ade91df85e36085c13752d13b1b", "size": "1995", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GitDmoe/GitDmoe/Common/Category/UIView+myExtension.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "864632" }, { "name": "Ruby", "bytes": "175" }, { "name": "Shell", "bytes": "8808" } ], "symlink_target": "" }
class User{ private name: string; constructor(fullname:string) { this.name = fullname; } Hi(msg: string): string { return msg + " " + this.name; } } var user = new User("kataras"); var hi = user.Hi("Hello"); window.alert(hi);
{ "content_hash": "6f78ab849555caa5f214e495940dcd73", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 33, "avg_line_length": 15.75, "alnum_prop": 0.5992063492063492, "repo_name": "iris-framework/iris", "id": "cc750583a20e25927dd98e06a3df8ace7aa03be5", "size": "252", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "_examples/advanced/cloud-editor/www/scripts/app.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "74" }, { "name": "Go", "bytes": "726895" }, { "name": "HTML", "bytes": "9558" }, { "name": "JavaScript", "bytes": "3909" }, { "name": "TypeScript", "bytes": "9264" } ], "symlink_target": "" }
package tpl.nutz.web; import java.io.IOException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public interface HtmlRunnable { public abstract String run(String path, Map<String, Object> context, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException; }
{ "content_hash": "7ecc5edc1cb72be2a14bcef6298324fb", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 69, "avg_line_length": 29.357142857142858, "alnum_prop": 0.8248175182481752, "repo_name": "weiht/nutz-tpl", "id": "0b1dfb2a4953a097065c190cfac64532e0338b4c", "size": "411", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nutz-tpl-web/src/main/java/tpl/nutz/web/HtmlRunnable.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "73414" }, { "name": "Groovy", "bytes": "508" }, { "name": "HTML", "bytes": "48086" }, { "name": "Java", "bytes": "185970" }, { "name": "JavaScript", "bytes": "365767" }, { "name": "Smarty", "bytes": "232" } ], "symlink_target": "" }
import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) import unittest from systemverilog2verilog.src.sv2v import * import filecmp class TestSequenceFunctions(unittest.TestCase): def setUp(self): pass def test_normal(self): module_data_base().flash() module_dict, _, _ = convert2sv(["norm_test.sv",], True) self.assertTrue(filecmp.cmp('norm_test_conv.v', 'norm_test_conv_expect.v')) self.assertEqual(sorted(module_dict['TOP'].input, key = lambda x:x), ['ADDR', 'CLK', 'READ', 'RST', 'WRITE', 'WRITE_DATA']) self.assertEqual(sorted(module_dict['TOP'].output, key = lambda x:x), ['READ_DATA']) self.assertEqual(sorted(module_dict['SUB2'].input, key = lambda x:x), ['CLK', 'IN', 'RST']) self.assertEqual(sorted(module_dict['SUB2'].output, key = lambda x:x), ['OUT']) def test_submodule(self): module_data_base().flash() convert2sv(["submodule.sv",], True) self.assertTrue(filecmp.cmp('submodule_conv.v', 'submodule_conv_expect.v')) def test_submodule2(self): module_data_base().flash() convert2sv(["submodule2.sv",], True) self.assertTrue(filecmp.cmp('submodule2_conv.v', 'submodule2_conv_expect.v')) def test_submodule3(self): module_data_base().flash() module_dict, reg_dict, wire_dict = convert2sv(["name_and_order_assign.sv",], True) self.assertTrue(filecmp.cmp('name_and_order_assign_conv.v', 'name_and_order_assign_conv_expect.v')) self.assertEqual(reg_dict['SUB'], ['reg1']) self.assertEqual(reg_dict['SUB2'], ['reg1']) self.assertEqual(set(reg_dict['TOP']), set(['reg1', 'reg2', 'reg3'])) self.assertEqual(wire_dict['SUB'], ['IN']) self.assertEqual(wire_dict['SUB2'], ['IN']) self.assertEqual(set(wire_dict['TOP']), set(['in1', 'OUT', 'OUTOUT', 'IN', 'IN2'])) def test_eda(self): module_data_base().flash() module_data_base().flash() convert2sv(["dot_asterisk.sv",], True) self.assertTrue(filecmp.cmp('dot_asterisk_eda.v', 'dot_asterisk_eda_expect.v')) def tearDown(self): clean_directory() ## elif '_conv.v' in file: ## os.remove(u'./' + file) if __name__ == '__main__': unittest.main()
{ "content_hash": "1b74f7997b136b37b11a11050f0e7d65", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 107, "avg_line_length": 38.375, "alnum_prop": 0.5846905537459284, "repo_name": "fukatani/systemverilog2verilog", "id": "e30522212ee80967cbfe17e92021b3219f12c053", "size": "2749", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test_conv.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "27974" }, { "name": "SystemVerilog", "bytes": "3289" }, { "name": "Verilog", "bytes": "4137" } ], "symlink_target": "" }
package com.amd.aparapi.sample.mandel; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.util.List; import javax.swing.JComponent; import javax.swing.JFrame; import com.amd.aparapi.Kernel; import com.amd.aparapi.ProfileInfo; import com.amd.aparapi.Range; /** * An example Aparapi application which displays a view of the Mandelbrot set and lets the user zoom in to a particular point. * * When the user clicks on the view, this example application will zoom in to the clicked point and zoom out there after. * On GPU, additional computing units will offer a better viewing experience. On the other hand on CPU, this example * application might suffer with sub-optimal frame refresh rate as compared to GPU. * * @author gfrost * */ public class Main2D{ /** * An Aparapi Kernel implementation for creating a scaled view of the mandelbrot set. * * @author gfrost * */ public static class MandelKernel extends Kernel{ /** RGB buffer used to store the Mandelbrot image. This buffer holds (width * height) RGB values. */ final private int rgb[]; /** Maximum iterations we will check for. */ final private int maxIterations = 64; /** Palette maps iteration values to RGB values. */ @Constant final private int pallette[] = new int[maxIterations + 1]; /** Mutable values of scale, offsetx and offsety so that we can modify the zoom level and position of a view. */ private float scale = .0f; private float offsetx = .0f; private float offsety = .0f; /** * Initialize the Kernel. * * @param _width Mandelbrot image width * @param _height Mandelbrot image height * @param _rgb Mandelbrot image RGB buffer * @param _pallette Mandelbrot image palette */ public MandelKernel(int[] _rgb) { rgb = _rgb; //Initialize palette for (int i = 0; i < maxIterations; i++) { float h = i / (float) maxIterations; float b = 1.0f - h * h; pallette[i] = Color.HSBtoRGB(h, 1f, b); } } @Override public void run() { /** Determine which RGB value we are going to process (0..RGB.length). */ int gid = getGlobalId(1) * getGlobalSize(0) + getGlobalId(0); /** Translate the gid into an x an y value. */ float x = (((getGlobalId(0) * scale) - ((scale / 2) * getGlobalSize(0))) / getGlobalSize(0)) + offsetx; float y = (((getGlobalId(1) * scale) - ((scale / 2) * getGlobalSize(1))) / getGlobalSize(1)) + offsety; int count = 0; float zx = x; float zy = y; float new_zx = 0f; // Iterate until the algorithm converges or until maxIterations are reached. while (count < maxIterations && zx * zx + zy * zy < 8) { new_zx = zx * zx - zy * zy + x; zy = 2 * zx * zy + y; zx = new_zx; count++; } // Pull the value out of the palette for this iteration count. rgb[gid] = pallette[count]; } public void setScaleAndOffset(float _scale, float _offsetx, float _offsety) { offsetx = _offsetx; offsety = _offsety; scale = _scale; } } /** User selected zoom-in point on the Mandelbrot view. */ public static volatile Point to = null; @SuppressWarnings("serial") public static void main(String[] _args) { JFrame frame = new JFrame("MandelBrot"); /** Mandelbrot image height. */ final Range range = Range.create2D(768, 768); System.out.println("range= " + range); /** Image for Mandelbrot view. */ final BufferedImage image = new BufferedImage(range.getGlobalSize(0), range.getGlobalSize(1), BufferedImage.TYPE_INT_RGB); final BufferedImage offscreen = new BufferedImage(range.getGlobalSize(0), range.getGlobalSize(1), BufferedImage.TYPE_INT_RGB); // Draw Mandelbrot image JComponent viewer = new JComponent(){ @Override public void paintComponent(Graphics g) { g.drawImage(image, 0, 0, range.getGlobalSize(0), range.getGlobalSize(1), this); } }; // Set the size of JComponent which displays Mandelbrot image viewer.setPreferredSize(new Dimension(range.getGlobalSize(0), range.getGlobalSize(1))); final Object doorBell = new Object(); // Mouse listener which reads the user clicked zoom-in point on the Mandelbrot view viewer.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e) { to = e.getPoint(); synchronized (doorBell) { doorBell.notify(); } } }); // Swing housework to create the frame frame.getContentPane().add(viewer); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); // Extract the underlying RGB buffer from the image. // Pass this to the kernel so it operates directly on the RGB buffer of the image final int[] rgb = ((DataBufferInt) offscreen.getRaster().getDataBuffer()).getData(); final int[] imageRgb = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); // Create a Kernel passing the size, RGB buffer and the palette. final MandelKernel kernel = new MandelKernel(rgb); float defaultScale = 3f; // Set the default scale and offset, execute the kernel and force a repaint of the viewer. kernel.setScaleAndOffset(defaultScale, -1f, 0f); kernel.execute(range); System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); viewer.repaint(); // Report target execution mode: GPU or JTP (Java Thread Pool). System.out.println("Execution mode=" + kernel.getExecutionMode()); // Window listener to dispose Kernel resources on user exit. frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent _windowEvent) { kernel.dispose(); System.exit(0); } }); // Wait until the user selects a zoom-in point on the Mandelbrot view. while (true) { // Wait for the user to click somewhere while (to == null) { synchronized (doorBell) { try { doorBell.wait(); } catch (InterruptedException ie) { ie.getStackTrace(); } } } float x = -1f; float y = 0f; float scale = defaultScale; float tox = (float) (to.x - range.getGlobalSize(0) / 2) / range.getGlobalSize(0) * scale; float toy = (float) (to.y - range.getGlobalSize(1) / 2) / range.getGlobalSize(1) * scale; // This is how many frames we will display as we zoom in and out. int frames = 128; long startMillis = System.currentTimeMillis(); for (int sign = -1; sign < 2; sign += 2) { for (int i = 0; i < frames - 4; i++) { scale = scale + sign * defaultScale / frames; x = x - sign * (tox / frames); y = y - sign * (toy / frames); // Set the scale and offset, execute the kernel and force a repaint of the viewer. kernel.setScaleAndOffset(scale, x, y); kernel.execute(range); List<ProfileInfo> profileInfo = kernel.getProfileInfo(); if (profileInfo != null && profileInfo.size() > 0) { for (ProfileInfo p : profileInfo) { System.out.print(" " + p.getType() + " " + p.getLabel() + " " + (p.getStart() / 1000) + " .. " + (p.getEnd() / 1000) + " " + (p.getEnd() - p.getStart()) / 1000 + "us"); } System.out.println(); } System.arraycopy(rgb, 0, imageRgb, 0, rgb.length); viewer.repaint(); } } long elapsedMillis = System.currentTimeMillis() - startMillis; System.out.println("FPS = " + frames * 1000 / elapsedMillis); // Reset zoom-in point. to = null; } } }
{ "content_hash": "62fb1ba681f8f4e35c5a24ff6cb8c40d", "timestamp": "", "source": "github", "line_count": 243, "max_line_length": 132, "avg_line_length": 35.90534979423868, "alnum_prop": 0.5798280802292264, "repo_name": "sadikovi/spark-gpu", "id": "fc03bc10f421b5ad6eaeae39cce225b9bb684206", "size": "11565", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aparapi/samples/mandel/src/com/amd/aparapi/sample/mandel/Main2D.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "4496" }, { "name": "C", "bytes": "44950" }, { "name": "CSS", "bytes": "11139" }, { "name": "HTML", "bytes": "740578" }, { "name": "Java", "bytes": "158282" }, { "name": "Scala", "bytes": "591" }, { "name": "Shell", "bytes": "2050" } ], "symlink_target": "" }
/* $Id: rsa-sanity.cpp $ */ /** @file * IPRT - Crypto - RSA, Sanity Checkers. */ /* * Copyright (C) 2006-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ /******************************************************************************* * Header Files * *******************************************************************************/ #include "internal/iprt.h" #include <iprt/crypto/rsa.h> #include <iprt/err.h> #include <iprt/string.h> #include "rsa-internal.h" /* * Generate the code. */ #include <iprt/asn1-generator-sanity.h>
{ "content_hash": "9cb5791637669f3d1bd7ee6316c10731", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 80, "avg_line_length": 35.51162790697674, "alnum_prop": 0.6162409954158481, "repo_name": "egraba/vbox_openbsd", "id": "2c099cebb09b0a10b26514a1a0998a97cb2aab6a", "size": "1527", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "VirtualBox-5.0.0/src/VBox/Runtime/common/crypto/rsa-sanity.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "88714" }, { "name": "Assembly", "bytes": "4303680" }, { "name": "AutoIt", "bytes": "2187" }, { "name": "Batchfile", "bytes": "95534" }, { "name": "C", "bytes": "192632221" }, { "name": "C#", "bytes": "64255" }, { "name": "C++", "bytes": "83842667" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "6041" }, { "name": "CSS", "bytes": "26756" }, { "name": "D", "bytes": "41844" }, { "name": "DIGITAL Command Language", "bytes": "56579" }, { "name": "DTrace", "bytes": "1466646" }, { "name": "GAP", "bytes": "350327" }, { "name": "Groff", "bytes": "298540" }, { "name": "HTML", "bytes": "467691" }, { "name": "IDL", "bytes": "106734" }, { "name": "Java", "bytes": "261605" }, { "name": "JavaScript", "bytes": "80927" }, { "name": "Lex", "bytes": "25122" }, { "name": "Logos", "bytes": "4941" }, { "name": "Makefile", "bytes": "426902" }, { "name": "Module Management System", "bytes": "2707" }, { "name": "NSIS", "bytes": "177212" }, { "name": "Objective-C", "bytes": "5619792" }, { "name": "Objective-C++", "bytes": "81554" }, { "name": "PHP", "bytes": "58585" }, { "name": "Pascal", "bytes": "69941" }, { "name": "Perl", "bytes": "240063" }, { "name": "PowerShell", "bytes": "10664" }, { "name": "Python", "bytes": "9094160" }, { "name": "QMake", "bytes": "3055" }, { "name": "R", "bytes": "21094" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "1460572" }, { "name": "SourcePawn", "bytes": "4139" }, { "name": "TypeScript", "bytes": "142342" }, { "name": "Visual Basic", "bytes": "7161" }, { "name": "XSLT", "bytes": "1034475" }, { "name": "Yacc", "bytes": "22312" } ], "symlink_target": "" }
**[Map2gpx](../README.md)** > [Globals](../README.md) / ["Map2gpx"](../modules/_map2gpx_.md) / [Controls](../modules/_map2gpx_.controls.md) / ZoomOptions # Interface: ZoomOptions ## Hierarchy * any ↳ **ZoomOptions** ## Index ### Properties * [zoomInTitle](_map2gpx_.controls.zoomoptions.md#zoomintitle) * [zoomOutTitle](_map2gpx_.controls.zoomoptions.md#zoomouttitle) ## Properties ### zoomInTitle • `Optional` **zoomInTitle**: string ___ ### zoomOutTitle • `Optional` **zoomOutTitle**: string
{ "content_hash": "a25e4134c2b9ac9b5b5f7341d073cd24", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 125, "avg_line_length": 17, "alnum_prop": 0.6666666666666666, "repo_name": "tmuguet/map2gpx", "id": "7e3a8b3cf9acdb3071266510e9848f17cf9807f7", "size": "516", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/interfaces/_map2gpx_.controls.zoomoptions.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3618" }, { "name": "HTML", "bytes": "63368" }, { "name": "JavaScript", "bytes": "49973" }, { "name": "PHP", "bytes": "4936" } ], "symlink_target": "" }
<?php namespace BL\SGIBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use BL\SGIBundle\Entity\Usuario; use BL\SGIBundle\Form\UsuarioType; use Doctrine\ORM\Query; use Symfony\Component\HttpFoundation\JsonResponse; /** * Usuario controller. * * @Route("/usuario") */ class UsuarioController extends Controller { /** * Lists all Usuario entities. * * @Route("/", name="usuario") * @Method("GET") * @Template() */ public function indexAction() { // Elaboro los botones $link_new = $this->generateUrl('usuario_new', array()); $userManager = $this->container->get('fos_user.user_manager'); /* $user = $userManager->findUserByUsername($this->container->get('security.context') ->getToken() ->getUser()); $usuario = $user->getUsername(); */ $user=$this->getUser(); // Obtengo el grupo de mi usuario $grupo_usuario = $user->getGroupNames(); $grupo_usuario = $grupo_usuario[0]; // Asigno los botones según mi grupo switch ($grupo_usuario) { case "Administrador": $new = '<a href = "'.$link_new.'" class = "btn btn-success btn-sm"><span class = "glyphicon glyphicon-plus"></span> Agregar</a>'; break; default: $new = ''; break; } return array( 'new' => $new, ); } /** * Creates a new Usuario entity. * * @Route("/", name="usuario_create") * @Method("POST") * @Template("SGIBundle:Usuario:new.html.twig") */ public function createAction(Request $request) { $entity = new Usuario(); $form = $this->createCreateForm($entity); $form->handleRequest($request); $usuario = $request->get('sgi_siretrabundle_usuario'); $grupos = $usuario['grupo']; if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); $em2 = $this->getDoctrine()->getEntityManager('reportasistencia'); $connection = $em2->getConnection(); $statement = $connection->prepare("SELECT * FROM userinfo WHERE dbi like :dbi"); $statement->bindValue('dbi', $entity->getDni()); $statement->execute(); $results = $statement->fetchAll(); if (count($results) > 0) { $userid = $results[0]["userid"]; $entity->setIdUserinfo($userid); $em->persist($entity); $em->flush(); } for($i=0;$i < count($grupos);$i++) { $entity_group = $em->getRepository('SGIBundle:Group')->find($grupos[$i]); $entity->addGroup($entity_group); $em->persist($entity); $em->flush(); } $id = $entity->getId(); // Procedo log $userManager = $this->container->get('fos_user.user_manager'); /*$user = $userManager->findUserByUsername($this->container->get('security.context') ->getToken() ->getUser()); $usuario = $user->getUsername(); */ $user=$this->getUser(); $query = $em->createQuery('SELECT x FROM SGIBundle:Usuario x WHERE x.id = ?1'); $query->setParameter(1, $id); $arreglo_formulario = $query->getSingleResult(Query::HYDRATE_ARRAY); $bitacora = $em->getRepository('SGIBundle:ExtLogEntries') ->bitacora($usuario,'Insert','Usuario',$entity->getId(),$arreglo_formulario); // fin proceso log return $this->redirect($this->generateUrl('usuario_show', array('id' => $entity->getId()))); } return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * Creates a form to create a Usuario entity. * * @param Usuario $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createCreateForm(Usuario $entity) { $form = $this->createForm(new UsuarioType(), $entity, array( 'action' => $this->generateUrl('usuario_create'), 'method' => 'POST', )); $groups = $this->container->get('fos_user.group_manager')->findGroups(); foreach ($groups as $grupo) { $grupos[$grupo->getId()] = $grupo->getName(); } $form->add('grupo', 'choice', array( 'attr' => array('class' => 'form-control'), 'choices' => $grupos, 'multiple' => true, 'mapped' => false, )); $form->add('submit', 'submit', array('label' => 'Enviar', 'attr' => array('class' => 'btn btn-success btn-sm center-block') ) ); return $form; } /** * Displays a form to create a new Usuario entity. * * @Route("/new", name="usuario_new") * @Method("GET") * @Template() */ public function newAction() { $entity = new Usuario(); $form = $this->createCreateForm($entity); return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * Finds and displays a Usuario entity. * * @Route("/{id}", name="usuario_show") * @Method("GET") * @Template() */ public function showAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('SGIBundle:Usuario')->find($id); $activo = ($entity->IsEnabled()) ? "Sí" : "No"; // Obtengo todos los grupos previos de mi usuario $grupos_usuario = $entity->getGroupNames(); // Busco cada grupo for ($i=0; $i < count($grupos_usuario); $i++) { $entity_grupo = $this->container->get('fos_user.group_manager')-> findGroupBy(array('name' => $grupos_usuario[$i])); // Por cada grupo que consiga lo elimino $entity_group = $em->getRepository('SGIBundle:Group')->find($entity_grupo->getId()); $grupo = $entity_group->getName(); } $usuario = array( "dbi" => $entity->getDni(), "nacionalidad" => $entity->getNacionalidad(), "nombre" => $entity->getNombre(), "apellido" => $entity->getApellido(), "telefono" => $entity->getTelefono(), "telefono_secundario" => $entity->getTelefonoSecundario(), "username" => $entity->getUsername(), "email" => $entity->getEmail(), "activo" => $activo, "grupo" => $grupo, ); $userManager = $this->container->get('fos_user.user_manager'); $user = $userManager->findUserByUsername($this->container->get('security.context') ->getToken() ->getUser()); // Obtengo el grupo de mi usuario // $grupo_usuario = $user->getGroupNames(); $grupo_usuario = 1; $grupo_usuario = $grupo_usuario[0]; // Elaboro los botones $link_index = $this->generateUrl('usuario', array()); $link_show = $this->generateUrl('usuario_show', array('id' => $id)); $link_edit = $this->generateUrl('usuario_edit', array('id' => $id)); $link_delete = $this->generateUrl('usuario_delete', array('id' => $id)); $index = '<a href = "'.$link_index.'" class = "btn btn-info btn-sm"><span class = "glyphicon glyphicon-th-list"></span> Listado</a>'; $show = '<a href = "'.$link_show.'" class = "btn btn-info btn-sm"><span class = "glyphicon glyphicon glyphicon-search"></span> Ver</a>'; $edit = '<a href = "'.$link_edit.'" class = "btn btn-info btn-sm"><span class = "glyphicon glyphicon-edit"></span> Editar</a>'; $delete = '<a id="eliminar" href = "'.$link_delete.'" class = "btn btn-danger btn-sm"><span class = "glyphicon glyphicon glyphicon-alert"></span> Desactivar</a>'; // Asigno los botones según mi grupo // Asigno los botones según mi grupo switch ($grupo_usuario) { case "Administrador": $botones = $index.' '.$show.' '.$edit.' '.$delete; break; case "Usuario Extendido": if ($id == $user->getId()) { $botones = $index.' '.$show.' '.$edit; } else { $botones = $index.' '.$show; } break; default: $botones = $index.' '.$show; break; } return array( 'usuario' => $usuario, 'botones' => $botones ); } /** * Displays a form to edit an existing Usuario entity. * * @Route("/{id}/edit", name="usuario_edit") * @Method("GET") * @Template() */ public function editAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('SGIBundle:Usuario')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Usuario entity.'); } $editForm = $this->createEditForm($entity); $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); } /** * Creates a form to edit a Usuario entity. * * @param Usuario $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createEditForm(Usuario $entity) { $form = $this->createForm(new UsuarioType(), $entity, array( 'action' => $this->generateUrl('usuario_update', array('id' => $entity->getId())), 'method' => 'PUT', )); $groups = $this->container->get('fos_user.group_manager')->findGroups(); foreach ($groups as $grupo) { $grupos[$grupo->getId()] = $grupo->getName(); } // Obtengo todos los grupos de mi usuario $grupos_usuario = $entity->getGroupNames(); // Busco cada grupo for ($i=0; $i < count($grupos_usuario); $i++) { $entity_grupo = $this->container->get('fos_user.group_manager')-> findGroupBy(array('name' => $grupos_usuario[$i])); // Construyo el arreglo por id para que en el choice puedan aparecer como // selected $grupo_existente[$entity_grupo->getId()] = $entity_grupo->getId(); } $form->add('grupo', 'choice', array( 'attr' => array('class' => 'form-control'), 'choices' => $grupos, 'multiple' => true, 'mapped' => false, 'data' => $grupo_existente, )); $form->add('submit', 'submit', array('label' => 'Enviar', 'attr' => array('class' => 'btn btn-success btn-sm center-block') ) ); return $form; } /** * Edits an existing Usuario entity. * * @Route("/{id}", name="usuario_update") * @Method("PUT") * @Template("SGIBundle:Usuario:edit.html.twig") */ public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('SGIBundle:Usuario')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Usuario entity.'); } $deleteForm = $this->createDeleteForm($id); $editForm = $this->createEditForm($entity); $editForm->handleRequest($request); if ($editForm->isValid()) { $em->flush(); // Eliminar los grupos previamente incluidos para este usuario y realizar // la nueva insercion correspondiente // Obtengo todos los grupos previos de mi usuario $grupos_usuario = $entity->getGroupNames(); // Busco cada grupo for ($i=0; $i < count($grupos_usuario); $i++) { $entity_grupo = $this->container->get('fos_user.group_manager')-> findGroupBy(array('name' => $grupos_usuario[$i])); // Por cada grupo que consiga lo elimino $entity_group = $em->getRepository('SGIBundle:Group')->find($entity_grupo->getId()); $entity->getGroups()->removeElement($entity_group); $em->persist($entity); $em->flush(); } // Obtengo los grupos que voy a asignarle al usuario $usuario = $request->get('sgi_siretrabundle_usuario'); $grupos = $usuario['grupo']; for($i=0;$i < count($grupos);$i++) { $entity_group = $em->getRepository('SGIBundle:Group')->find($grupos[$i]); $entity->addGroup($entity_group); $em->persist($entity); $em->flush(); } // Proceso Log $userManager = $this->container->get('fos_user.user_manager'); /*$user = $userManager->findUserByUsername($this->container->get('security.context') ->getToken() ->getUser()); $usuario = $user->getUsername();*/ $user=$this->getUser(); $query = $em->createQuery('SELECT x FROM SGIBundle:Usuario x WHERE x.id = ?1'); $query->setParameter(1, $id); $arreglo_formulario = $query->getSingleResult(Query::HYDRATE_ARRAY); $bitacora = $em->getRepository('SGIBundle:ExtLogEntries') ->bitacora($usuario,'Update','Usuario',$entity->getId(),$arreglo_formulario); // fin proceso log return $this->redirect($this->generateUrl('usuario', array('id' => $id))); } return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); } /** * Deletes a Usuario entity. * * @Route("/delete/{id}", name="usuario_delete") * @Method("GET") */ public function deleteAction(Request $request, $id) { $form = $this->createDeleteForm($id); $form->handleRequest($request); $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('SGIBundle:Usuario')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Usuario entity.'); } // Proceso Log $userManager = $this->container->get('fos_user.user_manager'); /*$user = $userManager->findUserByUsername($this->container->get('security.context') ->getToken() ->getUser()); $usuario = $user->getUsername(); */ $user=$this->getUser(); $query = $em->createQuery('SELECT x FROM SGIBundle:Usuario x WHERE x.id = ?1'); $query->setParameter(1, $id); $arreglo_formulario = $query->getSingleResult(Query::HYDRATE_ARRAY); $bitacora = $em->getRepository('SGIBundle:ExtLogEntries') ->bitacora($usuario,'Update','Usuario',$entity->getId(),$arreglo_formulario); // fin proceso log $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; $pass = array(); //remember to declare $pass as an array $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache for ($i = 0; $i < 8; $i++) { $n = rand(0, $alphaLength); $pass[] = $alphabet[$n]; } $password = implode($pass); $query = $em->createQuery('update SGIBundle:Usuario u set u.enabled = ?2, u.password = ?3 where u.id = ?1'); $query->setParameter(1, $id); $query->setParameter(2, 'false'); $query->setParameter(3, $password); $query->getSingleResult(Query::HYDRATE_ARRAY); return $this->redirect($this->generateUrl('usuario')); } /** * Creates a form to delete a Usuario entity by id. * * @param mixed $id The entity id * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('usuario_delete', array('id' => $id))) ->setMethod('DELETE') ->add('submit', 'submit', array('label' => 'Delete')) ->getForm() ; } /** * Creates a new Marca entity. * * @Route("/ajax/index", name="usuario_ajax") */ public function ajaxAction() { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('SGIBundle:Usuario')->findBy(array(), array('dbi'=>'asc')); $userManager = $this->container->get('fos_user.user_manager'); $user = $userManager->findUserByUsername($this->container->get('security.context') ->getToken() ->getUser()); // Obtengo el grupo de mi usuario $grupo_usuario = $user->getGroupNames(); $grupo_usuario = $grupo_usuario[0]; $data = array(); $dbi = array(); $nombre = array(); $apellido = array(); $telefono = array(); $telefono_secundario = array(); $username = array(); $email = array(); $activo = array(); $tipo = array(); $botones_array = array(); foreach ($entities as $list) { // Obtengo todos los grupos previos de mi usuario $grupos_usuario = $list->getGroupNames(); // Busco cada grupo for ($i=0; $i < count($grupos_usuario); $i++) { $entity_grupo = $this->container->get('fos_user.group_manager')-> findGroupBy(array('name' => $grupos_usuario[$i])); // Por cada grupo que consiga lo elimino $entity_group = $em->getRepository('SGIBundle:Group')->find($entity_grupo->getId()); $grupo = $entity_group->getName(); } $activo_usu = ($list->IsEnabled()) ? "Sí" : "No"; $dbi_usu = $list->getNacionalidad().$list->getDni(); array_push($dbi, $dbi_usu); array_push($nombre, $list->getNombre()); array_push($apellido, $list->getApellido()); array_push($telefono, $list->getTelefono()); array_push($telefono_secundario, $list->getTelefonoSecundario()); array_push($username, $list->getUsername()); array_push($email, $list->getEmail()); array_push($activo, $activo_usu); array_push($tipo, $grupo); // Elaboro los botones $link_show = $this->generateUrl('usuario_show', array('id' => $list->getId())); $link_edit = $this->generateUrl('usuario_edit', array('id' => $list->getId())); $show = '<a href = "'.$link_show.'" data-toggle="tooltip" title="Ver"><span class = "glyphicon glyphicon glyphicon-search"></a>&nbsp;&nbsp;&nbsp;'; $edit = '<a href = "'.$link_edit.'" data-toggle="tooltip" title="Editar"><span class = "glyphicon glyphicon glyphicon-edit"></a>'; // Asigno los botones según mi grupo switch ($grupo_usuario) { case "Administrador": $botones = $show.' '.$edit; break; case "Usuario Extendido": $botones = $show; break; default: $botones = $show; break; } if ($list->getId() == $user->getId() && $grupo_usuario != 'Usuario') { $botones = $show.' '.$edit; } array_push($botones_array, htmlentities($botones)); } $k = 0; for ($i = 0; $i < count($dbi); $i++) { $row = array(); $row["dbi"] = $dbi[$k]; $row["nombre"] = $nombre[$k]; $row["apellido"] = $apellido[$k]; $row["telefono"] = $telefono[$k]; $row["telefono_secundario"] = $telefono_secundario[$k]; $row["username"] = $username[$k]; $row["email"] = $email[$k]; $row["activo"] = $activo[$k]; $row["tipo"] = $tipo[$k]; $row["botones"] = html_entity_decode($botones_array[$k]); $data[$i] = $row; $k++; } return new JsonResponse($data); } }
{ "content_hash": "c4fb165efeb3dac1618f51fccb30d5f8", "timestamp": "", "source": "github", "line_count": 601, "max_line_length": 170, "avg_line_length": 36.96672212978369, "alnum_prop": 0.4894450195796012, "repo_name": "mwveliz/bl", "id": "63f0a59c0a6ca04ea9eb8ca712decee5fde8f656", "size": "22223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/BL/SGIBundle/Controller/UsuarioController.php", "mode": "33261", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "25594" }, { "name": "AngelScript", "bytes": "190" }, { "name": "CSS", "bytes": "4441852" }, { "name": "CoffeeScript", "bytes": "83631" }, { "name": "HTML", "bytes": "33261748" }, { "name": "JavaScript", "bytes": "21733044" }, { "name": "PHP", "bytes": "1368994" }, { "name": "Shell", "bytes": "444" } ], "symlink_target": "" }
int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([CHBAppDelegate class])); } }
{ "content_hash": "6a6dcbcff39fd24f9e9bbfea629d8a1f", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 93, "avg_line_length": 26.833333333333332, "alnum_prop": 0.6645962732919255, "repo_name": "followben/uicollectionview-awesome", "id": "b2f5db5e037ba0054ee70e16cdf6be1288390dc8", "size": "364", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHBCollectionView/main.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "20796" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>DebugHand &mdash; Leap Motion Objective-C SDK v2.3 documentation</title> <link rel="stylesheet" href="../../cpp/_static/bootstrap-3.0.0/css/documentation-bundle.1439949735.css" type="text/css" /> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '2.3', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: false }; </script> <script type="text/javascript" src="../../cpp/_static/bootstrap-3.0.0/js/documentation-bundle.1439949735.js"></script> <link rel="top" title="Leap Motion Objective-C SDK v2.3 documentation" href="../index.html" /> <script type="text/javascript" src="/assets/standalone-header.js?r9"></script> <link rel="stylesheet" href="/assets/standalone-header.css?r9" type="text/css" /> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'> <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'> <meta name="apple-mobile-web-app-capable" content="yes"> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-31536531-1']); _gaq.push(['_setDomainName', 'leapmotion.com']); _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> <script> function getQueryValue(variable) { var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); if(pair[0] == variable){return pair[1];} } return(false); } var relPath = "../../"; var requestedAPI = getQueryValue("proglang"); if(requestedAPI == "current") requestedAPI = localStorage["currentAPI"]; var pageAPI = 'objc'; var hasAPI = {}; hasAPI.unity = true; if(requestedAPI && (requestedAPI != pageAPI)) { if(pageAPI != 'none'){ var redirectedLocation = relPath + 'objc/unity/Unity.DebugHand.html'; if( requestedAPI == 'cpp' && hasAPI.cpp){ redirectedLocation = relPath + "cpp/unity/Unity.DebugHand.html"; } else if( requestedAPI == 'csharp' && hasAPI.csharp){ redirectedLocation = relPath + "csharp/unity/Unity.DebugHand.html"; } else if( requestedAPI == 'unity' && hasAPI.unity){ redirectedLocation = relPath + "unity/unity/Unity.DebugHand.html"; } else if( requestedAPI == 'objc' && hasAPI.objc){ redirectedLocation = relPath + "objc/unity/Unity.DebugHand.html"; } else if( requestedAPI == 'java' && hasAPI.java) { redirectedLocation = relPath + "java/unity/Unity.DebugHand.html"; } else if( requestedAPI == 'javascript' && hasAPI.javascript){ redirectedLocation = relPath + "javascript/unity/Unity.DebugHand.html"; } else if( requestedAPI == 'python' && hasAPI.python){ redirectedLocation = relPath + "python/unity/Unity.DebugHand.html"; } else if( requestedAPI == 'unreal' && hasAPI.unreal) { redirectedLocation = relPath + "unreal/unity/Unity.DebugHand.html"; } else { if( requestedAPI == 'cpp'){ redirectedLocation = relPath + "cpp/index.html?proglang=cpp"; } else if( requestedAPI == 'csharp'){ redirectedLocation = relPath + "csharp/index.html?proglang=csharp"; } else if( requestedAPI == 'unity'){ redirectedLocation = relPath + "unity/index.html?proglang=unity"; } else if( requestedAPI == 'objc'){ redirectedLocation = relPath + "objc/index.html?proglang=objc"; } else if( requestedAPI == 'java') { redirectedLocation = relPath + "java/index.html?proglang=java"; } else if( requestedAPI == 'javascript'){ redirectedLocation = relPath + "javascript/index.html?proglang=javascript"; } else if( requestedAPI == 'python'){ redirectedLocation = relPath + "python/index.html?proglang=python"; } else if( requestedAPI == 'unreal') { redirectedLocation = relPath + "unreal/index.html?proglang=unreal"; } else { redirectedLocation = relPath + "index.html"; } } //Guard against redirecting to the same page (infinitely) if(relPath + 'objc/unity/Unity.DebugHand.html' != redirectedLocation) window.location.replace(redirectedLocation); } } </script> <script> window.addEventListener('keyup', handleKeyInput); function handleKeyInput(e) { var code; if (!e) var e = window.event; if (e.keyCode) code = e.keyCode; else if (e.which) code = e.which; var character = String.fromCharCode(code); if( character == "J" & e.altKey){ } else if( character == "K" & e.altKey){ } } </script> </head> <body role="document"> <div class="developer-portal-styles"> <header class="navbar navbar-static-top developer-navbar header beta-header"> <nav class="container pr"> <a class="logo-link pull-left" href="/"> <img alt="Leap Motion Developers" class="media-object pull-left white-background" src="../_static/logo.png" /> </a> <span class="inline-block hidden-phone developer-logo-text"> <div class="text"> <a href="/"> <span class="more-than-1199">Developer Portal</span> </a> </div> </span> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Everything within here will be hidden at 940px or less, accessible via a button. --> <div class="nav-collapse"> <ul class="nav header-navigation developer-links"> <li class="external-link"><a href="https://developer.leapmotion.com/features">What's new</a> </li> <li class="external-link"><a href="https://developer.leapmotion.com/downloads/skeletal-beta" class="">Getting Started</a></li> <li><a class="active" href="#" class="">Documentation</a></li> <li class="external-link"> <a href="https://developer.leapmotion.com/gallery" class="">Examples</a> </li> <li class="external-link"> <a href="https://www.leapmotion.com/blog/category/labs/" class="" target="_blank">Blog <i class='fa fa-external-link'></i></a> </li> <li class="external-link"> <a href="https://community.leapmotion.com/category/beta" class="" target="_blank">Community <i class='fa fa-external-link'></i></a> </li> </ul> </div> </nav> </header> </div> <section class="main-wrap"> <div data-swiftype-index="true"> <div class="second_navigation"> <div class="container"> <div class="row"> <div class="col-md-8"> <ul> <li> <a href="../../javascript/index.html?proglang=javascript" onclick="localStorage['currentAPI'] = 'javascript'">JavaScript</a> </li> <li> <a href="../../unity/unity/Unity.DebugHand.html?proglang=unity" onclick="localStorage['currentAPI'] = 'unity'">Unity</a> </li> <li> <a href="../../csharp/index.html?proglang=csharp" onclick="localStorage['currentAPI'] = 'csharp'">C#</a> </li> <li> <a href="../../cpp/index.html?proglang=cpp" onclick="localStorage['currentAPI'] = 'cpp'">C++</a> </li> <li> <a href="../../java/index.html?proglang=java" onclick="localStorage['currentAPI'] = 'java'">Java</a> </li> <li> <a href="../../python/index.html?proglang=python" onclick="localStorage['currentAPI'] = 'python'">Python</a> </li> <li> Objective-C </li> <li> <a href="../../unreal/index.html?proglang=unreal" onclick="localStorage['currentAPI'] = 'unreal'">Unreal</a> </li> </ul> </div> <div class="col-md-4 search"> <script> function storeThisPage(){ sessionStorage["pageBeforeSearch"] = window.location; return true; } function doneWithSearch(){ var storedPage = sessionStorage["pageBeforeSearch"]; if(storedPage){ window.location = storedPage; } else { window.location = "index.html"; //fallback } return false; } </script> <div style="margin-top:-4px"> <ul style="display:inline; white-space:nowrap"><li> <form class="navbar-form" action="../search.html" method="get" onsubmit="storeThisPage()"> <div class="form-group"> <input type="search" results="5" name="q" class="form-control" placeholder="Search" /> </div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form></li> </ul> </div> </div> </div> </div> </div> <script> //Remove dev portal header and footer when viewing from file system if(window.location.protocol == 'file:'){ var navNode = document.querySelector(".developer-links"); navNode.parentNode.removeChild(navNode); } </script> <div id="wrap" data-spy="scroll" data-target="#sidebar"> <div class="container"> <div class="row"> <div class="col-md-9 pull-right"> <!-- <span id="breadcrumbs"> <a href="../index.html">Home</a>&raquo; DebugHand </span> --> <div class="section" id="debughand"> <h1>DebugHand<a class="headerlink" href="#debughand" title="Permalink to this headline">¶</a></h1> <p>The DebugHand draws no graphics in a Game view, but draws lines for the parts of the hand in the Scene view. Use the DebugHand when you do not want visible hands, but want to see where the hands are in the Scene view.</p> <img alt="unity/../../../images/unity/Unity_DebugHand.png" src="unity/../../../images/unity/Unity_DebugHand.png" /> <div class="line-block" id="unitycorea00003"> <div class="line"><em>class</em> <strong>DebugHand</strong></div> </div> <blockquote> <div><p>A <a class="reference internal" href="Unity.HandModel.html#unitycorea00013"><em>HandModel</em></a> that draws lines for the bones in the hand and its fingers. </p> <p>The debugs lines are only drawn in the Editor Scene view (when a hand is tracked) and not in the Game view. Use debug hands when you aren&#8217;t using visible hands in a scene so that you can see where the hands are in the scene view. </p> <em>Public Functions</em><blockquote> <div><p><span class="target" id="unitycorea00003_1a4ea48ffa2884bb50c500d0cbcc6061ae"></span><div class="line-block"> <div class="line">override void <strong>InitHand</strong>()</div> </div> </p> <blockquote> <div><p>Initializes the hand and calls the line drawing function. </p> <p></p> </div></blockquote> <p><span class="target" id="unitycorea00003_1a1d926966feb837567511a14fca9b8cc1"></span><div class="line-block"> <div class="line">override void <strong>UpdateHand</strong>()</div> </div> </p> <blockquote> <div><p>Updates the hand and calls the line drawing function. </p> <p></p> </div></blockquote> </div></blockquote> </div></blockquote> <blockquote> <div></div></blockquote> </div> <!-- get_disqus_sso --> </div> <div id="sidebar" class="col-md-3"> <div class="well-sidebar" data-offset-top="188"> <ul> <li><a href="../index.html" title="Home">Objective-C Docs (v2.3)</a></li> </ul><ul> <li class="toctree-l1"><a class="reference internal" href="../devguide/Intro_Skeleton_API.html">Introducing the Skeletal Tracking Model</a></li> <li class="toctree-l1"><a class="reference internal" href="../devguide/Leap_Overview.html">API Overview</a></li> <li class="toctree-l1"><a class="reference internal" href="../practices/Leap_Practices.html">Guidelines</a></li> <li class="toctree-l1"><a class="reference internal" href="../devguide/Leap_Guides.html">Application Development</a></li> <li class="toctree-l1"><a class="reference internal" href="../devguide/Leap_Guides2.html">Using the Tracking API</a></li> <li class="toctree-l1"><a class="reference internal" href="../api/Leap_Classes.html">API Reference</a></li> <li class="toctree-l1"><a class="reference internal" href="../supplements/Leap_Supplements.html">Appendices</a></li> </ul> </div> </div> </div> </div> </div> <!-- <div class="ribbon"> <p>Objective-C</p> </div> <footer> <div id="footer" class="container"> <div class="container"> <div class="copyright"> <span>Copyright &copy; 2012 - 2014, Leap Motion, Inc.</span> </div> </div> </div> </footer> </body> </html>
{ "content_hash": "a5f5dc3f243165f4aecd4d2ce63f6e01", "timestamp": "", "source": "github", "line_count": 368, "max_line_length": 243, "avg_line_length": 37.442934782608695, "alnum_prop": 0.5967051309964438, "repo_name": "joelbandi/Be-ethoven", "id": "678e461d9f7976ca2f19a1f7657a355737e4f2f6", "size": "13783", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LeapSDK/docs/objc/unity/Unity.DebugHand.html", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "6722" }, { "name": "C++", "bytes": "347503" }, { "name": "CSS", "bytes": "101632" }, { "name": "HTML", "bytes": "24938147" }, { "name": "Java", "bytes": "14109" }, { "name": "JavaScript", "bytes": "408159" }, { "name": "Makefile", "bytes": "526" }, { "name": "Python", "bytes": "96203" } ], "symlink_target": "" }
from unittest import TestCase from yaml_rulz.validator import YAMLValidator SCHEMA_CONTENT = r""" --- root: key_a: "~ exactly this" key_b: "@ num | > 15" key_c: "> root:key_b" """ RESOURCE_WITH_ISSUES = r""" --- root: key_a: exactly that key_b: 6 key_c: 2 """ RESOURCE_ALL_OK = r""" --- root: key_a: exactly this key_b: 16 key_c: 20 """ EXCLUSIONS = r""" root:key_a """ ISSUES = [ {"resource": "root:key_a", "severity": "Warning", "value": "exactly that", "criterion": "exactly this", "schema": "root:key_a", "message": "Regular expression mismatch", "ref": False}, {"criterion": 6, "message": "Value must be greater than criterion", "ref": True, "resource": "root:key_c", "severity": "Error", "schema": "root:key_b", "value": 2}, {"criterion": "15", "message": "Value must be greater than criterion", "ref": False, "resource": "root:key_b", "severity": "Error", "schema": "root:key_b", "value": 6}, ] class TestValidator(TestCase): maxDiff = None def test_validator_without_issues(self): has_errors, issues = self.__create_validator_and_get_result(RESOURCE_ALL_OK) self.assertFalse(has_errors) self.assertEqual([], issues) def test_validator_with_issues(self): has_errors, issues = self.__create_validator_and_get_result(RESOURCE_WITH_ISSUES, EXCLUSIONS) self.assertTrue(has_errors) try: self.assertItemsEqual(ISSUES, issues) except AttributeError: self.assertEqual(len(ISSUES), len(issues)) for issue in ISSUES: self.assertIn(issue, issues) @staticmethod def __create_validator_and_get_result(resource, exclusions=None): validator = YAMLValidator(SCHEMA_CONTENT, resource, exclusions) return validator.get_validation_issues()
{ "content_hash": "b022ca71a18e3ea8c2f70d9ba8debf06", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 101, "avg_line_length": 23.75, "alnum_prop": 0.6042105263157894, "repo_name": "milonoir/yaml_rulz", "id": "ce5e2ae2f257acc53af8a43825124401166fd4ec", "size": "1900", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test_validator.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "39586" } ], "symlink_target": "" }
<?php namespace Sbts\Bundle\UserBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; class UserProfileType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('username', null, ['disabled' => true]) ->add('plainPassword', 'repeated', [ 'type' => 'password', 'options' => ['translation_domain' => 'FOSUserBundle'], 'first_options' => ['label' => 'form.new_password'], 'second_options' => ['label' => 'form.new_password_confirmation'], 'invalid_message' => 'fos_user.password.mismatch', 'required' => false, ]) ->add('fullname') ->add('avatarFile', 'vich_file', [ 'required' => false, 'allow_delete' => true, ]) ->remove('current_password') ->add('save', 'submit', ['label' => 'user.link.update_my_profile']); } public function getParent() { return 'fos_user_profile'; } public function getName() { return 'sbts_user_profile'; } }
{ "content_hash": "403d1dcd2b4b2be6fe6b3a2915a11efb", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 83, "avg_line_length": 31.15909090909091, "alnum_prop": 0.5171407731582787, "repo_name": "teslitsky/sbts", "id": "04ee4f58bd1822925d82b54b095056fb4dc30c9f", "size": "1371", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Sbts/Bundle/UserBundle/Form/Type/UserProfileType.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3297" }, { "name": "CSS", "bytes": "198" }, { "name": "HTML", "bytes": "44374" }, { "name": "JavaScript", "bytes": "381" }, { "name": "PHP", "bytes": "208118" } ], "symlink_target": "" }
Some random projects to play with... For Mac user, please build and install https://github.com/conormcd/osx-keychain-java to local Maven repo git clone git@github.com:conormcd/osx-keychain-java.git ant jar mvn install:install-file -Dfile=dist/osxkeychain.jar -DgroupId=com.mcdermottroe.apple -DartifactId=osxkeychain -Dversion=1.0 -Dpackaging=jar ## Usage FIXME ## License Copyright © 2015 FIXME Distributed under the Eclipse Public License either version 1.0 or (at your option) any later version.
{ "content_hash": "e70eabaa70fcec45541339ef11e529ae", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 140, "avg_line_length": 28.11111111111111, "alnum_prop": 0.7885375494071146, "repo_name": "rmcv/play", "id": "f8d32076606edab65e754b58ef9418e0d378127f", "size": "522", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Clojure", "bytes": "102371" }, { "name": "F#", "bytes": "12001" } ], "symlink_target": "" }
GhettoPrefs =========== A truly ghetto almost-drop-in replacement for Unity3D's PlayerPrefs class. Use at your own peril.
{ "content_hash": "79a296e0d8b5ed8c7ecd3becaa374678", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 74, "avg_line_length": 20.666666666666668, "alnum_prop": 0.7258064516129032, "repo_name": "aayars/GhettoPrefs", "id": "2a28968a158e8e8c6abb0d0ea517ad479b12d65f", "size": "124", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "8834" } ], "symlink_target": "" }
<?php namespace common\models; use Yii; /** * This is the model class for table "comment". * * @property integer $id * @property string $content * @property integer $status * @property integer $create_time * @property integer $userid * @property string $email * @property string $url * @property integer $post_id * @property integer $remind * @property Post $post * @property Commentstatus $status0 * @property User $user */ class Comment extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'comment'; } /** * @inheritdoc */ public function rules() { return [ [['content', 'status', 'userid', 'email', 'post_id'], 'required'], [['content'], 'string'], [['status', 'create_time', 'userid', 'post_id','remind'], 'integer'], [['email', 'url'], 'string', 'max' => 128], [['post_id'], 'exist', 'skipOnError' => true, 'targetClass' => Post::className(), 'targetAttribute' => ['post_id' => 'id']], [['status'], 'exist', 'skipOnError' => true, 'targetClass' => Commentstatus::className(), 'targetAttribute' => ['status' => 'id']], [['userid'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['userid' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'content' => '内容', 'status' => '状态', 'create_time' => '发布时间', 'userid' => '用户', 'email' => 'Email', 'url' => 'Url', 'post_id' => '文章', 'remind' => 'Remind', ]; } /** * @return \yii\db\ActiveQuery */ public function getPost() { return $this->hasOne(Post::className(), ['id' => 'post_id']); } /** * @return \yii\db\ActiveQuery */ public function getStatus0() { return $this->hasOne(Commentstatus::className(), ['id' => 'status']); } /** * @return \yii\db\ActiveQuery */ public function getUser() { return $this->hasOne(User::className(), ['id' => 'userid']); } public function getBeginning() { $tmpStr = strip_tags($this->content); $tmpLen = mb_strlen($tmpStr); return mb_substr($tmpStr,0,10,'utf-8').(($tmpLen>10)?'...':''); } public function approve() { $this->status = 2; //设置评论状态为已审核 return ($this->save()?true:false); } public static function getPengdingCommentCount() { return Comment::find()->where(['status'=>1])->count(); } public function beforeSave($insert) { if(parent::beforeSave($insert)) { if($insert) { $this->create_time=time(); } return true; } else return false; } public static function findRecentComments($limit=10) { return Comment::find()->where(['status'=>2])->orderBy('create_time DESC') ->limit($limit)->all(); } }
{ "content_hash": "fb571091083f8e7d8ef48209d76d09bf", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 143, "avg_line_length": 23.115942028985508, "alnum_prop": 0.5040752351097179, "repo_name": "zhouyunjin1234/yii2", "id": "1c286ad0a0f513828d0ededca8cfdf07268ff1d1", "size": "3234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/models/Comment.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1541" }, { "name": "CSS", "bytes": "3332" }, { "name": "JavaScript", "bytes": "237778" }, { "name": "PHP", "bytes": "3054829" }, { "name": "Shell", "bytes": "3257" } ], "symlink_target": "" }
<!-- Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. This code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 only, as published by the Free Software Foundation. Oracle designates this particular file as subject to the "Classpath" exception as provided by Oracle in the LICENSE file that accompanied this code. This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 for more details (a copy is included in the LICENSE file that accompanied this code). You should have received a copy of the GNU General Public License version 2 along with this work; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA or visit www.oracle.com if you need additional information or have any questions. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html> <body bgcolor="white"> Provides classes and interfaces for key specifications and algorithm parameter specifications. <p>A key specification is a transparent representation of the key material that constitutes a key. A key may be specified in an algorithm-specific way, or in an algorithm-independent encoding format (such as ASN.1). This package contains key specifications for Diffie-Hellman public and private keys, as well as key specifications for DES, Triple DES, and PBE secret keys. <p>An algorithm parameter specification is a transparent representation of the sets of parameters used with an algorithm. This package contains algorithm parameter specifications for parameters used with the Diffie-Hellman, DES, Triple DES, PBE, RC2 and RC5 algorithms. <h2>Package Specification</h2> <ul> <li>PKCS #3: Diffie-Hellman Key-Agreement Standard, Version 1.4, November 1993.</li> <li>PKCS #5: Password-Based Encryption Standard, Version 1.5, November 1993.</li> <li>Federal Information Processing Standards Publication (FIPS PUB) 46-2: Data Encryption Standard (DES) </li> </ul> <h2>Related Documentation</h2> For documentation that includes information about algorithm parameter and key specifications, please see: <ul> <li> <a href= "{@docRoot}/../technotes/guides/security/crypto/CryptoSpec.html"> <b>Java<FONT SIZE=-2><SUP>TM</SUP></FONT> Cryptography Architecture API Specification and Reference </b></a></li> <li> <a href= "{@docRoot}/../technotes/guides/security/crypto/HowToImplAProvider.html"> <b>How to Implement a Provider for the Java<FONT SIZE=-2><SUP>TM</SUP></FONT> Cryptography Architecture </b></a></li> </ul> @since 1.4 </body> </html>
{ "content_hash": "fd85764e667bfc9a7cf228da7e5ca218", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 79, "avg_line_length": 37.88461538461539, "alnum_prop": 0.7573604060913706, "repo_name": "groschovskiy/j2objc", "id": "b8fd80724dea3bddeb98356becc97fed69fd8ee6", "size": "2955", "binary": false, "copies": "68", "ref": "refs/heads/master", "path": "jre_emul/android/platform/libcore/ojluni/src/main/java/javax/crypto/spec/package.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1043" }, { "name": "C", "bytes": "741240" }, { "name": "C++", "bytes": "322767" }, { "name": "HTML", "bytes": "111524" }, { "name": "Java", "bytes": "47099387" }, { "name": "Makefile", "bytes": "551067" }, { "name": "Objective-C", "bytes": "1542208" }, { "name": "Objective-C++", "bytes": "209566" }, { "name": "Python", "bytes": "25563" }, { "name": "Shell", "bytes": "22890" } ], "symlink_target": "" }
A_OK_HTTP_CODES = [ 200, 207 ] A_ERROR_HTTP_CODES = { 400: "Request was invalid", 401: "Invalid API key", 403: "Bad OAuth scope", 404: "Selector did not match any lights", 422: "Missing or malformed parameters", 426: "HTTP is required to perform transaction", # see http://api.developer.lifx.com/v1/docs/rate-limits 429: "Rate limit exceeded", 500: "API currently unavailable", 502: "API currently unavailable", 503: "API currently unavailable", 523: "API currently unavailable" }
{ "content_hash": "2523b257e22405da4e754fdbdec4d86d", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 59, "avg_line_length": 28.31578947368421, "alnum_prop": 0.6505576208178439, "repo_name": "cydrobolt/pifx", "id": "b214d604963e9576b755e4b200d9e821e8431152", "size": "1163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pifx/constants.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "19870" } ], "symlink_target": "" }
<div class="page-header"> <h1>{{ page.title }} {% if page.tagline %}<small>{{page.tagline}}</small>{% endif %}</h1> </div> <div class="row post-full"> <div class="col-xs-12"> <div class="date"> <span>{{ page.date | date_to_long_string }}</span> </div> <div class="content"> {{ content }} </div> <h2>Categories and Tags</h2> {% unless page.categories == empty %} <ul class="tag_box inline"> <li><i class="glyphicon glyphicon-open"></i></li> {% assign categories_list = page.categories %} {% include JB/categories_list %} </ul> {% endunless %} {% unless page.tags == empty %} <ul class="tag_box inline"> <li><i class="glyphicon glyphicon-tags"></i></li> {% assign tags_list = page.tags %} {% include JB/tags_list %} </ul> {% endunless %} <hr> <ul class="pagination"> {% if page.previous %} <li class="prev"><a href="{{ BASE_PATH }}{{ page.previous.url }}" title="{{ page.previous.title }}">&laquo; Previous</a></li> {% else %} <li class="prev disabled"><a>&larr; Previous</a></li> {% endif %} <li><a href="{{ BASE_PATH }}{{ site.JB.archive_path }}">Archive</a></li> {% if page.next %} <li class="next"><a href="{{ BASE_PATH }}{{ page.next.url }}" title="{{ page.next.title }}">Next &raquo;</a></li> {% else %} <li class="next disabled"><a>Next &rarr;</a> {% endif %} </ul> <hr> {% include JB/comments %} </div> </div>
{ "content_hash": "240fe830eb4db4c9330c2722bcdb5040", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 131, "avg_line_length": 30.551020408163264, "alnum_prop": 0.5357381429525718, "repo_name": "obromios/obromios.github.com", "id": "dbfad051c3ae62884744df099b5f179dfe79c7ec", "size": "1497", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/themes/bootstrap-3/post.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4564" }, { "name": "HTML", "bytes": "11465" }, { "name": "Ruby", "bytes": "17309" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <sem:triples uri="http://www.lds.org/vrl/people/specific-people/people-from-scriptures/old-testament/hosea" xmlns:sem="http://marklogic.com/semantics"> <sem:triple> <sem:subject>http://www.lds.org/vrl/people/specific-people/people-from-scriptures/old-testament/hosea</sem:subject> <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate> <sem:object datatype="xsd:string" xml:lang="eng">Hosea</sem:object> </sem:triple> <sem:triple> <sem:subject>http://www.lds.org/vrl/people/specific-people/people-from-scriptures/old-testament/hosea</sem:subject> <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate> <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object> </sem:triple> <sem:triple> <sem:subject>http://www.lds.org/vrl/people/specific-people/people-from-scriptures/old-testament/hosea</sem:subject> <sem:predicate>http://www.lds.org/core#entityType</sem:predicate> <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object> </sem:triple> </sem:triples>
{ "content_hash": "d49f033b5cbcbf456ac612c456da9dbd", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 151, "avg_line_length": 62.44444444444444, "alnum_prop": 0.7277580071174378, "repo_name": "freshie/ml-taxonomies", "id": "645707feb157093ed3a45e4107c4ab7b60c850d8", "size": "1124", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "roxy/data/gospel-topical-explorer-v2/taxonomies/vrl/people/specific-people/people-from-scriptures/old-testament/hosea.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4422" }, { "name": "CSS", "bytes": "38665" }, { "name": "HTML", "bytes": "356" }, { "name": "JavaScript", "bytes": "411651" }, { "name": "Ruby", "bytes": "259121" }, { "name": "Shell", "bytes": "7329" }, { "name": "XQuery", "bytes": "857170" }, { "name": "XSLT", "bytes": "13753" } ], "symlink_target": "" }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/cx/v3/changelog.proto package com.google.cloud.dialogflow.cx.v3; public interface ListChangelogsResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.dialogflow.cx.v3.ListChangelogsResponse) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The list of changelogs. There will be a maximum number of items returned * based on the page_size field in the request. The changelogs will be ordered * by timestamp. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3.Changelog changelogs = 1;</code> */ java.util.List<com.google.cloud.dialogflow.cx.v3.Changelog> getChangelogsList(); /** * * * <pre> * The list of changelogs. There will be a maximum number of items returned * based on the page_size field in the request. The changelogs will be ordered * by timestamp. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3.Changelog changelogs = 1;</code> */ com.google.cloud.dialogflow.cx.v3.Changelog getChangelogs(int index); /** * * * <pre> * The list of changelogs. There will be a maximum number of items returned * based on the page_size field in the request. The changelogs will be ordered * by timestamp. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3.Changelog changelogs = 1;</code> */ int getChangelogsCount(); /** * * * <pre> * The list of changelogs. There will be a maximum number of items returned * based on the page_size field in the request. The changelogs will be ordered * by timestamp. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3.Changelog changelogs = 1;</code> */ java.util.List<? extends com.google.cloud.dialogflow.cx.v3.ChangelogOrBuilder> getChangelogsOrBuilderList(); /** * * * <pre> * The list of changelogs. There will be a maximum number of items returned * based on the page_size field in the request. The changelogs will be ordered * by timestamp. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3.Changelog changelogs = 1;</code> */ com.google.cloud.dialogflow.cx.v3.ChangelogOrBuilder getChangelogsOrBuilder(int index); /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ java.lang.String getNextPageToken(); /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ com.google.protobuf.ByteString getNextPageTokenBytes(); }
{ "content_hash": "3a6cdaafe9addc8817ffa64b90cfc0ff", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 103, "avg_line_length": 29.08, "alnum_prop": 0.6678129298486932, "repo_name": "googleapis/java-dialogflow-cx", "id": "d4ea06a6e9212cf57de4124ba9b93079ed8ca072", "size": "3502", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "proto-google-cloud-dialogflow-cx-v3/src/main/java/com/google/cloud/dialogflow/cx/v3/ListChangelogsResponseOrBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "801" }, { "name": "Java", "bytes": "31858414" }, { "name": "Python", "bytes": "1229" }, { "name": "Shell", "bytes": "20462" } ], "symlink_target": "" }
use inkwell::context::Context; use inkwell::values::InstructionOpcode; #[test] fn test_basic_block_ordering() { let context = Context::create(); let module = context.create_module("test"); let builder = context.create_builder(); assert!(builder.get_insert_block().is_none()); let i128_type = context.i128_type(); let fn_type = i128_type.fn_type(&[], false); let function = module.add_function("testing", fn_type, None); assert!(function.get_first_basic_block().is_none()); let basic_block = context.append_basic_block(function, "entry"); let basic_block4 = context.insert_basic_block_after(basic_block, "block4"); let basic_block2 = context.insert_basic_block_after(basic_block, "block2"); let basic_block3 = context.prepend_basic_block(basic_block4, "block3"); let basic_blocks = function.get_basic_blocks(); assert_eq!(basic_blocks.len(), 4); assert_eq!(basic_blocks[0], basic_block); assert_eq!(basic_blocks[1], basic_block2); assert_eq!(basic_blocks[2], basic_block3); assert_eq!(basic_blocks[3], basic_block4); assert!(basic_block3.move_before(basic_block2).is_ok()); assert!(basic_block.move_after(basic_block4).is_ok()); let basic_block5 = context.prepend_basic_block(basic_block, "block5"); let basic_blocks = function.get_basic_blocks(); assert_eq!(basic_blocks.len(), 5); assert_eq!(basic_blocks[0], basic_block3); assert_eq!(basic_blocks[1], basic_block2); assert_eq!(basic_blocks[2], basic_block4); assert_eq!(basic_blocks[3], basic_block5); assert_eq!(basic_blocks[4], basic_block); assert_ne!(basic_blocks[0], basic_block); assert_ne!(basic_blocks[1], basic_block3); assert_ne!(basic_blocks[2], basic_block2); assert_ne!(basic_blocks[3], basic_block4); assert_ne!(basic_blocks[4], basic_block5); context.append_basic_block(function, "block6"); let bb1 = function.get_first_basic_block().unwrap(); let bb4 = basic_block5.get_previous_basic_block().unwrap(); assert_eq!(bb1, basic_block3); assert_eq!(bb4, basic_block4); assert!(basic_block3.get_previous_basic_block().is_none()); unsafe { assert!(bb4.delete().is_ok()); } let bb2 = basic_block5.get_previous_basic_block().unwrap(); assert_eq!(bb2, basic_block2); let bb3 = function.get_first_basic_block().unwrap(); assert_eq!(bb3, basic_block3); assert_eq!(basic_block.get_name().to_str(), Ok("entry")); assert_eq!(basic_block2.get_name().to_str(), Ok("block2")); assert_eq!(basic_block3.get_name().to_str(), Ok("block3")); assert_eq!(basic_block5.get_name().to_str(), Ok("block5")); } #[test] fn test_get_basic_blocks() { let context = Context::create(); let module = context.create_module("test"); let bool_type = context.bool_type(); let fn_type = bool_type.fn_type(&[], false); let function = module.add_function("testing", fn_type, None); assert_eq!(function.get_name().to_str(), Ok("testing")); assert_eq!(fn_type.get_return_type().unwrap().into_int_type().get_bit_width(), 1); assert!(function.get_last_basic_block().is_none()); assert_eq!(function.get_basic_blocks().len(), 0); let basic_block = context.append_basic_block(function, "entry"); let last_basic_block = function .get_last_basic_block() .expect("Did not find expected basic block"); assert_eq!(last_basic_block, basic_block); let basic_blocks = function.get_basic_blocks(); assert_eq!(basic_blocks.len(), 1); assert_eq!(basic_blocks[0], basic_block); } #[test] fn test_get_terminator() { let context = Context::create(); let module = context.create_module("test"); let builder = context.create_builder(); let void_type = context.void_type(); let fn_type = void_type.fn_type(&[], false); let function = module.add_function("testing", fn_type, None); let basic_block = context.append_basic_block(function, "entry"); builder.position_at_end(basic_block); // REVIEW: What's the difference between a terminator and last instruction? assert!(basic_block.get_terminator().is_none()); assert!(basic_block.get_first_instruction().is_none()); assert!(basic_block.get_last_instruction().is_none()); builder.build_return(None); assert_eq!( basic_block.get_terminator().unwrap().get_opcode(), InstructionOpcode::Return ); assert_eq!( basic_block.get_first_instruction().unwrap().get_opcode(), InstructionOpcode::Return ); assert_eq!( basic_block.get_last_instruction().unwrap().get_opcode(), InstructionOpcode::Return ); assert_eq!(basic_block.get_last_instruction(), basic_block.get_terminator()); } #[test] fn test_no_parent() { let context = Context::create(); let module = context.create_module("test"); let void_type = context.void_type(); let fn_type = void_type.fn_type(&[], false); let function = module.add_function("testing", fn_type, None); let basic_block = context.append_basic_block(function, "entry"); let basic_block2 = context.append_basic_block(function, "next"); assert_eq!(basic_block.get_parent().unwrap(), function); assert_eq!(basic_block.get_next_basic_block().unwrap(), basic_block2); assert!(basic_block.remove_from_function().is_ok()); assert!(basic_block.get_next_basic_block().is_none()); assert!(basic_block2.get_previous_basic_block().is_none()); assert!(basic_block.remove_from_function().is_err()); assert!(basic_block.remove_from_function().is_err()); assert!(basic_block.get_parent().is_none()); } #[test] fn test_rauw() { let context = Context::create(); let builder = context.create_builder(); let module = context.create_module("my_mod"); let void_type = context.void_type(); let fn_type = void_type.fn_type(&[], false); let fn_val = module.add_function("my_fn", fn_type, None); let entry = context.append_basic_block(fn_val, "entry"); let bb1 = context.append_basic_block(fn_val, "bb1"); let bb2 = context.append_basic_block(fn_val, "bb2"); builder.position_at_end(entry); let branch_inst = builder.build_unconditional_branch(bb1); bb1.replace_all_uses_with(&bb1); // no-op bb1.replace_all_uses_with(&bb2); assert_eq!(branch_inst.get_operand(0).unwrap().right().unwrap(), bb2); } #[test] fn test_get_first_use() { let context = Context::create(); let module = context.create_module("ivs"); let builder = context.create_builder(); let void_type = context.void_type(); let fn_type = void_type.fn_type(&[], false); let fn_val = module.add_function("my_fn", fn_type, None); let entry = context.append_basic_block(fn_val, "entry"); let bb1 = context.append_basic_block(fn_val, "bb1"); let bb2 = context.append_basic_block(fn_val, "bb2"); builder.position_at_end(entry); let branch_inst = builder.build_unconditional_branch(bb1); assert!(bb2.get_first_use().is_none()); assert!(bb1.get_first_use().is_some()); assert_eq!(bb1.get_first_use().unwrap().get_user(), branch_inst); assert!(bb1.get_first_use().unwrap().get_next_use().is_none()); } #[test] fn test_get_address() { let context = Context::create(); let module = context.create_module("my_mod"); let void_type = context.void_type(); let fn_type = void_type.fn_type(&[], false); let fn_val = module.add_function("my_fn", fn_type, None); let entry_bb = context.append_basic_block(fn_val, "entry"); let next_bb = context.append_basic_block(fn_val, "next"); assert!(unsafe { entry_bb.get_address() }.is_none()); assert!(unsafe { next_bb.get_address() }.is_some()); }
{ "content_hash": "ea711bf7dde5f5f845a8f1a8f744b87c", "timestamp": "", "source": "github", "line_count": 221, "max_line_length": 86, "avg_line_length": 35.04977375565611, "alnum_prop": 0.6488510198812291, "repo_name": "TheDan64/inkwell", "id": "9d906be9c96a5bbcab45031b4e84bbcb940bacc7", "size": "7746", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/all/test_basic_block.rs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Rust", "bytes": "1006976" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>BootstrapValidator demo</title> <link rel="stylesheet" href="../vendor/bootstrap/css/bootstrap.css"/> <link rel="stylesheet" href="../dist/css/bootstrapValidator.css"/> <script type="text/javascript" src="../vendor/jquery/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="../vendor/bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript" src="../dist/js/bootstrapValidator.js"></script> </head> <body> <div class="container"> <div class="row"> <section> <div class="col-lg-8 col-lg-offset-2"> <div class="page-header"> <h2>choice validator</h2> </div> <form id="interviewForm" method="post" class="form-horizontal" action="target.php"> <div class="form-group"> <label class="col-lg-3 control-label">Programming Languages</label> <div class="col-lg-4"> <div class="checkbox"> <label> <input type="checkbox" name="languages[]" value="net" /> .Net </label> </div> <div class="checkbox"> <label> <input type="checkbox" name="languages[]" value="java" /> Java </label> </div> <div class="checkbox"> <label> <input type="checkbox" name="languages[]" value="c" /> C/C++ </label> </div> <div class="checkbox"> <label> <input type="checkbox" name="languages[]" value="php" /> PHP </label> </div> <div class="checkbox"> <label> <input type="checkbox" name="languages[]" value="perl" /> Perl </label> </div> <div class="checkbox"> <label> <input type="checkbox" name="languages[]" value="ruby" /> Ruby </label> </div> <div class="checkbox"> <label> <input type="checkbox" name="languages[]" value="python" /> Python </label> </div> <div class="checkbox"> <label> <input type="checkbox" name="languages[]" value="javascript" /> Javascript </label> </div> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label">Editors</label> <div class="col-lg-4"> <select class="form-control" name="editors[]" multiple="multiple" style="height: 200px;"> <option value="" disabled>Choose 2 - 3 editors</option> <option value="atom">Atom</option> <option value="eclipse">Eclipse</option> <option value="netbeen">NetBean</option> <option value="nodepadplusplus">Nodepad++</option> <option value="phpstorm">PHP Storm</option> <option value="sublime">Sublime</option> <option value="webstorm">Web Storm</option> </select> </div> </div> <div class="form-group"> <div class="col-lg-9 col-lg-offset-3"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> </div> </section> </div> </div> <script type="text/javascript"> $(document).ready(function() { $('#interviewForm').bootstrapValidator({ feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { 'languages[]': { validators: { choice: { min: 2, max: 4, message: 'Please choose %s - %s programming languages you are good at' } } }, 'editors[]': { validators: { choice: { min: 2, max: 3, message: 'Please choose %s - %s editors you know' } } } } }); }); </script> </body> </html>
{ "content_hash": "a87263cc85122324e46214985ba4f801", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 121, "avg_line_length": 45.2578125, "alnum_prop": 0.3550837217331262, "repo_name": "BUKMAR/Mart24", "id": "27d10aecc31f9bb21282bb6536e4b0e8ccd4ef3c", "size": "5793", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/node_modules/bootstrapvalidator/demo/choice.html", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "37559" }, { "name": "HTML", "bytes": "8276744" }, { "name": "JavaScript", "bytes": "56182" }, { "name": "PHP", "bytes": "1878582" } ], "symlink_target": "" }
package me.tikitoo.androiddemo.utils; public class FileUtils { }
{ "content_hash": "1df2ee3e7ebdb9a2e007418ab596b71c", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 37, "avg_line_length": 16.5, "alnum_prop": 0.7878787878787878, "repo_name": "Tikitoo/androidsamples", "id": "4424e6b2dce4de6c5ca83bfc0dd054ecc784eb3e", "size": "66", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/me/tikitoo/androiddemo/utils/FileUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1744" }, { "name": "Java", "bytes": "128274" } ], "symlink_target": "" }
package jast import ( "go/ast" "go/types" ) // New creates a new jast cache. func New(imports map[string]string, uses map[*ast.Ident]types.Object) *Cache { if (imports == nil && uses == nil) || (imports != nil && uses != nil) { panic("must specify either imports or uses but not both") } return &Cache{ imports: imports, uses: uses, } } type Cache struct { imports map[string]string uses map[*ast.Ident]types.Object }
{ "content_hash": "48566fdfa2a4788211eeb10d07e13b4d", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 78, "avg_line_length": 20.045454545454547, "alnum_prop": 0.655328798185941, "repo_name": "frizz/frizz", "id": "6e8f726a76f7d18ab822f76147da09a84ac62913", "size": "577", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "generate/jast/jast.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "448359" }, { "name": "Shell", "bytes": "7258" } ], "symlink_target": "" }
@interface NaturvielfaltAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> { UIWindow *window; UITabBarController *tabBarController; } @property (nonatomic) IBOutlet UIWindow *window; @property (nonatomic) IBOutlet UITabBarController *tabBarController; @end
{ "content_hash": "615e59f4baa270efec7c9ef22b9480e6", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 100, "avg_line_length": 32.44444444444444, "alnum_prop": 0.8116438356164384, "repo_name": "naturwerk/naturvielfalt_iphone", "id": "1f2e66a60a90bccbc5d21393580394004cf404d4", "size": "475", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Naturvielfalt/NaturvielfaltAppDelegate.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Objective-C", "bytes": "698327" } ], "symlink_target": "" }
#ifndef __itkHoughTransform2DCirclesImageFilter_h #define __itkHoughTransform2DCirclesImageFilter_h #include "itkImageToImageFilter.h" #include "itkEllipseSpatialObject.h" namespace itk { /** * \class HoughTransform2DCirclesImageFilter * \brief Performs the Hough Transform to find circles in a 2D image. * * This filter derives from the base class ImageToImageFilter. * The input is an image, and all pixels above some threshold are those * we want to consider during the process. * * This filter produces two output: * 1) The accumulator array, which represents probability of centers. * 2) The array or radii, which has the radius value at each coordinate point. * * When the filter finds a "correct" point, it computes the gradient at this * point and draws a regular narrow-banded circle using the minimum and maximum * radius given by the user, and fills in the array of radii. * The SweepAngle value can be adjusted to improve the segmentation. * * \ingroup ImageFeatureExtraction * * \ingroup ITKImageFeature * * \wiki * \wikiexample{Conversions/HoughTransform2DCirclesImageFilter,HoughTransform2DCirclesImageFilter} * \endwiki */ template< typename TInputPixelType, typename TOutputPixelType > class ITK_EXPORT HoughTransform2DCirclesImageFilter: public ImageToImageFilter< Image< TInputPixelType, 2 >, Image< TOutputPixelType, 2 > > { public: /** Standard "Self" typedef. */ typedef HoughTransform2DCirclesImageFilter Self; /** Input Image typedef */ typedef Image< TInputPixelType, 2 > InputImageType; typedef typename InputImageType::Pointer InputImagePointer; typedef typename InputImageType::ConstPointer InputImageConstPointer; /** Output Image typedef */ typedef Image< TOutputPixelType, 2 > OutputImageType; typedef typename OutputImageType::Pointer OutputImagePointer; /** Standard "Superclass" typedef. */ typedef ImageToImageFilter< Image< TInputPixelType, 2 >, Image< TOutputPixelType, 2 > > Superclass; /** Smart pointer typedef support. */ typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; /** Image index typedef */ typedef typename InputImageType::IndexType IndexType; /** Image pixel value typedef */ typedef typename InputImageType::PixelType PixelType; /** Typedef to describe the output image region type. */ typedef typename InputImageType::RegionType OutputImageRegionType; /** Circle typedef */ typedef EllipseSpatialObject< 2 > CircleType; typedef typename CircleType::Pointer CirclePointer; typedef std::list< CirclePointer > CirclesListType; typedef typename CirclesListType::size_type CirclesListSizeType; /** Run-time type information (and related methods). */ itkTypeMacro(HoughTransform2DCirclesImageFilter, ImageToImageFilter); /** Method for creation through the object factory. */ itkNewMacro(Self); /** Method for evaluating the implicit function over the image. */ void GenerateData(); /** Set both Minimum and Maximum radius values */ void SetRadius(double radius); /** Set the minimum radiu value the filter should look for */ itkSetMacro(MinimumRadius, double); itkGetConstMacro(MinimumRadius, double); /** Set the maximum radius value the filter should look for */ itkSetMacro(MaximumRadius, double); itkGetConstMacro(MaximumRadius, double); /** Set the gradient factor for object detection */ itkSetMacro(GradientFactor, double); itkGetConstMacro(GradientFactor, double); /** Set the threshold above which the filter should consider the point as a valid point */ itkSetMacro(Threshold, double); /** Get the threshold value */ itkGetConstMacro(Threshold, double); /** Get the radius image */ itkGetObjectMacro(RadiusImage, OutputImageType); /** Set the scale of the derivative function (using DoG) */ itkSetMacro(SigmaGradient, double); /** Get the scale value */ itkGetConstMacro(SigmaGradient, double); /** Get the list of circles. This recomputes the circles */ CirclesListType & GetCircles(unsigned int n = 0); /** Set/Get the number of circles to extract */ itkSetMacro(NumberOfCircles, unsigned int); itkGetConstMacro(NumberOfCircles, unsigned int); /** Set/Get the radius of the disc to remove from the accumulator * for each circle found */ itkSetMacro(DiscRadiusRatio, float); itkGetConstMacro(DiscRadiusRatio, float); /** Set the variance of the gaussian bluring for the accumulator */ itkSetMacro(Variance, float); itkGetConstMacro(Variance, float); /** Set the sweep angle */ itkSetMacro(SweepAngle, float); itkGetConstMacro(SweepAngle, float); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro( IntConvertibleToOutputCheck, ( Concept::Convertible< int, TOutputPixelType > ) ); itkConceptMacro( InputGreaterThanDoubleCheck, ( Concept::GreaterThanComparable< PixelType, double > ) ); itkConceptMacro( OutputPlusIntCheck, ( Concept::AdditiveOperators< TOutputPixelType, int > ) ); itkConceptMacro( OutputDividedByIntCheck, ( Concept::DivisionOperators< TOutputPixelType, int > ) ); /** End concept checking */ #endif protected: HoughTransform2DCirclesImageFilter(); virtual ~HoughTransform2DCirclesImageFilter() {} void PrintSelf(std::ostream & os, Indent indent) const; /** HoughTransform2DCirclesImageFilter needs the entire input. Therefore * it must provide an implementation GenerateInputRequestedRegion(). * \sa ProcessObject::GenerateInputRequestedRegion(). */ void GenerateInputRequestedRegion(); /** HoughTransform2DCirclesImageFilter's produces all the output. * Therefore, it must provide an implementation of * EnlargeOutputRequestedRegion. * \sa ProcessObject::EnlargeOutputRequestedRegion() */ void EnlargeOutputRequestedRegion( DataObject *itkNotUsed(output) ); private: HoughTransform2DCirclesImageFilter(const Self &); void operator=(const Self &); float m_SweepAngle; double m_MinimumRadius; double m_MaximumRadius; double m_Threshold; double m_SigmaGradient; double m_GradientFactor; // modif OutputImagePointer m_RadiusImage; CirclesListType m_CirclesList; CirclesListSizeType m_NumberOfCircles; float m_DiscRadiusRatio; float m_Variance; ModifiedTimeType m_OldModifiedTime; CirclesListSizeType m_OldNumberOfCircles; }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkHoughTransform2DCirclesImageFilter.hxx" #endif #endif
{ "content_hash": "c263bfb8f757fd27a3bbce7cb22f7415", "timestamp": "", "source": "github", "line_count": 198, "max_line_length": 98, "avg_line_length": 34.535353535353536, "alnum_prop": 0.7209710441649605, "repo_name": "3324fr/spinalcordtoolbox", "id": "6e5e390c883cb9e46eb1c754a11f92ad58ec1eca", "size": "7629", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dev/sct_detect_spinalcord/itkHoughTransform2DCirclesImageFilter.h", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "5961" }, { "name": "C++", "bytes": "1025992" }, { "name": "CMake", "bytes": "18919" }, { "name": "CSS", "bytes": "1384" }, { "name": "Groff", "bytes": "3141" }, { "name": "HTML", "bytes": "5315" }, { "name": "JavaScript", "bytes": "2505" }, { "name": "KiCad", "bytes": "5522" }, { "name": "Matlab", "bytes": "275100" }, { "name": "Python", "bytes": "4808677" }, { "name": "Shell", "bytes": "193192" } ], "symlink_target": "" }
MICROSERVICES = { # Map specific device types to a list of microservices "DEVICE_MICROSERVICES": { # Gateways 10031: [ {"module": "intelligence.daylight.device_daylight_microservice", "class": "DaylightMicroservice"}, ], # Gateways 31: [ {"module": "intelligence.daylight.device_daylight_microservice", "class": "DaylightMicroservice"}, ] }, "LOCATION_MICROSERVICES": [ { "module": "intelligence.daylight.location_midnight_microservice", "class": "LocationMidnightMicroservice" } ] }
{ "content_hash": "6447fcc9002bae3863df4229b99eb060", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 110, "avg_line_length": 29.952380952380953, "alnum_prop": 0.5739268680445151, "repo_name": "peoplepower/composer-sdk-python", "id": "81ce01987b54b1a936e8fb9e0ad9b7bf3ac0e7de", "size": "629", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "com.ppc.Microservices/intelligence/daylight/index.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "170609" }, { "name": "Shell", "bytes": "22591" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.aethersanctum.lilrest.config; import com.google.inject.AbstractModule; /** */ public class ConfigModule extends AbstractModule { @Override protected void configure() { bind(ConfigFactory.class).asEagerSingleton(); } }
{ "content_hash": "e1920069d175bdfbc82eb8e8746b7d04", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 75, "avg_line_length": 31.23076923076923, "alnum_prop": 0.7376847290640394, "repo_name": "benhardy/lilrest", "id": "b255381c3daa9acc94de49fdcd6ff0af505d9e3f", "size": "812", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/src/main/java/net/aethersanctum/lilrest/config/ConfigModule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "28294" } ], "symlink_target": "" }
SimpleWebDocumentViewer ======================= Simple web document viewer that is used to easily show a document(pdf,swf,doc etc) on a web page. This is a simple control built using C# and .NET. Features ----------------------- 1. The document viewer is built using WebControl and C#. 2. The document viewer has a FilePath property and the path name of the document will be assigned to this property.
{ "content_hash": "852a5b33ca17ea82aebb17fa947992e4", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 147, "avg_line_length": 36.90909090909091, "alnum_prop": 0.6921182266009852, "repo_name": "ambremandar/SimpleWebDocumentViewer", "id": "b8a0a557f023100b44a5301ee61ac9f9c37b9cae", "size": "406", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "1568" }, { "name": "C#", "bytes": "4741" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "9aca548bea9f4530c5e9a3f8e559657c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "e19c343dc1e2d63073d855158e4a140cc0ce3bc3", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Gesneriaceae/Cyrtandra/Cyrtandra picta/Cyrtandra picta ovatifolia/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'vendor/state_pattern/lib')) require 'state_pattern'
{ "content_hash": "8ed1b35f4dfdd59dd5327642dd024237", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 81, "avg_line_length": 35.666666666666664, "alnum_prop": 0.7289719626168224, "repo_name": "dcadenas/active_record_state_pattern", "id": "61919186fd0b7d576f87eea0d2311c9a85700c01", "size": "107", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "init.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "3253" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace StructType; use InvalidArgumentException; use WsdlToPhp\PackageBase\AbstractStructBase; /** * This class stands for ClientAccessTokenType StructType * @package Ews * @subpackage Structs * @author WsdlToPhp <contact@wsdltophp.com> */ class EwsClientAccessTokenType extends AbstractStructBase { /** * The Id * @var string|null */ protected ?string $Id = null; /** * The TokenType * @var string|null */ protected ?string $TokenType = null; /** * The TokenValue * @var string|null */ protected ?string $TokenValue = null; /** * The TTL * @var int|null */ protected ?int $TTL = null; /** * Constructor method for ClientAccessTokenType * @uses EwsClientAccessTokenType::setId() * @uses EwsClientAccessTokenType::setTokenType() * @uses EwsClientAccessTokenType::setTokenValue() * @uses EwsClientAccessTokenType::setTTL() * @param string $id * @param string $tokenType * @param string $tokenValue * @param int $tTL */ public function __construct(?string $id = null, ?string $tokenType = null, ?string $tokenValue = null, ?int $tTL = null) { $this ->setId($id) ->setTokenType($tokenType) ->setTokenValue($tokenValue) ->setTTL($tTL); } /** * Get Id value * @return string|null */ public function getId(): ?string { return $this->Id; } /** * Set Id value * @param string $id * @return \StructType\EwsClientAccessTokenType */ public function setId(?string $id = null): self { // validation for constraint: string if (!is_null($id) && !is_string($id)) { throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($id, true), gettype($id)), __LINE__); } $this->Id = $id; return $this; } /** * Get TokenType value * @return string|null */ public function getTokenType(): ?string { return $this->TokenType; } /** * Set TokenType value * @uses \EnumType\EwsClientAccessTokenTypeType::valueIsValid() * @uses \EnumType\EwsClientAccessTokenTypeType::getValidValues() * @throws InvalidArgumentException * @param string $tokenType * @return \StructType\EwsClientAccessTokenType */ public function setTokenType(?string $tokenType = null): self { // validation for constraint: enumeration if (!\EnumType\EwsClientAccessTokenTypeType::valueIsValid($tokenType)) { throw new InvalidArgumentException(sprintf('Invalid value(s) %s, please use one of: %s from enumeration class \EnumType\EwsClientAccessTokenTypeType', is_array($tokenType) ? implode(', ', $tokenType) : var_export($tokenType, true), implode(', ', \EnumType\EwsClientAccessTokenTypeType::getValidValues())), __LINE__); } $this->TokenType = $tokenType; return $this; } /** * Get TokenValue value * @return string|null */ public function getTokenValue(): ?string { return $this->TokenValue; } /** * Set TokenValue value * @param string $tokenValue * @return \StructType\EwsClientAccessTokenType */ public function setTokenValue(?string $tokenValue = null): self { // validation for constraint: string if (!is_null($tokenValue) && !is_string($tokenValue)) { throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($tokenValue, true), gettype($tokenValue)), __LINE__); } $this->TokenValue = $tokenValue; return $this; } /** * Get TTL value * @return int|null */ public function getTTL(): ?int { return $this->TTL; } /** * Set TTL value * @param int $tTL * @return \StructType\EwsClientAccessTokenType */ public function setTTL(?int $tTL = null): self { // validation for constraint: int if (!is_null($tTL) && !(is_int($tTL) || ctype_digit($tTL))) { throw new InvalidArgumentException(sprintf('Invalid value %s, please provide an integer value, %s given', var_export($tTL, true), gettype($tTL)), __LINE__); } $this->TTL = $tTL; return $this; } }
{ "content_hash": "036227d1d9a048ab1ca57201e474843f", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 328, "avg_line_length": 29.625, "alnum_prop": 0.5969353764157228, "repo_name": "WsdlToPhp/PackageEws365", "id": "ddc599c605b6d8f0b6c2c01f45546f07fe4007f2", "size": "4503", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/StructType/EwsClientAccessTokenType.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "6415903" }, { "name": "Shell", "bytes": "1190" } ], "symlink_target": "" }
/*global history*/ jQuery.sap.require("StationTimetable/util/Configuration"); jQuery.sap.require("sap.m.MessageBox"); sap.ui.define([ 'StationTimetable/view/BaseController' ], function( BaseController) { "use strict"; return BaseController.extend("StationTimetable.view.admin.ModifyTrainM", { onInit : function() { BaseController.prototype.onInit.apply(this, arguments); this._oView.getModel().setDefaultBindingMode(sap.ui.model.BindingMode.TwoWay); this._df = sap.ui.core.format.DateFormat.getTimeInstance({ pattern: "dd-MM-yyyy" }); this._dfBackend = sap.ui.core.format.DateFormat.getTimeInstance({ pattern: "yyyy.MM.dd" }); this.getStationNameDropdown().setSelectedKey(this.getStationNameDropdown().getItems()[0].getKey()); this.getTrainCountLabel().addStyleClass("trainCountM"); //used to keep a reference to the Date corresponding to the last shown info this._showDataForDate = new Date(); var oRouter = this.getRouter(); oRouter.getRoute("ModifyTrainM").attachMatched(this._onRouteMatched, this); }, onBeforeRendering: function() { this.getTrainCountContainer().addStyleClass("trainCountContainers"); }, _onRouteMatched: function() { this.getDeparturePicker().setValue(this._df.format(this._showDataForDate)); var requestDate = this._dfBackend.format(this._showDataForDate); this._requestData(requestDate); }, getDeparturePicker: function() { return this._oView.byId("departurePicker"); }, getDepartureLabel: function() { return this._oView.byId("dateOfDeparture"); }, getTable: function() { return this._oView.byId("ModifyTimetableM"); }, getTrainCountLabel: function() { return this._oView.byId("trainCount"); }, getTrainCountContainer: function() { return this._oView.byId("trainCountContainer"); }, getStationNameDropdown: function() { return this._oView.byId("stationDropdown"); }, forward: function() { var departurePicker=this.getDeparturePicker(); var oDate = departurePicker.getDateValue(); oDate.setDate(oDate.getDate() + 1); this.getTrainCountContainer().setVisible(false); var that = this; var callback = function() { departurePicker.setValue(that._df.format(oDate)); }; this._showDataForDate = oDate; this._requestData(this._dfBackend.format(oDate), callback); }, backward: function() { var departurePicker=this.getDeparturePicker(); var oDate = departurePicker.getDateValue(); oDate.setDate(oDate.getDate() - 1); this.getTrainCountContainer().setVisible(false); var that = this; var callback = function() { departurePicker.setValue(that._df.format(oDate)); }; this._showDataForDate = oDate; this._requestData(this._dfBackend.format(oDate), callback); }, _requestData: function(requestDate, scCallback) { var that = this; that.getView().setBusy(true); var stationName = that.getStationNameDropdown().getSelectedKey() || "КРИВОДОЛ"; setTimeout(function() { var url = Configuration.servicesURL + "departures?stationName=" + stationName + "&date=" + requestDate; jQuery.get(encodeURI(url)). done(function(data){ that.getView().setBusy(false); that.getTrainCountContainer().setVisible(true); that._oView.getModel().setData(data.data); //that.getDepartureLabel().setText("ПРОМЯНА НА РАЗПИСАНИЕ НА ЗАМИНАВАЩИ ЗА ДАТА: " + that._df.format(that._dfBackend.parse(requestDate)) + ". Брой влакове: " + data.data.length); that.getTrainCountLabel().setText(data.data.length); if (scCallback) { scCallback(); } }). fail(function() { that.getView().setBusy(false); this.getTrainCountContainer().setVisible(true); sap.m.MessageBox.show( "Данните за дата " + requestDate + " не успяха да се заредят.", { icon: sap.m.MessageBox.Icon.ERROR, title: "Неуспешно зареждане" } ); }); },0); }, onDateChange: function(event) { var requestDate = this._dfBackend.format(event.oSource.getDateValue()); this._requestData(requestDate); }, onTimeChanged: function(e) { var bc = e.oSource.getParent().getBindingContext(); var oldDepartures = new Date(this._oView.getModel().getProperty(bc.sPath + "/departures")); var newTime = this._dfBackend.parse(e.getParameter("newValue")); var newDepartures = oldDepartures; newDepartures.setHours(newTime.getHours()); newDepartures.setMinutes(newTime.getMinutes()); this._oView.getModel().setProperty(bc.sPath +"/departures", newDepartures.getTime()); }, onStationChange: function(oSelectedItem) { var departurePicker=this.getDeparturePicker(); var oDate = departurePicker.getDateValue(); var that = this; var callback = function() { departurePicker.setValue(that._df.format(oDate)); }; this._requestData(this._dfBackend.format(oDate), callback); }, updateTrain: function(event) { var that = this; that.getTable().setBusy(true); var t = event.oSource.getParent().getBindingContext(); var oData = this._oView.getModel().getProperty(t.sPath); oData.to = getDirectionForRow(event.getSource().getId()).getValue(); oData.delay = getDelayForRow(event.getSource().getId()).getValue(); oData.lane = getLaneForRow(event.getSource().getId()).getValue(); jQuery.ajax({ type: "POST", url: Configuration.services.updateTrain, data: JSON.stringify(oData), contentType: "application/json; charset=UTF-8" }).done(function(){ that.getTable().setBusy(false); sap.m.MessageBox.show( "Данните за влак " + oData.trainNumber + " са променени успешно.", { icon: sap.m.MessageBox.Icon.SUCCESS, title: "Промяна на разписание" }); }).fail(function(){ that.getTable().setBusy(false); sap.m.MessageBox.show( "Данните за влак " + oData.trainNumber + " не са променени. Моля опитайте пак по-късно", { icon: sap.m.MessageBox.Icon.ERROR, title: "Промяна на разписание" }); }); function getTimePickerForRow(sButtonID) { var sIndex = sButtonID.substr(sButtonID.indexOf("clone")); return that._oView.byId("timeValue-__" + sIndex); } function getLaneForRow(sButtonID) { var sIndex = sButtonID.substr(sButtonID.indexOf("clone")); return that._oView.byId("laneValue-__" + sIndex); } function getDirectionForRow(sButtonID) { var sIndex = sButtonID.substr(sButtonID.indexOf("clone")); return that._oView.byId("directionValue-__" + sIndex); } function getDelayForRow(sButtonID) { var sIndex = sButtonID.substr(sButtonID.indexOf("clone")); return that._oView.byId("delayValue-__" + sIndex); } }, onListItemPressed : function(oEvent){ var oItem, oCtx, oData, oDetailsPageModel; oItem = oEvent.getSource(); oCtx = oItem.getBindingContext(); oData = this.getView().getModel().getProperty(oCtx.getPath()); oDetailsPageModel = new sap.ui.model.json.JSONModel(oData); sap.ui.getCore().setModel(oDetailsPageModel, "trainDetails"); this.getRouter().navTo("TrainDetailsM"); } }); });
{ "content_hash": "bcf7e82b80bb63583ad7b253b30c487b", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 183, "avg_line_length": 34.333333333333336, "alnum_prop": 0.6765603328710125, "repo_name": "awolfish/timetableservices", "id": "18e2ee04a10b1c7ae3115d4a61ac6fa5c0bc0cd6", "size": "7433", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/src/main/webapp/view/admin/ModifyTrainM.controller.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "424" }, { "name": "CSS", "bytes": "5359" }, { "name": "HTML", "bytes": "8903" }, { "name": "Java", "bytes": "257249" }, { "name": "JavaScript", "bytes": "81011" }, { "name": "Shell", "bytes": "401" } ], "symlink_target": "" }
package org.apache.sqoop.json; import org.apache.sqoop.classification.InterfaceAudience; import org.apache.sqoop.classification.InterfaceStability; import org.json.simple.JSONObject; @InterfaceAudience.Private @InterfaceStability.Unstable public interface JsonBean { // common JSON constants for the rest-api response static final String CONFIGURABLE_VERSION = "version"; static final String ALL_CONFIGS= "all-config-resources"; @Deprecated // should not be used anymore in the rest api static final String ALL = "all"; static final String ID = "id"; static final String NAME = "name"; static final String CLASS = "class"; static final String ENABLED = "enabled"; static final String CREATION_USER = "creation-user"; static final String CREATION_DATE = "creation-date"; static final String UPDATE_USER = "update-user"; static final String UPDATE_DATE = "update-date"; JSONObject extract(boolean skipSensitive); void restore(JSONObject jsonObject); public static final JsonBean EMPTY_BEAN = new JsonBean() { @Override public JSONObject extract(boolean skipSensitive) { return new JSONObject(); } @Override public void restore(JSONObject jsonObject) { } }; }
{ "content_hash": "d3e0b34eae66f2456a595c7cf1f6bc85", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 60, "avg_line_length": 29.30952380952381, "alnum_prop": 0.7416734362307067, "repo_name": "vybs/sqoop-on-spark", "id": "1dd275e80df25b3521bb20dd31e4e2221db50ff8", "size": "2037", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/src/main/java/org/apache/sqoop/json/JsonBean.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "839" }, { "name": "HTML", "bytes": "1805" }, { "name": "Java", "bytes": "2943639" }, { "name": "Python", "bytes": "16985" }, { "name": "Shell", "bytes": "11266" } ], "symlink_target": "" }
package example.service; import example.repo.Customer577Repository; import org.springframework.stereotype.Service; @Service public class Customer577Service { public Customer577Service(Customer577Repository repo) {} }
{ "content_hash": "64603f6478d9d6e18f3c68a6ba62fab8", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 57, "avg_line_length": 22.1, "alnum_prop": 0.8371040723981901, "repo_name": "spring-projects/spring-data-examples", "id": "3b50566cbfabf5ae117ecf827cc7b28b27856e2f", "size": "221", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "jpa/deferred/src/main/java/example/service/Customer577Service.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "407" }, { "name": "HTML", "bytes": "11754" }, { "name": "Java", "bytes": "3549318" }, { "name": "Kotlin", "bytes": "25902" } ], "symlink_target": "" }
{% extends "lifestream_base.html" %} {% load hyperbola_lifestream_tags %} {% block title %} {{ block.super }} {% if posts.number != 1 %} :: page {{ posts.number|escape }} {% endif %} {% endblock title %} {% block lifestream_content %} {% for post in posts %} <div class="card mb-3 rounded"> {% if post.lifestreampicture %} <a href="{{ post.lifestreampicture.picture.url|escape }}"> <img class="card-img-top img-thumbnail" alt="Photo for post {{ post.id|escape }}" src="{{ post.lifestreampicture.picture.x1.url|escape }}" srcset="{{ post.lifestreampicture.picture.x1.url|escape }} 1x, {{ post.lifestreampicture.picture.x2.url|escape }} 2x, {{ post.lifestreampicture.picture.x3.url|escape }} 3x"> </a> {% endif %} <div class="card-body"> <small class="card-subtitle"> <local-time datetime="{{ post.pub_date|date:"Y-m-d" }}T{{ post.pub_date|time:"H:i:s" }}Z" month="short" day="numeric" year="numeric" hour="numeric" minute="numeric"> {{ post.pub_date|date:"H:i T b d Y"|lower }} </local-time> <a href="{{ post.get_absolute_url|escape }}">permalink</a> </small> <p class="card-text lifestream-content">{{ post.blurb|urlize|hashtagize }}</p> </div> </div> {% endfor %} <div class="d-flex flex-row justify-content-between"> {% if links.newer %} <a href="{{ links.newer|escape }}">&laquo; newer</a> {% endif %} <span></span> {% if links.older %} <a href="{{ links.older|escape }}">older &raquo;</a> {% endif %} </div> {% endblock lifestream_content %}
{ "content_hash": "470af2a62bcc2af080d85e3fdf2242ff", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 316, "avg_line_length": 42.111111111111114, "alnum_prop": 0.6286279683377308, "repo_name": "lopopolo/hyperbola", "id": "75c49f4a342bb7b665b740a0ec14e02a71a0a3c7", "size": "1516", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hyperbola/lifestream/templates/lifestream_paged.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6635" }, { "name": "HCL", "bytes": "46861" }, { "name": "HTML", "bytes": "11186" }, { "name": "JavaScript", "bytes": "1755" }, { "name": "Python", "bytes": "56014" }, { "name": "Shell", "bytes": "1297" } ], "symlink_target": "" }
class UploadsController < ApplicationController http_basic_authenticate_with name: 'user', password: 'password' def create head 201 end end
{ "content_hash": "34ab2bbd4b22d724384173025f9c384a", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 65, "avg_line_length": 21.571428571428573, "alnum_prop": 0.7549668874172185, "repo_name": "zipmark/rspec_api_documentation", "id": "8855a415a114b5d90448769422253bcb7879ca20", "size": "151", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/app/controllers/uploads_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2237" }, { "name": "Gherkin", "bytes": "98527" }, { "name": "HTML", "bytes": "16689" }, { "name": "JavaScript", "bytes": "664" }, { "name": "Ruby", "bytes": "217295" } ], "symlink_target": "" }
from unittest import expectedFailure from .. utils import TranspileTestCase, BuiltinFunctionTestCase class TypeTests(TranspileTestCase): @expectedFailure def test_dynamic_class_definitions_leak_state(self): self.assertCodeExecution(""" my_class_obj = type("MyClass", (object,), {}) print("my_class_obj: ", my_class_obj) obj = object print("obj: ", object) dynamic_obj = type("object", (object,), {}) print("dynamic_obj: ", dynamic_obj) # Check state leak print("my_class_obj: ", my_class_obj) print("obj: ", obj) """) class BuiltinTypeFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["type"] not_implemented = [ ]
{ "content_hash": "2107172af3046aca1acaca828d718c27", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 75, "avg_line_length": 26.366666666666667, "alnum_prop": 0.5967130214917825, "repo_name": "freakboy3742/voc", "id": "1803e4cb44ac9c5b6f2b77887ff43c94f793d20f", "size": "791", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "tests/builtins/test_type.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "1016347" }, { "name": "Python", "bytes": "1167243" } ], "symlink_target": "" }
import { connect } from 'react-redux'; import { selectRecentHistory } from 'redux/selectors/content'; import RecentUserHistory from './view'; const select = (state, props) => ({ history: selectRecentHistory(state), }); export default connect( select, null )(RecentUserHistory);
{ "content_hash": "438408ccf4e20cab37eb10455609bb0d", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 62, "avg_line_length": 23.833333333333332, "alnum_prop": 0.7237762237762237, "repo_name": "lbryio/lbry-app", "id": "5d43822f6bd9f6ef665853f579fb35b504238485", "size": "286", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ui/component/navigationHistoryRecent/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "56472" }, { "name": "HTML", "bytes": "4564" }, { "name": "JavaScript", "bytes": "589537" } ], "symlink_target": "" }
namespace { using converter::Metadata; converter::ETWConsumer consumer; converter::CTFProducer producer; void WINAPI ProcessEvent(PEVENT_RECORD pevent) { assert(pevent != NULL); consumer.ProcessEvent(pevent); while (consumer.IsFullPacketReady()) { // Write the full packet into the current stream. Metadata::Packet output; consumer.BuildFullPacket(&output); const char* raw = reinterpret_cast<const char*>(output.raw_bytes()); if (!producer.Write(raw, output.size())) { std::cerr << "Cannot write packet into stream." << std::endl; return; } } } void FlushEvents() { while (!consumer.IsSendingQueueEmpty()) { // Write the full packet into the current stream. Metadata::Packet output; consumer.BuildFullPacket(&output); const char* raw = reinterpret_cast<const char*>(output.raw_bytes()); if (!producer.Write(raw, output.size())) { std::cerr << "Cannot write packet into stream." << std::endl; return; } } } ULONG WINAPI ProcessBuffer(PEVENT_TRACE_LOGFILEW ptrace) { assert(ptrace != NULL); // Close the previous stream. producer.CloseStream(); // Open the next buffer. std::wstring stream_name; if (!consumer.GetBufferName(ptrace, &stream_name)) { std::wcerr << L"Cannot get buffer name." << std::endl; return FALSE; } if (!producer.OpenStream(stream_name)) { std::wcerr << L"Cannot open output stream: \"" << stream_name << L"\"" << std::endl; return FALSE; } if (!consumer.ProcessBuffer(ptrace)) return FALSE; return TRUE; } bool FileExists(const std::wstring& path) { DWORD attrib = GetFileAttributes(path.c_str()); return (attrib != INVALID_FILE_ATTRIBUTES && !(attrib & FILE_ATTRIBUTE_DIRECTORY)); } struct Options { bool help; bool overwrite; std::wstring output; bool split_buffer; size_t packet_size; std::vector<std::wstring> files; }; void DefaultOptions(Options* options) { assert(options != NULL); options->help = false; options->output = L"ctf"; options->overwrite = false; options->split_buffer = false; options->packet_size = 4096; } bool ParseOptions(int argc, wchar_t** argv, Options* options) { assert(argv != NULL); assert(options != NULL); // Activate help when no arguments. if (argc == 1) { options->help = true; return true; } for (int i = 1; i < argc; ++i) { std::wstring arg(argv[i]); // Not an option, push it as a file to process. if (!arg.empty() && arg[0] != '-') { // Check whether the file exists. if (!FileExists(arg)) { std::wcerr << "File doesn't exist: \"" << arg << "\"" << std::endl; return false; } options->files.push_back(arg); continue; } // Next argument may be a parameter. std::wstring param; if (i + 1 < argc) param = argv[i + 1]; if (arg == L"-h" || arg == L"--help") { options->help = true; continue; } if (arg == L"--output" && !param.empty()) { options->output = param; ++i; continue; } if (arg == L"--overwrite") { options->overwrite = true; continue; } if (arg == L"--split-buffer") { options->split_buffer = true; continue; } if (arg == L"--packet-size") { std::string p(param.begin(), param.end()); int size = atoi(p.c_str()); if (size <= 1) { std::wcerr << "Invalid packet size '" << param << "'" << std::endl; return false; } ++i; options->packet_size = size; continue; } std::wcerr << L"Unknown argument: \"" << arg << L"\"" << std::endl; return false; } return true; } void PrintUsage() { std::wcerr << "\n" << " USAGE: etw2ctf [options] <traces.etl>*\n" << "\n" << " [options]\n" << " --help\n" << " Print this message.\n" << " --output [dir]\n" << " Specify the output directory for the produced CTF trace.\n" << " --overwrite\n" << " Overwrite the output directory.\n" << " --split-buffer\n" << " Split each ETW buffers in a separate CTF stream.\n" << " --packet-size <size>\n" << " Split CTF stream into CTF packets of <size> bytes.\n" << "\n" << std::endl; } } // namespace int wmain(int argc, wchar_t** argv) { struct Options options; // Initialize options with default values. DefaultOptions(&options); // Parse command-line options. if (!ParseOptions(argc, argv, &options)) return -1; // Print usage when requested or command-line empty. if (options.help) { PrintUsage(); return 0; } // Open the output folder. if (!producer.OpenFolder(options.output, options.overwrite)) { std::wcerr << L"Cannot open output directory \"" << options.output << L"\"" << std::endl; return -1; } // Add traces to be consumed to the consumer. for (std::vector<std::wstring>::iterator it = options.files.begin(); it != options.files.end(); ++it) { consumer.AddTraceFile(*it); } // No trace files to consume. if (consumer.Empty()) return 0; consumer.SetEventCallback(ProcessEvent); if (options.split_buffer) consumer.SetBufferCallback(ProcessBuffer); consumer.set_packet_maximal_size(options.packet_size); // Consume trace files. if (!producer.OpenStream(L"stream")) { std::wcerr << L"Cannot open output stream." << std::endl; return -1; } // Consume all events. The ETW API will call our registered callbacks on // each buffer and each event. Callbacks forward the processing to the // consumer via ProcessEvent and ProcessBuffer. After the processing of each // event by the consumer, the packet (encoded event) is written to the // producer. if (!consumer.ConsumeAllEvents()) { std::wcerr << L"Could not consume traces files." << std::endl; return -1; } FlushEvents(); producer.CloseStream(); // Serialize the metadata build during events processing. if (!producer.OpenStream(L"metadata")) { std::wcerr << L"Cannot open metadata stream." << std::endl; return -1; } std::string metadata; if (!consumer.SerializeMetadata(&metadata)) return -1; if (!producer.Write(metadata.c_str(), metadata.size())) return -1; producer.CloseStream(); return 0; }
{ "content_hash": "454604072a84c43f36761fdf45d16bb8", "timestamp": "", "source": "github", "line_count": 250, "max_line_length": 79, "avg_line_length": 25.656, "alnum_prop": 0.5991580916744621, "repo_name": "fwininger/ETW2CTF", "id": "4d660dc31b51a7e5d0aa7404f9e94a8e1516fe75", "size": "9012", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "4950" }, { "name": "C++", "bytes": "143233" }, { "name": "Python", "bytes": "3335" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.spi.predicate; import com.facebook.airlift.json.ObjectMapperProvider; import com.facebook.presto.spi.ColumnHandle; import com.facebook.presto.spi.TestingColumnHandle; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.TestingBlockEncodingSerde; import com.facebook.presto.spi.block.TestingBlockJsonSerde; import com.facebook.presto.spi.type.TestingTypeDeserializer; import com.facebook.presto.spi.type.TestingTypeManager; import com.facebook.presto.spi.type.Type; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.google.common.collect.ImmutableMap; import org.testng.annotations.Test; import java.io.IOException; import java.util.Map; import static com.facebook.presto.spi.predicate.TupleDomain.columnWiseUnion; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static io.airlift.slice.Slices.utf8Slice; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public class TestTupleDomain { private static final ColumnHandle A = new TestingColumnHandle("a"); private static final ColumnHandle B = new TestingColumnHandle("b"); private static final ColumnHandle C = new TestingColumnHandle("c"); private static final ColumnHandle D = new TestingColumnHandle("d"); private static final ColumnHandle E = new TestingColumnHandle("e"); private static final ColumnHandle F = new TestingColumnHandle("f"); @Test public void testNone() { assertTrue(TupleDomain.none().isNone()); assertEquals(TupleDomain.<ColumnHandle>none(), TupleDomain.withColumnDomains(ImmutableMap.of( A, Domain.none(BIGINT)))); assertEquals(TupleDomain.<ColumnHandle>none(), TupleDomain.withColumnDomains(ImmutableMap.of( A, Domain.all(BIGINT), B, Domain.none(VARCHAR)))); } @Test public void testAll() { assertTrue(TupleDomain.all().isAll()); assertEquals(TupleDomain.<ColumnHandle>all(), TupleDomain.withColumnDomains(ImmutableMap.of( A, Domain.all(BIGINT)))); assertEquals(TupleDomain.<ColumnHandle>all(), TupleDomain.withColumnDomains(ImmutableMap.<ColumnHandle, Domain>of())); } @Test public void testIntersection() { TupleDomain<ColumnHandle> tupleDomain1 = TupleDomain.withColumnDomains( ImmutableMap.<ColumnHandle, Domain>builder() .put(A, Domain.all(VARCHAR)) .put(B, Domain.notNull(DOUBLE)) .put(C, Domain.singleValue(BIGINT, 1L)) .put(D, Domain.create(ValueSet.ofRanges(Range.greaterThanOrEqual(DOUBLE, 0.0)), true)) .build()); TupleDomain<ColumnHandle> tupleDomain2 = TupleDomain.withColumnDomains( ImmutableMap.<ColumnHandle, Domain>builder() .put(A, Domain.singleValue(VARCHAR, utf8Slice("value"))) .put(B, Domain.singleValue(DOUBLE, 0.0)) .put(C, Domain.singleValue(BIGINT, 1L)) .put(D, Domain.create(ValueSet.ofRanges(Range.lessThan(DOUBLE, 10.0)), false)) .build()); TupleDomain<ColumnHandle> expectedTupleDomain = TupleDomain.withColumnDomains( ImmutableMap.<ColumnHandle, Domain>builder() .put(A, Domain.singleValue(VARCHAR, utf8Slice("value"))) .put(B, Domain.singleValue(DOUBLE, 0.0)) .put(C, Domain.singleValue(BIGINT, 1L)) .put(D, Domain.create(ValueSet.ofRanges(Range.range(DOUBLE, 0.0, true, 10.0, false)), false)) .build()); assertEquals(tupleDomain1.intersect(tupleDomain2), expectedTupleDomain); } @Test public void testNoneIntersection() { assertEquals(TupleDomain.none().intersect(TupleDomain.all()), TupleDomain.none()); assertEquals(TupleDomain.all().intersect(TupleDomain.none()), TupleDomain.none()); assertEquals(TupleDomain.none().intersect(TupleDomain.none()), TupleDomain.none()); assertEquals( TupleDomain.withColumnDomains(ImmutableMap.of(A, Domain.onlyNull(BIGINT))) .intersect(TupleDomain.withColumnDomains(ImmutableMap.of(A, Domain.notNull(BIGINT)))), TupleDomain.<ColumnHandle>none()); } @Test public void testMismatchedColumnIntersection() { TupleDomain<ColumnHandle> tupleDomain1 = TupleDomain.withColumnDomains( ImmutableMap.of( A, Domain.all(DOUBLE), B, Domain.singleValue(VARCHAR, utf8Slice("value")))); TupleDomain<ColumnHandle> tupleDomain2 = TupleDomain.withColumnDomains( ImmutableMap.of( A, Domain.create(ValueSet.ofRanges(Range.greaterThanOrEqual(DOUBLE, 0.0)), true), C, Domain.singleValue(BIGINT, 1L))); TupleDomain<ColumnHandle> expectedTupleDomain = TupleDomain.withColumnDomains(ImmutableMap.of( A, Domain.create(ValueSet.ofRanges(Range.greaterThanOrEqual(DOUBLE, 0.0)), true), B, Domain.singleValue(VARCHAR, utf8Slice("value")), C, Domain.singleValue(BIGINT, 1L))); assertEquals(tupleDomain1.intersect(tupleDomain2), expectedTupleDomain); } @Test public void testColumnWiseUnion() { TupleDomain<ColumnHandle> tupleDomain1 = TupleDomain.withColumnDomains( ImmutableMap.<ColumnHandle, Domain>builder() .put(A, Domain.all(VARCHAR)) .put(B, Domain.notNull(DOUBLE)) .put(C, Domain.onlyNull(BIGINT)) .put(D, Domain.singleValue(BIGINT, 1L)) .put(E, Domain.create(ValueSet.ofRanges(Range.greaterThanOrEqual(DOUBLE, 0.0)), true)) .build()); TupleDomain<ColumnHandle> tupleDomain2 = TupleDomain.withColumnDomains( ImmutableMap.<ColumnHandle, Domain>builder() .put(A, Domain.singleValue(VARCHAR, utf8Slice("value"))) .put(B, Domain.singleValue(DOUBLE, 0.0)) .put(C, Domain.notNull(BIGINT)) .put(D, Domain.singleValue(BIGINT, 1L)) .put(E, Domain.create(ValueSet.ofRanges(Range.lessThan(DOUBLE, 10.0)), false)) .build()); TupleDomain<ColumnHandle> expectedTupleDomain = TupleDomain.withColumnDomains( ImmutableMap.<ColumnHandle, Domain>builder() .put(A, Domain.all(VARCHAR)) .put(B, Domain.notNull(DOUBLE)) .put(C, Domain.all(BIGINT)) .put(D, Domain.singleValue(BIGINT, 1L)) .put(E, Domain.all(DOUBLE)) .build()); assertEquals(columnWiseUnion(tupleDomain1, tupleDomain2), expectedTupleDomain); } @Test public void testNoneColumnWiseUnion() { assertEquals(columnWiseUnion(TupleDomain.none(), TupleDomain.all()), TupleDomain.all()); assertEquals(columnWiseUnion(TupleDomain.all(), TupleDomain.none()), TupleDomain.all()); assertEquals(columnWiseUnion(TupleDomain.none(), TupleDomain.none()), TupleDomain.none()); assertEquals( columnWiseUnion( TupleDomain.withColumnDomains(ImmutableMap.of(A, Domain.onlyNull(BIGINT))), TupleDomain.withColumnDomains(ImmutableMap.of(A, Domain.notNull(BIGINT)))), TupleDomain.<ColumnHandle>all()); } @Test public void testMismatchedColumnWiseUnion() { TupleDomain<ColumnHandle> tupleDomain1 = TupleDomain.withColumnDomains( ImmutableMap.of( A, Domain.all(DOUBLE), B, Domain.singleValue(VARCHAR, utf8Slice("value")))); TupleDomain<ColumnHandle> tupleDomain2 = TupleDomain.withColumnDomains( ImmutableMap.of( A, Domain.create(ValueSet.ofRanges(Range.greaterThanOrEqual(DOUBLE, 0.0)), true), C, Domain.singleValue(BIGINT, 1L))); TupleDomain<ColumnHandle> expectedTupleDomain = TupleDomain.withColumnDomains(ImmutableMap.of(A, Domain.all(DOUBLE))); assertEquals(columnWiseUnion(tupleDomain1, tupleDomain2), expectedTupleDomain); } @Test public void testOverlaps() { assertTrue(overlaps( ImmutableMap.of(), ImmutableMap.of())); assertTrue(overlaps( ImmutableMap.of(), ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)))); assertFalse(overlaps( ImmutableMap.of(), ImmutableMap.of(A, Domain.none(BIGINT)))); assertFalse(overlaps( ImmutableMap.of(A, Domain.none(BIGINT)), ImmutableMap.of(A, Domain.none(BIGINT)))); assertTrue(overlaps( ImmutableMap.of(A, Domain.all(BIGINT)), ImmutableMap.of(A, Domain.all(BIGINT)))); assertTrue(overlaps( ImmutableMap.of(A, Domain.singleValue(BIGINT, 1L)), ImmutableMap.of(B, Domain.singleValue(VARCHAR, utf8Slice("value"))))); assertTrue(overlaps( ImmutableMap.of(A, Domain.singleValue(BIGINT, 1L)), ImmutableMap.of(A, Domain.all(BIGINT)))); assertFalse(overlaps( ImmutableMap.of(A, Domain.singleValue(BIGINT, 1L)), ImmutableMap.of(A, Domain.singleValue(BIGINT, 2L)))); assertFalse(overlaps( ImmutableMap.of( A, Domain.singleValue(BIGINT, 1L), B, Domain.singleValue(BIGINT, 1L)), ImmutableMap.of( A, Domain.singleValue(BIGINT, 1L), B, Domain.singleValue(BIGINT, 2L)))); assertTrue(overlaps( ImmutableMap.of( A, Domain.singleValue(BIGINT, 1L), B, Domain.all(BIGINT)), ImmutableMap.of( A, Domain.singleValue(BIGINT, 1L), B, Domain.singleValue(BIGINT, 2L)))); } @Test public void testContains() { assertTrue(contains( ImmutableMap.of(), ImmutableMap.of())); assertTrue(contains( ImmutableMap.of(), ImmutableMap.of(A, Domain.none(BIGINT)))); assertTrue(contains( ImmutableMap.of(), ImmutableMap.of(A, Domain.all(BIGINT)))); assertTrue(contains( ImmutableMap.of(), ImmutableMap.of(A, Domain.singleValue(DOUBLE, 0.0)))); assertFalse(contains( ImmutableMap.of(A, Domain.none(BIGINT)), ImmutableMap.of())); assertTrue(contains( ImmutableMap.of(A, Domain.none(BIGINT)), ImmutableMap.of(A, Domain.none(BIGINT)))); assertFalse(contains( ImmutableMap.of(A, Domain.none(BIGINT)), ImmutableMap.of(A, Domain.all(BIGINT)))); assertFalse(contains( ImmutableMap.of(A, Domain.none(BIGINT)), ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)))); assertTrue(contains( ImmutableMap.of(A, Domain.all(BIGINT)), ImmutableMap.of())); assertTrue(contains( ImmutableMap.of(A, Domain.all(BIGINT)), ImmutableMap.of(A, Domain.none(BIGINT)))); assertTrue(contains( ImmutableMap.of(A, Domain.all(BIGINT)), ImmutableMap.of(A, Domain.all(BIGINT)))); assertTrue(contains( ImmutableMap.of(A, Domain.all(BIGINT)), ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)))); assertFalse(contains( ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)), ImmutableMap.of())); assertTrue(contains( ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)), ImmutableMap.of(A, Domain.none(BIGINT)))); assertFalse(contains( ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)), ImmutableMap.of(A, Domain.all(BIGINT)))); assertTrue(contains( ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)), ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)))); assertFalse(contains( ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)), ImmutableMap.of(B, Domain.singleValue(VARCHAR, utf8Slice("value"))))); assertFalse(contains( ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.singleValue(VARCHAR, utf8Slice("value"))), ImmutableMap.of(B, Domain.singleValue(VARCHAR, utf8Slice("value"))))); assertTrue(contains( ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.singleValue(VARCHAR, utf8Slice("value"))), ImmutableMap.of(B, Domain.none(VARCHAR)))); assertTrue(contains( ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.singleValue(VARCHAR, utf8Slice("value"))), ImmutableMap.of( A, Domain.singleValue(BIGINT, 1L), B, Domain.none(VARCHAR)))); assertTrue(contains( ImmutableMap.of( B, Domain.singleValue(VARCHAR, utf8Slice("value"))), ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.singleValue(VARCHAR, utf8Slice("value"))))); assertTrue(contains( ImmutableMap.of( A, Domain.all(BIGINT), B, Domain.singleValue(VARCHAR, utf8Slice("value"))), ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.singleValue(VARCHAR, utf8Slice("value"))))); assertFalse(contains( ImmutableMap.of( A, Domain.all(BIGINT), B, Domain.singleValue(VARCHAR, utf8Slice("value"))), ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.singleValue(VARCHAR, utf8Slice("value2"))))); assertTrue(contains( ImmutableMap.of( A, Domain.all(BIGINT), B, Domain.singleValue(VARCHAR, utf8Slice("value"))), ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.singleValue(VARCHAR, utf8Slice("value2")), C, Domain.none(VARCHAR)))); assertFalse(contains( ImmutableMap.of( A, Domain.all(BIGINT), B, Domain.singleValue(VARCHAR, utf8Slice("value")), C, Domain.none(VARCHAR)), ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.singleValue(VARCHAR, utf8Slice("value2"))))); assertTrue(contains( ImmutableMap.of( A, Domain.all(BIGINT), B, Domain.singleValue(VARCHAR, utf8Slice("value")), C, Domain.none(VARCHAR)), ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.none(VARCHAR)))); } @Test public void testEquals() { assertTrue(equals( ImmutableMap.of(), ImmutableMap.of())); assertTrue(equals( ImmutableMap.of(), ImmutableMap.of(A, Domain.all(BIGINT)))); assertFalse(equals( ImmutableMap.of(), ImmutableMap.of(A, Domain.none(BIGINT)))); assertFalse(equals( ImmutableMap.of(), ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)))); assertTrue(equals( ImmutableMap.of(A, Domain.all(BIGINT)), ImmutableMap.of(A, Domain.all(BIGINT)))); assertFalse(equals( ImmutableMap.of(A, Domain.all(BIGINT)), ImmutableMap.of(A, Domain.none(BIGINT)))); assertFalse(equals( ImmutableMap.of(A, Domain.all(BIGINT)), ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)))); assertTrue(equals( ImmutableMap.of(A, Domain.none(BIGINT)), ImmutableMap.of(A, Domain.none(BIGINT)))); assertFalse(equals( ImmutableMap.of(A, Domain.none(BIGINT)), ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)))); assertTrue(equals( ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)), ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)))); assertFalse(equals( ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)), ImmutableMap.of(B, Domain.singleValue(BIGINT, 0L)))); assertFalse(equals( ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L)), ImmutableMap.of(A, Domain.singleValue(BIGINT, 1L)))); assertTrue(equals( ImmutableMap.of(A, Domain.all(BIGINT)), ImmutableMap.of(B, Domain.all(VARCHAR)))); assertTrue(equals( ImmutableMap.of(A, Domain.none(BIGINT)), ImmutableMap.of(B, Domain.none(VARCHAR)))); assertTrue(equals( ImmutableMap.of(A, Domain.none(BIGINT)), ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.none(VARCHAR)))); assertFalse(equals( ImmutableMap.of( A, Domain.singleValue(BIGINT, 1L)), ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.none(VARCHAR)))); assertTrue(equals( ImmutableMap.of( A, Domain.singleValue(BIGINT, 1L), C, Domain.none(DOUBLE)), ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.none(VARCHAR)))); assertTrue(equals( ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.all(DOUBLE)), ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.all(DOUBLE)))); assertTrue(equals( ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.all(VARCHAR)), ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), C, Domain.all(DOUBLE)))); assertFalse(equals( ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.all(VARCHAR)), ImmutableMap.of( A, Domain.singleValue(BIGINT, 1L), C, Domain.all(DOUBLE)))); assertFalse(equals( ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), B, Domain.all(VARCHAR)), ImmutableMap.of( A, Domain.singleValue(BIGINT, 0L), C, Domain.singleValue(DOUBLE, 0.0)))); } @Test public void testIsNone() { assertFalse(TupleDomain.withColumnDomains(ImmutableMap.<ColumnHandle, Domain>of()).isNone()); assertFalse(TupleDomain.withColumnDomains(ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L))).isNone()); assertTrue(TupleDomain.withColumnDomains(ImmutableMap.of(A, Domain.none(BIGINT))).isNone()); assertFalse(TupleDomain.withColumnDomains(ImmutableMap.of(A, Domain.all(BIGINT))).isNone()); assertTrue(TupleDomain.withColumnDomains(ImmutableMap.of(A, Domain.all(BIGINT), B, Domain.none(BIGINT))).isNone()); } @Test public void testIsAll() { assertTrue(TupleDomain.withColumnDomains(ImmutableMap.<ColumnHandle, Domain>of()).isAll()); assertFalse(TupleDomain.withColumnDomains(ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L))).isAll()); assertTrue(TupleDomain.withColumnDomains(ImmutableMap.of(A, Domain.all(BIGINT))).isAll()); assertFalse(TupleDomain.withColumnDomains(ImmutableMap.of(A, Domain.singleValue(BIGINT, 0L), B, Domain.all(BIGINT))).isAll()); } @Test public void testExtractFixedValues() { assertEquals( TupleDomain.extractFixedValues(TupleDomain.withColumnDomains( ImmutableMap.<ColumnHandle, Domain>builder() .put(A, Domain.all(DOUBLE)) .put(B, Domain.singleValue(VARCHAR, utf8Slice("value"))) .put(C, Domain.onlyNull(BIGINT)) .put(D, Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L)), true)) .build())).get(), ImmutableMap.of( B, NullableValue.of(VARCHAR, utf8Slice("value")), C, NullableValue.asNull(BIGINT))); } @Test public void testExtractFixedValuesFromNone() { assertFalse(TupleDomain.extractFixedValues(TupleDomain.none()).isPresent()); } @Test public void testExtractFixedValuesFromAll() { assertEquals(TupleDomain.extractFixedValues(TupleDomain.all()).get(), ImmutableMap.of()); } @Test public void testSingleValuesMapToDomain() { assertEquals( TupleDomain.fromFixedValues( ImmutableMap.<ColumnHandle, NullableValue>builder() .put(A, NullableValue.of(BIGINT, 1L)) .put(B, NullableValue.of(VARCHAR, utf8Slice("value"))) .put(C, NullableValue.of(DOUBLE, 0.01)) .put(D, NullableValue.asNull(BOOLEAN)) .build()), TupleDomain.withColumnDomains(ImmutableMap.<ColumnHandle, Domain>builder() .put(A, Domain.singleValue(BIGINT, 1L)) .put(B, Domain.singleValue(VARCHAR, utf8Slice("value"))) .put(C, Domain.singleValue(DOUBLE, 0.01)) .put(D, Domain.onlyNull(BOOLEAN)) .build())); } @Test public void testEmptySingleValuesMapToDomain() { assertEquals(TupleDomain.fromFixedValues(ImmutableMap.of()), TupleDomain.all()); } @Test public void testJsonSerialization() throws Exception { TestingTypeManager typeManager = new TestingTypeManager(); TestingBlockEncodingSerde blockEncodingSerde = new TestingBlockEncodingSerde(typeManager); ObjectMapper mapper = new ObjectMapperProvider().get() .registerModule(new SimpleModule() .addDeserializer(ColumnHandle.class, new JsonDeserializer<ColumnHandle>() { @Override public ColumnHandle deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { return new ObjectMapperProvider().get().readValue(jsonParser, TestingColumnHandle.class); } }) .addDeserializer(Type.class, new TestingTypeDeserializer(typeManager)) .addSerializer(Block.class, new TestingBlockJsonSerde.Serializer(blockEncodingSerde)) .addDeserializer(Block.class, new TestingBlockJsonSerde.Deserializer(blockEncodingSerde))); TupleDomain<ColumnHandle> tupleDomain = TupleDomain.all(); assertEquals(tupleDomain, mapper.readValue(mapper.writeValueAsString(tupleDomain), new TypeReference<TupleDomain<ColumnHandle>>() {})); tupleDomain = TupleDomain.none(); assertEquals(tupleDomain, mapper.readValue(mapper.writeValueAsString(tupleDomain), new TypeReference<TupleDomain<ColumnHandle>>() {})); tupleDomain = TupleDomain.fromFixedValues(ImmutableMap.of(A, NullableValue.of(BIGINT, 1L), B, NullableValue.asNull(VARCHAR))); assertEquals(tupleDomain, mapper.readValue(mapper.writeValueAsString(tupleDomain), new TypeReference<TupleDomain<ColumnHandle>>() {})); } @Test public void testTransform() { Map<Integer, Domain> domains = ImmutableMap.<Integer, Domain>builder() .put(1, Domain.singleValue(BIGINT, 1L)) .put(2, Domain.singleValue(BIGINT, 2L)) .put(3, Domain.singleValue(BIGINT, 3L)) .build(); TupleDomain<Integer> domain = TupleDomain.withColumnDomains(domains); TupleDomain<String> transformed = domain.transform(Object::toString); Map<String, Domain> expected = ImmutableMap.<String, Domain>builder() .put("1", Domain.singleValue(BIGINT, 1L)) .put("2", Domain.singleValue(BIGINT, 2L)) .put("3", Domain.singleValue(BIGINT, 3L)) .build(); assertEquals(transformed.getDomains().get(), expected); } @Test(expectedExceptions = IllegalArgumentException.class) public void testTransformFailsWithNonUniqueMapping() { Map<Integer, Domain> domains = ImmutableMap.<Integer, Domain>builder() .put(1, Domain.singleValue(BIGINT, 1L)) .put(2, Domain.singleValue(BIGINT, 2L)) .put(3, Domain.singleValue(BIGINT, 3L)) .build(); TupleDomain<Integer> domain = TupleDomain.withColumnDomains(domains); domain.transform(input -> "x"); } private boolean overlaps(Map<ColumnHandle, Domain> domains1, Map<ColumnHandle, Domain> domains2) { TupleDomain<ColumnHandle> tupleDomain1 = TupleDomain.withColumnDomains(domains1); TupleDomain<ColumnHandle> tupleDOmain2 = TupleDomain.withColumnDomains(domains2); return tupleDomain1.overlaps(tupleDOmain2); } private boolean contains(Map<ColumnHandle, Domain> superSet, Map<ColumnHandle, Domain> subSet) { TupleDomain<ColumnHandle> superSetTupleDomain = TupleDomain.withColumnDomains(superSet); TupleDomain<ColumnHandle> subSetTupleDomain = TupleDomain.withColumnDomains(subSet); return superSetTupleDomain.contains(subSetTupleDomain); } private boolean equals(Map<ColumnHandle, Domain> domains1, Map<ColumnHandle, Domain> domains2) { TupleDomain<ColumnHandle> tupleDomain1 = TupleDomain.withColumnDomains(domains1); TupleDomain<ColumnHandle> tupleDOmain2 = TupleDomain.withColumnDomains(domains2); return tupleDomain1.equals(tupleDOmain2); } }
{ "content_hash": "500fb57ae599e1b1d2037efd2d739009", "timestamp": "", "source": "github", "line_count": 673, "max_line_length": 143, "avg_line_length": 43.10698365527489, "alnum_prop": 0.5790906897383751, "repo_name": "ptkool/presto", "id": "08d8ac1bb2e25334c609695538a57ecb74aadde3", "size": "29011", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "presto-spi/src/test/java/com/facebook/presto/spi/predicate/TestTupleDomain.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "28777" }, { "name": "CSS", "bytes": "13127" }, { "name": "HTML", "bytes": "28660" }, { "name": "Java", "bytes": "37430827" }, { "name": "JavaScript", "bytes": "216033" }, { "name": "Makefile", "bytes": "6830" }, { "name": "PLSQL", "bytes": "2797" }, { "name": "Python", "bytes": "8714" }, { "name": "SQLPL", "bytes": "926" }, { "name": "Shell", "bytes": "29909" }, { "name": "TSQL", "bytes": "161695" }, { "name": "Thrift", "bytes": "12631" } ], "symlink_target": "" }
<?php return [ /* |-------------------------------------------------------------------------- | Default Authentication Driver |-------------------------------------------------------------------------- | | This option controls the authentication driver that will be utilized. | This driver manages the retrieval and authentication of the users | attempting to get access to protected areas of your application. | | Supported: "database", "eloquent" | */ 'driver' => 'eloquent', /* |-------------------------------------------------------------------------- | Authentication Model |-------------------------------------------------------------------------- | | When using the "Eloquent" authentication driver, we need to know which | Eloquent model should be used to retrieve your users. Of course, it | is often just the "User" model but you may use whatever you like. | */ 'model' => MtgSlo\User::class, /* |-------------------------------------------------------------------------- | Authentication Table |-------------------------------------------------------------------------- | | When using the "Database" authentication driver, we need to know which | table should be used to retrieve your users. We have chosen a basic | default value but you may easily change it to any table you like. | */ 'table' => 'users', /* |-------------------------------------------------------------------------- | Password Reset Settings |-------------------------------------------------------------------------- | | Here you may set the options for resetting passwords including the view | that is your password reset e-mail. You can also set the name of the | table that maintains all of the reset tokens for your application. | | The expire time is the number of minutes that the reset token should be | considered valid. This security feature keeps tokens short-lived so | they have less time to be guessed. You may change this as needed. | */ 'password' => [ 'email' => 'emails.password', 'table' => 'password_resets', 'expire' => 60, ], ];
{ "content_hash": "fc843c42bb18abd985c0a0837d8dbb52", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 79, "avg_line_length": 33.92537313432836, "alnum_prop": 0.45974483062032556, "repo_name": "neyko5/mtgslo", "id": "873027554512731176bae4fb865ecb888051f26c", "size": "2273", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/auth.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "412" }, { "name": "CSS", "bytes": "43581" }, { "name": "HTML", "bytes": "3396616" }, { "name": "JavaScript", "bytes": "2952636" }, { "name": "PHP", "bytes": "248506" } ], "symlink_target": "" }
#include <errno.h> #include <stddef.h> #include <unistd.h> #include <sys/types.h> #include <limits.h> /* If SIZE is zero, return the number of supplementary groups the calling process is in. Otherwise, fill in the group IDs of its supplementary groups in LIST and return the number written. */ int __getgroups (size, list) int size; gid_t *list; { #if defined (NGROUPS_MAX) && NGROUPS_MAX == 0 /* The system has no supplementary groups. */ return 0; #endif __set_errno (ENOSYS); return -1; } #if !(defined (NGROUPS_MAX) && NGROUPS_MAX == 0) stub_warning (getgroups); #endif weak_alias (__getgroups, getgroups) #include <stub-tag.h>
{ "content_hash": "20de2cb0ac250a041f7195cf45e36035", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 73, "avg_line_length": 20.8125, "alnum_prop": 0.6741741741741741, "repo_name": "andrewjylee/omniplay", "id": "d5868cc1b8806aa30a03539253a87646b6cc82c5", "size": "1540", "binary": false, "copies": "24", "ref": "refs/heads/master", "path": "eglibc-2.15/posix/getgroups.c", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "4528" }, { "name": "Assembly", "bytes": "8662249" }, { "name": "Awk", "bytes": "79791" }, { "name": "Batchfile", "bytes": "903" }, { "name": "C", "bytes": "451499135" }, { "name": "C++", "bytes": "6338106" }, { "name": "Groff", "bytes": "2522798" }, { "name": "HTML", "bytes": "47935" }, { "name": "Java", "bytes": "2193" }, { "name": "Lex", "bytes": "44513" }, { "name": "Logos", "bytes": "97869" }, { "name": "Makefile", "bytes": "1700085" }, { "name": "Objective-C", "bytes": "1148023" }, { "name": "Perl", "bytes": "530370" }, { "name": "Perl6", "bytes": "3727" }, { "name": "Python", "bytes": "493452" }, { "name": "Scilab", "bytes": "21433" }, { "name": "Shell", "bytes": "409014" }, { "name": "SourcePawn", "bytes": "11760" }, { "name": "TeX", "bytes": "283872" }, { "name": "UnrealScript", "bytes": "6143" }, { "name": "XS", "bytes": "1240" }, { "name": "Yacc", "bytes": "93190" } ], "symlink_target": "" }
// Load theme according to localStorage if(localStorage.getItem("theme") == "dark"){ $("#switchTheme").html("White theme"); $("#switchTheme").val("white"); loadTheme("dark"); }else{ $("#switchTheme").val("dark"); loadTheme("white"); } $(function(){ $("#switchTheme").on("click", function(){ if($(this).val() == "dark"){ $(this).html("White theme"); this.value = "white"; // We load the dark theme loadTheme("dark"); localStorage.setItem("theme","dark"); }else{ $(this).html("Dark theme"); this.value = "dark"; // We load the white theme loadTheme("white"); localStorage.setItem("theme","white"); } }); }) function loadTheme(color){ $('body').removeClass(); $('body').addClass(color); }
{ "content_hash": "f6781bc1f130253c7fde06b5dfdff94a", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 44, "avg_line_length": 20.027027027027028, "alnum_prop": 0.5978407557354926, "repo_name": "sbthegreat/turskain.github.io", "id": "b2b368e7007a756366e9afd1d8c7f9edbdcbcc7d", "size": "741", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "8thgen/script_res/switch_mode.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7884" }, { "name": "HTML", "bytes": "102016" }, { "name": "JavaScript", "bytes": "652939" } ], "symlink_target": "" }
{% extends "_layouts/dashboard.html" %} {% set active_page = "projects" %} {% import "_helpers/_card.html" as card_helpers %} {% import "_helpers/_general.html" as general_helpers %} {% block content %} {{ general_helpers.render_title(project.name, 'Delete Tasks') }} <div class="card"> {{ card_helpers.render_title('Danger Zone', 'There is no undo!') }} <div class="card-block pt-0"> <div class="alert alert-danger"> <strong>Warning!</strong> If you delete all task and contribution data it will be gone forever! </div> <form method="POST" action="{{ url_for('project.delete_tasks', short_name=project.short_name) }}"> <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" /> <div class="text-right"> <a href="{{ url_for('project.tasks', short_name=project.short_name) }}" class="btn btn-outline-secondary" role="button">No, do not delete anything!</a> <button type="submit" name='btn' class="btn btn-danger" value="Yes" role="button">Yes, delete everything</button> </div> </form> </div> </div> {% endblock %}
{ "content_hash": "3b195e95b5769fd0488cb9ec5eaa9e38", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 167, "avg_line_length": 49.95652173913044, "alnum_prop": 0.608355091383812, "repo_name": "LibCrowds/libcrowds-bs4-pybossa-theme", "id": "65e7c7382408db2c942720a455681bd8c8a3aa5d", "size": "1149", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/projects/tasks/delete.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "30604" }, { "name": "HTML", "bytes": "259826" }, { "name": "JavaScript", "bytes": "55369" } ], "symlink_target": "" }
package com.indeed.imhotep.service; import com.google.common.base.Throwables; import com.indeed.util.core.io.Closeables2; import org.apache.log4j.Logger; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLockInterruptionException; import java.nio.channels.OverlappingFileLockException; import java.util.HashMap; import java.util.Map; /** * @author jplaisance */ public final class AcquireShared { private static final Logger log = Logger.getLogger(AcquireShared.class); public static void main(String[] args) throws InterruptedException { System.out.println(System.getProperty("java.version")); final File testlocking = new File("testlocking"); testlocking.mkdir(); final Map<File, RandomAccessFile> lockFileMap = new HashMap<File, RandomAccessFile>(); try { acquireReadLock(lockFileMap, testlocking); } catch (AlreadyOpenException e) { System.out.println("already open"); } catch (LockAquisitionException e) { System.out.println("deleted"); } try { acquireReadLock(lockFileMap, testlocking); System.out.println("should've failed"); } catch (AlreadyOpenException e) { //ignore } catch (LockAquisitionException e) { System.out.println("deleted"); } Thread.sleep(Long.MAX_VALUE); } private static void acquireReadLock(Map<File, RandomAccessFile> lockFileMap, File indexDir) throws LockAquisitionException { final File writeLock = new File(indexDir, "delete.lock"); try { writeLock.createNewFile(); while (true) { synchronized (lockFileMap) { RandomAccessFile raf = lockFileMap.get(indexDir); if (raf == null) { raf = new RandomAccessFile(writeLock, "r"); lockFileMap.put(indexDir, raf); } else { throw new AlreadyOpenException(); } final FileChannel channel = raf.getChannel(); try { channel.lock(0, Long.MAX_VALUE, true); if (indexDir.exists()) { System.out.println("lock acquired"); return; } lockFileMap.remove(indexDir); Closeables2.closeQuietly(raf, log); throw new ShardDeletedException(); } catch (OverlappingFileLockException e) { lockFileMap.remove(indexDir); Closeables2.closeQuietly(raf, log); throw Throwables.propagate(e); } catch (FileLockInterruptionException e) { lockFileMap.remove(indexDir); Closeables2.closeQuietly(raf, log); } } } } catch (IOException e) { throw new ShardDeletedException(); } } private static class LockAquisitionException extends Exception { public LockAquisitionException() { } } private static final class ShardDeletedException extends LockAquisitionException { private ShardDeletedException() { } } private static final class AlreadyOpenException extends LockAquisitionException { private AlreadyOpenException() { } } }
{ "content_hash": "24c43221035e9c926758f3c5d8837269", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 128, "avg_line_length": 35.01923076923077, "alnum_prop": 0.5752333882482152, "repo_name": "indeedeng/imhotep", "id": "2d7241fbd23006ca85e514881ebc6efa616dfd5d", "size": "4230", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "imhotep-server/src/test/java/com/indeed/imhotep/service/AcquireShared.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "43876" }, { "name": "C++", "bytes": "58637" }, { "name": "Java", "bytes": "1832070" }, { "name": "Perl", "bytes": "706" }, { "name": "Shell", "bytes": "772" } ], "symlink_target": "" }
package com.hribol.bromium.common.replay.actions; import com.hribol.bromium.common.replay.InstanceBasedAutomationResultBuilder; import com.hribol.bromium.common.synchronization.JSPrecondition; import com.hribol.bromium.core.config.SearchContextFunction; import com.hribol.bromium.core.synchronization.EventSynchronizer; import com.hribol.bromium.core.synchronization.SynchronizationEvent; import com.hribol.bromium.replay.ReplayingState; import com.hribol.bromium.replay.actions.ActionWithJSPrecondition; import com.hribol.bromium.replay.actions.WebDriverAction; import com.hribol.bromium.replay.execution.WebDriverActionExecutionException; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeoutException; import java.util.function.Function; /** * A base class for all actions that need a js condition to be satisfied before they can be executed. * An example would be a click on an element with an id, the js condition would be that the element is present * in the DOM. */ public abstract class ActionWithJSPreconditionBase implements ActionWithJSPrecondition, WebDriverAction { private static final Logger logger = LoggerFactory.getLogger(ActionWithJSPreconditionBase.class); private SearchContextFunction contextProvider; protected ActionWithJSPreconditionBase(SearchContextFunction contextProvider) { this.contextProvider = contextProvider; } @Override public void execute(WebDriver driver, ReplayingState replayingState, EventSynchronizer eventSynchronizer) { String hashCodeToWaitFor = String.valueOf(getJSEventToWaitFor().hashCode()); logger.info("Condition {} has hashcode {}", getJSEventToWaitFor(), hashCodeToWaitFor); SynchronizationEvent synchronizationEvent = new JSPrecondition(hashCodeToWaitFor, eventSynchronizer, replayingState); try { eventSynchronizer.awaitUntil(synchronizationEvent); } catch (InterruptedException | TimeoutException e) { throw new WebDriverActionExecutionException("Exception while awaiting JS precondition", e, new InstanceBasedAutomationResultBuilder()); } executeAfterJSPreconditionHasBeenSatisfied(driver, replayingState, contextProvider); } /** * The code to be executed after the condition was satisfied. The meat of the action * @param driver the driver instance * @param replayingState the current state of the replaying * @param contextProvider */ public abstract void executeAfterJSPreconditionHasBeenSatisfied(WebDriver driver, ReplayingState replayingState, Function<SearchContext, SearchContext> contextProvider); @Override public String getName() { return getJSEventToWaitFor(); } }
{ "content_hash": "5b1cd5098c22108b5d8d9f2b0f118d24", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 173, "avg_line_length": 45.75806451612903, "alnum_prop": 0.788861473387381, "repo_name": "hristo-vrigazov/bromium", "id": "bc399e1f0c6547ffd7ceb83c41dd3aaa02668330", "size": "2837", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bromium-common/src/main/java/com/hribol/bromium/common/replay/actions/ActionWithJSPreconditionBase.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "669" }, { "name": "GAP", "bytes": "129872" }, { "name": "HTML", "bytes": "15134" }, { "name": "Handlebars", "bytes": "1514" }, { "name": "Java", "bytes": "1334283" }, { "name": "JavaScript", "bytes": "25455" }, { "name": "Xtend", "bytes": "14579" } ], "symlink_target": "" }
require 'active_support/core_ext' require 'aws/s3' require 'data_mapper' require 'net/http' require 'json' class APINotOkError < StandardError end class Character class << self def bucket bucket_name = ENV["AWS_S3_BUCKET"] bucket_name += "-development" if ENV["RACK_ENV"] == "development" @@bucket ||= AWS::S3.new( access_key_id: ENV["AWS_ACCESS_KEY_ID"], secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"]).buckets[bucket_name] @@bucket end def dm_setup DataMapper::Model.raise_on_save_failure = true DataMapper.setup(:default, (ENV["DATABASE_URL"] || "sqlite3:///#{Dir.pwd}/development.sqlite3")) DataMapper.auto_upgrade! end end include DataMapper::Resource before :create, :titleize before :destroy, :delete_img property :id, Serial property :region, String, required: true, format: /^[a-z]{2}$/ property :realm, String, required: true property :char, String, required: true, format: /^[[:alpha:]]+$/ property :created_at, DateTime property :updated_at, DateTime def char_path "#{region}/#{realm}/#{char}" end def armory_url "http://#{region}.battle.net/wow/en/character/#{realm}/#{char}/" end def img_uri unless img_s3.exists? update_img else Thread.new { update_img } unless @updating end img_s3.public_url end def update_img return unless updated_at < 3.hours.ago or not img_s3.exists? begin @updating = true json = JSON.parse(Net::HTTP.get(api_uri)) raise APINotOkError, json["msg"] unless json["status"] == "ok" img_s3.write(Net::HTTP.get URI(json["link"])) img_s3.acl = :public_read self.update updated_at: Time.now rescue Exception => e raise e unless img_s3.exists? ensure @updating = false end end private def titleize self.region = region.downcase self.realm = realm.titleize self.char = char.capitalize end def api_uri uri = URI('http://www.best-signatures.com/api/') uri.query = URI.encode_www_form({ region: region, realm: realm, char: char, type: "Sign9" }) return uri end def delete_img img_s3.delete if img_s3.exists? end def img_s3 Character.bucket.objects["#{char_path}.png"] end end
{ "content_hash": "80a889a221036bff3f71ad12598cfec0", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 102, "avg_line_length": 22.39047619047619, "alnum_prop": 0.6214376860910251, "repo_name": "jbhannah/bestsigs-wow-cacher", "id": "321686e77a92001ede248902f5006f222219f299", "size": "2351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "character.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "245" }, { "name": "Ruby", "bytes": "5555" } ], "symlink_target": "" }
kloudbook ========= KB Source to move to Heroku
{ "content_hash": "308bf189ec49a7f1cd3ce9d8d2c10f5b", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 27, "avg_line_length": 12.25, "alnum_prop": 0.6326530612244898, "repo_name": "dburgess560/kloudbook", "id": "d28c408e4398cca1f6be3d3bbe49e16edbd8f166", "size": "49", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
require "rails_helper" describe Course::Compiler do let(:course) { Course.create(:name => "nodejs") } let(:compiler) { course.compiler } describe "#list_of_pages" do it "list directories that has an index document" do expect(compiler.list_of_pages.sort).to eql( ["api-driven-development", "build-the-express-app", "build-the-middleware-stack", "class-inheritance", "class-system", "conditional-get", "content-negotiation", "create-npm-package", "dependence-injection", "extending-request-response", "mini-harp-preprocessor", "mini-harp-server", "path-matcher", "path-matcher-fancy", "router-chaining", "router-http-verbs", "send-file", "setting-up-mocha", "using-coffeescript", "why-middleware"]) end end describe "#pages_xml" do it("compiles all pages into a list of <page> tags") do xml = compiler.pages_xml expect(xml).to be_a(String) puts xml end end describe "#weeks_xml" do it("includes references to all lessons, organized in <week> tags") do xml = compiler.weeks_xml expect(xml).to be_a(String) puts xml end end describe "#course_xml" do it("compiles the course into a single xml") do xml = compiler.course_xml puts xml end end end
{ "content_hash": "736229378c60276c086ce9c4bc08e7d2", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 73, "avg_line_length": 24.633333333333333, "alnum_prop": 0.5703653585926928, "repo_name": "hayeah/sike", "id": "f00d6c54a467e0d7d42eeb95116726abaa233723", "size": "1479", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/models/course/compiler_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "99730" }, { "name": "CoffeeScript", "bytes": "6959" }, { "name": "HTML", "bytes": "66060" }, { "name": "JavaScript", "bytes": "254264" }, { "name": "Makefile", "bytes": "67" }, { "name": "Ruby", "bytes": "132691" }, { "name": "Shell", "bytes": "57" } ], "symlink_target": "" }
**NOTE**: Check out [**Project Details**](Project-Details) before running it locally! To add changes and improvements or resolve issues, these are the usual steps: 1. Fork the project on Github then clone it to your machine: ```bash git clone https://github.com/<your-username>/AlgorithmVisualizer # clone your forked repo cd AlgorithmVisualizer # navigate inside the created directory git submodule init # initialize wiki submodule git submodule update # setup wiki submodule updates ``` 2. Your fork's remote repository should be named `origin` by default, so add the main repository as a remote as well and give it a name to distinguish it from your fork (something like `main` would work): ```bash git remote add main https://github.com/parkjs814/AlgorithmVisualizer ``` 3. Create a branch addressing the issue/improvement you'd like to tackle. ```bash git checkout -b my-problem-fixer-branch ``` 4. Make your changes and push to `my-problem-fixer-branch` on your repo ```bash # write some awesome code and then ... git add . git commit -m "Explain my awesome changes" git push origin my-problem-fixer-branch ``` 5. Next create a pull request from `my-problem-fixer-branch` branch on `origin` to `master` branch on `main`. 6. Once approved, just delete `my-problem-fixer-branch` both locally and remotely because it's not needed anymore. 7. Finally, checkout `master` locally, pull the approved changes from the `main` repo, and push them to your `origin` repo: ```bash git checkout master # checkout master locally git pull main master # pull new changes from main repository git push main master # push the changes to your fork ``` That's it, everything should be in sync now. If you run into problems, feel free to [ask us for help on gitter](https://gitter.im/parkjs814/AlgorithmVisualizer?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) As mentioned, check out [**Project Details**](Project-Details) for more information on how to run the project.
{ "content_hash": "ad137c6f199e8d53139c3d7f276ab28b", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 204, "avg_line_length": 43.58, "alnum_prop": 0.6998623221661312, "repo_name": "nem035/AlgorithmVisualizer", "id": "5510e41c4c232ae1b2f044e327b1e50355ac832b", "size": "2179", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "wiki/Contributing.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13192" }, { "name": "HTML", "bytes": "6913" }, { "name": "JavaScript", "bytes": "219543" } ], "symlink_target": "" }
FROM node:8 WORKDIR /usr/src/app COPY package*.json ./ RUN yarn install COPY . . EXPOSE 3000 CMD [ "yarn", "start" ]
{ "content_hash": "a880866802215264cc26f1e27e8d451f", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 23, "avg_line_length": 16.714285714285715, "alnum_prop": 0.6837606837606838, "repo_name": "JasonSteck/JS-Nexus", "id": "247cdc55dc558f7f550e72d6adc7b33d88121c74", "size": "117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "491" }, { "name": "JavaScript", "bytes": "106457" } ], "symlink_target": "" }
<!-- Copyright (c) 2015 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!DOCTYPE html> <html> <head> <title>Dataset reader</title> <script type="text/javascript" src="js/third-party/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript" src="js/third-party/underscore/1.8.3/underscore-min.js"></script> <script type="text/javascript" src="js/third-party/flot/0.8.3/jquery.flot.min.js"></script> <script type="text/javascript" src="js/third-party/flot/0.8.3/jquery.flot.categories.min.js"></script> <script type="text/javascript" src="js/third-party/flot/0.8.3/jquery.flot.symbol.min.js"></script> <script type="text/javascript" src="js/third-party/flot/0.8.3/jquery.flot.resize.min.js"></script> <script type="text/javascript" src="js/app.js"></script> <link rel="stylesheet" type="text/css" href="css/third-party/font-awesome/4.6.3/font-awesome.min.css"> <link rel="stylesheet" href="css/main.css" /> </head> <body> <div class="main"> <h1><img src="img/logo.png" /> Dataset reader</h1> <div class="charts"> <div id="histogram_ln_ibyt_SUM"></div> <div id="scatter_ln_obyt_SUM_ln_ibyt_SUM"></div> <div id="scatter_ln_degree_ln_ibyt_SUM"></div> <div id="scatter_ln_weighted_degree_ln_ibyt_SUM"></div> <div id="scatter_ln_ibyt_SUM_ln_obyt_SUM"></div> <div id="histogram_ln_obyt_SUM"></div> <div id="scatter_ln_degree_ln_obyt_SUM"></div> <div id="scatter_ln_weighted_degree_ln_obyt_SUM"></div> <div id="scatter_ln_ibyt_SUM_ln_degree"></div> <div id="scatter_ln_obyt_SUM_ln_degree"></div> <div id="histogram_ln_degree"></div> <div id="scatter_ln_weighted_degree_ln_degree"></div> <div id="scatter_ln_ibyt_SUM_ln_weighted_degree"></div> <div id="scatter_ln_obyt_SUM_ln_weighted_degree"></div> <div id="scatter_ln_degree_ln_weighted_degree"></div> <div id="histogram_ln_weighted_degree"></div> </div> <div class="link"> <a href="https://github.com/trustedanalytics/dataset-reader-sample/blob/master/README.md" target="_blank">Read more on Github <i class="fa fa-external-link"></i> </a> </div> </div> </body> </html>
{ "content_hash": "b6499ae401ed3f9aab82c1bc591f321d", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 133, "avg_line_length": 40.457142857142856, "alnum_prop": 0.6440677966101694, "repo_name": "trustedanalytics/dataset-reader-sample", "id": "aae298e1d7aaebf061739e0a4e1d41d82c53118e", "size": "2832", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/static/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2605" }, { "name": "HTML", "bytes": "4188" }, { "name": "Java", "bytes": "13434" }, { "name": "JavaScript", "bytes": "2845" }, { "name": "Jupyter Notebook", "bytes": "39550" }, { "name": "Python", "bytes": "2304" }, { "name": "Shell", "bytes": "1616" } ], "symlink_target": "" }
SYNONYM #### According to Index Fungorum #### Published in null #### Original name Erioderma physcioides Vain. ### Remarks null
{ "content_hash": "59363599af5d20f7402a18a3e1ca2390", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 27, "avg_line_length": 10.076923076923077, "alnum_prop": 0.7099236641221374, "repo_name": "mdoering/backbone", "id": "8ded5b8ea4c3149b0c8a27569cb426e040f97109", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Peltigerales/Pannariaceae/Erioderma/Malmella physcioides/ Syn. Malmella physciodes/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.8 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ public enum unit_constants { UNIT_KPA, UNIT_PA, UNIT_BAR, UNIT_KG_M3, UNIT_KG_L }
{ "content_hash": "29a99d4350cf6df4e017511d027d3c3a", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 83, "avg_line_length": 29.0625, "alnum_prop": 0.44731182795698926, "repo_name": "CoolProp/CoolProp-museum", "id": "f960a60749f94b600378743daf2692371e2a89a1", "size": "465", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "wrappers/C#/VSCsharp/unit_constants.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4100033" }, { "name": "C#", "bytes": "44760" }, { "name": "C++", "bytes": "3544686" }, { "name": "CSS", "bytes": "10460" }, { "name": "FORTRAN", "bytes": "2453" }, { "name": "Java", "bytes": "13100" }, { "name": "M", "bytes": "183" }, { "name": "Matlab", "bytes": "20322" }, { "name": "Objective-C", "bytes": "6271" }, { "name": "Python", "bytes": "971754" }, { "name": "Scilab", "bytes": "774" }, { "name": "Shell", "bytes": "27491" }, { "name": "TeX", "bytes": "58925" }, { "name": "Visual Basic", "bytes": "18659" } ], "symlink_target": "" }
class AddRatingsCountToEpisodes < ActiveRecord::Migration[5.1] def change add_column :episodes, :ratings_count, :integer, null: false, default: 0 add_index :episodes, :ratings_count add_column :episodes, :satisfaction_rate, :float add_index :episodes, :satisfaction_rate add_index :episodes, %i(satisfaction_rate ratings_count) end end
{ "content_hash": "1fd00eabc26340638ab11d56d7e1c8b4", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 75, "avg_line_length": 36.1, "alnum_prop": 0.7313019390581718, "repo_name": "elzzup/annict", "id": "c8a8d9376337515fe932a074e3c01f3c60243005", "size": "392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20180120150327_add_ratings_count_to_episodes.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "48592" }, { "name": "CoffeeScript", "bytes": "16467" }, { "name": "HTML", "bytes": "153898" }, { "name": "JavaScript", "bytes": "791" }, { "name": "Ruby", "bytes": "294320" } ], "symlink_target": "" }
package cmd import ( "fmt" "github.com/spf13/cobra" ) // helpCmd represents the help command var helpCmd = &cobra.Command{ Use: "help [command]", Short: "Help about any command", Long: `Help provides help for any command in the application. Simply type ` + RootCmd.Name() + ` help [path to command] for full details.`, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Command was %v\n", cmd.Name()) cmd.Help() }, } func init() { RootCmd.AddCommand(helpCmd) }
{ "content_hash": "b03d8872d46ad85f8c2aca7449ea2fd9", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 77, "avg_line_length": 22.09090909090909, "alnum_prop": 0.676954732510288, "repo_name": "davidewatson/careen", "id": "a4fa3bbd068e62cffa8d28b6bebec5884fc0bfe8", "size": "1079", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmd/help.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "18094" }, { "name": "Makefile", "bytes": "780" }, { "name": "Shell", "bytes": "1269" } ], "symlink_target": "" }
{-# LANGUAGE Rank2Types #-} -- from base import Control.Applicative ((<$>)) import Control.Monad.ST (runST) import Data.Word (Word8) -- from bytestring import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L -- from crypto-api import Crypto.Classes ((.::.)) import qualified Crypto.Classes as C import qualified Crypto.HMAC as C import qualified Crypto.Modes as CM --import qualified Crypto.Padding as C --import qualified Crypto.Random as C import qualified Crypto.Types as C -- from conduit import Data.Conduit import Data.Conduit.Binary (isolate) import Data.Conduit.List (sourceList, consume) -- from cryptohash-cryptoapi import Crypto.Hash.CryptoAPI ( MD2, MD4, MD5, RIPEMD160, SHA1, SHA224 , SHA256, SHA384, SHA512, Tiger ) -- from skein import qualified Crypto.Skein as Skein -- from hspec import Test.Hspec import Test.Hspec.QuickCheck -- from this package import Crypto.Conduit main :: IO () main = hspec $ do describe "cryptohash's MD2" $ testHash (undefined :: MD2) describe "cryptohash's MD4" $ testHash (undefined :: MD4) describe "cryptohash's MD5" $ testHash (undefined :: MD5) describe "cryptohash's RIPEMD160" $ testHash (undefined :: RIPEMD160) describe "cryptohash's SHA1" $ testHash (undefined :: SHA1) describe "cryptohash's SHA224" $ testHash (undefined :: SHA224) describe "cryptohash's SHA256" $ testHash (undefined :: SHA256) describe "cryptohash's SHA384" $ testHash (undefined :: SHA384) describe "cryptohash's SHA512" $ testHash (undefined :: SHA512) describe "cryptohash's Tiger" $ testHash (undefined :: Tiger) describe "skein's Skein_512_512" $ testHash (undefined :: Skein.Skein_512_512) describe "skein's Skein_1024_1024" $ testHash (undefined :: Skein.Skein_1024_1024) describe "skein's Skein_256_256" $ testHash (undefined :: Skein.Skein_256_256) describe "skein's Skein_256_128" $ testHash (undefined :: Skein.Skein_256_128) describe "skein's Skein_256_160" $ testHash (undefined :: Skein.Skein_256_160) describe "skein's Skein_256_224" $ testHash (undefined :: Skein.Skein_256_224) describe "skein's Skein_512_128" $ testHash (undefined :: Skein.Skein_512_128) describe "skein's Skein_512_160" $ testHash (undefined :: Skein.Skein_512_160) describe "skein's Skein_512_224" $ testHash (undefined :: Skein.Skein_512_224) describe "skein's Skein_512_256" $ testHash (undefined :: Skein.Skein_512_256) describe "skein's Skein_512_384" $ testHash (undefined :: Skein.Skein_512_384) describe "skein's Skein_1024_384" $ testHash (undefined :: Skein.Skein_1024_384) describe "skein's Skein_1024_512" $ testHash (undefined :: Skein.Skein_1024_512) ---------------------------------------------------------------------- testHash :: C.Hash ctx d => d -> Spec testHash d = do prop "works with sinkHash" $ \str -> prop_sinkHash d (L.pack str) prop "works with sinkHmac" $ \key str -> prop_sinkHmac d (C.MacKey $ B.pack key) (L.pack str) prop_sinkHash :: C.Hash ctx d => d -> L.ByteString -> Bool prop_sinkHash d input = let d1 = runPureResource $ sourceList (L.toChunks input) $$ sinkHash d2 = C.hashFunc d input in d1 == d2 prop_sinkHmac :: C.Hash ctx d => d -> C.MacKey ctx d -> L.ByteString -> Bool prop_sinkHmac d mackey input = let d1 = runPureResource $ sourceList (L.toChunks input) $$ sinkHmac mackey d2 = C.hmac mackey input `asTypeOf` d in d1 == d2 ---------------------------------------------------------------------- testBlockCipher :: C.BlockCipher k => k -> Spec testBlockCipher undefinedKey = do let Just k = let len = (C.keyLength .::. k) `div` 8 in C.buildKey (B.replicate len 0xFF) `asTypeOf` Just undefinedKey blockSize = (C.blockSize .::. k) `div` 8 prop "works with conduitEncryptEcb" $ testBlockCipherConduit (Just blockSize) (conduitEncryptEcb k) (C.ecb k) prop "works with conduitDecryptEcb" $ testBlockCipherConduit (Just blockSize) (conduitDecryptEcb k) (C.unEcb k) prop "works with conduitEncryptCbc" $ testBlockCipherConduit (Just blockSize) (conduitEncryptCbc k C.zeroIV) (fst . C.cbc k C.zeroIV) prop "works with conduitDecryptCbc" $ testBlockCipherConduit (Just blockSize) (conduitDecryptCbc k C.zeroIV) (fst . C.unCbc k C.zeroIV) prop "works with conduitEncryptCfb" $ testBlockCipherConduit (Just blockSize) (conduitEncryptCfb k C.zeroIV) (fst . C.cfb k C.zeroIV) prop "works with conduitDecryptCfb" $ testBlockCipherConduit (Just blockSize) (conduitDecryptCfb k C.zeroIV) (fst . C.unCfb k C.zeroIV) prop "works with conduitEncryptOfb" $ testBlockCipherConduit (Just blockSize) (conduitEncryptOfb k C.zeroIV) (fst . C.ofb k C.zeroIV) prop "works with conduitDecryptOfb" $ testBlockCipherConduit (Just blockSize) (conduitDecryptOfb k C.zeroIV) (fst . C.unOfb k C.zeroIV) prop "works with conduitEncryptCtr" $ testBlockCipherConduit Nothing (conduitEncryptCtr k C.zeroIV C.incIV) (fst . C.ctr k C.zeroIV) prop "works with conduitDecryptCtr" $ testBlockCipherConduit Nothing (conduitDecryptCtr k C.zeroIV C.incIV) (fst . C.unCtr k C.zeroIV) it "works with sourceCtr" $ let len :: Num a => a len = 1024 * 1024 -- 1 MiB r1 = runPureResource $ sourceCtr k C.zeroIV $$ isolate len =$ consumeAsStrict r2 = fst $ C.ctr k C.zeroIV (B.replicate len 0) in r1 == r2 prop "works with sinkCbcMac" $ \input -> let inputL = fixBlockedSize blockSize (L.pack input) r1 = runPureResource $ sourceList (L.toChunks inputL) $$ sinkCbcMac k r2 = C.encode $ snd $ C.cbc k C.zeroIV $ B.pack input in r1 == r2 testBlockCipherConduit :: Maybe C.ByteLength -- ^ Fix input length to be a multiple of the block size? -> (forall m. Monad m => Conduit B.ByteString m B.ByteString) -> (B.ByteString -> B.ByteString) -> [Word8] -> Bool testBlockCipherConduit mblockSize conduit strictfun input = let inputL = maybe id fixBlockedSize mblockSize (L.pack input) r1 = runPureResource $ sourceList (L.toChunks inputL) $$ conduit =$ consumeAsStrict r2 = strictfun $ B.pack input in r1 == r2 ---------------------------------------------------------------------- runPureResource :: (forall m. Monad m => m a) -> a runPureResource r = runST r consumeAsLazy :: Monad m => Sink B.ByteString m L.ByteString consumeAsLazy = L.fromChunks <$> consume consumeAsStrict :: Monad m => Sink B.ByteString m B.ByteString consumeAsStrict = B.concat <$> consume fixBlockedSize :: C.ByteLength -> L.ByteString -> L.ByteString fixBlockedSize blockSize lbs = let blockSize' = fromIntegral blockSize toFill = let leftovers = L.length lbs `mod` blockSize' in if leftovers == 0 then 0 else blockSize' - leftovers in L.append lbs $ L.replicate toFill 0xFF
{ "content_hash": "b295dde2cf654a1295e2184aab14222e", "timestamp": "", "source": "github", "line_count": 203, "max_line_length": 91, "avg_line_length": 35.21182266009852, "alnum_prop": 0.6509513150531617, "repo_name": "prowdsponsor/crypto-conduit", "id": "311a078be8d9238ec56a7d761d96aeff83920671", "size": "7148", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/runtests.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "23430" } ], "symlink_target": "" }
package org.springframework.social.salesforce.client; import org.springframework.social.salesforce.api.Salesforce; import java.util.HashMap; import java.util.Map; /** * Simple caching wrapper for SalesforceFactory. * * @author Umut Utkan */ public class SimpleCachingSalesforceFactory implements SalesforceFactory { private SalesforceFactory delegate; private final Map<String, Salesforce> cache = new HashMap<String, Salesforce>(); public SimpleCachingSalesforceFactory(SalesforceFactory delegate) { this.delegate = delegate; } @Override public Salesforce create(String username, String password, String securityToken) { synchronized (this.cache) { Salesforce template = cache.get(username); if (template == null) { this.cache.put(username, this.delegate.create(username, password, securityToken)); } return this.cache.get(username); } } }
{ "content_hash": "929dcb134b17641e0d098824f722ce2b", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 98, "avg_line_length": 26.97222222222222, "alnum_prop": 0.6951596292481977, "repo_name": "silanis/spring-social-salesforce", "id": "4c7db9ae21fc345ef0376eba01acd3f695a9d7d0", "size": "971", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/springframework/social/salesforce/client/SimpleCachingSalesforceFactory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "114694" } ], "symlink_target": "" }
<?xml version="1.0" ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <!-- saved from url=(0017)http://localhost/ --> <script language="JavaScript" src="../../displayToc.js"></script> <script language="JavaScript" src="../../tocParas.js"></script> <script language="JavaScript" src="../../tocTab.js"></script> <link rel="stylesheet" type="text/css" href="../../scineplex.css"> <title></title> <link rel="stylesheet" href="../../Active.css" type="text/css" /> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <link rev="made" href="mailto:" /> </head> <body> <ul id="index"> <li><a href="#NAME">NAME</a></li> <li><a href="#VERSION">VERSION</a></li> <li><a href="#DESCRIPTION">DESCRIPTION</a></li> <li><a href="#RECIPES">RECIPES</a> <ul> <li><a href="#Basic-Moose">Basic Moose</a></li> <li><a href="#Moose-Roles">Moose Roles</a></li> <li><a href="#Meta-Moose">Meta Moose</a></li> <li><a href="#Extending-Moose">Extending Moose</a></li> </ul> </li> <li><a href="#SNACKS">SNACKS</a></li> <li><a href="#Legacy-Recipes">Legacy Recipes</a></li> <li><a href="#SEE-ALSO">SEE ALSO</a></li> <li><a href="#AUTHOR">AUTHOR</a></li> <li><a href="#COPYRIGHT-AND-LICENSE">COPYRIGHT AND LICENSE</a></li> </ul> <h1 id="NAME">NAME</h1> <p>Moose::Cookbook - How to cook a Moose</p> <h1 id="VERSION">VERSION</h1> <p>version 2.0604</p> <h1 id="DESCRIPTION">DESCRIPTION</h1> <p>The Moose cookbook is a series of recipes showing various Moose features. Most recipes present some code demonstrating some feature, and then explain the details of the code.</p> <p>You should probably read the <a href="../../lib/Moose/Manual.html">Moose::Manual</a> first. The manual explains Moose concepts without being too code-heavy.</p> <h1 id="RECIPES">RECIPES</h1> <h2 id="Basic-Moose">Basic Moose</h2> <p>These recipes will give you a good overview of Moose&#39;s capabilities, starting with simple attribute declaration, and moving on to more powerful features like laziness, types, type coercion, method modifiers, and more.</p> <dl> <dt id="Moose::Cookbook::Basics::Point_AttributesAndSubclassing"><a href="../../lib/Moose/Cookbook/Basics/Point_AttributesAndSubclassing.html">Moose::Cookbook::Basics::Point_AttributesAndSubclassing</a></dt> <dd> <p>A simple Moose-based class. Demonstrates basic Moose attributes and subclassing.</p> </dd> <dt id="Moose::Cookbook::Basics::BankAccount_MethodModifiersAndSubclassing"><a href="../../lib/Moose/Cookbook/Basics/BankAccount_MethodModifiersAndSubclassing.html">Moose::Cookbook::Basics::BankAccount_MethodModifiersAndSubclassing</a></dt> <dd> <p>A slightly more complex Moose class. Demonstrates using a method modifier in a subclass.</p> </dd> <dt id="Moose::Cookbook::Basics::BinaryTree_AttributeFeatures"><a href="../../lib/Moose/Cookbook/Basics/BinaryTree_AttributeFeatures.html">Moose::Cookbook::Basics::BinaryTree_AttributeFeatures</a></dt> <dd> <p>Demonstrates several attribute features, including types, weak references, predicates (&quot;does this object have a foo?&quot;), defaults, laziness, and triggers.</p> </dd> <dt id="Moose::Cookbook::Basics::Company_Subtypes"><a href="../../lib/Moose/Cookbook/Basics/Company_Subtypes.html">Moose::Cookbook::Basics::Company_Subtypes</a></dt> <dd> <p>Introduces the creation and use of custom types, a <code><code>BUILD</code></code> method, and the use of <code><code>override</code></code> in a subclass. This recipe also shows how to model a set of classes that could be used to model companies, people, employees, etc.</p> </dd> <dt id="Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion"><a href="../../lib/Moose/Cookbook/Basics/HTTP_SubtypesAndCoercion.html">Moose::Cookbook::Basics::HTTP_SubtypesAndCoercion</a></dt> <dd> <p>This recipe covers more subtype creation, including the use of type coercions.</p> </dd> <dt id="Moose::Cookbook::Basics::Immutable"><a href="../../lib/Moose/Cookbook/Basics/Immutable.html">Moose::Cookbook::Basics::Immutable</a></dt> <dd> <p>Making a class immutable greatly increases the speed of accessors and object construction.</p> </dd> <dt id="Moose::Cookbook::Basics::BinaryTree_BuilderAndLazyBuild---Builder-methods-and-lazy_build"><a href="../../lib/Moose/Cookbook/Basics/BinaryTree_BuilderAndLazyBuild.html">Moose::Cookbook::Basics::BinaryTree_BuilderAndLazyBuild</a> - Builder methods and lazy_build</dt> <dd> <p>The builder feature provides an inheritable and role-composable way to provide a default attribute value.</p> </dd> <dt id="Moose::Cookbook::Basics::Genome_OverloadingSubtypesAndCoercion"><a href="../../lib/Moose/Cookbook/Basics/Genome_OverloadingSubtypesAndCoercion.html">Moose::Cookbook::Basics::Genome_OverloadingSubtypesAndCoercion</a></dt> <dd> <p>Demonstrates using operator overloading, coercion, and subtypes to model how eye color is determined during reproduction.</p> </dd> <dt id="Moose::Cookbook::Basics::Person_BUILDARGSAndBUILD"><a href="../../lib/Moose/Cookbook/Basics/Person_BUILDARGSAndBUILD.html">Moose::Cookbook::Basics::Person_BUILDARGSAndBUILD</a></dt> <dd> <p>This recipe demonstrates the use of <code><code>BUILDARGS</code></code> and <code><code>BUILD</code></code> to hook into object construction.</p> </dd> <dt id="Moose::Cookbook::Basics::DateTime_ExtendingNonMooseParent"><a href="../../lib/Moose/Cookbook/Basics/DateTime_ExtendingNonMooseParent.html">Moose::Cookbook::Basics::DateTime_ExtendingNonMooseParent</a></dt> <dd> <p>In this recipe, we make a Moose-based subclass of <a href="../../lib/ActiveState/DateTime.html">DateTime</a>, a module which does not use Moose itself.</p> </dd> <dt id="Moose::Cookbook::Basics::Document_AugmentAndInner"><a href="../../lib/Moose/Cookbook/Basics/Document_AugmentAndInner.html">Moose::Cookbook::Basics::Document_AugmentAndInner</a></dt> <dd> <p>Demonstrates the use of <code><code>augment</code></code> method modifiers, a way of turning the usual method overriding style &quot;inside-out&quot;.</p> </dd> </dl> <h2 id="Moose-Roles">Moose Roles</h2> <p>These recipes will show you how to use Moose roles.</p> <dl> <dt id="Moose::Cookbook::Roles::Comparable_CodeReuse"><a href="../../lib/Moose/Cookbook/Roles/Comparable_CodeReuse.html">Moose::Cookbook::Roles::Comparable_CodeReuse</a></dt> <dd> <p>Demonstrates roles, which are also sometimes known as traits or mix-ins. Roles provide a method of code re-use which is orthogonal to subclassing.</p> </dd> <dt id="Moose::Cookbook::Roles::Restartable_AdvancedComposition"><a href="../../lib/Moose/Cookbook/Roles/Restartable_AdvancedComposition.html">Moose::Cookbook::Roles::Restartable_AdvancedComposition</a></dt> <dd> <p>Sometimes you just want to include part of a role in your class. Sometimes you want the whole role but one of its methods conflicts with one in your class. With method exclusion and aliasing, you can work around these problems.</p> </dd> <dt id="Moose::Cookbook::Roles::ApplicationToInstance"><a href="../../lib/Moose/Cookbook/Roles/ApplicationToInstance.html">Moose::Cookbook::Roles::ApplicationToInstance</a></dt> <dd> <p>In this recipe, we apply a role to an existing object instance.</p> </dd> </dl> <h2 id="Meta-Moose">Meta Moose</h2> <p>These recipes show you how to write your own meta classes, which lets you extend the object system provided by Moose.</p> <dl> <dt id="Moose::Cookbook::Meta::WhyMeta"><a href="../../lib/Moose/Cookbook/Meta/WhyMeta.html">Moose::Cookbook::Meta::WhyMeta</a></dt> <dd> <p>If you&#39;re wondering what all this &quot;meta&quot; stuff is, and why you should care about it, read this &quot;recipe&quot;.</p> </dd> <dt id="Moose::Cookbook::Meta::Labeled_AttributeTrait"><a href="../../lib/Moose/Cookbook/Meta/Labeled_AttributeTrait.html">Moose::Cookbook::Meta::Labeled_AttributeTrait</a></dt> <dd> <p>Extending Moose&#39;s attribute metaclass is a great way to add functionality. However, attributes can only have one metaclass. Applying roles to the attribute metaclass lets you provide composable attribute functionality.</p> </dd> <dt id="Moose::Cookbook::Meta::Table_MetaclassTrait"><a href="../../lib/Moose/Cookbook/Meta/Table_MetaclassTrait.html">Moose::Cookbook::Meta::Table_MetaclassTrait</a></dt> <dd> <p>This recipe takes the class metaclass we saw in the previous recipe and reimplements it as a metaclass trait.</p> </dd> <dt id="Moose::Cookbook::Meta::PrivateOrPublic_MethodMetaclass"><a href="../../lib/Moose/Cookbook/Meta/PrivateOrPublic_MethodMetaclass.html">Moose::Cookbook::Meta::PrivateOrPublic_MethodMetaclass</a></dt> <dd> <p>This recipe shows a custom method metaclass that implements making a method private.</p> </dd> <dt id="Moose::Cookbook::Meta::GlobRef_InstanceMetaclass"><a href="../../lib/Moose/Cookbook/Meta/GlobRef_InstanceMetaclass.html">Moose::Cookbook::Meta::GlobRef_InstanceMetaclass</a></dt> <dd> <p>This recipe shows an example of how you create your own meta-instance class. The meta-instance determines the internal structure of object instances and provide access to attribute slots.</p> <p>In this particular instance, we use a blessed glob reference as the instance instead of a blessed hash reference.</p> </dd> <dt id="Hooking-into-immutabilization-TODO-">Hooking into immutabilization (TODO)</dt> <dd> <p>Moose has a feature known as &quot;immutabilization&quot;. By calling <code><code>__PACKAGE__-&gt;meta()-&gt;make_immutable()</code></code> after defining your class (attributes, roles, etc), you tell Moose to optimize things like object creation, attribute access, and so on.</p> <p>If you are creating your own metaclasses, you may need to hook into the immutabilization system. This cuts across a number of spots, including the metaclass class, meta method classes, and possibly the meta-instance class as well.</p> <p>This recipe shows you how to write extensions which immutabilize properly.</p> </dd> </dl> <h2 id="Extending-Moose">Extending Moose</h2> <p>These recipes cover some more ways to extend Moose, and will be useful if you plan to write your own <code><code>MooseX</code></code> module.</p> <dl> <dt id="Moose::Cookbook::Extending::ExtensionOverview"><a href="../../lib/Moose/Cookbook/Extending/ExtensionOverview.html">Moose::Cookbook::Extending::ExtensionOverview</a></dt> <dd> <p>There are quite a few ways to extend Moose. This recipe provides an overview of each method, and provides recommendations for when each is appropriate.</p> </dd> <dt id="Moose::Cookbook::Extending::Debugging_BaseClassRole"><a href="../../lib/Moose/Cookbook/Extending/Debugging_BaseClassRole.html">Moose::Cookbook::Extending::Debugging_BaseClassRole</a></dt> <dd> <p>Many base object class extensions can be implemented as roles. This example shows how to provide a base object class debugging role that is applied to any class that uses a notional <code><code>MooseX::Debugging</code></code> module.</p> </dd> <dt id="Moose::Cookbook::Extending::Mooseish_MooseSugar"><a href="../../lib/Moose/Cookbook/Extending/Mooseish_MooseSugar.html">Moose::Cookbook::Extending::Mooseish_MooseSugar</a></dt> <dd> <p>This recipe shows how to provide a replacement for <code><code>Moose.pm</code></code>. You may want to do this as part of the API for a <code><code>MooseX</code></code> module, especially if you want to default to a new metaclass class or base object class.</p> </dd> </dl> <h1 id="SNACKS">SNACKS</h1> <dl> <dt id="Moose::Cookbook::Snack::Keywords"><a href="../../lib/Moose/Cookbook/Snack/Keywords.html">Moose::Cookbook::Snack::Keywords</a></dt> <dd> </dd> <dt id="Moose::Cookbook::Snack::Types"><a href="../../lib/Moose/Cookbook/Snack/Types.html">Moose::Cookbook::Snack::Types</a></dt> <dd> </dd> </dl> <h1 id="Legacy-Recipes">Legacy Recipes</h1> <p>These cover topics that are no longer considered best practice. We&#39;ve kept them in case in you encounter these usages in the wild.</p> <dl> <dt id="Moose::Cookbook::Legacy::Labeled_AttributeMetaclass"><a href="../../lib/Moose/Cookbook/Legacy/Labeled_AttributeMetaclass.html">Moose::Cookbook::Legacy::Labeled_AttributeMetaclass</a></dt> <dd> </dd> <dt id="Moose::Cookbook::Legacy::Table_ClassMetaclass"><a href="../../lib/Moose/Cookbook/Legacy/Table_ClassMetaclass.html">Moose::Cookbook::Legacy::Table_ClassMetaclass</a></dt> <dd> </dd> <dt id="Moose::Cookbook::Legacy::Debugging_BaseClassReplacement"><a href="../../lib/Moose/Cookbook/Legacy/Debugging_BaseClassReplacement.html">Moose::Cookbook::Legacy::Debugging_BaseClassReplacement</a></dt> <dd> </dd> </dl> <h1 id="SEE-ALSO">SEE ALSO</h1> <dl> <dt id="http:-www.gsph.com-index.php-Lang-EnID-291"><a href="http://www.gsph.com/index.php?Lang=En&amp;ID=291">http://www.gsph.com/index.php?Lang=En&amp;ID=291</a></dt> <dd> </dd> </dl> <h1 id="AUTHOR">AUTHOR</h1> <p>Moose is maintained by the Moose Cabal, along with the help of many contributors. See <a href="../../lib/Moose.html#CABAL">&quot;CABAL&quot; in Moose</a> and <a href="../../lib/Moose.html#CONTRIBUTORS">&quot;CONTRIBUTORS&quot; in Moose</a> for details.</p> <h1 id="COPYRIGHT-AND-LICENSE">COPYRIGHT AND LICENSE</h1> <p>This software is copyright (c) 2012 by Infinity Interactive, Inc..</p> <p>This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.</p> </body> </html>
{ "content_hash": "302b36254709831c58d57ef6e9e765ad", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 283, "avg_line_length": 46.1, "alnum_prop": 0.7281771261874486, "repo_name": "amidoimidazol/bio_info", "id": "b0d39084eafece7895b4e14664046cd67157ddda", "size": "13369", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Beginning Perl for Bioinformatics/html/lib/Moose/Cookbook.html", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "59131" }, { "name": "C", "bytes": "6411096" }, { "name": "C++", "bytes": "948727" }, { "name": "CSS", "bytes": "19636" }, { "name": "Groff", "bytes": "729471" }, { "name": "HTML", "bytes": "36592112" }, { "name": "JavaScript", "bytes": "276009" }, { "name": "Objective-C", "bytes": "9782" }, { "name": "Perl", "bytes": "35025376" }, { "name": "Perl6", "bytes": "474376" }, { "name": "Prolog", "bytes": "2605820" }, { "name": "Python", "bytes": "1276815" }, { "name": "Tcl", "bytes": "226362" }, { "name": "Visual Basic", "bytes": "269" } ], "symlink_target": "" }
ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
{ "content_hash": "16507b294b040713e9637dfb93e5d56e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 23, "avg_line_length": 9.076923076923077, "alnum_prop": 0.6779661016949152, "repo_name": "mdoering/backbone", "id": "abeffc3787bf760e7e35444c73af1d5edc02c9e1", "size": "181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Scrophulariaceae/Scrophularia/Scrophularia scorodonia/Scrophularia scorodonia scorodonia/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.opensoc.topology; import org.apache.commons.configuration.ConfigurationException; import backtype.storm.generated.InvalidTopologyException; import com.opensoc.topology.runner.LancopeRunner; import com.opensoc.topology.runner.TopologyRunner; /** * Topology for processing Lancope messages * */ public class Lancope{ public static void main(String[] args) throws ConfigurationException, Exception, InvalidTopologyException { TopologyRunner runner = new LancopeRunner(); runner.initTopology(args, "lancope"); } }
{ "content_hash": "933e03dc86a58cb306dab11fc97e204c", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 108, "avg_line_length": 22.666666666666668, "alnum_prop": 0.7922794117647058, "repo_name": "OpenSOC/opensoc-streaming", "id": "c3ecc54beb6ecce6d39d5109a6f3181175dba512", "size": "1345", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "OpenSOC-Topologies/src/main/java/com/opensoc/topology/Lancope.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "872742" }, { "name": "Python", "bytes": "8130" } ], "symlink_target": "" }
package org.axonframework.springboot; import org.axonframework.config.ProcessingGroup; import org.axonframework.eventhandling.EventHandler; import org.axonframework.messaging.annotation.HandlerEnhancerDefinition; import org.axonframework.messaging.annotation.MessageHandlingMember; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableMBeanExport; import org.springframework.jmx.support.RegistrationPolicy; import org.springframework.test.context.ContextConfiguration; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nonnull; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test class verifying a {@link HandlerEnhancerDefinition} configurations. For example, that a {@code * HandlerEnhancerDefinition} bean will only wrap if there are message handling functions present. * * @author Steven van Beelen */ class HandlerEnhancerDefinitionConfigurationTest { private static final AtomicBoolean VERIFY_ENHANCER = new AtomicBoolean(false); @BeforeEach void setUp() { VERIFY_ENHANCER.compareAndSet(true, false); } @Test void handlerEnhancerDefinitionWrapsEventHandler() { new ApplicationContextRunner() .withUserConfiguration(ContextWithHandlers.class) .withPropertyValues("axon.axonserver.enabled=false") .run(context -> { assertThat(context).hasSingleBean(CustomHandlerEnhancerDefinition.class); assertThat(context).hasSingleBean(MyEventHandlingComponent.class); assertTrue(VERIFY_ENHANCER.get()); }); } @Test void handlerEnhancerDefinitionDoesNotWrapInAbsenceOfMessageHandlers() { new ApplicationContextRunner() .withUserConfiguration(ContextWithoutHandlers.class) .withPropertyValues("axon.axonserver.enabled=false") .run(context -> { assertThat(context).hasSingleBean(CustomHandlerEnhancerDefinition.class); assertFalse(VERIFY_ENHANCER.get()); }); } @ContextConfiguration @EnableAutoConfiguration @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) private static class ContextWithHandlers { @Bean public HandlerEnhancerDefinition customHandlerEnhancerDefinition() { return new CustomHandlerEnhancerDefinition(); } @Bean public MyEventHandlingComponent myEventHandlingComponent() { return new MyEventHandlingComponent(); } } @ContextConfiguration @EnableAutoConfiguration @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) private static class ContextWithoutHandlers { @Bean public HandlerEnhancerDefinition customHandlerEnhancerDefinition() { return new CustomHandlerEnhancerDefinition(); } } private static class CustomHandlerEnhancerDefinition implements HandlerEnhancerDefinition { @Override public @Nonnull <T> MessageHandlingMember<T> wrapHandler(@Nonnull MessageHandlingMember<T> original) { VERIFY_ENHANCER.set(true); return original; } } @ProcessingGroup("customGroup") private static class MyEventHandlingComponent { @EventHandler public void on(Object someEvent) { } } }
{ "content_hash": "8a9da15ff786292cc5182e68b205d151", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 102, "avg_line_length": 34.74545454545454, "alnum_prop": 0.7210884353741497, "repo_name": "AxonFramework/AxonFramework", "id": "8d57e80c49b451b7017c29c46278e6b6965a9f87", "size": "4428", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring-boot-autoconfigure/src/test/java/org/axonframework/springboot/HandlerEnhancerDefinitionConfigurationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "9480392" } ], "symlink_target": "" }
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2012 EMC Corp. // // @filename: // CLogicalSequence.cpp // // @doc: // Implementation of logical sequence operator //--------------------------------------------------------------------------- #include "gpopt/operators/CLogicalSequence.h" #include "gpos/base.h" #include "gpopt/base/CColRefSet.h" #include "gpopt/operators/CExpression.h" #include "gpopt/operators/CExpressionHandle.h" using namespace gpopt; //--------------------------------------------------------------------------- // @function: // CLogicalSequence::CLogicalSequence // // @doc: // ctor // //--------------------------------------------------------------------------- CLogicalSequence::CLogicalSequence(CMemoryPool *mp) : CLogical(mp) { GPOS_ASSERT(NULL != mp); } //--------------------------------------------------------------------------- // @function: // CLogicalSequence::Matches // // @doc: // Match function on operator level // //--------------------------------------------------------------------------- BOOL CLogicalSequence::Matches(COperator *pop) const { return pop->Eopid() == Eopid(); } //--------------------------------------------------------------------------- // @function: // CLogicalSequence::PxfsCandidates // // @doc: // Get candidate xforms // //--------------------------------------------------------------------------- CXformSet * CLogicalSequence::PxfsCandidates(CMemoryPool *mp) const { CXformSet *xform_set = GPOS_NEW(mp) CXformSet(mp); (void) xform_set->ExchangeSet(CXform::ExfImplementSequence); return xform_set; } //--------------------------------------------------------------------------- // @function: // CLogicalSequence::DeriveOutputColumns // // @doc: // Derive output columns // //--------------------------------------------------------------------------- CColRefSet * CLogicalSequence::DeriveOutputColumns(CMemoryPool *, // mp CExpressionHandle &exprhdl) { GPOS_ASSERT(1 <= exprhdl.Arity()); // get output columns of last child CColRefSet *pcrs = exprhdl.DeriveOutputColumns(exprhdl.Arity() - 1); pcrs->AddRef(); return pcrs; } //--------------------------------------------------------------------------- // @function: // CLogicalSequence::PkcDeriveKeys // // @doc: // Derive key collection // //--------------------------------------------------------------------------- CKeyCollection * CLogicalSequence::DeriveKeyCollection(CMemoryPool *, // mp CExpressionHandle &exprhdl) const { // return key of last child const ULONG arity = exprhdl.Arity(); return PkcDeriveKeysPassThru(exprhdl, arity - 1 /* ulChild */); } //--------------------------------------------------------------------------- // @function: // CLogicalSequence::DeriveMaxCard // // @doc: // Derive max card // //--------------------------------------------------------------------------- CMaxCard CLogicalSequence::DeriveMaxCard(CMemoryPool *, // mp CExpressionHandle &exprhdl) const { // pass on max card of last child return exprhdl.DeriveMaxCard(exprhdl.Arity() - 1); } //--------------------------------------------------------------------------- // @function: // CLogicalSequence::DerivePartitionInfo // // @doc: // Derive part consumers // //--------------------------------------------------------------------------- CPartInfo * CLogicalSequence::DerivePartitionInfo(CMemoryPool *mp, CExpressionHandle &exprhdl) const { return PpartinfoDeriveCombine(mp, exprhdl); } // EOF
{ "content_hash": "5612aab18ce924f08291ece0c7a5a674", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 77, "avg_line_length": 25.542857142857144, "alnum_prop": 0.45805369127516776, "repo_name": "greenplum-db/gporca", "id": "e45318466f60e4a9facd0f327e413d78aed4d4e3", "size": "3576", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "libgpopt/src/operators/CLogicalSequence.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "44424" }, { "name": "C++", "bytes": "12361209" }, { "name": "CMake", "bytes": "43200" }, { "name": "Python", "bytes": "84683" }, { "name": "Shell", "bytes": "4879" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2014 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <inset xmlns:android="http://schemas.android.com/apk/res/android" android:insetLeft="@dimen/abc_control_inset_material" android:insetTop="@dimen/abc_control_inset_material" android:insetBottom="@dimen/abc_control_inset_material" android:insetRight="@dimen/abc_control_inset_material"> <selector> <item android:state_checked="false" android:state_pressed="false"> <layer-list> <item android:drawable="@drawable/abc_textfield_default_mtrl_alpha" /> <item android:drawable="@drawable/abc_spinner_mtrl_am_alpha" /> </layer-list> </item> <item> <layer-list> <item android:drawable="@drawable/abc_textfield_activated_mtrl_alpha" /> <item android:drawable="@drawable/abc_spinner_mtrl_am_alpha" /> </layer-list> </item> </selector> </inset><!-- From: file:/usr/local/google/buildbot/src/googleplex-android/mnc-supportlib-release/frameworks/support/v7/appcompat/res/drawable/abc_spinner_textfield_background_material.xml --><!-- From: file:/C:/Users/Zacck/Documents/Uber/ParseStarterProject/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.1.1/res/drawable/abc_spinner_textfield_background_material.xml -->
{ "content_hash": "86f938b5f2a2784842229e6884fd44df", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 393, "avg_line_length": 54.666666666666664, "alnum_prop": 0.6864837398373984, "repo_name": "zacck/AndroidUberCloneDemo", "id": "061aec9b70dc0f5df2ff82b6642383f2b12fc280", "size": "1968", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ParseStarterProject/build/intermediates/res/debug/drawable/abc_spinner_textfield_background_material.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "544336" } ], "symlink_target": "" }
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{border:0;font-size:100%;font:inherit;vertical-align:baseline;margin:0;padding:0}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:before,blockquote:after,q:before,q:after{content:none}table{border-collapse:collapse;border-spacing:0} html{ overflow-y: scroll; } body { line-height: 1;font-family: Arial, Helvetica, sans-serif;font-size: 12px; width: 100%; height: 100%; color: #000; font-size: 14px; } h1{ font: 48px arial,helvetica,sans-serif bold; text-transform: uppercase; } h2{ font: 25px arial,helvetica,sans-serif bold; } .clear{ clear: both; } .clear-no-space { clear: both; height: 1px; margin:0px; overflow: hidden; padding:0px; } .right-text{ float: right; } .left-text{ float: left; } #wrapper { margin: 10px auto; width: 1000px; } #wrapper a { text-decoration: none; color: #F48A00; } #wrapper span.highlight { color: #F48A00; } #wrapper header #header { border-bottom: 1px solid #ccc; margin: 0px 0px 20px 0px; } #wrapper header #header hgroup h2 { font-family: 'Irish Grover', cursive; font-size: 92px; line-height: 110px; text-align: center; } #wrapper header #header hgroup h2 a { color: #000; } #wrapper header #header hgroup h3 { font-family: 'La Belle Aurore', cursive; font-size: 24px; text-align: center; font-weight: normal; margin: 0px 0px 20px 0px; } #wrapper header #header .top { margin: 0px 0px 10px 0px; } #wrapper header #header .top nav #main-nav{ float: right; list-style: none; position: relative; z-index: 94; } #wrapper header #header .top nav #main-nav li{ display: inline; padding: 0px 20px; position: relative; z-index: 94; } #wrapper header #header .top #account-holder{ float: right; padding: 0px 20px; } #wrapper section .main-col form .row{ width: 100%; } #wrapper section .main-col form .row label{ float: left; line-height: 2.5em; width: 175px; } #wrapper section .main-col form .row .controls{ float: left; } #wrapper section .main-col form .row .controls input{ border-radius: 3px; box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); font-size: 14px; height: 20px; outline: none; width: 200px; } #wrapper section .main-col form .row .controls textarea{ height: 200px; width: 400px; } #wrapper section .main-col form .row .controls input.error{ border: 1px solid #f00; } #wrapper section .main-col form .row .controls label.error{ color: #f00; display: block; font-weight: normal; float: none; width: auto; } #wrapper .sidebar{ float: right; } #wrapper footer #footer{ border-top: 1px solid #ccc; margin: 0px auto; padding: 5px 0px 0px 0px; text-align: center; }
{ "content_hash": "8bd98496214ef56f745d61dc42a48625", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 762, "avg_line_length": 24.62992125984252, "alnum_prop": 0.7164322250639387, "repo_name": "craigstroman/better-symblog", "id": "76a6277c708cdea78f2642edb01c57241a52c01d", "size": "3128", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/css/screen.css", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "62104" } ], "symlink_target": "" }
# bash/zsh completion support for core Git. # # Copyright (C) 2006,2007 Shawn O. Pearce <spearce@spearce.org> # Conceptually based on gitcompletion (http://gitweb.hawaga.org.uk/). # Distributed under the GNU General Public License, version 2.0. # # The contained completion routines provide support for completing: # # *) local and remote branch names # *) local and remote tag names # *) .git/remotes file names # *) git 'subcommands' # *) git email aliases for git-send-email # *) tree paths within 'ref:path/to/file' expressions # *) file paths within current working directory and index # *) common --long-options # # To use these routines: # # 1) Copy this file to somewhere (e.g. ~/.git-completion.bash). # 2) Add the following line to your .bashrc/.zshrc: # source ~/.git-completion.bash # 3) Consider changing your PS1 to also show the current branch, # see git-prompt.sh for details. # # If you use complex aliases of form '!f() { ... }; f', you can use the null # command ':' as the first command in the function body to declare the desired # completion style. For example '!f() { : git commit ; ... }; f' will # tell the completion to use commit completion. This also works with aliases # of form "!sh -c '...'". For example, "!sh -c ': git commit ; ... '". # # You can set the following environment variables to influence the behavior of # the completion routines: # # GIT_COMPLETION_CHECKOUT_NO_GUESS # # When set to "1", do not include "DWIM" suggestions in git-checkout # completion (e.g., completing "foo" when "origin/foo" exists). case "$COMP_WORDBREAKS" in *:*) : great ;; *) COMP_WORDBREAKS="$COMP_WORDBREAKS:" esac # Discovers the path to the git repository taking any '--git-dir=<path>' and # '-C <path>' options into account and stores it in the $__git_repo_path # variable. __git_find_repo_path () { if [ -n "$__git_repo_path" ]; then # we already know where it is return fi if [ -n "${__git_C_args-}" ]; then __git_repo_path="$(git "${__git_C_args[@]}" \ ${__git_dir:+--git-dir="$__git_dir"} \ rev-parse --absolute-git-dir 2>/dev/null)" elif [ -n "${__git_dir-}" ]; then test -d "$__git_dir" && __git_repo_path="$__git_dir" elif [ -n "${GIT_DIR-}" ]; then test -d "${GIT_DIR-}" && __git_repo_path="$GIT_DIR" elif [ -d .git ]; then __git_repo_path=.git else __git_repo_path="$(git rev-parse --git-dir 2>/dev/null)" fi } # Deprecated: use __git_find_repo_path() and $__git_repo_path instead # __gitdir accepts 0 or 1 arguments (i.e., location) # returns location of .git repo __gitdir () { if [ -z "${1-}" ]; then __git_find_repo_path || return 1 echo "$__git_repo_path" elif [ -d "$1/.git" ]; then echo "$1/.git" else echo "$1" fi } # Runs git with all the options given as argument, respecting any # '--git-dir=<path>' and '-C <path>' options present on the command line __git () { git ${__git_C_args:+"${__git_C_args[@]}"} \ ${__git_dir:+--git-dir="$__git_dir"} "$@" 2>/dev/null } # The following function is based on code from: # # bash_completion - programmable completion functions for bash 3.2+ # # Copyright © 2006-2008, Ian Macdonald <ian@caliban.org> # © 2009-2010, Bash Completion Maintainers # <bash-completion-devel@lists.alioth.debian.org> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # The latest version of this software can be obtained here: # # http://bash-completion.alioth.debian.org/ # # RELEASE: 2.x # This function can be used to access a tokenized list of words # on the command line: # # __git_reassemble_comp_words_by_ref '=:' # if test "${words_[cword_-1]}" = -w # then # ... # fi # # The argument should be a collection of characters from the list of # word completion separators (COMP_WORDBREAKS) to treat as ordinary # characters. # # This is roughly equivalent to going back in time and setting # COMP_WORDBREAKS to exclude those characters. The intent is to # make option types like --date=<type> and <rev>:<path> easy to # recognize by treating each shell word as a single token. # # It is best not to set COMP_WORDBREAKS directly because the value is # shared with other completion scripts. By the time the completion # function gets called, COMP_WORDS has already been populated so local # changes to COMP_WORDBREAKS have no effect. # # Output: words_, cword_, cur_. __git_reassemble_comp_words_by_ref() { local exclude i j first # Which word separators to exclude? exclude="${1//[^$COMP_WORDBREAKS]}" cword_=$COMP_CWORD if [ -z "$exclude" ]; then words_=("${COMP_WORDS[@]}") return fi # List of word completion separators has shrunk; # re-assemble words to complete. for ((i=0, j=0; i < ${#COMP_WORDS[@]}; i++, j++)); do # Append each nonempty word consisting of just # word separator characters to the current word. first=t while [ $i -gt 0 ] && [ -n "${COMP_WORDS[$i]}" ] && # word consists of excluded word separators [ "${COMP_WORDS[$i]//[^$exclude]}" = "${COMP_WORDS[$i]}" ] do # Attach to the previous token, # unless the previous token is the command name. if [ $j -ge 2 ] && [ -n "$first" ]; then ((j--)) fi first= words_[$j]=${words_[j]}${COMP_WORDS[i]} if [ $i = $COMP_CWORD ]; then cword_=$j fi if (($i < ${#COMP_WORDS[@]} - 1)); then ((i++)) else # Done. return fi done words_[$j]=${words_[j]}${COMP_WORDS[i]} if [ $i = $COMP_CWORD ]; then cword_=$j fi done } if ! type _get_comp_words_by_ref >/dev/null 2>&1; then _get_comp_words_by_ref () { local exclude cur_ words_ cword_ if [ "$1" = "-n" ]; then exclude=$2 shift 2 fi __git_reassemble_comp_words_by_ref "$exclude" cur_=${words_[cword_]} while [ $# -gt 0 ]; do case "$1" in cur) cur=$cur_ ;; prev) prev=${words_[$cword_-1]} ;; words) words=("${words_[@]}") ;; cword) cword=$cword_ ;; esac shift done } fi # Fills the COMPREPLY array with prefiltered words without any additional # processing. # Callers must take care of providing only words that match the current word # to be completed and adding any prefix and/or suffix (trailing space!), if # necessary. # 1: List of newline-separated matching completion words, complete with # prefix and suffix. __gitcomp_direct () { local IFS=$'\n' COMPREPLY=($1) } __gitcompappend () { local x i=${#COMPREPLY[@]} for x in $1; do if [[ "$x" == "$3"* ]]; then COMPREPLY[i++]="$2$x$4" fi done } __gitcompadd () { COMPREPLY=() __gitcompappend "$@" } # Generates completion reply, appending a space to possible completion words, # if necessary. # It accepts 1 to 4 arguments: # 1: List of possible completion words. # 2: A prefix to be added to each possible completion word (optional). # 3: Generate possible completion matches for this word (optional). # 4: A suffix to be appended to each possible completion word (optional). __gitcomp () { local cur_="${3-$cur}" case "$cur_" in --*=) ;; *) local c i=0 IFS=$' \t\n' for c in $1; do c="$c${4-}" if [[ $c == "$cur_"* ]]; then case $c in --*=*|*.) ;; *) c="$c " ;; esac COMPREPLY[i++]="${2-}$c" fi done ;; esac } # Variation of __gitcomp_nl () that appends to the existing list of # completion candidates, COMPREPLY. __gitcomp_nl_append () { local IFS=$'\n' __gitcompappend "$1" "${2-}" "${3-$cur}" "${4- }" } # Generates completion reply from newline-separated possible completion words # by appending a space to all of them. # It accepts 1 to 4 arguments: # 1: List of possible completion words, separated by a single newline. # 2: A prefix to be added to each possible completion word (optional). # 3: Generate possible completion matches for this word (optional). # 4: A suffix to be appended to each possible completion word instead of # the default space (optional). If specified but empty, nothing is # appended. __gitcomp_nl () { COMPREPLY=() __gitcomp_nl_append "$@" } # Generates completion reply with compgen from newline-separated possible # completion filenames. # It accepts 1 to 3 arguments: # 1: List of possible completion filenames, separated by a single newline. # 2: A directory prefix to be added to each possible completion filename # (optional). # 3: Generate possible completion matches for this word (optional). __gitcomp_file () { local IFS=$'\n' # XXX does not work when the directory prefix contains a tilde, # since tilde expansion is not applied. # This means that COMPREPLY will be empty and Bash default # completion will be used. __gitcompadd "$1" "${2-}" "${3-$cur}" "" # use a hack to enable file mode in bash < 4 compopt -o filenames +o nospace 2>/dev/null || compgen -f /non-existing-dir/ > /dev/null } # Execute 'git ls-files', unless the --committable option is specified, in # which case it runs 'git diff-index' to find out the files that can be # committed. It return paths relative to the directory specified in the first # argument, and using the options specified in the second argument. __git_ls_files_helper () { if [ "$2" == "--committable" ]; then __git -C "$1" diff-index --name-only --relative HEAD else # NOTE: $2 is not quoted in order to support multiple options __git -C "$1" ls-files --exclude-standard $2 fi } # __git_index_files accepts 1 or 2 arguments: # 1: Options to pass to ls-files (required). # 2: A directory path (optional). # If provided, only files within the specified directory are listed. # Sub directories are never recursed. Path must have a trailing # slash. __git_index_files () { local root="${2-.}" file __git_ls_files_helper "$root" "$1" | while read -r file; do case "$file" in ?*/*) echo "${file%%/*}" ;; *) echo "$file" ;; esac done | sort | uniq } # Lists branches from the local repository. # 1: A prefix to be added to each listed branch (optional). # 2: List only branches matching this word (optional; list all branches if # unset or empty). # 3: A suffix to be appended to each listed branch (optional). __git_heads () { local pfx="${1-}" cur_="${2-}" sfx="${3-}" __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \ "refs/heads/$cur_*" "refs/heads/$cur_*/**" } # Lists tags from the local repository. # Accepts the same positional parameters as __git_heads() above. __git_tags () { local pfx="${1-}" cur_="${2-}" sfx="${3-}" __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \ "refs/tags/$cur_*" "refs/tags/$cur_*/**" } # Lists refs from the local (by default) or from a remote repository. # It accepts 0, 1 or 2 arguments: # 1: The remote to list refs from (optional; ignored, if set but empty). # Can be the name of a configured remote, a path, or a URL. # 2: In addition to local refs, list unique branches from refs/remotes/ for # 'git checkout's tracking DWIMery (optional; ignored, if set but empty). # 3: A prefix to be added to each listed ref (optional). # 4: List only refs matching this word (optional; list all refs if unset or # empty). # 5: A suffix to be appended to each listed ref (optional; ignored, if set # but empty). # # Use __git_complete_refs() instead. __git_refs () { local i hash dir track="${2-}" local list_refs_from=path remote="${1-}" local format refs local pfx="${3-}" cur_="${4-$cur}" sfx="${5-}" local match="${4-}" local fer_pfx="${pfx//\%/%%}" # "escape" for-each-ref format specifiers __git_find_repo_path dir="$__git_repo_path" if [ -z "$remote" ]; then if [ -z "$dir" ]; then return fi else if __git_is_configured_remote "$remote"; then # configured remote takes precedence over a # local directory with the same name list_refs_from=remote elif [ -d "$remote/.git" ]; then dir="$remote/.git" elif [ -d "$remote" ]; then dir="$remote" else list_refs_from=url fi fi if [ "$list_refs_from" = path ]; then if [[ "$cur_" == ^* ]]; then pfx="$pfx^" fer_pfx="$fer_pfx^" cur_=${cur_#^} match=${match#^} fi case "$cur_" in refs|refs/*) format="refname" refs=("$match*" "$match*/**") track="" ;; *) for i in HEAD FETCH_HEAD ORIG_HEAD MERGE_HEAD; do case "$i" in $match*) if [ -e "$dir/$i" ]; then echo "$pfx$i$sfx" fi ;; esac done format="refname:strip=2" refs=("refs/tags/$match*" "refs/tags/$match*/**" "refs/heads/$match*" "refs/heads/$match*/**" "refs/remotes/$match*" "refs/remotes/$match*/**") ;; esac __git_dir="$dir" __git for-each-ref --format="$fer_pfx%($format)$sfx" \ "${refs[@]}" if [ -n "$track" ]; then # employ the heuristic used by git checkout # Try to find a remote branch that matches the completion word # but only output if the branch name is unique __git for-each-ref --format="$fer_pfx%(refname:strip=3)$sfx" \ --sort="refname:strip=3" \ "refs/remotes/*/$match*" "refs/remotes/*/$match*/**" | \ uniq -u fi return fi case "$cur_" in refs|refs/*) __git ls-remote "$remote" "$match*" | \ while read -r hash i; do case "$i" in *^{}) ;; *) echo "$pfx$i$sfx" ;; esac done ;; *) if [ "$list_refs_from" = remote ]; then case "HEAD" in $match*) echo "${pfx}HEAD$sfx" ;; esac __git for-each-ref --format="$fer_pfx%(refname:strip=3)$sfx" \ "refs/remotes/$remote/$match*" \ "refs/remotes/$remote/$match*/**" else local query_symref case "HEAD" in $match*) query_symref="HEAD" ;; esac __git ls-remote "$remote" $query_symref \ "refs/tags/$match*" "refs/heads/$match*" \ "refs/remotes/$match*" | while read -r hash i; do case "$i" in *^{}) ;; refs/*) echo "$pfx${i#refs/*/}$sfx" ;; *) echo "$pfx$i$sfx" ;; # symbolic refs esac done fi ;; esac } # Completes refs, short and long, local and remote, symbolic and pseudo. # # Usage: __git_complete_refs [<option>]... # --remote=<remote>: The remote to list refs from, can be the name of a # configured remote, a path, or a URL. # --track: List unique remote branches for 'git checkout's tracking DWIMery. # --pfx=<prefix>: A prefix to be added to each ref. # --cur=<word>: The current ref to be completed. Defaults to the current # word to be completed. # --sfx=<suffix>: A suffix to be appended to each ref instead of the default # space. __git_complete_refs () { local remote track pfx cur_="$cur" sfx=" " while test $# != 0; do case "$1" in --remote=*) remote="${1##--remote=}" ;; --track) track="yes" ;; --pfx=*) pfx="${1##--pfx=}" ;; --cur=*) cur_="${1##--cur=}" ;; --sfx=*) sfx="${1##--sfx=}" ;; *) return 1 ;; esac shift done __gitcomp_direct "$(__git_refs "$remote" "$track" "$pfx" "$cur_" "$sfx")" } # __git_refs2 requires 1 argument (to pass to __git_refs) # Deprecated: use __git_complete_fetch_refspecs() instead. __git_refs2 () { local i for i in $(__git_refs "$1"); do echo "$i:$i" done } # Completes refspecs for fetching from a remote repository. # 1: The remote repository. # 2: A prefix to be added to each listed refspec (optional). # 3: The ref to be completed as a refspec instead of the current word to be # completed (optional) # 4: A suffix to be appended to each listed refspec instead of the default # space (optional). __git_complete_fetch_refspecs () { local i remote="$1" pfx="${2-}" cur_="${3-$cur}" sfx="${4- }" __gitcomp_direct "$( for i in $(__git_refs "$remote" "" "" "$cur_") ; do echo "$pfx$i:$i$sfx" done )" } # __git_refs_remotes requires 1 argument (to pass to ls-remote) __git_refs_remotes () { local i hash __git ls-remote "$1" 'refs/heads/*' | \ while read -r hash i; do echo "$i:refs/remotes/$1/${i#refs/heads/}" done } __git_remotes () { __git_find_repo_path test -d "$__git_repo_path/remotes" && ls -1 "$__git_repo_path/remotes" __git remote } # Returns true if $1 matches the name of a configured remote, false otherwise. __git_is_configured_remote () { local remote for remote in $(__git_remotes); do if [ "$remote" = "$1" ]; then return 0 fi done return 1 } __git_list_merge_strategies () { git merge -s help 2>&1 | sed -n -e '/[Aa]vailable strategies are: /,/^$/{ s/\.$// s/.*:// s/^[ ]*// s/[ ]*$// p }' } __git_merge_strategies= # 'git merge -s help' (and thus detection of the merge strategy # list) fails, unfortunately, if run outside of any git working # tree. __git_merge_strategies is set to the empty string in # that case, and the detection will be repeated the next time it # is needed. __git_compute_merge_strategies () { test -n "$__git_merge_strategies" || __git_merge_strategies=$(__git_list_merge_strategies) } __git_complete_revlist_file () { local pfx ls ref cur_="$cur" case "$cur_" in *..?*:*) return ;; ?*:*) ref="${cur_%%:*}" cur_="${cur_#*:}" case "$cur_" in ?*/*) pfx="${cur_%/*}" cur_="${cur_##*/}" ls="$ref:$pfx" pfx="$pfx/" ;; *) ls="$ref" ;; esac case "$COMP_WORDBREAKS" in *:*) : great ;; *) pfx="$ref:$pfx" ;; esac __gitcomp_nl "$(__git ls-tree "$ls" \ | sed '/^100... blob /{ s,^.* ,, s,$, , } /^120000 blob /{ s,^.* ,, s,$, , } /^040000 tree /{ s,^.* ,, s,$,/, } s/^.* //')" \ "$pfx" "$cur_" "" ;; *...*) pfx="${cur_%...*}..." cur_="${cur_#*...}" __git_complete_refs --pfx="$pfx" --cur="$cur_" ;; *..*) pfx="${cur_%..*}.." cur_="${cur_#*..}" __git_complete_refs --pfx="$pfx" --cur="$cur_" ;; *) __git_complete_refs ;; esac } # __git_complete_index_file requires 1 argument: # 1: the options to pass to ls-file # # The exception is --committable, which finds the files appropriate commit. __git_complete_index_file () { local pfx="" cur_="$cur" case "$cur_" in ?*/*) pfx="${cur_%/*}" cur_="${cur_##*/}" pfx="${pfx}/" ;; esac __gitcomp_file "$(__git_index_files "$1" ${pfx:+"$pfx"})" "$pfx" "$cur_" } __git_complete_file () { __git_complete_revlist_file } __git_complete_revlist () { __git_complete_revlist_file } __git_complete_remote_or_refspec () { local cur_="$cur" cmd="${words[1]}" local i c=2 remote="" pfx="" lhs=1 no_complete_refspec=0 if [ "$cmd" = "remote" ]; then ((c++)) fi while [ $c -lt $cword ]; do i="${words[c]}" case "$i" in --mirror) [ "$cmd" = "push" ] && no_complete_refspec=1 ;; -d|--delete) [ "$cmd" = "push" ] && lhs=0 ;; --all) case "$cmd" in push) no_complete_refspec=1 ;; fetch) return ;; *) ;; esac ;; -*) ;; *) remote="$i"; break ;; esac ((c++)) done if [ -z "$remote" ]; then __gitcomp_nl "$(__git_remotes)" return fi if [ $no_complete_refspec = 1 ]; then return fi [ "$remote" = "." ] && remote= case "$cur_" in *:*) case "$COMP_WORDBREAKS" in *:*) : great ;; *) pfx="${cur_%%:*}:" ;; esac cur_="${cur_#*:}" lhs=0 ;; +*) pfx="+" cur_="${cur_#+}" ;; esac case "$cmd" in fetch) if [ $lhs = 1 ]; then __git_complete_fetch_refspecs "$remote" "$pfx" "$cur_" else __git_complete_refs --pfx="$pfx" --cur="$cur_" fi ;; pull|remote) if [ $lhs = 1 ]; then __git_complete_refs --remote="$remote" --pfx="$pfx" --cur="$cur_" else __git_complete_refs --pfx="$pfx" --cur="$cur_" fi ;; push) if [ $lhs = 1 ]; then __git_complete_refs --pfx="$pfx" --cur="$cur_" else __git_complete_refs --remote="$remote" --pfx="$pfx" --cur="$cur_" fi ;; esac } __git_complete_strategy () { __git_compute_merge_strategies case "$prev" in -s|--strategy) __gitcomp "$__git_merge_strategies" return 0 esac case "$cur" in --strategy=*) __gitcomp "$__git_merge_strategies" "" "${cur##--strategy=}" return 0 ;; esac return 1 } __git_commands () { if test -n "${GIT_TESTING_COMMAND_COMPLETION:-}" then printf "%s" "${GIT_TESTING_COMMAND_COMPLETION}" else git help -a|egrep '^ [a-zA-Z0-9]' fi } __git_list_all_commands () { local i IFS=" "$'\n' for i in $(__git_commands) do case $i in *--*) : helper pattern;; *) echo $i;; esac done } __git_all_commands= __git_compute_all_commands () { test -n "$__git_all_commands" || __git_all_commands=$(__git_list_all_commands) } __git_list_porcelain_commands () { local i IFS=" "$'\n' __git_compute_all_commands for i in $__git_all_commands do case $i in *--*) : helper pattern;; applymbox) : ask gittus;; applypatch) : ask gittus;; archimport) : import;; cat-file) : plumbing;; check-attr) : plumbing;; check-ignore) : plumbing;; check-mailmap) : plumbing;; check-ref-format) : plumbing;; checkout-index) : plumbing;; column) : internal helper;; commit-tree) : plumbing;; count-objects) : infrequent;; credential) : credentials;; credential-*) : credentials helper;; cvsexportcommit) : export;; cvsimport) : import;; cvsserver) : daemon;; daemon) : daemon;; diff-files) : plumbing;; diff-index) : plumbing;; diff-tree) : plumbing;; fast-import) : import;; fast-export) : export;; fsck-objects) : plumbing;; fetch-pack) : plumbing;; fmt-merge-msg) : plumbing;; for-each-ref) : plumbing;; hash-object) : plumbing;; http-*) : transport;; index-pack) : plumbing;; init-db) : deprecated;; local-fetch) : plumbing;; ls-files) : plumbing;; ls-remote) : plumbing;; ls-tree) : plumbing;; mailinfo) : plumbing;; mailsplit) : plumbing;; merge-*) : plumbing;; mktree) : plumbing;; mktag) : plumbing;; pack-objects) : plumbing;; pack-redundant) : plumbing;; pack-refs) : plumbing;; parse-remote) : plumbing;; patch-id) : plumbing;; prune) : plumbing;; prune-packed) : plumbing;; quiltimport) : import;; read-tree) : plumbing;; receive-pack) : plumbing;; remote-*) : transport;; rerere) : plumbing;; rev-list) : plumbing;; rev-parse) : plumbing;; runstatus) : plumbing;; sh-setup) : internal;; shell) : daemon;; show-ref) : plumbing;; send-pack) : plumbing;; show-index) : plumbing;; ssh-*) : transport;; stripspace) : plumbing;; symbolic-ref) : plumbing;; unpack-file) : plumbing;; unpack-objects) : plumbing;; update-index) : plumbing;; update-ref) : plumbing;; update-server-info) : daemon;; upload-archive) : plumbing;; upload-pack) : plumbing;; write-tree) : plumbing;; var) : infrequent;; verify-pack) : infrequent;; verify-tag) : plumbing;; *) echo $i;; esac done } __git_porcelain_commands= __git_compute_porcelain_commands () { test -n "$__git_porcelain_commands" || __git_porcelain_commands=$(__git_list_porcelain_commands) } # Lists all set config variables starting with the given section prefix, # with the prefix removed. __git_get_config_variables () { local section="$1" i IFS=$'\n' for i in $(__git config --name-only --get-regexp "^$section\..*"); do echo "${i#$section.}" done } __git_pretty_aliases () { __git_get_config_variables "pretty" } __git_aliases () { __git_get_config_variables "alias" } # __git_aliased_command requires 1 argument __git_aliased_command () { local word cmdline=$(__git config --get "alias.$1") for word in $cmdline; do case "$word" in \!gitk|gitk) echo "gitk" return ;; \!*) : shell command alias ;; -*) : option ;; *=*) : setting env ;; git) : git itself ;; \(\)) : skip parens of shell function definition ;; {) : skip start of shell helper function ;; :) : skip null command ;; \'*) : skip opening quote after sh -c ;; *) echo "$word" return esac done } # __git_find_on_cmdline requires 1 argument __git_find_on_cmdline () { local word subcommand c=1 while [ $c -lt $cword ]; do word="${words[c]}" for subcommand in $1; do if [ "$subcommand" = "$word" ]; then echo "$subcommand" return fi done ((c++)) done } # Echo the value of an option set on the command line or config # # $1: short option name # $2: long option name including = # $3: list of possible values # $4: config string (optional) # # example: # result="$(__git_get_option_value "-d" "--do-something=" \ # "yes no" "core.doSomething")" # # result is then either empty (no option set) or "yes" or "no" # # __git_get_option_value requires 3 arguments __git_get_option_value () { local c short_opt long_opt val local result= values config_key word short_opt="$1" long_opt="$2" values="$3" config_key="$4" ((c = $cword - 1)) while [ $c -ge 0 ]; do word="${words[c]}" for val in $values; do if [ "$short_opt$val" = "$word" ] || [ "$long_opt$val" = "$word" ]; then result="$val" break 2 fi done ((c--)) done if [ -n "$config_key" ] && [ -z "$result" ]; then result="$(__git config "$config_key")" fi echo "$result" } __git_has_doubledash () { local c=1 while [ $c -lt $cword ]; do if [ "--" = "${words[c]}" ]; then return 0 fi ((c++)) done return 1 } # Try to count non option arguments passed on the command line for the # specified git command. # When options are used, it is necessary to use the special -- option to # tell the implementation were non option arguments begin. # XXX this can not be improved, since options can appear everywhere, as # an example: # git mv x -n y # # __git_count_arguments requires 1 argument: the git command executed. __git_count_arguments () { local word i c=0 # Skip "git" (first argument) for ((i=1; i < ${#words[@]}; i++)); do word="${words[i]}" case "$word" in --) # Good; we can assume that the following are only non # option arguments. ((c = 0)) ;; "$1") # Skip the specified git command and discard git # main options ((c = 0)) ;; ?*) ((c++)) ;; esac done printf "%d" $c } __git_whitespacelist="nowarn warn error error-all fix" _git_am () { __git_find_repo_path if [ -d "$__git_repo_path"/rebase-apply ]; then __gitcomp "--skip --continue --resolved --abort" return fi case "$cur" in --whitespace=*) __gitcomp "$__git_whitespacelist" "" "${cur##--whitespace=}" return ;; --*) __gitcomp " --3way --committer-date-is-author-date --ignore-date --ignore-whitespace --ignore-space-change --interactive --keep --no-utf8 --signoff --utf8 --whitespace= --scissors " return esac } _git_apply () { case "$cur" in --whitespace=*) __gitcomp "$__git_whitespacelist" "" "${cur##--whitespace=}" return ;; --*) __gitcomp " --stat --numstat --summary --check --index --cached --index-info --reverse --reject --unidiff-zero --apply --no-add --exclude= --ignore-whitespace --ignore-space-change --whitespace= --inaccurate-eof --verbose --recount --directory= " return esac } _git_add () { case "$cur" in --*) __gitcomp " --interactive --refresh --patch --update --dry-run --ignore-errors --intent-to-add --force --edit --chmod= " return esac local complete_opt="--others --modified --directory --no-empty-directory" if test -n "$(__git_find_on_cmdline "-u --update")" then complete_opt="--modified" fi __git_complete_index_file "$complete_opt" } _git_archive () { case "$cur" in --format=*) __gitcomp "$(git archive --list)" "" "${cur##--format=}" return ;; --remote=*) __gitcomp_nl "$(__git_remotes)" "" "${cur##--remote=}" return ;; --*) __gitcomp " --format= --list --verbose --prefix= --remote= --exec= --output " return ;; esac __git_complete_file } _git_bisect () { __git_has_doubledash && return local subcommands="start bad good skip reset visualize replay log run" local subcommand="$(__git_find_on_cmdline "$subcommands")" if [ -z "$subcommand" ]; then __git_find_repo_path if [ -f "$__git_repo_path"/BISECT_START ]; then __gitcomp "$subcommands" else __gitcomp "replay start" fi return fi case "$subcommand" in bad|good|reset|skip|start) __git_complete_refs ;; *) ;; esac } _git_branch () { local i c=1 only_local_ref="n" has_r="n" while [ $c -lt $cword ]; do i="${words[c]}" case "$i" in -d|--delete|-m|--move) only_local_ref="y" ;; -r|--remotes) has_r="y" ;; esac ((c++)) done case "$cur" in --set-upstream-to=*) __git_complete_refs --cur="${cur##--set-upstream-to=}" ;; --*) __gitcomp " --color --no-color --verbose --abbrev= --no-abbrev --track --no-track --contains --no-contains --merged --no-merged --set-upstream-to= --edit-description --list --unset-upstream --delete --move --remotes --column --no-column --sort= --points-at " ;; *) if [ $only_local_ref = "y" -a $has_r = "n" ]; then __gitcomp_direct "$(__git_heads "" "$cur" " ")" else __git_complete_refs fi ;; esac } _git_bundle () { local cmd="${words[2]}" case "$cword" in 2) __gitcomp "create list-heads verify unbundle" ;; 3) # looking for a file ;; *) case "$cmd" in create) __git_complete_revlist ;; esac ;; esac } _git_checkout () { __git_has_doubledash && return case "$cur" in --conflict=*) __gitcomp "diff3 merge" "" "${cur##--conflict=}" ;; --*) __gitcomp " --quiet --ours --theirs --track --no-track --merge --conflict= --orphan --patch " ;; *) # check if --track, --no-track, or --no-guess was specified # if so, disable DWIM mode local flags="--track --no-track --no-guess" track_opt="--track" if [ "$GIT_COMPLETION_CHECKOUT_NO_GUESS" = "1" ] || [ -n "$(__git_find_on_cmdline "$flags")" ]; then track_opt='' fi __git_complete_refs $track_opt ;; esac } _git_cherry () { __git_complete_refs } _git_cherry_pick () { __git_find_repo_path if [ -f "$__git_repo_path"/CHERRY_PICK_HEAD ]; then __gitcomp "--continue --quit --abort" return fi case "$cur" in --*) __gitcomp "--edit --no-commit --signoff --strategy= --mainline" ;; *) __git_complete_refs ;; esac } _git_clean () { case "$cur" in --*) __gitcomp "--dry-run --quiet" return ;; esac # XXX should we check for -x option ? __git_complete_index_file "--others --directory" } _git_clone () { case "$cur" in --*) __gitcomp " --local --no-hardlinks --shared --reference --quiet --no-checkout --bare --mirror --origin --upload-pack --template= --depth --single-branch --no-tags --branch --recurse-submodules --no-single-branch --shallow-submodules " return ;; esac } __git_untracked_file_modes="all no normal" _git_commit () { case "$prev" in -c|-C) __git_complete_refs return ;; esac case "$cur" in --cleanup=*) __gitcomp "default scissors strip verbatim whitespace " "" "${cur##--cleanup=}" return ;; --reuse-message=*|--reedit-message=*|\ --fixup=*|--squash=*) __git_complete_refs --cur="${cur#*=}" return ;; --untracked-files=*) __gitcomp "$__git_untracked_file_modes" "" "${cur##--untracked-files=}" return ;; --*) __gitcomp " --all --author= --signoff --verify --no-verify --edit --no-edit --amend --include --only --interactive --dry-run --reuse-message= --reedit-message= --reset-author --file= --message= --template= --cleanup= --untracked-files --untracked-files= --verbose --quiet --fixup= --squash= --patch --short --date --allow-empty " return esac if __git rev-parse --verify --quiet HEAD >/dev/null; then __git_complete_index_file "--committable" else # This is the first commit __git_complete_index_file "--cached" fi } _git_describe () { case "$cur" in --*) __gitcomp " --all --tags --contains --abbrev= --candidates= --exact-match --debug --long --match --always --first-parent --exclude " return esac __git_complete_refs } __git_diff_algorithms="myers minimal patience histogram" __git_diff_submodule_formats="diff log short" __git_diff_common_options="--stat --numstat --shortstat --summary --patch-with-stat --name-only --name-status --color --no-color --color-words --no-renames --check --full-index --binary --abbrev --diff-filter= --find-copies-harder --text --ignore-space-at-eol --ignore-space-change --ignore-all-space --ignore-blank-lines --exit-code --quiet --ext-diff --no-ext-diff --no-prefix --src-prefix= --dst-prefix= --inter-hunk-context= --patience --histogram --minimal --raw --word-diff --word-diff-regex= --dirstat --dirstat= --dirstat-by-file --dirstat-by-file= --cumulative --diff-algorithm= --submodule --submodule= " _git_diff () { __git_has_doubledash && return case "$cur" in --diff-algorithm=*) __gitcomp "$__git_diff_algorithms" "" "${cur##--diff-algorithm=}" return ;; --submodule=*) __gitcomp "$__git_diff_submodule_formats" "" "${cur##--submodule=}" return ;; --*) __gitcomp "--cached --staged --pickaxe-all --pickaxe-regex --base --ours --theirs --no-index $__git_diff_common_options " return ;; esac __git_complete_revlist_file } __git_mergetools_common="diffuse diffmerge ecmerge emerge kdiff3 meld opendiff tkdiff vimdiff gvimdiff xxdiff araxis p4merge bc codecompare " _git_difftool () { __git_has_doubledash && return case "$cur" in --tool=*) __gitcomp "$__git_mergetools_common kompare" "" "${cur##--tool=}" return ;; --*) __gitcomp "--cached --staged --pickaxe-all --pickaxe-regex --base --ours --theirs --no-renames --diff-filter= --find-copies-harder --relative --ignore-submodules --tool=" return ;; esac __git_complete_revlist_file } __git_fetch_recurse_submodules="yes on-demand no" __git_fetch_options=" --quiet --verbose --append --upload-pack --force --keep --depth= --tags --no-tags --all --prune --dry-run --recurse-submodules= --unshallow --update-shallow " _git_fetch () { case "$cur" in --recurse-submodules=*) __gitcomp "$__git_fetch_recurse_submodules" "" "${cur##--recurse-submodules=}" return ;; --*) __gitcomp "$__git_fetch_options" return ;; esac __git_complete_remote_or_refspec } __git_format_patch_options=" --stdout --attach --no-attach --thread --thread= --no-thread --numbered --start-number --numbered-files --keep-subject --signoff --signature --no-signature --in-reply-to= --cc= --full-index --binary --not --all --cover-letter --no-prefix --src-prefix= --dst-prefix= --inline --suffix= --ignore-if-in-upstream --subject-prefix= --output-directory --reroll-count --to= --quiet --notes " _git_format_patch () { case "$cur" in --thread=*) __gitcomp " deep shallow " "" "${cur##--thread=}" return ;; --*) __gitcomp "$__git_format_patch_options" return ;; esac __git_complete_revlist } _git_fsck () { case "$cur" in --*) __gitcomp " --tags --root --unreachable --cache --no-reflogs --full --strict --verbose --lost-found --name-objects " return ;; esac } _git_gc () { case "$cur" in --*) __gitcomp "--prune --aggressive" return ;; esac } _git_gitk () { _gitk } # Lists matching symbol names from a tag (as in ctags) file. # 1: List symbol names matching this word. # 2: The tag file to list symbol names from. # 3: A prefix to be added to each listed symbol name (optional). # 4: A suffix to be appended to each listed symbol name (optional). __git_match_ctag () { awk -v pfx="${3-}" -v sfx="${4-}" " /^${1//\//\\/}/ { print pfx \$1 sfx } " "$2" } # Complete symbol names from a tag file. # Usage: __git_complete_symbol [<option>]... # --tags=<file>: The tag file to list symbol names from instead of the # default "tags". # --pfx=<prefix>: A prefix to be added to each symbol name. # --cur=<word>: The current symbol name to be completed. Defaults to # the current word to be completed. # --sfx=<suffix>: A suffix to be appended to each symbol name instead # of the default space. __git_complete_symbol () { local tags=tags pfx="" cur_="${cur-}" sfx=" " while test $# != 0; do case "$1" in --tags=*) tags="${1##--tags=}" ;; --pfx=*) pfx="${1##--pfx=}" ;; --cur=*) cur_="${1##--cur=}" ;; --sfx=*) sfx="${1##--sfx=}" ;; *) return 1 ;; esac shift done if test -r "$tags"; then __gitcomp_direct "$(__git_match_ctag "$cur_" "$tags" "$pfx" "$sfx")" fi } _git_grep () { __git_has_doubledash && return case "$cur" in --*) __gitcomp " --cached --text --ignore-case --word-regexp --invert-match --full-name --line-number --extended-regexp --basic-regexp --fixed-strings --perl-regexp --threads --files-with-matches --name-only --files-without-match --max-depth --count --and --or --not --all-match --break --heading --show-function --function-context --untracked --no-index " return ;; esac case "$cword,$prev" in 2,*|*,-*) __git_complete_symbol && return ;; esac __git_complete_refs } _git_help () { case "$cur" in --*) __gitcomp "--all --guides --info --man --web" return ;; esac __git_compute_all_commands __gitcomp "$__git_all_commands $(__git_aliases) attributes cli core-tutorial cvs-migration diffcore everyday gitk glossary hooks ignore modules namespaces repository-layout revisions tutorial tutorial-2 workflows " } _git_init () { case "$cur" in --shared=*) __gitcomp " false true umask group all world everybody " "" "${cur##--shared=}" return ;; --*) __gitcomp "--quiet --bare --template= --shared --shared=" return ;; esac } _git_ls_files () { case "$cur" in --*) __gitcomp "--cached --deleted --modified --others --ignored --stage --directory --no-empty-directory --unmerged --killed --exclude= --exclude-from= --exclude-per-directory= --exclude-standard --error-unmatch --with-tree= --full-name --abbrev --ignored --exclude-per-directory " return ;; esac # XXX ignore options like --modified and always suggest all cached # files. __git_complete_index_file "--cached" } _git_ls_remote () { case "$cur" in --*) __gitcomp "--heads --tags --refs --get-url --symref" return ;; esac __gitcomp_nl "$(__git_remotes)" } _git_ls_tree () { __git_complete_file } # Options that go well for log, shortlog and gitk __git_log_common_options=" --not --all --branches --tags --remotes --first-parent --merges --no-merges --max-count= --max-age= --since= --after= --min-age= --until= --before= --min-parents= --max-parents= --no-min-parents --no-max-parents " # Options that go well for log and gitk (not shortlog) __git_log_gitk_options=" --dense --sparse --full-history --simplify-merges --simplify-by-decoration --left-right --notes --no-notes " # Options that go well for log and shortlog (not gitk) __git_log_shortlog_options=" --author= --committer= --grep= --all-match --invert-grep " __git_log_pretty_formats="oneline short medium full fuller email raw format:" __git_log_date_formats="relative iso8601 rfc2822 short local default raw" _git_log () { __git_has_doubledash && return __git_find_repo_path local merge="" if [ -f "$__git_repo_path/MERGE_HEAD" ]; then merge="--merge" fi case "$prev,$cur" in -L,:*:*) return # fall back to Bash filename completion ;; -L,:*) __git_complete_symbol --cur="${cur#:}" --sfx=":" return ;; -G,*|-S,*) __git_complete_symbol return ;; esac case "$cur" in --pretty=*|--format=*) __gitcomp "$__git_log_pretty_formats $(__git_pretty_aliases) " "" "${cur#*=}" return ;; --date=*) __gitcomp "$__git_log_date_formats" "" "${cur##--date=}" return ;; --decorate=*) __gitcomp "full short no" "" "${cur##--decorate=}" return ;; --diff-algorithm=*) __gitcomp "$__git_diff_algorithms" "" "${cur##--diff-algorithm=}" return ;; --submodule=*) __gitcomp "$__git_diff_submodule_formats" "" "${cur##--submodule=}" return ;; --*) __gitcomp " $__git_log_common_options $__git_log_shortlog_options $__git_log_gitk_options --root --topo-order --date-order --reverse --follow --full-diff --abbrev-commit --abbrev= --relative-date --date= --pretty= --format= --oneline --show-signature --cherry-mark --cherry-pick --graph --decorate --decorate= --walk-reflogs --parents --children $merge $__git_diff_common_options --pickaxe-all --pickaxe-regex " return ;; -L:*:*) return # fall back to Bash filename completion ;; -L:*) __git_complete_symbol --cur="${cur#-L:}" --sfx=":" return ;; -G*) __git_complete_symbol --pfx="-G" --cur="${cur#-G}" return ;; -S*) __git_complete_symbol --pfx="-S" --cur="${cur#-S}" return ;; esac __git_complete_revlist } # Common merge options shared by git-merge(1) and git-pull(1). __git_merge_options=" --no-commit --no-stat --log --no-log --squash --strategy --commit --stat --no-squash --ff --no-ff --ff-only --edit --no-edit --verify-signatures --no-verify-signatures --gpg-sign --quiet --verbose --progress --no-progress " _git_merge () { __git_complete_strategy && return case "$cur" in --*) __gitcomp "$__git_merge_options --rerere-autoupdate --no-rerere-autoupdate --abort --continue" return esac __git_complete_refs } _git_mergetool () { case "$cur" in --tool=*) __gitcomp "$__git_mergetools_common tortoisemerge" "" "${cur##--tool=}" return ;; --*) __gitcomp "--tool= --prompt --no-prompt" return ;; esac } _git_merge_base () { case "$cur" in --*) __gitcomp "--octopus --independent --is-ancestor --fork-point" return ;; esac __git_complete_refs } _git_mv () { case "$cur" in --*) __gitcomp "--dry-run" return ;; esac if [ $(__git_count_arguments "mv") -gt 0 ]; then # We need to show both cached and untracked files (including # empty directories) since this may not be the last argument. __git_complete_index_file "--cached --others --directory" else __git_complete_index_file "--cached" fi } _git_name_rev () { __gitcomp "--tags --all --stdin" } _git_notes () { local subcommands='add append copy edit list prune remove show' local subcommand="$(__git_find_on_cmdline "$subcommands")" case "$subcommand,$cur" in ,--*) __gitcomp '--ref' ;; ,*) case "$prev" in --ref) __git_complete_refs ;; *) __gitcomp "$subcommands --ref" ;; esac ;; add,--reuse-message=*|append,--reuse-message=*|\ add,--reedit-message=*|append,--reedit-message=*) __git_complete_refs --cur="${cur#*=}" ;; add,--*|append,--*) __gitcomp '--file= --message= --reedit-message= --reuse-message=' ;; copy,--*) __gitcomp '--stdin' ;; prune,--*) __gitcomp '--dry-run --verbose' ;; prune,*) ;; *) case "$prev" in -m|-F) ;; *) __git_complete_refs ;; esac ;; esac } _git_pull () { __git_complete_strategy && return case "$cur" in --recurse-submodules=*) __gitcomp "$__git_fetch_recurse_submodules" "" "${cur##--recurse-submodules=}" return ;; --*) __gitcomp " --rebase --no-rebase $__git_merge_options $__git_fetch_options " return ;; esac __git_complete_remote_or_refspec } __git_push_recurse_submodules="check on-demand only" __git_complete_force_with_lease () { local cur_=$1 case "$cur_" in --*=) ;; *:*) __git_complete_refs --cur="${cur_#*:}" ;; *) __git_complete_refs --cur="$cur_" ;; esac } _git_push () { case "$prev" in --repo) __gitcomp_nl "$(__git_remotes)" return ;; --recurse-submodules) __gitcomp "$__git_push_recurse_submodules" return ;; esac case "$cur" in --repo=*) __gitcomp_nl "$(__git_remotes)" "" "${cur##--repo=}" return ;; --recurse-submodules=*) __gitcomp "$__git_push_recurse_submodules" "" "${cur##--recurse-submodules=}" return ;; --force-with-lease=*) __git_complete_force_with_lease "${cur##--force-with-lease=}" return ;; --*) __gitcomp " --all --mirror --tags --dry-run --force --verbose --quiet --prune --delete --follow-tags --receive-pack= --repo= --set-upstream --force-with-lease --force-with-lease= --recurse-submodules= " return ;; esac __git_complete_remote_or_refspec } _git_rebase () { __git_find_repo_path if [ -f "$__git_repo_path"/rebase-merge/interactive ]; then __gitcomp "--continue --skip --abort --quit --edit-todo" return elif [ -d "$__git_repo_path"/rebase-apply ] || \ [ -d "$__git_repo_path"/rebase-merge ]; then __gitcomp "--continue --skip --abort --quit" return fi __git_complete_strategy && return case "$cur" in --whitespace=*) __gitcomp "$__git_whitespacelist" "" "${cur##--whitespace=}" return ;; --*) __gitcomp " --onto --merge --strategy --interactive --preserve-merges --stat --no-stat --committer-date-is-author-date --ignore-date --ignore-whitespace --whitespace= --autosquash --no-autosquash --fork-point --no-fork-point --autostash --no-autostash --verify --no-verify --keep-empty --root --force-rebase --no-ff --exec " return esac __git_complete_refs } _git_reflog () { local subcommands="show delete expire" local subcommand="$(__git_find_on_cmdline "$subcommands")" if [ -z "$subcommand" ]; then __gitcomp "$subcommands" else __git_complete_refs fi } __git_send_email_confirm_options="always never auto cc compose" __git_send_email_suppresscc_options="author self cc bodycc sob cccmd body all" _git_send_email () { case "$prev" in --to|--cc|--bcc|--from) __gitcomp "$(__git send-email --dump-aliases)" return ;; esac case "$cur" in --confirm=*) __gitcomp " $__git_send_email_confirm_options " "" "${cur##--confirm=}" return ;; --suppress-cc=*) __gitcomp " $__git_send_email_suppresscc_options " "" "${cur##--suppress-cc=}" return ;; --smtp-encryption=*) __gitcomp "ssl tls" "" "${cur##--smtp-encryption=}" return ;; --thread=*) __gitcomp " deep shallow " "" "${cur##--thread=}" return ;; --to=*|--cc=*|--bcc=*|--from=*) __gitcomp "$(__git send-email --dump-aliases)" "" "${cur#--*=}" return ;; --*) __gitcomp "--annotate --bcc --cc --cc-cmd --chain-reply-to --compose --confirm= --dry-run --envelope-sender --from --identity --in-reply-to --no-chain-reply-to --no-signed-off-by-cc --no-suppress-from --no-thread --quiet --signed-off-by-cc --smtp-pass --smtp-server --smtp-server-port --smtp-encryption= --smtp-user --subject --suppress-cc= --suppress-from --thread --to --validate --no-validate $__git_format_patch_options" return ;; esac __git_complete_revlist } _git_stage () { _git_add } _git_status () { local complete_opt local untracked_state case "$cur" in --ignore-submodules=*) __gitcomp "none untracked dirty all" "" "${cur##--ignore-submodules=}" return ;; --untracked-files=*) __gitcomp "$__git_untracked_file_modes" "" "${cur##--untracked-files=}" return ;; --column=*) __gitcomp " always never auto column row plain dense nodense " "" "${cur##--column=}" return ;; --*) __gitcomp " --short --branch --porcelain --long --verbose --untracked-files= --ignore-submodules= --ignored --column= --no-column " return ;; esac untracked_state="$(__git_get_option_value "-u" "--untracked-files=" \ "$__git_untracked_file_modes" "status.showUntrackedFiles")" case "$untracked_state" in no) # --ignored option does not matter complete_opt= ;; all|normal|*) complete_opt="--cached --directory --no-empty-directory --others" if [ -n "$(__git_find_on_cmdline "--ignored")" ]; then complete_opt="$complete_opt --ignored --exclude=*" fi ;; esac __git_complete_index_file "$complete_opt" } __git_config_get_set_variables () { local prevword word config_file= c=$cword while [ $c -gt 1 ]; do word="${words[c]}" case "$word" in --system|--global|--local|--file=*) config_file="$word" break ;; -f|--file) config_file="$word $prevword" break ;; esac prevword=$word c=$((--c)) done __git config $config_file --name-only --list } _git_config () { case "$prev" in branch.*.remote|branch.*.pushremote) __gitcomp_nl "$(__git_remotes)" return ;; branch.*.merge) __git_complete_refs return ;; branch.*.rebase) __gitcomp "false true preserve interactive" return ;; remote.pushdefault) __gitcomp_nl "$(__git_remotes)" return ;; remote.*.fetch) local remote="${prev#remote.}" remote="${remote%.fetch}" if [ -z "$cur" ]; then __gitcomp_nl "refs/heads/" "" "" "" return fi __gitcomp_nl "$(__git_refs_remotes "$remote")" return ;; remote.*.push) local remote="${prev#remote.}" remote="${remote%.push}" __gitcomp_nl "$(__git for-each-ref \ --format='%(refname):%(refname)' refs/heads)" return ;; pull.twohead|pull.octopus) __git_compute_merge_strategies __gitcomp "$__git_merge_strategies" return ;; color.branch|color.diff|color.interactive|\ color.showbranch|color.status|color.ui) __gitcomp "always never auto" return ;; color.pager) __gitcomp "false true" return ;; color.*.*) __gitcomp " normal black red green yellow blue magenta cyan white bold dim ul blink reverse " return ;; diff.submodule) __gitcomp "log short" return ;; help.format) __gitcomp "man info web html" return ;; log.date) __gitcomp "$__git_log_date_formats" return ;; sendemail.aliasesfiletype) __gitcomp "mutt mailrc pine elm gnus" return ;; sendemail.confirm) __gitcomp "$__git_send_email_confirm_options" return ;; sendemail.suppresscc) __gitcomp "$__git_send_email_suppresscc_options" return ;; sendemail.transferencoding) __gitcomp "7bit 8bit quoted-printable base64" return ;; --get|--get-all|--unset|--unset-all) __gitcomp_nl "$(__git_config_get_set_variables)" return ;; *.*) return ;; esac case "$cur" in --*) __gitcomp " --system --global --local --file= --list --replace-all --get --get-all --get-regexp --add --unset --unset-all --remove-section --rename-section --name-only " return ;; branch.*.*) local pfx="${cur%.*}." cur_="${cur##*.}" __gitcomp "remote pushremote merge mergeoptions rebase" "$pfx" "$cur_" return ;; branch.*) local pfx="${cur%.*}." cur_="${cur#*.}" __gitcomp_direct "$(__git_heads "$pfx" "$cur_" ".")" __gitcomp_nl_append $'autosetupmerge\nautosetuprebase\n' "$pfx" "$cur_" return ;; guitool.*.*) local pfx="${cur%.*}." cur_="${cur##*.}" __gitcomp " argprompt cmd confirm needsfile noconsole norescan prompt revprompt revunmerged title " "$pfx" "$cur_" return ;; difftool.*.*) local pfx="${cur%.*}." cur_="${cur##*.}" __gitcomp "cmd path" "$pfx" "$cur_" return ;; man.*.*) local pfx="${cur%.*}." cur_="${cur##*.}" __gitcomp "cmd path" "$pfx" "$cur_" return ;; mergetool.*.*) local pfx="${cur%.*}." cur_="${cur##*.}" __gitcomp "cmd path trustExitCode" "$pfx" "$cur_" return ;; pager.*) local pfx="${cur%.*}." cur_="${cur#*.}" __git_compute_all_commands __gitcomp_nl "$__git_all_commands" "$pfx" "$cur_" return ;; remote.*.*) local pfx="${cur%.*}." cur_="${cur##*.}" __gitcomp " url proxy fetch push mirror skipDefaultUpdate receivepack uploadpack tagopt pushurl " "$pfx" "$cur_" return ;; remote.*) local pfx="${cur%.*}." cur_="${cur#*.}" __gitcomp_nl "$(__git_remotes)" "$pfx" "$cur_" "." __gitcomp_nl_append "pushdefault" "$pfx" "$cur_" return ;; url.*.*) local pfx="${cur%.*}." cur_="${cur##*.}" __gitcomp "insteadOf pushInsteadOf" "$pfx" "$cur_" return ;; esac __gitcomp " add.ignoreErrors advice.amWorkDir advice.commitBeforeMerge advice.detachedHead advice.implicitIdentity advice.pushAlreadyExists advice.pushFetchFirst advice.pushNeedsForce advice.pushNonFFCurrent advice.pushNonFFMatching advice.pushUpdateRejected advice.resolveConflict advice.rmHints advice.statusHints advice.statusUoption alias. am.keepcr am.threeWay apply.ignorewhitespace apply.whitespace branch.autosetupmerge branch.autosetuprebase browser. clean.requireForce color.branch color.branch.current color.branch.local color.branch.plain color.branch.remote color.decorate.HEAD color.decorate.branch color.decorate.remoteBranch color.decorate.stash color.decorate.tag color.diff color.diff.commit color.diff.frag color.diff.func color.diff.meta color.diff.new color.diff.old color.diff.plain color.diff.whitespace color.grep color.grep.context color.grep.filename color.grep.function color.grep.linenumber color.grep.match color.grep.selected color.grep.separator color.interactive color.interactive.error color.interactive.header color.interactive.help color.interactive.prompt color.pager color.showbranch color.status color.status.added color.status.changed color.status.header color.status.localBranch color.status.nobranch color.status.remoteBranch color.status.unmerged color.status.untracked color.status.updated color.ui commit.cleanup commit.gpgSign commit.status commit.template commit.verbose core.abbrev core.askpass core.attributesfile core.autocrlf core.bare core.bigFileThreshold core.checkStat core.commentChar core.compression core.createObject core.deltaBaseCacheLimit core.editor core.eol core.excludesfile core.fileMode core.fsyncobjectfiles core.gitProxy core.hideDotFiles core.hooksPath core.ignoreStat core.ignorecase core.logAllRefUpdates core.loosecompression core.notesRef core.packedGitLimit core.packedGitWindowSize core.packedRefsTimeout core.pager core.precomposeUnicode core.preferSymlinkRefs core.preloadindex core.protectHFS core.protectNTFS core.quotepath core.repositoryFormatVersion core.safecrlf core.sharedRepository core.sparseCheckout core.splitIndex core.sshCommand core.symlinks core.trustctime core.untrackedCache core.warnAmbiguousRefs core.whitespace core.worktree credential.helper credential.useHttpPath credential.username credentialCache.ignoreSIGHUP diff.autorefreshindex diff.external diff.ignoreSubmodules diff.mnemonicprefix diff.noprefix diff.renameLimit diff.renames diff.statGraphWidth diff.submodule diff.suppressBlankEmpty diff.tool diff.wordRegex diff.algorithm difftool. difftool.prompt fetch.recurseSubmodules fetch.unpackLimit format.attach format.cc format.coverLetter format.from format.headers format.numbered format.pretty format.signature format.signoff format.subjectprefix format.suffix format.thread format.to gc. gc.aggressiveDepth gc.aggressiveWindow gc.auto gc.autoDetach gc.autopacklimit gc.logExpiry gc.packrefs gc.pruneexpire gc.reflogexpire gc.reflogexpireunreachable gc.rerereresolved gc.rerereunresolved gc.worktreePruneExpire gitcvs.allbinary gitcvs.commitmsgannotation gitcvs.dbTableNamePrefix gitcvs.dbdriver gitcvs.dbname gitcvs.dbpass gitcvs.dbuser gitcvs.enabled gitcvs.logfile gitcvs.usecrlfattr guitool. gui.blamehistoryctx gui.commitmsgwidth gui.copyblamethreshold gui.diffcontext gui.encoding gui.fastcopyblame gui.matchtrackingbranch gui.newbranchtemplate gui.pruneduringfetch gui.spellingdictionary gui.trustmtime help.autocorrect help.browser help.format http.lowSpeedLimit http.lowSpeedTime http.maxRequests http.minSessions http.noEPSV http.postBuffer http.proxy http.sslCipherList http.sslVersion http.sslCAInfo http.sslCAPath http.sslCert http.sslCertPasswordProtected http.sslKey http.sslVerify http.useragent i18n.commitEncoding i18n.logOutputEncoding imap.authMethod imap.folder imap.host imap.pass imap.port imap.preformattedHTML imap.sslverify imap.tunnel imap.user init.templatedir instaweb.browser instaweb.httpd instaweb.local instaweb.modulepath instaweb.port interactive.singlekey log.date log.decorate log.showroot mailmap.file man. man.viewer merge. merge.conflictstyle merge.log merge.renameLimit merge.renormalize merge.stat merge.tool merge.verbosity mergetool. mergetool.keepBackup mergetool.keepTemporaries mergetool.prompt notes.displayRef notes.rewrite. notes.rewrite.amend notes.rewrite.rebase notes.rewriteMode notes.rewriteRef pack.compression pack.deltaCacheLimit pack.deltaCacheSize pack.depth pack.indexVersion pack.packSizeLimit pack.threads pack.window pack.windowMemory pager. pretty. pull.octopus pull.twohead push.default push.followTags rebase.autosquash rebase.stat receive.autogc receive.denyCurrentBranch receive.denyDeleteCurrent receive.denyDeletes receive.denyNonFastForwards receive.fsckObjects receive.unpackLimit receive.updateserverinfo remote.pushdefault remotes. repack.usedeltabaseoffset rerere.autoupdate rerere.enabled sendemail. sendemail.aliasesfile sendemail.aliasfiletype sendemail.bcc sendemail.cc sendemail.cccmd sendemail.chainreplyto sendemail.confirm sendemail.envelopesender sendemail.from sendemail.identity sendemail.multiedit sendemail.signedoffbycc sendemail.smtpdomain sendemail.smtpencryption sendemail.smtppass sendemail.smtpserver sendemail.smtpserveroption sendemail.smtpserverport sendemail.smtpuser sendemail.suppresscc sendemail.suppressfrom sendemail.thread sendemail.to sendemail.validate sendemail.smtpbatchsize sendemail.smtprelogindelay showbranch.default status.relativePaths status.showUntrackedFiles status.submodulesummary submodule. tar.umask transfer.unpackLimit url. user.email user.name user.signingkey web.browser branch. remote. " } _git_remote () { local subcommands=" add rename remove set-head set-branches get-url set-url show prune update " local subcommand="$(__git_find_on_cmdline "$subcommands")" if [ -z "$subcommand" ]; then case "$cur" in --*) __gitcomp "--verbose" ;; *) __gitcomp "$subcommands" ;; esac return fi case "$subcommand,$cur" in add,--*) __gitcomp "--track --master --fetch --tags --no-tags --mirror=" ;; add,*) ;; set-head,--*) __gitcomp "--auto --delete" ;; set-branches,--*) __gitcomp "--add" ;; set-head,*|set-branches,*) __git_complete_remote_or_refspec ;; update,--*) __gitcomp "--prune" ;; update,*) __gitcomp "$(__git_get_config_variables "remotes")" ;; set-url,--*) __gitcomp "--push --add --delete" ;; get-url,--*) __gitcomp "--push --all" ;; prune,--*) __gitcomp "--dry-run" ;; *) __gitcomp_nl "$(__git_remotes)" ;; esac } _git_replace () { case "$cur" in --*) __gitcomp "--edit --graft --format= --list --delete" return ;; esac __git_complete_refs } _git_rerere () { local subcommands="clear forget diff remaining status gc" local subcommand="$(__git_find_on_cmdline "$subcommands")" if test -z "$subcommand" then __gitcomp "$subcommands" return fi } _git_reset () { __git_has_doubledash && return case "$cur" in --*) __gitcomp "--merge --mixed --hard --soft --patch --keep" return ;; esac __git_complete_refs } _git_revert () { __git_find_repo_path if [ -f "$__git_repo_path"/REVERT_HEAD ]; then __gitcomp "--continue --quit --abort" return fi case "$cur" in --*) __gitcomp " --edit --mainline --no-edit --no-commit --signoff --strategy= --strategy-option= " return ;; esac __git_complete_refs } _git_rm () { case "$cur" in --*) __gitcomp "--cached --dry-run --ignore-unmatch --quiet" return ;; esac __git_complete_index_file "--cached" } _git_shortlog () { __git_has_doubledash && return case "$cur" in --*) __gitcomp " $__git_log_common_options $__git_log_shortlog_options --numbered --summary --email " return ;; esac __git_complete_revlist } _git_show () { __git_has_doubledash && return case "$cur" in --pretty=*|--format=*) __gitcomp "$__git_log_pretty_formats $(__git_pretty_aliases) " "" "${cur#*=}" return ;; --diff-algorithm=*) __gitcomp "$__git_diff_algorithms" "" "${cur##--diff-algorithm=}" return ;; --submodule=*) __gitcomp "$__git_diff_submodule_formats" "" "${cur##--submodule=}" return ;; --*) __gitcomp "--pretty= --format= --abbrev-commit --oneline --show-signature $__git_diff_common_options " return ;; esac __git_complete_revlist_file } _git_show_branch () { case "$cur" in --*) __gitcomp " --all --remotes --topo-order --date-order --current --more= --list --independent --merge-base --no-name --color --no-color --sha1-name --sparse --topics --reflog " return ;; esac __git_complete_revlist } _git_stash () { local save_opts='--all --keep-index --no-keep-index --quiet --patch --include-untracked' local subcommands='push save list show apply clear drop pop create branch' local subcommand="$(__git_find_on_cmdline "$subcommands")" if [ -z "$subcommand" ]; then case "$cur" in --*) __gitcomp "$save_opts" ;; *) if [ -z "$(__git_find_on_cmdline "$save_opts")" ]; then __gitcomp "$subcommands" fi ;; esac else case "$subcommand,$cur" in push,--*) __gitcomp "$save_opts --message" ;; save,--*) __gitcomp "$save_opts" ;; apply,--*|pop,--*) __gitcomp "--index --quiet" ;; drop,--*) __gitcomp "--quiet" ;; show,--*|branch,--*) ;; branch,*) if [ $cword -eq 3 ]; then __git_complete_refs else __gitcomp_nl "$(__git stash list \ | sed -n -e 's/:.*//p')" fi ;; show,*|apply,*|drop,*|pop,*) __gitcomp_nl "$(__git stash list \ | sed -n -e 's/:.*//p')" ;; *) ;; esac fi } _git_submodule () { __git_has_doubledash && return local subcommands="add status init deinit update summary foreach sync" local subcommand="$(__git_find_on_cmdline "$subcommands")" if [ -z "$subcommand" ]; then case "$cur" in --*) __gitcomp "--quiet" ;; *) __gitcomp "$subcommands" ;; esac return fi case "$subcommand,$cur" in add,--*) __gitcomp "--branch --force --name --reference --depth" ;; status,--*) __gitcomp "--cached --recursive" ;; deinit,--*) __gitcomp "--force --all" ;; update,--*) __gitcomp " --init --remote --no-fetch --recommend-shallow --no-recommend-shallow --force --rebase --merge --reference --depth --recursive --jobs " ;; summary,--*) __gitcomp "--cached --files --summary-limit" ;; foreach,--*|sync,--*) __gitcomp "--recursive" ;; *) ;; esac } _git_svn () { local subcommands=" init fetch clone rebase dcommit log find-rev set-tree commit-diff info create-ignore propget proplist show-ignore show-externals branch tag blame migrate mkdirs reset gc " local subcommand="$(__git_find_on_cmdline "$subcommands")" if [ -z "$subcommand" ]; then __gitcomp "$subcommands" else local remote_opts="--username= --config-dir= --no-auth-cache" local fc_opts=" --follow-parent --authors-file= --repack= --no-metadata --use-svm-props --use-svnsync-props --log-window-size= --no-checkout --quiet --repack-flags --use-log-author --localtime --add-author-from --ignore-paths= --include-paths= $remote_opts " local init_opts=" --template= --shared= --trunk= --tags= --branches= --stdlayout --minimize-url --no-metadata --use-svm-props --use-svnsync-props --rewrite-root= --prefix= $remote_opts " local cmt_opts=" --edit --rmdir --find-copies-harder --copy-similarity= " case "$subcommand,$cur" in fetch,--*) __gitcomp "--revision= --fetch-all $fc_opts" ;; clone,--*) __gitcomp "--revision= $fc_opts $init_opts" ;; init,--*) __gitcomp "$init_opts" ;; dcommit,--*) __gitcomp " --merge --strategy= --verbose --dry-run --fetch-all --no-rebase --commit-url --revision --interactive $cmt_opts $fc_opts " ;; set-tree,--*) __gitcomp "--stdin $cmt_opts $fc_opts" ;; create-ignore,--*|propget,--*|proplist,--*|show-ignore,--*|\ show-externals,--*|mkdirs,--*) __gitcomp "--revision=" ;; log,--*) __gitcomp " --limit= --revision= --verbose --incremental --oneline --show-commit --non-recursive --authors-file= --color " ;; rebase,--*) __gitcomp " --merge --verbose --strategy= --local --fetch-all --dry-run $fc_opts " ;; commit-diff,--*) __gitcomp "--message= --file= --revision= $cmt_opts" ;; info,--*) __gitcomp "--url" ;; branch,--*) __gitcomp "--dry-run --message --tag" ;; tag,--*) __gitcomp "--dry-run --message" ;; blame,--*) __gitcomp "--git-format" ;; migrate,--*) __gitcomp " --config-dir= --ignore-paths= --minimize --no-auth-cache --username= " ;; reset,--*) __gitcomp "--revision= --parent" ;; *) ;; esac fi } _git_tag () { local i c=1 f=0 while [ $c -lt $cword ]; do i="${words[c]}" case "$i" in -d|-v) __gitcomp_direct "$(__git_tags "" "$cur" " ")" return ;; -f) f=1 ;; esac ((c++)) done case "$prev" in -m|-F) ;; -*|tag) if [ $f = 1 ]; then __gitcomp_direct "$(__git_tags "" "$cur" " ")" fi ;; *) __git_complete_refs ;; esac case "$cur" in --*) __gitcomp " --list --delete --verify --annotate --message --file --sign --cleanup --local-user --force --column --sort= --contains --no-contains --points-at --merged --no-merged --create-reflog " ;; esac } _git_whatchanged () { _git_log } _git_worktree () { local subcommands="add list lock prune unlock" local subcommand="$(__git_find_on_cmdline "$subcommands")" if [ -z "$subcommand" ]; then __gitcomp "$subcommands" else case "$subcommand,$cur" in add,--*) __gitcomp "--detach" ;; list,--*) __gitcomp "--porcelain" ;; lock,--*) __gitcomp "--reason" ;; prune,--*) __gitcomp "--dry-run --expire --verbose" ;; *) ;; esac fi } __git_main () { local i c=1 command __git_dir __git_repo_path local __git_C_args C_args_count=0 while [ $c -lt $cword ]; do i="${words[c]}" case "$i" in --git-dir=*) __git_dir="${i#--git-dir=}" ;; --git-dir) ((c++)) ; __git_dir="${words[c]}" ;; --bare) __git_dir="." ;; --help) command="help"; break ;; -c|--work-tree|--namespace) ((c++)) ;; -C) __git_C_args[C_args_count++]=-C ((c++)) __git_C_args[C_args_count++]="${words[c]}" ;; -*) ;; *) command="$i"; break ;; esac ((c++)) done if [ -z "$command" ]; then case "$prev" in --git-dir|-C|--work-tree) # these need a path argument, let's fall back to # Bash filename completion return ;; -c|--namespace) # we don't support completing these options' arguments return ;; esac case "$cur" in --*) __gitcomp " --paginate --no-pager --git-dir= --bare --version --exec-path --exec-path= --html-path --man-path --info-path --work-tree= --namespace= --no-replace-objects --help " ;; *) __git_compute_porcelain_commands __gitcomp "$__git_porcelain_commands $(__git_aliases)" ;; esac return fi local completion_func="_git_${command//-/_}" declare -f $completion_func >/dev/null 2>/dev/null && $completion_func && return local expansion=$(__git_aliased_command "$command") if [ -n "$expansion" ]; then words[1]=$expansion completion_func="_git_${expansion//-/_}" declare -f $completion_func >/dev/null 2>/dev/null && $completion_func fi } __gitk_main () { __git_has_doubledash && return local __git_repo_path __git_find_repo_path local merge="" if [ -f "$__git_repo_path/MERGE_HEAD" ]; then merge="--merge" fi case "$cur" in --*) __gitcomp " $__git_log_common_options $__git_log_gitk_options $merge " return ;; esac __git_complete_revlist } if [[ -n ${ZSH_VERSION-} ]]; then #echo "WARNING: this script is deprecated, please see git-completion.zsh" 1>&2 autoload -U +X compinit && compinit __gitcomp () { emulate -L zsh local cur_="${3-$cur}" case "$cur_" in --*=) ;; *) local c IFS=$' \t\n' local -a array for c in ${=1}; do c="$c${4-}" case $c in --*=*|*.) ;; *) c="$c " ;; esac array[${#array[@]}+1]="$c" done compset -P '*[=:]' compadd -Q -S '' -p "${2-}" -a -- array && _ret=0 ;; esac } __gitcomp_direct () { emulate -L zsh local IFS=$'\n' compset -P '*[=:]' compadd -Q -- ${=1} && _ret=0 } __gitcomp_nl () { emulate -L zsh local IFS=$'\n' compset -P '*[=:]' compadd -Q -S "${4- }" -p "${2-}" -- ${=1} && _ret=0 } __gitcomp_file () { emulate -L zsh local IFS=$'\n' compset -P '*[=:]' compadd -Q -p "${2-}" -f -- ${=1} && _ret=0 } _git () { local _ret=1 cur cword prev cur=${words[CURRENT]} prev=${words[CURRENT-1]} let cword=CURRENT-1 emulate ksh -c __${service}_main let _ret && _default && _ret=0 return _ret } compdef _git git gitk return fi __git_func_wrap () { local cur words cword prev _get_comp_words_by_ref -n =: cur words cword prev $1 } # Setup completion for certain functions defined above by setting common # variables and workarounds. # This is NOT a public function; use at your own risk. __git_complete () { local wrapper="__git_wrap${2}" eval "$wrapper () { __git_func_wrap $2 ; }" complete -o bashdefault -o default -o nospace -F $wrapper $1 2>/dev/null \ || complete -o default -o nospace -F $wrapper $1 } # wrapper for backwards compatibility _git () { __git_wrap__git_main } # wrapper for backwards compatibility _gitk () { __git_wrap__gitk_main } __git_complete git __git_main __git_complete gitk __gitk_main # The following are necessary only for Cygwin, and only are needed # when the user has tab-completed the executable name and consequently # included the '.exe' suffix. # if [ Cygwin = "$(uname -o 2>/dev/null)" ]; then __git_complete git.exe __git_main fi
{ "content_hash": "42e5caaf1aaba8436c2ba180f6cfa1c7", "timestamp": "", "source": "github", "line_count": 3317, "max_line_length": 89, "avg_line_length": 21.37835393427796, "alnum_prop": 0.6060610333935018, "repo_name": "1dose/devTools", "id": "0564060109fadf7b4f14e7c38fc76d5cff718e72", "size": "70914", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "symlinks/dotfiles/.git-completion.bash", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "13788" }, { "name": "Vim script", "bytes": "9422" } ], "symlink_target": "" }
<?php # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/devtools/clouddebugger/v2/data.proto namespace Google\Cloud\Debugger\V2; use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** * Represents the breakpoint specification, status and results. * * Generated from protobuf message <code>google.devtools.clouddebugger.v2.Breakpoint</code> */ class Breakpoint extends \Google\Protobuf\Internal\Message { /** * Breakpoint identifier, unique in the scope of the debuggee. * * Generated from protobuf field <code>string id = 1;</code> */ private $id = ''; /** * Action that the agent should perform when the code at the * breakpoint location is hit. * * Generated from protobuf field <code>.google.devtools.clouddebugger.v2.Breakpoint.Action action = 13;</code> */ private $action = 0; /** * Breakpoint source location. * * Generated from protobuf field <code>.google.devtools.clouddebugger.v2.SourceLocation location = 2;</code> */ private $location = null; /** * Condition that triggers the breakpoint. * The condition is a compound boolean expression composed using expressions * in a programming language at the source location. * * Generated from protobuf field <code>string condition = 3;</code> */ private $condition = ''; /** * List of read-only expressions to evaluate at the breakpoint location. * The expressions are composed using expressions in the programming language * at the source location. If the breakpoint action is `LOG`, the evaluated * expressions are included in log statements. * * Generated from protobuf field <code>repeated string expressions = 4;</code> */ private $expressions; /** * Only relevant when action is `LOG`. Defines the message to log when * the breakpoint hits. The message may include parameter placeholders `$0`, * `$1`, etc. These placeholders are replaced with the evaluated value * of the appropriate expression. Expressions not referenced in * `log_message_format` are not logged. * Example: `Message received, id = $0, count = $1` with * `expressions` = `[ message.id, message.count ]`. * * Generated from protobuf field <code>string log_message_format = 14;</code> */ private $log_message_format = ''; /** * Indicates the severity of the log. Only relevant when action is `LOG`. * * Generated from protobuf field <code>.google.devtools.clouddebugger.v2.Breakpoint.LogLevel log_level = 15;</code> */ private $log_level = 0; /** * When true, indicates that this is a final result and the * breakpoint state will not change from here on. * * Generated from protobuf field <code>bool is_final_state = 5;</code> */ private $is_final_state = false; /** * Time this breakpoint was created by the server in seconds resolution. * * Generated from protobuf field <code>.google.protobuf.Timestamp create_time = 11;</code> */ private $create_time = null; /** * Time this breakpoint was finalized as seen by the server in seconds * resolution. * * Generated from protobuf field <code>.google.protobuf.Timestamp final_time = 12;</code> */ private $final_time = null; /** * E-mail address of the user that created this breakpoint * * Generated from protobuf field <code>string user_email = 16;</code> */ private $user_email = ''; /** * Breakpoint status. * The status includes an error flag and a human readable message. * This field is usually unset. The message can be either * informational or an error message. Regardless, clients should always * display the text message back to the user. * Error status indicates complete failure of the breakpoint. * Example (non-final state): `Still loading symbols...` * Examples (final state): * * `Invalid line number` referring to location * * `Field f not found in class C` referring to condition * * Generated from protobuf field <code>.google.devtools.clouddebugger.v2.StatusMessage status = 10;</code> */ private $status = null; /** * The stack at breakpoint time, where stack_frames[0] represents the most * recently entered function. * * Generated from protobuf field <code>repeated .google.devtools.clouddebugger.v2.StackFrame stack_frames = 7;</code> */ private $stack_frames; /** * Values of evaluated expressions at breakpoint time. * The evaluated expressions appear in exactly the same order they * are listed in the `expressions` field. * The `name` field holds the original expression text, the `value` or * `members` field holds the result of the evaluated expression. * If the expression cannot be evaluated, the `status` inside the `Variable` * will indicate an error and contain the error text. * * Generated from protobuf field <code>repeated .google.devtools.clouddebugger.v2.Variable evaluated_expressions = 8;</code> */ private $evaluated_expressions; /** * The `variable_table` exists to aid with computation, memory and network * traffic optimization. It enables storing a variable once and reference * it from multiple variables, including variables stored in the * `variable_table` itself. * For example, the same `this` object, which may appear at many levels of * the stack, can have all of its data stored once in this table. The * stack frame variables then would hold only a reference to it. * The variable `var_table_index` field is an index into this repeated field. * The stored objects are nameless and get their name from the referencing * variable. The effective variable is a merge of the referencing variable * and the referenced variable. * * Generated from protobuf field <code>repeated .google.devtools.clouddebugger.v2.Variable variable_table = 9;</code> */ private $variable_table; /** * A set of custom breakpoint properties, populated by the agent, to be * displayed to the user. * * Generated from protobuf field <code>map<string, string> labels = 17;</code> */ private $labels; /** * Constructor. * * @param array $data { * Optional. Data for populating the Message object. * * @type string $id * Breakpoint identifier, unique in the scope of the debuggee. * @type int $action * Action that the agent should perform when the code at the * breakpoint location is hit. * @type \Google\Cloud\Debugger\V2\SourceLocation $location * Breakpoint source location. * @type string $condition * Condition that triggers the breakpoint. * The condition is a compound boolean expression composed using expressions * in a programming language at the source location. * @type string[]|\Google\Protobuf\Internal\RepeatedField $expressions * List of read-only expressions to evaluate at the breakpoint location. * The expressions are composed using expressions in the programming language * at the source location. If the breakpoint action is `LOG`, the evaluated * expressions are included in log statements. * @type string $log_message_format * Only relevant when action is `LOG`. Defines the message to log when * the breakpoint hits. The message may include parameter placeholders `$0`, * `$1`, etc. These placeholders are replaced with the evaluated value * of the appropriate expression. Expressions not referenced in * `log_message_format` are not logged. * Example: `Message received, id = $0, count = $1` with * `expressions` = `[ message.id, message.count ]`. * @type int $log_level * Indicates the severity of the log. Only relevant when action is `LOG`. * @type bool $is_final_state * When true, indicates that this is a final result and the * breakpoint state will not change from here on. * @type \Google\Protobuf\Timestamp $create_time * Time this breakpoint was created by the server in seconds resolution. * @type \Google\Protobuf\Timestamp $final_time * Time this breakpoint was finalized as seen by the server in seconds * resolution. * @type string $user_email * E-mail address of the user that created this breakpoint * @type \Google\Cloud\Debugger\V2\StatusMessage $status * Breakpoint status. * The status includes an error flag and a human readable message. * This field is usually unset. The message can be either * informational or an error message. Regardless, clients should always * display the text message back to the user. * Error status indicates complete failure of the breakpoint. * Example (non-final state): `Still loading symbols...` * Examples (final state): * * `Invalid line number` referring to location * * `Field f not found in class C` referring to condition * @type \Google\Cloud\Debugger\V2\StackFrame[]|\Google\Protobuf\Internal\RepeatedField $stack_frames * The stack at breakpoint time, where stack_frames[0] represents the most * recently entered function. * @type \Google\Cloud\Debugger\V2\Variable[]|\Google\Protobuf\Internal\RepeatedField $evaluated_expressions * Values of evaluated expressions at breakpoint time. * The evaluated expressions appear in exactly the same order they * are listed in the `expressions` field. * The `name` field holds the original expression text, the `value` or * `members` field holds the result of the evaluated expression. * If the expression cannot be evaluated, the `status` inside the `Variable` * will indicate an error and contain the error text. * @type \Google\Cloud\Debugger\V2\Variable[]|\Google\Protobuf\Internal\RepeatedField $variable_table * The `variable_table` exists to aid with computation, memory and network * traffic optimization. It enables storing a variable once and reference * it from multiple variables, including variables stored in the * `variable_table` itself. * For example, the same `this` object, which may appear at many levels of * the stack, can have all of its data stored once in this table. The * stack frame variables then would hold only a reference to it. * The variable `var_table_index` field is an index into this repeated field. * The stored objects are nameless and get their name from the referencing * variable. The effective variable is a merge of the referencing variable * and the referenced variable. * @type array|\Google\Protobuf\Internal\MapField $labels * A set of custom breakpoint properties, populated by the agent, to be * displayed to the user. * } */ public function __construct($data = NULL) { \GPBMetadata\Google\Devtools\Clouddebugger\V2\Data::initOnce(); parent::__construct($data); } /** * Breakpoint identifier, unique in the scope of the debuggee. * * Generated from protobuf field <code>string id = 1;</code> * @return string */ public function getId() { return $this->id; } /** * Breakpoint identifier, unique in the scope of the debuggee. * * Generated from protobuf field <code>string id = 1;</code> * @param string $var * @return $this */ public function setId($var) { GPBUtil::checkString($var, True); $this->id = $var; return $this; } /** * Action that the agent should perform when the code at the * breakpoint location is hit. * * Generated from protobuf field <code>.google.devtools.clouddebugger.v2.Breakpoint.Action action = 13;</code> * @return int */ public function getAction() { return $this->action; } /** * Action that the agent should perform when the code at the * breakpoint location is hit. * * Generated from protobuf field <code>.google.devtools.clouddebugger.v2.Breakpoint.Action action = 13;</code> * @param int $var * @return $this */ public function setAction($var) { GPBUtil::checkEnum($var, \Google\Cloud\Debugger\V2\Breakpoint\Action::class); $this->action = $var; return $this; } /** * Breakpoint source location. * * Generated from protobuf field <code>.google.devtools.clouddebugger.v2.SourceLocation location = 2;</code> * @return \Google\Cloud\Debugger\V2\SourceLocation|null */ public function getLocation() { return $this->location; } public function hasLocation() { return isset($this->location); } public function clearLocation() { unset($this->location); } /** * Breakpoint source location. * * Generated from protobuf field <code>.google.devtools.clouddebugger.v2.SourceLocation location = 2;</code> * @param \Google\Cloud\Debugger\V2\SourceLocation $var * @return $this */ public function setLocation($var) { GPBUtil::checkMessage($var, \Google\Cloud\Debugger\V2\SourceLocation::class); $this->location = $var; return $this; } /** * Condition that triggers the breakpoint. * The condition is a compound boolean expression composed using expressions * in a programming language at the source location. * * Generated from protobuf field <code>string condition = 3;</code> * @return string */ public function getCondition() { return $this->condition; } /** * Condition that triggers the breakpoint. * The condition is a compound boolean expression composed using expressions * in a programming language at the source location. * * Generated from protobuf field <code>string condition = 3;</code> * @param string $var * @return $this */ public function setCondition($var) { GPBUtil::checkString($var, True); $this->condition = $var; return $this; } /** * List of read-only expressions to evaluate at the breakpoint location. * The expressions are composed using expressions in the programming language * at the source location. If the breakpoint action is `LOG`, the evaluated * expressions are included in log statements. * * Generated from protobuf field <code>repeated string expressions = 4;</code> * @return \Google\Protobuf\Internal\RepeatedField */ public function getExpressions() { return $this->expressions; } /** * List of read-only expressions to evaluate at the breakpoint location. * The expressions are composed using expressions in the programming language * at the source location. If the breakpoint action is `LOG`, the evaluated * expressions are included in log statements. * * Generated from protobuf field <code>repeated string expressions = 4;</code> * @param string[]|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setExpressions($var) { $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::STRING); $this->expressions = $arr; return $this; } /** * Only relevant when action is `LOG`. Defines the message to log when * the breakpoint hits. The message may include parameter placeholders `$0`, * `$1`, etc. These placeholders are replaced with the evaluated value * of the appropriate expression. Expressions not referenced in * `log_message_format` are not logged. * Example: `Message received, id = $0, count = $1` with * `expressions` = `[ message.id, message.count ]`. * * Generated from protobuf field <code>string log_message_format = 14;</code> * @return string */ public function getLogMessageFormat() { return $this->log_message_format; } /** * Only relevant when action is `LOG`. Defines the message to log when * the breakpoint hits. The message may include parameter placeholders `$0`, * `$1`, etc. These placeholders are replaced with the evaluated value * of the appropriate expression. Expressions not referenced in * `log_message_format` are not logged. * Example: `Message received, id = $0, count = $1` with * `expressions` = `[ message.id, message.count ]`. * * Generated from protobuf field <code>string log_message_format = 14;</code> * @param string $var * @return $this */ public function setLogMessageFormat($var) { GPBUtil::checkString($var, True); $this->log_message_format = $var; return $this; } /** * Indicates the severity of the log. Only relevant when action is `LOG`. * * Generated from protobuf field <code>.google.devtools.clouddebugger.v2.Breakpoint.LogLevel log_level = 15;</code> * @return int */ public function getLogLevel() { return $this->log_level; } /** * Indicates the severity of the log. Only relevant when action is `LOG`. * * Generated from protobuf field <code>.google.devtools.clouddebugger.v2.Breakpoint.LogLevel log_level = 15;</code> * @param int $var * @return $this */ public function setLogLevel($var) { GPBUtil::checkEnum($var, \Google\Cloud\Debugger\V2\Breakpoint\LogLevel::class); $this->log_level = $var; return $this; } /** * When true, indicates that this is a final result and the * breakpoint state will not change from here on. * * Generated from protobuf field <code>bool is_final_state = 5;</code> * @return bool */ public function getIsFinalState() { return $this->is_final_state; } /** * When true, indicates that this is a final result and the * breakpoint state will not change from here on. * * Generated from protobuf field <code>bool is_final_state = 5;</code> * @param bool $var * @return $this */ public function setIsFinalState($var) { GPBUtil::checkBool($var); $this->is_final_state = $var; return $this; } /** * Time this breakpoint was created by the server in seconds resolution. * * Generated from protobuf field <code>.google.protobuf.Timestamp create_time = 11;</code> * @return \Google\Protobuf\Timestamp|null */ public function getCreateTime() { return $this->create_time; } public function hasCreateTime() { return isset($this->create_time); } public function clearCreateTime() { unset($this->create_time); } /** * Time this breakpoint was created by the server in seconds resolution. * * Generated from protobuf field <code>.google.protobuf.Timestamp create_time = 11;</code> * @param \Google\Protobuf\Timestamp $var * @return $this */ public function setCreateTime($var) { GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class); $this->create_time = $var; return $this; } /** * Time this breakpoint was finalized as seen by the server in seconds * resolution. * * Generated from protobuf field <code>.google.protobuf.Timestamp final_time = 12;</code> * @return \Google\Protobuf\Timestamp|null */ public function getFinalTime() { return $this->final_time; } public function hasFinalTime() { return isset($this->final_time); } public function clearFinalTime() { unset($this->final_time); } /** * Time this breakpoint was finalized as seen by the server in seconds * resolution. * * Generated from protobuf field <code>.google.protobuf.Timestamp final_time = 12;</code> * @param \Google\Protobuf\Timestamp $var * @return $this */ public function setFinalTime($var) { GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class); $this->final_time = $var; return $this; } /** * E-mail address of the user that created this breakpoint * * Generated from protobuf field <code>string user_email = 16;</code> * @return string */ public function getUserEmail() { return $this->user_email; } /** * E-mail address of the user that created this breakpoint * * Generated from protobuf field <code>string user_email = 16;</code> * @param string $var * @return $this */ public function setUserEmail($var) { GPBUtil::checkString($var, True); $this->user_email = $var; return $this; } /** * Breakpoint status. * The status includes an error flag and a human readable message. * This field is usually unset. The message can be either * informational or an error message. Regardless, clients should always * display the text message back to the user. * Error status indicates complete failure of the breakpoint. * Example (non-final state): `Still loading symbols...` * Examples (final state): * * `Invalid line number` referring to location * * `Field f not found in class C` referring to condition * * Generated from protobuf field <code>.google.devtools.clouddebugger.v2.StatusMessage status = 10;</code> * @return \Google\Cloud\Debugger\V2\StatusMessage|null */ public function getStatus() { return $this->status; } public function hasStatus() { return isset($this->status); } public function clearStatus() { unset($this->status); } /** * Breakpoint status. * The status includes an error flag and a human readable message. * This field is usually unset. The message can be either * informational or an error message. Regardless, clients should always * display the text message back to the user. * Error status indicates complete failure of the breakpoint. * Example (non-final state): `Still loading symbols...` * Examples (final state): * * `Invalid line number` referring to location * * `Field f not found in class C` referring to condition * * Generated from protobuf field <code>.google.devtools.clouddebugger.v2.StatusMessage status = 10;</code> * @param \Google\Cloud\Debugger\V2\StatusMessage $var * @return $this */ public function setStatus($var) { GPBUtil::checkMessage($var, \Google\Cloud\Debugger\V2\StatusMessage::class); $this->status = $var; return $this; } /** * The stack at breakpoint time, where stack_frames[0] represents the most * recently entered function. * * Generated from protobuf field <code>repeated .google.devtools.clouddebugger.v2.StackFrame stack_frames = 7;</code> * @return \Google\Protobuf\Internal\RepeatedField */ public function getStackFrames() { return $this->stack_frames; } /** * The stack at breakpoint time, where stack_frames[0] represents the most * recently entered function. * * Generated from protobuf field <code>repeated .google.devtools.clouddebugger.v2.StackFrame stack_frames = 7;</code> * @param \Google\Cloud\Debugger\V2\StackFrame[]|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setStackFrames($var) { $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Debugger\V2\StackFrame::class); $this->stack_frames = $arr; return $this; } /** * Values of evaluated expressions at breakpoint time. * The evaluated expressions appear in exactly the same order they * are listed in the `expressions` field. * The `name` field holds the original expression text, the `value` or * `members` field holds the result of the evaluated expression. * If the expression cannot be evaluated, the `status` inside the `Variable` * will indicate an error and contain the error text. * * Generated from protobuf field <code>repeated .google.devtools.clouddebugger.v2.Variable evaluated_expressions = 8;</code> * @return \Google\Protobuf\Internal\RepeatedField */ public function getEvaluatedExpressions() { return $this->evaluated_expressions; } /** * Values of evaluated expressions at breakpoint time. * The evaluated expressions appear in exactly the same order they * are listed in the `expressions` field. * The `name` field holds the original expression text, the `value` or * `members` field holds the result of the evaluated expression. * If the expression cannot be evaluated, the `status` inside the `Variable` * will indicate an error and contain the error text. * * Generated from protobuf field <code>repeated .google.devtools.clouddebugger.v2.Variable evaluated_expressions = 8;</code> * @param \Google\Cloud\Debugger\V2\Variable[]|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setEvaluatedExpressions($var) { $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Debugger\V2\Variable::class); $this->evaluated_expressions = $arr; return $this; } /** * The `variable_table` exists to aid with computation, memory and network * traffic optimization. It enables storing a variable once and reference * it from multiple variables, including variables stored in the * `variable_table` itself. * For example, the same `this` object, which may appear at many levels of * the stack, can have all of its data stored once in this table. The * stack frame variables then would hold only a reference to it. * The variable `var_table_index` field is an index into this repeated field. * The stored objects are nameless and get their name from the referencing * variable. The effective variable is a merge of the referencing variable * and the referenced variable. * * Generated from protobuf field <code>repeated .google.devtools.clouddebugger.v2.Variable variable_table = 9;</code> * @return \Google\Protobuf\Internal\RepeatedField */ public function getVariableTable() { return $this->variable_table; } /** * The `variable_table` exists to aid with computation, memory and network * traffic optimization. It enables storing a variable once and reference * it from multiple variables, including variables stored in the * `variable_table` itself. * For example, the same `this` object, which may appear at many levels of * the stack, can have all of its data stored once in this table. The * stack frame variables then would hold only a reference to it. * The variable `var_table_index` field is an index into this repeated field. * The stored objects are nameless and get their name from the referencing * variable. The effective variable is a merge of the referencing variable * and the referenced variable. * * Generated from protobuf field <code>repeated .google.devtools.clouddebugger.v2.Variable variable_table = 9;</code> * @param \Google\Cloud\Debugger\V2\Variable[]|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setVariableTable($var) { $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Debugger\V2\Variable::class); $this->variable_table = $arr; return $this; } /** * A set of custom breakpoint properties, populated by the agent, to be * displayed to the user. * * Generated from protobuf field <code>map<string, string> labels = 17;</code> * @return \Google\Protobuf\Internal\MapField */ public function getLabels() { return $this->labels; } /** * A set of custom breakpoint properties, populated by the agent, to be * displayed to the user. * * Generated from protobuf field <code>map<string, string> labels = 17;</code> * @param array|\Google\Protobuf\Internal\MapField $var * @return $this */ public function setLabels($var) { $arr = GPBUtil::checkMapField($var, \Google\Protobuf\Internal\GPBType::STRING, \Google\Protobuf\Internal\GPBType::STRING); $this->labels = $arr; return $this; } }
{ "content_hash": "a0f5ec12b655aff7b8c5d9991ee580ea", "timestamp": "", "source": "github", "line_count": 781, "max_line_length": 138, "avg_line_length": 38.070422535211264, "alnum_prop": 0.6447381697104227, "repo_name": "googleapis/google-cloud-php-debugger", "id": "c87ef42765d4e31828036e07ed2f40d112c04bdd", "size": "29733", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "src/V2/Breakpoint.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "381682" }, { "name": "Python", "bytes": "2733" } ], "symlink_target": "" }
import { mount, createLocalVue } from '@vue/test-utils' import Cryflow from '../Cryflow.vue' const localVue = createLocalVue() describe('Cryflow', () => { function generateCryflow(options) { const el = { components: { Cryflow }, template: ` <cryflow :phrases="phrases" /> `, data() { return { phrases: [ 'I am', 'trying', 'to be cryptic.' ] } } } return mount(el, { localVue, attachToDocument: true }) } it('is a Vue instance', () => { const wrapper = generateCryflow() expect(wrapper.isVueInstance()).toBeTruthy() }) it('renders correctly', () => { const wrapper = generateCryflow() expect(wrapper.element).toMatchSnapshot() }) })
{ "content_hash": "dd5b8217d896182ac6c2efd5b7551d7c", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 55, "avg_line_length": 19.452380952380953, "alnum_prop": 0.5263157894736842, "repo_name": "mugetsu/cryflow", "id": "f11691768a5dc78735b49cb09f5f5d3cee564c8c", "size": "817", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/__tests__/Cryflow.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "613" }, { "name": "JavaScript", "bytes": "2130" }, { "name": "Vue", "bytes": "2782" } ], "symlink_target": "" }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isImportTypeNode = void 0; const tslib_1 = require("tslib"); tslib_1.__exportStar(require("../2.8/node"), exports); const ts = require("typescript"); function isImportTypeNode(node) { return node.kind === ts.SyntaxKind.ImportType; } exports.isImportTypeNode = isImportTypeNode; //# sourceMappingURL=node.js.map
{ "content_hash": "e698f26e3e6ec379edb1369e43c7edb7", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 62, "avg_line_length": 36.27272727272727, "alnum_prop": 0.731829573934837, "repo_name": "ChromeDevTools/devtools-frontend", "id": "3c4178396f8a6f8c85c7d584b9d5e6c7e0ee6383", "size": "399", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "node_modules/tsutils/typeguard/2.9/node.js", "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": "" }
// Search script generated by doxygen // Copyright (C) 2009 by Dimitri van Heesch. // The code in this file is loosly based on main.js, part of Natural Docs, // which is Copyright (C) 2003-2008 Greg Valure // Natural Docs is licensed under the GPL. var indexSectionsWithContent = { 0: "abcdgimnsw", 1: "abmnw", 2: "abmw", 3: "cdgisw" }; var indexSectionNames = { 0: "all", 1: "classes", 2: "files", 3: "functions" }; function convertToId(search) { var result = ''; for (i=0;i<search.length;i++) { var c = search.charAt(i); var cn = c.charCodeAt(0); if (c.match(/[a-z0-9\u0080-\uFFFF]/)) { result+=c; } else if (cn<16) { result+="_0"+cn.toString(16); } else { result+="_"+cn.toString(16); } } return result; } function getXPos(item) { var x = 0; if (item.offsetWidth) { while (item && item!=document.body) { x += item.offsetLeft; item = item.offsetParent; } } return x; } function getYPos(item) { var y = 0; if (item.offsetWidth) { while (item && item!=document.body) { y += item.offsetTop; item = item.offsetParent; } } return y; } /* A class handling everything associated with the search panel. Parameters: name - The name of the global variable that will be storing this instance. Is needed to be able to set timeouts. resultPath - path to use for external files */ function SearchBox(name, resultsPath, inFrame, label) { if (!name || !resultsPath) { alert("Missing parameters to SearchBox."); } // ---------- Instance variables this.name = name; this.resultsPath = resultsPath; this.keyTimeout = 0; this.keyTimeoutLength = 500; this.closeSelectionTimeout = 300; this.lastSearchValue = ""; this.lastResultsPage = ""; this.hideTimeout = 0; this.searchIndex = 0; this.searchActive = false; this.insideFrame = inFrame; this.searchLabel = label; // ----------- DOM Elements this.DOMSearchField = function() { return document.getElementById("MSearchField"); } this.DOMSearchSelect = function() { return document.getElementById("MSearchSelect"); } this.DOMSearchSelectWindow = function() { return document.getElementById("MSearchSelectWindow"); } this.DOMPopupSearchResults = function() { return document.getElementById("MSearchResults"); } this.DOMPopupSearchResultsWindow = function() { return document.getElementById("MSearchResultsWindow"); } this.DOMSearchClose = function() { return document.getElementById("MSearchClose"); } this.DOMSearchBox = function() { return document.getElementById("MSearchBox"); } // ------------ Event Handlers // Called when focus is added or removed from the search field. this.OnSearchFieldFocus = function(isActive) { this.Activate(isActive); } this.OnSearchSelectShow = function() { var searchSelectWindow = this.DOMSearchSelectWindow(); var searchField = this.DOMSearchSelect(); if (this.insideFrame) { var left = getXPos(searchField); var top = getYPos(searchField); left += searchField.offsetWidth + 6; top += searchField.offsetHeight; // show search selection popup searchSelectWindow.style.display='block'; left -= searchSelectWindow.offsetWidth; searchSelectWindow.style.left = left + 'px'; searchSelectWindow.style.top = top + 'px'; } else { var left = getXPos(searchField); var top = getYPos(searchField); top += searchField.offsetHeight; // show search selection popup searchSelectWindow.style.display='block'; searchSelectWindow.style.left = left + 'px'; searchSelectWindow.style.top = top + 'px'; } // stop selection hide timer if (this.hideTimeout) { clearTimeout(this.hideTimeout); this.hideTimeout=0; } return false; // to avoid "image drag" default event } this.OnSearchSelectHide = function() { this.hideTimeout = setTimeout(this.name +".CloseSelectionWindow()", this.closeSelectionTimeout); } // Called when the content of the search field is changed. this.OnSearchFieldChange = function(evt) { if (this.keyTimeout) // kill running timer { clearTimeout(this.keyTimeout); this.keyTimeout = 0; } var e = (evt) ? evt : window.event; // for IE if (e.keyCode==40 || e.keyCode==13) { if (e.shiftKey==1) { this.OnSearchSelectShow(); var win=this.DOMSearchSelectWindow(); for (i=0;i<win.childNodes.length;i++) { var child = win.childNodes[i]; // get span within a if (child.className=='SelectItem') { child.focus(); return; } } return; } else if (window.frames.MSearchResults.searchResults) { var elem = window.frames.MSearchResults.searchResults.NavNext(0); if (elem) elem.focus(); } } else if (e.keyCode==27) // Escape out of the search field { this.DOMSearchField().blur(); this.DOMPopupSearchResultsWindow().style.display = 'none'; this.DOMSearchClose().style.display = 'none'; this.lastSearchValue = ''; this.Activate(false); return; } // strip whitespaces var searchValue = this.DOMSearchField().value.replace(/ +/g, ""); if (searchValue != this.lastSearchValue) // search value has changed { if (searchValue != "") // non-empty search { // set timer for search update this.keyTimeout = setTimeout(this.name + '.Search()', this.keyTimeoutLength); } else // empty search field { this.DOMPopupSearchResultsWindow().style.display = 'none'; this.DOMSearchClose().style.display = 'none'; this.lastSearchValue = ''; } } } this.SelectItemCount = function(id) { var count=0; var win=this.DOMSearchSelectWindow(); for (i=0;i<win.childNodes.length;i++) { var child = win.childNodes[i]; // get span within a if (child.className=='SelectItem') { count++; } } return count; } this.SelectItemSet = function(id) { var i,j=0; var win=this.DOMSearchSelectWindow(); for (i=0;i<win.childNodes.length;i++) { var child = win.childNodes[i]; // get span within a if (child.className=='SelectItem') { var node = child.firstChild; if (j==id) { node.innerHTML='&#8226;'; } else { node.innerHTML='&#160;'; } j++; } } } // Called when an search filter selection is made. // set item with index id as the active item this.OnSelectItem = function(id) { this.searchIndex = id; this.SelectItemSet(id); var searchValue = this.DOMSearchField().value.replace(/ +/g, ""); if (searchValue!="" && this.searchActive) // something was found -> do a search { this.Search(); } } this.OnSearchSelectKey = function(evt) { var e = (evt) ? evt : window.event; // for IE if (e.keyCode==40 && this.searchIndex<this.SelectItemCount()) // Down { this.searchIndex++; this.OnSelectItem(this.searchIndex); } else if (e.keyCode==38 && this.searchIndex>0) // Up { this.searchIndex--; this.OnSelectItem(this.searchIndex); } else if (e.keyCode==13 || e.keyCode==27) { this.OnSelectItem(this.searchIndex); this.CloseSelectionWindow(); this.DOMSearchField().focus(); } return false; } // --------- Actions // Closes the results window. this.CloseResultsWindow = function() { this.DOMPopupSearchResultsWindow().style.display = 'none'; this.DOMSearchClose().style.display = 'none'; this.Activate(false); } this.CloseSelectionWindow = function() { this.DOMSearchSelectWindow().style.display = 'none'; } // Performs a search. this.Search = function() { this.keyTimeout = 0; // strip leading whitespace var searchValue = this.DOMSearchField().value.replace(/^ +/, ""); var code = searchValue.toLowerCase().charCodeAt(0); var idxChar = searchValue.substr(0, 1).toLowerCase(); if ( 0xD800 <= code && code <= 0xDBFF && searchValue > 1) // surrogate pair { idxChar = searchValue.substr(0, 2); } var resultsPage; var resultsPageWithSearch; var hasResultsPage; var idx = indexSectionsWithContent[this.searchIndex].indexOf(idxChar); if (idx!=-1) { var hexCode=idx.toString(16); resultsPage = this.resultsPath + '/' + indexSectionNames[this.searchIndex] + '_' + hexCode + '.html'; resultsPageWithSearch = resultsPage+'?'+escape(searchValue); hasResultsPage = true; } else // nothing available for this search term { resultsPage = this.resultsPath + '/nomatches.html'; resultsPageWithSearch = resultsPage; hasResultsPage = false; } window.frames.MSearchResults.location = resultsPageWithSearch; var domPopupSearchResultsWindow = this.DOMPopupSearchResultsWindow(); if (domPopupSearchResultsWindow.style.display!='block') { var domSearchBox = this.DOMSearchBox(); this.DOMSearchClose().style.display = 'inline'; if (this.insideFrame) { var domPopupSearchResults = this.DOMPopupSearchResults(); domPopupSearchResultsWindow.style.position = 'relative'; domPopupSearchResultsWindow.style.display = 'block'; var width = document.body.clientWidth - 8; // the -8 is for IE :-( domPopupSearchResultsWindow.style.width = width + 'px'; domPopupSearchResults.style.width = width + 'px'; } else { var domPopupSearchResults = this.DOMPopupSearchResults(); var left = getXPos(domSearchBox) + 150; // domSearchBox.offsetWidth; var top = getYPos(domSearchBox) + 20; // domSearchBox.offsetHeight + 1; domPopupSearchResultsWindow.style.display = 'block'; left -= domPopupSearchResults.offsetWidth; domPopupSearchResultsWindow.style.top = top + 'px'; domPopupSearchResultsWindow.style.left = left + 'px'; } } this.lastSearchValue = searchValue; this.lastResultsPage = resultsPage; } // -------- Activation Functions // Activates or deactivates the search panel, resetting things to // their default values if necessary. this.Activate = function(isActive) { if (isActive || // open it this.DOMPopupSearchResultsWindow().style.display == 'block' ) { this.DOMSearchBox().className = 'MSearchBoxActive'; var searchField = this.DOMSearchField(); if (searchField.value == this.searchLabel) // clear "Search" term upon entry { searchField.value = ''; this.searchActive = true; } } else if (!isActive) // directly remove the panel { this.DOMSearchBox().className = 'MSearchBoxInactive'; this.DOMSearchField().value = this.searchLabel; this.searchActive = false; this.lastSearchValue = '' this.lastResultsPage = ''; } } } // ----------------------------------------------------------------------- // The class that handles everything on the search results page. function SearchResults(name) { // The number of matches from the last run of <Search()>. this.lastMatchCount = 0; this.lastKey = 0; this.repeatOn = false; // Toggles the visibility of the passed element ID. this.FindChildElement = function(id) { var parentElement = document.getElementById(id); var element = parentElement.firstChild; while (element && element!=parentElement) { if (element.nodeName == 'DIV' && element.className == 'SRChildren') { return element; } if (element.nodeName == 'DIV' && element.hasChildNodes()) { element = element.firstChild; } else if (element.nextSibling) { element = element.nextSibling; } else { do { element = element.parentNode; } while (element && element!=parentElement && !element.nextSibling); if (element && element!=parentElement) { element = element.nextSibling; } } } } this.Toggle = function(id) { var element = this.FindChildElement(id); if (element) { if (element.style.display == 'block') { element.style.display = 'none'; } else { element.style.display = 'block'; } } } // Searches for the passed string. If there is no parameter, // it takes it from the URL query. // // Always returns true, since other documents may try to call it // and that may or may not be possible. this.Search = function(search) { if (!search) // get search word from URL { search = window.location.search; search = search.substring(1); // Remove the leading '?' search = unescape(search); } search = search.replace(/^ +/, ""); // strip leading spaces search = search.replace(/ +$/, ""); // strip trailing spaces search = search.toLowerCase(); search = convertToId(search); var resultRows = document.getElementsByTagName("div"); var matches = 0; var i = 0; while (i < resultRows.length) { var row = resultRows.item(i); if (row.className == "SRResult") { var rowMatchName = row.id.toLowerCase(); rowMatchName = rowMatchName.replace(/^sr\d*_/, ''); // strip 'sr123_' if (search.length<=rowMatchName.length && rowMatchName.substr(0, search.length)==search) { row.style.display = 'block'; matches++; } else { row.style.display = 'none'; } } i++; } document.getElementById("Searching").style.display='none'; if (matches == 0) // no results { document.getElementById("NoMatches").style.display='block'; } else // at least one result { document.getElementById("NoMatches").style.display='none'; } this.lastMatchCount = matches; return true; } // return the first item with index index or higher that is visible this.NavNext = function(index) { var focusItem; while (1) { var focusName = 'Item'+index; focusItem = document.getElementById(focusName); if (focusItem && focusItem.parentNode.parentNode.style.display=='block') { break; } else if (!focusItem) // last element { break; } focusItem=null; index++; } return focusItem; } this.NavPrev = function(index) { var focusItem; while (1) { var focusName = 'Item'+index; focusItem = document.getElementById(focusName); if (focusItem && focusItem.parentNode.parentNode.style.display=='block') { break; } else if (!focusItem) // last element { break; } focusItem=null; index--; } return focusItem; } this.ProcessKeys = function(e) { if (e.type == "keydown") { this.repeatOn = false; this.lastKey = e.keyCode; } else if (e.type == "keypress") { if (!this.repeatOn) { if (this.lastKey) this.repeatOn = true; return false; // ignore first keypress after keydown } } else if (e.type == "keyup") { this.lastKey = 0; this.repeatOn = false; } return this.lastKey!=0; } this.Nav = function(evt,itemIndex) { var e = (evt) ? evt : window.event; // for IE if (e.keyCode==13) return true; if (!this.ProcessKeys(e)) return false; if (this.lastKey==38) // Up { var newIndex = itemIndex-1; var focusItem = this.NavPrev(newIndex); if (focusItem) { var child = this.FindChildElement(focusItem.parentNode.parentNode.id); if (child && child.style.display == 'block') // children visible { var n=0; var tmpElem; while (1) // search for last child { tmpElem = document.getElementById('Item'+newIndex+'_c'+n); if (tmpElem) { focusItem = tmpElem; } else // found it! { break; } n++; } } } if (focusItem) { focusItem.focus(); } else // return focus to search field { parent.document.getElementById("MSearchField").focus(); } } else if (this.lastKey==40) // Down { var newIndex = itemIndex+1; var focusItem; var item = document.getElementById('Item'+itemIndex); var elem = this.FindChildElement(item.parentNode.parentNode.id); if (elem && elem.style.display == 'block') // children visible { focusItem = document.getElementById('Item'+itemIndex+'_c0'); } if (!focusItem) focusItem = this.NavNext(newIndex); if (focusItem) focusItem.focus(); } else if (this.lastKey==39) // Right { var item = document.getElementById('Item'+itemIndex); var elem = this.FindChildElement(item.parentNode.parentNode.id); if (elem) elem.style.display = 'block'; } else if (this.lastKey==37) // Left { var item = document.getElementById('Item'+itemIndex); var elem = this.FindChildElement(item.parentNode.parentNode.id); if (elem) elem.style.display = 'none'; } else if (this.lastKey==27) // Escape { parent.searchBox.CloseResultsWindow(); parent.document.getElementById("MSearchField").focus(); } else if (this.lastKey==13) // Enter { return true; } return false; } this.NavChild = function(evt,itemIndex,childIndex) { var e = (evt) ? evt : window.event; // for IE if (e.keyCode==13) return true; if (!this.ProcessKeys(e)) return false; if (this.lastKey==38) // Up { if (childIndex>0) { var newIndex = childIndex-1; document.getElementById('Item'+itemIndex+'_c'+newIndex).focus(); } else // already at first child, jump to parent { document.getElementById('Item'+itemIndex).focus(); } } else if (this.lastKey==40) // Down { var newIndex = childIndex+1; var elem = document.getElementById('Item'+itemIndex+'_c'+newIndex); if (!elem) // last child, jump to parent next parent { elem = this.NavNext(itemIndex+1); } if (elem) { elem.focus(); } } else if (this.lastKey==27) // Escape { parent.searchBox.CloseResultsWindow(); parent.document.getElementById("MSearchField").focus(); } else if (this.lastKey==13) // Enter { return true; } return false; } } function setKeyActions(elem,action) { elem.setAttribute('onkeydown',action); elem.setAttribute('onkeypress',action); elem.setAttribute('onkeyup',action); } function setClassAttr(elem,attr) { elem.setAttribute('class',attr); elem.setAttribute('className',attr); } function createResults() { var results = document.getElementById("SRResults"); for (var e=0; e<searchData.length; e++) { var id = searchData[e][0]; var srResult = document.createElement('div'); srResult.setAttribute('id','SR_'+id); setClassAttr(srResult,'SRResult'); var srEntry = document.createElement('div'); setClassAttr(srEntry,'SREntry'); var srLink = document.createElement('a'); srLink.setAttribute('id','Item'+e); setKeyActions(srLink,'return searchResults.Nav(event,'+e+')'); setClassAttr(srLink,'SRSymbol'); srLink.innerHTML = searchData[e][1][0]; srEntry.appendChild(srLink); if (searchData[e][1].length==2) // single result { srLink.setAttribute('href',searchData[e][1][1][0]); if (searchData[e][1][1][1]) { srLink.setAttribute('target','_parent'); } var srScope = document.createElement('span'); setClassAttr(srScope,'SRScope'); srScope.innerHTML = searchData[e][1][1][2]; srEntry.appendChild(srScope); } else // multiple results { srLink.setAttribute('href','javascript:searchResults.Toggle("SR_'+id+'")'); var srChildren = document.createElement('div'); setClassAttr(srChildren,'SRChildren'); for (var c=0; c<searchData[e][1].length-1; c++) { var srChild = document.createElement('a'); srChild.setAttribute('id','Item'+e+'_c'+c); setKeyActions(srChild,'return searchResults.NavChild(event,'+e+','+c+')'); setClassAttr(srChild,'SRScope'); srChild.setAttribute('href',searchData[e][1][c+1][0]); if (searchData[e][1][c+1][1]) { srChild.setAttribute('target','_parent'); } srChild.innerHTML = searchData[e][1][c+1][2]; srChildren.appendChild(srChild); } srEntry.appendChild(srChildren); } srResult.appendChild(srEntry); results.appendChild(srResult); } }
{ "content_hash": "d30f9b0ff2ccc38161866fa48c0a903e", "timestamp": "", "source": "github", "line_count": 799, "max_line_length": 108, "avg_line_length": 27.683354192740925, "alnum_prop": 0.5761562457615624, "repo_name": "zzjkf2009/Acme-Robotics-Project", "id": "0c7278b0cc5f89c1e946d6ab63908462fcaa0da2", "size": "22119", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Docs/html/search/search.js", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "18782" }, { "name": "CMake", "bytes": "825" }, { "name": "CSS", "bytes": "29559" }, { "name": "HTML", "bytes": "245281" }, { "name": "JavaScript", "bytes": "29322" }, { "name": "Makefile", "bytes": "508" }, { "name": "PostScript", "bytes": "7556" }, { "name": "Python", "bytes": "5095" }, { "name": "TeX", "bytes": "45278" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="main.css"/> </head> <body> <div id="main"></div> <script src="organise.js"></script> <script> var node = document.getElementById('main'); var app = Elm.Main.embed(node); </script> </body> </html>
{ "content_hash": "7d0fdcca50752b607631ed0dd7197db8", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 48, "avg_line_length": 21.466666666666665, "alnum_prop": 0.5652173913043478, "repo_name": "maxf/waterfall", "id": "893841d10d3e5602136234d1d73a3d100c2122c2", "size": "322", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/organise.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3793" }, { "name": "Elm", "bytes": "55898" }, { "name": "HTML", "bytes": "10388" }, { "name": "JavaScript", "bytes": "918947" }, { "name": "PHP", "bytes": "6528" }, { "name": "Shell", "bytes": "658" } ], "symlink_target": "" }
namespace csci5570 { SimpleIdMapper::SimpleIdMapper(Node node, const std::vector<Node>& nodes) { // TODO } uint32_t SimpleIdMapper::GetNodeIdForThread(uint32_t tid) { // TODO } void SimpleIdMapper::Init(int num_server_threads_per_node) { // TODO } uint32_t SimpleIdMapper::AllocateWorkerThread(uint32_t node_id) { // TODO } void SimpleIdMapper::DeallocateWorkerThread(uint32_t node_id, uint32_t tid) { // TODO } std::vector<uint32_t> SimpleIdMapper::GetServerThreadsForId(uint32_t node_id) { // TODO } std::vector<uint32_t> SimpleIdMapper::GetWorkerHelperThreadsForId(uint32_t node_id) { // TODO } std::vector<uint32_t> SimpleIdMapper::GetWorkerThreadsForId(uint32_t node_id) { // TODO } std::vector<uint32_t> SimpleIdMapper::GetAllServerThreads() { // TODO } const uint32_t SimpleIdMapper::kMaxNodeId; const uint32_t SimpleIdMapper::kMaxThreadsPerNode; const uint32_t SimpleIdMapper::kMaxBgThreadsPerNode; const uint32_t SimpleIdMapper::kWorkerHelperThreadId; } // namespace csci5570
{ "content_hash": "c3dc2575f357e60dc508e6c973088486", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 85, "avg_line_length": 25.275, "alnum_prop": 0.7546983184965381, "repo_name": "TatianaJin/csci5570", "id": "ac03bd0229e1ce1f736407db17dad731fd70187e", "size": "1117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "driver/simple_id_mapper.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "153088" }, { "name": "CMake", "bytes": "15399" }, { "name": "Python", "bytes": "6838" } ], "symlink_target": "" }
package com.ee.midas.dsl.expressions; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface FunctionExpression { }
{ "content_hash": "fe93b9516d2579464144d91d3acd1a1a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 44, "avg_line_length": 23.53846153846154, "alnum_prop": 0.826797385620915, "repo_name": "EqualExperts/Midas", "id": "9c80c6415c5f927df0c60bbf43e7acc9259dbef2", "size": "2061", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/ee/midas/dsl/expressions/FunctionExpression.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "18851" }, { "name": "Groovy", "bytes": "103697" }, { "name": "Java", "bytes": "28308" }, { "name": "JavaScript", "bytes": "157883" }, { "name": "Python", "bytes": "6394" }, { "name": "Scala", "bytes": "573708" }, { "name": "Shell", "bytes": "4957" } ], "symlink_target": "" }
/** * webserver-db-app.js * * @version 1.0 * * DESCRIPTION: * a "HELLO WORLD" server-side application to demonstrate running a node * Webserver and a mongo DB on separate instances on AWS EC2. * Uses the Express and Mongoose node packages. * * * @throws none * @see nodejs.org * @see express.org * @see mongoosejs.com * * @author Ceeb * (C) 2013 Fatkahawai */ var http = require('http'); var mongoose = require('mongoose'); var express = require('express'); var app = express(); var config = { "USER" : "", // if your database has user/pwd defined "PASS" : "", "HOST" : "ec2-35-163-222-223.us-west-2.compute.amazonaws.com", // the domain name of our MongoDB EC2 instance "PORT" : "27017", // this is the default port mongoDB is listening for incoming queries "DATABASE" : "my_example" // the name of your database on that instanc }; var dbPath = "mongodb://" + config.USER + ":" + config.PASS + "@"+ config.HOST + ":"+ config.PORT + "/"+ config.DATABASE; var standardGreeting = 'Hello World!'; var db; // our MongoDb database var greetingSchema; // our mongoose Schema var Greeting; // our mongoose Model // create our schema greetingSchema = mongoose.Schema({ sentence: String }); // create our model using this schema Greeting = mongoose.model('Greeting', greetingSchema); // ------------------------------------------------------------------------ // Connect to our Mongo Database hosted on another server // console.log('\nattempting to connect to remote MongoDB instance on another EC2 server '+config.HOST); if ( !(db = mongoose.connect(dbPath)) ) console.log('Unable to connect to MongoDB at '+dbPath); else console.log('connecting to MongoDB at '+dbPath); // connection failed event handler mongoose.connection.on('error', function(err){ console.log('database connect error '+err); }); // mongoose.connection.on() // connection successful event handler: // check if the Db already contains a greeting. if not, create one and save it to the Db mongoose.connection.once('open', function() { var greeting; console.log('database '+config.DATABASE+' is now open on '+config.HOST ); // search if a greeting has already been saved in our db Greeting.find( function(err, greetings){ if( !err && greetings ){ // at least one greeting record already exists in our db. we can use that console.log(greetings.length+' greetings already exist in DB' ); } else { // no records found console.log('no greetings in DB yet, creating one' ); greeting = new Greeting({ sentence: standardGreeting }); greeting.save(function (err, greetingsav) { if (err){ // TODO handle the error console('couldnt save a greeting to the Db'); } else{ console.log('new greeting '+greeting.sentence+' was succesfully saved to Db' ); Greeting.find( function(err, greetings){ if( greetings ) console.log('checked after save: found '+greetings.length+' greetings in DB' ); }); // Greeting.find() } // else }); // greeting.save() } // if no records }); // Greeting.find() }); // mongoose.connection.once() // ------------------------------------------------------------------------ // set up Express routes to handle incoming requests // // Express route for all incoming requests app.get('/', function(req, res){ var responseText = ''; console.log('received client request'); if( !Greeting ) console.log('Database not ready'); // look up all greetings in our DB Greeting.find(function (err, greetings) { if (err) { console.log('couldnt find a greeting in DB. error '+err); next(err); } else { if(greetings){ console.log('found '+greetings.length+' greetings in DB'); // send newest greeting responseText = greetings[0].sentence; } console.log('sending greeting to client: '+responseText); res.send(responseText); } }); }); // apt.get() // // Express route to handle errors // app.use(function(err, req, res, next){ if (req.xhr) { res.send(500, 'Something went wrong!'); } else { next(err); } }); // apt.use() // ------------------------------------------------------------------------ // Start Express Webserver // console.log('starting the Express (NodeJS) Web server'); app.listen(8080); console.log('Webserver is listening on port 8080');
{ "content_hash": "d8326571c6fa3f34f635730e556a9bcf", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 120, "avg_line_length": 31.466666666666665, "alnum_prop": 0.5828389830508475, "repo_name": "apattath/aws_node_server", "id": "f51494f6518462b3c7857ec6167d61d87371125e", "size": "4720", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_server_sample.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4720" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_long_malloc_84a.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml Template File: sources-sinks-84a.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: malloc Allocate data using malloc() * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #include "std_testcase.h" #include "CWE762_Mismatched_Memory_Management_Routines__delete_long_malloc_84.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_malloc_84 { #ifndef OMITBAD void bad() { long * data; /* Initialize data*/ data = NULL; CWE762_Mismatched_Memory_Management_Routines__delete_long_malloc_84_bad * badObject = new CWE762_Mismatched_Memory_Management_Routines__delete_long_malloc_84_bad(data); delete badObject; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { long * data; /* Initialize data*/ data = NULL; CWE762_Mismatched_Memory_Management_Routines__delete_long_malloc_84_goodG2B * goodG2BObject = new CWE762_Mismatched_Memory_Management_Routines__delete_long_malloc_84_goodG2B(data); delete goodG2BObject; } /* goodG2B uses the BadSource with the GoodSink */ static void goodB2G() { long * data; /* Initialize data*/ data = NULL; CWE762_Mismatched_Memory_Management_Routines__delete_long_malloc_84_goodB2G * goodB2GObject = new CWE762_Mismatched_Memory_Management_Routines__delete_long_malloc_84_goodB2G(data); delete goodB2GObject; } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_malloc_84; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "6a361394955b7fecf061fcacef4cf46d", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 184, "avg_line_length": 30.16842105263158, "alnum_prop": 0.6950453593859037, "repo_name": "JianpingZeng/xcc", "id": "3616cd5d818ab264c4c91bd13152beb35be2295f", "size": "2866", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s04/CWE762_Mismatched_Memory_Management_Routines__delete_long_malloc_84a.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
namespace Nancy { using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text.RegularExpressions; using Nancy.Extensions; using Nancy.Helpers; using Nancy.IO; using Session; /// <summary> /// Encapsulates HTTP-request information to an Nancy application. /// </summary> [DebuggerDisplay("{DebuggerDisplay, nq}")] public class Request : IDisposable { private readonly List<HttpFile> files = new List<HttpFile>(); private dynamic form = new DynamicDictionary(); private IDictionary<string, string> cookies; /// <summary> /// Initializes a new instance of the <see cref="Request"/> class. /// </summary> /// <param name="method">The HTTP data transfer method used by the client.</param> /// <param name="path">The path of the requested resource, relative to the "Nancy root". This should not include the scheme, host name, or query portion of the URI.</param> /// <param name="scheme">The HTTP protocol that was used by the client.</param> public Request(string method, string path, string scheme) : this(method, new Url { Path = path, Scheme = scheme }) { } /// <summary> /// Initializes a new instance of the <see cref="Request"/> class. /// </summary> /// <param name="method">The HTTP data transfer method used by the client.</param> /// <param name="url">The <see cref="Url"/> of the requested resource</param> /// <param name="headers">The headers that was passed in by the client.</param> /// <param name="body">The <see cref="Stream"/> that represents the incoming HTTP body.</param> /// <param name="ip">The client's IP address</param> /// <param name="certificate">The client's certificate when present.</param> /// <param name="protocolVersion">The HTTP protocol version.</param> public Request(string method, Url url, RequestStream body = null, IDictionary<string, IEnumerable<string>> headers = null, string ip = null, byte[] certificate = null, string protocolVersion = null) { if (String.IsNullOrEmpty(method)) { throw new ArgumentOutOfRangeException("method"); } if (url == null) { throw new ArgumentNullException("url"); } if (url.Path == null) { throw new ArgumentNullException("url.Path"); } if (String.IsNullOrEmpty(url.Scheme)) { throw new ArgumentOutOfRangeException("url.Scheme"); } this.UserHostAddress = ip; this.Url = url; this.Method = method; this.Query = url.Query.AsQueryDictionary(); this.Body = body ?? RequestStream.FromStream(new MemoryStream()); this.Headers = new RequestHeaders(headers ?? new Dictionary<string, IEnumerable<string>>()); this.Session = new NullSessionProvider(); if (certificate != null && certificate.Length != 0) { this.ClientCertificate = new X509Certificate2(certificate); } this.ProtocolVersion = protocolVersion ?? string.Empty; if (String.IsNullOrEmpty(this.Url.Path)) { this.Url.Path = "/"; } this.ParseFormData(); this.RewriteMethod(); } /// <summary> /// Gets the certificate sent by the client. /// </summary> public X509Certificate ClientCertificate { get; private set; } /// <summary> /// Gets the HTTP protocol version. /// </summary> public string ProtocolVersion { get; private set; } /// <summary> /// Gets the IP address of the client /// </summary> public string UserHostAddress { get; private set; } /// <summary> /// Gets or sets the HTTP data transfer method used by the client. /// </summary> /// <value>The method.</value> public string Method { get; private set; } /// <summary> /// Gets the url /// </summary> public Url Url { get; private set; } /// <summary> /// Gets the request path, relative to the base path. /// Used for route matching etc. /// </summary> public string Path { get { return this.Url.Path; } } /// <summary> /// Gets the query string data of the requested resource. /// </summary> /// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of query string data.</value> public dynamic Query { get; set; } /// <summary> /// Gets a <see cref="RequestStream"/> that can be used to read the incoming HTTP body /// </summary> /// <value>A <see cref="RequestStream"/> object representing the incoming HTTP body.</value> public RequestStream Body { get; private set; } /// <summary> /// Gets the request cookies. /// </summary> public IDictionary<string, string> Cookies { get { return this.cookies ?? (this.cookies = this.GetCookieData()); } } /// <summary> /// Gets the current session. /// </summary> public ISession Session { get; set; } /// <summary> /// Gets the cookie data from the request header if it exists /// </summary> /// <returns>Cookies dictionary</returns> private IDictionary<string, string> GetCookieData() { var cookieDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); if (!this.Headers.Cookie.Any()) { return cookieDictionary; } var values = this.Headers["cookie"].First().TrimEnd(';').Split(';'); foreach (var parts in values.Select(c => c.Split(new[] { '=' }, 2))) { var cookieName = parts[0].Trim(); string cookieValue; if (parts.Length == 1) { //Cookie attribute cookieValue = string.Empty; } else { cookieValue = HttpUtility.UrlDecode(parts[1]); } cookieDictionary[cookieName] = cookieValue; } return cookieDictionary; } /// <summary> /// Gets a collection of files sent by the client- /// </summary> /// <value>An <see cref="IEnumerable{T}"/> instance, containing an <see cref="HttpFile"/> instance for each uploaded file.</value> public IEnumerable<HttpFile> Files { get { return this.files; } } /// <summary> /// Gets the form data of the request. /// </summary> /// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of form data.</value> /// <remarks>Currently Nancy will only parse form data sent using the application/x-www-url-encoded mime-type.</remarks> public dynamic Form { get { return this.form; } } /// <summary> /// Gets the HTTP headers sent by the client. /// </summary> /// <value>An <see cref="IDictionary{TKey,TValue}"/> containing the name and values of the headers.</value> /// <remarks>The values are stored in an <see cref="IEnumerable{T}"/> of string to be compliant with multi-value headers.</remarks> public RequestHeaders Headers { get; private set; } public void Dispose() { ((IDisposable)this.Body).Dispose(); } private void ParseFormData() { if (string.IsNullOrEmpty(this.Headers.ContentType)) { return; } var contentType = this.Headers["content-type"].First(); var mimeType = contentType.Split(';').First(); if (mimeType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) { var reader = new StreamReader(this.Body); this.form = reader.ReadToEnd().AsQueryDictionary(); this.Body.Position = 0; } if (!mimeType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase)) { return; } var boundary = Regex.Match(contentType, @"boundary=""?(?<token>[^\n\;\"" ]*)").Groups["token"].Value; var multipart = new HttpMultipart(this.Body, boundary); var formValues = new NameValueCollection(StaticConfiguration.CaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase); foreach (var httpMultipartBoundary in multipart.GetBoundaries()) { if (string.IsNullOrEmpty(httpMultipartBoundary.Filename)) { var reader = new StreamReader(httpMultipartBoundary.Value); formValues.Add(httpMultipartBoundary.Name, reader.ReadToEnd()); } else { this.files.Add(new HttpFile(httpMultipartBoundary)); } } foreach (var key in formValues.AllKeys.Where(key => key != null)) { this.form[key] = formValues[key]; } this.Body.Position = 0; } private void RewriteMethod() { if (!this.Method.Equals("POST", StringComparison.OrdinalIgnoreCase)) { return; } var overrides = new List<Tuple<string, string>> { Tuple.Create("_method form input element", (string)this.Form["_method"]), Tuple.Create("X-HTTP-Method-Override form input element", (string)this.Form["X-HTTP-Method-Override"]), Tuple.Create("X-HTTP-Method-Override header", this.Headers["X-HTTP-Method-Override"].FirstOrDefault()) }; var providedOverride = overrides.Where(x => !string.IsNullOrEmpty(x.Item2)); if (!providedOverride.Any()) { return; } if (providedOverride.Count() > 1) { var overrideSources = string.Join(", ", providedOverride); var errorMessage = string.Format("More than one HTTP method override was provided. The provided values where: {0}", overrideSources); throw new InvalidOperationException(errorMessage); } this.Method = providedOverride.Single().Item2; } private string DebuggerDisplay { get { return string.Format("{0} {1} {2}", this.Method, this.Url, this.ProtocolVersion).Trim(); } } } }
{ "content_hash": "41de4ef67e0556d32003b9a0300510f3", "timestamp": "", "source": "github", "line_count": 328, "max_line_length": 180, "avg_line_length": 36.08841463414634, "alnum_prop": 0.5274140407197769, "repo_name": "wtilton/Nancy", "id": "699a6f5846070e5e1474b3b26480b9b1e4aaa3d6", "size": "11837", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Nancy/Request.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3767141" }, { "name": "CSS", "bytes": "16121" }, { "name": "HTML", "bytes": "100650" }, { "name": "JavaScript", "bytes": "94374" }, { "name": "Liquid", "bytes": "22091" }, { "name": "PowerShell", "bytes": "3723" }, { "name": "Ruby", "bytes": "14116" }, { "name": "Visual Basic", "bytes": "381" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_16.html">Class Test_AbaRouteValidator_16</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_36715_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_16.html?line=41224#src-41224" >testAbaNumberCheck_36715_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:45:32 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_36715_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=18466#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
{ "content_hash": "3573931f5ec9934ff7fccf987b4a2c28", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 297, "avg_line_length": 43.92822966507177, "alnum_prop": 0.5097483934211959, "repo_name": "dcarda/aba.route.validator", "id": "f19c1fa47b78a7ebb08d56c57e00fbfc81a54438", "size": "9181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_16_testAbaNumberCheck_36715_good_e8y.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "18715254" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project name="name-of-project" default="build"> <target name="build" depends="prepare,vendors,parameters,lint,phploc,pdepend,phpmd-ci,phpcs-ci,phpcpd,phpdox,phpunit,phpcb"/> <target name="build-parallel" depends="prepare,lint,tools-parallel,phpunit,phpcb"/> <target name="tools-parallel" description="Run tools in parallel"> <parallel threadCount="2"> <sequential> <antcall target="pdepend"/> <antcall target="phpmd-ci"/> </sequential> <antcall target="phpcpd"/> <antcall target="phpcs-ci"/> <antcall target="phploc"/> <antcall target="phpdox"/> </parallel> </target> <target name="clean" description="Cleanup build artifacts"> <delete dir="${basedir}/app/build/api"/> <delete dir="${basedir}/app/build/code-browser"/> <delete dir="${basedir}/app/build/coverage"/> <delete dir="${basedir}/app/build/logs"/> <delete dir="${basedir}/app/build/pdepend"/> </target> <target name="prepare" depends="clean" description="Prepare for build"> <mkdir dir="${basedir}/app/build/api"/> <mkdir dir="${basedir}/app/build/code-browser"/> <mkdir dir="${basedir}/app/build/coverage"/> <mkdir dir="${basedir}/app/build/logs"/> <mkdir dir="${basedir}/app/build/pdepend"/> <mkdir dir="${basedir}/app/build/phpdox"/> </target> <target name="lint" description="Perform syntax check of sourcecode files"> <apply executable="php" failonerror="true"> <arg value="-l" /> <fileset dir="${basedir}/src"> <include name="**/*.php" /> <modified /> </fileset> <fileset dir="${basedir}/src/"> <include name="**/*Test.php" /> <modified /> </fileset> </apply> </target> <target name="phploc" description="Measure project size using PHPLOC"> <exec executable="phploc"> <arg value="--log-csv" /> <arg value="${basedir}/app/build/logs/phploc.csv" /> <arg path="${basedir}/src" /> </exec> </target> <target name="pdepend" description="Calculate software metrics using PHP_Depend"> <exec executable="pdepend"> <arg value="--jdepend-xml=${basedir}/app/build/logs/jdepend.xml" /> <arg value="--jdepend-chart=${basedir}/app/build/pdepend/dependencies.svg" /> <arg value="--overview-pyramid=${basedir}/app/build/pdepend/overview-pyramid.svg" /> <arg path="${basedir}/src" /> </exec> </target> <target name="phpmd" description="Perform project mess detection using PHPMD and print human readable output. Intended for usage on the command line before committing."> <exec executable="phpmd"> <arg path="${basedir}/src" /> <arg value="text" /> <arg value="${basedir}/app/Resources/jenkins/phpmd.xml" /> </exec> </target> <target name="phpmd-ci" description="Perform project mess detection using PHPMD creating a log file for the continuous integration server"> <exec executable="phpmd"> <arg path="${basedir}/src" /> <arg value="xml" /> <arg value="${basedir}/app/Resources/jenkins/phpmd.xml" /> <arg value="--reportfile" /> <arg value="${basedir}/app/build/logs/pmd.xml" /> </exec> </target> <target name="phpcs" description="Find coding standard violations using PHP_CodeSniffer and print human readable output. Intended for usage on the command line before committing."> <exec executable="phpcs"> <arg value="--standard=Symfony2" /> <arg path="${basedir}/src" /> </exec> </target> <target name="phpcs-ci" description="Find coding standard violations using PHP_CodeSniffer creating a log file for the continuous integration server"> <exec executable="phpcs" output="/dev/null"> <arg value="--report=checkstyle" /> <arg value="--report-file=${basedir}/app/build/logs/checkstyle.xml" /> <arg value="--standard=Symfony2" /> <arg path="${basedir}/src" /> </exec> </target> <target name="phpcpd" description="Find duplicate code using PHPCPD"> <exec executable="phpcpd"> <arg value="--log-pmd" /> <arg value="${basedir}/app/build/logs/pmd-cpd.xml" /> <arg path="${basedir}/src" /> </exec> </target> <target name="phpdox" description="Generate API documentation using phpDox"> <exec executable="phpdox"> <arg value="-f" /> <arg path="${basedir}/app/Resources/jenkins/phpdox.xml" /> </exec> </target> <target name="phpunit" description="Run unit tests with PHPUnit"> <exec executable="phpunit" failonerror="true"> <arg value="-c" /> <arg path="${basedir}/app/phpunit.xml" /> </exec> </target> <target name="phpcb" description="Aggregate tool output with PHP_CodeBrowser"> <exec executable="phpcb"> <arg value="--log" /> <arg path="${basedir}/app/build/logs" /> <arg value="--source" /> <arg path="${basedir}/src" /> <arg value="--output" /> <arg path="${basedir}/app/build/code-browser" /> </exec> </target> <target name="vendors" description="Update vendors"> <exec executable="php" failonerror="true"> <arg value="composer.phar" /> <arg value="update" /> </exec> </target> <target name="parameters" description="Copy parameters"> <exec executable="cp" failonerror="true"> <arg path="app/config/parameters.yml.dist" /> <arg path="app/config/parameters.yml" /> </exec> </target> </project>
{ "content_hash": "5cdbe7702090eaf384bb37a43e5582d4", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 184, "avg_line_length": 40.06666666666667, "alnum_prop": 0.5742096505823627, "repo_name": "Sylfrid/lunchy", "id": "aae73402a2c6dda7c400dbe237a48a9408822e9d", "size": "6010", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build2.xml", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "59824" } ], "symlink_target": "" }
<!DOCTYPE frameset SYSTEM "frameset.dtd"> <frameset> <predicate lemma="indemnify"> <note> Frames file for 'indemnify' based on sentences in wsj. No Verbnet entry. </note> <roleset id="indemnify.01" name="protect from damage" vncls="-"> <roles> <role descr="protector" n="0"/> <role descr="protected" n="1"/> <role descr="damage" n="2"/> </roles> <example name="the one example"> <inflection aspect="ns" form="infinitive" person="ns" tense="ns" voice="ns"/> <text> Sony-1 also agreed *trace*-1 to indemnify the producers against any liability to Warner. </text> <arg n="0">*trace*</arg> <rel>indemnify</rel> <arg n="1">the producers</arg> <arg n="2">against any liability to Warner</arg> </example> <note> OK, I had to look this one up too. </note> </roleset> </predicate> </frameset>
{ "content_hash": "a4a174fae640304c1f036b81ddef6c9c", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 93, "avg_line_length": 34.88235294117647, "alnum_prop": 0.45868465430016864, "repo_name": "keenon/jamr", "id": "28ddf46fc4e7de50cc93435894837f8d07e930a2", "size": "1186", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "data/frames/indemnify.xml", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "640454" }, { "name": "Perl", "bytes": "8697" }, { "name": "Python", "bytes": "76079" }, { "name": "Scala", "bytes": "353885" }, { "name": "Shell", "bytes": "41192" } ], "symlink_target": "" }
package com.blazebit.persistence.deltaspike.data.impl.builder; import com.blazebit.persistence.CriteriaBuilder; import com.blazebit.persistence.FullQueryBuilder; import com.blazebit.persistence.criteria.BlazeCriteriaBuilder; import com.blazebit.persistence.criteria.BlazeCriteriaQuery; import com.blazebit.persistence.criteria.BlazeCriteria; import com.blazebit.persistence.deltaspike.data.Pageable; import com.blazebit.persistence.deltaspike.data.Specification; import com.blazebit.persistence.deltaspike.data.base.builder.QueryBuilderUtils; import com.blazebit.persistence.deltaspike.data.impl.builder.part.EntityViewQueryRoot; import com.blazebit.persistence.deltaspike.data.impl.handler.EntityViewCdiQueryInvocationContext; import com.blazebit.persistence.deltaspike.data.impl.param.ExtendedParameters; import org.apache.deltaspike.data.impl.meta.MethodType; import org.apache.deltaspike.data.impl.meta.QueryInvocation; import javax.enterprise.context.ApplicationScoped; import javax.persistence.Query; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; /** * Implementation is similar to {@link org.apache.deltaspike.data.impl.builder.MethodQueryBuilder} but was modified to * work with entity views. * * @author Moritz Becker * @since 1.2.0 */ @QueryInvocation(MethodType.PARSE) @ApplicationScoped public class EntityViewMethodQueryBuilder extends EntityViewQueryBuilder { @Override public Object execute(EntityViewCdiQueryInvocationContext context) { Query jpaQuery = createJpaQuery(context); return context.executeQuery(jpaQuery); } private <V> Query createJpaQuery(EntityViewCdiQueryInvocationContext context) { ExtendedParameters params = context.getParams(); EntityViewQueryRoot root = context.getRepositoryMethod().getEntityViewQueryRoot(); Pageable pageable = params.getPageable(); CriteriaBuilder<?> cb; Specification<?> specification = params.getSpecification(); if (specification == null) { cb = context.getCriteriaBuilderFactory().create(context.getEntityManager(), context.getEntityClass()); root.apply(cb); } else { BlazeCriteriaBuilder blazeCriteriaBuilder = BlazeCriteria.get(context.getCriteriaBuilderFactory()); BlazeCriteriaQuery<?> query = blazeCriteriaBuilder.createQuery(context.getEntityClass()); Root queryRoot = query.from(context.getEntityClass()); root.apply(queryRoot, query, blazeCriteriaBuilder); Predicate predicate = specification.toPredicate(queryRoot, query, blazeCriteriaBuilder); if (predicate != null) { if (query.getRestriction() == null) { query.where(predicate); } else { query.where(query.getRestriction(), predicate); } } cb = query.createCriteriaBuilder(context.getEntityManager()); } Class<V> entityViewClass = (Class<V>) context.getEntityViewClass(); boolean keysetExtraction = false; // TODO: depending on return type we might need to do keyset extraction FullQueryBuilder<? ,?> fullCb = QueryBuilderUtils.getFullQueryBuilder(cb, pageable, context.getEntityViewManager(), entityViewClass, keysetExtraction); fullCb = context.applyCriteriaBuilderPostProcessors(fullCb); Query q = params.applyTo(context.createQuery(fullCb)); return context.applyRestrictions(q); } }
{ "content_hash": "9acc10866c29e60557ae2b3977959b04", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 159, "avg_line_length": 46.946666666666665, "alnum_prop": 0.7404146549275774, "repo_name": "Blazebit/blaze-persistence", "id": "e378e92505c08cc2fda8612b68de73f5e29ecc40", "size": "4121", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "integration/deltaspike-data/impl-1.7/src/main/java/com/blazebit/persistence/deltaspike/data/impl/builder/EntityViewMethodQueryBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "44368" }, { "name": "Batchfile", "bytes": "727" }, { "name": "CSS", "bytes": "85149" }, { "name": "FreeMarker", "bytes": "16964" }, { "name": "HTML", "bytes": "8988" }, { "name": "Java", "bytes": "20068561" }, { "name": "JavaScript", "bytes": "7022" }, { "name": "Shell", "bytes": "12643" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "d6d12ec64bdec7f051da609084cb7c26", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "2c50d1a668487ad59687a4f7137bcec0de98dd27", "size": "190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Chromista/Ochrophyta/Xanthophyceae/Mischococcales/Pleurochloridaceae/Ellipsoidion/Ellipsoidion pachydermum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
export const selectActivePanel = state => state.activePanel;
{ "content_hash": "8fbd85deb0aee55ce117f62a0a882227", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 60, "avg_line_length": 61, "alnum_prop": 0.8032786885245902, "repo_name": "nicksergeant/leather", "id": "fcd69acccde01414dcec4b180b82f36932645fa5", "size": "61", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/js/selectors/panels.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "782" }, { "name": "Elixir", "bytes": "55265" }, { "name": "HTML", "bytes": "6164" }, { "name": "JavaScript", "bytes": "50425" }, { "name": "Makefile", "bytes": "74" } ], "symlink_target": "" }
"use strict"; const namedExports = new Map([ ["FileSystem", "./lib/filesystem.js"], ["EntityType", "./lib/entity-type.js"], ["System", "./lib/system.js"], // TODO: Rename ["Resource", "./lib/resource.js"], ["File", "./lib/file.js"], ["Directory", "./lib/directory.js"] ]); for(const [key, value] of namedExports) Object.defineProperty(module.exports, key, { configurable: false, writable: false, enumerable: false, value: require(value), }); global.AtomFS = module.exports.FileSystem;
{ "content_hash": "038ed49d8ea0a37e9cc0ec9d159ff8df", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 51, "avg_line_length": 26.15, "alnum_prop": 0.6290630975143403, "repo_name": "noahlvb/dotfiles", "id": "fee79728067545345d1c70a7773643e1d0c176b0", "size": "523", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": ".atom/packages/file-icons/node_modules/atom-fs/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "220" }, { "name": "CSS", "bytes": "117043" }, { "name": "CoffeeScript", "bytes": "653982" }, { "name": "HTML", "bytes": "38" }, { "name": "JavaScript", "bytes": "695056" }, { "name": "Shell", "bytes": "37894" }, { "name": "TeX", "bytes": "404" } ], "symlink_target": "" }
var SendGrid = require('sendgrid').SendGrid ,Email = require('sendgrid').Email; var sendgrid, from; exports.load = function(app) { sendgrid = new SendGrid(app.settings.sendgrid_user, app.settings.sendgrid_key); from = app.settings.system_email; }; var sendMail = exports.sendMail = function(to,body,subject,callback) { if(!sendgrid) { console.log('email not sent because it\'s off in app.js. to turn mails on set app.set("send_mails",true); '); callback(); return; } console.log('sending to ' + to + ' ' + subject); var email = new Email({ to:[to], from:from, fromname:'אמנת הולכי רגל ורוכבי אופניים', subject:subject, html:body }); console.log('mail sent to ' + to); sendgrid.send(email,function(success,message) { if(!success){ console.error('mail was not sent'); console.error(message); callback(message); } else{ console.log('mail was sent'); callback(null,message); } }); //sendSMTPMail(to, from, body, subject, function(err) { // if(err){ // console.error('mail was not sent'); // callback('mail was not sent'); // } // else{ // console.log('mail was sent'); // callback(null, 'mail was sent'); // } // }); }; var sendMailFromTemplate = exports.sendMailFromTemplate = function(to, string,callback) { var parts = string.split('<!--body -->'); var subject = parts[0] || 'אמנת הולכי רגל ורוכבי אופניים'; var body = parts[1] || parts[0]; sendMail(to,body,subject,callback); }; var sendSMTPMail = module.exports.sendSMTPMail = function (userMail, from, body, subject, callback) { var nodemailer = require('nodemailer'); var smtpTransport = require('nodemailer-smtp-transport'); // create reusable transporter object using SMTP transport var transporter = nodemailer.createTransport(smtpTransport({ secure: false, debug: true, tls: {rejectUnauthorized: false} })); var mailOptions = { from: from , // sender address to: userMail, // list of receivers subject: subject, // Subject line html: body // html body }; // //// send mail with defined transport object transporter.sendMail(mailOptions, function(error, info){ if(error){ console.log(error); callback(null, info); }else{ console.log('Message sent: ' + info.response); callback(); } }); };
{ "content_hash": "afe9e5cb2b7236aa4b4d998946e5bb12", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 117, "avg_line_length": 28.64516129032258, "alnum_prop": 0.5709459459459459, "repo_name": "Aharon-Porath/Democrasee", "id": "fdf2d866cd6d97072913edc191adf15be7e9154b", "size": "2716", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/mail.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "100" }, { "name": "CSS", "bytes": "601961" }, { "name": "HTML", "bytes": "123923" }, { "name": "JavaScript", "bytes": "1452828" }, { "name": "PHP", "bytes": "8674" }, { "name": "Shell", "bytes": "107" } ], "symlink_target": "" }
ACCEPTED #### According to World Register of Marine Species #### Published in null #### Original name null ### Remarks null
{ "content_hash": "190db413e0cd4cdbede6d327625427f3", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 32, "avg_line_length": 9.76923076923077, "alnum_prop": 0.7007874015748031, "repo_name": "mdoering/backbone", "id": "736c707f2fbbd46b309a9932ed6ffff72d6d955b", "size": "188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Chromista/Haplophragmoididae/Conglophragmium/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.aldoborrero.tinder.api.entities; public class AuthData { private String facebookToken; private String locale; public AuthData(String facebookToken, String locale) { this.facebookToken = facebookToken; this.locale = locale; } public String getFacebookToken() { return facebookToken; } public void setFacebookToken(String facebookToken) { this.facebookToken = facebookToken; } public String getLocale() { return locale; } public void setLocale(String locale) { this.locale = locale; } }
{ "content_hash": "8d34bdf261b92a536fe07e3fd72331e2", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 58, "avg_line_length": 20.724137931034484, "alnum_prop": 0.6572379367720466, "repo_name": "aldoborrero/tinder-java-api", "id": "449449441d488fe9a627c8f475b2a6b630a7846c", "size": "1219", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "api/src/main/java/com/aldoborrero/tinder/api/entities/AuthData.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "14276" }, { "name": "Java", "bytes": "114187" } ], "symlink_target": "" }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Box } from 'axs'; import { Image } from '../base'; import { StyledViewPager, StyledFrame, StyledTrack } from './hocs'; import ProgressPage from './progress-page'; import ProgressView from './progress-view'; import ProgressBar from './progress-bar'; const thumb = image => image.replace('.jpg', '-s.jpg'); const styles = { viewport: { maxWidth: 800, margin: '0 auto', flexDirection: 'column', }, frame: { maxWidth: 800, margin: '0 auto', }, pageNav: { flexDirection: 'row', }, }; class Carousel extends Component { constructor(props) { super(props); this.state = { currentView: 0, progress: 0, }; this._handleScroll = this._handleScroll.bind(this); } componentWillReceiveProps(nextProps) { if (this.props.productId !== nextProps.productId) { this.setState({ currentView: 0, progress: 0 }); } } _handleScroll(progress) { this.setState({ progress }); } render() { const { currentView, progress } = this.state; return ( <StyledViewPager width={1} display="flex" css={styles.viewport} > <StyledFrame width={1} ref={c => this.frame = c} // eslint-disable-line no-return-assign css={styles.frame} > <StyledTrack display="flex" currentView={currentView} onScroll={this._handleScroll} onViewChange={(currentIndicies) => { this.setState({ currentView: currentIndicies[0] }); }} > {this.props.images.map((image, i) => ( <ProgressView key={`${this.props.productId}_${i}`}> <Image src={`/static/images/product/${image}`} /> </ProgressView> ))} </StyledTrack> <ProgressBar progress={progress} /> </StyledFrame> <Box my1 mx0 display="flex" justifyContent="flex-start" alignItems="center" is="nav" css={styles.pageNav} > {this.props.images.map((image, i) => <ProgressPage key={`${this.props.productId}_s_${i}`} index={i} onClick={() => this.setState({ currentView: i })} > <Image src={`/static/images/product/${thumb(image)}`} /> </ProgressPage> )} </Box> </StyledViewPager> ); } } Carousel.propTypes = { images: PropTypes.arrayOf(PropTypes.string), productId: PropTypes.string, }; Carousel.displayName = 'Carousel'; export default Carousel;
{ "content_hash": "e43ff5cc28750e1c8ae1c2a5ee741485", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 75, "avg_line_length": 24.972477064220183, "alnum_prop": 0.5440852314474651, "repo_name": "dwest-teo/wattos-spaceship-emporium", "id": "5a0318aa3595915637d33a9e3c1e3830c0535d0e", "size": "2722", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/carousel/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "47141" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../../../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../../../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../../../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../../../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../../../_static/javascripts/modernizr.js"></script> <title>Generalized Least Squares &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../../../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../../../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../../../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../../../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../../../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../../../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../../../_static/stylesheets/deprecation.css"> <link rel="stylesheet" type="text/css" href="../../../_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="../../../_static/material.css" /> <link rel="stylesheet" type="text/css" href="../../../_static/graphviz.css" /> <link rel="stylesheet" type="text/css" href="../../../_static/plot_directive.css" /> <script data-url_root="../../../" id="documentation_options" src="../../../_static/documentation_options.js"></script> <script src="../../../_static/jquery.js"></script> <script src="../../../_static/underscore.js"></script> <script src="../../../_static/doctools.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script>window.MathJax = {"tex": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true}, "options": {"ignoreHtmlClass": "tex2jax_ignore|mathjax_ignore|document", "processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script> <script defer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> <link rel="shortcut icon" href="../../../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../../../about.html" /> <link rel="index" title="Index" href="../../../genindex.html" /> <link rel="search" title="Search" href="../../../search.html" /> <link rel="next" title="Quantile regression" href="quantile_regression.html" /> <link rel="prev" title="Ordinary Least Squares" href="ols.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#examples/notebooks/generated/gls" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../../../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../../../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.13.2</span> <span class="md-header-nav__topic"> Generalized Least Squares </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../../../search.html" method="get" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../../../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../../../versions-v2.json", target_loc = "../../../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../../index.html" class="md-tabs__link">Examples</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../../../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../../../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../../../index.html" title="statsmodels">statsmodels v0.13.2</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../../../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../../../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../../../user-guide.html" class="md-nav__link">User Guide</a> </li> <li class="md-nav__item"> <a href="../../index.html" class="md-nav__link">Examples</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../../index.html#linear-regression-models" class="md-nav__link">Linear Regression Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="ols.html" class="md-nav__link">Ordinary Least Squares</a> </li> <li class="md-nav__item"> <input class="md-toggle md-nav__toggle" data-md-toggle="toc" type="checkbox" id="__toc"> <label class="md-nav__link md-nav__link--active" for="__toc"> Generalized Least Squares </label> <a href="#" class="md-nav__link md-nav__link--active">Generalized Least Squares</a> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../../../_sources/examples/notebooks/generated/gls.ipynb.txt">Show Source</a> </li> </ul> </nav> </li> <li class="md-nav__item"> <a href="quantile_regression.html" class="md-nav__link">Quantile regression</a> </li> <li class="md-nav__item"> <a href="recursive_ls.html" class="md-nav__link">Recursive least squares</a> </li> <li class="md-nav__item"> <a href="rolling_ls.html" class="md-nav__link">Rolling Regression</a> </li> <li class="md-nav__item"> <a href="regression_diagnostics.html" class="md-nav__link">Regression diagnostics</a> </li> <li class="md-nav__item"> <a href="wls.html" class="md-nav__link">Weighted Least Squares</a> </li> <li class="md-nav__item"> <a href="mixed_lm_example.html" class="md-nav__link">Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="mixed_lm_example.html#Comparing-R-lmer-to-statsmodels-MixedLM" class="md-nav__link">Comparing R lmer to statsmodels MixedLM</a> </li> <li class="md-nav__item"> <a href="variance_components.html" class="md-nav__link">Variance Component Analysis</a> </li></ul> </li> <li class="md-nav__item"> <a href="../../index.html#plotting" class="md-nav__link">Plotting</a> </li> <li class="md-nav__item"> <a href="../../index.html#discrete-choice-models" class="md-nav__link">Discrete Choice Models</a> </li> <li class="md-nav__item"> <a href="../../index.html#nonparametric-statistics" class="md-nav__link">Nonparametric Statistics</a> </li> <li class="md-nav__item"> <a href="../../index.html#generalized-linear-models" class="md-nav__link">Generalized Linear Models</a> </li> <li class="md-nav__item"> <a href="../../index.html#robust-regression" class="md-nav__link">Robust Regression</a> </li> <li class="md-nav__item"> <a href="../../index.html#generalized-estimating-equations" class="md-nav__link">Generalized Estimating Equations</a> </li> <li class="md-nav__item"> <a href="../../index.html#statistics" class="md-nav__link">Statistics</a> </li> <li class="md-nav__item"> <a href="../../index.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../../index.html#state-space-models" class="md-nav__link">State space models</a> </li> <li class="md-nav__item"> <a href="../../index.html#state-space-models-technical-notes" class="md-nav__link">State space models - Technical notes</a> </li> <li class="md-nav__item"> <a href="../../index.html#forecasting" class="md-nav__link">Forecasting</a> </li> <li class="md-nav__item"> <a href="../../index.html#multivariate-methods" class="md-nav__link">Multivariate Methods</a> </li> <li class="md-nav__item"> <a href="../../index.html#user-notes" class="md-nav__link">User Notes</a> </li></ul> </li> <li class="md-nav__item"> <a href="../../../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../../../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../../../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../../../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../../../_sources/examples/notebooks/generated/gls.ipynb.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <style> /* CSS for nbsphinx extension */ /* remove conflicting styling from Sphinx themes */ div.nbinput.container div.prompt *, div.nboutput.container div.prompt *, div.nbinput.container div.input_area pre, div.nboutput.container div.output_area pre, div.nbinput.container div.input_area .highlight, div.nboutput.container div.output_area .highlight { border: none; padding: 0; margin: 0; box-shadow: none; } div.nbinput.container > div[class*=highlight], div.nboutput.container > div[class*=highlight] { margin: 0; } div.nbinput.container div.prompt *, div.nboutput.container div.prompt * { background: none; } div.nboutput.container div.output_area .highlight, div.nboutput.container div.output_area pre { background: unset; } div.nboutput.container div.output_area div.highlight { color: unset; /* override Pygments text color */ } /* avoid gaps between output lines */ div.nboutput.container div[class*=highlight] pre { line-height: normal; } /* input/output containers */ div.nbinput.container, div.nboutput.container { display: -webkit-flex; display: flex; align-items: flex-start; margin: 0; width: 100%; } @media (max-width: 540px) { div.nbinput.container, div.nboutput.container { flex-direction: column; } } /* input container */ div.nbinput.container { padding-top: 5px; } /* last container */ div.nblast.container { padding-bottom: 5px; } /* input prompt */ div.nbinput.container div.prompt pre { color: #307FC1; } /* output prompt */ div.nboutput.container div.prompt pre { color: #BF5B3D; } /* all prompts */ div.nbinput.container div.prompt, div.nboutput.container div.prompt { width: 4.5ex; padding-top: 5px; position: relative; user-select: none; } div.nbinput.container div.prompt > div, div.nboutput.container div.prompt > div { position: absolute; right: 0; margin-right: 0.3ex; } @media (max-width: 540px) { div.nbinput.container div.prompt, div.nboutput.container div.prompt { width: unset; text-align: left; padding: 0.4em; } div.nboutput.container div.prompt.empty { padding: 0; } div.nbinput.container div.prompt > div, div.nboutput.container div.prompt > div { position: unset; } } /* disable scrollbars on prompts */ div.nbinput.container div.prompt pre, div.nboutput.container div.prompt pre { overflow: hidden; } /* input/output area */ div.nbinput.container div.input_area, div.nboutput.container div.output_area { -webkit-flex: 1; flex: 1; overflow: auto; } @media (max-width: 540px) { div.nbinput.container div.input_area, div.nboutput.container div.output_area { width: 100%; } } /* input area */ div.nbinput.container div.input_area { border: 1px solid #e0e0e0; border-radius: 2px; /*background: #f5f5f5;*/ } /* override MathJax center alignment in output cells */ div.nboutput.container div[class*=MathJax] { text-align: left !important; } /* override sphinx.ext.imgmath center alignment in output cells */ div.nboutput.container div.math p { text-align: left; } /* standard error */ div.nboutput.container div.output_area.stderr { background: #fdd; } /* ANSI colors */ .ansi-black-fg { color: #3E424D; } .ansi-black-bg { background-color: #3E424D; } .ansi-black-intense-fg { color: #282C36; } .ansi-black-intense-bg { background-color: #282C36; } .ansi-red-fg { color: #E75C58; } .ansi-red-bg { background-color: #E75C58; } .ansi-red-intense-fg { color: #B22B31; } .ansi-red-intense-bg { background-color: #B22B31; } .ansi-green-fg { color: #00A250; } .ansi-green-bg { background-color: #00A250; } .ansi-green-intense-fg { color: #007427; } .ansi-green-intense-bg { background-color: #007427; } .ansi-yellow-fg { color: #DDB62B; } .ansi-yellow-bg { background-color: #DDB62B; } .ansi-yellow-intense-fg { color: #B27D12; } .ansi-yellow-intense-bg { background-color: #B27D12; } .ansi-blue-fg { color: #208FFB; } .ansi-blue-bg { background-color: #208FFB; } .ansi-blue-intense-fg { color: #0065CA; } .ansi-blue-intense-bg { background-color: #0065CA; } .ansi-magenta-fg { color: #D160C4; } .ansi-magenta-bg { background-color: #D160C4; } .ansi-magenta-intense-fg { color: #A03196; } .ansi-magenta-intense-bg { background-color: #A03196; } .ansi-cyan-fg { color: #60C6C8; } .ansi-cyan-bg { background-color: #60C6C8; } .ansi-cyan-intense-fg { color: #258F8F; } .ansi-cyan-intense-bg { background-color: #258F8F; } .ansi-white-fg { color: #C5C1B4; } .ansi-white-bg { background-color: #C5C1B4; } .ansi-white-intense-fg { color: #A1A6B2; } .ansi-white-intense-bg { background-color: #A1A6B2; } .ansi-default-inverse-fg { color: #FFFFFF; } .ansi-default-inverse-bg { background-color: #000000; } .ansi-bold { font-weight: bold; } .ansi-underline { text-decoration: underline; } div.nbinput.container div.input_area div[class*=highlight] > pre, div.nboutput.container div.output_area div[class*=highlight] > pre, div.nboutput.container div.output_area div[class*=highlight].math, div.nboutput.container div.output_area.rendered_html, div.nboutput.container div.output_area > div.output_javascript, div.nboutput.container div.output_area:not(.rendered_html) > img{ padding: 5px; margin: 0; } /* fix copybtn overflow problem in chromium (needed for 'sphinx_copybutton') */ div.nbinput.container div.input_area > div[class^='highlight'], div.nboutput.container div.output_area > div[class^='highlight']{ overflow-y: hidden; } /* hide copybtn icon on prompts (needed for 'sphinx_copybutton') */ .prompt .copybtn { display: none; } /* Some additional styling taken form the Jupyter notebook CSS */ div.rendered_html table { border: none; border-collapse: collapse; border-spacing: 0; color: black; font-size: 12px; table-layout: fixed; } div.rendered_html thead { border-bottom: 1px solid black; vertical-align: bottom; } div.rendered_html tr, div.rendered_html th, div.rendered_html td { text-align: right; vertical-align: middle; padding: 0.5em 0.5em; line-height: normal; white-space: normal; max-width: none; border: none; } div.rendered_html th { font-weight: bold; } div.rendered_html tbody tr:nth-child(odd) { background: #f5f5f5; } div.rendered_html tbody tr:hover { background: rgba(66, 165, 245, 0.2); } </style> <section id="Generalized-Least-Squares"> <h1 id="examples-notebooks-generated-gls--page-root">Generalized Least Squares<a class="headerlink" href="#examples-notebooks-generated-gls--page-root" title="Permalink to this headline">¶</a></h1> <div class="nbinput nblast docutils container"> <div class="prompt highlight-none notranslate"><div class="highlight"><pre><span></span>[1]: </pre></div> </div> <div class="input_area highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span> <span class="kn">import</span> <span class="nn">statsmodels.api</span> <span class="k">as</span> <span class="nn">sm</span> </pre></div> </div> </div> <p>The Longley dataset is a time series dataset:</p> <div class="nbinput docutils container"> <div class="prompt highlight-none notranslate"><div class="highlight"><pre><span></span>[2]: </pre></div> </div> <div class="input_area highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">data</span> <span class="o">=</span> <span class="n">sm</span><span class="o">.</span><span class="n">datasets</span><span class="o">.</span><span class="n">longley</span><span class="o">.</span><span class="n">load</span><span class="p">()</span> <span class="n">data</span><span class="o">.</span><span class="n">exog</span> <span class="o">=</span> <span class="n">sm</span><span class="o">.</span><span class="n">add_constant</span><span class="p">(</span><span class="n">data</span><span class="o">.</span><span class="n">exog</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">data</span><span class="o">.</span><span class="n">exog</span><span class="o">.</span><span class="n">head</span><span class="p">())</span> </pre></div> </div> </div> <div class="nboutput nblast docutils container"> <div class="prompt empty docutils container"> </div> <div class="output_area docutils container"> <div class="highlight"><pre> const GNPDEFL GNP UNEMP ARMED POP YEAR 0 1.0 83.0 234289.0 2356.0 1590.0 107608.0 1947.0 1 1.0 88.5 259426.0 2325.0 1456.0 108632.0 1948.0 2 1.0 88.2 258054.0 3682.0 1616.0 109773.0 1949.0 3 1.0 89.5 284599.0 3351.0 1650.0 110929.0 1950.0 4 1.0 96.2 328975.0 2099.0 3099.0 112075.0 1951.0 </pre></div></div> </div> <p>Let’s assume that the data is heteroskedastic and that we know the nature of the heteroskedasticity. We can then define <code class="docutils literal notranslate"><span class="pre">sigma</span></code> and use it to give us a GLS model</p> <p>First we will obtain the residuals from an OLS fit</p> <div class="nbinput nblast docutils container"> <div class="prompt highlight-none notranslate"><div class="highlight"><pre><span></span>[3]: </pre></div> </div> <div class="input_area highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">ols_resid</span> <span class="o">=</span> <span class="n">sm</span><span class="o">.</span><span class="n">OLS</span><span class="p">(</span><span class="n">data</span><span class="o">.</span><span class="n">endog</span><span class="p">,</span> <span class="n">data</span><span class="o">.</span><span class="n">exog</span><span class="p">)</span><span class="o">.</span><span class="n">fit</span><span class="p">()</span><span class="o">.</span><span class="n">resid</span> </pre></div> </div> </div> <p>Assume that the error terms follow an AR(1) process with a trend:</p> <p><span class="math notranslate nohighlight">\(\epsilon_i = \beta_0 + \rho\epsilon_{i-1} + \eta_i\)</span></p> <p>where <span class="math notranslate nohighlight">\(\eta \sim N(0,\Sigma^2)\)</span></p> <p>and that <span class="math notranslate nohighlight">\(\rho\)</span> is simply the correlation of the residual a consistent estimator for rho is to regress the residuals on the lagged residuals</p> <div class="nbinput docutils container"> <div class="prompt highlight-none notranslate"><div class="highlight"><pre><span></span>[4]: </pre></div> </div> <div class="input_area highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">resid_fit</span> <span class="o">=</span> <span class="n">sm</span><span class="o">.</span><span class="n">OLS</span><span class="p">(</span> <span class="n">np</span><span class="o">.</span><span class="n">asarray</span><span class="p">(</span><span class="n">ols_resid</span><span class="p">)[</span><span class="mi">1</span><span class="p">:],</span> <span class="n">sm</span><span class="o">.</span><span class="n">add_constant</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">asarray</span><span class="p">(</span><span class="n">ols_resid</span><span class="p">)[:</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span> <span class="p">)</span><span class="o">.</span><span class="n">fit</span><span class="p">()</span> <span class="nb">print</span><span class="p">(</span><span class="n">resid_fit</span><span class="o">.</span><span class="n">tvalues</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span> <span class="nb">print</span><span class="p">(</span><span class="n">resid_fit</span><span class="o">.</span><span class="n">pvalues</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span> </pre></div> </div> </div> <div class="nboutput nblast docutils container"> <div class="prompt empty docutils container"> </div> <div class="output_area docutils container"> <div class="highlight"><pre> -1.4390229839793167 0.17378444788655237 </pre></div></div> </div> <p>While we do not have strong evidence that the errors follow an AR(1) process we continue</p> <div class="nbinput nblast docutils container"> <div class="prompt highlight-none notranslate"><div class="highlight"><pre><span></span>[5]: </pre></div> </div> <div class="input_area highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">rho</span> <span class="o">=</span> <span class="n">resid_fit</span><span class="o">.</span><span class="n">params</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> </pre></div> </div> </div> <p>As we know, an AR(1) process means that near-neighbors have a stronger relation so we can give this structure by using a toeplitz matrix</p> <div class="nbinput docutils container"> <div class="prompt highlight-none notranslate"><div class="highlight"><pre><span></span>[6]: </pre></div> </div> <div class="input_area highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">scipy.linalg</span> <span class="kn">import</span> <span class="n">toeplitz</span> <span class="n">toeplitz</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">))</span> </pre></div> </div> </div> <div class="nboutput nblast docutils container"> <div class="prompt highlight-none notranslate"><div class="highlight"><pre><span></span>[6]: </pre></div> </div> <div class="output_area docutils container"> <div class="highlight"><pre> array([[0, 1, 2, 3, 4], [1, 0, 1, 2, 3], [2, 1, 0, 1, 2], [3, 2, 1, 0, 1], [4, 3, 2, 1, 0]]) </pre></div></div> </div> <div class="nbinput nblast docutils container"> <div class="prompt highlight-none notranslate"><div class="highlight"><pre><span></span>[7]: </pre></div> </div> <div class="input_area highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">order</span> <span class="o">=</span> <span class="n">toeplitz</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">ols_resid</span><span class="p">)))</span> </pre></div> </div> </div> <p>so that our error covariance structure is actually rho**order which defines an autocorrelation structure</p> <div class="nbinput nblast docutils container"> <div class="prompt highlight-none notranslate"><div class="highlight"><pre><span></span>[8]: </pre></div> </div> <div class="input_area highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">sigma</span> <span class="o">=</span> <span class="n">rho</span> <span class="o">**</span> <span class="n">order</span> <span class="n">gls_model</span> <span class="o">=</span> <span class="n">sm</span><span class="o">.</span><span class="n">GLS</span><span class="p">(</span><span class="n">data</span><span class="o">.</span><span class="n">endog</span><span class="p">,</span> <span class="n">data</span><span class="o">.</span><span class="n">exog</span><span class="p">,</span> <span class="n">sigma</span><span class="o">=</span><span class="n">sigma</span><span class="p">)</span> <span class="n">gls_results</span> <span class="o">=</span> <span class="n">gls_model</span><span class="o">.</span><span class="n">fit</span><span class="p">()</span> </pre></div> </div> </div> <p>Of course, the exact rho in this instance is not known so it it might make more sense to use feasible gls, which currently only has experimental support.</p> <p>We can use the GLSAR model with one lag, to get to a similar result:</p> <div class="nbinput docutils container"> <div class="prompt highlight-none notranslate"><div class="highlight"><pre><span></span>[9]: </pre></div> </div> <div class="input_area highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">glsar_model</span> <span class="o">=</span> <span class="n">sm</span><span class="o">.</span><span class="n">GLSAR</span><span class="p">(</span><span class="n">data</span><span class="o">.</span><span class="n">endog</span><span class="p">,</span> <span class="n">data</span><span class="o">.</span><span class="n">exog</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="n">glsar_results</span> <span class="o">=</span> <span class="n">glsar_model</span><span class="o">.</span><span class="n">iterative_fit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">glsar_results</span><span class="o">.</span><span class="n">summary</span><span class="p">())</span> </pre></div> </div> </div> <div class="nboutput docutils container"> <div class="prompt empty docutils container"> </div> <div class="output_area docutils container"> <div class="highlight"><pre> GLSAR Regression Results ============================================================================== Dep. Variable: TOTEMP R-squared: 0.996 Model: GLSAR Adj. R-squared: 0.992 Method: Least Squares F-statistic: 295.2 Date: Tue, 08 Feb 2022 Prob (F-statistic): 6.09e-09 Time: 18:20:52 Log-Likelihood: -102.04 No. Observations: 15 AIC: 218.1 Df Residuals: 8 BIC: 223.0 Df Model: 6 Covariance Type: nonrobust ============================================================================== coef std err t P&gt;|t| [0.025 0.975] ------------------------------------------------------------------------------ const -3.468e+06 8.72e+05 -3.979 0.004 -5.48e+06 -1.46e+06 GNPDEFL 34.5568 84.734 0.408 0.694 -160.840 229.953 GNP -0.0343 0.033 -1.047 0.326 -0.110 0.041 UNEMP -1.9621 0.481 -4.083 0.004 -3.070 -0.854 ARMED -1.0020 0.211 -4.740 0.001 -1.489 -0.515 POP -0.0978 0.225 -0.435 0.675 -0.616 0.421 YEAR 1823.1829 445.829 4.089 0.003 795.100 2851.266 ============================================================================== Omnibus: 1.960 Durbin-Watson: 2.554 Prob(Omnibus): 0.375 Jarque-Bera (JB): 1.423 Skew: 0.713 Prob(JB): 0.491 Kurtosis: 2.508 Cond. No. 4.80e+09 ============================================================================== Notes: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. [2] The condition number is large, 4.8e+09. This might indicate that there are strong multicollinearity or other numerical problems. </pre></div></div> </div> <div class="nboutput nblast docutils container"> <div class="prompt empty docutils container"> </div> <div class="output_area stderr docutils container"> <div class="highlight"><pre> /opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/scipy/stats/_stats_py.py:1477: UserWarning: kurtosistest only valid for n&gt;=20 ... continuing anyway, n=15 warnings.warn("kurtosistest only valid for n&gt;=20 ... continuing " </pre></div></div> </div> <p>Comparing gls and glsar results, we see that there are some small differences in the parameter estimates and the resulting standard errors of the parameter estimate. This might be do to the numerical differences in the algorithm, e.g. the treatment of initial conditions, because of the small number of observations in the longley dataset.</p> <div class="nbinput docutils container"> <div class="prompt highlight-none notranslate"><div class="highlight"><pre><span></span>[10]: </pre></div> </div> <div class="input_area highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="n">gls_results</span><span class="o">.</span><span class="n">params</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">glsar_results</span><span class="o">.</span><span class="n">params</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">gls_results</span><span class="o">.</span><span class="n">bse</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">glsar_results</span><span class="o">.</span><span class="n">bse</span><span class="p">)</span> </pre></div> </div> </div> <div class="nboutput nblast docutils container"> <div class="prompt empty docutils container"> </div> <div class="output_area docutils container"> <div class="highlight"><pre> const -3.797855e+06 GNPDEFL -1.276565e+01 GNP -3.800132e-02 UNEMP -2.186949e+00 ARMED -1.151776e+00 POP -6.805356e-02 YEAR 1.993953e+03 dtype: float64 const -3.467961e+06 GNPDEFL 3.455678e+01 GNP -3.434101e-02 UNEMP -1.962144e+00 ARMED -1.001973e+00 POP -9.780460e-02 YEAR 1.823183e+03 dtype: float64 const 670688.699308 GNPDEFL 69.430807 GNP 0.026248 UNEMP 0.382393 ARMED 0.165253 POP 0.176428 YEAR 342.634628 dtype: float64 const 871584.051696 GNPDEFL 84.733715 GNP 0.032803 UNEMP 0.480545 ARMED 0.211384 POP 0.224774 YEAR 445.828748 dtype: float64 </pre></div></div> </div> </section> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="ols.html" title="Ordinary Least Squares" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> Ordinary Least Squares </span> </div> </a> <a href="quantile_regression.html" title="Quantile regression" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> Quantile regression </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Feb 08, 2022. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 4.4.0. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../../../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "31cd1ed13cfce2deab4497821cc5f132", "timestamp": "", "source": "github", "line_count": 1035, "max_line_length": 999, "avg_line_length": 39.65217391304348, "alnum_prop": 0.6068957115009747, "repo_name": "statsmodels/statsmodels.github.io", "id": "8c276f7c49cebef3b907015f558a08458ea3f9a9", "size": "41044", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.13.2/examples/notebooks/generated/gls.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
(function () { if (!window.localStorage) { document.body.textContent = "Upgrade to a better browser which includes localStorage" } })() // Model for all the favorite gifs in using browser's localStorage API // favorite Gifs will be stored by their id in the localStorage var favoriteGifsModel = { init: function () { this.localStorageCheck() }, getAllGifs: function () { return this.giphyStorage }, getGifById: function (id) { var result = this.giphyStorage.filter(function (gifId) { return gifId == id }) return result && result[0] }, addGifById: function (id) { this.giphyStorage.push(id) this.localStoragePersist() }, localStorageCheck: function () { if (!localStorage.giphyStorage) { this.localStorageInit() return } this.giphyStorage = JSON.parse(localStorage.giphyStorage) }, localStorageInit: function () { this.giphyStorage = [] this.localStoragePersist() }, localStoragePersist: function () { try { localStorage.setItem("giphyStorage", JSON.stringify(this.giphyStorage)) } catch (error) { console.error(error) } } } // giphyService to communicate with the giphyApi var giphyService = { init: function (key) { this.giphyKey = key || "dc6zaTOxFJmzC" this.baseUrl = "https://api.giphy.com" this.endpoints = { search: "/v1/gifs/search", gifById: "/v1/gifs/:gifId", trending: "/v1/gifs/trending", gifsById: "/v1/gifs" } }, search: function (q, limit, rating) { var params = { q: q, limit: limit, rating: rating || undefined, api_key: this.giphyKey } return $.ajax({ url: this.baseUrl + this.endpoints.search, data: params, }) }, trending: function (limit) { return $.ajax({ limit: limit, url: this.baseUrl + this.endpoints.trending, data: { api_key: this.giphyKey } }) }, searchById: function (id) { if (!id) { var id = "YyKPbc5OOTSQE" } return $.ajax({ url: this.baseUrl + this.endpoints.gifById.replace(":gifId", id), data: { api_key: this.giphyKey } }) }, getGifs: function (ids) { if (!ids) { console.log("no ids given for gifs") return } return $.ajax({ url: this.baseUrl + this.endpoints.gifsById, data: { api_key: this.giphyKey, ids: ids.join(",") } }) } } var giphyOctopus = { init: function () { favoriteGifsModel.init() giphyService.init() favortieView.init() }, getAllGifsData: function () { return giphyService.getGifs(favoriteGifsModel.getAllGifs()) }, addGifById: function (id) { favoriteGifsModel.addGifById(id) } } // gif result for showing all types of results about gifs var gifResultView = { init: function () { }, gifRender: function () { } } var favortieView = { init: function () { this.favortieView = $("#favortieView") var addGifBtn = $("#addGifBtn") addGifBtn.on("click", function (event) { var gifIdInput = $("#gifIdInput") giphyOctopus.addGifById(gifIdInput.val()) this.render() }.bind(this)) }, render: function () { var panel = this.favortieView giphyOctopus.getAllGifsData() .then(function (data) { }) } } giphyOctopus.init()
{ "content_hash": "d59bf04e883ad443de0491e0f90c0839", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 87, "avg_line_length": 20.174193548387098, "alnum_prop": 0.6514230892228974, "repo_name": "abdulhannanali/theGifTime", "id": "2702b16605bd789159e77e523fdb655d9fe46585", "size": "3254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/main.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "819" }, { "name": "JavaScript", "bytes": "3254" } ], "symlink_target": "" }
namespace mash.Gui.Forms { partial class MasterWindow { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.MenuStrip mainMenuStrip; System.Windows.Forms.StatusStrip globalStatusBar; mash.Gui.Properties.Settings settings1 = new mash.Gui.Properties.Settings(); System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MasterWindow)); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.debugToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.showLogWindowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.globalStatus = new System.Windows.Forms.ToolStripStatusLabel(); this.globalProgressBar = new System.Windows.Forms.ToolStripProgressBar(); this.shellBar = new System.Windows.Forms.ToolStrip(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.shellTabs = new System.Windows.Forms.TabControl(); mainMenuStrip = new System.Windows.Forms.MenuStrip(); globalStatusBar = new System.Windows.Forms.StatusStrip(); toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); mainMenuStrip.SuspendLayout(); globalStatusBar.SuspendLayout(); this.shellBar.SuspendLayout(); this.SuspendLayout(); // // mainMenuStrip // mainMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.debugToolStripMenuItem}); mainMenuStrip.Location = new System.Drawing.Point(0, 0); mainMenuStrip.Name = "mainMenuStrip"; mainMenuStrip.Size = new System.Drawing.Size(670, 24); mainMenuStrip.TabIndex = 0; mainMenuStrip.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "File"; // // debugToolStripMenuItem // this.debugToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.showLogWindowToolStripMenuItem}); this.debugToolStripMenuItem.Name = "debugToolStripMenuItem"; this.debugToolStripMenuItem.Size = new System.Drawing.Size(54, 20); this.debugToolStripMenuItem.Text = "Debug"; // // showLogWindowToolStripMenuItem // this.showLogWindowToolStripMenuItem.Name = "showLogWindowToolStripMenuItem"; this.showLogWindowToolStripMenuItem.Size = new System.Drawing.Size(181, 22); this.showLogWindowToolStripMenuItem.Text = "Toggle Log Window"; this.showLogWindowToolStripMenuItem.Click += new System.EventHandler(this.showLogWindowToolStripMenuItem_Click); // // globalStatusBar // globalStatusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.globalStatus, toolStripStatusLabel1, this.globalProgressBar}); globalStatusBar.Location = new System.Drawing.Point(0, 379); globalStatusBar.Name = "globalStatusBar"; globalStatusBar.Size = new System.Drawing.Size(670, 23); globalStatusBar.TabIndex = 1; globalStatusBar.Text = "Ready."; // // globalStatus // this.globalStatus.Name = "globalStatus"; this.globalStatus.Size = new System.Drawing.Size(42, 18); settings1.GlobalStatusLine = "Ready."; settings1.MasterFormTitle = "Mash"; settings1.SettingsKey = ""; settings1.StatusProgress = 0; this.globalStatus.Text = settings1.GlobalStatusLine; // // toolStripStatusLabel1 // toolStripStatusLabel1.Name = "toolStripStatusLabel1"; toolStripStatusLabel1.Size = new System.Drawing.Size(493, 18); toolStripStatusLabel1.Spring = true; // // globalProgressBar // this.globalProgressBar.Name = "globalProgressBar"; this.globalProgressBar.Size = new System.Drawing.Size(118, 17); this.globalProgressBar.Value = settings1.StatusProgress; // // shellBar // this.shellBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButton1}); this.shellBar.Location = new System.Drawing.Point(0, 24); this.shellBar.Name = "shellBar"; this.shellBar.Size = new System.Drawing.Size(670, 25); this.shellBar.TabIndex = 2; this.shellBar.Text = "toolStrip1"; // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image"))); this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(31, 22); this.toolStripButton1.Text = "add"; this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click); // // shellTabs // this.shellTabs.Dock = System.Windows.Forms.DockStyle.Fill; this.shellTabs.Location = new System.Drawing.Point(0, 49); this.shellTabs.Margin = new System.Windows.Forms.Padding(0); this.shellTabs.Name = "shellTabs"; this.shellTabs.SelectedIndex = 0; this.shellTabs.Size = new System.Drawing.Size(670, 330); this.shellTabs.TabIndex = 3; this.shellTabs.TabStop = false; this.shellTabs.MouseClick += new System.Windows.Forms.MouseEventHandler(this.shellTabs_MouseClick); // // MasterWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(670, 402); this.Controls.Add(this.shellTabs); this.Controls.Add(this.shellBar); this.Controls.Add(globalStatusBar); this.Controls.Add(mainMenuStrip); this.DataBindings.Add(new System.Windows.Forms.Binding("Text", settings1, "MasterFormTitle", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.KeyPreview = true; this.MainMenuStrip = mainMenuStrip; this.Name = "MasterWindow"; this.Text = settings1.MasterFormTitle; this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MasterForm_KeyDown); this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.MasterForm_KeyPress); mainMenuStrip.ResumeLayout(false); mainMenuStrip.PerformLayout(); globalStatusBar.ResumeLayout(false); globalStatusBar.PerformLayout(); this.shellBar.ResumeLayout(false); this.shellBar.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStrip shellBar; private System.Windows.Forms.TabControl shellTabs; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.ToolStripProgressBar globalProgressBar; private System.Windows.Forms.ToolStripStatusLabel globalStatus; private System.Windows.Forms.ToolStripMenuItem debugToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem showLogWindowToolStripMenuItem; } }
{ "content_hash": "a68419d36cea3bd3095851c850161d68", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 164, "avg_line_length": 42.537234042553195, "alnum_prop": 0.7260222583468801, "repo_name": "Manuzor/mash", "id": "0f47e9d0de5b78315ff8142125bdbd39cda2e391", "size": "7999", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/mash.Gui/Forms/MasterWindow.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "12555" }, { "name": "Shell", "bytes": "31" } ], "symlink_target": "" }
from random import randint import pytest from lcs.agents.acs2 import Configuration from lcs.agents.acs2 import Classifier, ClassifiersList from lcs.agents.racs.action_selection import exploit, choose_random_action, \ choose_latest_action, choose_action_from_knowledge_array, choose_action class TestActionSelection: @pytest.fixture def cfg(self): return Configuration( classifier_length=8, number_of_possible_actions=8) def test_should_return_all_possible_actions(self, cfg): # given all_actions = cfg.number_of_possible_actions population = ClassifiersList() actions = set() # when for _ in range(1000): act = choose_action(population, all_actions=all_actions, epsilon=1.0, biased_exploration_prob=0.0) actions.add(act) # then assert len(actions) == all_actions def test_should_exploit_when_no_effect_specified(self, cfg): # given a classifier not anticipating change cl = Classifier(action=1, cfg=cfg) population = ClassifiersList(*[cl]) # when action = exploit(population, cfg.number_of_possible_actions) # then random action is returned assert action is not None def test_should_exploit_with_single_classifier(self, cfg): # given cl = Classifier(action=2, effect='1###0###', reward=0.25, cfg=cfg) population = ClassifiersList(*[cl]) # when action = exploit(population, cfg.number_of_possible_actions) # then assert action == 2 def test_should_exploit_using_majority_voting(self, cfg): # given cl1 = Classifier(action=1, effect='1###0###', reward=0.1, quality=0.7, numerosity=9, cfg=cfg) cl2 = Classifier(action=2, effect='1###0###', reward=0.1, quality=0.7, numerosity=10, cfg=cfg) population = ClassifiersList(*[cl1, cl2]) # when action = exploit(population, cfg.number_of_possible_actions) # then assert action == 2 def test_should_return_random_action(self, cfg): # given all_actions = cfg.number_of_possible_actions random_actions = [] # when for _ in range(0, 500): random_actions.append(choose_random_action(all_actions)) min_action = min(random_actions) max_action = max(random_actions) # then assert min_action == 0 assert max_action == 7 def test_should_return_latest_action(self, cfg): # given all_actions = cfg.number_of_possible_actions population = ClassifiersList() c0 = Classifier(action=0, cfg=cfg) c0.talp = 1 # when population.append(c0) # Should return first action with no classifiers assert 1 == choose_latest_action(population, all_actions) # Add rest of classifiers population.append(Classifier(action=3, cfg=cfg)) population.append(Classifier(action=7, cfg=cfg)) population.append(Classifier(action=5, cfg=cfg)) population.append(Classifier(action=1, cfg=cfg)) population.append(Classifier(action=4, cfg=cfg)) population.append(Classifier(action=2, cfg=cfg)) population.append(Classifier(action=6, cfg=cfg)) # Assign each classifier random talp from certain range for cl in population: cl.talp = randint(70, 100) # But third classifier (action 7) will be the executed long time ago population[2].talp = randint(10, 20) # then assert choose_latest_action(population, all_actions) == 7 def test_should_return_worst_quality_action(self, cfg): # given all_actions = cfg.number_of_possible_actions population = ClassifiersList() c0 = Classifier(action=0, cfg=cfg) population.append(c0) # Should return C1 (because it's first not mentioned) assert choose_action_from_knowledge_array(population, all_actions) == 1 # Add rest of classifiers c1 = Classifier(action=1, numerosity=31, quality=0.72, cfg=cfg) c2 = Classifier(action=2, numerosity=2, quality=0.6, cfg=cfg) c3 = Classifier(action=3, numerosity=2, quality=0.63, cfg=cfg) c4 = Classifier(action=4, numerosity=7, quality=0.75, cfg=cfg) c5 = Classifier(action=5, numerosity=1, quality=0.63, cfg=cfg) c6 = Classifier(action=6, numerosity=6, quality=0.52, cfg=cfg) c7 = Classifier(action=7, numerosity=10, quality=0.36, cfg=cfg) population += ClassifiersList(*[c1, c2, c3, c4, c5, c6, c7]) # then # Classifier C7 should be the worst here assert choose_action_from_knowledge_array(population, all_actions) == 7
{ "content_hash": "b2aa3e6881970ef39f36741dd0249cc9", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 79, "avg_line_length": 34.321917808219176, "alnum_prop": 0.6038714827379764, "repo_name": "ParrotPrediction/pyalcs", "id": "7065fb62e99654692604f3fc42b07daeb8a05a93", "size": "5011", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/lcs/agents/racs/test_action_selection.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "119" }, { "name": "Makefile", "bytes": "82" }, { "name": "Python", "bytes": "502854" } ], "symlink_target": "" }
from flask import request from werkzeug.exceptions import NotFound from indico.core.db import db from indico.modules.events.models.series import EventSeries from indico.modules.events.series.schemas import EventSeriesSchema, EventSeriesUpdateSchema from indico.util.i18n import _ from indico.web.args import use_rh_args from indico.web.rh import RH class RHEventSeries(RH): def _process_args(self): self.series = None if 'series_id' in request.view_args: self.series = EventSeries.get(request.view_args['series_id']) if self.series is None: raise NotFound(_('A series with this ID does not exist.')) def _process_GET(self): return EventSeriesSchema().dump(self.series) @use_rh_args(EventSeriesUpdateSchema, partial=True) def _process_PATCH(self, changes): self.series.populate_from_dict(changes) return '', 204 @use_rh_args(EventSeriesUpdateSchema) def _process_POST(self, data): series = EventSeries() series.populate_from_dict(data) return '', 204 def _process_DELETE(self): db.session.delete(self.series) return '', 204
{ "content_hash": "54161e8a798b8edcc6d2605aa28cca59", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 91, "avg_line_length": 32.72222222222222, "alnum_prop": 0.6842105263157895, "repo_name": "indico/indico", "id": "9dacdb79d8297224e20444f90f9241b21d77af24", "size": "1392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "indico/modules/events/series/controllers.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33289" }, { "name": "HTML", "bytes": "1420471" }, { "name": "JavaScript", "bytes": "2362355" }, { "name": "Mako", "bytes": "1527" }, { "name": "Python", "bytes": "5550085" }, { "name": "SCSS", "bytes": "486043" }, { "name": "Shell", "bytes": "3877" }, { "name": "TeX", "bytes": "23435" }, { "name": "XSLT", "bytes": "1504" } ], "symlink_target": "" }
#if defined(USE_TI_UITEXTWIDGET) || defined(USE_TI_UITEXTAREA) || defined(USE_TI_UITEXTFIELD) #import "TiUITextWidgetProxy.h" #import "TiUITextWidget.h" #import "TiUtils.h" @implementation TiUITextWidgetProxy @synthesize suppressFocusEvents; DEFINE_DEF_BOOL_PROP(suppressReturn,YES); - (void)windowWillClose { if([self viewInitialized]) { [[self view] resignFirstResponder]; } [(TiViewProxy *)[keyboardTiView proxy] windowWillClose]; for (TiViewProxy * thisToolBarItem in keyboardToolbarItems) { [thisToolBarItem windowWillClose]; [self forgetProxy:thisToolBarItem]; } [super windowWillClose]; } - (void) dealloc { [keyboardTiView removeFromSuperview]; [keyboardUIToolbar removeFromSuperview]; RELEASE_TO_NIL(keyboardTiView); for (TiProxy* proxy in keyboardToolbarItems) { [self forgetProxy:proxy]; } RELEASE_TO_NIL(keyboardToolbarItems); RELEASE_TO_NIL(keyboardUIToolbar); [super dealloc]; } -(NSString*)apiName { return @"Ti.UI.TextWidget"; } -(NSNumber*)hasText:(id)unused { if ([self viewAttached]) { __block BOOL viewHasText = NO; TiThreadPerformOnMainThread(^{ viewHasText = [(TiUITextWidget*)[self view] hasText]; }, YES); return [NSNumber numberWithBool:viewHasText]; } else { NSString *value = [self valueForKey:@"value"]; BOOL viewHasText = value!=nil && [value length] > 0; return [NSNumber numberWithBool:viewHasText]; } } -(void)blur:(id)args { ENSURE_UI_THREAD_1_ARG(args) if ([self viewAttached]) { [[self view] resignFirstResponder]; } } -(void)focus:(id)args { ENSURE_UI_THREAD_1_ARG(args) if ([self viewAttached]) { [[self view] becomeFirstResponder]; } } -(BOOL)focused:(id)unused { BOOL result=NO; if ([self viewAttached]) { result = [(TiUITextWidget*)[self view] isFirstResponder]; } return result; } -(void)noteValueChange:(NSString *)newValue { if (![[self valueForKey:@"value"] isEqual:newValue]) { [self replaceValue:newValue forKey:@"value" notification:NO]; [self contentsWillChange]; [self fireEvent:@"change" withObject:[NSDictionary dictionaryWithObject:newValue forKey:@"value"]]; TiThreadPerformOnMainThread(^{ //Make sure the text widget is in view when editing. [(TiUITextWidget*)[self view] updateKeyboardStatus]; }, NO); } } #pragma mark Toolbar - (CGFloat) keyboardAccessoryHeight { CGFloat result = MAX(keyboardAccessoryHeight,40); if ([[keyboardTiView proxy] respondsToSelector:@selector(verifyHeight:)]) { result = [(TiViewProxy<LayoutAutosizing>*)[keyboardTiView proxy] verifyHeight:result]; } return result; } -(void)setKeyboardToolbarHeight:(id)value { ENSURE_UI_THREAD_1_ARG(value); keyboardAccessoryHeight = [TiUtils floatValue:value]; //TODO: If we're focused or the toolbar is otherwise onscreen, we need to let the root view controller know and update. } -(void)setKeyboardToolbarColor:(id)value { //Because views aren't lock-protected, ANY and all references, even checking if non-nil, should be done in the main thread. ENSURE_UI_THREAD_1_ARG(value); [self replaceValue:value forKey:@"keyboardToolbarColor" notification:YES]; if(keyboardUIToolbar != nil){ //It already exists, update it. UIColor * newColor = [[TiUtils colorValue:value] _color]; if ([TiUtils isIOS7OrGreater]) { [keyboardUIToolbar performSelector:@selector(setBarTintColor:) withObject:newColor]; } else { [keyboardUIToolbar setTintColor:newColor]; } } } -(void)updateUIToolbar { NSMutableArray *items = [NSMutableArray arrayWithCapacity:[keyboardToolbarItems count]]; for (TiViewProxy *proxy in keyboardToolbarItems) { if ([proxy supportsNavBarPositioning]) { UIBarButtonItem* button = [proxy barButtonItem]; [items addObject:button]; } } [keyboardUIToolbar setItems:items animated:YES]; } -(UIToolbar *)keyboardUIToolbar { if(keyboardUIToolbar == nil) { keyboardUIToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320,[self keyboardAccessoryHeight])]; UIColor * newColor = [[TiUtils colorValue:[self valueForKey:@"keyboardToolbarColor"]] _color]; if(newColor != nil){ if ([TiUtils isIOS7OrGreater]) { [keyboardUIToolbar performSelector:@selector(setBarTintColor:) withObject:newColor]; } else { [keyboardUIToolbar setTintColor:newColor]; } } [self updateUIToolbar]; } return keyboardUIToolbar; } -(void)setKeyboardToolbar:(id)value { // TODO: The entire codebase needs to be evaluated for the following: // // - Any property setter which potentially takes an array of proxies MUST ALWAYS have its // content evaluated to protect them. This is INCREDIBLY CRITICAL and almost certainly a major // source of memory bugs in refillbyscan iOS!!! // // - Any property setter which is active on the main thread only MAY NOT protect their object // correctly or in time (see the comment in -[KrollObject noteKeylessKrollObject:]). // // This may have to be done as part of TIMOB-6990 (convert KrollContext to serialized GCD) if ([value isKindOfClass:[NSArray class]]) { for (id item in value) { ENSURE_TYPE(item, TiProxy); [self rememberProxy:item]; } } //Because views aren't lock-protected, ANY and all references, even checking if non-nil, should be done in the main thread. // TODO: ENSURE_UI_THREAD needs to be deprecated in favor of more effective and concicse mechanisms // which use the main thread only when necessary to reduce latency. ENSURE_UI_THREAD_1_ARG(value); [self replaceValue:value forKey:@"keyboardToolbar" notification:YES]; if (value == nil) { //TODO: Should we remove these gracefully? [keyboardTiView removeFromSuperview]; [keyboardUIToolbar removeFromSuperview]; for (TiProxy* proxy in keyboardToolbarItems) { [self forgetProxy:proxy]; } RELEASE_TO_NIL(keyboardTiView); RELEASE_TO_NIL(keyboardToolbarItems); [keyboardUIToolbar setItems:nil]; return; } if ([value isKindOfClass:[NSArray class]]) { //TODO: Should we remove these gracefully? [keyboardTiView removeFromSuperview]; RELEASE_TO_NIL(keyboardTiView); // TODO: Check for proxies [keyboardToolbarItems autorelease]; for (TiProxy* proxy in keyboardToolbarItems) { [self forgetProxy:proxy]; } keyboardToolbarItems = [value copy]; if(keyboardUIToolbar != nil) { [self updateUIToolbar]; } //TODO: If we have focus while this happens, we need to signal an update. return; } if ([value isKindOfClass:[TiViewProxy class]]) { TiUIView * valueView = [(TiViewProxy *)value view]; if (valueView == keyboardTiView) {//Nothing to do here. return; } //TODO: Should we remove these gracefully? [keyboardTiView removeFromSuperview]; [keyboardUIToolbar removeFromSuperview]; RELEASE_TO_NIL(keyboardTiView); for (TiProxy* proxy in keyboardToolbarItems) { [self forgetProxy:proxy]; } RELEASE_TO_NIL(keyboardToolbarItems); [keyboardUIToolbar setItems:nil]; keyboardTiView = [valueView retain]; //TODO: If we have focus while this happens, we need to signal an update. } } - (UIView *)keyboardAccessoryView; { if(keyboardTiView != nil){ return keyboardTiView; } if([keyboardToolbarItems count] > 0){ return [self keyboardUIToolbar]; } return nil; } -(TiDimension)defaultAutoWidthBehavior:(id)unused { return TiDimensionAutoSize; } -(TiDimension)defaultAutoHeightBehavior:(id)unused { return TiDimensionAutoSize; } -(void)setSelection:(id)arg withObject:(id)property { NSInteger start = [TiUtils intValue:arg def: -1]; NSInteger end = [TiUtils intValue:property def:-1]; NSString* curValue = [TiUtils stringValue:[self valueForKey:@"value"]]; NSInteger textLength = [curValue length]; if ((start < 0) || (start > textLength) || (end < 0) || (end > textLength)) { DebugLog(@"Invalid range for text selection. Ignoring."); return; } TiThreadPerformOnMainThread(^{[(TiUITextWidget*)[self view] setSelectionFrom:arg to:property];}, NO); } USE_VIEW_FOR_CONTENT_HEIGHT USE_VIEW_FOR_CONTENT_WIDTH @end #endif
{ "content_hash": "e34fc6f58f5a8f05acbac11e2bce80fb", "timestamp": "", "source": "github", "line_count": 295, "max_line_length": 124, "avg_line_length": 27.938983050847458, "alnum_prop": 0.7034700315457413, "repo_name": "jgirisha/RBS", "id": "bdf78ff742c8118fc8410b6f8bcc83b32e140a7d", "size": "8564", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/iphone/Classes/TiUITextWidgetProxy.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "152497" }, { "name": "C++", "bytes": "51991" }, { "name": "CSS", "bytes": "49184" }, { "name": "D", "bytes": "700833" }, { "name": "JavaScript", "bytes": "2420256" }, { "name": "Objective-C", "bytes": "3583153" }, { "name": "Objective-C++", "bytes": "18015" }, { "name": "Perl", "bytes": "7063" }, { "name": "Python", "bytes": "5251" }, { "name": "Shell", "bytes": "1237" } ], "symlink_target": "" }
""" Sponge Knowledge Base Used for testing a Remote API server and clients. """ from java.util.concurrent.atomic import AtomicBoolean from org.apache.commons.io import IOUtils from java.time import LocalDateTime from java.nio.charset import StandardCharsets def onInit(): # Variables for assertions only. sponge.setVariable("actionCalled", AtomicBoolean(False)) sponge.setVariable("eventSent", AtomicBoolean(False)) sponge.setVariable("reloaded", AtomicBoolean(False)) # Variables that simulate a data model. sponge.setVariable("actuator1", "A") sponge.setVariable("actuator2", False) sponge.setVariable("actuator3", 1) sponge.setVariable("actuator4", 1) sponge.setVariable("actuator5", "X") sponge.addCategories(CategoryMeta("category1").withLabel("Category 1").withDescription("Category 1 description"), CategoryMeta("category2").withLabel("Category 2").withDescription("Category 2 description")) def onBeforeLoad(): sponge.addType("Person", lambda: RecordType().withFields([ StringType("firstName").withLabel("First name"), StringType("surname").withLabel("Surname") ])) sponge.addType("Citizen", lambda: RecordType().withBaseType(sponge.getType("Person")).withFields([ StringType("country").withLabel("Country") ])) def onLoad(): sponge.kb.version = 2 class UpperCase(Action): def onConfigure(self): self.withLabel("Convert to upper case").withDescription("Converts a string to upper case.").withCategory("category1").withVersion(2) self.withArg( StringType("text").withMaxLength(256).withLabel("Text to upper case").withDescription("The text that will be converted to upper case.") ).withResult(StringType().withLabel("Upper case text")) def onCall(self, text): sponge.getVariable("actionCalled").set(True) return text.upper() class LowerCase(Action): def onConfigure(self): self.withLabel("Convert to lower case").withDescription("Converts a string to lower case.").withCategory("category1") self.withArg(StringType("text").withLabel("A text that will be changed to lower case")) self.withResult(StringType().withLabel("Lower case text")) def onCall(self, text): return text.lower() class EchoImage(Action): def onConfigure(self): self.withLabel("Echo an image").withCategory("category2") self.withArg(BinaryType("image").withMimeType("image/png").withLabel("Image")) self.withResult(BinaryType().withMimeType("image/png").withLabel("Image echo")) def onCall(self, image): return image class ListValues(Action): def onConfigure(self): self.withFeatures({"visible":False}).withNoArgs().withResult(ListType(StringType())) def onCall(self): return ["value1", "value2", "value3"] class ProvideByAction(Action): def onConfigure(self): self.withLabel("Action with provided argument").withCategory("category2") self.withArg(StringType("value").withLabel("Value").withProvided(ProvidedMeta().withValueSet())) self.withResult(StringType().withLabel("Same value")) def onCall(self, value): return value def onProvideArgs(self, context): if "value" in context.provide: context.provided["value"] = ProvidedValue().withValueSet(sponge.call("ListValues")) class PrivateAction(Action): def onCall(self, args): return None class NoMetadataAction(Action): def onCall(self, args): return None class KnowledgeBaseErrorAction(Action): def onConfigure(self): self.withLabel("Knowledge base error action").withNoArgs().withNoResult() def onCall(self): raise Exception("Knowledge base exception") class LangErrorAction(Action): def onConfigure(self): self.withLabel("Language error action").withNoArgs().withNoResult() def onCall(self): return throws_error class ComplexObjectAction(Action): def onConfigure(self): self.withArg(ObjectType("arg").withClassName("org.openksavi.sponge.remoteapi.test.base.CompoundComplexObject")) self.withResult(ObjectType().withClassName("org.openksavi.sponge.remoteapi.test.base.CompoundComplexObject")) def onCall(self, arg): arg.id += 1 return arg class ComplexObjectListAction(Action): def onConfigure(self): self.withArg(ListType("arg").withElement( ObjectType().withClassName("org.openksavi.sponge.remoteapi.test.base.CompoundComplexObject") ).withLabel("Text to upper case")) self.withResult(ListType().withElement( ObjectType().withClassName("org.openksavi.sponge.remoteapi.test.base.CompoundComplexObject") )) def onCall(self, arg): arg[0].id += 1 return arg class ComplexObjectHierarchyAction(Action): def onConfigure(self): self.withArgs([ StringType("stringArg"), AnyType("anyArg"), ListType("stringListArg", StringType()), ListType("decimalListArg", ObjectType().withClassName("java.math.BigDecimal")), ObjectType("stringArrayArg").withClassName("java.lang.String[]"), MapType("mapArg", StringType(), ObjectType().withClassName("org.openksavi.sponge.remoteapi.test.base.CompoundComplexObject")) ]).withResult(ListType(AnyType())) def onCall(self, stringArg, anyArg, stringListArg, decimalListArg, stringArrayArg, mapArg): self.logger.info("Action {} called: {}, {}, {}, {}, {}, {}", self.meta.name, stringArg, anyArg, stringListArg, decimalListArg, stringArrayArg, mapArg) return [stringArg, anyArg, stringListArg, decimalListArg, stringArrayArg, mapArg] def createTestObjectType(name = None): return ObjectType(name).withClassName("org.openksavi.sponge.examples.CustomObject").withCompanionType(RecordType().withFields([ IntegerType("id").withLabel("ID"), StringType("name").withLabel("Name") ])) class ObjectTypeWithCompanionTypeAction(Action): def onConfigure(self): self.withLabel("Object type with companion type").withArgs([ createTestObjectType("customObject"), ]).withResult(createTestObjectType()) def onCall(self, customObject): if customObject.name: customObject.name = customObject.name.upper() return customObject class SetActuator(Action): def onConfigure(self): self.withLabel("Set actuator").withDescription("Sets the actuator state.") self.withArgs([ StringType("actuator1").withLabel("Actuator 1 state").withProvided(ProvidedMeta().withValue().withValueSet()), BooleanType("actuator2").withLabel("Actuator 2 state").withProvided(ProvidedMeta().withValue()), IntegerType("actuator3").withNullable().withReadOnly().withLabel("Actuator 3 state").withProvided(ProvidedMeta().withValue()), IntegerType("actuator4").withLabel("Actuator 4 state") ]).withNoResult() def onCall(self, actuator1, actuator2, actuator3, actuator4): sponge.setVariable("actuator1", actuator1) sponge.setVariable("actuator2", actuator2) # actuator3 is read only in this action. sponge.setVariable("actuator4", actuator4) def onProvideArgs(self, context): if "actuator1" in context.provide: context.provided["actuator1"] = ProvidedValue().withValue(sponge.getVariable("actuator1", None)).withValueSet(["A", "B", "C"]) if "actuator2" in context.provide: context.provided["actuator2"] = ProvidedValue().withValue(sponge.getVariable("actuator2", None)) if "actuator3" in context.provide: context.provided["actuator3"] = ProvidedValue().withValue(sponge.getVariable("actuator3", None)) class SetActuatorNotLimitedValueSet(Action): def onConfigure(self): self.withLabel("Set actuator not limited value set") self.withArgs([ StringType("actuator1").withLabel("Actuator 1 state").withProvided(ProvidedMeta().withValue().withValueSet(ValueSetMeta().withNotLimited())), ]).withNoResult() def onCall(self, actuator1): pass def onProvideArgs(self, context): if "actuator1" in context.provide: context.provided["actuator1"] = ProvidedValue().withValue(sponge.getVariable("actuator1", None)).withValueSet(["A", "B", "C"]) class SetActuatorDepends(Action): def onConfigure(self): self.withLabel("Set actuator with depends").withDescription("Sets the actuator state.") self.withArgs([ StringType("actuator1").withLabel("Actuator 1 state").withProvided(ProvidedMeta().withValue().withValueSet()), BooleanType("actuator2").withLabel("Actuator 2 state").withProvided(ProvidedMeta().withValue()), IntegerType("actuator3").withLabel("Actuator 3 state").withProvided(ProvidedMeta().withValue()), IntegerType("actuator4").withLabel("Actuator 4 state"), StringType("actuator5").withLabel("Actuator 5 state").withProvided(ProvidedMeta().withValue().withValueSet().withDependency("actuator1")), ]).withNoResult() def onCall(self, actuator1, actuator2, actuator3, actuator4, actuator5): sponge.setVariable("actuator1", actuator1) sponge.setVariable("actuator2", actuator2) sponge.setVariable("actuator3", actuator3) sponge.setVariable("actuator4", actuator4) sponge.setVariable("actuator5", actuator5) def onProvideArgs(self, context): if "actuator1" in context.provide: context.provided["actuator1"] = ProvidedValue().withValue(sponge.getVariable("actuator1", None)).withAnnotatedValueSet( [AnnotatedValue("A").withValueLabel("Value A"), AnnotatedValue("B").withValueLabel("Value B"), AnnotatedValue("C").withValueLabel("Value C")]) if "actuator2" in context.provide: context.provided["actuator2"] = ProvidedValue().withValue(sponge.getVariable("actuator2", None)) if "actuator3" in context.provide: context.provided["actuator3"] = ProvidedValue().withValue(sponge.getVariable("actuator3", None)) if "actuator5" in context.provide: context.provided["actuator5"] = ProvidedValue().withValue(sponge.getVariable("actuator5", None)).withValueSet([ "X", "Y", "Z", context.current["actuator1"]]) class SetActuatorSubmit(Action): def onConfigure(self): self.withLabel("Set actuator with submit").withDescription("Sets the actuator state with submit.") self.withArgs([ StringType("actuator1").withLabel("Actuator 1 state").withProvided(ProvidedMeta().withValue().withValueSet().withSubmittable( SubmittableMeta().withInfluence("actuator2"))), BooleanType("actuator2").withLabel("Actuator 2 state").withProvided(ProvidedMeta().withValue()) ]).withNoResult() def onCall(self, actuator1, actuator2): sponge.setVariable("actuator1", actuator1) sponge.setVariable("actuator2", actuator2) def onProvideArgs(self, context): if "actuator1" in context.submit: # Set an actuator value with submit. sponge.setVariable("actuator1", context.current["actuator1"]) # The actuator1 influence on actuator2 could be implemented here. if "actuator1" in context.provide: context.provided["actuator1"] = ProvidedValue().withValue(sponge.getVariable("actuator1", None)).withValueSet(["A", "B", "C"]) if "actuator2" in context.provide: context.provided["actuator2"] = ProvidedValue().withValue(sponge.getVariable("actuator2", None)) class AnnotatedTypeAction(Action): def onConfigure(self): self.withArg(BooleanType("arg1").withAnnotated().withLabel("Argument 1")) self.withResult(StringType().withAnnotated().withLabel("Annotated result")) def onCall(self, arg1): features = {"feature1":"value1"} features.update(arg1.features) return AnnotatedValue("RESULT").withValueLabel("Result value").withValueDescription("Result value description").withFeatures( features).withTypeLabel("Result type").withTypeDescription("Result type description") class DynamicResultAction(Action): def onConfigure(self): self.withArg(StringType("type")).withResult(DynamicType()) def onCall(self, type): if type == "string": return DynamicValue("text", StringType()) elif type == "boolean": return DynamicValue(True, BooleanType()) else: return None class TypeResultAction(Action): def onConfigure(self): self.withArgs([ StringType("type"), TypeType("arg").withNullable() ]).withResult(TypeType()) def onCall(self, type, arg): if type == "string": return StringType() elif type == "boolean": return BooleanType() elif type == "arg": return arg else: return None class DateTimeAction(Action): def onConfigure(self): self.withArgs([ DateTimeType("dateTime").withDateTime().withMinValue(LocalDateTime.of(2020, 1, 1, 0, 0)).withMaxValue(LocalDateTime.of(2030, 1, 1, 0, 0)), DateTimeType("dateTimeZone").withDateTimeZone(), DateTimeType("date").withDate().withFormat("yyyy-MM-dd"), DateTimeType("time").withTime().withFormat("HH:mm:ss"), DateTimeType("instant").withInstant() ]).withResult(ListType(DynamicType())) def onCall(self, dateTime, dateTimeZone, date, time, instant): return [DynamicValue(dateTime, self.meta.args[0]), DynamicValue(dateTimeZone, self.meta.args[1]), DynamicValue(date, self.meta.args[2]), DynamicValue(time, self.meta.args[3]), DynamicValue(instant, self.meta.args[4])] def createBookType(name): return RecordType(name, [ IntegerType("id").withNullable().withLabel("Identifier"), StringType("author").withLabel("Author"), StringType("title").withLabel("Title"), StringType("comment").withNullable().withLabel("Comment") ]) class RecordAsResultAction(Action): def onConfigure(self): self.withArg(IntegerType("bookId")).withResult(createBookType("book").withNullable()) def onCall(self, bookId): return {"id":bookId, "author":"James Joyce", "title":"Ulysses", "comment":None} class RecordAsArgAction(Action): def onConfigure(self): self.withArg(createBookType("book")).withResult(createBookType("book")) def onCall(self, book): return book class NestedRecordAsArgAction(Action): def onConfigure(self): self.withArg( RecordType("book").withLabel("Book").withFields([ IntegerType("id").withNullable().withLabel("Identifier"), RecordType("author").withLabel("Author").withFields([ IntegerType("id").withNullable().withLabel("Identifier"), StringType("firstName").withLabel("First name"), StringType("surname").withLabel("Surname") ]), StringType("title").withLabel("Title"), ])).withResult(StringType()) def onCall(self, book): return "{} {} - {}".format(book["author"]["firstName"], book["author"]["surname"], book["title"]) class OutputStreamResultAction(Action): def onConfigure(self): self.withNoArgs().withResult(OutputStreamType()) def onCall(self): return OutputStreamValue(lambda output: IOUtils.write("Sample text file\n", output, "UTF-8"))\ .withContentType("text/plain; charset=\"UTF-8\"").withFilename("sample file.txt").withHeaders({}) class RegisteredTypeArgAction(Action): def onConfigure(self): self.withLabel("Registered type argument action").withArg(sponge.getType("Person").withName("person")).withResult(StringType()) def onCall(self, person): return person["surname"] class InheritedRegisteredTypeArgAction(Action): def onConfigure(self): self.withLabel("Inherited, registered type argument action").withArg(sponge.getType("Citizen").withName("citizen")).withResult(StringType()) def onCall(self, citizen): return citizen["firstName"] + " comes from " + citizen["country"] class FruitsElementValueSetAction(Action): def onConfigure(self): self.withLabel("Fruits action with argument element value set") self.withArg(ListType("fruits", StringType()).withLabel("Fruits").withUnique().withProvided(ProvidedMeta().withElementValueSet())).withResult(IntegerType()) def onCall(self, fruits): return len(fruits) def onProvideArgs(self, context): if "fruits" in context.provide: context.provided["fruits"] = ProvidedValue().withAnnotatedElementValueSet([ AnnotatedValue("apple").withValueLabel("Apple"), AnnotatedValue("banana").withValueLabel("Banana"), AnnotatedValue("lemon").withValueLabel("Lemon") ]) class ViewFruitsPaging(Action): def onConfigure(self): self.withLabel("Fruits with value paging").withArgs([ ListType("fruits", StringType()).withLabel("Fruits").withAnnotated().withProvided(ProvidedMeta().withValue()).withFeatures({ "pageable":True}) ]).withNonCallable() def onInit(self): self.fruits = ["apple", "orange", "lemon", "banana", "cherry", "grapes", "peach", "mango", "grapefruit", "kiwi", "plum"] def onProvideArgs(self, context): if "fruits" in context.provide: offset = context.getArgFeature("fruits", "offset") limit = context.getArgFeature("fruits", "limit") context.provided["fruits"] = ProvidedValue().withValue(AnnotatedValue(self.fruits[offset:(offset + limit)]).withFeatures( {"offset":offset, "limit":limit, "count":len(self.fruits)})) class AnnotatedWithDefaultValue(Action): def onConfigure(self): self.withLabel("Action with annotated arg with default").withArgs([ StringType("annotated").withLabel("Annotated").withAnnotated().withDefaultValue(AnnotatedValue("Value")) ]).withResult(StringType()) def onCall(self, annotated): return annotated.value class ProvidedWithCurrentAndLazyUpdate(Action): def onConfigure(self): self.withLabel("Provided with current and lazy update").withArgs([ StringType("arg").withLabel("Arg").withAnnotated().withProvided( ProvidedMeta().withValue().withOverwrite().withCurrent().withLazyUpdate()), ]).withNonCallable() def onProvideArgs(self, context): if "arg" in context.provide: context.provided["arg"] = ProvidedValue().withValue(AnnotatedValue(context.current["arg"].value)) class ProvidedWithOptional(Action): def onConfigure(self): self.withLabel("Provided with optional").withArgs([ StringType("arg").withLabel("Arg").withProvided(ProvidedMeta().withValue().withOptionalMode()), ]).withNonCallable() def onProvideArgs(self, context): context.provided["arg"] = ProvidedValue().withValue("VALUE") class IsActionActiveAction(Action): def onConfigure(self): self.withLabel("Action with an activity status").withArgs([ StringType("arg").withLabel("Arg"), ]).withNoResult().withActivatable() def onIsActive(self, context): return context.value is not None def onCall(self, arg): pass class SubActionsAction(Action): def onConfigure(self): self.withLabel("Sub-actions action") self.withArgs([ StringType("arg1"), ListType("arg2", StringType()).withDefaultValue(["a", "b", "c"]) ]).withNonCallable().withFeatures({"contextActions":[ SubAction("SubAction1").withLabel("Sub-action 1/1").withArg("target1", "arg1").withResult("arg1"), SubAction("SubAction1").withLabel("Sub-action 1/2 (no result substitution)").withArg("target1", "arg1"), SubAction("SubAction1").withLabel("Sub-action 1/3 (no arg and result substitution)"), SubAction("SubAction2").withLabel("Sub-action 2/1 (arg by value)").withArg("target1", "arg2").withResult("arg2"), ]}) class SubAction1(Action): def onConfigure(self): self.withLabel("SubAction 1") self.withArgs([StringType("target1")]).withResult(StringType()) def onCall(self, arg1): return upper(arg1) class SubAction2(Action): def onConfigure(self): self.withLabel("SubAction 2") self.withArgs([ListType("target1")]).withResult(ListType()) def onCall(self, target1): return target1 + ["z"] class InputStreamArgAction(Action): def onConfigure(self): self.withLabel("Input stream arg").withArgs([ StringType("value"), InputStreamType("fileStream"), InputStreamType("fileStream2") ]).withResult(StringType()) def onCall(self, value, fileStream, fileStream2): uploaded = "Uploaded" uploadDir = "{}/upload/".format(sponge.home) # Single file. if fileStream.hasNext(): IOUtils.readLines(fileStream.inputStream, StandardCharsets.UTF_8) uploaded += " " + fileStream.filename # Multiple files. while fileStream2.hasNext(): fs2 = fileStream2.next() IOUtils.readLines(fs2.inputStream, StandardCharsets.UTF_8) uploaded += " " + fs2.filename return uploaded class RemoteApiIsActionPublic(Action): def onCall(self, actionAdapter): return not (actionAdapter.meta.name.startswith("Private") or actionAdapter.meta.name.startswith("RemoteApi")) class RemoteApiIsEventPublic(Action): def onCall(self, eventName): return True class Alarm(Trigger): def onConfigure(self): self.withEvent("alarm") def onRun(self, event): self.logger.debug("Received event: {}", event) sponge.getVariable("eventSent").set(True) def onAfterReload(): sponge.getVariable("reloaded").set(True)
{ "content_hash": "09984ee839f19b2ba1e75c6b27677274", "timestamp": "", "source": "github", "line_count": 471, "max_line_length": 164, "avg_line_length": 47.388535031847134, "alnum_prop": 0.665905017921147, "repo_name": "softelnet/sponge", "id": "6521c33fbe1f4c80c58e15ee705ce7e589c998e8", "size": "22320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sponge-remote-api-integration-tests/examples/remote-api-server/remote_api.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "482" }, { "name": "Dockerfile", "bytes": "2389" }, { "name": "Groovy", "bytes": "70914" }, { "name": "HTML", "bytes": "6759" }, { "name": "Java", "bytes": "3300560" }, { "name": "JavaScript", "bytes": "70716" }, { "name": "Kotlin", "bytes": "113542" }, { "name": "Mustache", "bytes": "38" }, { "name": "Python", "bytes": "426240" }, { "name": "Ruby", "bytes": "65491" }, { "name": "SCSS", "bytes": "6217" }, { "name": "Shell", "bytes": "1388" } ], "symlink_target": "" }
package com.mb3364.twitch.api.resources; import com.mb3364.http.RequestParams; import com.mb3364.twitch.api.auth.Scopes; import com.mb3364.twitch.api.handlers.VideoResponseHandler; import com.mb3364.twitch.api.handlers.VideosResponseHandler; import com.mb3364.twitch.api.models.Video; import com.mb3364.twitch.api.models.Videos; import java.io.IOException; import java.util.List; import java.util.Map; /** * The {@link VideosResource} provides the functionality * to access the <code>/videos</code> endpoints of the Twitch API. * * @author Matthew Bell */ public class VideosResource extends AbstractResource { /** * Construct the resource using the Twitch API base URL and specified API version. * * @param baseUrl the base URL of the Twitch API * @param apiVersion the requested version of the Twitch API */ public VideosResource(String baseUrl, int apiVersion) { super(baseUrl, apiVersion); } /** * Returns a {@link Video} object. * * @param id the ID of the Video * @param handler the response handler */ public void get(final String id, final VideoResponseHandler handler) { String url = String.format("%s/videos/%s", getBaseUrl(), id); http.get(url, new TwitchHttpResponseHandler(handler) { @Override public void onSuccess(int statusCode, Map<String, List<String>> headers, String content) { try { Video value = objectMapper.readValue(content, Video.class); handler.onSuccess(value); } catch (IOException e) { handler.onFailure(e); } } }); } /** * Returns a list of {@link Video}'s created in a given time period sorted by number of views, most popular first. * * @param params the optional request parameters: * <ul> * <li><code>limit</code>: the maximum number of objects in array. Maximum is 100.</li> * <li><code>offset</code>: the object offset for pagination. Default is 0.</li> * <li><code>game</code>: Returns only videos from game.</li> * <li><code>period</code>: Returns only videos created in time period. * Valid values are <code>week</code>, <code>month</code>, * or <code>all</code>. Default is <code>week</code>. * </li> * </ul> * @param handler the response handler */ public void getTop(final RequestParams params, final VideosResponseHandler handler) { String url = String.format("%s/videos/top", getBaseUrl()); http.get(url, params, new TwitchHttpResponseHandler(handler) { @Override public void onSuccess(int statusCode, Map<String, List<String>> headers, String content) { try { Videos value = objectMapper.readValue(content, Videos.class); handler.onSuccess(value.getVideos().size(), value.getVideos()); } catch (IOException e) { handler.onFailure(e); } } }); } /** * Returns a list of {@link Video}'s created in a given time period sorted by number of views, most popular first. * * @param handler the response handler */ public void getTop(final VideosResponseHandler handler) { getTop(null, handler); } /** * Returns a list of {@link Video}'s from channels that the authenticated user is following. * Authenticated, required scope: {@link Scopes#USER_READ} * * @param params the optional request parameters: * <ul> * <li><code>limit</code>: the maximum number of objects in array. Maximum is 100.</li> * <li><code>offset</code>: the object offset for pagination. Default is 0.</li> * </ul> * @param handler the response handler */ public void getFollowed(final RequestParams params, final VideosResponseHandler handler) { String url = String.format("%s/videos/followed", getBaseUrl()); http.get(url, params, new TwitchHttpResponseHandler(handler) { @Override public void onSuccess(int statusCode, Map<String, List<String>> headers, String content) { try { Videos value = objectMapper.readValue(content, Videos.class); handler.onSuccess(value.getVideos().size(), value.getVideos()); } catch (IOException e) { handler.onFailure(e); } } }); } /** * Returns a list of {@link Video}'s from channels that the authenticated user is following. * Authenticated, required scope: {@link Scopes#USER_READ} * * @param handler the response handler */ public void getFollowed(final VideosResponseHandler handler) { getFollowed(new RequestParams(), handler); } }
{ "content_hash": "dc9033870426439222a77d286844dc17", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 118, "avg_line_length": 39.36153846153846, "alnum_prop": 0.5952706664060973, "repo_name": "urgrue/Java-Twitch-Api-Wrapper", "id": "57cd36ebc3dd7b0220e164d1bc5594dde8c784a8", "size": "5117", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/mb3364/twitch/api/resources/VideosResource.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3011" }, { "name": "Java", "bytes": "173350" }, { "name": "JavaScript", "bytes": "1509" } ], "symlink_target": "" }
/* * SubSonic - http://subsonicproject.com * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. */ using System; using System.Data; using System.Text; using SubSonic.Sugar; namespace SubSonic { /// <summary> /// /// </summary> public class MySqlGenerator : ANSISqlGenerator { private const string PAGING_SQL = @"{0} {1} LIMIT {2}, {3};"; /// <summary> /// Initializes a new instance of the <see cref="MySqlGenerator"/> class. /// </summary> /// <param name="query">The query.</param> public MySqlGenerator(SqlQuery query) : base(query) {} /// <summary> /// Gets the type of the native. /// </summary> /// <param name="dbType">Type of the db.</param> /// <returns></returns> protected override string GetNativeType(DbType dbType) { switch(dbType) { case DbType.Object: case DbType.AnsiString: case DbType.AnsiStringFixedLength: case DbType.String: case DbType.StringFixedLength: return "nvarchar"; case DbType.Boolean: return "bit"; case DbType.SByte: case DbType.Binary: case DbType.Byte: return "image"; case DbType.Currency: return "money"; case DbType.Time: case DbType.Date: case DbType.DateTime: return "datetime"; case DbType.Decimal: return "decimal"; case DbType.Double: return "float"; case DbType.Guid: return "uniqueidentifier"; case DbType.UInt32: case DbType.UInt16: case DbType.Int16: case DbType.Int32: return "INTEGER"; case DbType.UInt64: case DbType.Int64: return "bigint"; case DbType.Single: return "real"; case DbType.VarNumeric: return "numeric"; case DbType.Xml: return "xml"; default: return "nvarchar"; } } public override string BuildCreateTableStatement(TableSchema.Table table) { string columnSql = GenerateColumns(table); return string.Format(CREATE_TABLE, "`" + table.Name + "`", columnSql); } /// <summary> /// Generates SQL for all the columns in table /// </summary> /// <param name="table">Table containing the columns.</param> /// <returns> /// SQL fragment representing the supplied columns. /// </returns> protected override string GenerateColumns(TableSchema.Table table) { if(table.Columns.Count == 0) return String.Empty; StringBuilder columnsSql = new StringBuilder(); foreach(TableSchema.TableColumn col in table.Columns) columnsSql.AppendFormat("\r\n `{0}`{1},", col.ColumnName, GenerateColumnAttributes(col)); if(table.HasPrimaryKey) columnsSql.AppendFormat("\r\n PRIMARY KEY (`{0}`),", table.PrimaryKey.ColumnName); string sql = columnsSql.ToString(); return Strings.Chop(sql, ","); } /// <summary> /// Sets the column attributes. /// </summary> /// <param name="column">The column.</param> /// <returns></returns> protected override string GenerateColumnAttributes(TableSchema.TableColumn column) { StringBuilder sb = new StringBuilder(); if(column.DataType == DbType.DateTime && column.DefaultSetting == "getdate()") { //there is no way to have two fields with a NOW or CURRENT_TIMESTAMP setting //so need to rely on the code to help here sb.Append(" datetime "); } else { sb.Append(" " + GetNativeType(column.DataType)); if(column.IsPrimaryKey) { sb.Append(" NOT NULL"); if(column.IsNumeric) sb.Append(" AUTO_INCREMENT"); } else { if(column.MaxLength > 0 && column.MaxLength < 8000) sb.Append("(" + column.MaxLength + ")"); if(!column.IsNullable) sb.Append(" NOT NULL"); else sb.Append(" NULL"); if(!String.IsNullOrEmpty(column.DefaultSetting)) sb.Append(" DEFAULT " + column.DefaultSetting + " "); } } return sb.ToString(); } /// <summary> /// Builds the paged select statement. /// </summary> /// <returns></returns> public override string BuildPagedSelectStatement() { string select = GenerateCommandLine(); string fromLine = GenerateFromList(); string joins = GenerateJoins(); string wheres = GenerateWhere(); string orderby = GenerateOrderBy(); string havings = String.Empty; string groupby = String.Empty; if (query.Aggregates.Count > 0) { havings = GenerateHaving(); groupby = GenerateGroupBy(); } string sql = string.Format(PAGING_SQL, String.Concat(select, fromLine, joins), String.Concat(wheres, groupby, havings, orderby), (query.CurrentPage - 1) * query.PageSize, query.PageSize); return sql; } } }
{ "content_hash": "ae2c6fa16dfd8df16500247ceaeff9a1", "timestamp": "", "source": "github", "line_count": 189, "max_line_length": 106, "avg_line_length": 34.51322751322751, "alnum_prop": 0.5042158516020236, "repo_name": "SAEONData/SAEON-Observations-Database", "id": "f1c111b810c77154188ceedcf705c7bdd6e8cc46", "size": "6523", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "SAEON.SubSonic/SubSonic/SqlQuery/SqlGenerators/MySqlGenerator.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "814481" }, { "name": "Batchfile", "bytes": "766" }, { "name": "C#", "bytes": "7546547" }, { "name": "CSS", "bytes": "13906672" }, { "name": "Dockerfile", "bytes": "1748" }, { "name": "HTML", "bytes": "288820" }, { "name": "JavaScript", "bytes": "295583" }, { "name": "Less", "bytes": "19846829" }, { "name": "PowerShell", "bytes": "652" }, { "name": "TSQL", "bytes": "9070502" }, { "name": "TypeScript", "bytes": "22318" }, { "name": "XSLT", "bytes": "2456" } ], "symlink_target": "" }
package org.apache.lucene.store; import java.io.IOException; import java.io.File; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.BufferUnderflowException; import java.nio.channels.ClosedChannelException; // javadoc import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; import java.lang.reflect.Method; import org.apache.lucene.util.Constants; /** File-based {@link Directory} implementation that uses * mmap for reading, and {@link * FSDirectory.FSIndexOutput} for writing. * * <p><b>NOTE</b>: memory mapping uses up a portion of the * virtual memory address space in your process equal to the * size of the file being mapped. Before using this class, * be sure your have plenty of virtual address space, e.g. by * using a 64 bit JRE, or a 32 bit JRE with indexes that are * guaranteed to fit within the address space. * On 32 bit platforms also consult {@link #setMaxChunkSize} * if you have problems with mmap failing because of fragmented * address space. If you get an OutOfMemoryException, it is recommended * to reduce the chunk size, until it works. * * <p>Due to <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4724038"> * this bug</a> in Sun's JRE, MMapDirectory's {@link IndexInput#close} * is unable to close the underlying OS file handle. Only when GC * finally collects the underlying objects, which could be quite * some time later, will the file handle be closed. * * <p>This will consume additional transient disk usage: on Windows, * attempts to delete or overwrite the files will result in an * exception; on other platforms, which typically have a &quot;delete on * last close&quot; semantics, while such operations will succeed, the bytes * are still consuming space on disk. For many applications this * limitation is not a problem (e.g. if you have plenty of disk space, * and you don't rely on overwriting files on Windows) but it's still * an important limitation to be aware of. * * <p>This class supplies the workaround mentioned in the bug report * (see {@link #setUseUnmap}), which may fail on * non-Sun JVMs. It forcefully unmaps the buffer on close by using * an undocumented internal cleanup functionality. * {@link #UNMAP_SUPPORTED} is <code>true</code>, if the workaround * can be enabled (with no guarantees). * <p> * <b>NOTE:</b> Accessing this class either directly or * indirectly from a thread while it's interrupted can close the * underlying channel immediately if at the same time the thread is * blocked on IO. The channel will remain closed and subsequent access * to {@link MMapDirectory} will throw a {@link ClosedChannelException}. * </p> */ public class MMapDirectory extends FSDirectory { private boolean useUnmapHack = UNMAP_SUPPORTED; public static final int DEFAULT_MAX_BUFF = Constants.JRE_IS_64BIT ? (1 << 30) : (1 << 28); private int chunkSizePower; /** Create a new MMapDirectory for the named location. * * @param path the path of the directory * @param lockFactory the lock factory to use, or null for the default * ({@link NativeFSLockFactory}); * @throws IOException */ public MMapDirectory(File path, LockFactory lockFactory) throws IOException { super(path, lockFactory); setMaxChunkSize(DEFAULT_MAX_BUFF); } /** Create a new MMapDirectory for the named location and {@link NativeFSLockFactory}. * * @param path the path of the directory * @throws IOException */ public MMapDirectory(File path) throws IOException { super(path, null); setMaxChunkSize(DEFAULT_MAX_BUFF); } /** * <code>true</code>, if this platform supports unmapping mmapped files. */ public static final boolean UNMAP_SUPPORTED; static { boolean v; try { Class.forName("sun.misc.Cleaner"); Class.forName("java.nio.DirectByteBuffer") .getMethod("cleaner"); v = true; } catch (Exception e) { v = false; } UNMAP_SUPPORTED = v; } /** * This method enables the workaround for unmapping the buffers * from address space after closing {@link IndexInput}, that is * mentioned in the bug report. This hack may fail on non-Sun JVMs. * It forcefully unmaps the buffer on close by using * an undocumented internal cleanup functionality. * <p><b>NOTE:</b> Enabling this is completely unsupported * by Java and may lead to JVM crashes if <code>IndexInput</code> * is closed while another thread is still accessing it (SIGSEGV). * @throws IllegalArgumentException if {@link #UNMAP_SUPPORTED} * is <code>false</code> and the workaround cannot be enabled. */ public void setUseUnmap(final boolean useUnmapHack) { if (useUnmapHack && !UNMAP_SUPPORTED) throw new IllegalArgumentException("Unmap hack not supported on this platform!"); this.useUnmapHack=useUnmapHack; } /** * Returns <code>true</code>, if the unmap workaround is enabled. * @see #setUseUnmap */ public boolean getUseUnmap() { return useUnmapHack; } /** * Try to unmap the buffer, this method silently fails if no support * for that in the JVM. On Windows, this leads to the fact, * that mmapped files cannot be modified or deleted. */ final void cleanMapping(final ByteBuffer buffer) throws IOException { if (useUnmapHack) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { final Method getCleanerMethod = buffer.getClass() .getMethod("cleaner"); getCleanerMethod.setAccessible(true); final Object cleaner = getCleanerMethod.invoke(buffer); if (cleaner != null) { cleaner.getClass().getMethod("clean") .invoke(cleaner); } return null; } }); } catch (PrivilegedActionException e) { final IOException ioe = new IOException("unable to unmap the mapped buffer"); ioe.initCause(e.getCause()); throw ioe; } } } /** * Sets the maximum chunk size (default is {@link Integer#MAX_VALUE} for * 64 bit JVMs and 256 MiBytes for 32 bit JVMs) used for memory mapping. * Especially on 32 bit platform, the address space can be very fragmented, * so large index files cannot be mapped. * Using a lower chunk size makes the directory implementation a little * bit slower (as the correct chunk may be resolved on lots of seeks) * but the chance is higher that mmap does not fail. On 64 bit * Java platforms, this parameter should always be {@code 1 << 30}, * as the address space is big enough. * <b>Please note:</b> This method always rounds down the chunk size * to a power of 2. */ public final void setMaxChunkSize(final int maxChunkSize) { if (maxChunkSize <= 0) throw new IllegalArgumentException("Maximum chunk size for mmap must be >0"); //System.out.println("Requested chunk size: "+maxChunkSize); this.chunkSizePower = 31 - Integer.numberOfLeadingZeros(maxChunkSize); assert this.chunkSizePower >= 0 && this.chunkSizePower <= 30; //System.out.println("Got chunk size: "+getMaxChunkSize()); } /** * Returns the current mmap chunk size. * @see #setMaxChunkSize */ public final int getMaxChunkSize() { return 1 << chunkSizePower; } /** Creates an IndexInput for the file with the given name. */ @Override public IndexInput openInput(String name, int bufferSize) throws IOException { ensureOpen(); File f = new File(getDirectory(), name); RandomAccessFile raf = new RandomAccessFile(f, "r"); try { return new MMapIndexInput("MMapIndexInput(path=\"" + f + "\")", raf, chunkSizePower); } finally { raf.close(); } } // Because Java's ByteBuffer uses an int to address the // values, it's necessary to access a file > // Integer.MAX_VALUE in size using multiple byte buffers. private final class MMapIndexInput extends IndexInput { private ByteBuffer[] buffers; private final long length, chunkSizeMask, chunkSize; private final int chunkSizePower; private int curBufIndex; private ByteBuffer curBuf; // redundant for speed: buffers[curBufIndex] private boolean isClone = false; MMapIndexInput(String resourceDescription, RandomAccessFile raf, int chunkSizePower) throws IOException { super(resourceDescription); this.length = raf.length(); this.chunkSizePower = chunkSizePower; this.chunkSize = 1L << chunkSizePower; this.chunkSizeMask = chunkSize - 1L; if (chunkSizePower < 0 || chunkSizePower > 30) throw new IllegalArgumentException("Invalid chunkSizePower used for ByteBuffer size: " + chunkSizePower); if ((length >>> chunkSizePower) >= Integer.MAX_VALUE) throw new IllegalArgumentException("RandomAccessFile too big for chunk size: " + raf.toString()); // we always allocate one more buffer, the last one may be a 0 byte one final int nrBuffers = (int) (length >>> chunkSizePower) + 1; //System.out.println("length="+length+", chunkSizePower=" + chunkSizePower + ", chunkSizeMask=" + chunkSizeMask + ", nrBuffers=" + nrBuffers); this.buffers = new ByteBuffer[nrBuffers]; long bufferStart = 0L; FileChannel rafc = raf.getChannel(); for (int bufNr = 0; bufNr < nrBuffers; bufNr++) { int bufSize = (int) ( (length > (bufferStart + chunkSize)) ? chunkSize : (length - bufferStart) ); this.buffers[bufNr] = rafc.map(MapMode.READ_ONLY, bufferStart, bufSize); bufferStart += bufSize; } seek(0L); } @Override public byte readByte() throws IOException { try { return curBuf.get(); } catch (BufferUnderflowException e) { do { curBufIndex++; if (curBufIndex >= buffers.length) { throw new IOException("read past EOF: " + this); } curBuf = buffers[curBufIndex]; curBuf.position(0); } while (!curBuf.hasRemaining()); return curBuf.get(); } } @Override public void readBytes(byte[] b, int offset, int len) throws IOException { try { curBuf.get(b, offset, len); } catch (BufferUnderflowException e) { int curAvail = curBuf.remaining(); while (len > curAvail) { curBuf.get(b, offset, curAvail); len -= curAvail; offset += curAvail; curBufIndex++; if (curBufIndex >= buffers.length) { throw new IOException("read past EOF: " + this); } curBuf = buffers[curBufIndex]; curBuf.position(0); curAvail = curBuf.remaining(); } curBuf.get(b, offset, len); } } @Override public int readInt() throws IOException { try { return curBuf.getInt(); } catch (BufferUnderflowException e) { return super.readInt(); } } @Override public long readLong() throws IOException { try { return curBuf.getLong(); } catch (BufferUnderflowException e) { return super.readLong(); } } @Override public long getFilePointer() { return (((long) curBufIndex) << chunkSizePower) + curBuf.position(); } @Override public void seek(long pos) throws IOException { // we use >> here to preserve negative, so we will catch AIOOBE: final int bi = (int) (pos >> chunkSizePower); try { final ByteBuffer b = buffers[bi]; b.position((int) (pos & chunkSizeMask)); // write values, on exception all is unchanged this.curBufIndex = bi; this.curBuf = b; } catch (ArrayIndexOutOfBoundsException aioobe) { if (pos < 0L) { throw new IllegalArgumentException("Seeking to negative position: " + this); } throw new IOException("seek past EOF"); } catch (IllegalArgumentException iae) { if (pos < 0L) { throw new IllegalArgumentException("Seeking to negative position: " + this); } throw new IOException("seek past EOF: " + this); } } @Override public long length() { return length; } @Override public Object clone() { if (buffers == null) { throw new AlreadyClosedException("MMapIndexInput already closed: " + this); } final MMapIndexInput clone = (MMapIndexInput)super.clone(); clone.isClone = true; clone.buffers = new ByteBuffer[buffers.length]; // Since most clones will use only one buffer, duplicate() could also be // done lazy in clones, e.g. when adapting curBuf. for (int bufNr = 0; bufNr < buffers.length; bufNr++) { clone.buffers[bufNr] = buffers[bufNr].duplicate(); } try { clone.seek(getFilePointer()); } catch(IOException ioe) { throw new RuntimeException("Should never happen: " + this, ioe); } return clone; } @Override public void close() throws IOException { try { if (isClone || buffers == null) return; for (int bufNr = 0; bufNr < buffers.length; bufNr++) { // unmap the buffer (if enabled) and at least unset it for GC try { cleanMapping(buffers[bufNr]); } finally { buffers[bufNr] = null; } } } finally { buffers = null; } } } }
{ "content_hash": "4bf5faf7c9a11a9c753fdb02458153d7", "timestamp": "", "source": "github", "line_count": 384, "max_line_length": 148, "avg_line_length": 35.856770833333336, "alnum_prop": 0.65371486672961, "repo_name": "fnp/pylucene", "id": "ad007410c45412f6c876834cbefd79574f9fa322", "size": "14571", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "lucene-java-3.5.0/lucene/src/java/org/apache/lucene/store/MMapDirectory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "22004" }, { "name": "C++", "bytes": "400999" }, { "name": "Java", "bytes": "17659185" }, { "name": "JavaScript", "bytes": "43988" }, { "name": "Perl", "bytes": "63743" }, { "name": "Python", "bytes": "384342" } ], "symlink_target": "" }
/* This file contains the DatabaseContext class. * This database context is the entry point to the Entity Framework and provides access to the users table. * * Datei: DatabaseContext.cs Autor: Ramandeep Singh * Datum: 23.12.2015 Version: 1.0 */ using System.Data.Entity; namespace Webserver.Models { /// <summary> /// This class should be used to get acces to the database and users table. /// </summary> public class DatabaseContext : DbContext { public DatabaseContext() : base("name=WebserverContext") { Database.SetInitializer(new DatabaseInitilizer()); } public DbSet<User> Users { get; set; } /// <summary> /// This database initializer is used to drop all tables from the database and recreate them if the model classes have /// changed. /// </summary> private class DatabaseInitilizer : DropCreateDatabaseIfModelChanges<DatabaseContext> { } } }
{ "content_hash": "09a8dbfd8bd0574a8395856d8a29b47f", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 131, "avg_line_length": 31.0625, "alnum_prop": 0.6498993963782697, "repo_name": "marbo86/androidApplication", "id": "4b9538c33daf42099cd06c7366dc7a00762c9876", "size": "996", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Webserver/Webserver/Models/DatabaseContext.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "103" }, { "name": "C#", "bytes": "17999" }, { "name": "Java", "bytes": "115307" } ], "symlink_target": "" }