text
stringlengths
2
1.04M
meta
dict
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="se.oort.spoticlock" > <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".SpotiClock" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.spotify.sdk.android.authentication.LoginActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar"/> </application> </manifest>
{ "content_hash": "d18e53d114d2bcf594f9763c993ab52b", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 79, "avg_line_length": 38.291666666666664, "alnum_prop": 0.6202393906420022, "repo_name": "zond/spoticlock", "id": "b3b5780aafd2aedde1b077af2796863bf4d72839", "size": "919", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "4461" } ], "symlink_target": "" }
package io.github.thatsmusic99.headsplus.inventories.list; import io.github.thatsmusic99.headsplus.config.ConfigHeadsSelector; import io.github.thatsmusic99.headsplus.inventories.BaseInventory; import io.github.thatsmusic99.headsplus.inventories.icons.Content; import io.github.thatsmusic99.headsplus.inventories.icons.content.CustomHead; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class HeadsSection extends BaseInventory { public HeadsSection(Player player, HashMap<String, String> context) { super(player, context); } public HeadsSection() { } @Override public String getDefaultTitle() { return "HeadsPlus Heads: {page}/{pages}"; } @Override public String getDefaultItems() { return "FGGGSGGGKGCCCCCCCGGCCCCCCCGGCCCCCCCGGCCCCCCCG<{[BMN]}>"; } @Override public String getId() { return "headsection"; } @Override public List<Content> transformContents(HashMap<String, String> context, Player player) { List<Content> contents = new ArrayList<>(); for (String key : ConfigHeadsSelector.get().getSection(context.get("section")).getHeads().keySet()) { CustomHead head1 = new CustomHead(key); head1.initNameAndLore(key, player); contents.add(head1); } return contents; } }
{ "content_hash": "fe64c5dbd77715a10d63fe475e54772b", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 109, "avg_line_length": 30.127659574468087, "alnum_prop": 0.6998587570621468, "repo_name": "Thatsmusic99/HeadsPlus", "id": "9898544892051fbb0dc3bfb0f94a427dd66ce73a", "size": "1416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/io/github/thatsmusic99/headsplus/inventories/list/HeadsSection.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "883166" } ], "symlink_target": "" }
/* Simple program: Create a native window and attach an SDL renderer */ #include <stdio.h> #include <stdlib.h> /* for srand() */ #include <time.h> /* for time() */ #include "testnative.h" #define WINDOW_W 640 #define WINDOW_H 480 #define NUM_SPRITES 100 #define MAX_SPEED 1 static NativeWindowFactory *factories[] = { #ifdef TEST_NATIVE_WINDOWS &WindowsWindowFactory, #endif #ifdef TEST_NATIVE_X11 &X11WindowFactory, #endif #ifdef TEST_NATIVE_COCOA &CocoaWindowFactory, #endif NULL }; static NativeWindowFactory *factory = NULL; static void *native_window; static SDL_Rect *positions, *velocities; /* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */ static void quit(int rc) { SDL_VideoQuit(); if (native_window) { factory->DestroyNativeWindow(native_window); } exit(rc); } SDL_Texture * LoadSprite(SDL_Renderer *renderer, char *file) { SDL_Surface *temp; SDL_Texture *sprite; /* Load the sprite image */ temp = SDL_LoadBMP(file); if (temp == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s", file, SDL_GetError()); return 0; } /* Set transparent pixel as the pixel at (0,0) */ if (temp->format->palette) { SDL_SetColorKey(temp, 1, *(Uint8 *) temp->pixels); } /* Create textures from the image */ sprite = SDL_CreateTextureFromSurface(renderer, temp); if (!sprite) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError()); SDL_FreeSurface(temp); return 0; } SDL_FreeSurface(temp); /* We're ready to roll. :) */ return sprite; } void MoveSprites(SDL_Renderer * renderer, SDL_Texture * sprite) { int sprite_w, sprite_h; int i; SDL_Rect viewport; SDL_Rect *position, *velocity; /* Query the sizes */ SDL_RenderGetViewport(renderer, &viewport); SDL_QueryTexture(sprite, NULL, NULL, &sprite_w, &sprite_h); /* Draw a gray background */ SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF); SDL_RenderClear(renderer); /* Move the sprite, bounce at the wall, and draw */ for (i = 0; i < NUM_SPRITES; ++i) { position = &positions[i]; velocity = &velocities[i]; position->x += velocity->x; if ((position->x < 0) || (position->x >= (viewport.w - sprite_w))) { velocity->x = -velocity->x; position->x += velocity->x; } position->y += velocity->y; if ((position->y < 0) || (position->y >= (viewport.h - sprite_h))) { velocity->y = -velocity->y; position->y += velocity->y; } /* Blit the sprite onto the screen */ SDL_RenderCopy(renderer, sprite, NULL, position); } /* Update the screen! */ SDL_RenderPresent(renderer); } int main(int argc, char *argv[]) { int i, done; const char *driver; SDL_Window *window; SDL_Renderer *renderer; SDL_Texture *sprite; int window_w, window_h; int sprite_w, sprite_h; SDL_Event event; /* Enable standard application logging */ SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); if (SDL_VideoInit(NULL) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL video: %s\n", SDL_GetError()); exit(1); } driver = SDL_GetCurrentVideoDriver(); /* Find a native window driver and create a native window */ for (i = 0; factories[i]; ++i) { if (SDL_strcmp(driver, factories[i]->tag) == 0) { factory = factories[i]; break; } } if (!factory) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't find native window code for %s driver\n", driver); quit(2); } SDL_Log("Creating native window for %s driver\n", driver); native_window = factory->CreateNativeWindow(WINDOW_W, WINDOW_H); if (!native_window) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create native window\n"); quit(3); } window = SDL_CreateWindowFrom(native_window); if (!window) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create SDL window: %s\n", SDL_GetError()); quit(4); } SDL_SetWindowTitle(window, "SDL Native Window Test"); /* Create the renderer */ renderer = SDL_CreateRenderer(window, -1, 0); if (!renderer) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError()); quit(5); } /* Clear the window, load the sprite and go! */ SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF); SDL_RenderClear(renderer); sprite = LoadSprite(renderer, "icon.bmp"); if (!sprite) { quit(6); } /* Allocate memory for the sprite info */ SDL_GetWindowSize(window, &window_w, &window_h); SDL_QueryTexture(sprite, NULL, NULL, &sprite_w, &sprite_h); positions = (SDL_Rect *) SDL_malloc(NUM_SPRITES * sizeof(SDL_Rect)); velocities = (SDL_Rect *) SDL_malloc(NUM_SPRITES * sizeof(SDL_Rect)); if (!positions || !velocities) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory!\n"); quit(2); } srand(time(NULL)); for (i = 0; i < NUM_SPRITES; ++i) { positions[i].x = rand() % (window_w - sprite_w); positions[i].y = rand() % (window_h - sprite_h); positions[i].w = sprite_w; positions[i].h = sprite_h; velocities[i].x = 0; velocities[i].y = 0; while (!velocities[i].x && !velocities[i].y) { velocities[i].x = (rand() % (MAX_SPEED * 2 + 1)) - MAX_SPEED; velocities[i].y = (rand() % (MAX_SPEED * 2 + 1)) - MAX_SPEED; } } /* Main render loop */ done = 0; while (!done) { /* Check for events */ while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_EXPOSED: SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF); SDL_RenderClear(renderer); break; } break; case SDL_QUIT: done = 1; break; default: break; } } MoveSprites(renderer, sprite); } quit(0); return 0; /* to prevent compiler warning */ } /* vi: set ts=4 sw=4 expandtab: */
{ "content_hash": "9e636131047d83c09d56403f9e44f4f5", "timestamp": "", "source": "github", "line_count": 227, "max_line_length": 103, "avg_line_length": 28.964757709251103, "alnum_prop": 0.577338403041825, "repo_name": "GarageGames/Torque3D", "id": "c1facd398526fbe6dfb3fa719dde090efbdd6d02", "size": "6979", "binary": false, "copies": "6", "ref": "refs/heads/development", "path": "Engine/lib/sdl/test/testnative.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "32222" }, { "name": "Batchfile", "bytes": "8398" }, { "name": "C", "bytes": "30786115" }, { "name": "C#", "bytes": "5730625" }, { "name": "C++", "bytes": "39013535" }, { "name": "CMake", "bytes": "454255" }, { "name": "CSS", "bytes": "29109" }, { "name": "GLSL", "bytes": "806172" }, { "name": "HLSL", "bytes": "850669" }, { "name": "HTML", "bytes": "368260" }, { "name": "JavaScript", "bytes": "18010" }, { "name": "Lex", "bytes": "18783" }, { "name": "Lua", "bytes": "1288" }, { "name": "M4", "bytes": "236074" }, { "name": "Makefile", "bytes": "88858" }, { "name": "Metal", "bytes": "3849" }, { "name": "Module Management System", "bytes": "13253" }, { "name": "NSIS", "bytes": "1194010" }, { "name": "Objective-C", "bytes": "559024" }, { "name": "Objective-C++", "bytes": "127055" }, { "name": "PHP", "bytes": "615704" }, { "name": "Pascal", "bytes": "6505" }, { "name": "Perl", "bytes": "24056" }, { "name": "PowerShell", "bytes": "12518" }, { "name": "Python", "bytes": "5098" }, { "name": "Rich Text Format", "bytes": "4380" }, { "name": "Roff", "bytes": "310763" }, { "name": "SAS", "bytes": "13756" }, { "name": "Shell", "bytes": "464739" }, { "name": "Smalltalk", "bytes": "19234" }, { "name": "Smarty", "bytes": "333060" }, { "name": "StringTemplate", "bytes": "4329" }, { "name": "WebAssembly", "bytes": "13560" }, { "name": "Yacc", "bytes": "19714" } ], "symlink_target": "" }
#import "AWSModel.h" @class NSString, NSArray; @interface AWSAutoScalingActivitiesType : AWSModel { NSArray* _activities; NSString* _nextToken; } @property(retain, nonatomic) NSArray* activities; @property(retain, nonatomic) NSString* nextToken; + (id)JSONKeyPathsByPropertyKey; + (id)activitiesJSONTransformer; - (void).cxx_destruct; @end
{ "content_hash": "b4cca2e28517dfaa53aedbac9f41e331", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 52, "avg_line_length": 20.41176470588235, "alnum_prop": 0.7665706051873199, "repo_name": "ZaneH/ChineseSkill-Hack", "id": "631a519c0abdaa9a3b67ed6e87251568a939229e", "size": "498", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ChineseSkill-Headers/AWSAutoScalingActivitiesType.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3263" }, { "name": "Groff", "bytes": "2" }, { "name": "Logos", "bytes": "6437" }, { "name": "Makefile", "bytes": "293" }, { "name": "Objective-C", "bytes": "2563544" } ], "symlink_target": "" }
package org.apache.camel.catalog.maven; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import groovy.grape.Grape; import groovy.lang.GroovyClassLoader; import org.apache.camel.catalog.VersionManager; import org.apache.ivy.util.url.URLHandlerRegistry; /** * A {@link VersionManager} that can load the resources using Maven to download needed artifacts from a local or remote * Maven repository. * <p/> * This implementation uses Groovy Grape to download the Maven JARs. */ public class MavenVersionManager implements VersionManager, Closeable { private final ClassLoader classLoader = new GroovyClassLoader(); private final TimeoutHttpClientHandler httpClient = new TimeoutHttpClientHandler(); private String version; private String runtimeProviderVersion; private String cacheDirectory; private boolean log; /** * Configures the directory for the download cache. * <p/> * The default folder is <tt>USER_HOME/.groovy/grape</tt> * * @param directory the directory. */ public void setCacheDirectory(String directory) { this.cacheDirectory = directory; } /** * Sets whether to log errors and warnings to System.out. By default nothing is logged. */ public void setLog(boolean log) { this.log = log; } /** * Sets the timeout in millis (http.socket.timeout) when downloading via http/https protocols. * <p/> * The default value is 10000 */ public void setHttpClientTimeout(int timeout) { httpClient.setTimeout(timeout); } /** * To add a 3rd party Maven repository. * * @param name the repository name * @param url the repository url */ public void addMavenRepository(String name, String url) { Map<String, Object> repo = new HashMap<>(); repo.put("name", name); repo.put("root", url); Grape.addResolver(repo); } @Override public String getLoadedVersion() { return version; } @Override public boolean loadVersion(String version) { try { URLHandlerRegistry.setDefault(httpClient); if (cacheDirectory != null) { System.setProperty("grape.root", cacheDirectory); } Grape.setEnableAutoDownload(true); Map<String, Object> param = new HashMap<>(); param.put("classLoader", classLoader); param.put("group", "org.apache.camel"); param.put("module", "camel-catalog"); param.put("version", version); Grape.grab(param); this.version = version; return true; } catch (Exception e) { if (log) { System.out.print("WARN: Cannot load version " + version + " due " + e.getMessage()); } return false; } } @Override public String getRuntimeProviderLoadedVersion() { return runtimeProviderVersion; } @Override public boolean loadRuntimeProviderVersion(String groupId, String artifactId, String version) { try { URLHandlerRegistry.setDefault(httpClient); Grape.setEnableAutoDownload(true); Map<String, Object> param = new HashMap<>(); param.put("classLoader", classLoader); param.put("group", groupId); param.put("module", artifactId); param.put("version", version); Grape.grab(param); this.runtimeProviderVersion = version; return true; } catch (Exception e) { if (log) { System.out.print("WARN: Cannot load runtime provider version " + version + " due " + e.getMessage()); } return false; } } @Override public InputStream getResourceAsStream(String name) { InputStream is = null; if (runtimeProviderVersion != null) { is = doGetResourceAsStream(name, runtimeProviderVersion); } if (is == null && version != null) { is = doGetResourceAsStream(name, version); } if (is == null) { is = MavenVersionManager.class.getClassLoader().getResourceAsStream(name); } if (is == null) { is = classLoader.getResourceAsStream(name); } return is; } private InputStream doGetResourceAsStream(String name, String version) { if (version == null) { return null; } try { URL found = null; Enumeration<URL> urls = classLoader.getResources(name); while (urls.hasMoreElements()) { URL url = urls.nextElement(); if (url.getPath().contains(version)) { found = url; break; } } if (found != null) { return found.openStream(); } } catch (IOException e) { if (log) { System.out.print("WARN: Cannot open resource " + name + " and version " + version + " due " + e.getMessage()); } } return null; } @Override public void close() throws IOException { } }
{ "content_hash": "d92935e8b387cf0f9c644e6144350c14", "timestamp": "", "source": "github", "line_count": 186, "max_line_length": 126, "avg_line_length": 29.0752688172043, "alnum_prop": 0.5854289940828402, "repo_name": "nicolaferraro/camel", "id": "3151894bebab86ba476ed62ff10fdcc3f39e5479", "size": "6210", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "catalog/camel-catalog-maven/src/main/java/org/apache/camel/catalog/maven/MavenVersionManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6521" }, { "name": "Batchfile", "bytes": "2353" }, { "name": "CSS", "bytes": "5472" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "8015" }, { "name": "Groovy", "bytes": "14479" }, { "name": "HTML", "bytes": "916625" }, { "name": "Java", "bytes": "82748568" }, { "name": "JavaScript", "bytes": "100326" }, { "name": "Makefile", "bytes": "513" }, { "name": "Shell", "bytes": "17240" }, { "name": "TSQL", "bytes": "28835" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "275257" } ], "symlink_target": "" }
gittip-calculator ################# This project is a calculator to figure out much Gittip_ needs to charge to pay out. Every Thursday, Gittip sends your contributions to specific users. If you account balance is less than the amount of money required to fulfill all of your contributions, then your credit card is charged a minimum of $10.00 to add to your balance. Because Gittip operates on a once-weekly basis and requres a $10.00 minimum charge, it's cumbersome to predict how much money Gittip might charge your credit card any given week, or over a longer period (e.g., monthly, quarterly, or annually). This calculator is intended to make it easier to sort those numbers out, especially for people who like to plan their budget more than a week in advance. .. _Gittip: https://www.gittip.com/
{ "content_hash": "8b4b23d7d94fc92f59c62511183c0884", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 102, "avg_line_length": 53.6, "alnum_prop": 0.7699004975124378, "repo_name": "ddbeck/gittip-calculator", "id": "fd19fa371d622e60dde7009f3238ed063e689135", "size": "804", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "8289" } ], "symlink_target": "" }
require 'postbot/version' require 'postbot/client' module Postbot def self.create(params = {}) Postbot::Client.new(params) end def self.recipe_dir File.expand_path(File.join(File.dirname(__FILE__), '../recipients')) end end
{ "content_hash": "e22ec7ec53d18fcf378cbec29a62215e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 72, "avg_line_length": 18.692307692307693, "alnum_prop": 0.6872427983539094, "repo_name": "ainame/postbot", "id": "fad43424c4797646a40b1fc8f701c902f12916d9", "size": "243", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/postbot.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "4020" } ], "symlink_target": "" }
// ----------------------------------------------------------------------- // <copyright file="BaseUsageBasedLineItem.java" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- package com.microsoft.store.partnercenter.models.invoices; import org.joda.time.DateTime; /** * Represents common properties for Usage based invoice line items */ public abstract class BaseUsageBasedLineItem extends InvoiceLineItem { /** * Gets or sets the partner's commerce account Id. */ private String __PartnerId; public String getPartnerId() { return __PartnerId; } public void setPartnerId( String value ) { __PartnerId = value; } /** * Gets or sets the partner's Name. */ private String __PartnerName; public String getPartnerName() { return __PartnerName; } public void setPartnerName( String value ) { __PartnerName = value; } /** * Gets or sets the partner billable account Id. */ private String __PartnerBillableAccountId; public String getPartnerBillableAccountId() { return __PartnerBillableAccountId; } public void setPartnerBillableAccountId( String value ) { __PartnerBillableAccountId = value; } /** * Gets or sets the customer company name. */ private String __CustomerCompanyName; public String getCustomerCompanyName() { return __CustomerCompanyName; } public void setCustomerCompanyName( String value ) { __CustomerCompanyName = value; } /** * Gets or sets the partner's Microsoft Partner Network Id. */ private int __MpnId; public int getMpnId() { return __MpnId; } public void setMpnId( int value ) { __MpnId = value; } /** * Gets or sets the Tier 2 Partner's Microsoft Partner Network Id. */ private int __Tier2MpnId; public int getTier2MpnId() { return __Tier2MpnId; } public void setTier2MpnId( int value ) { __Tier2MpnId = value; } /** * Gets or sets the invoice number. */ private String __InvoiceNumber; public String getInvoiceNumber() { return __InvoiceNumber; } public void setInvoiceNumber( String value ) { __InvoiceNumber = value; } /** * Gets or sets the subscription Id. */ private String __SubscriptionId; public String getSubscriptionId() { return __SubscriptionId; } public void setSubscriptionId( String value ) { __SubscriptionId = value; } /** * Gets or sets the subscription name. */ private String __SubscriptionName; public String getSubscriptionName() { return __SubscriptionName; } public void setSubscriptionName( String value ) { __SubscriptionName = value; } /** * Gets or sets the description of the subscription. */ private String __SubscriptionDescription; public String getSubscriptionDescription() { return __SubscriptionDescription; } public void setSubscriptionDescription( String value ) { __SubscriptionDescription = value; } /** * Gets or sets the order Id. */ private String __OrderId; public String getOrderId() { return __OrderId; } public void setOrderId( String value ) { __OrderId = value; } /** * Gets or sets the service name. Example: Azure Data Service */ private String __ServiceName; public String getServiceName() { return __ServiceName; } public void setServiceName( String value ) { __ServiceName = value; } /** * Gets or sets the service type. Example: Azure SQL Azure DB. */ private String __ServiceType; public String getServiceType() { return __ServiceType; } public void setServiceType( String value ) { __ServiceType = value; } /** * Gets or sets the resource identifier. */ private String __ResourceGuid; public String getResourceGuid() { return __ResourceGuid; } public void setResourceGuid( String value ) { __ResourceGuid = value; } /** * Gets or sets the resource name. Example: Database (GB/month) */ private String __ResourceName; public String getResourceName() { return __ResourceName; } public void setResourceName( String value ) { __ResourceName = value; } /** * Gets or sets the region associated with the resource instance. */ private String __Region; public String getRegion() { return __Region; } public void setRegion( String value ) { __Region = value; } /** * Gets or sets the total units consumed. */ private int __ConsumedQuantity; public int getConsumedQuantity() { return __ConsumedQuantity; } public void setConsumedQuantity( int value ) { __ConsumedQuantity = value; } /** * Gets or sets the date charge begins. */ private DateTime __ChargeStartDate; public DateTime getChargeStartDate() { return __ChargeStartDate; } public void setChargeStartDate( DateTime value ) { __ChargeStartDate = value; } /** * Gets or sets the date charge ends. */ private DateTime __ChargeEndDate; public DateTime getChargeEndDate() { return __ChargeEndDate; } public void setChargeEndDate( DateTime value ) { __ChargeEndDate = value; } /** * Returns the billing provider * * @return The billing provider. */ public BillingProvider getBillingProvider() { return BillingProvider.AZURE; } }
{ "content_hash": "b4db880432483ea1358b063a4ed575ac", "timestamp": "", "source": "github", "line_count": 312, "max_line_length": 74, "avg_line_length": 19.525641025641026, "alnum_prop": 0.577478660538411, "repo_name": "iogav/Partner-Center-Java-SDK", "id": "a9912ca8de1fdc0ac99b01552ac346628ccab41c", "size": "6092", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PartnerSdk/src/main/java/com/microsoft/store/partnercenter/models/invoices/BaseUsageBasedLineItem.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "830276" } ], "symlink_target": "" }
/** * Created by dietn on 28/11/14. */ var mysql = require("mysql"); var settings = require("../settings.json"); function getConnection(){ var db = mysql.createConnection({ host : settings.dbHost, user : settings.dbUser, password : settings.dbPwd, database: settings.dbName }); db.connect(); return db; } module.exports.getConnection = getConnection;
{ "content_hash": "3ff932006f619723f58f95aef18a2754", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 45, "avg_line_length": 25.5625, "alnum_prop": 0.6210268948655256, "repo_name": "dieterbeelaert/Repcheckr", "id": "8e5a07c3ecfcc2c26b7490d17a580c60e4be2106", "size": "409", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "App/Data/ConnectionManager.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "378" }, { "name": "HTML", "bytes": "31712" }, { "name": "JavaScript", "bytes": "41148" } ], "symlink_target": "" }
const EntityCell = require('./EntityCell.js'); class House extends EntityCell { onEnter(creature){ } } module.exports = House;
{ "content_hash": "c44ab0c3d3f246345bd009a0d51748fd", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 46, "avg_line_length": 15.444444444444445, "alnum_prop": 0.6762589928057554, "repo_name": "goodzsq/cocos_template", "id": "d686a9daf5ef213f55369e8d2470f138b6d731e8", "size": "139", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/samples/games/rocket/House.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "387" }, { "name": "HTML", "bytes": "496" }, { "name": "JavaScript", "bytes": "153833" }, { "name": "TypeScript", "bytes": "113432" } ], "symlink_target": "" }
// // Novell.Directory.Ldap.LdapResponseQueue.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; namespace Novell.Directory.Ldap { /// <summary> A mechanism for processing asynchronous messages received from a server. /// It represents the message queue associated with a particular asynchronous /// Ldap operation or operations. /// </summary> public class LdapResponseQueue:LdapMessageQueue { /// <summary> Constructs a response queue using the specified message agent /// /// </summary> /// <param name="agent">The message agent to associate with this queue /// </param> /* package */ internal LdapResponseQueue(MessageAgent agent):base("LdapResponseQueue", agent) { return ; } /// <summary> Merges two message queues. It appends the current and /// future contents from another queue to this one. /// /// After the operation, queue2.getMessageIDs() /// returns an empty array, and its outstanding responses /// have been removed and appended to this queue. /// /// </summary> /// <param name="queue2"> The queue that is merged from. Following /// the merge, this queue object will no /// longer receive any data, and calls made /// to its methods will fail with a RuntimeException. /// The queue can be reactivated by using it in an /// Ldap request, after which it will receive responses /// for that request.. /// </param> public virtual void merge(LdapMessageQueue queue2) { LdapResponseQueue q = (LdapResponseQueue) queue2; agent.merge(q.MessageAgent); return ; } } }
{ "content_hash": "a82829052a27c3c61ad7c1c498d71d1f", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 88, "avg_line_length": 28.842105263157894, "alnum_prop": 0.6879562043795621, "repo_name": "tpurtell/CsharpLDAP", "id": "aaf6ca6de3c256443a655487f41f7db87dcf8315", "size": "2936", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Novell.Directory.LDAP/Novell.Directory.Ldap/LdapResponseQueue.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1660309" }, { "name": "Shell", "bytes": "2664" } ], "symlink_target": "" }
package querqy.solr.rewriter.wordbreak; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsIterableContainingInOrder.*; import static org.hamcrest.collection.IsMapContaining.hasEntry; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static querqy.solr.rewriter.wordbreak.WordBreakCompoundRewriterFactory.CONF_ALWAYS_ADD_REVERSE_COMPOUNDS; import static querqy.solr.rewriter.wordbreak.WordBreakCompoundRewriterFactory.CONF_DECOMPOUND; import static querqy.solr.rewriter.wordbreak.WordBreakCompoundRewriterFactory.CONF_DECOMPOUND_MAX_EXPANSIONS; import static querqy.solr.rewriter.wordbreak.WordBreakCompoundRewriterFactory.CONF_DECOMPOUND_VERIFY_COLLATION; import static querqy.solr.rewriter.wordbreak.WordBreakCompoundRewriterFactory.CONF_DICTIONARY_FIELD; import static querqy.solr.rewriter.wordbreak.WordBreakCompoundRewriterFactory.CONF_LOWER_CASE_INPUT; import static querqy.solr.rewriter.wordbreak.WordBreakCompoundRewriterFactory.CONF_MAX_COMBINE_WORD_LENGTH; import static querqy.solr.rewriter.wordbreak.WordBreakCompoundRewriterFactory.CONF_MIN_BREAK_LENGTH; import static querqy.solr.rewriter.wordbreak.WordBreakCompoundRewriterFactory.CONF_MIN_SUGGESTION_FREQ; import static querqy.solr.rewriter.wordbreak.WordBreakCompoundRewriterFactory.CONF_MORPHOLOGY; import static querqy.solr.rewriter.wordbreak.WordBreakCompoundRewriterFactory.CONF_REVERSE_COMPOUND_TRIGGER_WORDS; import org.junit.Test; import querqy.lucene.contrib.rewrite.wordbreak.Morphology; import java.util.List; import java.util.Map; public class WordBreakCompoundConfigRequestBuilderTest { @Test public void testThatDictionaryFieldMustBeSet() { try { new WordBreakCompoundConfigRequestBuilder().buildConfig(); fail("dictionaryField==null must not be allowed"); } catch (final Exception e) { assertTrue(e.getMessage().contains(CONF_DICTIONARY_FIELD)); } try { new WordBreakCompoundConfigRequestBuilder().dictionaryField(null); fail("dictionaryField==null must not be allowed"); } catch (final IllegalArgumentException e) { assertTrue(e.getMessage().contains(CONF_DICTIONARY_FIELD)); } try { new WordBreakCompoundConfigRequestBuilder().dictionaryField(""); fail("empty dictionaryField must not be allowed"); } catch (final IllegalArgumentException e) { assertTrue(e.getMessage().contains(CONF_DICTIONARY_FIELD)); } } @Test public void testThatMinBreakMustBeGreaterOrEqual1() { try { new WordBreakCompoundConfigRequestBuilder().dictionaryField("f1").minBreakLength(0); fail("minBreakLength<1 must not be allowed"); } catch (final IllegalArgumentException e) { assertTrue(e.getMessage().contains("minBreakLength")); } } @Test public void testMinimalConfig() { final Map<String, Object> config = new WordBreakCompoundConfigRequestBuilder().dictionaryField("f1") .buildConfig(); final List<String> errors = new WordBreakCompoundRewriterFactory("id").validateConfiguration(config); assertTrue(errors == null || errors.isEmpty()); } @Test public void testSetAllProperties() { final Map<String, Object> config = new WordBreakCompoundConfigRequestBuilder() .dictionaryField("f1") .minBreakLength(1) .alwaysAddReverseCompounds(true) .lowerCaseInput(false) .maxCombineWordLength(10) .maxDecompoundExpansions(4) .minSuggestionFrequency(2) .morphology(Morphology.GERMAN) .reverseCompoundTriggerWords("from", "of") .verifyDecompoundCollation(false) .buildConfig(); final List<String> errors = new WordBreakCompoundRewriterFactory("id").validateConfiguration(config); assertTrue(errors == null || errors.isEmpty()); assertThat(config, hasEntry(CONF_DICTIONARY_FIELD, "f1")); assertThat(config, hasEntry(CONF_MIN_BREAK_LENGTH, 1)); assertThat(config, hasEntry(CONF_ALWAYS_ADD_REVERSE_COMPOUNDS, Boolean.TRUE)); assertThat(config, hasEntry(CONF_LOWER_CASE_INPUT, Boolean.FALSE)); assertThat(config, hasEntry(CONF_MAX_COMBINE_WORD_LENGTH, 10)); assertThat(config, hasEntry(CONF_MIN_SUGGESTION_FREQ, 2)); assertThat(config, hasEntry(CONF_MORPHOLOGY, Morphology.GERMAN.name())); final Map<String, Object> decompound = (Map<String, Object>) config.get(CONF_DECOMPOUND); assertThat(decompound, hasEntry(CONF_DECOMPOUND_VERIFY_COLLATION, Boolean.FALSE)); assertThat(decompound, hasEntry(CONF_DECOMPOUND_MAX_EXPANSIONS, 4)); final List<String> reverseCompoundTriggerWords = (List<String>) config.get(CONF_REVERSE_COMPOUND_TRIGGER_WORDS); assertThat(reverseCompoundTriggerWords, contains("from", "of")); } }
{ "content_hash": "0b2f0bb48066d72a84f1af2144f32dde", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 120, "avg_line_length": 46.19090909090909, "alnum_prop": 0.7203306435740996, "repo_name": "renekrie/querqy", "id": "e3011cd9eea0e44e4b7968e50a165411bcd4b383", "size": "5081", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "querqy-for-lucene/querqy-solr/src/test/java/querqy/solr/rewriter/wordbreak/WordBreakCompoundConfigRequestBuilderTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1036697" } ], "symlink_target": "" }
package org.apache.pig.newplan.logical.rules; import java.io.IOException; import org.apache.hadoop.mapreduce.Job; import org.apache.pig.PigException; import org.apache.pig.ResourceSchema; import org.apache.pig.StoreFuncInterface; import org.apache.pig.backend.hadoop.datastorage.ConfigurationUtil; import org.apache.pig.impl.PigContext; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.newplan.DepthFirstWalker; import org.apache.pig.newplan.OperatorPlan; import org.apache.pig.newplan.PlanWalker; import org.apache.pig.newplan.logical.Util; import org.apache.pig.newplan.logical.relational.LOCogroup; import org.apache.pig.newplan.logical.relational.LOStore; import org.apache.pig.newplan.logical.relational.LogicalPlan; import org.apache.pig.newplan.logical.relational.LogicalRelationalNodesVisitor; import org.apache.pig.newplan.logical.relational.LogicalRelationalOperator; import org.apache.pig.newplan.logical.rules.GroupByConstParallelSetter.GroupAllParallelSetterTransformer; import org.apache.pig.newplan.optimizer.Rule; import org.apache.pig.newplan.optimizer.Transformer; public class InputOutputFileValidator { private PigContext pigCtx; OperatorPlan plan; public InputOutputFileValidator(OperatorPlan plan, PigContext pigContext) { pigCtx = pigContext; this.plan = plan; } public void validate() throws FrontendException { InputOutputFileVisitor visitor = new InputOutputFileVisitor(plan); visitor.visit(); } class InputOutputFileVisitor extends LogicalRelationalNodesVisitor { protected InputOutputFileVisitor(OperatorPlan plan) throws FrontendException { super(plan, new DepthFirstWalker(plan)); } @Override public void visit(LOStore store) throws FrontendException { StoreFuncInterface sf = store.getStoreFunc(); String outLoc = store.getOutputSpec().getFileName(); int errCode = 2116; String validationErrStr ="Output Location Validation Failed for: '" + outLoc ; Job dummyJob; try { if(store.getSchema() != null){ sf.checkSchema(new ResourceSchema(Util.translateSchema(store.getSchema()), store.getSortInfo())); } dummyJob = new Job(ConfigurationUtil.toConfiguration(pigCtx.getProperties())); sf.setStoreLocation(outLoc, dummyJob); } catch (IOException ioe) { if(ioe instanceof PigException){ errCode = ((PigException)ioe).getErrorCode(); } String exceptionMsg = ioe.getMessage(); validationErrStr += (exceptionMsg == null) ? "" : " More info to follow:\n" +exceptionMsg; throw new FrontendException(validationErrStr, errCode, pigCtx.getErrorSource(), ioe); } validationErrStr += " More info to follow:\n"; try { sf.getOutputFormat().checkOutputSpecs(dummyJob); } catch (IOException ioe) { byte errSrc = pigCtx.getErrorSource(); switch(errSrc) { case PigException.BUG: errCode = 2002; break; case PigException.REMOTE_ENVIRONMENT: errCode = 6000; break; case PigException.USER_ENVIRONMENT: errCode = 4000; break; } validationErrStr += ioe.getMessage(); throw new FrontendException(validationErrStr, errCode, errSrc, ioe); } catch (InterruptedException ie) { validationErrStr += ie.getMessage(); throw new FrontendException(validationErrStr, errCode, pigCtx.getErrorSource(), ie); } } } }
{ "content_hash": "db028acd8eec7a7ea388c15f49e35bfa", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 133, "avg_line_length": 42.59139784946237, "alnum_prop": 0.641504670537743, "repo_name": "simplegeo/hadoop-pig", "id": "0ab2d403439411dc43a46cfe2c2c6543b040dcb6", "size": "4766", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/apache/pig/newplan/logical/rules/InputOutputFileValidator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "13034958" }, { "name": "JavaScript", "bytes": "35260" }, { "name": "Perl", "bytes": "2766" }, { "name": "Shell", "bytes": "32379" } ], "symlink_target": "" }
import json import traceback import typing import disnake from disnake.ext import commands from utils.command.clip import * from utils.command.commandargs import * from utils.tools.globals import botdata, logger, settings from utils.tools.helpers import * # Note: This code used to be in mangobyte.py so look there for more history with open(settings.resource("json/deprecated_commands.json"), "r") as f: deprecated_commands = json.loads(f.read()) # leave this in for a bit for now cuz owner commands still use it async def on_prefix_command_error(ctx: commands.Context, error: commands.CommandError): bot: commands.Bot bot = ctx.bot cmdpfx = "?" try: if isinstance(error, commands.CommandNotFound): if ctx.guild and not botdata.guildinfo(ctx).deprecationhints: return # if deprecation hints are disabled, do nothing. cmd = ctx.message.content[1:].split(" ")[0] slash_command_names = list(map(lambda c: c.name, slash_command_expand(bot.slash_commands))) if cmd in deprecated_commands: logger.info(f"deprecated command '{cmd}' attempted") if deprecated_commands[cmd].startswith("_"): await ctx.send(f"`{cmdpfx}{cmd}` has been deprecated. {deprecated_commands[cmd][1:]}") return await ctx.send(f"`{cmdpfx}{cmd}` has been deprecated. Try `/{deprecated_commands[cmd]}` instead.") return elif cmd in slash_command_names: logger.info(f"deprecated command '{cmd}' attempted") await ctx.send(f"`{cmdpfx}{cmd}` has been moved to a slash command. Try typing `/{cmd}`.") return elif cmd == "" or cmd.startswith("?") or cmd.startswith("!"): return # These were probably not meant to be commands if cmd.lower() in bot.commands: new_message = ctx.message new_message.content = cmdpfx + cmd.lower() + ctx.message.content[len(cmd) + 1:] await bot.process_commands(new_message) elif isinstance(error, CustomBadArgument): await error.user_error.send_self(ctx, botdata) elif isinstance(error, commands.BadArgument): await ctx.send("Thats the wrong type of argument for that command.") elif isinstance(error, commands.MissingRequiredArgument): await ctx.send("Missing a required argument for that command.") # should never get triggered for public facing commands else: await command_error_handler(ctx, error) except disnake.errors.Forbidden: try: await ctx.author.send("Looks like I don't have permission to talk in that channel, sorry") except disnake.errors.Forbidden: logger.error(f"double forbidden for message {ctx.message.id}") async def on_app_command_error(inter: disnake.Interaction, error: commands.CommandError): await command_error_handler(inter, error) async def command_error_handler(ctx_inter: InterContext, error: commands.CommandError): bot: commands.AutoShardedBot bot = ctx_inter.bot cmd_log_data = {} if isinstance(ctx_inter, commands.Context): cmd_log_data["message_id"] = ctx_inter.message.id identifier = f"[prefix_command: {ctx_inter.message.id}]" else: cmd_log_data["inter_id"] = ctx_inter.id identifier = f"[interaction: {ctx_inter.id}]" logger.event("command_finished", cmd_log_data) try: if isinstance(error, commands.CheckFailure): emoji_dict = read_json(settings.resource("json/emoji.json")) command = None if isinstance(ctx_inter, disnake.ApplicationCommandInteraction): command = slash_command_name(ctx_inter) elif isinstance(ctx_inter, commands.Context): command = ctx_inter.command emoji = None message = None if command and botdata.guildinfo(ctx_inter).is_disabled(command): emoji = bot.get_emoji(emoji_dict["command_disabled"]) message = "This command is disabled for this guild" else: emoji = bot.get_emoji(emoji_dict["unauthorized"]) message = "You're not authorized to run this command" if isinstance(ctx_inter, commands.Context): await ctx_inter.message.add_reaction(emoji) else: await ctx_inter.send(f"{emoji} {message}") return # The user does not have permissions elif isinstance(error, CustomBadArgument): await error.user_error.send_self(ctx_inter, botdata) elif isinstance(error, commands.CommandInvokeError) and isinstance(error.original, disnake.errors.Forbidden): await print_missing_perms(ctx_inter, error) elif isinstance(error, commands.CommandInvokeError) and isinstance(error.original, disnake.errors.HTTPException): await ctx_inter.send("Looks like there was a problem with discord just then. Try again in a bit.") logger.error(f"discord http exception triggered {identifier}") elif isinstance(error, commands.CommandInvokeError) and isinstance(error.original, HttpError): await error.original.send_self(ctx_inter, botdata) if error.original.code != 404: # 404 errors are not worth reporting logger.warning(f"http error {error.original.code} on {identifier} for url: {error.original.url}") elif isinstance(error, commands.CommandInvokeError) and isinstance(error.original, UserError): await error.original.send_self(ctx_inter, botdata) elif isinstance(error, commands.ConversionError) and isinstance(error.original, UserError): await error.original.send_self(ctx_inter, botdata) elif isinstance(error, commands.ConversionError) and isinstance(error.original, CustomBadArgument): await error.original.user_error.send_self(ctx_inter, botdata) else: await ctx_inter.send("Uh-oh, sumthin dun gone wrong 😱") trace_string = await report_error(ctx_inter, error, skip_lines=4) if settings.debug: if len(trace_string) > 1950: trace_string = "TRACETOOBIG:" + trace_string[len(trace_string) - 1950:] await ctx_inter.send(f"```{trace_string}```") except disnake.errors.Forbidden: try: await ctx_inter.author.send("Looks like I don't have permission to talk in that channel, sorry") except disnake.errors.Forbidden: pass except Exception as e: logging.error(f"uncaught error {e} when processing CommandError") await report_error(ctx_inter, e, skip_lines=0) error_file = "errors.json" async def print_missing_perms(ctx_inter: InterContext, error): if not (ctx_inter.guild): await ctx_inter.send("Uh-oh, sumthin dun gone wrong 😱") trace_string = await report_error(ctx_inter, error, skip_lines=0) my_perms = ctx_inter.channel.permissions_for(ctx_inter.guild.me) perms_strings = read_json(settings.resource("json/permissions.json")) perms = [] for i in range(0, 32): if ((settings.permissions >> i) & 1) and not ((settings.permissions >> i) & 1): words = perms_strings["0x{:08x}".format(1 << i)].split("_") for i in range(0, len(words)): words[i] = f"**{words[i][0] + words[i][1:].lower()}**" perms.append(" ".join(words)) if perms: await ctx_inter.send("Looks like I'm missin' these permissions 😢:\n" + "\n".join(perms)) else: await ctx_inter.send(f"Looks like I'm missing permissions 😢. Have an admin giff me back my permissions, or re-invite me to the server using this invite link: {settings.invite_link}") async def report_error(ctx_inter_msg: typing.Union[InterContext, disnake.Message, str], error, skip_lines=2): try: if isinstance(error, disnake.errors.InteractionTimedOut): trace = [ "InteractionTimedOut: took longer than 3 seconds" ] else: if hasattr(error, "original"): raise error.original else: raise error except: trace = traceback.format_exc().replace("\"", "'").split("\n") if skip_lines > 0 and len(trace) >= (2 + skip_lines): del trace[1:(skip_lines + 1)] trace = [x for x in trace if x] # removes empty lines trace_string = "\n".join(trace) err_info = {} if isinstance(ctx_inter_msg, commands.Context): message = ctx_inter_msg.message err_info["source"] = message.content err_info["message_id"] = message.id err_info["author_id"] = message.author.id elif isinstance(ctx_inter_msg, disnake.Interaction): err_info["source"] = stringify_slash_command(ctx_inter_msg) err_info["inter_id"] = ctx_inter_msg.id err_info["author_id"] = ctx_inter_msg.author.id elif isinstance(ctx_inter_msg, disnake.Message): # is a message message = ctx_inter_msg err_info["source"] = message.content err_info["message_id"] = message.id err_info["author_id"] = message.author.id else: # Is a string err_info["source"] = ctx_inter_msg err_info = "\n".join(map(lambda kv: f"{kv[0]}: {kv[1]}", err_info.items())) logger.error(f"{err_info}\n{trace_string}\n") return trace_string
{ "content_hash": "937fe9afddec2aa5a93e76f012137bcd", "timestamp": "", "source": "github", "line_count": 194, "max_line_length": 184, "avg_line_length": 43.29896907216495, "alnum_prop": 0.7197619047619047, "repo_name": "mdiller/MangoByte", "id": "2f1c30c0e051813756ffa551f1d4482eb6445844", "size": "8412", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "utils/other/errorhandling.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "374065" } ], "symlink_target": "" }
package com.davidjohnburrowes.formats.jpeg.marker; import com.davidjohnburrowes.format.jpeg.data.GenericSegment; import com.davidjohnburrowes.format.jpeg.marker.JpgNSegment; import com.davidjohnburrowes.formats.jpeg.test.TestUtils; import java.io.IOException; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class JpgNSegmentTest { private TestUtils utils; private JpgNSegment segment; @Before public void setUp() { utils = new TestUtils(); segment = new JpgNSegment(JpgNSegment.FIRST_MARKERID); } @Test public void testThatHasTheRightMarkerByDefault() { assertEquals(JpgNSegment.FIRST_MARKERID, segment.getMarkerId()); } @Test(expected=IllegalArgumentException.class) public void constructor_passedInvalidMarkerId_throwsException() { new JpgNSegment(JpgNSegment.LAST_MARKERID + 2); } @Test public void getBytes_returnsTheBytes() throws IOException { segment.read(utils.makeInputStream("00 0C" + "01 02 03 04 05 06 07 08 09 0a")); assertArrayEquals("bytes", utils.makeByteArray("01 02 03 04 05 06 07 08 09 0a"), segment.getBytes()); } @Test public void setBytes_changesTheButes() throws IOException { segment.read(utils.makeInputStream("00 0C" + "01 02 03 04 05 06 07 08 09 0a")); segment.setBytes(new byte[] { 10, 11, 12 }); assertArrayEquals("bytes", utils.makeByteArray("0a 0b 0c"), segment.getBytes()); } @Test public void twoEqualSegmentsEqual() throws IOException { segment.read(utils.makeInputStream("00 0C" + "01 02 03 04 05 06 07 08 09 0a")); JpgNSegment other = new JpgNSegment(JpgNSegment.FIRST_MARKERID); other.setBytes(utils.makeByteArray("01 02 03 04 05 06 07 08 09 0a")); assertEquals("segment", other, segment); } @Test public void unequalSegmentsAreNotEqual() throws IOException { segment.read(utils.makeInputStream("00 0C" + "01 02 03 04 05 06 07 08 09 0a")); JpgNSegment other = new JpgNSegment(JpgNSegment.FIRST_MARKERID); other.setBytes(utils.makeByteArray("FF FE FD 04 05 06 07 08 09 0a")); assertFalse("segment", other.equals(segment)); } @Test public void equals_withGenericSegment_notEqual() throws IOException { GenericSegment other = new GenericSegment(JpgNSegment.FIRST_MARKERID); assertFalse(segment.equals(other)); } @Test public void jpgNSegmentsEqual() throws IOException { assertTrue(segment.equals(new JpgNSegment(JpgNSegment.FIRST_MARKERID))); } @Test public void jpgNSegmentNotEqualToSomeOtherObject() throws IOException { assertFalse(segment.equals(new Object())); } @Test public void jpgNSegmentWithDifferentMarkersNotEqualToOther() throws IOException { assertFalse(segment.equals(new JpgNSegment(JpgNSegment.FIRST_MARKERID + 2))); } }
{ "content_hash": "db287ba50826f619d509ce8dd5189673", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 82, "avg_line_length": 28.677083333333332, "alnum_prop": 0.7482746095168906, "repo_name": "bodawei/JPEGFile", "id": "bd26a1db8a1b4468e013742ac9990499ee5d428b", "size": "3353", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/com/davidjohnburrowes/formats/jpeg/marker/JpgNSegmentTest.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "544296" }, { "name": "Shell", "bytes": "1579" } ], "symlink_target": "" }
In general, the google-cloud-asset library uses [Service Account](https://cloud.google.com/iam/docs/creating-managing-service-accounts) credentials to connect to Google Cloud services. When running within [Google Cloud Platform environments](#google-cloud-platform-environments) the credentials will be discovered automatically. When running on other environments, the Service Account credentials can be specified by providing the path to the [JSON keyfile](https://cloud.google.com/iam/docs/managing-service-account-keys) for the account (or the JSON itself) in [environment variables](#environment-variables). Additionally, Cloud SDK credentials can also be discovered automatically, but this is only recommended during development. ## Quickstart 1. [Create a service account and credentials](#creating-a-service-account). 2. Set the [environment variable](#environment-variables). ```sh export ASSET_CREDENTIALS=path/to/keyfile.json ``` 3. Initialize the client. ```ruby require "google/cloud/asset" client = Google::Cloud::Asset.asset_service ``` ## Credential Lookup The google-cloud-asset library aims to make authentication as simple as possible, and provides several mechanisms to configure your system without requiring **Service Account Credentials** directly in code. **Credentials** are discovered in the following order: 1. Specify credentials in method arguments 2. Specify credentials in configuration 3. Discover credentials path in environment variables 4. Discover credentials JSON in environment variables 5. Discover credentials file in the Cloud SDK's path 6. Discover GCP credentials ### Google Cloud Platform environments When running on Google Cloud Platform (GCP), including Google Compute Engine (GCE), Google Kubernetes Engine (GKE), Google App Engine (GAE), Google Cloud Functions (GCF) and Cloud Run, **Credentials** are discovered automatically. Code should be written as if already authenticated. ### Environment Variables The **Credentials JSON** can be placed in environment variables instead of declaring them directly in code. Each service has its own environment variable, allowing for different service accounts to be used for different services. (See the READMEs for the individual service gems for details.) The path to the **Credentials JSON** file can be stored in the environment variable, or the **Credentials JSON** itself can be stored for environments such as Docker containers where writing files is difficult or not encouraged. The environment variables that google-cloud-asset checks for credentials are configured on the service Credentials class (such as `::Google::Cloud::Asset::V1::AssetService::Credentials`): * `ASSET_CREDENTIALS` - Path to JSON file, or JSON contents * `ASSET_KEYFILE` - Path to JSON file, or JSON contents * `GOOGLE_CLOUD_CREDENTIALS` - Path to JSON file, or JSON contents * `GOOGLE_CLOUD_KEYFILE` - Path to JSON file, or JSON contents * `GOOGLE_APPLICATION_CREDENTIALS` - Path to JSON file ```ruby require "google/cloud/asset" ENV["ASSET_CREDENTIALS"] = "path/to/keyfile.json" client = Google::Cloud::Asset.asset_service ``` ### Configuration The path to the **Credentials JSON** file can be configured instead of storing it in an environment variable. Either on an individual client initialization: ```ruby require "google/cloud/asset" client = Google::Cloud::Asset.asset_service do |config| config.credentials = "path/to/keyfile.json" end ``` Or globally for all clients: ```ruby require "google/cloud/asset" Google::Cloud::Asset.configure do |config| config.credentials = "path/to/keyfile.json" end client = Google::Cloud::Asset.asset_service ``` ### Cloud SDK This option allows for an easy way to authenticate during development. If credentials are not provided in code or in environment variables, then Cloud SDK credentials are discovered. To configure your system for this, simply: 1. [Download and install the Cloud SDK](https://cloud.google.com/sdk) 2. Authenticate using OAuth 2.0 `$ gcloud auth application-default login` 3. Write code as if already authenticated. **NOTE:** This is _not_ recommended for running in production. The Cloud SDK *should* only be used during development. ## Creating a Service Account Google Cloud requires **Service Account Credentials** to connect to the APIs. You will use the **JSON key file** to connect to most services with google-cloud-asset. If you are not running this client within [Google Cloud Platform environments](#google-cloud-platform-environments), you need a Google Developers service account. 1. Visit the [Google Cloud Console](https://console.cloud.google.com/project). 2. Create a new project or click on an existing project. 3. Activate the menu in the upper left and select **APIs & Services**. From here, you will enable the APIs that your application requires. *Note: You may need to enable billing in order to use these services.* 4. Select **Credentials** from the side navigation. Find the "Create credentials" drop down near the top of the page, and select "Service account" to be guided through downloading a new JSON key file. If you want to re-use an existing service account, you can easily generate a new key file. Just select the account you wish to re-use, click the pencil tool on the right side to edit the service account, select the **Keys** tab, and then select **Add Key**. The key file you download will be used by this library to authenticate API requests and should be stored in a secure location.
{ "content_hash": "30cde66a725623b23384bf0bbde7e57f", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 87, "avg_line_length": 37.16107382550336, "alnum_prop": 0.7762326169405815, "repo_name": "dazuma/google-cloud-ruby", "id": "71048db9f83789589a7478c93c96ed1e85503563", "size": "5555", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "google-cloud-asset/AUTHENTICATION.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "23930" }, { "name": "CSS", "bytes": "1422" }, { "name": "DIGITAL Command Language", "bytes": "2216" }, { "name": "Go", "bytes": "1321" }, { "name": "HTML", "bytes": "66414" }, { "name": "JavaScript", "bytes": "1862" }, { "name": "Ruby", "bytes": "103941624" }, { "name": "Shell", "bytes": "19653" } ], "symlink_target": "" }
""" Usage: call with <filename> <typename> """ import sys import clang.cindex def find_typerefs(node, typename): """ Find all references to the type named 'typename' """ if node.kind.is_reference(): ref_node = clang.cindex.Cursor_ref(node) if ref_node.spelling == typename: print 'Found %s [line=%s, col=%s]' % ( typename, node.location.line, node.location.column) # Recurse for children of this node for c in node.get_children(): find_typerefs(c, typename) index = clang.cindex.Index.create() tu = index.parse(sys.argv[1]) print 'Translation unit:', tu.spelling find_typerefs(tu.cursor, sys.argv[2])
{ "content_hash": "3198f5c091c2511ba44b8b5a0a929c86", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 67, "avg_line_length": 29.434782608695652, "alnum_prop": 0.6425406203840472, "repo_name": "sheijk/Zomp", "id": "3e650aa07c5a105bca1216961771b9be540c200d", "size": "699", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/clang_api/lookup_symbol.py", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "318385" }, { "name": "C++", "bytes": "488073" }, { "name": "Emacs Lisp", "bytes": "54683" }, { "name": "GLSL", "bytes": "7344" }, { "name": "Gnuplot", "bytes": "237" }, { "name": "HTML", "bytes": "821" }, { "name": "Makefile", "bytes": "63814" }, { "name": "OCaml", "bytes": "538313" }, { "name": "Objective-C", "bytes": "9294" }, { "name": "Python", "bytes": "1211" }, { "name": "Shell", "bytes": "18996" }, { "name": "Standard ML", "bytes": "583" } ], "symlink_target": "" }
package main import ( "bytes" "fmt" "image" "image/color" "image/draw" "image/png" "math" "app" "gopnik" "gproj" "perflog" "github.com/davecgh/go-spew/spew" "github.com/orofarne/freetype-go/freetype" "github.com/orofarne/freetype-go/freetype/truetype" ) func getTileColor(perfData []perflog.PerfLogEntry, coord gopnik.TileCoord, maxTime float64) (col color.Color, renderTimeSeconds float64) { metaCoord := app.App.Metatiler().TileToMetatile(&coord) for _, entry := range perfData { if entry.Coord.Equals(&metaCoord) { col := color.RGBA{ R: 255, G: 10, B: 10, A: uint8((entry.RenderTime.Seconds() / maxTime) * 200), } return col, entry.RenderTime.Seconds() } } return color.Transparent, -1.0 } func convertCoordByZoom(coord gopnik.TileCoord, zoom uint64) gopnik.TileCoord { lat, lon, _ := gproj.FromCoordToLL(coord) return gproj.FromLLToCoord(lat, lon, zoom) } func getMaxTime(perfData []perflog.PerfLogEntry, zoom uint64) float64 { var maxTime float64 = 0.0 for _, entry := range perfData { if entry.Coord.Zoom == zoom && entry.RenderTime.Seconds() > maxTime { maxTime = entry.RenderTime.Seconds() } } return maxTime } func convertTime(t float64) string { if t < 0. { return "--" } if t >= 86400. { return fmt.Sprintf("%.2fd", t/86400.) } if t >= 3600. { return fmt.Sprintf("%.2fh", t/3600.) } if t >= 60. { return fmt.Sprintf("%.2fm", t/60.) } return fmt.Sprintf("%.2fs", t) } func drawTime(img *image.RGBA, t float64) error { ctx := freetype.NewContext() fntData, err := Asset("public/fonts/UbuntuMono-R.ttf") if err != nil { return err } fnt, err := truetype.Parse(fntData) if err != nil { return err } ctx.SetFont(fnt) ctx.SetFontSize(22) ctx.SetSrc(&image.Uniform{color.Black}) ctx.SetDst(img) ctx.SetClip(img.Bounds()) pt := freetype.Pt(30, 30) tStr := convertTime(t) _, err = ctx.DrawString(tStr, pt) return err } func genPerfTile(perfData []perflog.PerfLogEntry, coord gopnik.TileCoord, zoom uint64) ([]byte, error) { // Get max time maxTime := getMaxTime(perfData, zoom) // Convert coordinates coordMin := convertCoordByZoom(coord, zoom) coord2 := gopnik.TileCoord{ X: coord.X + coord.Size, Y: coord.Y + coord.Size, Zoom: coord.Zoom, Size: coord.Size, } coordMax := convertCoordByZoom(coord2, zoom) // Find all subtiles bounds := image.Rect(0, 0, 256, 256) img := image.NewRGBA(bounds) mult := 256 / math.Pow(2, float64(zoom-coord.Zoom)) maxTimeS := float64(-1.) for x := coordMin.X; x < coordMax.X || (x == coordMin.X && x == coordMax.X); x += coord.Size { for y := coordMin.Y; y < coordMax.Y || (y == coordMin.Y && y == coordMax.Y); y += coord.Size { c := gopnik.TileCoord{ X: x, Y: y, Zoom: zoom, Size: coord.Size, } col, renderTime := getTileColor(perfData, c, maxTime) if renderTime > maxTimeS { maxTimeS = renderTime } rect := image.Rect( int(math.Max(float64((c.X-coordMin.X)/c.Size)*mult, 0)), int(math.Max(float64((c.Y-coordMin.Y)/c.Size)*mult, 0)), int(math.Min(float64((c.X-coordMin.X)/c.Size+1)*mult, 256)), int(math.Min(float64((c.Y-coordMin.Y)/c.Size+1)*mult, 256))) draw.Draw(img, rect, &image.Uniform{col}, image.ZP, draw.Src) } } drawErr := drawTime(img, maxTimeS) if drawErr != nil { spew.Dump(drawErr) return nil, drawErr } outbuf := bytes.NewBuffer(nil) err := png.Encode(outbuf, img) if err != nil { return nil, err } return outbuf.Bytes(), nil }
{ "content_hash": "e06b1f653bf78d1b666f34e80b2e2e42", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 138, "avg_line_length": 24.291666666666668, "alnum_prop": 0.6515151515151515, "repo_name": "sputnik-maps/gopnik", "id": "2155c2593b69aac2aaaeff7da40cece8c10dc511", "size": "3498", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/gopnikperf/tiles.go", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C++", "bytes": "20855" }, { "name": "CMake", "bytes": "31728" }, { "name": "CSS", "bytes": "10401" }, { "name": "Go", "bytes": "178308" }, { "name": "HTML", "bytes": "837" }, { "name": "JavaScript", "bytes": "1434" }, { "name": "Protocol Buffer", "bytes": "374" }, { "name": "Shell", "bytes": "5753" }, { "name": "Thrift", "bytes": "996" } ], "symlink_target": "" }
FROM balenalib/cubox-i-ubuntu:cosmic-build # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.5.10 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.0.1 ENV SETUPTOOLS_VERSION 56.0.0 RUN set -x \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \ && echo "4abc87b995e08c143de14f26d8ab6ffd9017aad400bf91bc36a802efda7fe27a Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # install "virtualenv", since the vast majority of users of this image will want it RUN pip3 install --no-cache-dir virtualenv ENV PYTHON_DBUS_VERSION 1.2.8 # install dbus-python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ libdbus-1-dev \ libdbus-glib-1-dev \ && rm -rf /var/lib/apt/lists/* \ && apt-get -y autoremove # install dbus-python RUN set -x \ && mkdir -p /usr/src/dbus-python \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \ && gpg --verify dbus-python.tar.gz.asc \ && tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \ && rm dbus-python.tar.gz* \ && cd /usr/src/dbus-python \ && PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \ && make -j$(nproc) \ && make install -j$(nproc) \ && cd / \ && rm -rf /usr/src/dbus-python # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu cosmic \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.5.10, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "614181024bc68e6e35b619d554e5fe84", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 711, "avg_line_length": 50.62105263157895, "alnum_prop": 0.7038885423164899, "repo_name": "nghiant2710/base-images", "id": "9e3ac42cf097544b1e2c1d55ef05135d5f7ab14b", "size": "4830", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/python/cubox-i/ubuntu/cosmic/3.5.10/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
/* * ControllerBase */ define(function () { console.log('SKIN: controllerBase called'); function controllerBase(id) { this.id = id; }; controllerBase.prototype = { setStoreName: function (storeName) { console.log('SKIN: controllerBase setStoreName(storeName) called'); this.storeName = storeName; }, setAppController: function (appController) { console.log('SKIN: controllerBase setAppController(appController) called'); this.appController = appController; this.appController.setStoreName(this.storeName); this.appController.setConfig(this.config); this.appController.setServiceBus(this.serviceBus); }, setAppEvent: function (appEvent) { console.log('SKIN: controllerBase setAppEvent(appEvent) called'); this.appEvent = appEvent; this.appController.setAppEvent(appEvent); }, setAppService: function (appService) { console.log('SKIN: controllerBase setAppService(appService) called'); this.appService = appService; this.appController.setAppService(appService); }, setApp: function (app) { console.log('SKIN: controllerBase setApp(app) called'); this.app = app; this.appController.setApp(app); }, loadApp: function (id) { console.log('SKIN: controllerBase loadApp(id) called'); this.appController.loadApp(id); }, subscribeAppService: function() { console.log('SKIN: controllerBase subscribeAppService() called'); this.appController.subscribeAppService(); }, setConfig: function (config) { console.log('SKIN: controllerBase setConfig(config) called'); this.config = config; }, setServiceBus: function (serviceBus) { console.log('SKIN: controllerBase setServiceBus(serviceBus) called'); this.serviceBus = serviceBus; }, setViewController: function (viewController) { console.log('SKIN: controllerBase setViewController(viewController) called'); this.viewController = viewController; this.viewController.setStoreName(this.storeName); this.viewController.setConfig(this.config); this.viewController.setServiceBus(this.serviceBus); }, setViewEvent: function (viewEvent) { console.log('SKIN: controllerBase setViewEvent(viewEvent) called'); this.viewEvent = viewEvent; this.viewController.setViewEvent(viewEvent); }, setViewService: function (viewService) { console.log('SKIN: controllerBase setViewService(viewService) called'); this.viewService = viewService; this.viewController.setViewService(viewService); }, setView: function (view) { console.log('SKIN: controllerBase setView(view) called'); this.view = view; this.viewController.setView(view); }, loadView: function (id) { console.log('SKIN: controllerBase loadView(id) called'); this.viewController.loadView(id); }, renderView: function (elementId) { console.log('SKIN: controllerBase renderView(elementId) called'); this.viewController.renderView(elementId); }, subscribeViewService: function() { console.log('SKIN: controllerBase subscribeViewService() called'); this.viewController.subscribeViewService(); } }; return controllerBase; });
{ "content_hash": "3b8de17c3f48f0c23c1a4f24ea31d076", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 81, "avg_line_length": 37.57954545454545, "alnum_prop": 0.6894466283640762, "repo_name": "vanHeemstraSystems/skin", "id": "5edb63892fd41d8d6f0308825a5f51bc5abef18c", "size": "3307", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pre-public/js/app/controller/Base.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "928119" }, { "name": "PHP", "bytes": "482" }, { "name": "Shell", "bytes": "222" } ], "symlink_target": "" }
/*jslint white: true, browser: true, devel: true, onevar: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, strict: true, newcap: true, immed: true */ /*global Ext, Rpc, Rhino */ "use strict"; Ext.namespace('Rhino.Security'); Rhino.Security.UsersGroupSearchPanel = Ext.extend(Ext.Panel, { initComponent: function () { var _this = this, _fireEditItemEvent = function (items) { Ext.each(items, function (item) { _this.fireEvent('edititem', _this, item); }); }, _fireNewItemEvent = function () { _this.fireEvent('newitem', _this); }, _onGridPanelRowDblClick = function (grid, rowIndex, event) { var item = grid.getStore().getAt(rowIndex).data; _fireEditItemEvent(item); }, _searchFormPanel = new Rhino.Security.UsersGroupSearchFormPanel({ title: 'Search Filters', region: 'north', autoHeight: true, collapsible: true, collapsed: true, titleCollapse: true, floatable: false }), _onStartLoad = function () { _this.el.mask('Loading...', 'x-mask-loading'); }, _onEndLoad = function () { _this.el.unmask(); }, _store = new Ext.data.Store({ autoDestroy: true, proxy: new Rpc.JsonPostHttpProxy({ url: 'UsersGroup/Search' }), remoteSort: true, reader: new Rhino.Security.UsersGroupJsonReader(), listeners: { beforeload: _onStartLoad, load: _onEndLoad, exception: _onEndLoad } }), _pagingToolbar = new Ext.PagingToolbar({ store: _store, displayInfo: true, pageSize: 25, prependButtons: true }), _gridPanel = new Rhino.Security.UsersGroupGridPanel({ region: 'center', store: _store, bbar: _pagingToolbar, listeners: { rowdblclick: _onGridPanelRowDblClick } }), _getSelectedItems = function () { var sm = _gridPanel.getSelectionModel(), selectedItems = []; if (sm.getCount() > 0) { Ext.each(sm.getSelections(), function (item) { selectedItems.push(item.data); }); return selectedItems; } return null; }, _getSelectedStringIds = function (items) { if (items && items.length > 0) { var selectedStringIds = []; Ext.each(items, function (item) { selectedStringIds.push(item.StringId); }); return selectedStringIds; } return null; }, _onSearchButtonClick = function (b, e) { var params = _searchFormPanel.getForm().getFieldValues(); Ext.apply(_gridPanel.getStore().baseParams, params); _gridPanel.getStore().load({ params: { start: 0, limit: _pagingToolbar.pageSize } }); }, _onNewButtonClick = function () { _fireNewItemEvent(); }, _onEditButtonClick = function () { var selectedItems = _getSelectedItems(); if (!selectedItems) { return; } _fireEditItemEvent(selectedItems); }, _onDeleteButtonClick = function () { var selectedItems = _getSelectedItems(); if (!selectedItems) { return; } Ext.MessageBox.confirm('Delete', 'Are you sure?', function (buttonId) { if (buttonId !== 'yes') { return; } _this.el.mask('Saving...', 'x-mask-loading'); Rpc.call({ url: 'UsersGroup/Delete', params: { stringIds: _getSelectedStringIds(selectedItems) }, success: function (result) { if (result.success) { _pagingToolbar.doRefresh(); } else { Ext.MessageBox.show({ msg: result.errors.operationError, icon: Ext.MessageBox.ERROR, buttons: Ext.MessageBox.OK }); } }, callback: function () { _this.el.unmask(); } }); }); }; Ext.apply(_this, { layout: 'border', border: false, items: [_searchFormPanel, _gridPanel], tbar: [ { text: 'Search', handler: _onSearchButtonClick, icon: 'images/zoom.png', cls: 'x-btn-text-icon' }, { text: 'New', handler: _onNewButtonClick, icon: 'images/add.png', cls: 'x-btn-text-icon' }, { text: 'Edit', handler: _onEditButtonClick, icon: 'images/pencil.png', cls: 'x-btn-text-icon' }, { text: 'Delete', handler: _onDeleteButtonClick, icon: 'images/delete.png', cls: 'x-btn-text-icon' } ] }); Rhino.Security.UsersGroupSearchPanel.superclass.initComponent.apply(_this, arguments); _this.addEvents('edititem', 'newitem'); } }); Ext.reg('Rhino.Security.UsersGroupSearchPanel', Rhino.Security.UsersGroupSearchPanel);
{ "content_hash": "875ec25f481a1c68a3edf4236c873071", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 178, "avg_line_length": 29.17763157894737, "alnum_prop": 0.616685456595265, "repo_name": "nexida/Rhino-Security-Administration", "id": "08303a0a26775e38668c538e558d017b0c50fa21", "size": "4435", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Rhino.Security.Mgmt/js/Rhino.Security.UsersGroupSearchPanel.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "6143" }, { "name": "C#", "bytes": "101303" }, { "name": "JavaScript", "bytes": "93417" } ], "symlink_target": "" }
// Dummy hardware interface // Author: Max Schwarz <max.schwarz@uni-bonn.de> #ifndef DUMMYINTERFACE_H #define DUMMYINTERFACE_H #include <robotcontrol/hw/hardwareinterface.h> #include <boost/circular_buffer.hpp> namespace robotcontrol { /** * @brief Dummy hardware interface * * This provides a simple loopback hardware interface. The joint commands * are simply stored and returned as position feedback. **/ class DummyInterface : public HardwareInterface { public: DummyInterface(); virtual ~DummyInterface(); virtual bool init(RobotModel* model); virtual boost::shared_ptr< Joint > createJoint(const std::string& name); virtual void getDiagnostics(robotcontrol::DiagnosticsPtr ptr); virtual bool readJointStates(); virtual bool sendJointTargets(); virtual bool setStiffness(float torque); private: typedef boost::circular_buffer<std::vector<double> > DataBuf; DataBuf m_dataBuf; RobotModel* m_model; }; } #endif
{ "content_hash": "51f682d5ea1790eaae4a535522ccaa01", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 73, "avg_line_length": 22.975609756097562, "alnum_prop": 0.7632696390658175, "repo_name": "NimbRo/nimbro-op-ros", "id": "745541e642db1d1e1dec7b4e184d8946957eed81", "size": "942", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/nimbro_robotcontrol/hardware/robotcontrol/include/robotcontrol/hw/dummyinterface.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "9720" }, { "name": "C", "bytes": "2537509" }, { "name": "C++", "bytes": "2731714" }, { "name": "CSS", "bytes": "1647" }, { "name": "Lua", "bytes": "3969" }, { "name": "M", "bytes": "3800" }, { "name": "Matlab", "bytes": "13239" }, { "name": "Objective-C", "bytes": "34306" }, { "name": "Python", "bytes": "66379" }, { "name": "Shell", "bytes": "11137" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>SSD1306 OLED display driver: Class Members - Functions</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">SSD1306 OLED display driver &#160;<span id="projectnumber">1.8.2</span> </div> <div id="projectbrief">This library is developed to control SSD1306/SSD1331/SSD1351/IL9163/PCD8554 RGB i2c/spi LED displays</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> &#160; <h3><a id="index_a"></a>- a -</h3><ul> <li>above() : <a class="el" href="struct___nano_rect.html#af6e7e9f5270a121c6385657e250949e5">_NanoRect</a> </li> <li>AdafruitCanvasOps() : <a class="el" href="class_adafruit_canvas_ops.html#a05005ab6548a0d0c548096a1a206e917">AdafruitCanvasOps&lt; BPP &gt;</a> </li> <li>add() : <a class="el" href="class_sprite_pool.html#a60cdca785f31e9535d97485afb4b2202">SpritePool</a> </li> <li>addH() : <a class="el" href="struct___nano_rect.html#a5f4e0f0b9065e2135fa2271e19e4d326">_NanoRect</a> </li> <li>addV() : <a class="el" href="struct___nano_rect.html#afcf2745c8689550a9ec37f6112e62c1b">_NanoRect</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.13 </small></address> </body> </html>
{ "content_hash": "afeee1ecb51b6b4502fa08c3fb269181", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 132, "avg_line_length": 37.21111111111111, "alnum_prop": 0.691251119737235, "repo_name": "lexus2k/ssd1306", "id": "89f9f3bf31523260b230eaa563ad91098a4a3d0d", "size": "3349", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/functions_func.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "3577" }, { "name": "C", "bytes": "675386" }, { "name": "C++", "bytes": "181684" }, { "name": "CMake", "bytes": "390" }, { "name": "Makefile", "bytes": "5178" }, { "name": "Python", "bytes": "31917" }, { "name": "Shell", "bytes": "6136" } ], "symlink_target": "" }
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.rules.android; import com.google.auto.value.AutoValue; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.FilesToRunProvider; import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.analysis.TransitiveInfoCollection; import com.google.devtools.build.lib.analysis.TransitiveInfoProvider; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; import javax.annotation.Nullable; /** Description of the tools Blaze needs from an Android SDK. */ @AutoValue @Immutable public abstract class AndroidSdkProvider implements TransitiveInfoProvider { public static AndroidSdkProvider create( String buildToolsVersion, boolean aaptSupportsMainDexGeneration, Artifact frameworkAidl, Artifact androidJar, Artifact shrinkedAndroidJar, NestedSet<Artifact> androidBaseClasspathForJack, NestedSet<Artifact> javaBaseClasspathForJack, Artifact annotationsJar, Artifact mainDexClasses, FilesToRunProvider adb, FilesToRunProvider dx, FilesToRunProvider mainDexListCreator, FilesToRunProvider aidl, FilesToRunProvider aapt, FilesToRunProvider apkBuilder, @Nullable FilesToRunProvider apkSigner, FilesToRunProvider proguard, FilesToRunProvider zipalign, FilesToRunProvider jack, FilesToRunProvider jill, FilesToRunProvider resourceExtractor) { return new AutoValue_AndroidSdkProvider( buildToolsVersion, aaptSupportsMainDexGeneration, frameworkAidl, androidJar, shrinkedAndroidJar, androidBaseClasspathForJack, javaBaseClasspathForJack, annotationsJar, mainDexClasses, adb, dx, mainDexListCreator, aidl, aapt, apkBuilder, apkSigner, proguard, zipalign, jack, jill, resourceExtractor); } /** * Returns the Android SDK associated with the rule being analyzed or null if the Android SDK is * not specified. */ public static AndroidSdkProvider fromRuleContext(RuleContext ruleContext) { TransitiveInfoCollection androidSdkDep = ruleContext.getPrerequisite(":android_sdk", Mode.TARGET); AndroidSdkProvider androidSdk = androidSdkDep == null ? null : androidSdkDep.getProvider(AndroidSdkProvider.class); return androidSdk; } /** * Signals an error if the Android SDK cannot be found. */ public static boolean verifyPresence(RuleContext ruleContext) { if (fromRuleContext(ruleContext) == null) { ruleContext.ruleError( "No Android SDK found. Use the --android_sdk command line option to specify one."); return false; } return true; } /** The value of build_tools_version. May be null or empty. */ public abstract String getBuildToolsVersion(); public abstract boolean getAaptSupportsMainDexGeneration(); public abstract Artifact getFrameworkAidl(); public abstract Artifact getAndroidJar(); public abstract Artifact getShrinkedAndroidJar(); /** * Returns the set of jack files to be used as a base classpath for jack compilation of Android * rules, typically a Jack translation of the jar returned by {@link getAndroidJar}. */ public abstract NestedSet<Artifact> getAndroidBaseClasspathForJack(); /** * Returns the set of jack files to be used as a base classpath for jack compilation of Java * rules, typically a Jack translation of the jars in the Java bootclasspath. */ public abstract NestedSet<Artifact> getJavaBaseClasspathForJack(); public abstract Artifact getAnnotationsJar(); public abstract Artifact getMainDexClasses(); public abstract FilesToRunProvider getAdb(); public abstract FilesToRunProvider getDx(); public abstract FilesToRunProvider getMainDexListCreator(); public abstract FilesToRunProvider getAidl(); public abstract FilesToRunProvider getAapt(); public abstract FilesToRunProvider getApkBuilder(); @Nullable public abstract FilesToRunProvider getApkSigner(); public abstract FilesToRunProvider getProguard(); public abstract FilesToRunProvider getZipalign(); public abstract FilesToRunProvider getJack(); public abstract FilesToRunProvider getJill(); public abstract FilesToRunProvider getResourceExtractor(); AndroidSdkProvider() {} }
{ "content_hash": "89ee47baa6145e19a663abb5945e3632", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 98, "avg_line_length": 33.050632911392405, "alnum_prop": 0.7464572960551513, "repo_name": "iamthearm/bazel", "id": "da82a92d45f34f64f21e5fdac0af48082ee44bda", "size": "5222", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/google/devtools/build/lib/rules/android/AndroidSdkProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "78" }, { "name": "C", "bytes": "24763" }, { "name": "C++", "bytes": "627772" }, { "name": "HTML", "bytes": "17163" }, { "name": "Java", "bytes": "19244379" }, { "name": "Makefile", "bytes": "248" }, { "name": "PowerShell", "bytes": "3422" }, { "name": "Protocol Buffer", "bytes": "108199" }, { "name": "Python", "bytes": "283593" }, { "name": "Shell", "bytes": "629499" } ], "symlink_target": "" }
package exoscale import ( "bytes" "fmt" "io/ioutil" "strings" "text/template" "time" "github.com/docker/machine/libmachine/drivers" "github.com/docker/machine/libmachine/log" "github.com/docker/machine/libmachine/mcnflag" "github.com/docker/machine/libmachine/mcnutils" "github.com/docker/machine/libmachine/state" "github.com/pyr/egoscale/src/egoscale" ) type Driver struct { *drivers.BaseDriver URL string ApiKey string ApiSecretKey string InstanceProfile string DiskSize int Image string SecurityGroup string AvailabilityZone string KeyPair string PublicKey string Id string } const ( defaultInstanceProfile = "small" defaultDiskSize = 50 defaultImage = "ubuntu-14.04" defaultAvailabilityZone = "ch-gva-2" ) // RegisterCreateFlags registers the flags this driver adds to // "docker hosts create" func (d *Driver) GetCreateFlags() []mcnflag.Flag { return []mcnflag.Flag{ mcnflag.StringFlag{ EnvVar: "EXOSCALE_ENDPOINT", Name: "exoscale-url", Usage: "exoscale API endpoint", }, mcnflag.StringFlag{ EnvVar: "EXOSCALE_API_KEY", Name: "exoscale-api-key", Usage: "exoscale API key", }, mcnflag.StringFlag{ EnvVar: "EXOSCALE_API_SECRET", Name: "exoscale-api-secret-key", Usage: "exoscale API secret key", }, mcnflag.StringFlag{ EnvVar: "EXOSCALE_INSTANCE_PROFILE", Name: "exoscale-instance-profile", Value: defaultInstanceProfile, Usage: "exoscale instance profile (small, medium, large, ...)", }, mcnflag.IntFlag{ EnvVar: "EXOSCALE_DISK_SIZE", Name: "exoscale-disk-size", Value: defaultDiskSize, Usage: "exoscale disk size (10, 50, 100, 200, 400)", }, mcnflag.StringFlag{ EnvVar: "EXSOCALE_IMAGE", Name: "exoscale-image", Value: defaultImage, Usage: "exoscale image template", }, mcnflag.StringSliceFlag{ EnvVar: "EXOSCALE_SECURITY_GROUP", Name: "exoscale-security-group", Value: []string{}, Usage: "exoscale security group", }, mcnflag.StringFlag{ EnvVar: "EXOSCALE_AVAILABILITY_ZONE", Name: "exoscale-availability-zone", Value: defaultAvailabilityZone, Usage: "exoscale availibility zone", }, } } func NewDriver(hostName, storePath string) drivers.Driver { return &Driver{ InstanceProfile: defaultInstanceProfile, DiskSize: defaultDiskSize, Image: defaultImage, AvailabilityZone: defaultAvailabilityZone, BaseDriver: &drivers.BaseDriver{ MachineName: hostName, StorePath: storePath, }, } } func (d *Driver) GetSSHHostname() (string, error) { return d.GetIP() } func (d *Driver) GetSSHUsername() string { return "ubuntu" } func (d *Driver) DriverName() string { return "exoscale" } func (d *Driver) SetConfigFromFlags(flags drivers.DriverOptions) error { d.URL = flags.String("exoscale-endpoint") d.ApiKey = flags.String("exoscale-api-key") d.ApiSecretKey = flags.String("exoscale-api-secret-key") d.InstanceProfile = flags.String("exoscale-instance-profile") d.DiskSize = flags.Int("exoscale-disk-size") d.Image = flags.String("exoscale-image") securityGroups := flags.StringSlice("exoscale-security-group") if len(securityGroups) == 0 { securityGroups = []string{"docker-machine"} } d.SecurityGroup = strings.Join(securityGroups, ",") d.AvailabilityZone = flags.String("exoscale-availability-zone") d.SwarmMaster = flags.Bool("swarm-master") d.SwarmHost = flags.String("swarm-host") d.SwarmDiscovery = flags.String("swarm-discovery") if d.URL == "" { d.URL = "https://api.exoscale.ch/compute" } if d.ApiKey == "" || d.ApiSecretKey == "" { return fmt.Errorf("Please specify an API key (--exoscale-api-key) and an API secret key (--exoscale-api-secret-key).") } return nil } func (d *Driver) GetURL() (string, error) { ip, err := d.GetIP() if err != nil { return "", err } return fmt.Sprintf("tcp://%s:2376", ip), nil } func (d *Driver) GetIP() (string, error) { if d.IPAddress == "" { return "", fmt.Errorf("IP address is not set") } return d.IPAddress, nil } func (d *Driver) GetState() (state.State, error) { client := egoscale.NewClient(d.URL, d.ApiKey, d.ApiSecretKey) vm, err := client.GetVirtualMachine(d.Id) if err != nil { return state.Error, err } switch vm.State { case "Starting": return state.Starting, nil case "Running": return state.Running, nil case "Stopping": return state.Running, nil case "Stopped": return state.Stopped, nil case "Destroyed": return state.Stopped, nil case "Expunging": return state.Stopped, nil case "Migrating": return state.Paused, nil case "Error": return state.Error, nil case "Unknown": return state.Error, nil case "Shutdowned": return state.Stopped, nil } return state.None, nil } func (d *Driver) createDefaultSecurityGroup(client *egoscale.Client, group string) (string, error) { rules := []egoscale.SecurityGroupRule{ { SecurityGroupId: "", Cidr: "0.0.0.0/0", Protocol: "TCP", Port: 22, }, { SecurityGroupId: "", Cidr: "0.0.0.0/0", Protocol: "TCP", Port: 2376, }, { SecurityGroupId: "", Cidr: "0.0.0.0/0", Protocol: "TCP", Port: 3376, }, { SecurityGroupId: "", Cidr: "0.0.0.0/0", Protocol: "ICMP", IcmpType: 8, IcmpCode: 0, }, } sgresp, err := client.CreateSecurityGroupWithRules( group, rules, make([]egoscale.SecurityGroupRule, 0, 0)) if err != nil { return "", err } sg := sgresp.Id return sg, nil } func (d *Driver) Create() error { log.Infof("Querying exoscale for the requested parameters...") client := egoscale.NewClient(d.URL, d.ApiKey, d.ApiSecretKey) topology, err := client.GetTopology() if err != nil { return err } // Availability zone UUID zone, ok := topology.Zones[d.AvailabilityZone] if !ok { return fmt.Errorf("Availability zone %v doesn't exist", d.AvailabilityZone) } log.Debugf("Availability zone %v = %s", d.AvailabilityZone, zone) // Image UUID var tpl string images, ok := topology.Images[strings.ToLower(d.Image)] if ok { tpl, ok = images[d.DiskSize] } if !ok { return fmt.Errorf("Unable to find image %v with size %d", d.Image, d.DiskSize) } log.Debugf("Image %v(%d) = %s", d.Image, d.DiskSize, tpl) // Profile UUID profile, ok := topology.Profiles[strings.ToLower(d.InstanceProfile)] if !ok { return fmt.Errorf("Unable to find the %s profile", d.InstanceProfile) } log.Debugf("Profile %v = %s", d.InstanceProfile, profile) // Security groups securityGroups := strings.Split(d.SecurityGroup, ",") sgs := make([]string, len(securityGroups)) for idx, group := range securityGroups { sg, ok := topology.SecurityGroups[group] if !ok { log.Infof("Security group %v does not exist, create it", group) sg, err = d.createDefaultSecurityGroup(client, group) if err != nil { return err } } log.Debugf("Security group %v = %s", group, sg) sgs[idx] = sg } log.Infof("Generate an SSH keypair...") keypairName := fmt.Sprintf("docker-machine-%s", d.MachineName) kpresp, err := client.CreateKeypair(keypairName) if err != nil { return err } err = ioutil.WriteFile(d.GetSSHKeyPath(), []byte(kpresp.Privatekey), 0600) if err != nil { return err } d.KeyPair = keypairName log.Infof("Spawn exoscale host...") userdata, err := d.getCloudInit() if err != nil { return err } log.Debugf("Using the following cloud-init file:") log.Debugf("%s", userdata) machineProfile := egoscale.MachineProfile{ Template: tpl, ServiceOffering: profile, SecurityGroups: sgs, Userdata: userdata, Zone: zone, Keypair: d.KeyPair, Name: d.MachineName, } cvmresp, err := client.CreateVirtualMachine(machineProfile) if err != nil { return err } vm, err := d.waitForVM(client, cvmresp) if err != nil { return err } d.IPAddress = vm.Nic[0].Ipaddress d.Id = vm.Id return nil } func (d *Driver) Start() error { vmstate, err := d.GetState() if err != nil { return err } if vmstate == state.Running || vmstate == state.Starting { log.Infof("Host is already running or starting") return nil } client := egoscale.NewClient(d.URL, d.ApiKey, d.ApiSecretKey) svmresp, err := client.StartVirtualMachine(d.Id) if err != nil { return err } if err = d.waitForJob(client, svmresp); err != nil { return err } return nil } func (d *Driver) Stop() error { vmstate, err := d.GetState() if err != nil { return err } if vmstate == state.Stopped { log.Infof("Host is already stopped") return nil } client := egoscale.NewClient(d.URL, d.ApiKey, d.ApiSecretKey) svmresp, err := client.StopVirtualMachine(d.Id) if err != nil { return err } if err = d.waitForJob(client, svmresp); err != nil { return err } return nil } func (d *Driver) Remove() error { client := egoscale.NewClient(d.URL, d.ApiKey, d.ApiSecretKey) // Destroy the SSH key if _, err := client.DeleteKeypair(d.KeyPair); err != nil { return err } // Destroy the virtual machine dvmresp, err := client.DestroyVirtualMachine(d.Id) if err != nil { return err } if err = d.waitForJob(client, dvmresp); err != nil { return err } return nil } func (d *Driver) Restart() error { vmstate, err := d.GetState() if err != nil { return err } if vmstate == state.Stopped { return fmt.Errorf("Host is stopped, use start command to start it") } client := egoscale.NewClient(d.URL, d.ApiKey, d.ApiSecretKey) svmresp, err := client.RebootVirtualMachine(d.Id) if err != nil { return err } if err = d.waitForJob(client, svmresp); err != nil { return err } return nil } func (d *Driver) Kill() error { return d.Stop() } func (d *Driver) jobIsDone(client *egoscale.Client, jobid string) (bool, error) { resp, err := client.PollAsyncJob(jobid) if err != nil { return true, err } switch resp.Jobstatus { case 0: // Job is still in progress case 1: // Job has successfully completed return true, nil case 2: // Job has failed to complete return true, fmt.Errorf("Operation failed to complete") default: // Some other code } return false, nil } func (d *Driver) waitForJob(client *egoscale.Client, jobid string) error { log.Infof("Waiting for job to complete...") return mcnutils.WaitForSpecificOrError(func() (bool, error) { return d.jobIsDone(client, jobid) }, 60, 2*time.Second) } func (d *Driver) waitForVM(client *egoscale.Client, jobid string) (*egoscale.DeployVirtualMachineResponse, error) { if err := d.waitForJob(client, jobid); err != nil { return nil, err } resp, err := client.PollAsyncJob(jobid) if err != nil { return nil, err } vm, err := client.AsyncToVirtualMachine(*resp) if err != nil { return nil, err } return vm, nil } // Build a cloud-init user data string that will install and run // docker. func (d *Driver) getCloudInit() (string, error) { const tpl = `#cloud-config manage_etc_hosts: true fqdn: {{ .MachineName }} resize_rootfs: true ` var buffer bytes.Buffer tmpl, err := template.New("cloud-init").Parse(tpl) if err != nil { return "", err } err = tmpl.Execute(&buffer, d) if err != nil { return "", err } return buffer.String(), nil }
{ "content_hash": "c6d3b2d8baf780d80527cdb522c0d547", "timestamp": "", "source": "github", "line_count": 473, "max_line_length": 120, "avg_line_length": 24.006342494714588, "alnum_prop": 0.6609423161602818, "repo_name": "pdxjohnny/machine", "id": "e083e3f0d5a09fe92e4b22d532d88f38bea0197c", "size": "11355", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "drivers/exoscale/exoscale.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "1039" }, { "name": "Go", "bytes": "651691" }, { "name": "Makefile", "bytes": "8273" }, { "name": "Shell", "bytes": "43282" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <sem:triples uri="http://www.lds.org/vrl/concepts/languages-and-cultures/reformed-egyptian-language" xmlns:sem="http://marklogic.com/semantics"> <sem:triple> <sem:subject>http://www.lds.org/vrl/concepts/languages-and-cultures/reformed-egyptian-language</sem:subject> <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate> <sem:object datatype="xsd:string" xml:lang="eng">Reformed Egyptian Language</sem:object> </sem:triple> <sem:triple> <sem:subject>http://www.lds.org/vrl/concepts/languages-and-cultures/reformed-egyptian-language</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/concepts/languages-and-cultures/reformed-egyptian-language</sem:subject> <sem:predicate>http://www.lds.org/core#entityType</sem:predicate> <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object> </sem:triple> </sem:triples>
{ "content_hash": "d705fc476c8187acf871e36f89fd017d", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 144, "avg_line_length": 61.888888888888886, "alnum_prop": 0.7307001795332136, "repo_name": "freshie/ml-taxonomies", "id": "e82de325b45ba8f72497594130e8bec003873796", "size": "1114", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "roxy/data/gospel-topical-explorer-v2/taxonomies/vrl/concepts/languages-and-cultures/reformed-egyptian-language.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": "" }
FactoryGirl.define do factory :song do title "Great song" end factory :set_list do title "Great set list" end end
{ "content_hash": "0d0fe6324289b5362bd67e24bd9d2b40", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 26, "avg_line_length": 14.555555555555555, "alnum_prop": 0.6717557251908397, "repo_name": "andrewhao/chorus-api", "id": "9bb0baf2c1495dc4dc2437e3e53717064b885fa8", "size": "131", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/factories.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "900" }, { "name": "CoffeeScript", "bytes": "422" }, { "name": "JavaScript", "bytes": "641" }, { "name": "Ruby", "bytes": "37155" } ], "symlink_target": "" }
<?php include_once '../lib/common.php'; API::add('Content','getRecord',array('our-security')); $query = API::send(); $content = $query['Content']['getRecord']['results'][0]; $page_title = $content['title']; include 'includes/head.php'; ?> <div class="page_title"> <div class="container"> <div class="title"><h1><?= $page_title ?></h1></div> <div class="pagenation">&nbsp;<a href="<?= Lang::url('index.php') ?>"><?= Lang::string('home') ?></a> <i>/</i> <a href="<?= Lang::url('our-security.php') ?>"><?= Lang::string('our-security') ?></a></div> </div> </div> <div class="container"> <div class="content_right"> <div class="text1"><?= $content['content'] ?></div> </div> <? include 'includes/sidebar_topics.php'; ?> <div class="clearfix mar_top8"></div> </div> <? include 'includes/foot.php'; ?>
{ "content_hash": "b8e27ee655542e3e505e136208ce5c04", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 211, "avg_line_length": 31.73076923076923, "alnum_prop": 0.5890909090909091, "repo_name": "gfts/wlox", "id": "840176af0bec28a6761ad3e890487ee13b50c83c", "size": "825", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/htdocs/our-security.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "7422" }, { "name": "Batchfile", "bytes": "44" }, { "name": "CSS", "bytes": "686314" }, { "name": "HTML", "bytes": "256514" }, { "name": "JavaScript", "bytes": "706178" }, { "name": "PHP", "bytes": "3768598" }, { "name": "PostScript", "bytes": "497524" }, { "name": "Shell", "bytes": "20750" } ], "symlink_target": "" }
from utils import CanadianScraper, CanadianPerson as Person from opencivicdata.divisions import Division from pupa.scrape import Organization from datetime import date COUNCIL_PAGE = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vTP3PplANMDX5EkNBwLN1zz4IxDvUcMbT3L2l6RoA5Hr27p5NovyzlpV2wlBNAHsA8sdDxXdMQ78eF0/pub?gid=1928681855&single=true&output=csv' class BritishColumbiaMunicipalitiesCandidatesPersonScraper(CanadianScraper): updated_at = date(2018, 9, 20) contact_person = 'andrew@newmode.net' def scrape(self): exclude_divisions = { } exclude_districts = { 'Capital', 'Capital F', 'Capital G', 'Capital H', 'Central Coast B', 'Central Okanagan East', 'Central Okanagan West', 'Comox Valley B', 'Comox Valley C', 'Islands Trust', 'Kitimat-Stikine C', 'Kootenay Boundary B', 'Kootenay Boundary C', 'Kootenay Boundary D', 'Kootenay Boundary E', 'Metro Vancouver A', 'North Coast A', 'North Coast C', 'North Coast D', 'North Coast E', 'Okanagan-Similkameen I', 'Okanagan-Similkameen Olalla Local Community Commission', 'Qathet A', 'Qathet B', 'Qathet C', 'Qathet D', 'Qathet E', } expected_roles = { 'candidate', } infixes = { 'CY': 'City', 'DM': 'District', 'IGD': 'District', 'IM': 'Municipal', 'RGM': 'Regional', 'T': 'Town', 'VL': 'Village', 'RDA': 'District', } duplicate_names = { 'Rick Smith', 'Sung Y Wong', 'Elizabeth Taylor', } names_to_ids = {} for division in Division.get('ocd-division/country:ca').children('csd'): type_id = division.id.rsplit(':', 1)[1] if type_id.startswith('59'): if division.attrs['classification'] == 'IRI': continue if division.name in names_to_ids: names_to_ids[division.name] = None else: names_to_ids[division.name] = division.id reader = self.csv_reader(COUNCIL_PAGE, header=True) reader.fieldnames = [field.lower() for field in reader.fieldnames] organizations = {} birth_date = 1900 seen = set() rows = [row for row in reader] assert len(rows), 'No councillors found' for row in rows: name = row['full name'] district_name = row['district name'] if not any(row.values()) or name.lower() in ('', 'vacant') or district_name in exclude_districts: continue if row['district id']: division_id = 'ocd-division/country:ca/csd:{}'.format(row['district id']) else: division_id = names_to_ids[row['district name']] if division_id in exclude_divisions: continue if not division_id: raise Exception('unhandled collision: {}'.format(row['district name'])) division = Division.get(division_id) division_name = division.name organization_name = '{} {} Council'.format(division_name, infixes[division.attrs['classification']]) if division_id not in seen: seen.add(division_id) organizations[division_id] = Organization(name=organization_name, classification='government') organizations[division_id].add_source(COUNCIL_PAGE) organization = organizations[division_id] role = row['primary role'] if role not in expected_roles: raise Exception('unexpected role: {}'.format(role)) if row['district id']: district = format(division_id) else: district = division_name organization.add_post(role=role, label=district, division_id=division_id) p = Person(primary_org='government', primary_org_name=organization_name, name=name, district=district, role=role) p.add_source(COUNCIL_PAGE) if row['source url']: p.add_source(row['source url']) if name in duplicate_names: p.birth_date = str(birth_date) birth_date += 1 if row['email']: p.add_contact('email', row['email']) if row['phone']: p.add_contact('voice', row['phone'], 'legislature') if row['twitter']: p.add_link(row['twitter']) p._related[0].extras['boundary_url'] = '/boundaries/census-subdivisions/{}/'.format(division_id.rsplit(':', 1)[1]) yield p for organization in organizations.values(): yield organization
{ "content_hash": "24291d578209249d8df57e3d3a14336f", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 186, "avg_line_length": 34.41891891891892, "alnum_prop": 0.5333725952100511, "repo_name": "opencivicdata/scrapers-ca", "id": "1b9e1d784269e26f74ead6ac2972ba2fa1cc3a9e", "size": "5094", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ca_bc_municipalities_candidates/people.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "832" }, { "name": "Python", "bytes": "374889" }, { "name": "Shell", "bytes": "1759" } ], "symlink_target": "" }
using Foundation; using System; using System.CodeDom.Compiler; using UIKit; namespace TPKeyboardAvoidingSample { [Register ("CollectionViewControllerCell")] partial class CollectionViewControllerCell { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UILabel label { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UITextField textField { get; set; } void ReleaseDesignerOutlets () { if (label != null) { label.Dispose (); label = null; } if (textField != null) { textField.Dispose (); textField = null; } } } }
{ "content_hash": "820eb86f1301f1ecc33afa957a97e722", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 44, "avg_line_length": 18.64516129032258, "alnum_prop": 0.6591695501730104, "repo_name": "topgenorth/XamarinComponents", "id": "a44b009877ac9b0c283bbcb9b49b877f8e295667", "size": "780", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "iOS/TPKeyboardAvoiding/samples/TPKeyboardAvoidingSample/CollectionViewControllerCell.designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3435734" }, { "name": "GLSL", "bytes": "2524" }, { "name": "HTML", "bytes": "1746" }, { "name": "Makefile", "bytes": "16119" }, { "name": "Objective-C", "bytes": "1020" }, { "name": "PowerShell", "bytes": "4617" }, { "name": "Ruby", "bytes": "254" }, { "name": "Shell", "bytes": "5593" }, { "name": "Smalltalk", "bytes": "6265" } ], "symlink_target": "" }
const panels = document.querySelectorAll('.panels__panel'); function togglePanelOpen() { this.classList.toggle('panels__panel--open'); } function togglePanelActive(e) { if (e.propertyName.includes('flex')) { this.classList.toggle('panels__panel--active'); } } panels.forEach(panel => panel.addEventListener('click', togglePanelOpen)); panels.forEach(panel => panel.addEventListener('transitionend', togglePanelActive));
{ "content_hash": "aa0657cdff8652eb3946748de1c33bf1", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 84, "avg_line_length": 30.5, "alnum_prop": 0.7494145199063232, "repo_name": "RequestingMark/myjavascript30", "id": "b244d5169da877a3b2c41ee1eafa4728138f92b4", "size": "427", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "05-flex-panel-gallery/js/main.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4774" }, { "name": "HTML", "bytes": "8250" }, { "name": "JavaScript", "bytes": "3669" } ], "symlink_target": "" }
Screen::Screen(const std::string& screenName) : Screen(screenName, Nodect("nullObject-screen:" + screenName, nullptr)) { } Screen::Screen(const std::string& screenName, Nodect&& node) : _screenName(screenName) , _screenNativeObject(std::move(node)) { }
{ "content_hash": "49fdfd9a6ce63e9f9b79755de0e02c83", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 74, "avg_line_length": 26, "alnum_prop": 0.7153846153846154, "repo_name": "gelldur/DexodeEngine", "id": "15172f7e9223b5b3fc63d921f432e66258081faf", "size": "339", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/screen/Screen.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3001" }, { "name": "C++", "bytes": "149867" }, { "name": "CMake", "bytes": "8119" }, { "name": "Java", "bytes": "4949" }, { "name": "Makefile", "bytes": "559" }, { "name": "Objective-C", "bytes": "584" }, { "name": "Objective-C++", "bytes": "4684" } ], "symlink_target": "" }
"""Definition of platform parameters.""" from __future__ import annotations import enum from core.domain import platform_parameter_domain from core.domain import platform_parameter_registry as registry Registry = registry.Registry # TODO(#14419): Change naming style of Enum class from SCREAMING_SNAKE_CASE # to PascalCase and its values to UPPER_CASE. Because we want to be consistent # throughout the codebase according to the coding style guide. # https://github.com/oppia/oppia/wiki/Coding-style-guide class PARAM_NAMES(enum.Enum): # pylint: disable=invalid-name """Enum for parameter names.""" dummy_feature = 'dummy_feature' # pylint: disable=invalid-name dummy_parameter = 'dummy_parameter' # pylint: disable=invalid-name # Platform parameters should all be defined below. Registry.create_feature_flag( PARAM_NAMES.dummy_feature, 'This is a dummy feature flag.', platform_parameter_domain.FeatureStages.DEV, ) Registry.create_platform_parameter( PARAM_NAMES.dummy_parameter, 'This is a dummy platform parameter.', platform_parameter_domain.DataTypes.STRING )
{ "content_hash": "ff56781f32c64b8a60d896fad71f5bfc", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 78, "avg_line_length": 30.916666666666668, "alnum_prop": 0.7592093441150045, "repo_name": "brianrodri/oppia", "id": "49f56851fa5ddb4f0b28903e3efa32c67edfc740", "size": "1736", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "core/domain/platform_parameter_list.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "487903" }, { "name": "HTML", "bytes": "1748056" }, { "name": "JavaScript", "bytes": "1176446" }, { "name": "PEG.js", "bytes": "71377" }, { "name": "Python", "bytes": "14169091" }, { "name": "Shell", "bytes": "2239" }, { "name": "TypeScript", "bytes": "13316709" } ], "symlink_target": "" }
```php public __construct ( void ) ``` ## Details Class: [BearFramework\App\DataItem](bearframework.app.dataitem.class.md) Location: ~/src/App/DataItem.php --- [back to index](index.md)
{ "content_hash": "060eaf231e0b9308a2bd01bc2b5979cb", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 72, "avg_line_length": 13.714285714285714, "alnum_prop": 0.6875, "repo_name": "bearframework/bearframework", "id": "b15f4c1e578cdb09198c15c2f083d829645b5f98", "size": "235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/markdown/bearframework.app.dataitem.__construct.method.md", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "607088" } ], "symlink_target": "" }
require 'contest' require 'swirl/helpers' class SlopTest < Test::Unit::TestCase include Swirl::Helpers test "camalize" do assert_equal "foo", Slop.camalize(:foo) assert_equal "fooBar", Slop.camalize(:foo_bar) end test "gets sloppy" do slop = Slop.new({"fooBar" => "baz"}) assert_equal "baz", slop[:foo_bar] end test "honors keys already camalized" do slop = Slop.new({"fooBar" => "baz"}) assert_equal "baz", slop["fooBar"] end test "raise InvalidKey if key not found" do slop = Slop.new({}) assert_raises Slop::InvalidKey do slop[:not_here] end end end
{ "content_hash": "dcdb00c785677fae891793079071f6b7", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 50, "avg_line_length": 21.344827586206897, "alnum_prop": 0.6413570274636511, "repo_name": "bmizerany/swirl", "id": "a196a9b8ded3d4f41a2607801d1f295fb426ba95", "size": "619", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/slop_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "11610" } ], "symlink_target": "" }
<a id="exportlatexa" target="_blank" class="exportlink"> <div class="exporttype" id="exportlatex">LaTeX file</div> </a>
{ "content_hash": "4a59c81a7fbfc9a7519990a58f5a82cf", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 58, "avg_line_length": 40, "alnum_prop": 0.7083333333333334, "repo_name": "swapnilp/etherpadlite", "id": "18c2403449cdeb01ac39d1d3d087b0d56aaed393", "size": "120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "available_plugins/ep_latexexport/templates/exportcolumn.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "1170740" }, { "name": "Shell", "bytes": "9223" } ], "symlink_target": "" }
package com.microsoft.azure.management.network.v2020_06_01; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.arm.resources.models.Resource; import com.microsoft.azure.arm.resources.models.GroupableResourceCore; import com.microsoft.azure.arm.resources.models.HasResourceGroup; import com.microsoft.azure.arm.model.Refreshable; import com.microsoft.azure.arm.model.Updatable; import com.microsoft.azure.arm.model.Appliable; import com.microsoft.azure.arm.model.Creatable; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.network.v2020_06_01.implementation.NetworkManager; import java.util.List; import com.microsoft.azure.management.network.v2020_06_01.implementation.NetworkProfileInner; /** * Type representing NetworkProfile. */ public interface NetworkProfile extends HasInner<NetworkProfileInner>, Resource, GroupableResourceCore<NetworkManager, NetworkProfileInner>, HasResourceGroup, Refreshable<NetworkProfile>, Updatable<NetworkProfile.Update>, HasManager<NetworkManager> { /** * @return the containerNetworkInterfaceConfigurations value. */ List<ContainerNetworkInterfaceConfiguration> containerNetworkInterfaceConfigurations(); /** * @return the containerNetworkInterfaces value. */ List<ContainerNetworkInterface> containerNetworkInterfaces(); /** * @return the etag value. */ String etag(); /** * @return the provisioningState value. */ ProvisioningState provisioningState(); /** * @return the resourceGuid value. */ String resourceGuid(); /** * The entirety of the NetworkProfile definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate { } /** * Grouping of NetworkProfile definition stages. */ interface DefinitionStages { /** * The first stage of a NetworkProfile definition. */ interface Blank extends GroupableResourceCore.DefinitionWithRegion<WithGroup> { } /** * The stage of the NetworkProfile definition allowing to specify the resource group. */ interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup<WithCreate> { } /** * The stage of the networkprofile definition allowing to specify ContainerNetworkInterfaceConfigurations. */ interface WithContainerNetworkInterfaceConfigurations { /** * Specifies containerNetworkInterfaceConfigurations. * @param containerNetworkInterfaceConfigurations List of chid container network interface configurations * @return the next definition stage */ WithCreate withContainerNetworkInterfaceConfigurations(List<ContainerNetworkInterfaceConfiguration> containerNetworkInterfaceConfigurations); } /** * The stage of the definition which contains all the minimum required inputs for * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ interface WithCreate extends Creatable<NetworkProfile>, Resource.DefinitionWithTags<WithCreate>, DefinitionStages.WithContainerNetworkInterfaceConfigurations { } } /** * The template for a NetworkProfile update operation, containing all the settings that can be modified. */ interface Update extends Appliable<NetworkProfile>, Resource.UpdateWithTags<Update>, UpdateStages.WithContainerNetworkInterfaceConfigurations { } /** * Grouping of NetworkProfile update stages. */ interface UpdateStages { /** * The stage of the networkprofile update allowing to specify ContainerNetworkInterfaceConfigurations. */ interface WithContainerNetworkInterfaceConfigurations { /** * Specifies containerNetworkInterfaceConfigurations. * @param containerNetworkInterfaceConfigurations List of chid container network interface configurations * @return the next update stage */ Update withContainerNetworkInterfaceConfigurations(List<ContainerNetworkInterfaceConfiguration> containerNetworkInterfaceConfigurations); } } }
{ "content_hash": "0450fad39954629491739def8ba516e9", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 250, "avg_line_length": 39.410714285714285, "alnum_prop": 0.7224739465337562, "repo_name": "selvasingh/azure-sdk-for-java", "id": "841540103a3f677f3c37f861d9984b73ee2046b7", "size": "4644", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/network/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/network/v2020_06_01/NetworkProfile.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "29891970" }, { "name": "JavaScript", "bytes": "6198" }, { "name": "PowerShell", "bytes": "160" }, { "name": "Shell", "bytes": "609" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Biblthca Mycol. 116: 373 (1987) #### Original name Helotium berggrenii Cooke & W. Phillips, 1879 ### Remarks null
{ "content_hash": "1f9a6452682ed74b61340e6d9c460526", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 45, "avg_line_length": 15.538461538461538, "alnum_prop": 0.7128712871287128, "repo_name": "mdoering/backbone", "id": "e7c36be2dddbfb398d3711677460e0479b22aa66", "size": "279", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Rutstroemiaceae/Lanzia/Lanzia berggrenii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
module['exports'] = function (options, callback) { var resources = options.resources, $ = this.$; return callback(null, $.html()); }
{ "content_hash": "89af6ecd01bb51cca64292d67ab4b50e", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 50, "avg_line_length": 20.571428571428573, "alnum_prop": 0.625, "repo_name": "manjunathkg/generator-bizzns", "id": "fc9d36400a52f1c5874e33be946f21ff53dbf0fd", "size": "144", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "templates/javascript/server/resources/admin/view/docs.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "698260" }, { "name": "CoffeeScript", "bytes": "10558" }, { "name": "JavaScript", "bytes": "1265127" }, { "name": "Shell", "bytes": "1485" } ], "symlink_target": "" }
<?php namespace DoctrineModule\Validator\Service; use PHPUnit\Framework\TestCase; use DoctrineModule\Validator\ObjectExists; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\Persistence\ObjectRepository; use Interop\Container\ContainerInterface; /** * Generated by PHPUnit_SkeletonGenerator on 2017-09-04 at 11:55:36. * * @coversDefaultClass DoctrineModule\Validator\Service\ObjectExistsFactory * @group validator */ class ObjectExistsFactoryTest extends TestCase { /** * @var ObjectExistsFactory */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->object = new ObjectExistsFactory; } /** * @covers ::__invoke */ public function testInvoke() { $options = [ 'target_class' => 'Foo\Bar', 'fields' => ['test'], ]; $repository = $this->prophesize(ObjectRepository::class); $objectManager = $this->prophesize(ObjectManager::class); $objectManager->getRepository('Foo\Bar') ->shouldBeCalled() ->willReturn($repository->reveal()); $container = $this->prophesize(ContainerInterface::class); $container->get('doctrine.entitymanager.orm_default') ->shouldBeCalled() ->willReturn($objectManager->reveal()); $instance = $this->object->__invoke( $container->reveal(), ObjectExists::class, $options ); $this->assertInstanceOf(ObjectExists::class, $instance); } }
{ "content_hash": "27d2480b0445bffc8e21fbe4dbcc4df1", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 75, "avg_line_length": 27.62295081967213, "alnum_prop": 0.627299703264095, "repo_name": "netiul/DoctrineModule", "id": "8291488873694531d74cc3a0562ad34732e98634", "size": "1685", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/DoctrineModuleTest/Validator/Service/ObjectExistsFactoryTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "231" }, { "name": "PHP", "bytes": "448060" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "9b46c3b73b23840f099fc9c15b19695c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "475ebe7314a577495840922ec71d3428e36c4f84", "size": "177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Trichoschoenus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
title: "Ifanakalozy hevitra" date: 06/05/2022 --- ### Ifanakalozy hevitra Zarao ao amin'ny kilasin'ny Sekoly Sabata (na amin'ny mpiara-mianatra Baiboly) ny hevitra voarainao avy amin'ny tslanjery sy ny fianaranao Baiboly nandritra ity herinandro ity, ary koa ireo fahalalana azonao avy amin'izany, ireo fanamarihana nataonao sy fanontaniana isan karazany momba izany. `1. Zarao ny amin'ny fotoana iray izay nanaovan'ny olona teny manan-danja sy mitondra soa ho anao.` `2. Araka ny hevitrao, nahoana ny teny no misy fiantraikany lehibe amintsika?` `3. Inona eo amin'ny ny fiantraikany fifandraisantsika amin'Andriamanitra raha toa samy mivoaka ny vavantsika ny "rano mamy" sy "rano masirasira"?` `4. Ahoana no fahitanao ny fomba miavaka itenenan'i Jesosy taorian'ny fianarana ny lesona amin'ity herinandro ity?` `5. Ahoana no hampifandanjantsika ny fahatakarana ny lanjan'ny filazana izay ao am pontsika sy ny maha-zava-dehibe ny toetry ny fo?` `6. Ahoana no hahafahantsika manana ny fanandramana araka ny Ezek. 36:26?`
{ "content_hash": "0e9ac10197c0c0cb0e2c40af49580f8f", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 293, "avg_line_length": 54.1578947368421, "alnum_prop": 0.7871720116618076, "repo_name": "imasaru/sabbath-school-lessons", "id": "fbc6d1ba649e6ac43f4b95fb86b3ce59f12c1e0e", "size": "1033", "binary": false, "copies": "2", "ref": "refs/heads/stage", "path": "src/mg/2022-02-cq/06/07.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "160533" }, { "name": "HTML", "bytes": "20725" }, { "name": "JavaScript", "bytes": "54661" } ], "symlink_target": "" }
#include "SDL_config.h" extern SDL_bool SDL_GetSpanEnclosingRect(int width, int height, int numrects, SDL_Rect * rects, SDL_Rect *span); /* vi: set ts=4 sw=4 expandtab: */
{ "content_hash": "836685f0fe40614497b4471be48400d9", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 112, "avg_line_length": 29.166666666666668, "alnum_prop": 0.7085714285714285, "repo_name": "shadowmint/kivy-ios", "id": "b360a54c26c5dbc92690337add254ea7a026b26a", "size": "1113", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/SDL/src/video/SDL_rect_c.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6474142" }, { "name": "C++", "bytes": "278890" }, { "name": "D", "bytes": "54728057" }, { "name": "Java", "bytes": "25546" }, { "name": "Objective-C", "bytes": "243270" }, { "name": "Perl", "bytes": "34501" }, { "name": "Prolog", "bytes": "33" }, { "name": "Python", "bytes": "5190" }, { "name": "Shell", "bytes": "324556" } ], "symlink_target": "" }
/** * 绘制文字 * @param {CanvasRenderingContext2D} ctx 画图上下文 * @param {String} text 文字内容 * @param {Number} sx 起始绘制点 x * @param {Number} sy 起始绘制点 y * @param {Vector} [vct] 方向向量 * @param {Number} [cx] 中心点 x * @param {Number} [cy] 中心点 y * @param {Style} [style] 样式 * @constructor */ function Text(ctx, text, sx, sy, vct, cx, cy, style) { Shape.call(this, ctx, sx, sy, vct, cx, cy, style); this.text = text; } inheritPrototype(Text, Shape); Text.prototype.fill = function () { this.save().transform(); this.ctx.fillText(this.text, this.dx, this.dy); this.restore(); return this; }; Text.prototype.stroke = function () { this.save().transform(); this.ctx.strokeText(this.text, this.dx, this.dy); this.restore(); return this; };
{ "content_hash": "c9bda9593324b1fa525b6db736356c8d", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 54, "avg_line_length": 23.53125, "alnum_prop": 0.6401062416998672, "repo_name": "JarenChow/CanvasIcon", "id": "dd0772ab68204f2cc20eecc4a5f25c04eba7806c", "size": "823", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/pojo/text.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "87" }, { "name": "HTML", "bytes": "1088" }, { "name": "JavaScript", "bytes": "52852" } ], "symlink_target": "" }
from twisted.plugin import IPlugin from txircd.module_interface import IModuleData, ModuleData from zope.interface import implementer from typing import Callable, List, Tuple @implementer(IPlugin, IModuleData) class StatusReport(ModuleData): name = "ChannelStatusReport" core = True def actions(self) -> List[Tuple[str, int, Callable]]: return [ ("channelstatuses", 1, self.statuses) ] def statuses(self, channel: "IRCChannel", user: "IRCUser", requestingUser: "IRCUser") -> str: if user not in channel.users: return None if not channel.users[user]: return "" if not channel.users[user]["status"]: return "" return self.ircd.channelStatuses[channel.users[user]["status"][0]][0] statuses = StatusReport()
{ "content_hash": "00fd5c95502442dd2ed6a97d9dd6eccf", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 94, "avg_line_length": 31.82608695652174, "alnum_prop": 0.7377049180327869, "repo_name": "Heufneutje/txircd", "id": "04e5eb7e4ee51d13d421addae9e3840ace0ac9e8", "size": "732", "binary": false, "copies": "1", "ref": "refs/heads/dev/next", "path": "txircd/modules/core/channel_statuses.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Dockerfile", "bytes": "547" }, { "name": "Python", "bytes": "792279" } ], "symlink_target": "" }
package org.ensembl.healthcheck.eg_gui; import java.awt.Color; import java.util.logging.Level; public class Constants { /** * If nothing has been set explicitly use fine logging when running the * healthchecks in the gui. * */ protected static Level defaultLogLevel = Level.FINE; public static final String RUN_ALL_TESTS = "RUN_ALL_TESTS"; public static final String RUN_SELECTED_TESTS = "RUN_SELECTED_TESTS"; public static final String REMOVE_SELECTED_TESTS = "REMOVE_SELECTED_TESTS"; public static final String OPEN_MYSQL_CLI = "OPEN_MYSQL_CLI"; public static final String DB_SERVER_CHANGED = "DB_SERVER_CHANGED"; public static final String SECONDARY_DB_SERVER_CHANGED = "SECONDARY_DB_SERVER_CHANGED"; public static final String PAN_DB_SERVER_CHANGED = "PAN_DB_SERVER_CHANGED"; public static final String Add_to_tests_to_be_run = "Add to tests to be run"; public static final String Execute = "Execute"; public static final String checkoutPerlDependenciesButton = "checkoutPerlDependenciesButton"; public static final int DEFAULT_BUTTON_WIDTH = 50; public static final int DEFAULT_BUTTON_HEIGHT = 20; public static final String TREE_ROOT_NODE_NAME = "All Groups"; public static final String ALL_TESTS_GROUP_NAME = "All Tests"; public static final int INITIAL_APPLICATION_WINDOW_WIDTH = 1200; public static final int INITIAL_APPLICATION_WINDOW_HEIGHT = 800; public static final int DEFAULT_HORIZONTAL_COMPONENT_SPACING = 10; public static final int DEFAULT_VERTICAL_COMPONENT_SPACING = 10; public static final Color COLOR_SUCCESS = new Color(0, 192, 0); public static final Color COLOR_FAILURE = new Color(192, 0, 0); public static final String selectedDatabaseChanged = "selectedDatabaseChanged"; }
{ "content_hash": "c61f8f131b98a12dda615ec57340c3a9", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 94, "avg_line_length": 36.3, "alnum_prop": 0.7382920110192838, "repo_name": "thomasmaurel/ensj-healthcheck", "id": "ad39bd516a0ac9cf6eba4c47b5f35616fc2bb0a2", "size": "2551", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/ensembl/healthcheck/eg_gui/Constants.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4402" }, { "name": "HTML", "bytes": "5026" }, { "name": "Java", "bytes": "2900462" }, { "name": "Perl", "bytes": "110619" }, { "name": "Shell", "bytes": "24836" }, { "name": "Smalltalk", "bytes": "1162" } ], "symlink_target": "" }
div.entryThread{ margin: 10px; margin-right: 0px; margin-left: 0px; } div.entryThread img.avatar{ height: 20px; width: auto; float: left; border-radius: 10px; } div.entryThread strong.title{ display: block; padding: 5px; font-size: 15px; border-bottom: 1px dotted #d4d4d5; margin-bottom: 3px; font-family: Merriweather; } div.entryThread a.buttonTh{ color: #000; opacity: .6; transition: all .2s; } div.entryThread a.buttonTh:hover{ opacity: 1; color: #24A22D; } div.entryThread span.title{ display: block; margin-left: 12px; float: left; } div.entryThread div.content{ padding: 10px; } div.entryThread a.buttonTh{ } div.entryThread a.username{ color: #212121; } div.entryThread a.username:hover{ text-decoration: underline; } div.entryThread div.parent{ width: 100%; padding-right: 0px; padding-bottom: 0px; } div.entryThread div.children{ margin-left: 5%; } div.entryThread div.children.main{ border-bottom: 1px dotted #ededed; padding-bottom: 10px; } div.entryThreadHolder div.entryThread:first-child div.children{ border-left: 1px dotted #ededed; } div.entryThread div.children div.parent{ border-bottom: 1px dotted #ededed; border-radius: 0px 0px 0px 5px; padding: 0px; padding-top: 10px; padding-left: 20px; margin-left: -3px; } div.entryThread .pSectionTitle.extra{ border: 1px dotted #ededed; } div.entryThread .pSectionWrapper{ border: 1px dotted #ededed; } div.entryThread div.children div.parent .pSectionWrapper{ border-bottom: none; border-radius: 0px; } div.entryThread .pSectionWrapper{ margin: 0; background: white; padding: 0; }
{ "content_hash": "2e496b670eb7c5b92b9987e417379408", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 63, "avg_line_length": 15.784313725490197, "alnum_prop": 0.7285714285714285, "repo_name": "blekerfeld/donut", "id": "67f4724018319769262f70c880f3e6bc588a2fe6", "size": "1610", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/assets/css/thread.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "133778" }, { "name": "JavaScript", "bytes": "20073" }, { "name": "PHP", "bytes": "461085" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ldml SYSTEM "http://www.unicode.org/cldr/dtd/1.5/ldml.dtd"> <ldml> <identity> <version number="$Revision: 1.16 $"/> <generation date="$Date: 2007/07/19 22:31:38 $"/> <language type="af"/> <territory type="NA"/> </identity> <dates> <calendars> <calendar type="gregorian"> <dateFormats> <dateFormatLength type="full"> <dateFormat> <pattern>EEEE d MMMM yyyy</pattern> </dateFormat> </dateFormatLength> <dateFormatLength type="long"> <dateFormat> <pattern>d MMMM yyyy</pattern> </dateFormat> </dateFormatLength> <dateFormatLength type="medium"> <dateFormat> <pattern>d MMM yyyy</pattern> </dateFormat> </dateFormatLength> <dateFormatLength type="short"> <dateFormat> <pattern>yyyy-MM-dd</pattern> </dateFormat> </dateFormatLength> </dateFormats> <timeFormats> <timeFormatLength type="full"> <timeFormat> <pattern>HH:mm:ss v</pattern> </timeFormat> </timeFormatLength> <timeFormatLength type="long"> <timeFormat> <pattern>HH:mm:ss z</pattern> </timeFormat> </timeFormatLength> <timeFormatLength type="medium"> <timeFormat> <pattern>HH:mm:ss</pattern> </timeFormat> </timeFormatLength> <timeFormatLength type="short"> <timeFormat> <pattern>HH:mm</pattern> </timeFormat> </timeFormatLength> </timeFormats> <dateTimeFormats> <availableFormats> <dateFormatItem id="MMdd">MM-dd</dateFormatItem> <dateFormatItem id="yyyyMM">yyyy-MM</dateFormatItem> </availableFormats> </dateTimeFormats> </calendar> </calendars> </dates> <numbers> <currencyFormats> <currencyFormatLength> <currencyFormat> <pattern>¤ #,##0.00</pattern> </currencyFormat> </currencyFormatLength> </currencyFormats> </numbers> </ldml>
{ "content_hash": "bc767200bda6462af38ca86a27be6dfd", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 69, "avg_line_length": 26.855263157894736, "alnum_prop": 0.595296423321901, "repo_name": "supporteam/vtiger-mass-file-import", "id": "4499dac0ee391d6fb18260760d2e95192a170d53", "size": "2042", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "classes/Zend/Locale/Data/af_NA.xml", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "8077114" } ], "symlink_target": "" }
import review_parser.mb_release as mb releases = mb.readReleaseLog('releases.json') if releases is not None: print("%d releases read" % len(releases)) else: print("No releases read!")
{ "content_hash": "2051ea22388e0d3cf5c611f53ccf2cf1", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 45, "avg_line_length": 24.25, "alnum_prop": 0.711340206185567, "repo_name": "hidat/audio_pipeline", "id": "0f7e83b9e7ae45b1dac8fc355b759835b6e83855", "size": "194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "json_test.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "343203" } ], "symlink_target": "" }
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.externals import joblib print "Grabbing data..." training_text_collection_f = open("training_text_collection.pkl", "rb") training_text_collection = joblib.load(training_text_collection_f) training_text_collection_f.close() training_targets_f = open("training_targets.pkl", "rb") training_targets = joblib.load(training_targets_f) training_targets_f.close() print("Vectorizing data...") vectorizer = TfidfVectorizer(analyzer = "word", \ tokenizer = None, \ preprocessor = None, \ stop_words = "english", \ max_features = 2500, \ min_df = 5, \ max_df = 0.4) train_tfidf = vectorizer.fit_transform(training_text_collection) save_vect = open("nb_tfidf_vect.pkl", "wb") joblib.dump(vectorizer, save_vect) save_vect.close() clf = MultinomialNB().fit(train_tfidf, training_targets) save_clf = open("nb_clf.pkl", "wb") joblib.dump(clf, save_clf) save_clf.close()
{ "content_hash": "e8429112a6febb1691786c88e7e5b302", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 71, "avg_line_length": 33.25714285714286, "alnum_prop": 0.6280068728522337, "repo_name": "npentella/CuriousCorpus", "id": "f6002b8ebb1246cf99f93f957991bb91986598da", "size": "1164", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nb_train.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "98" }, { "name": "HTML", "bytes": "5234" }, { "name": "JavaScript", "bytes": "516" }, { "name": "Python", "bytes": "10229" } ], "symlink_target": "" }
<?php namespace Da\OAuthClientBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('da_oauth_client'); // DUPLICATED FROM THE HWIOAUTHCLIENTBUNDLE. // because a list of resource owners is defined // in the bundle to prevent the addition of custom // resource owner. You can see a custom resource owner // in the documentation? Uh? $rootNode ->children() ->scalarNode('login_template') ->defaultValue('DaOAuthClientBundle:Connect:login.html.twig') ->end() ->scalarNode('registration_template') ->defaultValue('DaOAuthClientBundle:Connect:register.html.twig') ->end() ->scalarNode('profile_template') ->defaultValue('DaOAuthClientBundle:Connect:profile.html.twig') ->end() ->scalarNode('default_resource_owner') ->isRequired(true) ->end() ->arrayNode('fosub') ->children() ->scalarNode('username_iterations') ->defaultValue(5) ->cannotBeEmpty() ->end() ->arrayNode('properties') ->isRequired() ->useAttributeAsKey('name') ->prototype('scalar') ->end() ->end() ->end() ->end() ->arrayNode('resource_owners') ->isRequired() ->useAttributeAsKey('name') ->prototype('array') ->children() ->scalarNode('base_url')->end() ->scalarNode('access_token_url') ->validate() ->ifTrue(function($v) { return empty($v); }) ->thenUnset() ->end() ->end() ->scalarNode('authorization_url') ->validate() ->ifTrue(function($v) { return empty($v); }) ->thenUnset() ->end() ->end() ->scalarNode('disconnection_url') ->validate() ->ifTrue(function($v) { return empty($v); }) ->thenUnset() ->end() ->end() ->scalarNode('request_token_url') ->validate() ->ifTrue(function($v) { return empty($v); }) ->thenUnset() ->end() ->end() ->scalarNode('client_id')->end() ->scalarNode('client_secret')->end() ->scalarNode('api_token')->end() ->arrayNode('identity') ->children() ->scalarNode('selector') ->defaultValue('da_oauth_client.identity_selector.default') ->end() ->scalarNode('default_tokens')->end() ->arrayNode('tokens') ->isRequired(true) ->useAttributeAsKey('name') ->prototype('array') ->children() ->scalarNode('client_id') ->cannotBeEmpty() ->end() ->scalarNode('client_secret') ->cannotBeEmpty() ->end() ->scalarNode('api_token')->end() ->scalarNode('authorization_url')->defaultNull()->end() ->end() ->end() ->end() ->end() ->end() ->scalarNode('infos_url') ->validate() ->ifTrue(function($v) { return empty($v); }) ->thenUnset() ->end() ->end() ->scalarNode('realm') ->validate() ->ifTrue(function($v) { return empty($v); }) ->thenUnset() ->end() ->end() ->scalarNode('scope') ->validate() ->ifTrue(function($v) { return empty($v); }) ->thenUnset() ->end() ->end() ->scalarNode('user_response_class') ->validate() ->ifTrue(function($v) { return empty($v); }) ->thenUnset() ->end() ->end() ->scalarNode('service') ->validate() ->ifTrue(function($v) { return empty($v); }) ->thenUnset() ->end() ->end() ->scalarNode('type') ->validate() ->ifTrue(function($v) { return empty($v); }) ->thenUnset() ->end() ->end() ->arrayNode('paths') ->useAttributeAsKey('name') ->prototype('scalar')->end() ->end() ->arrayNode('options') ->useAttributeAsKey('name') ->prototype('scalar')->end() ->end() ->end() ->validate() ->ifTrue(function($c) { // skip if this contains a service if (isset($c['service'])) { return false; } // for each type at least these have to be set foreach (array('type') as $child) { if (!isset($c[$child])) { return true; } } return false; }) ->thenInvalid("You should set at least the 'type' of a resource owner.") ->end() ->validate() ->ifTrue(function($c) { // skip if this contains a service if (isset($c['service'])) { return false; } // Only validate the 'oauth2' and 'oauth1' type if ('oauth2' !== $c['type'] && 'oauth1' !== $c['type']) { return false; } $children = array('authorization_url', 'access_token_url', 'request_token_url', 'infos_url'); foreach ($children as $child) { // This option exists only for OAuth1.0a if ('request_token_url' === $child && 'oauth2' === $c['type']) { continue; } if (!isset($c[$child])) { return true; } } return false; }) ->thenInvalid("All parameters are mandatory for types 'oauth2' and 'oauth1'. Check if you're missing one of: 'access_token_url', 'authorization_url', 'infos_url' and 'request_token_url' for 'oauth1'.") ->end() ->validate() ->ifTrue(function($c) { // skip if this contains a service if (isset($c['service'])) { return false; } // Only validate the 'oauth2' and 'oauth1' type if ('oauth2' !== $c['type'] && 'oauth1' !== $c['type']) { return false; } // one of this two options must be set if (0 === count($c['paths'])) { return !isset($c['user_response_class']); } foreach (array('identifier', 'nickname', 'realname') as $child) { if (!isset($c['paths'][$child])) { return true; } } return false; }) ->thenInvalid("At least the 'identifier', 'nickname' and 'realname' paths should be configured for 'oauth2' and 'oauth1' types.") ->end() ->validate() ->ifTrue(function($c) { if (isset($c['service'])) { // ignore paths & options if none were set return 0 !== count($c['paths']) || 0 !== count($c['options']) || 3 < count($c); } return false; }) ->thenInvalid("If you're setting a 'service', no other arguments should be set.") ->end() ->end() ->end() ->end() ; return $treeBuilder; } }
{ "content_hash": "1c68da81b1615255457ae72e0f58afc6", "timestamp": "", "source": "github", "line_count": 271, "max_line_length": 229, "avg_line_length": 47.391143911439116, "alnum_prop": 0.29385657556645645, "repo_name": "Gnuckorg/DaOAuthClientBundle", "id": "7a1a708be052af99411b0c834125d71dcb867d79", "size": "13064", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DependencyInjection/Configuration.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "7253" }, { "name": "PHP", "bytes": "61934" } ], "symlink_target": "" }
using PIM.Database.TO; using PIM.Service.Services; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PIM.Desktop { public partial class frmMorador : Form { public frmMorador() { InitializeComponent(); } private void btnMorNovoDep_Click(object sender, EventArgs e) { frmDependenteCadastrar morCadastrarDependente = new frmDependenteCadastrar(); morCadastrarDependente.Show(); } private void btnMorEditarDependente_Click(object sender, EventArgs e) { int idDependente = 0; if (dgMorDependentes.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dgMorDependentes.SelectedRows) { idDependente = (int)row.Cells[0].Value; } } else { foreach (DataGridViewCell cell in dgMorDependentes.SelectedCells) { DataGridViewRow row = dgMorDependentes.Rows[cell.RowIndex]; idDependente = (int)row.Cells[0].Value; } frmDependenteEditar morEditarDependente = new frmDependenteEditar(idDependente); morEditarDependente.Show(); } } private void btnMorExcluirDepemdemte_Click(object sender, EventArgs e) { int idVisitante = 0; if (dgMorDependentes.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dgMorDependentes.SelectedRows) { idVisitante = (int)row.Cells[0].Value; } } else { foreach (DataGridViewCell cell in dgMorDependentes.SelectedCells) { DataGridViewRow row = dgMorDependentes.Rows[cell.RowIndex]; idVisitante = (int)row.Cells[0].Value; } } frmDependenteExcluir morExcluirDependente = new frmDependenteExcluir(idVisitante); morExcluirDependente.Show(); } private void btnMorVisualizarDependente_Click(object sender, EventArgs e) { int idVisitante = 0; if (dgMorDependentes.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dgMorDependentes.SelectedRows) { idVisitante = (int)row.Cells[0].Value; } } else { foreach (DataGridViewCell cell in dgMorDependentes.SelectedCells) { DataGridViewRow row = dgMorDependentes.Rows[cell.RowIndex]; idVisitante = (int)row.Cells[0].Value; } } frmDependenteVisualizar morVisualizarDependente = new frmDependenteVisualizar(idVisitante); morVisualizarDependente.Show(); } private void btnMorCadastrarOcorrencia_Click(object sender, EventArgs e) { frmOcorrenciaCadastrar cadastrarOcorrencia = new frmOcorrenciaCadastrar(); cadastrarOcorrencia.Show(); } private void btnMorEditarOcorrencia_Click(object sender, EventArgs e) { int idOcorrencia = 0; if (dgOcorrencia.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dgOcorrencia.SelectedRows) { idOcorrencia = (int)row.Cells[0].Value; } } else { foreach (DataGridViewCell cell in dgOcorrencia.SelectedCells) { DataGridViewRow row = dgOcorrencia.Rows[cell.RowIndex]; idOcorrencia = (int)row.Cells[0].Value; } } frmOcorrenciaEditar admEditarOcorrencia = new frmOcorrenciaEditar(idOcorrencia); admEditarOcorrencia.Show(); } private void btnMorExcluirOcorrencia_Click(object sender, EventArgs e) { int idOcorrencia = 0; if (dgOcorrencia.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dgOcorrencia.SelectedRows) { idOcorrencia = (int)row.Cells[0].Value; } } else { foreach (DataGridViewCell cell in dgOcorrencia.SelectedCells) { DataGridViewRow row = dgOcorrencia.Rows[cell.RowIndex]; idOcorrencia = (int)row.Cells[0].Value; } } frmOcorrenciaExcluir admExcluirOcorrencia = new frmOcorrenciaExcluir(idOcorrencia); admExcluirOcorrencia.Show(); } private void btnMorVisualizarOcorrencia_Click(object sender, EventArgs e) { int idOcorrencia = 0; if (dgOcorrencia.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dgOcorrencia.SelectedRows) { idOcorrencia = (int)row.Cells[0].Value; } } else { foreach (DataGridViewCell cell in dgOcorrencia.SelectedCells) { DataGridViewRow row = dgOcorrencia.Rows[cell.RowIndex]; idOcorrencia = (int)row.Cells[0].Value; } } frmOcorrenciaVisualizar admVisualizarOcorrencia = new frmOcorrenciaVisualizar(idOcorrencia); admVisualizarOcorrencia.Show(); } private void btnNovoVisitante_Click(object sender, EventArgs e) { frmCadastrarVisitante visitante = new frmCadastrarVisitante(); visitante.Show(); } private void btnEditarVisitante_Click(object sender, EventArgs e) { int idVisitante = 0; if (dgVisitantes.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dgVisitantes.SelectedRows) { idVisitante = (int)row.Cells[0].Value; } } else { foreach (DataGridViewCell cell in dgVisitantes.SelectedCells) { DataGridViewRow row = dgVisitantes.Rows[cell.RowIndex]; idVisitante = (int)row.Cells[0].Value; } } frmVisitanteEditar editarVisitante = new frmVisitanteEditar(idVisitante); editarVisitante.Show(); } private void btnExcluirVisitante_Click(object sender, EventArgs e) { int idVisitante = 0; if (dgVisitantes.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dgVisitantes.SelectedRows) { idVisitante = (int)row.Cells[0].Value; } } else { foreach (DataGridViewCell cell in dgVisitantes.SelectedCells) { DataGridViewRow row = dgVisitantes.Rows[cell.RowIndex]; idVisitante = (int)row.Cells[0].Value; } } frmVisitanteExcluir visitanteExcluir = new frmVisitanteExcluir(idVisitante); visitanteExcluir.Show(); } private void btnVisualizarVisitante_Click(object sender, EventArgs e) { int idVisitante = 0; if (dgVisitantes.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dgVisitantes.SelectedRows) { idVisitante = (int)row.Cells[0].Value; } } else { foreach (DataGridViewCell cell in dgVisitantes.SelectedCells) { DataGridViewRow row = dgVisitantes.Rows[cell.RowIndex]; idVisitante = (int)row.Cells[0].Value; } } frmVisitanteVisualizar visitanteVisualizar = new frmVisitanteVisualizar(idVisitante); visitanteVisualizar.Show(); } private void CarregarDados() { ListaOcorrenciaTO listaOcorrenciaTO = new ListaOcorrenciaTO(); listaOcorrenciaTO = OcorrenciaService.Listar(); dgOcorrencia.DataSource = listaOcorrenciaTO.Lista; dgOcorrencia.Columns["Identificador"].Visible = false; dgOcorrencia.Columns["Valido"].Visible = false; dgOcorrencia.Columns["Mensagem"].Visible = false; dgOcorrencia.ReadOnly = true; ListaVisitanteTO listaVisitanteTO = new ListaVisitanteTO(); listaVisitanteTO = VisitanteService.Listar(); dgVisitantes.DataSource = listaVisitanteTO.Lista; dgVisitantes.Columns["Identificador"].Visible = false; dgVisitantes.Columns["Valido"].Visible = false; dgVisitantes.Columns["Mensagem"].Visible = false; dgVisitantes.ReadOnly = true; ListaDependenteTO listaDependentesTO = new ListaDependenteTO(); listaDependentesTO = DependenteService.Listar(); dgMorDependentes.DataSource = listaDependentesTO.Lista; dgMorDependentes.Columns["Identificador"].Visible = false; dgMorDependentes.Columns["Valido"].Visible = false; dgMorDependentes.Columns["Mensagem"].Visible = false; dgMorDependentes.ReadOnly = true; } private void btnMorAtualizar_Click(object sender, EventArgs e) { CarregarDados(); } private void btnNovaReservaMor_Click(object sender, EventArgs e) { frmReservaCadastrar cadastrarReserva = new frmReservaCadastrar(); cadastrarReserva.Show(); } private void btnEditarReservaMor_Click(object sender, EventArgs e) { int idReserva = 0; if (dgReservasMor.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dgReservasMor.SelectedRows) { idReserva = (int)row.Cells[0].Value; } } else { foreach (DataGridViewCell cell in dgReservasMor.SelectedCells) { DataGridViewRow row = dgReservasMor.Rows[cell.RowIndex]; idReserva = (int)row.Cells[0].Value; } } frmReservaEditar editarReserva = new frmReservaEditar(idReserva); editarReserva.Show(); } private void btnExcluirReservaMor_Click(object sender, EventArgs e) { int idReserva = 0; if (dgReservasMor.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dgReservasMor.SelectedRows) { idReserva = (int)row.Cells[0].Value; } } else { foreach (DataGridViewCell cell in dgReservasMor.SelectedCells) { DataGridViewRow row = dgReservasMor.Rows[cell.RowIndex]; idReserva = (int)row.Cells[0].Value; } } frmReservaExcluir excluirReserva = new frmReservaExcluir(idReserva); excluirReserva.Show(); } private void btnVisualizarReservaMor_Click(object sender, EventArgs e) { int idReserva = 0; if (dgReservasMor.SelectedRows.Count > 0) { foreach (DataGridViewRow row in dgReservasMor.SelectedRows) { idReserva = (int)row.Cells[0].Value; } } else { foreach (DataGridViewCell cell in dgReservasMor.SelectedCells) { DataGridViewRow row = dgReservasMor.Rows[cell.RowIndex]; idReserva = (int)row.Cells[0].Value; } } frmReservaVisualizar visualizarReserva = new frmReservaVisualizar(idReserva); visualizarReserva.Show(); } } }
{ "content_hash": "fa7aae20d2b15d7bbafe77bd9a6aa659", "timestamp": "", "source": "github", "line_count": 377, "max_line_length": 104, "avg_line_length": 33.55172413793103, "alnum_prop": 0.5374337892323504, "repo_name": "LucasMonteiroi/pim-condominio", "id": "12270aaca6b0f62b34311b2fef6f98a68fe6db8d", "size": "12651", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "01_Desenvolvimento/project/PIM/PIM.Desktop/frmMorador.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "196" }, { "name": "C#", "bytes": "894870" }, { "name": "CSS", "bytes": "1056832" }, { "name": "JavaScript", "bytes": "6742288" }, { "name": "PowerShell", "bytes": "169189" } ], "symlink_target": "" }
namespace ui { namespace { // A scoper to manage acquiring and automatically releasing the clipboard. class ScopedClipboard { public: ScopedClipboard() : opened_(false) { } ~ScopedClipboard() { if (opened_) Release(); } bool Acquire(HWND owner) { const int kMaxAttemptsToOpenClipboard = 5; if (opened_) { NOTREACHED(); return false; } // Attempt to open the clipboard, which will acquire the Windows clipboard // lock. This may fail if another process currently holds this lock. // We're willing to try a few times in the hopes of acquiring it. // // This turns out to be an issue when using remote desktop because the // rdpclip.exe process likes to read what we've written to the clipboard and // send it to the RDP client. If we open and close the clipboard in quick // succession, we might be trying to open it while rdpclip.exe has it open, // See Bug 815425. // // In fact, we believe we'll only spin this loop over remote desktop. In // normal situations, the user is initiating clipboard operations and there // shouldn't be contention. for (int attempts = 0; attempts < kMaxAttemptsToOpenClipboard; ++attempts) { // If we didn't manage to open the clipboard, sleep a bit and be hopeful. if (attempts != 0) ::Sleep(5); if (::OpenClipboard(owner)) { opened_ = true; return true; } } // We failed to acquire the clipboard. return false; } void Release() { if (opened_) { ::CloseClipboard(); opened_ = false; } else { NOTREACHED(); } } private: bool opened_; }; LRESULT CALLBACK ClipboardOwnerWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { LRESULT lresult = 0; switch (message) { case WM_RENDERFORMAT: // This message comes when SetClipboardData was sent a null data handle // and now it's come time to put the data on the clipboard. // We always set data, so there isn't a need to actually do anything here. break; case WM_RENDERALLFORMATS: // This message comes when SetClipboardData was sent a null data handle // and now this application is about to quit, so it must put data on // the clipboard before it exits. // We always set data, so there isn't a need to actually do anything here. break; case WM_DRAWCLIPBOARD: break; case WM_DESTROY: break; case WM_CHANGECBCHAIN: break; default: lresult = DefWindowProc(hwnd, message, wparam, lparam); break; } return lresult; } template <typename charT> HGLOBAL CreateGlobalData(const std::basic_string<charT>& str) { HGLOBAL data = ::GlobalAlloc(GMEM_MOVEABLE, ((str.size() + 1) * sizeof(charT))); if (data) { charT* raw_data = static_cast<charT*>(::GlobalLock(data)); memcpy(raw_data, str.data(), str.size() * sizeof(charT)); raw_data[str.size()] = '\0'; ::GlobalUnlock(data); } return data; }; bool BitmapHasInvalidPremultipliedColors(const SkBitmap& bitmap) { for (int x = 0; x < bitmap.width(); ++x) { for (int y = 0; y < bitmap.height(); ++y) { uint32_t pixel = *bitmap.getAddr32(x, y); if (SkColorGetR(pixel) > SkColorGetA(pixel) || SkColorGetG(pixel) > SkColorGetA(pixel) || SkColorGetB(pixel) > SkColorGetA(pixel)) return true; } } return false; } void MakeBitmapOpaque(const SkBitmap& bitmap) { for (int x = 0; x < bitmap.width(); ++x) { for (int y = 0; y < bitmap.height(); ++y) { *bitmap.getAddr32(x, y) = SkColorSetA(*bitmap.getAddr32(x, y), 0xFF); } } } } // namespace Clipboard::FormatType::FormatType() : data_() {} Clipboard::FormatType::FormatType(UINT native_format) : data_() { // There's no good way to actually initialize this in the constructor in // C++03. data_.cfFormat = native_format; data_.dwAspect = DVASPECT_CONTENT; data_.lindex = -1; data_.tymed = TYMED_HGLOBAL; } Clipboard::FormatType::FormatType(UINT native_format, LONG index) : data_() { // There's no good way to actually initialize this in the constructor in // C++03. data_.cfFormat = native_format; data_.dwAspect = DVASPECT_CONTENT; data_.lindex = index; data_.tymed = TYMED_HGLOBAL; } Clipboard::FormatType::~FormatType() { } std::string Clipboard::FormatType::Serialize() const { return base::IntToString(data_.cfFormat); } // static Clipboard::FormatType Clipboard::FormatType::Deserialize( const std::string& serialization) { int clipboard_format = -1; if (!base::StringToInt(serialization, &clipboard_format)) { NOTREACHED(); return FormatType(); } return FormatType(clipboard_format); } bool Clipboard::FormatType::operator<(const FormatType& other) const { return ToUINT() < other.ToUINT(); } Clipboard::Clipboard() : create_window_(false) { if (base::MessageLoop::current()->type() == base::MessageLoop::TYPE_UI) { // Make a dummy HWND to be the clipboard's owner. WNDCLASSEX window_class; base::win::InitializeWindowClass( L"ClipboardOwnerWindowClass", &base::win::WrappedWindowProc<ClipboardOwnerWndProc>, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, &window_class); ::RegisterClassEx(&window_class); create_window_ = true; } clipboard_owner_ = NULL; } Clipboard::~Clipboard() { if (clipboard_owner_) ::DestroyWindow(clipboard_owner_); clipboard_owner_ = NULL; } void Clipboard::WriteObjectsImpl(Buffer buffer, const ObjectMap& objects, SourceTag tag) { DCHECK_EQ(buffer, BUFFER_STANDARD); ScopedClipboard clipboard; if (!clipboard.Acquire(GetClipboardWindow())) return; ::EmptyClipboard(); for (ObjectMap::const_iterator iter = objects.begin(); iter != objects.end(); ++iter) { DispatchObject(static_cast<ObjectType>(iter->first), iter->second); } WriteSourceTag(tag); } void Clipboard::WriteText(const char* text_data, size_t text_len) { string16 text; UTF8ToUTF16(text_data, text_len, &text); HGLOBAL glob = CreateGlobalData(text); WriteToClipboard(CF_UNICODETEXT, glob); } void Clipboard::WriteHTML(const char* markup_data, size_t markup_len, const char* url_data, size_t url_len) { std::string markup(markup_data, markup_len); std::string url; if (url_len > 0) url.assign(url_data, url_len); std::string html_fragment = ClipboardUtil::HtmlToCFHtml(markup, url); HGLOBAL glob = CreateGlobalData(html_fragment); WriteToClipboard(Clipboard::GetHtmlFormatType().ToUINT(), glob); } void Clipboard::WriteRTF(const char* rtf_data, size_t data_len) { WriteData(GetRtfFormatType(), rtf_data, data_len); } void Clipboard::WriteBookmark(const char* title_data, size_t title_len, const char* url_data, size_t url_len) { std::string bookmark(title_data, title_len); bookmark.append(1, L'\n'); bookmark.append(url_data, url_len); string16 wide_bookmark = UTF8ToWide(bookmark); HGLOBAL glob = CreateGlobalData(wide_bookmark); WriteToClipboard(GetUrlWFormatType().ToUINT(), glob); } void Clipboard::WriteWebSmartPaste() { DCHECK(clipboard_owner_); ::SetClipboardData(GetWebKitSmartPasteFormatType().ToUINT(), NULL); } void Clipboard::WriteBitmap(const char* pixel_data, const char* size_data) { const gfx::Size* size = reinterpret_cast<const gfx::Size*>(size_data); HDC dc = ::GetDC(NULL); // This doesn't actually cost us a memcpy when the bitmap comes from the // renderer as we load it into the bitmap using setPixels which just sets a // pointer. Someone has to memcpy it into GDI, it might as well be us here. // TODO(darin): share data in gfx/bitmap_header.cc somehow BITMAPINFO bm_info = {0}; bm_info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bm_info.bmiHeader.biWidth = size->width(); bm_info.bmiHeader.biHeight = -size->height(); // sets vertical orientation bm_info.bmiHeader.biPlanes = 1; bm_info.bmiHeader.biBitCount = 32; bm_info.bmiHeader.biCompression = BI_RGB; // ::CreateDIBSection allocates memory for us to copy our bitmap into. // Unfortunately, we can't write the created bitmap to the clipboard, // (see http://msdn2.microsoft.com/en-us/library/ms532292.aspx) void *bits; HBITMAP source_hbitmap = ::CreateDIBSection(dc, &bm_info, DIB_RGB_COLORS, &bits, NULL, 0); if (bits && source_hbitmap) { // Copy the bitmap out of shared memory and into GDI memcpy(bits, pixel_data, 4 * size->width() * size->height()); // Now we have an HBITMAP, we can write it to the clipboard WriteBitmapFromHandle(source_hbitmap, *size); } ::DeleteObject(source_hbitmap); ::ReleaseDC(NULL, dc); } void Clipboard::WriteBitmapFromHandle(HBITMAP source_hbitmap, const gfx::Size& size) { // We would like to just call ::SetClipboardData on the source_hbitmap, // but that bitmap might not be of a sort we can write to the clipboard. // For this reason, we create a new bitmap, copy the bits over, and then // write that to the clipboard. HDC dc = ::GetDC(NULL); HDC compatible_dc = ::CreateCompatibleDC(NULL); HDC source_dc = ::CreateCompatibleDC(NULL); // This is the HBITMAP we will eventually write to the clipboard HBITMAP hbitmap = ::CreateCompatibleBitmap(dc, size.width(), size.height()); if (!hbitmap) { // Failed to create the bitmap ::DeleteDC(compatible_dc); ::DeleteDC(source_dc); ::ReleaseDC(NULL, dc); return; } HBITMAP old_hbitmap = (HBITMAP)SelectObject(compatible_dc, hbitmap); HBITMAP old_source = (HBITMAP)SelectObject(source_dc, source_hbitmap); // Now we need to blend it into an HBITMAP we can place on the clipboard BLENDFUNCTION bf = {AC_SRC_OVER, 0, 255, AC_SRC_ALPHA}; ::GdiAlphaBlend(compatible_dc, 0, 0, size.width(), size.height(), source_dc, 0, 0, size.width(), size.height(), bf); // Clean up all the handles we just opened ::SelectObject(compatible_dc, old_hbitmap); ::SelectObject(source_dc, old_source); ::DeleteObject(old_hbitmap); ::DeleteObject(old_source); ::DeleteDC(compatible_dc); ::DeleteDC(source_dc); ::ReleaseDC(NULL, dc); WriteToClipboard(CF_BITMAP, hbitmap); } void Clipboard::WriteData(const FormatType& format, const char* data_data, size_t data_len) { HGLOBAL hdata = ::GlobalAlloc(GMEM_MOVEABLE, data_len); if (!hdata) return; char* data = static_cast<char*>(::GlobalLock(hdata)); memcpy(data, data_data, data_len); ::GlobalUnlock(data); WriteToClipboard(format.ToUINT(), hdata); } void Clipboard::WriteSourceTag(SourceTag tag) { if (tag != SourceTag()) { ObjectMapParam binary = SourceTag2Binary(tag); WriteData(GetSourceTagFormatType(), &binary[0], binary.size()); } } void Clipboard::WriteToClipboard(unsigned int format, HANDLE handle) { DCHECK(clipboard_owner_); if (handle && !::SetClipboardData(format, handle)) { DCHECK(ERROR_CLIPBOARD_NOT_OPEN != GetLastError()); FreeData(format, handle); } } uint64 Clipboard::GetSequenceNumber(Buffer buffer) { DCHECK_EQ(buffer, BUFFER_STANDARD); return ::GetClipboardSequenceNumber(); } bool Clipboard::IsFormatAvailable(const Clipboard::FormatType& format, Clipboard::Buffer buffer) const { DCHECK_EQ(buffer, BUFFER_STANDARD); return ::IsClipboardFormatAvailable(format.ToUINT()) != FALSE; } void Clipboard::Clear(Buffer buffer) { DCHECK_EQ(buffer, BUFFER_STANDARD); ScopedClipboard clipboard; if (!clipboard.Acquire(GetClipboardWindow())) return; ::EmptyClipboard(); } void Clipboard::ReadAvailableTypes(Clipboard::Buffer buffer, std::vector<string16>* types, bool* contains_filenames) const { if (!types || !contains_filenames) { NOTREACHED(); return; } types->clear(); if (::IsClipboardFormatAvailable(GetPlainTextFormatType().ToUINT())) types->push_back(UTF8ToUTF16(kMimeTypeText)); if (::IsClipboardFormatAvailable(GetHtmlFormatType().ToUINT())) types->push_back(UTF8ToUTF16(kMimeTypeHTML)); if (::IsClipboardFormatAvailable(GetRtfFormatType().ToUINT())) types->push_back(UTF8ToUTF16(kMimeTypeRTF)); if (::IsClipboardFormatAvailable(CF_DIB)) types->push_back(UTF8ToUTF16(kMimeTypePNG)); *contains_filenames = false; // Acquire the clipboard. ScopedClipboard clipboard; if (!clipboard.Acquire(GetClipboardWindow())) return; HANDLE hdata = ::GetClipboardData(GetWebCustomDataFormatType().ToUINT()); if (!hdata) return; ReadCustomDataTypes(::GlobalLock(hdata), ::GlobalSize(hdata), types); ::GlobalUnlock(hdata); } void Clipboard::ReadText(Clipboard::Buffer buffer, string16* result) const { DCHECK_EQ(buffer, BUFFER_STANDARD); if (!result) { NOTREACHED(); return; } result->clear(); // Acquire the clipboard. ScopedClipboard clipboard; if (!clipboard.Acquire(GetClipboardWindow())) return; HANDLE data = ::GetClipboardData(CF_UNICODETEXT); if (!data) return; result->assign(static_cast<const char16*>(::GlobalLock(data))); ::GlobalUnlock(data); } void Clipboard::ReadAsciiText(Clipboard::Buffer buffer, std::string* result) const { DCHECK_EQ(buffer, BUFFER_STANDARD); if (!result) { NOTREACHED(); return; } result->clear(); // Acquire the clipboard. ScopedClipboard clipboard; if (!clipboard.Acquire(GetClipboardWindow())) return; HANDLE data = ::GetClipboardData(CF_TEXT); if (!data) return; result->assign(static_cast<const char*>(::GlobalLock(data))); ::GlobalUnlock(data); } void Clipboard::ReadHTML(Clipboard::Buffer buffer, string16* markup, std::string* src_url, uint32* fragment_start, uint32* fragment_end) const { DCHECK_EQ(buffer, BUFFER_STANDARD); markup->clear(); // TODO(dcheng): Remove these checks, I don't think they should be optional. DCHECK(src_url); if (src_url) src_url->clear(); *fragment_start = 0; *fragment_end = 0; // Acquire the clipboard. ScopedClipboard clipboard; if (!clipboard.Acquire(GetClipboardWindow())) return; HANDLE data = ::GetClipboardData(GetHtmlFormatType().ToUINT()); if (!data) return; std::string cf_html(static_cast<const char*>(::GlobalLock(data))); ::GlobalUnlock(data); size_t html_start = std::string::npos; size_t start_index = std::string::npos; size_t end_index = std::string::npos; ClipboardUtil::CFHtmlExtractMetadata(cf_html, src_url, &html_start, &start_index, &end_index); // This might happen if the contents of the clipboard changed and CF_HTML is // no longer available. if (start_index == std::string::npos || end_index == std::string::npos || html_start == std::string::npos) return; if (start_index < html_start || end_index < start_index) return; std::vector<size_t> offsets; offsets.push_back(start_index - html_start); offsets.push_back(end_index - html_start); markup->assign(base::UTF8ToUTF16AndAdjustOffsets(cf_html.data() + html_start, &offsets)); *fragment_start = base::checked_numeric_cast<uint32>(offsets[0]); *fragment_end = base::checked_numeric_cast<uint32>(offsets[1]); } void Clipboard::ReadRTF(Buffer buffer, std::string* result) const { DCHECK_EQ(buffer, BUFFER_STANDARD); ReadData(GetRtfFormatType(), result); } SkBitmap Clipboard::ReadImage(Buffer buffer) const { DCHECK_EQ(buffer, BUFFER_STANDARD); // Acquire the clipboard. ScopedClipboard clipboard; if (!clipboard.Acquire(GetClipboardWindow())) return SkBitmap(); // We use a DIB rather than a DDB here since ::GetObject() with the // HBITMAP returned from ::GetClipboardData(CF_BITMAP) always reports a color // depth of 32bpp. BITMAPINFO* bitmap = static_cast<BITMAPINFO*>(::GetClipboardData(CF_DIB)); if (!bitmap) return SkBitmap(); int color_table_length = 0; switch (bitmap->bmiHeader.biBitCount) { case 1: case 4: case 8: color_table_length = bitmap->bmiHeader.biClrUsed ? bitmap->bmiHeader.biClrUsed : 1 << bitmap->bmiHeader.biBitCount; break; case 16: case 32: if (bitmap->bmiHeader.biCompression == BI_BITFIELDS) color_table_length = 3; break; case 24: break; default: NOTREACHED(); } const void* bitmap_bits = reinterpret_cast<const char*>(bitmap) + bitmap->bmiHeader.biSize + color_table_length * sizeof(RGBQUAD); gfx::Canvas canvas(gfx::Size(bitmap->bmiHeader.biWidth, bitmap->bmiHeader.biHeight), ui::SCALE_FACTOR_100P, false); { skia::ScopedPlatformPaint scoped_platform_paint(canvas.sk_canvas()); HDC dc = scoped_platform_paint.GetPlatformSurface(); ::SetDIBitsToDevice(dc, 0, 0, bitmap->bmiHeader.biWidth, bitmap->bmiHeader.biHeight, 0, 0, 0, bitmap->bmiHeader.biHeight, bitmap_bits, bitmap, DIB_RGB_COLORS); } // Windows doesn't really handle alpha channels well in many situations. When // the source image is < 32 bpp, we force the bitmap to be opaque. When the // source image is 32 bpp, the alpha channel might still contain garbage data. // Since Windows uses premultiplied alpha, we scan for instances where // (R, G, B) > A. If there are any invalid premultiplied colors in the image, // we assume the alpha channel contains garbage and force the bitmap to be // opaque as well. Note that this heuristic will fail on a transparent bitmap // containing only black pixels... const SkBitmap& device_bitmap = canvas.sk_canvas()->getDevice()->accessBitmap(true); { SkAutoLockPixels lock(device_bitmap); bool has_invalid_alpha_channel = bitmap->bmiHeader.biBitCount < 32 || BitmapHasInvalidPremultipliedColors(device_bitmap); if (has_invalid_alpha_channel) { MakeBitmapOpaque(device_bitmap); } } return canvas.ExtractImageRep().sk_bitmap(); } void Clipboard::ReadCustomData(Buffer buffer, const string16& type, string16* result) const { DCHECK_EQ(buffer, BUFFER_STANDARD); // Acquire the clipboard. ScopedClipboard clipboard; if (!clipboard.Acquire(GetClipboardWindow())) return; HANDLE hdata = ::GetClipboardData(GetWebCustomDataFormatType().ToUINT()); if (!hdata) return; ReadCustomDataForType(::GlobalLock(hdata), ::GlobalSize(hdata), type, result); ::GlobalUnlock(hdata); } void Clipboard::ReadBookmark(string16* title, std::string* url) const { if (title) title->clear(); if (url) url->clear(); // Acquire the clipboard. ScopedClipboard clipboard; if (!clipboard.Acquire(GetClipboardWindow())) return; HANDLE data = ::GetClipboardData(GetUrlWFormatType().ToUINT()); if (!data) return; string16 bookmark(static_cast<const char16*>(::GlobalLock(data))); ::GlobalUnlock(data); ParseBookmarkClipboardFormat(bookmark, title, url); } void Clipboard::ReadData(const FormatType& format, std::string* result) const { if (!result) { NOTREACHED(); return; } ScopedClipboard clipboard; if (!clipboard.Acquire(GetClipboardWindow())) return; HANDLE data = ::GetClipboardData(format.ToUINT()); if (!data) return; result->assign(static_cast<const char*>(::GlobalLock(data)), ::GlobalSize(data)); ::GlobalUnlock(data); } SourceTag Clipboard::ReadSourceTag(Buffer buffer) const { DCHECK_EQ(buffer, BUFFER_STANDARD); std::string result; ReadData(GetSourceTagFormatType(), &result); return Binary2SourceTag(result); } // static void Clipboard::ParseBookmarkClipboardFormat(const string16& bookmark, string16* title, std::string* url) { const string16 kDelim = ASCIIToUTF16("\r\n"); const size_t title_end = bookmark.find_first_of(kDelim); if (title) title->assign(bookmark.substr(0, title_end)); if (url) { const size_t url_start = bookmark.find_first_not_of(kDelim, title_end); if (url_start != string16::npos) *url = UTF16ToUTF8(bookmark.substr(url_start, string16::npos)); } } // static Clipboard::FormatType Clipboard::GetFormatType( const std::string& format_string) { return FormatType( ::RegisterClipboardFormat(ASCIIToWide(format_string).c_str())); } // static const Clipboard::FormatType& Clipboard::GetUrlFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(CFSTR_INETURLA))); return type; } // static const Clipboard::FormatType& Clipboard::GetUrlWFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(CFSTR_INETURLW))); return type; } // static const Clipboard::FormatType& Clipboard::GetMozUrlFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(L"text/x-moz-url"))); return type; } // static const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() { CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_TEXT)); return type; } // static const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() { CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_UNICODETEXT)); return type; } // static const Clipboard::FormatType& Clipboard::GetFilenameFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(CFSTR_FILENAMEA))); return type; } // static const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(CFSTR_FILENAMEW))); return type; } // MS HTML Format // static const Clipboard::FormatType& Clipboard::GetHtmlFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(L"HTML Format"))); return type; } // MS RTF Format // static const Clipboard::FormatType& Clipboard::GetRtfFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(L"Rich Text Format"))); return type; } // static const Clipboard::FormatType& Clipboard::GetBitmapFormatType() { CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_BITMAP)); return type; } // Firefox text/html // static const Clipboard::FormatType& Clipboard::GetTextHtmlFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(L"text/html"))); return type; } // static const Clipboard::FormatType& Clipboard::GetCFHDropFormatType() { CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_HDROP)); return type; } // static const Clipboard::FormatType& Clipboard::GetFileDescriptorFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(CFSTR_FILEDESCRIPTOR))); return type; } // static const Clipboard::FormatType& Clipboard::GetFileContentZeroFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(CFSTR_FILECONTENTS), 0)); return type; } // static const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(L"WebKit Smart Paste Format"))); return type; } // static const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() { // TODO(dcheng): This name is temporary. See http://crbug.com/106449. CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(L"Chromium Web Custom MIME Data Format"))); return type; } // static const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(L"Chromium Pepper MIME Data Format"))); return type; } // static const Clipboard::FormatType& Clipboard::GetSourceTagFormatType() { CR_DEFINE_STATIC_LOCAL( FormatType, type, (::RegisterClipboardFormat(L"Chromium Source tag Format"))); return type; } // static void Clipboard::FreeData(unsigned int format, HANDLE data) { if (format == CF_BITMAP) ::DeleteObject(static_cast<HBITMAP>(data)); else ::GlobalFree(data); } HWND Clipboard::GetClipboardWindow() const { if (!clipboard_owner_ && create_window_) { clipboard_owner_ = ::CreateWindow(L"ClipboardOwnerWindowClass", L"ClipboardOwnerWindow", 0, 0, 0, 0, 0, HWND_MESSAGE, 0, 0, 0); } return clipboard_owner_; } } // namespace ui
{ "content_hash": "dbc3b78775e5ed3df11bba544ba5d3a0", "timestamp": "", "source": "github", "line_count": 832, "max_line_length": 80, "avg_line_length": 30.19591346153846, "alnum_prop": 0.6609879393384548, "repo_name": "loopCM/chromium", "id": "2935ea2173019baf0f7f1b1c1ff76ae08ea32251", "size": "26185", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "ui/base/clipboard/clipboard_win.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.github.ambry.store; import com.codahale.metrics.Counter; import com.codahale.metrics.MetricRegistry; import com.github.ambry.account.InMemAccountService; import com.github.ambry.accountstats.AccountStatsStore; import com.github.ambry.clustermap.ClusterMapUtils; import com.github.ambry.clustermap.ClusterParticipant; import com.github.ambry.clustermap.DataNodeId; import com.github.ambry.clustermap.DiskId; import com.github.ambry.clustermap.HardwareState; import com.github.ambry.clustermap.HelixParticipant; import com.github.ambry.clustermap.MockClusterMap; import com.github.ambry.clustermap.MockDataNodeId; import com.github.ambry.clustermap.MockHelixManagerFactory; import com.github.ambry.clustermap.MockPartitionId; import com.github.ambry.clustermap.PartitionId; import com.github.ambry.clustermap.PartitionStateChangeListener; import com.github.ambry.clustermap.ReplicaId; import com.github.ambry.clustermap.ReplicaState; import com.github.ambry.clustermap.StateModelListenerType; import com.github.ambry.clustermap.StateTransitionException; import com.github.ambry.commons.Callback; import com.github.ambry.config.ClusterMapConfig; import com.github.ambry.config.DiskManagerConfig; import com.github.ambry.config.StoreConfig; import com.github.ambry.config.VerifiableProperties; import com.github.ambry.server.AmbryStatsReport; import com.github.ambry.server.storagestats.AggregatedAccountStorageStats; import com.github.ambry.utils.Pair; import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.TestUtils; import com.github.ambry.utils.Utils; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.helix.HelixAdmin; import org.apache.helix.model.InstanceConfig; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import static com.github.ambry.clustermap.ClusterMapUtils.*; import static com.github.ambry.clustermap.StateTransitionException.TransitionErrorCode.*; import static com.github.ambry.clustermap.TestUtils.*; import static com.github.ambry.store.BlobStoreTest.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; /** * Test {@link StorageManager} and {@link DiskManager} */ public class StorageManagerTest { private static final Random RANDOM = new Random(); private static final String CLUSTER_NAME = "AmbryTestCluster"; private DiskManagerConfig diskManagerConfig; private ClusterMapConfig clusterMapConfig; private StoreConfig storeConfig; private MockClusterMap clusterMap; private MetricRegistry metricRegistry; /** * Startup the {@link MockClusterMap} for a test. * @throws IOException */ @Before public void initializeCluster() throws IOException { clusterMap = new MockClusterMap(false, true, 1, 3, 3, false, false, null); metricRegistry = clusterMap.getMetricRegistry(); generateConfigs(false, false); } /** * Cleanup the {@link MockClusterMap} after a test. * @throws IOException */ @After public void cleanupCluster() throws IOException { if (clusterMap != null) { clusterMap.cleanup(); } } /** * Test that stores on a disk without a valid mount path are not started. * @throws Exception */ @Test public void mountPathNotFoundTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); List<String> mountPaths = dataNode.getMountPaths(); String mountPathToDelete = mountPaths.get(RANDOM.nextInt(mountPaths.size())); int downReplicaCount = 0; for (ReplicaId replica : replicas) { if (replica.getMountPath().equals(mountPathToDelete)) { downReplicaCount++; } } Utils.deleteFileOrDirectory(new File(mountPathToDelete)); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); storageManager.start(); assertEquals("There should be no unexpected partitions reported", 0, getNumUnrecognizedPartitionsReported()); Map<String, Counter> counters = metricRegistry.getCounters(); assertEquals("DiskSpaceAllocator should not have failed to start.", 0, getCounterValue(counters, DiskSpaceAllocator.class.getName(), "DiskSpaceAllocatorInitFailureCount")); assertEquals("Unexpected number of store start failures", downReplicaCount, getCounterValue(counters, DiskManager.class.getName(), "TotalStoreStartFailures")); assertEquals("Expected 1 disk mount path failure", 1, getCounterValue(counters, DiskManager.class.getName(), "DiskMountPathFailures")); assertEquals("There should be no unexpected partitions reported", 0, getNumUnrecognizedPartitionsReported()); checkStoreAccessibility(replicas, mountPathToDelete, storageManager); assertEquals("Compaction thread count is incorrect", mountPaths.size() - 1, TestUtils.numThreadsByThisName(CompactionManager.THREAD_NAME_PREFIX)); verifyCompactionThreadCount(storageManager, mountPaths.size() - 1); shutdownAndAssertStoresInaccessible(storageManager, replicas); assertEquals("Compaction thread count is incorrect", 0, storageManager.getCompactionThreadCount()); } /** * Tests that schedule compaction and control compaction in StorageManager * @throws Exception */ @Test public void scheduleAndControlCompactionTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); List<MockDataNodeId> dataNodes = new ArrayList<>(); dataNodes.add(dataNode); MockPartitionId invalidPartition = new MockPartitionId(Long.MAX_VALUE, MockClusterMap.DEFAULT_PARTITION_CLASS, dataNodes, 0); List<? extends ReplicaId> invalidPartitionReplicas = invalidPartition.getReplicaIds(); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); storageManager.start(); assertEquals("There should be 1 unexpected partition reported", 1, getNumUnrecognizedPartitionsReported()); // add invalid replica id replicas.add(invalidPartitionReplicas.get(0)); for (int i = 0; i < replicas.size(); i++) { ReplicaId replica = replicas.get(i); PartitionId id = replica.getPartitionId(); if (i == replicas.size() - 1) { assertFalse("Schedule compaction should fail", storageManager.scheduleNextForCompaction(id)); assertFalse("Disable compaction should fail", storageManager.controlCompactionForBlobStore(id, false)); assertFalse("Enable compaction should fail", storageManager.controlCompactionForBlobStore(id, true)); } else { assertTrue("Enable compaction should succeed", storageManager.controlCompactionForBlobStore(id, true)); assertTrue("Schedule compaction should succeed", storageManager.scheduleNextForCompaction(id)); } } ReplicaId replica = replicas.get(0); PartitionId id = replica.getPartitionId(); assertTrue("Disable compaction should succeed", storageManager.controlCompactionForBlobStore(id, false)); assertFalse("Schedule compaction should fail", storageManager.scheduleNextForCompaction(id)); assertTrue("Enable compaction should succeed", storageManager.controlCompactionForBlobStore(id, true)); assertTrue("Schedule compaction should succeed", storageManager.scheduleNextForCompaction(id)); replica = replicas.get(1); id = replica.getPartitionId(); assertTrue("Schedule compaction should succeed", storageManager.scheduleNextForCompaction(id)); replicas.remove(replicas.size() - 1); shutdownAndAssertStoresInaccessible(storageManager, replicas); } /** * Test add new BlobStore with given {@link ReplicaId}. */ @Test public void addBlobStoreTest() throws Exception { generateConfigs(true, false); MockDataNodeId localNode = clusterMap.getDataNodes().get(0); List<ReplicaId> localReplicas = clusterMap.getReplicaIds(localNode); int newMountPathIndex = 3; // add new MountPath to local node File f = File.createTempFile("ambry", ".tmp"); File mountFile = new File(f.getParent(), "mountpathfile" + MockClusterMap.PLAIN_TEXT_PORT_START_NUMBER + newMountPathIndex); MockClusterMap.deleteFileOrDirectory(mountFile); assertTrue("Couldn't create mount path directory", mountFile.mkdir()); localNode.addMountPaths(Collections.singletonList(mountFile.getAbsolutePath())); PartitionId newPartition1 = new MockPartitionId(10L, MockClusterMap.DEFAULT_PARTITION_CLASS, clusterMap.getDataNodes(), newMountPathIndex); StorageManager storageManager = createStorageManager(localNode, metricRegistry, null); storageManager.start(); // test add store that already exists, which should fail assertFalse("Add store which is already existing should fail", storageManager.addBlobStore(localReplicas.get(0))); // test add store onto a new disk, which should succeed assertTrue("Add new store should succeed", storageManager.addBlobStore(newPartition1.getReplicaIds().get(0))); assertNotNull("The store shouldn't be null because new store is successfully added", storageManager.getStore(newPartition1, false)); // test add store whose diskManager is not running, which should fail PartitionId newPartition2 = new MockPartitionId(11L, MockClusterMap.DEFAULT_PARTITION_CLASS, clusterMap.getDataNodes(), 0); storageManager.getDiskManager(localReplicas.get(0).getPartitionId()).shutdown(); assertFalse("Add store onto the DiskManager which is not running should fail", storageManager.addBlobStore(newPartition2.getReplicaIds().get(0))); storageManager.getDiskManager(localReplicas.get(0).getPartitionId()).start(); // test replica addition can correctly handle existing dir (should delete it and create a new one) // To verify the directory has been recreated, we purposely put a test file in previous dir. PartitionId newPartition3 = new MockPartitionId(12L, MockClusterMap.DEFAULT_PARTITION_CLASS, clusterMap.getDataNodes(), 0); ReplicaId replicaToAdd = newPartition3.getReplicaIds().get(0); File previousDir = new File(replicaToAdd.getReplicaPath()); File testFile = new File(previousDir, "testFile"); MockClusterMap.deleteFileOrDirectory(previousDir); assertTrue("Cannot create dir for " + replicaToAdd.getReplicaPath(), previousDir.mkdir()); assertTrue("Cannot create test file within previous dir", testFile.createNewFile()); assertTrue("Adding new store should succeed", storageManager.addBlobStore(replicaToAdd)); assertFalse("Test file should not exist", testFile.exists()); assertNotNull("Store associated new added replica should not be null", storageManager.getStore(newPartition3, false)); shutdownAndAssertStoresInaccessible(storageManager, localReplicas); // test add store but fail to add segment requirements to DiskSpaceAllocator. (This is simulated by inducing // addRequiredSegments failure to make store inaccessible) List<String> mountPaths = localNode.getMountPaths(); String diskToFail = mountPaths.get(0); File reservePoolDir = new File(diskToFail, diskManagerConfig.diskManagerReserveFileDirName); File storeReserveDir = new File(reservePoolDir, DiskSpaceAllocator.STORE_DIR_PREFIX + newPartition2.toPathString()); StorageManager storageManager2 = createStorageManager(localNode, new MetricRegistry(), null); storageManager2.start(); Utils.deleteFileOrDirectory(storeReserveDir); assertTrue("File creation should succeed", storeReserveDir.createNewFile()); assertFalse("Add store should fail if store couldn't start due to initializePool failure", storageManager2.addBlobStore(newPartition2.getReplicaIds().get(0))); assertNull("New store shouldn't be in in-memory data structure", storageManager2.getStore(newPartition2, false)); shutdownAndAssertStoresInaccessible(storageManager2, localReplicas); } /** * test that both success and failure in storage manager when replica becomes BOOTSTRAP from OFFLINE (update * InstanceConfig in Helix is turned off in this test) * @throws Exception */ @Test public void replicaFromOfflineToBootstrapTest() throws Exception { generateConfigs(true, false); MockDataNodeId localNode = clusterMap.getDataNodes().get(0); List<PartitionId> partitionIds = clusterMap.getAllPartitionIds(null); List<ReplicaId> localReplicas = clusterMap.getReplicaIds(localNode); MockClusterParticipant mockHelixParticipant = new MockClusterParticipant(); StorageManager storageManager = createStorageManager(localNode, metricRegistry, Collections.singletonList(mockHelixParticipant)); storageManager.start(); // 1. get listeners from Helix participant and verify there is a storageManager listener. Map<StateModelListenerType, PartitionStateChangeListener> listeners = mockHelixParticipant.getPartitionStateChangeListeners(); assertTrue("Should contain storage manager listener", listeners.containsKey(StateModelListenerType.StorageManagerListener)); // 2. if new bootstrap replica is not found, there should be an exception try { mockHelixParticipant.onPartitionBecomeBootstrapFromOffline(String.valueOf(partitionIds.size() + 1)); fail("should fail due to bootstrap replica not found"); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", ReplicaNotFound, e.getErrorCode()); } // 3. test regular store didn't start up (which triggers StoreNotStarted exception) ReplicaId replicaId = localReplicas.get(0); Store localStore = storageManager.getStore(replicaId.getPartitionId(), true); localStore.shutdown(); try { mockHelixParticipant.onPartitionBecomeBootstrapFromOffline(replicaId.getPartitionId().toPathString()); fail("should fail due to store not started"); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", StoreNotStarted, e.getErrorCode()); } localStore.start(); // 4. test both failure and success cases regarding new replica addition PartitionId newPartition = clusterMap.createNewPartition(Collections.singletonList(localNode)); assertNull("There should not be any store associated with new partition", storageManager.getStore(newPartition, true)); // find an existing replica that shares disk with new replica ReplicaId newReplica = newPartition.getReplicaIds().get(0); ReplicaId replicaOnSameDisk = localReplicas.stream().filter(r -> r.getDiskId().equals(newReplica.getDiskId())).findFirst().get(); // test add new store failure by shutting down target diskManager storageManager.getDiskManager(replicaOnSameDisk.getPartitionId()).shutdown(); try { mockHelixParticipant.onPartitionBecomeBootstrapFromOffline(newPartition.toPathString()); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", ReplicaOperationFailure, e.getErrorCode()); } // restart disk manager to test case where new replica(store) is successfully added into StorageManager storageManager.getDiskManager(replicaOnSameDisk.getPartitionId()).start(); mockHelixParticipant.onPartitionBecomeBootstrapFromOffline(newPartition.toPathString()); BlobStore newAddedStore = (BlobStore) storageManager.getStore(newPartition); assertNotNull("There should be a started store associated with new partition", newAddedStore); // 5. verify that new added store has bootstrap file assertTrue("There should be a bootstrap file indicating store is in BOOTSTRAP state", newAddedStore.isBootstrapInProgress()); assertEquals("The store's current state should be BOOTSTRAP", ReplicaState.BOOTSTRAP, newAddedStore.getCurrentState()); // 6. test that state transition should succeed for existing non-empty replicas (we write some data into store beforehand) MockId id = new MockId(TestUtils.getRandomString(MOCK_ID_STRING_LENGTH), Utils.getRandomShort(TestUtils.RANDOM), Utils.getRandomShort(TestUtils.RANDOM)); MessageInfo info = new MessageInfo(id, PUT_RECORD_SIZE, id.getAccountId(), id.getContainerId(), Utils.Infinite_Time); MessageWriteSet writeSet = new MockMessageWriteSet(Collections.singletonList(info), Collections.singletonList(ByteBuffer.allocate(PUT_RECORD_SIZE))); Store storeToWrite = storageManager.getStore(localReplicas.get(1).getPartitionId()); storeToWrite.put(writeSet); mockHelixParticipant.onPartitionBecomeBootstrapFromOffline(localReplicas.get(1).getPartitionId().toPathString()); assertFalse("There should not be any bootstrap file for existing non-empty store", storeToWrite.isBootstrapInProgress()); assertEquals("The store's current state should be BOOTSTRAP", ReplicaState.BOOTSTRAP, storeToWrite.getCurrentState()); // 7. test that for new created (empty) store, state transition puts it into BOOTSTRAP state mockHelixParticipant.onPartitionBecomeBootstrapFromOffline(localReplicas.get(0).getPartitionId().toPathString()); assertTrue("There should be a bootstrap file because store is empty and probably recreated", localStore.isBootstrapInProgress()); assertEquals("The store's current state should be BOOTSTRAP", ReplicaState.BOOTSTRAP, localStore.getCurrentState()); shutdownAndAssertStoresInaccessible(storageManager, localReplicas); } /** * test both success and failure cases during STANDBY -> INACTIVE transition */ @Test public void replicaFromStandbyToInactiveTest() throws Exception { generateConfigs(true, false); MockDataNodeId localNode = clusterMap.getDataNodes().get(0); List<ReplicaId> localReplicas = clusterMap.getReplicaIds(localNode); MockClusterParticipant mockHelixParticipant = new MockClusterParticipant(); StorageManager storageManager = createStorageManager(localNode, metricRegistry, Collections.singletonList(mockHelixParticipant)); storageManager.start(); // 1. get listeners from Helix participant and verify there is a storageManager listener. Map<StateModelListenerType, PartitionStateChangeListener> listeners = mockHelixParticipant.getPartitionStateChangeListeners(); assertTrue("Should contain storage manager listener", listeners.containsKey(StateModelListenerType.StorageManagerListener)); // 2. not found replica should encounter exception try { mockHelixParticipant.onPartitionBecomeInactiveFromStandby("-1"); fail("should fail because replica is not found"); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", ReplicaNotFound, e.getErrorCode()); } // 3. not found store should throw exception (induced by removing the store) ReplicaId replicaToRemove = localReplicas.get(localReplicas.size() - 1); storageManager.controlCompactionForBlobStore(replicaToRemove.getPartitionId(), false); storageManager.shutdownBlobStore(replicaToRemove.getPartitionId()); storageManager.getDiskManager(replicaToRemove.getPartitionId()).removeBlobStore(replicaToRemove.getPartitionId()); try { mockHelixParticipant.onPartitionBecomeInactiveFromStandby(replicaToRemove.getPartitionId().toPathString()); fail("should fail because store is not found"); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", ReplicaNotFound, e.getErrorCode()); } // 4. store not started exception ReplicaId localReplica = localReplicas.get(0); storageManager.shutdownBlobStore(localReplica.getPartitionId()); try { mockHelixParticipant.onPartitionBecomeInactiveFromStandby(localReplica.getPartitionId().toPathString()); fail("should fail because store is not started"); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", StoreNotStarted, e.getErrorCode()); } storageManager.startBlobStore(localReplica.getPartitionId()); // 5. store is disabled due to disk I/O error BlobStore localStore = (BlobStore) storageManager.getStore(localReplica.getPartitionId()); localStore.setDisableState(true); try { mockHelixParticipant.onPartitionBecomeInactiveFromStandby(localReplica.getPartitionId().toPathString()); fail("should fail because store is disabled"); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", ReplicaOperationFailure, e.getErrorCode()); } localStore.setDisableState(false); // 6. success case (verify both replica's state and decommission file) mockHelixParticipant.onPartitionBecomeInactiveFromStandby(localReplica.getPartitionId().toPathString()); assertEquals("local store state should be set to INACTIVE", ReplicaState.INACTIVE, storageManager.getStore(localReplica.getPartitionId()).getCurrentState()); File decommissionFile = new File(localReplica.getReplicaPath(), BlobStore.DECOMMISSION_FILE_NAME); assertTrue("Decommission file is not found in local replica's dir", decommissionFile.exists()); shutdownAndAssertStoresInaccessible(storageManager, localReplicas); // 7. mock disable compaction failure mockHelixParticipant = new MockClusterParticipant(); MockStorageManager mockStorageManager = new MockStorageManager(localNode, Collections.singletonList(mockHelixParticipant)); mockStorageManager.start(); try { mockHelixParticipant.onPartitionBecomeInactiveFromStandby(localReplica.getPartitionId().toPathString()); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", ReplicaNotFound, e.getErrorCode()); } finally { shutdownAndAssertStoresInaccessible(mockStorageManager, localReplicas); } } /** * Test shutting down blob store failure during Inactive-To-Offline transition. * @throws Exception */ @Test public void replicaFromInactiveToOfflineTest() throws Exception { generateConfigs(true, false); MockDataNodeId localNode = clusterMap.getDataNodes().get(0); List<ReplicaId> localReplicas = clusterMap.getReplicaIds(localNode); ReplicaId testReplica = localReplicas.get(0); MockClusterParticipant mockHelixParticipant = new MockClusterParticipant(); StorageManager storageManager = createStorageManager(localNode, metricRegistry, Collections.singletonList(mockHelixParticipant)); storageManager.start(); // test shutdown store failure (this is induced by shutting down disk manager) storageManager.getDiskManager(testReplica.getPartitionId()).shutdown(); mockHelixParticipant.getReplicaSyncUpManager().initiateDisconnection(testReplica); CountDownLatch participantLatch = new CountDownLatch(1); Utils.newThread(() -> { try { mockHelixParticipant.onPartitionBecomeOfflineFromInactive(testReplica.getPartitionId().toPathString()); fail("should fail because of shutting down store failure"); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", ReplicaOperationFailure, e.getErrorCode()); participantLatch.countDown(); } }, false).start(); // make sync-up complete to let code proceed and encounter exception in storage manager. mockHelixParticipant.getReplicaSyncUpManager().onDisconnectionComplete(testReplica); assertTrue("Helix participant transition didn't get invoked within 1 sec", participantLatch.await(1, TimeUnit.SECONDS)); shutdownAndAssertStoresInaccessible(storageManager, localReplicas); } /** * Test failure cases when updating InstanceConfig in Helix for both Offline-To-Bootstrap and Inactive-To-Offline. */ @Test public void updateInstanceConfigFailureTest() throws Exception { generateConfigs(true, true); MockDataNodeId localNode = clusterMap.getDataNodes().get(0); List<ReplicaId> localReplicas = clusterMap.getReplicaIds(localNode); MockClusterParticipant mockHelixParticipant = new MockClusterParticipant(); StorageManager storageManager = createStorageManager(localNode, metricRegistry, Collections.singletonList(mockHelixParticipant)); storageManager.start(); // create a new partition and get its replica on local node PartitionId newPartition = clusterMap.createNewPartition(Collections.singletonList(localNode)); // override return value of updateDataNodeInfoInCluster() to mock update InstanceConfig failure mockHelixParticipant.updateNodeInfoReturnVal = false; try { mockHelixParticipant.onPartitionBecomeBootstrapFromOffline(newPartition.toPathString()); fail("should fail because updating InstanceConfig didn't succeed during Offline-To-Bootstrap"); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", StateTransitionException.TransitionErrorCode.HelixUpdateFailure, e.getErrorCode()); } try { mockHelixParticipant.onPartitionBecomeOfflineFromInactive(localReplicas.get(0).getPartitionId().toPathString()); fail("should fail because updating InstanceConfig didn't succeed during Inactive-To-Offline"); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", StateTransitionException.TransitionErrorCode.HelixUpdateFailure, e.getErrorCode()); } mockHelixParticipant.updateNodeInfoReturnVal = null; // mock InstanceConfig not found error (note that MockHelixAdmin is empty by default, so no InstanceConfig is present) newPartition = clusterMap.createNewPartition(Collections.singletonList(localNode)); try { mockHelixParticipant.onPartitionBecomeBootstrapFromOffline(newPartition.toPathString()); fail("should fail because InstanceConfig is not found during Offline-To-Bootstrap"); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", StateTransitionException.TransitionErrorCode.HelixUpdateFailure, e.getErrorCode()); } try { mockHelixParticipant.onPartitionBecomeOfflineFromInactive(localReplicas.get(1).getPartitionId().toPathString()); fail("should fail because InstanceConfig is not found during Inactive-To-Offline"); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", StateTransitionException.TransitionErrorCode.HelixUpdateFailure, e.getErrorCode()); } shutdownAndAssertStoresInaccessible(storageManager, localReplicas); } /** * Test success case when updating InstanceConfig in Helix after new replica is added in storage manager. */ @Test public void updateInstanceConfigSuccessTest() throws Exception { generateConfigs(true, true); MockDataNodeId localNode = clusterMap.getDataNodes().get(0); List<ReplicaId> localReplicas = clusterMap.getReplicaIds(localNode); MockClusterParticipant mockHelixParticipant = new MockClusterParticipant(); StorageManager storageManager = createStorageManager(localNode, metricRegistry, Collections.singletonList(mockHelixParticipant)); storageManager.start(); // create a new partition and get its replica on local node PartitionId newPartition = clusterMap.createNewPartition(Collections.singletonList(localNode)); ReplicaId newReplica = newPartition.getReplicaIds().get(0); // for updating instanceConfig test, we first add an empty InstanceConfig of current node String instanceName = ClusterMapUtils.getInstanceName(clusterMapConfig.clusterMapHostName, clusterMapConfig.clusterMapPort); InstanceConfig instanceConfig = new InstanceConfig(instanceName); instanceConfig.setHostName(localNode.getHostname()); instanceConfig.setPort(Integer.toString(localNode.getPort())); // for current test, we initial InstanceConfig empty, non-empty case will be tested in HelixParticipantTest Map<String, Map<String, String>> diskInfos = new HashMap<>(); instanceConfig.getRecord().setMapFields(diskInfos); HelixAdmin helixAdmin = mockHelixParticipant.getHelixAdmin(); helixAdmin.addCluster(CLUSTER_NAME); helixAdmin.addInstance(CLUSTER_NAME, instanceConfig); // test success case mockHelixParticipant.onPartitionBecomeBootstrapFromOffline(newPartition.toPathString()); instanceConfig = helixAdmin.getInstanceConfig(CLUSTER_NAME, instanceName); // verify that new replica info is present in InstanceConfig Map<String, Map<String, String>> mountPathToDiskInfos = instanceConfig.getRecord().getMapFields(); Map<String, String> diskInfo = mountPathToDiskInfos.get(newReplica.getMountPath()); String replicasStr = diskInfo.get("Replicas"); Set<String> partitionStrs = new HashSet<>(); for (String replicaInfo : replicasStr.split(",")) { String[] infos = replicaInfo.split(":"); partitionStrs.add(infos[0]); } assertTrue("New replica info is not found in InstanceConfig", partitionStrs.contains(newPartition.toPathString())); shutdownAndAssertStoresInaccessible(storageManager, localReplicas); } /** * Test start BlobStore with given {@link PartitionId}. */ @Test public void startBlobStoreTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); List<MockDataNodeId> dataNodes = new ArrayList<>(); dataNodes.add(dataNode); MockPartitionId invalidPartition = new MockPartitionId(Long.MAX_VALUE, MockClusterMap.DEFAULT_PARTITION_CLASS, dataNodes, 0); List<? extends ReplicaId> invalidPartitionReplicas = invalidPartition.getReplicaIds(); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); PartitionId id = null; storageManager.start(); assertEquals("There should be 1 unexpected partition reported", 1, getNumUnrecognizedPartitionsReported()); // shutdown all the replicas first for (ReplicaId replica : replicas) { id = replica.getPartitionId(); assertTrue("Shutdown should succeed on given store", storageManager.shutdownBlobStore(id)); } ReplicaId replica = replicas.get(0); id = replica.getPartitionId(); // test start a store successfully assertTrue("Start should succeed on given store", storageManager.startBlobStore(id)); // test start the store which is already started assertTrue("Start should succeed on the store which is already started", storageManager.startBlobStore(id)); // test invalid partition replica = invalidPartitionReplicas.get(0); id = replica.getPartitionId(); assertFalse("Start should fail on given invalid replica", storageManager.startBlobStore(id)); // test start the store whose DiskManager is not running replica = replicas.get(replicas.size() - 1); id = replica.getPartitionId(); storageManager.getDiskManager(id).shutdown(); assertFalse("Start should fail on given store whose DiskManager is not running", storageManager.startBlobStore(id)); shutdownAndAssertStoresInaccessible(storageManager, replicas); } /** * Test get DiskManager with given {@link PartitionId}. */ @Test public void getDiskManagerTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); List<MockDataNodeId> dataNodes = new ArrayList<>(); dataNodes.add(dataNode); MockPartitionId invalidPartition = new MockPartitionId(Long.MAX_VALUE, MockClusterMap.DEFAULT_PARTITION_CLASS, dataNodes, 0); List<? extends ReplicaId> invalidPartitionReplicas = invalidPartition.getReplicaIds(); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); PartitionId id = null; storageManager.start(); assertEquals("There should be 1 unexpected partition reported", 1, getNumUnrecognizedPartitionsReported()); for (ReplicaId replica : replicas) { id = replica.getPartitionId(); assertNotNull("DiskManager should not be null for valid partition", storageManager.getDiskManager(id)); } // test invalid partition ReplicaId replica = invalidPartitionReplicas.get(0); id = replica.getPartitionId(); assertNull("DiskManager should be null for invalid partition", storageManager.getDiskManager(id)); shutdownAndAssertStoresInaccessible(storageManager, replicas); } /** * Test shutdown blobstore with given {@link PartitionId}. */ @Test public void shutdownBlobStoreTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); List<MockDataNodeId> dataNodes = new ArrayList<>(); dataNodes.add(dataNode); MockPartitionId invalidPartition = new MockPartitionId(Long.MAX_VALUE, MockClusterMap.DEFAULT_PARTITION_CLASS, dataNodes, 0); List<? extends ReplicaId> invalidPartitionReplicas = invalidPartition.getReplicaIds(); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); storageManager.start(); assertEquals("There should be 1 unexpected partition reported", 1, getNumUnrecognizedPartitionsReported()); for (int i = 1; i < replicas.size() - 1; i++) { ReplicaId replica = replicas.get(i); PartitionId id = replica.getPartitionId(); assertTrue("Shutdown should succeed on given store", storageManager.shutdownBlobStore(id)); } // test shutdown the store which is not started ReplicaId replica = replicas.get(replicas.size() - 1); PartitionId id = replica.getPartitionId(); Store store = storageManager.getStore(id, false); store.shutdown(); assertTrue("Shutdown should succeed on the store which is not started", storageManager.shutdownBlobStore(id)); // test shutdown the store whose DiskManager is not running replica = replicas.get(0); id = replica.getPartitionId(); storageManager.getDiskManager(id).shutdown(); assertFalse("Shutdown should fail on given store whose DiskManager is not running", storageManager.shutdownBlobStore(id)); // test invalid partition replica = invalidPartitionReplicas.get(0); id = replica.getPartitionId(); assertFalse("Shutdown should fail on given invalid replica", storageManager.shutdownBlobStore(id)); shutdownAndAssertStoresInaccessible(storageManager, replicas); } /** * Test remove blob store with given {@link PartitionId} * @throws Exception */ @Test public void removeBlobStoreTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); List<MockDataNodeId> dataNodes = new ArrayList<>(); dataNodes.add(dataNode); MockPartitionId invalidPartition = new MockPartitionId(Long.MAX_VALUE, MockClusterMap.DEFAULT_PARTITION_CLASS, dataNodes, 0); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); storageManager.start(); // shut down replica[1] ~ replica[size - 2]. The replica[0] will be used to test removing store that disk is not running // Replica[1] will be used to test removing a started store. Replica[2] will be used to test a store with compaction enabled for (int i = 3; i < replicas.size(); i++) { ReplicaId replica = replicas.get(i); PartitionId id = replica.getPartitionId(); assertTrue("Disable compaction should succeed", storageManager.controlCompactionForBlobStore(id, false)); assertTrue("Shutdown should succeed on given store", storageManager.shutdownBlobStore(id)); assertTrue("Removing store should succeed", storageManager.removeBlobStore(id)); assertNull("The store should not exist", storageManager.getStore(id, false)); } // test remove store that compaction is still enabled on it, even though it is shutdown PartitionId id = replicas.get(2).getPartitionId(); assertTrue("Shutdown should succeed on given store", storageManager.shutdownBlobStore(id)); assertFalse("Removing store should fail because compaction is enabled on this store", storageManager.removeBlobStore(id)); // test remove store that is still started id = replicas.get(1).getPartitionId(); assertFalse("Removing store should fail because store is still started", storageManager.removeBlobStore(id)); // test remove store that the disk manager is not running id = replicas.get(0).getPartitionId(); storageManager.getDiskManager(id).shutdown(); assertFalse("Removing store should fail because disk manager is not running", storageManager.removeBlobStore(id)); // test a store that doesn't exist assertFalse("Removing not-found store should return false", storageManager.removeBlobStore(invalidPartition)); shutdownAndAssertStoresInaccessible(storageManager, replicas); // test that remove store when compaction executor is not instantiated // by default, storeCompactionTriggers = "" which makes compaction executor = null during initialization VerifiableProperties vProps = new VerifiableProperties(new Properties()); storageManager = new StorageManager(new StoreConfig(vProps), diskManagerConfig, Utils.newScheduler(1, false), metricRegistry, new MockIdFactory(), clusterMap, dataNode, new DummyMessageStoreHardDelete(), null, SystemTime.getInstance(), new DummyMessageStoreRecovery(), new InMemAccountService(false, false)); storageManager.start(); for (ReplicaId replica : replicas) { id = replica.getPartitionId(); assertTrue("Disable compaction should succeed", storageManager.controlCompactionForBlobStore(id, false)); assertTrue("Shutdown should succeed on given store", storageManager.shutdownBlobStore(id)); assertTrue("Removing store should succeed", storageManager.removeBlobStore(id)); assertNull("The store should not exist", storageManager.getStore(id, false)); } shutdownAndAssertStoresInaccessible(storageManager, replicas); } /** * Test setting blob stop state in two clusters (if server participates into two Helix clusters) * @throws Exception */ @Test public void setBlobStoreStoppedStateWithMultiDelegatesTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); MockClusterParticipant mockClusterParticipant1 = new MockClusterParticipant(); MockClusterParticipant mockClusterParticipant2 = new MockClusterParticipant(null, false); List<ClusterParticipant> participants = Arrays.asList(mockClusterParticipant1, mockClusterParticipant2); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, participants); storageManager.start(); PartitionId id = replicas.get(0).getPartitionId(); // test that any delegate fails to update stop state, then the whole operation fails List<PartitionId> failToUpdateList = storageManager.setBlobStoreStoppedState(Collections.singletonList(id), true); assertEquals("Set store stopped state should fail because one of delegates returns false", id, failToUpdateList.get(0)); // test the success case, both delegates succeed in updating stop state of replica mockClusterParticipant2.setStopStateReturnVal = null; failToUpdateList = storageManager.setBlobStoreStoppedState(Collections.singletonList(id), true); assertTrue("Set store stopped state should succeed", failToUpdateList.isEmpty()); // verify both delegates have the correct stopped replica list. List<String> expectedStoppedReplicas = Collections.singletonList(id.toPathString()); assertEquals("Stopped replica list from participant 1 is not expected", expectedStoppedReplicas, mockClusterParticipant1.getStoppedReplicas()); assertEquals("Stopped replica list from participant 2 is not expected", expectedStoppedReplicas, mockClusterParticipant2.getStoppedReplicas()); shutdownAndAssertStoresInaccessible(storageManager, replicas); } /** * Test that, if store is not started, all participants on this node are able to mark it in ERROR state during * OFFLINE -> BOOTSTRAP transition. * @throws Exception */ @Test public void multiParticipantsMarkStoreInErrorStateTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); List<ClusterParticipant> participants = Arrays.asList(new MockClusterParticipant(), new MockClusterParticipant()); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, participants); storageManager.start(); // stop one of the stores to induce transition failure PartitionId id = replicas.get(0).getPartitionId(); storageManager.shutdownBlobStore(id); // verify that both participants throw exception during OFFLINE -> BOOTSTRAP transition for (ClusterParticipant participant : participants) { try { ((MockClusterParticipant) participant).onPartitionBecomeBootstrapFromOffline(id.toPathString()); fail("should fail because store is not started"); } catch (StateTransitionException e) { assertEquals("Error code doesn't match", StoreNotStarted, e.getErrorCode()); } } shutdownAndAssertStoresInaccessible(storageManager, replicas); } /** * Test set stopped state of blobstore with given list of {@link PartitionId} in failure cases. */ @Test public void setBlobStoreStoppedStateFailureTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); List<MockDataNodeId> dataNodes = new ArrayList<>(); dataNodes.add(dataNode); MockPartitionId invalidPartition = new MockPartitionId(Long.MAX_VALUE, MockClusterMap.DEFAULT_PARTITION_CLASS, dataNodes, 0); List<? extends ReplicaId> invalidPartitionReplicas = invalidPartition.getReplicaIds(); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); storageManager.start(); assertEquals("There should be 1 unexpected partition reported", 1, getNumUnrecognizedPartitionsReported()); // test set the state of store whose replicaStatusDelegate is null ReplicaId replica = replicas.get(0); PartitionId id = replica.getPartitionId(); storageManager.getDiskManager(id).shutdown(); List<PartitionId> failToUpdateList = storageManager.setBlobStoreStoppedState(Arrays.asList(id), true); assertEquals("Set store stopped state should fail on given store whose replicaStatusDelegate is null", id, failToUpdateList.get(0)); // test invalid partition case (where diskManager == null) replica = invalidPartitionReplicas.get(0); id = replica.getPartitionId(); failToUpdateList = storageManager.setBlobStoreStoppedState(Arrays.asList(id), true); assertEquals("Set store stopped state should fail on given invalid replica", id, failToUpdateList.get(0)); shutdownAndAssertStoresInaccessible(storageManager, replicas); } /** * Test successfully set stopped state of blobstore with given list of {@link PartitionId}. */ @Test public void setBlobStoreStoppedStateSuccessTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); List<PartitionId> partitionIds = new ArrayList<>(); Map<DiskId, List<ReplicaId>> diskToReplicas = new HashMap<>(); // test setting the state of store via instantiated MockClusterParticipant ClusterParticipant participant = new MockClusterParticipant(); ClusterParticipant participantSpy = Mockito.spy(participant); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, Collections.singletonList(participantSpy)); storageManager.start(); assertEquals("There should be no unexpected partitions reported", 0, getNumUnrecognizedPartitionsReported()); for (ReplicaId replica : replicas) { partitionIds.add(replica.getPartitionId()); diskToReplicas.computeIfAbsent(replica.getDiskId(), disk -> new ArrayList<>()).add(replica); } List<PartitionId> failToUpdateList; // add a list of stores to STOPPED list. Note that the stores are residing on 3 disks. failToUpdateList = storageManager.setBlobStoreStoppedState(partitionIds, true); // make sure the update operation succeeds assertTrue("Add stores to stopped list should succeed, failToUpdateList should be empty", failToUpdateList.isEmpty()); // make sure the stopped list contains all the added stores Set<String> stoppedReplicasCopy = new HashSet<>(participantSpy.getStoppedReplicas()); for (ReplicaId replica : replicas) { assertTrue("The stopped list should contain the replica: " + replica.getPartitionId().toPathString(), stoppedReplicasCopy.contains(replica.getPartitionId().toPathString())); } // make sure replicaStatusDelegate is invoked 3 times and each time the input replica list conforms with stores on particular disk for (List<ReplicaId> replicasPerDisk : diskToReplicas.values()) { verify(participantSpy, times(1)).setReplicaStoppedState(replicasPerDisk, true); } // remove a list of stores from STOPPED list. Note that the stores are residing on 3 disks. storageManager.setBlobStoreStoppedState(partitionIds, false); // make sure the update operation succeeds assertTrue("Remove stores from stopped list should succeed, failToUpdateList should be empty", failToUpdateList.isEmpty()); // make sure the stopped list is empty because all the stores are successfully removed. assertTrue("The stopped list should be empty after removing all stores", participantSpy.getStoppedReplicas().isEmpty()); // make sure replicaStatusDelegate is invoked 3 times and each time the input replica list conforms with stores on particular disk for (List<ReplicaId> replicasPerDisk : diskToReplicas.values()) { verify(participantSpy, times(1)).setReplicaStoppedState(replicasPerDisk, false); } shutdownAndAssertStoresInaccessible(storageManager, replicas); } /** * Tests that{@link StorageManager} can correctly determine if disk is unavailable based on states of all stores. */ @Test public void isDiskAvailableTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); Map<DiskId, List<ReplicaId>> diskToReplicas = new HashMap<>(); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); storageManager.start(); assertEquals("There should be no unexpected partitions reported", 0, getNumUnrecognizedPartitionsReported()); for (ReplicaId replica : replicas) { diskToReplicas.computeIfAbsent(replica.getDiskId(), disk -> new ArrayList<>()).add(replica); } // for each disk, shutdown all the stores except for the last one for (List<ReplicaId> replicasOnDisk : diskToReplicas.values()) { for (int i = 0; i < replicasOnDisk.size() - 1; ++i) { storageManager.getStore(replicasOnDisk.get(i).getPartitionId(), false).shutdown(); } } // verify all disks are still available because at least one store on them is up for (List<ReplicaId> replicasOnDisk : diskToReplicas.values()) { assertTrue("Disk should be available", storageManager.isDiskAvailable(replicasOnDisk.get(0).getDiskId())); assertEquals("Disk state be available", HardwareState.AVAILABLE, replicasOnDisk.get(0).getDiskId().getState()); } // now, shutdown the last store on each disk for (List<ReplicaId> replicasOnDisk : diskToReplicas.values()) { storageManager.getStore(replicasOnDisk.get(replicasOnDisk.size() - 1).getPartitionId(), false).shutdown(); } // verify all disks are unavailable because all stores are down for (List<ReplicaId> replicasOnDisk : diskToReplicas.values()) { assertFalse("Disk should be unavailable", storageManager.isDiskAvailable(replicasOnDisk.get(0).getDiskId())); } // then, start the one store on each disk to test if disk is up again for (List<ReplicaId> replicasOnDisk : diskToReplicas.values()) { storageManager.startBlobStore(replicasOnDisk.get(0).getPartitionId()); } // verify all disks are available again because one store is started for (List<ReplicaId> replicasOnDisk : diskToReplicas.values()) { assertTrue("Disk should be available", storageManager.isDiskAvailable(replicasOnDisk.get(0).getDiskId())); assertEquals("Disk state be available", HardwareState.AVAILABLE, replicasOnDisk.get(0).getDiskId().getState()); } shutdownAndAssertStoresInaccessible(storageManager, replicas); } /** * Tests that {@link StorageManager} can start even when certain stores cannot be started. Checks that these stores * are not accessible. We can make the replica path non-readable to induce a store starting failure. * @throws Exception */ @Test public void storeStartFailureTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); Set<Integer> badReplicaIndexes = new HashSet<>(Arrays.asList(2, 7)); for (Integer badReplicaIndex : badReplicaIndexes) { new File(replicas.get(badReplicaIndex).getReplicaPath()).setReadable(false); } StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); storageManager.start(); assertEquals("There should be no unexpected partitions reported", 0, getNumUnrecognizedPartitionsReported()); Map<String, Counter> counters = metricRegistry.getCounters(); assertEquals(0, getCounterValue(counters, DiskSpaceAllocator.class.getName(), "DiskSpaceAllocatorInitFailureCount")); assertEquals(badReplicaIndexes.size(), getCounterValue(counters, DiskManager.class.getName(), "TotalStoreStartFailures")); assertEquals(0, getCounterValue(counters, DiskManager.class.getName(), "DiskMountPathFailures")); for (int i = 0; i < replicas.size(); i++) { ReplicaId replica = replicas.get(i); PartitionId id = replica.getPartitionId(); if (badReplicaIndexes.contains(i)) { assertNull("This store should not be accessible.", storageManager.getStore(id, false)); assertFalse("Compaction should not be scheduled", storageManager.scheduleNextForCompaction(id)); } else { Store store = storageManager.getStore(id, false); assertTrue("Store should be started", store.isStarted()); assertTrue("Compaction should be scheduled", storageManager.scheduleNextForCompaction(id)); } } assertEquals("Compaction thread count is incorrect", dataNode.getMountPaths().size(), TestUtils.numThreadsByThisName(CompactionManager.THREAD_NAME_PREFIX)); verifyCompactionThreadCount(storageManager, dataNode.getMountPaths().size()); shutdownAndAssertStoresInaccessible(storageManager, replicas); assertEquals("Compaction thread count is incorrect", 0, storageManager.getCompactionThreadCount()); } /** * Tests that {@link StorageManager} can start when all of the stores on one disk fail to start. Checks that these * stores are not accessible. We can make the replica path non-readable to induce a store starting failure. * @throws Exception */ @Test public void storeStartFailureOnOneDiskTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); List<String> mountPaths = dataNode.getMountPaths(); String badDiskMountPath = mountPaths.get(RANDOM.nextInt(mountPaths.size())); int downReplicaCount = 0; for (ReplicaId replica : replicas) { if (replica.getMountPath().equals(badDiskMountPath)) { new File(replica.getReplicaPath()).setReadable(false); downReplicaCount++; } } StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); storageManager.start(); assertEquals("There should be no unexpected partitions reported", 0, getNumUnrecognizedPartitionsReported()); Map<String, Counter> counters = metricRegistry.getCounters(); assertEquals(0, getCounterValue(counters, DiskSpaceAllocator.class.getName(), "DiskSpaceAllocatorInitFailureCount")); assertEquals(downReplicaCount, getCounterValue(counters, DiskManager.class.getName(), "TotalStoreStartFailures")); assertEquals(0, getCounterValue(counters, DiskManager.class.getName(), "DiskMountPathFailures")); checkStoreAccessibility(replicas, badDiskMountPath, storageManager); assertEquals("Compaction thread count is incorrect", mountPaths.size(), TestUtils.numThreadsByThisName(CompactionManager.THREAD_NAME_PREFIX)); verifyCompactionThreadCount(storageManager, mountPaths.size()); shutdownAndAssertStoresInaccessible(storageManager, replicas); assertEquals("Compaction thread count is incorrect", 0, storageManager.getCompactionThreadCount()); } /** * Test that stores on a disk are inaccessible if the {@link DiskSpaceAllocator} fails to start. * @throws Exception */ @Test public void diskSpaceAllocatorTest() throws Exception { generateConfigs(true, false); MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); List<String> mountPaths = dataNode.getMountPaths(); Map<String, List<ReplicaId>> replicasByMountPath = new HashMap<>(); for (ReplicaId replica : replicas) { replicasByMountPath.computeIfAbsent(replica.getMountPath(), key -> new ArrayList<>()).add(replica); } // Test that StorageManager starts correctly when segments are created in the reserve pool. // Startup/shutdown one more time to verify the restart scenario. for (int i = 0; i < 2; i++) { metricRegistry = new MetricRegistry(); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); storageManager.start(); assertEquals("There should be no unexpected partitions reported", 0, getNumUnrecognizedPartitionsReported()); checkStoreAccessibility(replicas, null, storageManager); Map<String, Counter> counters = metricRegistry.getCounters(); assertEquals(0, getCounterValue(counters, DiskSpaceAllocator.class.getName(), "DiskSpaceAllocatorInitFailureCount")); assertEquals(0, getCounterValue(counters, DiskManager.class.getName(), "TotalStoreStartFailures")); assertEquals(0, getCounterValue(counters, DiskManager.class.getName(), "DiskMountPathFailures")); for (String mountPath : dataNode.getMountPaths()) { List<ReplicaId> replicasOnDisk = replicasByMountPath.get(mountPath); DiskSpaceAllocatorTest.ExpectedState expectedState = new DiskSpaceAllocatorTest.ExpectedState(); // There should be 1 unallocated segment per replica on a mount path (each replica can have 2 segments) and the // swap segments. expectedState.addSwapSeg(storeConfig.storeSegmentSizeInBytes, 1); for (ReplicaId replica : replicasOnDisk) { expectedState.addStoreSeg(replica.getPartitionId().toPathString(), storeConfig.storeSegmentSizeInBytes, 1); } DiskSpaceAllocatorTest.verifyPoolState(new File(mountPath, diskManagerConfig.diskManagerReserveFileDirName), expectedState); } shutdownAndAssertStoresInaccessible(storageManager, replicas); assertEquals(0, getCounterValue(counters, DiskManager.class.getName(), "TotalStoreShutdownFailures")); } // Induce a initializePool failure by: // 1. deleting a file size directory // 2. instantiating the DiskManagers (this will not fail b/c the directory just won't be inventory) // 3. creating a regular file with the same name as the file size directory // 4. start the DiskManagers (this should cause the DiskSpaceAllocator to fail to initialize when it sees the // file where the directory should be created. metricRegistry = new MetricRegistry(); String diskToFail = mountPaths.get(RANDOM.nextInt(mountPaths.size())); File reservePoolDir = new File(diskToFail, diskManagerConfig.diskManagerReserveFileDirName); File storeReserveDir = new File(reservePoolDir, DiskSpaceAllocator.STORE_DIR_PREFIX + replicasByMountPath.get(diskToFail) .get(0) .getPartitionId() .toPathString()); File fileSizeDir = new File(storeReserveDir, DiskSpaceAllocator.generateFileSizeDirName(storeConfig.storeSegmentSizeInBytes)); Utils.deleteFileOrDirectory(fileSizeDir); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); assertTrue("File creation should have succeeded", fileSizeDir.createNewFile()); storageManager.start(); assertEquals("There should be no unexpected partitions reported", 0, getNumUnrecognizedPartitionsReported()); checkStoreAccessibility(replicas, diskToFail, storageManager); Map<String, Counter> counters = metricRegistry.getCounters(); shutdownAndAssertStoresInaccessible(storageManager, replicas); assertEquals(0, getCounterValue(counters, DiskManager.class.getName(), "TotalStoreShutdownFailures")); } /** * Test that stores for all partitions on a node have been started and partitions not present on this node are * inaccessible. Also tests all stores are shutdown on shutting down the storage manager * @throws Exception */ @Test public void successfulStartupShutdownTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); storageManager.start(); assertEquals("There should be no unexpected partitions reported", 0, getNumUnrecognizedPartitionsReported()); checkStoreAccessibility(replicas, null, storageManager); Map<String, Counter> counters = metricRegistry.getCounters(); assertEquals(0, getCounterValue(counters, DiskSpaceAllocator.class.getName(), "DiskSpaceAllocatorInitFailureCount")); assertEquals(0, getCounterValue(counters, DiskManager.class.getName(), "TotalStoreStartFailures")); assertEquals(0, getCounterValue(counters, DiskManager.class.getName(), "DiskMountPathFailures")); MockPartitionId invalidPartition = new MockPartitionId(Long.MAX_VALUE, MockClusterMap.DEFAULT_PARTITION_CLASS, Collections.emptyList(), 0); assertNull("Should not have found a store for an invalid partition.", storageManager.getStore(invalidPartition, false)); assertEquals("Compaction thread count is incorrect", dataNode.getMountPaths().size(), TestUtils.numThreadsByThisName(CompactionManager.THREAD_NAME_PREFIX)); verifyCompactionThreadCount(storageManager, dataNode.getMountPaths().size()); shutdownAndAssertStoresInaccessible(storageManager, replicas); assertEquals("Compaction thread count is incorrect", 0, storageManager.getCompactionThreadCount()); assertEquals(0, getCounterValue(counters, DiskManager.class.getName(), "TotalStoreShutdownFailures")); } /** * Test the stopped stores are correctly skipped and not started during StorageManager's startup. */ @Test public void skipStoppedStoresTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); ClusterParticipant mockParticipant = new MockClusterParticipant(); mockParticipant.setReplicaStoppedState(Collections.singletonList(replicas.get(0)), true); StorageManager storageManager = createStorageManager(dataNode, metricRegistry, Collections.singletonList(mockParticipant)); storageManager.start(); assertEquals("There should be no unexpected partitions reported", 0, getNumUnrecognizedPartitionsReported()); for (int i = 0; i < replicas.size(); ++i) { PartitionId id = replicas.get(i).getPartitionId(); if (i == 0) { assertNull("Store should be null because stopped stores will be skipped and will not be started", storageManager.getStore(id, false)); assertFalse("Compaction should not be scheduled", storageManager.scheduleNextForCompaction(id)); } else { Store store = storageManager.getStore(id, false); assertTrue("Store should be started", store.isStarted()); assertTrue("Compaction should be scheduled", storageManager.scheduleNextForCompaction(id)); } } shutdownAndAssertStoresInaccessible(storageManager, replicas); } /** * Tests that unrecognized directories are reported correctly * @throws Exception */ @Test public void unrecognizedDirsOnDiskTest() throws Exception { MockDataNodeId dataNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(dataNode); int extraDirsCount = 0; Set<String> createdMountPaths = new HashSet<>(); for (ReplicaId replicaId : replicas) { if (createdMountPaths.add(replicaId.getMountPath())) { int count = TestUtils.RANDOM.nextInt(6) + 5; createFilesAndDirsAtPath(new File(replicaId.getDiskId().getMountPath()), count - 1, count); // the extra files should not get reported extraDirsCount += count; } } StorageManager storageManager = createStorageManager(dataNode, metricRegistry, null); storageManager.start(); assertEquals("There should be some unexpected partitions reported", extraDirsCount, getNumUnrecognizedPartitionsReported()); checkStoreAccessibility(replicas, null, storageManager); shutdownAndAssertStoresInaccessible(storageManager, replicas); } /** * Test that residual directory associated with removed replica is deleted correctly during OFFLINE -> DROPPED transition. * @throws Exception */ @Test public void residualDirDeletionTest() throws Exception { MockDataNodeId localNode = clusterMap.getDataNodes().get(0); List<ReplicaId> replicas = clusterMap.getReplicaIds(localNode); MockClusterParticipant mockHelixParticipant = Mockito.spy(new MockClusterParticipant()); doNothing().when(mockHelixParticipant).setPartitionDisabledState(anyString(), anyBoolean()); // create an extra store dir at one of the mount paths String mountPath = replicas.get(0).getMountPath(); String extraPartitionName = "1000"; File extraStoreDir = new File(mountPath, extraPartitionName); assertTrue("Can't create an extra store dir", extraStoreDir.mkdir()); StorageManager storageManager = createStorageManager(localNode, metricRegistry, Collections.singletonList(mockHelixParticipant)); storageManager.start(); // failure case: IOException when deleting store dir File invalidDir = new File(extraStoreDir.getAbsolutePath(), "invalidDir"); invalidDir.deleteOnExit(); assertTrue("Couldn't create dir within store dir", invalidDir.mkdir()); assertTrue("Could not make unreadable", invalidDir.setReadable(false)); try { mockHelixParticipant.onPartitionBecomeDroppedFromOffline(extraPartitionName); fail("should fail because there is IOException when deleting store dir"); } catch (StateTransitionException e) { assertEquals("Error code is not expected", ReplicaOperationFailure, e.getErrorCode()); } assertTrue("Could not make readable", invalidDir.setReadable(true)); // trigger OFFLINE -> DROPPED transition on extra partition. Storage manager should delete residual store dir. mockHelixParticipant.onPartitionBecomeDroppedFromOffline(extraPartitionName); verify(mockHelixParticipant).setPartitionDisabledState(extraPartitionName, false); assertFalse("Extra store dir should not exist", extraStoreDir.exists()); shutdownAndAssertStoresInaccessible(storageManager, replicas); } // helpers /** * Construct a {@link StorageManager} for the passed in set of replicas. * @param currentNode the list of replicas for the {@link StorageManager} to use. * @param metricRegistry the {@link MetricRegistry} instance to use to instantiate {@link StorageManager} * @param clusterParticipants a list of {@link ClusterParticipant}(s) to use in storage manager * @return a started {@link StorageManager} * @throws StoreException */ private StorageManager createStorageManager(DataNodeId currentNode, MetricRegistry metricRegistry, List<ClusterParticipant> clusterParticipants) throws StoreException { return new StorageManager(storeConfig, diskManagerConfig, Utils.newScheduler(1, false), metricRegistry, new MockIdFactory(), clusterMap, currentNode, new DummyMessageStoreHardDelete(), clusterParticipants, SystemTime.getInstance(), new DummyMessageStoreRecovery(), new InMemAccountService(false, false)); } /** * Shutdown a {@link StorageManager} and assert that the stores cannot be accessed for the provided replicas. * @param storageManager the {@link StorageManager} to shutdown. * @param replicas the {@link ReplicaId}s to check for store inaccessibility. * @throws InterruptedException */ private static void shutdownAndAssertStoresInaccessible(StorageManager storageManager, List<ReplicaId> replicas) throws InterruptedException { storageManager.shutdown(); for (ReplicaId replica : replicas) { assertNull(storageManager.getStore(replica.getPartitionId(), false)); } } /** * @return the value of {@link StorageManagerMetrics#unexpectedDirsOnDisk}. */ private long getNumUnrecognizedPartitionsReported() { return getCounterValue(metricRegistry.getCounters(), DiskManager.class.getName(), "UnexpectedDirsOnDisk"); } /** * Get the counter value for the metric in {@link StorageManagerMetrics} for the given class and suffix. * @param counters Map of counter metrics to use * @param className the class to which the metric belongs to * @param suffix the suffix of the metric that distinguishes it from other metrics in the class. * @return the value of the counter. */ private long getCounterValue(Map<String, Counter> counters, String className, String suffix) { return counters.get(className + "." + suffix).getCount(); } /** * Verifies that return value {@link StorageManager#getCompactionThreadCount()} of the given {@code storageManager} * is equal to {@code expectedCount} * @param storageManager the {@link StorageManager} instance to use. * @param expectedCount the number of compaction threads expected. * @throws InterruptedException */ private static void verifyCompactionThreadCount(StorageManager storageManager, int expectedCount) throws InterruptedException { // there is no option but to sleep here since we have to wait for the CompactionManager to start the threads up // we cannot mock these components since they are internally constructed within the StorageManager and DiskManager. int totalWaitTimeMs = 1000; int alreadyWaitedMs = 0; int singleWaitTimeMs = 10; while (storageManager.getCompactionThreadCount() != expectedCount && alreadyWaitedMs < totalWaitTimeMs) { Thread.sleep(singleWaitTimeMs); alreadyWaitedMs += singleWaitTimeMs; } assertEquals("Compaction thread count report not as expected", expectedCount, storageManager.getCompactionThreadCount()); } /** * Check that stores on a bad disk are not accessible and that all other stores are accessible. * @param replicas a list of all {@link ReplicaId}s on the node. * @param badDiskMountPath the disk mount path that should have caused failures or {@code null} if all disks are fine. * @param storageManager the {@link StorageManager} to test. */ private void checkStoreAccessibility(List<ReplicaId> replicas, String badDiskMountPath, StorageManager storageManager) { for (ReplicaId replica : replicas) { PartitionId id = replica.getPartitionId(); if (replica.getMountPath().equals(badDiskMountPath)) { assertNull("This store should not be accessible.", storageManager.getStore(id, false)); assertFalse("Compaction should not be scheduled", storageManager.scheduleNextForCompaction(id)); } else { Store store = storageManager.getStore(id, false); assertTrue("Store should be started", store.isStarted()); assertTrue("Compaction should be scheduled", storageManager.scheduleNextForCompaction(id)); } } } /** * Generates {@link StoreConfig} and {@link DiskManagerConfig} for use in tests. * @param segmentedLog {@code true} to set a segment capacity lower than total store capacity * @param updateInstanceConfig whether to update InstanceConfig in Helix */ private void generateConfigs(boolean segmentedLog, boolean updateInstanceConfig) { List<com.github.ambry.utils.TestUtils.ZkInfo> zkInfoList = new ArrayList<>(); zkInfoList.add(new com.github.ambry.utils.TestUtils.ZkInfo(null, "DC0", (byte) 0, 2199, false)); JSONObject zkJson = constructZkLayoutJSON(zkInfoList); Properties properties = new Properties(); properties.put("disk.manager.enable.segment.pooling", "true"); properties.put("store.compaction.triggers", "Periodic,Admin"); properties.put("store.replica.status.delegate.enable", "true"); properties.put("store.set.local.partition.state.enabled", "true"); properties.setProperty("clustermap.host.name", "localhost"); properties.setProperty("clustermap.port", "2200"); properties.setProperty("clustermap.cluster.name", CLUSTER_NAME); properties.setProperty("clustermap.datacenter.name", "DC0"); properties.setProperty("clustermap.dcs.zk.connect.strings", zkJson.toString(2)); properties.setProperty("clustermap.update.datanode.info", Boolean.toString(updateInstanceConfig)); if (segmentedLog) { long replicaCapacity = clusterMap.getAllPartitionIds(null).get(0).getReplicaIds().get(0).getCapacityInBytes(); properties.put("store.segment.size.in.bytes", Long.toString(replicaCapacity / 2L)); } VerifiableProperties vProps = new VerifiableProperties(properties); diskManagerConfig = new DiskManagerConfig(vProps); storeConfig = new StoreConfig(vProps); clusterMapConfig = new ClusterMapConfig(vProps); } // unrecognizedDirsOnDiskTest() helpers /** * Creates {@code fileCount} files and {@code dirCount} directories at {@code dir}. * @param dir the directory to create the files and dirs at * @param fileCount the number of files to be created * @param dirCount the number of directories to be created * @return the list of files,dirs created as a pair. * @throws IOException */ private Pair<List<File>, List<File>> createFilesAndDirsAtPath(File dir, int fileCount, int dirCount) throws IOException { List<File> createdFiles = new ArrayList<>(); for (int i = 0; i < fileCount; i++) { File createdFile = new File(dir, "created-file-" + i); if (!createdFile.exists()) { assertTrue("Could not create " + createdFile, createdFile.createNewFile()); } createdFile.deleteOnExit(); createdFiles.add(createdFile); } List<File> createdDirs = new ArrayList<>(); for (int i = 0; i < dirCount; i++) { File createdDir = new File(dir, "created-dir-" + i); assertTrue("Could not create " + createdDir + " now", createdDir.mkdir()); createdDir.deleteOnExit(); createdDirs.add(createdDir); } return new Pair<>(createdFiles, createdDirs); } /** * An extension of {@link HelixParticipant} to help with tests. */ class MockClusterParticipant extends HelixParticipant { Boolean updateNodeInfoReturnVal = null; Set<ReplicaId> sealedReplicas = new HashSet<>(); Set<ReplicaId> stoppedReplicas = new HashSet<>(); Set<ReplicaId> disabledReplicas = new HashSet<>(); private Boolean setSealStateReturnVal; private Boolean setStopStateReturnVal; MockClusterParticipant() { this(null, null); markDisablePartitionComplete(); } /** * Ctor for MockClusterParticipant with arguments to override return value of some methods. * @param setSealStateReturnVal if not null, use this value to override result of setReplicaSealedState(). If null, * go through standard workflow in the method. * @param setStopStateReturnVal if not null, use this value to override result of setReplicaStoppedState(). If null, * go through standard workflow in the method. */ MockClusterParticipant(Boolean setSealStateReturnVal, Boolean setStopStateReturnVal) { super(clusterMapConfig, new MockHelixManagerFactory(), new MetricRegistry(), parseDcJsonAndPopulateDcInfo(clusterMapConfig.clusterMapDcsZkConnectStrings).get( clusterMapConfig.clusterMapDatacenterName).getZkConnectStrs().get(0), true); this.setSealStateReturnVal = setSealStateReturnVal; this.setStopStateReturnVal = setStopStateReturnVal; markDisablePartitionComplete(); } @Override public void participate(List<AmbryStatsReport> ambryStatsReports, AccountStatsStore accountStatsStore, Callback<AggregatedAccountStorageStats> callback) throws IOException { // no op } @Override public boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { if (setSealStateReturnVal != null) { return setSealStateReturnVal; } if (isSealed) { sealedReplicas.add(replicaId); } else { sealedReplicas.remove(replicaId); } return true; } @Override public boolean setReplicaStoppedState(List<ReplicaId> replicaIds, boolean markStop) { if (setStopStateReturnVal != null) { return setStopStateReturnVal; } if (markStop) { stoppedReplicas.addAll(replicaIds); } else { stoppedReplicas.removeAll(replicaIds); } return true; } @Override public void setReplicaDisabledState(ReplicaId replicaId, boolean disable) { if (disable) { disabledReplicas.add(replicaId); } else { disabledReplicas.remove(replicaId); } } @Override public List<String> getSealedReplicas() { return sealedReplicas.stream().map(r -> r.getPartitionId().toPathString()).collect(Collectors.toList()); } @Override public List<String> getStoppedReplicas() { return stoppedReplicas.stream().map(r -> r.getPartitionId().toPathString()).collect(Collectors.toList()); } @Override public boolean updateDataNodeInfoInCluster(ReplicaId replicaId, boolean shouldExist) { return updateNodeInfoReturnVal == null ? super.updateDataNodeInfoInCluster(replicaId, shouldExist) : updateNodeInfoReturnVal; } @Override public void close() { // no op } @Override public void setPartitionDisabledState(String partitionName, boolean disable) { super.setPartitionDisabledState(partitionName, disable); } } /** * An extension of {@link StorageManager} to help mock failure case */ private class MockStorageManager extends StorageManager { boolean controlCompactionReturnVal = false; MockStorageManager(DataNodeId currentNode, List<ClusterParticipant> clusterParticipants) throws Exception { super(storeConfig, diskManagerConfig, Utils.newScheduler(1, false), metricRegistry, new MockIdFactory(), clusterMap, currentNode, new DummyMessageStoreHardDelete(), clusterParticipants, SystemTime.getInstance(), new DummyMessageStoreRecovery(), new InMemAccountService(false, false)); } @Override public boolean controlCompactionForBlobStore(PartitionId id, boolean enabled) { return controlCompactionReturnVal; } } }
{ "content_hash": "755a8bbf064596055b8fb8a494a67f5a", "timestamp": "", "source": "github", "line_count": 1433, "max_line_length": 134, "avg_line_length": 53.60851360781577, "alnum_prop": 0.7501594616055506, "repo_name": "linkedin/ambry", "id": "aede0a5c3c656bc84ed9ddc3243edcb6f39ccd4a", "size": "77330", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ambry-store/src/test/java/com/github/ambry/store/StorageManagerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "14277307" }, { "name": "JavaScript", "bytes": "3822" }, { "name": "Python", "bytes": "7025" }, { "name": "Shell", "bytes": "279" } ], "symlink_target": "" }
package Question9_5; import java.util.*; public class Question { public static ArrayList<String> getPerms(String str) { if (str == null) { return null; } ArrayList<String> permutations = new ArrayList<String>(); if (str.length() == 0) { // base case permutations.add(""); return permutations; } char first = str.charAt(0); // get the first character String remainder = str.substring(1); // remove the first character ArrayList<String> words = getPerms(remainder); for (String word : words) { for (int j = 0; j <= word.length(); j++) { String s = insertCharAt(word, first, j); permutations.add(s); } } return permutations; } public static String insertCharAt(String word, char c, int i) { String start = word.substring(0, i); String end = word.substring(i); return start + c + end; } public static void main(String[] args) { ArrayList<String> list = getPerms("abcde"); System.out.println("There are " + list.size() + " permutations."); for (String s : list) { System.out.println(s); } } }
{ "content_hash": "a27e5fbbbf49af43a0ed97405ab229b5", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 68, "avg_line_length": 26.069767441860463, "alnum_prop": 0.6146297948260482, "repo_name": "tbian7/pst", "id": "c835ed6f45b90e6873a053ba3c337538c6e28935", "size": "1121", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cracking_ref/Chapter 9/Question9_5/Question.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "15" }, { "name": "C++", "bytes": "178611" }, { "name": "Java", "bytes": "955837" }, { "name": "JavaScript", "bytes": "1440" }, { "name": "Makefile", "bytes": "564" }, { "name": "Python", "bytes": "1723" }, { "name": "SQLPL", "bytes": "264" } ], "symlink_target": "" }
package com.bagri.server.hazelcast.task.doc; import java.util.Map.Entry; import org.springframework.beans.factory.annotation.Autowired; import com.bagri.core.DocumentKey; import com.bagri.core.api.BagriException; import com.bagri.core.api.DocumentManagement; import com.bagri.core.api.SchemaRepository; import com.bagri.core.model.Document; import com.bagri.core.system.Permission; import com.bagri.server.hazelcast.impl.DocumentManagementImpl; import com.hazelcast.map.EntryBackupProcessor; import com.hazelcast.spring.context.SpringAware; @SpringAware public class DocumentCollectionUpdater extends com.bagri.client.hazelcast.task.doc.DocumentCollectionUpdater { private Document doc; private transient DocumentManagement docMgr; @Autowired @Override public void setRepository(SchemaRepository repo) { super.setRepository(repo); this.docMgr = repo.getDocumentManagement(); } @Override public EntryBackupProcessor<DocumentKey, Document> getBackupProcessor() { return new DocumentBackupProcessor(doc); } @Override public Object process(Entry<DocumentKey, Document> entry) { try { checkPermission(Permission.Value.modify); doc = entry.getValue(); return ((DocumentManagementImpl) docMgr).updateDocumentCollections(add, entry, collections); } catch (BagriException ex) { throw new RuntimeException(ex); } } }
{ "content_hash": "735609d54d2a5992a0973d1bdb13abbb", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 110, "avg_line_length": 30.869565217391305, "alnum_prop": 0.7626760563380282, "repo_name": "dsukhoroslov/bagri", "id": "3cc01120b14e48311ca63c4146d592767d7f5f5b", "size": "1420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bagri-server/bagri-server-hazelcast/src/main/java/com/bagri/server/hazelcast/task/doc/DocumentCollectionUpdater.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "49711" }, { "name": "C#", "bytes": "9713" }, { "name": "Dockerfile", "bytes": "675" }, { "name": "GAP", "bytes": "81" }, { "name": "HTML", "bytes": "1505" }, { "name": "Java", "bytes": "5235980" }, { "name": "Shell", "bytes": "30349" }, { "name": "XQuery", "bytes": "34449" } ], "symlink_target": "" }
var gone_fixed = false; var refresh_queued = false; var lastYOffset = 0; var lastInnerHeight = 0; var lastMaxScroll = 0; var lastWindowPercent = 0; var nearDiv = 0; var farDiv = 0; var fillerDiv = 0; var birdDiv = 0; var siloDiv = 0; function queueRefresh() { lastYOffset = window.pageYOffset; lastInnerHeight = window.innerHeight; docHeight = window.scrollMaxY; lastMaxScroll = lastInnerHeight / 3; lastWindowPercent = lastYOffset / lastMaxScroll; if (!refresh_queued) { refresh_queued = true; requestAnimationFrame(setBkgnds); } } function setBkgnds() { refresh_queued = false; var nearTop = lastInnerHeight * 0.60; var farTop = lastInnerHeight * 0.20; var birdTop = lastInnerHeight * 0.10; var siloTop = lastInnerHeight * 0.60; if (lastYOffset < lastMaxScroll ) { if (gone_fixed) { nearDiv.removeClass('near-fixed'); farDiv.removeClass('far-fixed'); nearDiv.addClass('near-scroller'); farDiv.addClass('far-scroller'); gone_fixed = false; } nearTopFinal = (nearTop - ((nearTop - lastMaxScroll - 50) * lastWindowPercent)); farTopFinal = (farTop - ((farTop - lastMaxScroll + 10) * lastWindowPercent)); fillerDiv.css({'top': nearTopFinal + (0.40 * lastInnerHeight), 'height': lastInnerHeight * 0.60}); nearDiv.css('top', nearTopFinal + 'px' ); nearDiv.css('height', lastInnerHeight - (nearTopFinal - lastYOffset) + 'px' ); siloDiv.css('top', nearTopFinal - 300 + 'px' ); farDiv.css('top', farTopFinal + 'px' ); birdDiv.css({'top': (birdTop - (birdTop* lastWindowPercent)), 'opacity': (1 - lastWindowPercent)}); } else { if (!gone_fixed) { gone_fixed = true; nearDiv.addClass('near-fixed'); farDiv.addClass('far-fixed'); nearDiv.removeClass('near-scroller'); farDiv.removeClass('far-scroller'); nearDiv.css('height', lastInnerHeight - 50 + 'px' ); nearDiv.css('top', '0px' ); farDiv.css('top', '0px' ); } } } $( document ).ready(function(){ nearDiv = $('.near'); farDiv = $('.far'); fillerDiv = $('.filler'); birdDiv = $('.birds'); siloDiv = $('.silos'); window.onscroll = queueRefresh; window.onresize = queueRefresh; });
{ "content_hash": "f470f6b73e7c60e0c8e2fa12cf046efa", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 103, "avg_line_length": 29.144736842105264, "alnum_prop": 0.6424379232505644, "repo_name": "unsilo/uns_themes", "id": "e48b36a5d45d8ef41ec02d6b9cd923b4c823ad7b", "size": "2215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/assets/javascripts/uns_themes/themes/unsilo/background_anim.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "21635" }, { "name": "HTML", "bytes": "6605" }, { "name": "JavaScript", "bytes": "4592" }, { "name": "Ruby", "bytes": "10366" } ], "symlink_target": "" }
from django.shortcuts import render # Create your views here. def index(request): return render(request, 'index.html')
{ "content_hash": "1bf321b6cf2f08c60edad13e26703d51", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 40, "avg_line_length": 20.666666666666668, "alnum_prop": 0.75, "repo_name": "JetRunner/epictodo", "id": "19cfcfb6273b7f2e945cb64dcc9a7d3a86cfa32e", "size": "124", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/views.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4424" }, { "name": "JavaScript", "bytes": "13532" }, { "name": "Makefile", "bytes": "55" }, { "name": "Python", "bytes": "12785" }, { "name": "Smarty", "bytes": "451" } ], "symlink_target": "" }
<?php namespace Phix_Project\CliEngine\Helpers; use Phix_Project\CliEngine; use Phix_Project\CommandLineLib4\DefinedSwitch; /** * An assistant to display useful information about all of the commands * that a CliEngine knows about * * Used by: * * ShortHelpSwitch * * LongHelpSwitch * * HelpCommand * * @package Phix_Project * @subpackage CliEngine * @author Stuart Herbert <stuart@stuartherbert.com> * @copyright 2013-present Stuart Herbert. www.stuartherbert.com * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @link http://www.phix-project.org * @version @@PACKAGE_VERSION@@ */ class HelpHelper { public function showShortHelp(CliEngine $engine) { // get the list of switches in display order $sortedSwitches = $engine->getSwitchDefinitions()->getSwitchesInDisplayOrder(); // shorthand $op = $engine->output; $so = $engine->output->stdout; $so->output($op->highlightStyle, $engine->getAppName()); $this->showSwitchSummary($op, $so, $sortedSwitches); // special case - if a default command has been defined if ($engine->hasDefaultCommand()) { $defaultCommand = $engine->getDefaultCommand(); $so->outputLine(null, ' [ <command> ] [ command-options ]'); $so->output(null, '<command> is optional; if omitted, it defaults to: '); $so->outputLine($op->highlightStyle, $defaultCommand->getName()); } else { $so->outputLine(null, ' <command> [ command-options ]'); } } public function showLongHelp(CliEngine $engine) { // get the list of switches in display order $sortedSwitches = $engine->getSwitchDefinitions()->getSwitchesInDisplayOrder(); $sortedCommandSwitches = $engine->getSwitchDefinitions()->getSwitchesInDisplayOrder(array('actsAsCommand' => true)); $sortedModifierSwitches = $engine->getSwitchDefinitions()->getSwitchesInDisplayOrder(array('actsAsCommand' => false)); // shorthand $op = $engine->output; $so = $engine->output->stdout; $so->output($op->highlightStyle, $engine->getAppName() . ' ' . $engine->getAppVersion()); $so->output(null, ' -'); $so->outputLine($op->urlStyle, ' ' . $engine->getAppUrl()); $so->outputLine(null, $engine->getAppCopyright()); $so->outputLine(null, $engine->getAppLicense()); $so->outputBlankLine(); $this->showSynopsis($op, $so, $engine, $sortedSwitches); $this->showOptionsList($op, $so, $sortedCommandSwitches, $sortedModifierSwitches); $this->showCommandsList($op, $so, $engine->getAppName(), $engine->getCommandsList()); } protected function showSynopsis($op, $so, $engine, $sortedSwitches) { $so->outputLine(null, 'SYNOPSIS'); $so->setIndent(4); $so->output($op->commandStyle, $engine->getAppName()); $this->showSwitchSummary($op, $so, $sortedSwitches); // do we have a default command? if (!$engine->hasDefaultCommand()) { $so->outputLine(null, ' <command> [ command-options ]'); $so->outputBlankLine(); // nothing more to show return; } // if we get here, then there's a default command, which makes // things a little more complicated $defaultCommand = $engine->getDefaultCommand(); $so->outputLine(null, ' [ <command> ] [ command-options ]'); $so->outputBlankLine(); $so->output(null, '<command> is optional; if omitted, it defaults to: '); $so->outputLine($op->highlightStyle, $defaultCommand->getName()); $so->outputBlankLine(); } protected function showOptionsList($op, $so, $sortedCommandSwitches, $sortedModifierSwitches) { $so->setIndent(0); $so->outputLine(null, 'OPTIONS'); $so->addIndent(4); // keep track of the switches we have seen, to avoid // any duplication of output $seenSwitches = array(); // do we have any switches that are actually commands? if (count($sortedCommandSwitches['allSwitches'])) { $so->outputLine(null, 'Use the following switches to perform the following actions.'); $so->outputBlankLine(); foreach ($sortedCommandSwitches['allSwitches'] as $shortOrLongSwitch => $switch) { // have we already seen this switch? if (isset($seenSwitches[$switch->name])) { // yes, skip it continue; } $seenSwitches[$switch->name] = $switch; // we have not seen this switch before $this->showSwitchLongDetails($op, $so, $switch); } } // do we have any switches that are actually modifiers to commands? if (count($sortedModifierSwitches['allSwitches'])) { $so->outputLine(null, 'Use the following switches in front of any <command> to have the following effects.'); $so->outputBlankLine(); foreach ($sortedModifierSwitches['allSwitches'] as $shortOrLongSwitch => $switch) { // have we already seen this switch? if (isset($seenSwitches[$switch->name])) { // yes, skip it continue; } $seenSwitches[$switch->name] = $switch; // we have not seen this switch before $this->showSwitchLongDetails($op, $so, $switch); } } } protected function showCommandsList($op, $so, $appName, $commandsList) { // how many commands are there? $noOfCommands = count($commandsList); // what do we need to show the user? if ($noOfCommands == 0) { $this->showNoCommandsList($op, $so, $appName); } else { $this->showManyCommandsList($op, $so, $appName, $commandsList); } } protected function showNoCommandsList($op, $so, $appName) { $so->setIndent(0); $so->outputLine(null, 'COMMANDS'); $so->addIndent(4); $so->output("At this moment in time, "); $so->output($op->commandStyle, $appName); $so->outputLine(" hasn't defined any commands for you to run, sorry!"); } protected function showManyCommandsList($op, $so, $appName, $commandsList) { $so->setIndent(0); $so->outputLine(null, 'COMMANDS'); $so->addIndent(4); ksort($commandsList); // work out our longest command name length $maxlen = 0; foreach ($commandsList as $commandName => $command) { if (strlen($commandName) > $maxlen) { $maxlen = strlen($commandName); } } foreach ($commandsList as $commandName => $command) { $so->output($op->commandStyle, $commandName); $so->addIndent($maxlen + 1); $so->output($op->commentStyle, '# '); $so->addIndent(2); $so->outputLine(null, $command->getShortDescription()); $so->addIndent(0 - $maxlen - 3); } $so->outputBlankLine(); $so->output(null, 'See '); $so->output($op->commandStyle, $appName . ' help <command>'); $so->outputLine(null, ' for detailed help on <command>'); } public function showSwitchSummary($op, $so, $sortedSwitches) { if (count($sortedSwitches['shortSwitchesWithoutArgs']) > 0) { $so->output(null, ' [ '); $so->output($op->switchStyle, '-' . implode(' -', $sortedSwitches['shortSwitchesWithoutArgs'])); $so->output(null, ' ]'); } if (count($sortedSwitches['longSwitchesWithoutArgs']) > 0) { $so->output(null, ' [ '); $so->output($op->switchStyle, '--' . implode(' --', $sortedSwitches['longSwitchesWithoutArgs'])); $so->output(null, ' ]'); } if (count($sortedSwitches['shortSwitchesWithArgs']) > 0) { foreach ($sortedSwitches['shortSwitchesWithArgs'] as $shortSwitch => $switch) { $so->output(null, ' [ '); $so->output($op->switchStyle, '-' . $shortSwitch . ' '); $so->output($op->argStyle, $switch->arg->name); $so->output(null, ' ]'); } } if (count($sortedSwitches['longSwitchesWithArgs']) > 0) { foreach ($sortedSwitches['longSwitchesWithArgs'] as $longSwitch => $switch) { $so->output(null, ' [ '); if ($switch->testHasArgument()) { $so->output($op->switchStyle, '--' . $longSwitch . '='); $so->output($op->argStyle, $switch->arg->name); } $so->output(null, ' ]'); } } } public function showSwitchLongDetails($op, $so, DefinedSwitch $switch) { $shortOrLongSwitches = $switch->getHumanReadableSwitchList(); $append = false; foreach ($shortOrLongSwitches as $shortOrLongSwitch) { if ($append) { $so->output(null, ' | '); } $append = true; $so->output($op->switchStyle, $shortOrLongSwitch); // is there an argument? if ($switch->testHasArgument()) { if ($shortOrLongSwitch{1} == '-') { $so->output(null, '='); } else { $so->output(null, ' '); } $so->output($op->argStyle, $switch->arg->name); } } $so->outputLine(null, ''); $so->addIndent(4); $so->outputLine(null, $switch->desc); if (isset($switch->longdesc)) { $so->outputBlankLine(); $so->outputLine(null, $switch->longdesc); } // output details about any argument if ($switch->testHasArgument()) { $so->outputBlankLine(); $so->outputLine($op->argStyle, $switch->arg->name); $so->addIndent(4); $so->output(null, $switch->arg->desc); // output the default argument, if it is set if (isset($switch->arg->defaultValue)) { $so->output(null, ' (default: '); $so->output($op->exampleStyle, $switch->arg->defaultValue); $so->outputLine(null, ')'); } $so->addIndent(-4); } $so->addIndent(-4); $so->outputBlankLine(); } }
{ "content_hash": "f860d660bd376bca3964b51c8d6969f1", "timestamp": "", "source": "github", "line_count": 320, "max_line_length": 126, "avg_line_length": 34.209375, "alnum_prop": 0.5345756828354801, "repo_name": "stuartherbert/CliEngine", "id": "033f181360824ecf455458bac7e4abbc609661ae", "size": "12906", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/php/Phix_Project/CliEngine/Helpers/HelpHelper.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "78265" } ], "symlink_target": "" }
 #pragma once #include <aws/dynamodb/DynamoDB_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/dynamodb/model/Projection.h> #include <aws/dynamodb/model/KeySchemaElement.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace DynamoDB { namespace Model { /** * <p>Represents the properties of a local secondary index for the table when the * backup was created.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/LocalSecondaryIndexInfo">AWS * API Reference</a></p> */ class AWS_DYNAMODB_API LocalSecondaryIndexInfo { public: LocalSecondaryIndexInfo(); LocalSecondaryIndexInfo(Aws::Utils::Json::JsonView jsonValue); LocalSecondaryIndexInfo& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>Represents the name of the local secondary index.</p> */ inline const Aws::String& GetIndexName() const{ return m_indexName; } /** * <p>Represents the name of the local secondary index.</p> */ inline bool IndexNameHasBeenSet() const { return m_indexNameHasBeenSet; } /** * <p>Represents the name of the local secondary index.</p> */ inline void SetIndexName(const Aws::String& value) { m_indexNameHasBeenSet = true; m_indexName = value; } /** * <p>Represents the name of the local secondary index.</p> */ inline void SetIndexName(Aws::String&& value) { m_indexNameHasBeenSet = true; m_indexName = std::move(value); } /** * <p>Represents the name of the local secondary index.</p> */ inline void SetIndexName(const char* value) { m_indexNameHasBeenSet = true; m_indexName.assign(value); } /** * <p>Represents the name of the local secondary index.</p> */ inline LocalSecondaryIndexInfo& WithIndexName(const Aws::String& value) { SetIndexName(value); return *this;} /** * <p>Represents the name of the local secondary index.</p> */ inline LocalSecondaryIndexInfo& WithIndexName(Aws::String&& value) { SetIndexName(std::move(value)); return *this;} /** * <p>Represents the name of the local secondary index.</p> */ inline LocalSecondaryIndexInfo& WithIndexName(const char* value) { SetIndexName(value); return *this;} /** * <p>The complete key schema for a local secondary index, which consists of one or * more pairs of attribute names and key types:</p> <ul> <li> <p> <code>HASH</code> * - partition key</p> </li> <li> <p> <code>RANGE</code> - sort key</p> </li> </ul> * <p>The partition key of an item is also known as its <i>hash * attribute</i>. The term "hash attribute" derives from DynamoDB's usage of an * internal hash function to evenly distribute data items across partitions, based * on their partition key values.</p> <p>The sort key of an item is also known as * its <i>range attribute</i>. The term "range attribute" derives from the way * DynamoDB stores items with the same partition key physically close together, in * sorted order by the sort key value.</p> */ inline const Aws::Vector<KeySchemaElement>& GetKeySchema() const{ return m_keySchema; } /** * <p>The complete key schema for a local secondary index, which consists of one or * more pairs of attribute names and key types:</p> <ul> <li> <p> <code>HASH</code> * - partition key</p> </li> <li> <p> <code>RANGE</code> - sort key</p> </li> </ul> * <p>The partition key of an item is also known as its <i>hash * attribute</i>. The term "hash attribute" derives from DynamoDB's usage of an * internal hash function to evenly distribute data items across partitions, based * on their partition key values.</p> <p>The sort key of an item is also known as * its <i>range attribute</i>. The term "range attribute" derives from the way * DynamoDB stores items with the same partition key physically close together, in * sorted order by the sort key value.</p> */ inline bool KeySchemaHasBeenSet() const { return m_keySchemaHasBeenSet; } /** * <p>The complete key schema for a local secondary index, which consists of one or * more pairs of attribute names and key types:</p> <ul> <li> <p> <code>HASH</code> * - partition key</p> </li> <li> <p> <code>RANGE</code> - sort key</p> </li> </ul> * <p>The partition key of an item is also known as its <i>hash * attribute</i>. The term "hash attribute" derives from DynamoDB's usage of an * internal hash function to evenly distribute data items across partitions, based * on their partition key values.</p> <p>The sort key of an item is also known as * its <i>range attribute</i>. The term "range attribute" derives from the way * DynamoDB stores items with the same partition key physically close together, in * sorted order by the sort key value.</p> */ inline void SetKeySchema(const Aws::Vector<KeySchemaElement>& value) { m_keySchemaHasBeenSet = true; m_keySchema = value; } /** * <p>The complete key schema for a local secondary index, which consists of one or * more pairs of attribute names and key types:</p> <ul> <li> <p> <code>HASH</code> * - partition key</p> </li> <li> <p> <code>RANGE</code> - sort key</p> </li> </ul> * <p>The partition key of an item is also known as its <i>hash * attribute</i>. The term "hash attribute" derives from DynamoDB's usage of an * internal hash function to evenly distribute data items across partitions, based * on their partition key values.</p> <p>The sort key of an item is also known as * its <i>range attribute</i>. The term "range attribute" derives from the way * DynamoDB stores items with the same partition key physically close together, in * sorted order by the sort key value.</p> */ inline void SetKeySchema(Aws::Vector<KeySchemaElement>&& value) { m_keySchemaHasBeenSet = true; m_keySchema = std::move(value); } /** * <p>The complete key schema for a local secondary index, which consists of one or * more pairs of attribute names and key types:</p> <ul> <li> <p> <code>HASH</code> * - partition key</p> </li> <li> <p> <code>RANGE</code> - sort key</p> </li> </ul> * <p>The partition key of an item is also known as its <i>hash * attribute</i>. The term "hash attribute" derives from DynamoDB's usage of an * internal hash function to evenly distribute data items across partitions, based * on their partition key values.</p> <p>The sort key of an item is also known as * its <i>range attribute</i>. The term "range attribute" derives from the way * DynamoDB stores items with the same partition key physically close together, in * sorted order by the sort key value.</p> */ inline LocalSecondaryIndexInfo& WithKeySchema(const Aws::Vector<KeySchemaElement>& value) { SetKeySchema(value); return *this;} /** * <p>The complete key schema for a local secondary index, which consists of one or * more pairs of attribute names and key types:</p> <ul> <li> <p> <code>HASH</code> * - partition key</p> </li> <li> <p> <code>RANGE</code> - sort key</p> </li> </ul> * <p>The partition key of an item is also known as its <i>hash * attribute</i>. The term "hash attribute" derives from DynamoDB's usage of an * internal hash function to evenly distribute data items across partitions, based * on their partition key values.</p> <p>The sort key of an item is also known as * its <i>range attribute</i>. The term "range attribute" derives from the way * DynamoDB stores items with the same partition key physically close together, in * sorted order by the sort key value.</p> */ inline LocalSecondaryIndexInfo& WithKeySchema(Aws::Vector<KeySchemaElement>&& value) { SetKeySchema(std::move(value)); return *this;} /** * <p>The complete key schema for a local secondary index, which consists of one or * more pairs of attribute names and key types:</p> <ul> <li> <p> <code>HASH</code> * - partition key</p> </li> <li> <p> <code>RANGE</code> - sort key</p> </li> </ul> * <p>The partition key of an item is also known as its <i>hash * attribute</i>. The term "hash attribute" derives from DynamoDB's usage of an * internal hash function to evenly distribute data items across partitions, based * on their partition key values.</p> <p>The sort key of an item is also known as * its <i>range attribute</i>. The term "range attribute" derives from the way * DynamoDB stores items with the same partition key physically close together, in * sorted order by the sort key value.</p> */ inline LocalSecondaryIndexInfo& AddKeySchema(const KeySchemaElement& value) { m_keySchemaHasBeenSet = true; m_keySchema.push_back(value); return *this; } /** * <p>The complete key schema for a local secondary index, which consists of one or * more pairs of attribute names and key types:</p> <ul> <li> <p> <code>HASH</code> * - partition key</p> </li> <li> <p> <code>RANGE</code> - sort key</p> </li> </ul> * <p>The partition key of an item is also known as its <i>hash * attribute</i>. The term "hash attribute" derives from DynamoDB's usage of an * internal hash function to evenly distribute data items across partitions, based * on their partition key values.</p> <p>The sort key of an item is also known as * its <i>range attribute</i>. The term "range attribute" derives from the way * DynamoDB stores items with the same partition key physically close together, in * sorted order by the sort key value.</p> */ inline LocalSecondaryIndexInfo& AddKeySchema(KeySchemaElement&& value) { m_keySchemaHasBeenSet = true; m_keySchema.push_back(std::move(value)); return *this; } /** * <p>Represents attributes that are copied (projected) from the table into the * global secondary index. These are in addition to the primary key attributes and * index key attributes, which are automatically projected. </p> */ inline const Projection& GetProjection() const{ return m_projection; } /** * <p>Represents attributes that are copied (projected) from the table into the * global secondary index. These are in addition to the primary key attributes and * index key attributes, which are automatically projected. </p> */ inline bool ProjectionHasBeenSet() const { return m_projectionHasBeenSet; } /** * <p>Represents attributes that are copied (projected) from the table into the * global secondary index. These are in addition to the primary key attributes and * index key attributes, which are automatically projected. </p> */ inline void SetProjection(const Projection& value) { m_projectionHasBeenSet = true; m_projection = value; } /** * <p>Represents attributes that are copied (projected) from the table into the * global secondary index. These are in addition to the primary key attributes and * index key attributes, which are automatically projected. </p> */ inline void SetProjection(Projection&& value) { m_projectionHasBeenSet = true; m_projection = std::move(value); } /** * <p>Represents attributes that are copied (projected) from the table into the * global secondary index. These are in addition to the primary key attributes and * index key attributes, which are automatically projected. </p> */ inline LocalSecondaryIndexInfo& WithProjection(const Projection& value) { SetProjection(value); return *this;} /** * <p>Represents attributes that are copied (projected) from the table into the * global secondary index. These are in addition to the primary key attributes and * index key attributes, which are automatically projected. </p> */ inline LocalSecondaryIndexInfo& WithProjection(Projection&& value) { SetProjection(std::move(value)); return *this;} private: Aws::String m_indexName; bool m_indexNameHasBeenSet; Aws::Vector<KeySchemaElement> m_keySchema; bool m_keySchemaHasBeenSet; Projection m_projection; bool m_projectionHasBeenSet; }; } // namespace Model } // namespace DynamoDB } // namespace Aws
{ "content_hash": "658217a47bce74b06a21b2cdf4dad223", "timestamp": "", "source": "github", "line_count": 251, "max_line_length": 163, "avg_line_length": 50.02390438247012, "alnum_prop": 0.681745778910481, "repo_name": "jt70471/aws-sdk-cpp", "id": "bb486c1448f8681028a1cc32b4ebaf22b5ae7d7b", "size": "12675", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "aws-cpp-sdk-dynamodb/include/aws/dynamodb/model/LocalSecondaryIndexInfo.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "13452" }, { "name": "C++", "bytes": "278594037" }, { "name": "CMake", "bytes": "653931" }, { "name": "Dockerfile", "bytes": "5555" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "302182" }, { "name": "Python", "bytes": "110380" }, { "name": "Shell", "bytes": "4674" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Threading.Tasks; using Core.Repositories.ExtraAmounts; using MongoDB.Bson.Serialization.Attributes; using MongoRepositories.Mongo; namespace MongoRepositories.ExtraAmounts { public class ExtraAmountEntity : MongoEntity, IExtraAmount { public static string Partition = "ExtraAmount"; [BsonIgnore] public string Address => BsonId; public long Amount { get; set; } public static ExtraAmountEntity Create(string address, long amount) { return new ExtraAmountEntity { BsonId = address, Amount = amount }; } } public class ExtraAmountRepository : IExtraAmountRepository { private readonly IMongoStorage<ExtraAmountEntity> _table; public ExtraAmountRepository(IMongoStorage<ExtraAmountEntity> table) { _table = table; } public async Task<IExtraAmount> Add(string address, long amount) { var entity = ExtraAmountEntity.Create(address, amount); await _table.InsertOrModifyAsync(address, () => entity, x => { x.Amount += amount; return x; }); return entity; } public Task Decrease(IExtraAmount extraAmount) { return _table.ReplaceAsync(extraAmount.Address, amountEntity => { amountEntity.Amount -= extraAmount.Amount; return amountEntity; }); } public async Task<IEnumerable<IExtraAmount>> GetData() { return await _table.GetDataAsync(); } } }
{ "content_hash": "e1b1cac86afa39826734982361dc7551", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 76, "avg_line_length": 25.791044776119403, "alnum_prop": 0.5873842592592593, "repo_name": "LykkeCity/bitcoinservice", "id": "7f7845d60c0624f631e21b7ba7118bab77b51f92", "size": "1730", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/MongoRepositories/ExtraAmounts/ExtraAmountRepository.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1135287" }, { "name": "Dockerfile", "bytes": "252" }, { "name": "JavaScript", "bytes": "603" }, { "name": "PowerShell", "bytes": "213" } ], "symlink_target": "" }
package com.taobao.zeus.store.mysql; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.taobao.zeus.client.ZeusException; import com.taobao.zeus.model.GroupDescriptor; import com.taobao.zeus.model.JobDescriptor; import com.taobao.zeus.model.JobDescriptor.JobRunType; import com.taobao.zeus.model.JobStatus; import com.taobao.zeus.model.processer.Processer; import com.taobao.zeus.schedule.mvc.DebugInfoLog; import com.taobao.zeus.store.GroupBean; import com.taobao.zeus.store.GroupManager; import com.taobao.zeus.store.GroupManagerTool; import com.taobao.zeus.store.JobBean; import com.taobao.zeus.store.mysql.persistence.GroupPersistence; import com.taobao.zeus.store.mysql.persistence.JobPersistence; import com.taobao.zeus.store.mysql.persistence.JobPersistenceOld; import com.taobao.zeus.store.mysql.persistence.Worker; import com.taobao.zeus.store.mysql.tool.Judge; import com.taobao.zeus.store.mysql.tool.PersistenceAndBeanConvert; import com.taobao.zeus.util.Tuple; /** * 性能优化,防止每次都递归去查询mysql * @author zhoufang * */ public class ReadOnlyGroupManager extends HibernateDaoSupport{ private static final Logger log = LoggerFactory.getLogger(ReadOnlyGroupManager.class); private Judge jobjudge=new Judge(); private Judge groupjudge=new Judge(); private Judge ignoreContentJobJudge=new Judge(); private Judge ignoreContentGroupJudge=new Judge(); private GroupManager groupManager; public void setGroupManager(GroupManager groupManager) { this.groupManager = groupManager; } /**完整的globe GroupBean*/ private GroupBean globe; private GroupBean ignoreGlobe; private static final ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(20); /** * Jobs或者Groups是否有变化,忽略脚本内容的改变(保证树形结构不变即可) * @return */ @SuppressWarnings("unchecked") private boolean isJobsAndGroupsChangedIgnoreContent(){ //init final Judge ignoreContentJobJudge=this.ignoreContentJobJudge; final Judge ignoreContentGroupJudge=this.ignoreContentGroupJudge; final GroupBean ignoreGlobe=this.ignoreGlobe; boolean jobChanged; Judge jobrealtime=null; jobrealtime=(Judge) getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { Object[] o=(Object[]) session.createSQLQuery("select count(*),max(job_id),max(gmt_modified) from zeus_action where id>=date_format(now(),'20%y%m%d0000000000')").uniqueResult(); if(o!=null){ Judge j=new Judge(); j.count=((Number) o[0]).intValue(); j.maxId=o[1]==null?0:((Number)o[1]).intValue(); j.lastModified=o[2]==null?new Date(0):(Date) o[2]; j.stamp=new Date(); return j; } return null; } }); List<JobDescriptor> changedJobs; changedJobs=(List<JobDescriptor>) getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query=session.createQuery("select id,groupId from com.taobao.zeus.store.mysql.persistence.JobPersistence where gmt_modified>?"); query.setDate(0, ignoreContentJobJudge.lastModified); List<Object[]> list=query.list(); List<JobDescriptor> result=new ArrayList<JobDescriptor>(); for(Object[] o:list){ JobDescriptor jd=new JobDescriptor(); jd.setId(String.valueOf(o[0])); jd.setGroupId(String.valueOf(o[1])); result.add(jd); } return result; } }); if(jobrealtime!=null && jobrealtime.count.equals(ignoreContentJobJudge.count) && jobrealtime.maxId.equals(ignoreContentJobJudge.maxId) && isAllJobsNotChangeParent(ignoreGlobe, changedJobs)){ ignoreContentJobJudge.stamp=new Date(); ignoreContentJobJudge.lastModified=jobrealtime.lastModified; jobChanged= false; }else{ this.ignoreContentJobJudge=jobrealtime; jobChanged= true; } //Group boolean groupChanged; Judge grouprealtime=null; grouprealtime=(Judge) getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { Object[] o=(Object[]) session.createSQLQuery("select count(*),max(id),max(gmt_modified) from zeus_group").uniqueResult(); if(o!=null){ Judge j=new Judge(); j.count=((Number) o[0]).intValue(); j.maxId=o[1]==null?0:((Number)o[1]).intValue(); j.lastModified=o[2]==null?new Date(0):(Date) o[2]; j.stamp=new Date(); return j; } return null; } }); List<GroupDescriptor> changedGroups=null; changedGroups=(List<GroupDescriptor>) getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query=session.createQuery("from com.taobao.zeus.store.mysql.persistence.GroupPersistence where gmt_modified>?"); query.setDate(0, ignoreContentGroupJudge.lastModified); List<GroupPersistence> list=query.list(); List<GroupDescriptor> result=new ArrayList<GroupDescriptor>(); for(GroupPersistence p:list){ result.add(PersistenceAndBeanConvert.convert(p)); } return result; } }); if(grouprealtime!=null && grouprealtime.count.equals(ignoreContentGroupJudge.count) && grouprealtime.maxId.equals(ignoreContentGroupJudge.maxId) && isAllGroupsNotChangeParent(ignoreGlobe, changedGroups)){ ignoreContentGroupJudge.stamp=new Date(); groupChanged= false; }else{ this.ignoreContentGroupJudge=grouprealtime; groupChanged= true; } return jobChanged || groupChanged; } /** * 判断变动的Job中,是否全部不涉及parent节点的变化 * @param gb * @param list * @return */ private boolean isAllJobsNotChangeParent(GroupBean gb,List<JobDescriptor> list){ Map<String, JobBean> allJobs=gb.getAllSubJobBeans(); for(JobDescriptor jd:list){ JobBean bean=allJobs.get(jd.getId()); if(bean==null){ DebugInfoLog.info("isAllJobsNotChangeParent job id="+ jd.getId()+" has changed"); return false; } JobDescriptor old=bean.getJobDescriptor(); if(!old.getGroupId().equals(jd.getGroupId())){ DebugInfoLog.info("isAllJobsNotChangeParent job id="+ jd.getId()+" has changed"); return false; } } return true; } /** * 判断变动的Group中,是否全部不涉及parent节点的变化 * @param gb * @param list * @return */ private boolean isAllGroupsNotChangeParent(GroupBean gb,List<GroupDescriptor> list){ Map<String, GroupBean> allGroups=gb.getAllSubGroupBeans(); for(GroupDescriptor gd:list){ GroupBean bean=allGroups.get(gd.getId()); if(gd.getId().equals(gb.getGroupDescriptor().getId())){ break; } if(bean==null){ DebugInfoLog.info("isAllGroupsNotChangeParent group id="+ gd.getId()+" has changed"); return false; } GroupDescriptor old=bean.getGroupDescriptor(); if(!old.getParent().equals(gd.getParent())){ DebugInfoLog.info("isAllGroupsNotChangeParent group id="+ gd.getId()+" has changed"); return false; } } return true; } /** * Jobs或者Groups是否有变化 * 判断标准:同时满足以下条件 * 1.max id 一致 * 2.count 数一致 * 3.last_modified 一致 * @return */ private boolean isJobsAndGroupsChanged(){ //init final Judge jobjudge=this.jobjudge; final Judge groupjudge=this.groupjudge; boolean jobChanged; Judge jobrealtime=(Judge) getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { Object[] o=(Object[]) session.createSQLQuery("select count(*),max(job_id),max(gmt_modified) from zeus_action where id>=date_format(now(),'20%y%m%d0000000000')").uniqueResult(); if(o!=null){ Judge j=new Judge(); j.count=((Number) o[0]).intValue(); j.maxId=((Number)o[1]).intValue(); j.lastModified=(Date) o[2]; j.stamp=new Date(); return j; } return null; } }); if(jobrealtime!=null && jobrealtime.count.equals(jobjudge.count) && jobrealtime.maxId.equals(jobjudge.maxId) && jobrealtime.lastModified.equals(jobjudge.lastModified)){ jobjudge.stamp=new Date(); jobChanged= false; }else{ this.jobjudge=jobrealtime; jobChanged= true; } boolean groupChanged; Judge grouprealtime=(Judge) getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { Object[] o=(Object[]) session.createSQLQuery("select count(*),max(id),max(gmt_modified) from zeus_group").uniqueResult(); if(o!=null){ Judge j=new Judge(); j.count=((Number) o[0]).intValue(); j.maxId=((Number)o[1]).intValue(); j.lastModified=(Date) o[2]; j.stamp=new Date(); return j; } return null; } }); if(grouprealtime!=null && grouprealtime.count.equals(groupjudge.count) && grouprealtime.maxId.equals(groupjudge.maxId) && grouprealtime.lastModified.equals(groupjudge.lastModified)){ groupjudge.stamp=new Date(); groupChanged= false; }else{ this.groupjudge=grouprealtime; groupChanged= true; } return jobChanged || groupChanged; } public synchronized GroupBean getGlobeGroupBean() { if(globe!=null){ if(!isJobsAndGroupsChanged()){ return globe; } } globe=new ReadOnlyGroupManagerAssembly(groupManager).getGlobeGroupBean(); return globe; } /** * 为Tree展示提供的方法,每次都返回Copy对象,可以对返回结果进行引用修改 * @return */ public synchronized GroupBean getGlobeGroupBeanForTreeDisplay(boolean copy){ if(ignoreGlobe==null || isJobsAndGroupsChangedIgnoreContent() ){ ignoreGlobe=new ReadOnlyGroupManagerAssembly(groupManager).getGlobeGroupBean(); } if(copy){ return GroupManagerTool.buildGlobeGroupBeanWithoutDepend(new CopyGroupManagerAssembly(ignoreGlobe)); }else{ return ignoreGlobe; } } public GroupBean getCopyGlobeGroupBean(){ GroupBean gb=getGlobeGroupBean(); return GroupManagerTool.buildGlobeGroupBean(new CopyGroupManagerAssembly(gb)); } private class CopyGroupManagerAssembly extends ReadOnlyGroupManagerAssembly{ private GroupBean globe; public CopyGroupManagerAssembly(GroupBean globe) { super(null); this.globe=globe; } @Override public String getRootGroupId() { return globe.getGroupDescriptor().getId(); } @Override public List<GroupDescriptor> getChildrenGroup(String groupId) { List<GroupBean> list=null; if(globe.getGroupDescriptor().getId().equals(groupId)){ list=globe.getChildrenGroupBeans(); }else{ list=globe.getAllSubGroupBeans().get(groupId).getChildrenGroupBeans(); } List<GroupDescriptor> result=new ArrayList<GroupDescriptor>(); if(list!=null){ for(GroupBean gb:list){ result.add(gb.getGroupDescriptor()); } } return result; } @Override public GroupDescriptor getGroupDescriptor(String groupId) { if(globe.getGroupDescriptor().getId().equals(groupId)){ return globe.getGroupDescriptor(); }else{ return globe.getAllSubGroupBeans().get(groupId).getGroupDescriptor(); } } @Override public List<Tuple<JobDescriptor, JobStatus>> getChildrenJob( String groupId) { Map<String, JobBean> map=globe.getAllSubGroupBeans().get(groupId).getJobBeans(); List<Tuple<JobDescriptor, JobStatus>> result=new ArrayList<Tuple<JobDescriptor,JobStatus>>(); for(JobBean jb:map.values()){ result.add(new Tuple<JobDescriptor, JobStatus>(jb.getJobDescriptor(), jb.getJobStatus())); } return result; } } private class ReadOnlyGroupManagerAssembly implements GroupManager{ private GroupManager groupManager; public ReadOnlyGroupManagerAssembly(GroupManager gm){ this.groupManager=gm; } @Override public GroupDescriptor createGroup(String user, String groupName, String parentGroup, boolean isDirectory) throws ZeusException { throw new UnsupportedOperationException(); } @Override public JobDescriptor createJob(String user, String jobName, String parentGroup, JobRunType jobType) throws ZeusException { throw new UnsupportedOperationException(); } @Override public void deleteGroup(String user, String groupId) throws ZeusException { throw new UnsupportedOperationException(); } @Override public void deleteJob(String user, String jobId) throws ZeusException { throw new UnsupportedOperationException(); } @Override public List<GroupDescriptor> getChildrenGroup(String groupId) { List<GroupDescriptor> list= groupManager.getChildrenGroup(groupId); List<GroupDescriptor> result=new ArrayList<GroupDescriptor>(); for(GroupDescriptor gd:list){ result.add(new ReadOnlyGroupDescriptor(gd)); } return result; } @Override public List<Tuple<JobDescriptor, JobStatus>> getChildrenJob( String groupId) { List<Tuple<JobDescriptor, JobStatus>> list=groupManager.getChildrenJob(groupId); List<Tuple<JobDescriptor, JobStatus>> result=new ArrayList<Tuple<JobDescriptor,JobStatus>>(); for(Tuple<JobDescriptor, JobStatus> tuple:list){ Tuple<JobDescriptor, JobStatus> t=new Tuple<JobDescriptor, JobStatus>(new ReadOnlyJobDescriptor(tuple.getX()),new ReadOnlyJobStatus(tuple.getY())); result.add(t); } return result; } @Override public GroupBean getDownstreamGroupBean(String groupId) { ReadOnlyGroupDescriptor readGd=null; GroupDescriptor group=getGroupDescriptor(groupId); if(group instanceof ReadOnlyGroupDescriptor){ readGd=(ReadOnlyGroupDescriptor) group; }else{ readGd=new ReadOnlyGroupDescriptor(group); } GroupBean result=new GroupBean(readGd); return getDownstreamGroupBean(result); } @Override public GroupBean getDownstreamGroupBean(GroupBean parent) { try { return getDownstreamGroupBean(parent, 99).get(10,TimeUnit.SECONDS); } catch (Exception e) { log.error("getDownstreamGroupBean failed", e); return null; } } private Future<GroupBean> getDownstreamGroupBean(final GroupBean parent, final int depth) throws Exception{ Callable<GroupBean> callable = new Callable<GroupBean>(){ @Override public GroupBean call() throws Exception { if(parent.isDirectory()){ List<GroupDescriptor> children=getChildrenGroup(parent.getGroupDescriptor().getId()); ArrayList<Future<GroupBean>> futures = new ArrayList<Future<GroupBean>>(children.size()); for(GroupDescriptor child:children){ ReadOnlyGroupDescriptor readGd=null; if(child instanceof ReadOnlyGroupDescriptor){ readGd=(ReadOnlyGroupDescriptor) child; }else{ readGd=new ReadOnlyGroupDescriptor(child); } GroupBean childBean=new GroupBean(readGd); if(pool.getActiveCount()<15) { futures.add(getDownstreamGroupBean(childBean, 99)); }else{ getDownstreamGroupBean(childBean, 0); } childBean.setParentGroupBean(parent); parent.getChildrenGroupBeans().add(childBean); } for(Future<GroupBean> f:futures){ f.get(10,TimeUnit.SECONDS); } }else{ List<Tuple<JobDescriptor, JobStatus>> jobs=getChildrenJob(parent.getGroupDescriptor().getId()); for(Tuple<JobDescriptor, JobStatus> tuple:jobs){ JobBean jobBean=new JobBean(tuple.getX(),tuple.getY()); jobBean.setGroupBean(parent); parent.getJobBeans().put(tuple.getX().getId(), jobBean); } } return parent; } }; if(depth>0) { return pool.submit(callable); }else{ callable.call(); return new Future<GroupBean>() { @Override public boolean cancel(boolean mayInterruptIfRunning) {return false;} @Override public boolean isCancelled() {return false;} @Override public boolean isDone() {return false;} @Override public GroupBean get() throws InterruptedException, ExecutionException {return null;} @Override public GroupBean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return parent; } }; } } @Override public GroupBean getGlobeGroupBean() { return GroupManagerTool.buildGlobeGroupBean(this); } @Override public GroupDescriptor getGroupDescriptor(String groupId) { return new ReadOnlyGroupDescriptor(groupManager.getGroupDescriptor(groupId)); } @Override public Tuple<JobDescriptor, JobStatus> getJobDescriptor(String jobId) { return groupManager.getJobDescriptor(jobId); } @Override public Map<String, Tuple<JobDescriptor, JobStatus>> getJobDescriptor( Collection<String> jobIds) { return groupManager.getJobDescriptor(jobIds); } @Override public JobStatus getJobStatus(String jobId) { return new ReadOnlyJobStatus(groupManager.getJobStatus(jobId)); } @Override public String getRootGroupId() { return groupManager.getRootGroupId(); } @Override public GroupBean getUpstreamGroupBean(String groupId) { return GroupManagerTool.getUpstreamGroupBean(groupId, this); } @Override public JobBean getUpstreamJobBean(String jobId) { return GroupManagerTool.getUpstreamJobBean(jobId, this); } @Override public void grantGroupOwner(String granter, String uid, String groupId) throws ZeusException { throw new UnsupportedOperationException(); } @Override public void grantJobOwner(String granter, String uid, String jobId) throws ZeusException { throw new UnsupportedOperationException(); } @Override public void moveGroup(String uid, String groupId, String newParentGroupId) throws ZeusException { throw new UnsupportedOperationException(); } @Override public void moveJob(String uid, String jobId, String groupId) throws ZeusException { throw new UnsupportedOperationException(); } @Override public void updateGroup(String user, GroupDescriptor group) throws ZeusException { throw new UnsupportedOperationException(); } @Override public void updateJob(String user, JobDescriptor job) throws ZeusException { throw new UnsupportedOperationException(); } @Override public void updateJobStatus(JobStatus jobStatus) { throw new UnsupportedOperationException(); } @Override public List<String> getHosts() throws ZeusException { return Collections.emptyList(); } @Override public void replaceWorker(Worker worker) throws ZeusException { // TODO Auto-generated method stub } @Override public void removeWorker(String host) throws ZeusException { // TODO Auto-generated method stub } @Override public void saveJob(JobPersistence actionPer) throws ZeusException { // TODO Auto-generated method stub } @Override public List<JobPersistence> getLastJobAction(String jobId){ // TODO Auto-generated method stub return null; } @Override public void updateAction(JobDescriptor actionPer) throws ZeusException { // TODO Auto-generated method stub } @Override public List<Tuple<JobDescriptor, JobStatus>> getActionList(String jobId) { // TODO Auto-generated method stub return null; } @Override public void removeJob(Long actionId) throws ZeusException { // TODO Auto-generated method stub } @Override public boolean IsExistedBelowRootGroup(String GroupName) { throw new UnsupportedOperationException(); } } /** * 不可变的GroupDescriptor类 * @author zhoufang * */ public class ReadOnlyGroupDescriptor extends GroupDescriptor{ private static final long serialVersionUID = 1L; private GroupDescriptor gd; public ReadOnlyGroupDescriptor(GroupDescriptor gd){ this.gd=gd; } @Override public String getDesc() { return gd.getDesc(); } @Override public String getId() { return gd.getId(); } @Override public String getName() { return gd.getName(); } @Override public String getOwner() { return gd.getOwner(); } @Override public boolean isDirectory() { return gd.isDirectory(); } @Override public void setDesc(String desc) { throw new UnsupportedOperationException(); } @Override public void setName(String name) { throw new UnsupportedOperationException(); } @Override public void setOwner(String owner) { throw new UnsupportedOperationException(); } @Override public String getParent() { return gd.getParent(); } @Override public void setParent(String parent) { throw new UnsupportedOperationException(); } @Override public List<Map<String, String>> getResources() { List<Map<String, String>> list=gd.getResources(); List<Map<String, String>> result=new ArrayList<Map<String,String>>(); for(Map<String, String> map:list){ result.add(new HashMap<String, String>(map)); } return result; } @Override public void setResources(List<Map<String, String>> resources) { throw new UnsupportedOperationException(); } @Override public void setId(String id) { throw new UnsupportedOperationException(); } @Override public void setDirectory(boolean directory) { throw new UnsupportedOperationException(); } @Override public Map<String, String> getProperties() { return new HashMap<String, String>(gd.getProperties()); } @Override public void setProperties(Map<String, String> properties) { throw new UnsupportedOperationException(); } } /** * 不可变JobDescriptor类 * @author zhoufang * */ public class ReadOnlyJobDescriptor extends JobDescriptor{ private static final long serialVersionUID = 1L; private JobDescriptor jd; public ReadOnlyJobDescriptor(JobDescriptor jd){ this.jd=jd; } @Override public List<Map<String, String>> getResources() { List<Map<String, String>> list=jd.getResources(); List<Map<String, String>> result=new ArrayList<Map<String,String>>(); for(Map<String, String> map:list){ result.add(new HashMap<String, String>(map)); } return result; } @Override public String getCronExpression() { return jd.getCronExpression(); } @Override public List<String> getDependencies() { return new ArrayList<String>(jd.getDependencies()); } @Override public String getDesc() { return jd.getDesc(); } @Override public String getGroupId() { return jd.getGroupId(); } @Override public String getId() { return jd.getId(); } @Override public JobRunType getJobType() { return jd.getJobType(); } @Override public String getName() { return jd.getName(); } @Override public String getOwner() { return jd.getOwner(); } @Override public JobScheduleType getScheduleType() { return jd.getScheduleType(); } @Override public boolean hasDependencies() { return !jd.getDependencies().isEmpty(); } @Override public void setCronExpression(String cronExpression) { throw new UnsupportedOperationException(); } @Override public void setDependencies(List<String> depends) { throw new UnsupportedOperationException(); } @Override public void setDesc(String desc) { throw new UnsupportedOperationException(); } @Override public void setJobType(JobRunType type) { throw new UnsupportedOperationException(); } @Override public void setName(String name) { throw new UnsupportedOperationException(); } @Override public void setOwner(String owner) { throw new UnsupportedOperationException(); } @Override public void setScheduleType(JobScheduleType type) { throw new UnsupportedOperationException(); } @Override public void setGroupId(String groupId) { throw new UnsupportedOperationException(); } @Override public void setId(String id) { throw new UnsupportedOperationException(); } @Override public void setResources(List<Map<String, String>> resources) { throw new UnsupportedOperationException(); } @Override public Map<String, String> getProperties() { return new HashMap<String, String>(jd.getProperties()); } @Override public void setProperties(Map<String, String> properties) { throw new UnsupportedOperationException(); } @Override public Boolean getAuto() { return jd.getAuto(); } @Override public void setAuto(Boolean auto) { throw new UnsupportedOperationException(); } /*@Override public String getScript() { return jd.getScript(); } @Override public void setScript(String script) { throw new UnsupportedOperationException(); }*/ @Override public List<Processer> getPreProcessers() { return new ArrayList<Processer>(jd.getPreProcessers()); } @Override public void setPreProcessers(List<Processer> preProcessers) { throw new UnsupportedOperationException(); } @Override public List<Processer> getPostProcessers() { return new ArrayList<Processer>(jd.getPostProcessers()); } @Override public void setPostProcessers(List<Processer> postProcessers) { throw new UnsupportedOperationException(); } } /** * 不可变JobStatus类 * @author zhoufang * */ public class ReadOnlyJobStatus extends JobStatus{ private static final long serialVersionUID = 1L; private JobStatus jobStatus; public ReadOnlyJobStatus(JobStatus js){ jobStatus=js; } @Override public String getJobId(){ return jobStatus.getJobId(); } @Override public void setJobId(String jobId){ throw new UnsupportedOperationException(); } @Override public Status getStatus(){ return jobStatus.getStatus(); } @Override public void setStatus(Status status){ throw new UnsupportedOperationException(); } @Override public Map<String, String> getReadyDependency() { return new HashMap<String, String>(jobStatus.getReadyDependency()); } @Override public void setReadyDependency(Map<String, String> readyDependency){ throw new UnsupportedOperationException(); } @Override public String getHistoryId() { return jobStatus.getHistoryId(); } @Override public void setHistoryId(String historyId) { throw new UnsupportedOperationException(); } } }
{ "content_hash": "72dc3a9875cbf63216f7ec9e9e5fbf83", "timestamp": "", "source": "github", "line_count": 937, "max_line_length": 184, "avg_line_length": 28.464247598719318, "alnum_prop": 0.7262194893329834, "repo_name": "wwzhe/dataworks-zeus", "id": "a632dbdaf474f4d6040f13fdb1ef0aa56c3696b0", "size": "26977", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "schedule/src/main/java/com/taobao/zeus/store/mysql/ReadOnlyGroupManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "156" }, { "name": "CSS", "bytes": "134149" }, { "name": "HTML", "bytes": "57754" }, { "name": "Java", "bytes": "2276733" }, { "name": "JavaScript", "bytes": "737755" }, { "name": "Protocol Buffer", "bytes": "7710" }, { "name": "Ruby", "bytes": "302" }, { "name": "Shell", "bytes": "152" } ], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="th_TH" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Heavycoin</source> <translation>เกี่ยวกับ บิตคอย์น</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Heavycoin&lt;/b&gt; version</source> <translation>&lt;b&gt;บิตคอย์น&lt;b&gt;รุ่น</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The Heavycoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>สมุดรายชื่อ</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>ดับเบิลคลิก เพื่อแก้ไขที่อยู่ หรือชื่อ</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>สร้างที่อยู่ใหม่</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>คัดลอกที่อยู่ที่ถูกเลือกไปยัง คลิปบอร์ดของระบบ</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Heavycoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Heavycoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Heavycoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>ลบ</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Heavycoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>ส่งออกรายชื่อทั้งหมด</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>ส่งออกผิดพลาด</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>ไม่สามารถเขียนไปยังไฟล์ %1</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>ชื่อ</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>ที่อยู่</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(ไม่มีชื่อ)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>ใส่รหัสผ่าน</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>รหัสผา่นใหม่</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>กรุณากรอกรหัสผ่านใหม่อีกครั้งหนึ่ง</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>กระเป๋าสตางค์ที่เข้ารหัส</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>เปิดกระเป๋าสตางค์</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>ถอดรหัสกระเป๋าสตางค์</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>เปลี่ยนรหัสผ่าน</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>กรอกรหัสผ่านเก่าและรหัสผ่านใหม่สำหรับกระเป๋าสตางค์</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>ยืนยันการเข้ารหัสกระเป๋าสตางค์</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>กระเป๋าสตางค์ถูกเข้ารหัสเรียบร้อยแล้ว</translation> </message> <message> <location line="-56"/> <source>Heavycoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your Heavycoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>การเข้ารหัสกระเป๋าสตางค์ผิดพลาด</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>รหัสผ่านที่คุณกรอกไม่ตรงกัน</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Show information about Heavycoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Heavycoin address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for Heavycoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>Heavycoin</source> <translation type="unfinished"/> </message> <message> <location line="-530"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Heavycoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Heavycoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Heavycoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Heavycoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Heavycoin network</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Heavycoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Heavycoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Heavycoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Heavycoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start Heavycoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start Heavycoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the Heavycoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the Heavycoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Heavycoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show Heavycoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Heavycoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Heavycoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start heavycoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the Heavycoin-Qt help message to get a list with possible Heavycoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>Heavycoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Heavycoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the Heavycoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Heavycoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Heavycoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Heavycoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Heavycoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Heavycoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter Heavycoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Heavycoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation>ที่อยู่</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Today</source> <translation>วันนี้</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation>ชื่อ</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>ที่อยู่</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>ส่งออกผิดพลาด</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>ไม่สามารถเขียนไปยังไฟล์ %1</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Heavycoin version</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Send command to -server or bitcoind</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Specify configuration file (default: bitcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Specify pid file (default: bitcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 8333 or testnet: 18333)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 8332 or testnet: 18332)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Heavycoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Heavycoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Heavycoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the Heavycoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Heavycoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Heavycoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Heavycoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
{ "content_hash": "fa31c9f1e66316f3da548a88b2fda5a7", "timestamp": "", "source": "github", "line_count": 2917, "max_line_length": 395, "avg_line_length": 33.15735344532054, "alnum_prop": 0.5855872622001654, "repo_name": "hanxianzhai/hvcoin", "id": "e8d9b8133be0c88fd009567489df869e07f0a627", "size": "97886", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_th_TH.ts", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "91050" }, { "name": "C++", "bytes": "2417482" }, { "name": "CSS", "bytes": "1127" }, { "name": "IDL", "bytes": "13784" }, { "name": "Objective-C++", "bytes": "2656" }, { "name": "Python", "bytes": "69704" }, { "name": "Shell", "bytes": "12718" }, { "name": "TypeScript", "bytes": "5232121" } ], "symlink_target": "" }
The aim of this repository is to support the upcoming book, [Zend Framework 2 for Beginners](https://leanpub.com/zendframework2-for-beginners). It makes as much usage of the respective components of Zend Framework 2 as are required to support the book and the concepts which it attempts to teach. Lifting a bit out of the book, these areas are: ### Core Patterns (including): - Factory - MVC - Observer/Subscriber - Inversion of Control ### Core Concepts (including): - ModuleManager - EventsManager - ServiceManager - Dependency Injection - Modules - Routing - Configuration - Controllers & Actions - Testing - Deployment ### Additional Areas - ZFTool - External Modules - Diagnostics It's not aimed at people who are already proficient with Zend Framework 2, but those new to it, whether transitioning from Zend Framework 1, another framework or those getting in to using frameworks with PHP. ## Getting Started To get started with the project, simply clone it, then in the cloned project directory, run `vagrant up`. The project contains a Vagrant/Puppet virtual machine configuration, configured using [PuPHPet](http://www.puphpet.com). So there's no software to install, other than [VirtualBox](https://www.virtualbox.org/wiki/Downloads) and [Vagrant](http://vagrantup.com/downloads.html). ## Bugs If you find a bug in the code as always, let me know [by creating an issue](https://github.com/settermjd/zf2forbeginners/issues/). If there's a bug in the virtual machine, consider reporting an issue in [the PuPHPet issues tracker](https://github.com/puphpet/puphpet) or reviewing it to see if the issue's already been addressed.
{ "content_hash": "e12eb4453bfb2d9908c642199ee3add6", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 380, "avg_line_length": 42.17948717948718, "alnum_prop": 0.774468085106383, "repo_name": "settermjd/zf2forbeginners", "id": "f4c5725fabe681e0e3664bc01793866b8676189c", "size": "1696", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "711" }, { "name": "CSS", "bytes": "1042" }, { "name": "HTML", "bytes": "21434" }, { "name": "PHP", "bytes": "68877" } ], "symlink_target": "" }
import { IUserDataSyncService, IUserDataSyncLogService, IUserDataSyncResourceEnablementService, IUserDataSyncStoreService } from 'vs/platform/userDataSync/common/userDataSync'; import { Event } from 'vs/base/common/event'; import { IElectronService } from 'vs/platform/electron/electron-sandbox/electron'; import { UserDataAutoSyncService as BaseUserDataAutoSyncService } from 'vs/platform/userDataSync/common/userDataAutoSyncService'; import { IUserDataSyncAccountService } from 'vs/platform/userDataSync/common/userDataSyncAccount'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IUserDataSyncMachinesService } from 'vs/platform/userDataSync/common/userDataSyncMachines'; export class UserDataAutoSyncService extends BaseUserDataAutoSyncService { constructor( @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService, @IUserDataSyncResourceEnablementService userDataSyncResourceEnablementService: IUserDataSyncResourceEnablementService, @IUserDataSyncService userDataSyncService: IUserDataSyncService, @IElectronService electronService: IElectronService, @IUserDataSyncLogService logService: IUserDataSyncLogService, @IUserDataSyncAccountService authTokenService: IUserDataSyncAccountService, @ITelemetryService telemetryService: ITelemetryService, @IUserDataSyncMachinesService userDataSyncMachinesService: IUserDataSyncMachinesService, @IStorageService storageService: IStorageService, @IEnvironmentService environmentService: IEnvironmentService, ) { super(userDataSyncStoreService, userDataSyncResourceEnablementService, userDataSyncService, logService, authTokenService, telemetryService, userDataSyncMachinesService, storageService, environmentService); this._register(Event.debounce<string, string[]>(Event.any<string>( Event.map(electronService.onWindowFocus, () => 'windowFocus'), Event.map(electronService.onWindowOpen, () => 'windowOpen'), ), (last, source) => last ? [...last, source] : [source], 1000)(sources => this.triggerSync(sources, true))); } }
{ "content_hash": "10bcbffde80296de59f0f16a19919dd4", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 207, "avg_line_length": 63.42857142857143, "alnum_prop": 0.8324324324324325, "repo_name": "hoovercj/vscode", "id": "7868c0ebc2e2226eda18cf8bb06b7a112de8956f", "size": "2571", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/vs/platform/userDataSync/electron-browser/userDataAutoSyncService.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5527" }, { "name": "C", "bytes": "818" }, { "name": "C#", "bytes": "1640" }, { "name": "C++", "bytes": "1038" }, { "name": "CSS", "bytes": "429597" }, { "name": "Clojure", "bytes": "1206" }, { "name": "CoffeeScript", "bytes": "590" }, { "name": "F#", "bytes": "634" }, { "name": "Go", "bytes": "628" }, { "name": "Groovy", "bytes": "3928" }, { "name": "HLSL", "bytes": "184" }, { "name": "HTML", "bytes": "28219" }, { "name": "Inno Setup", "bytes": "108702" }, { "name": "Java", "bytes": "599" }, { "name": "JavaScript", "bytes": "839590" }, { "name": "Lua", "bytes": "252" }, { "name": "Makefile", "bytes": "553" }, { "name": "Objective-C", "bytes": "1387" }, { "name": "PHP", "bytes": "998" }, { "name": "Perl", "bytes": "857" }, { "name": "Perl6", "bytes": "1065" }, { "name": "PowerShell", "bytes": "6526" }, { "name": "Python", "bytes": "2119" }, { "name": "R", "bytes": "362" }, { "name": "Ruby", "bytes": "1703" }, { "name": "Rust", "bytes": "532" }, { "name": "ShaderLab", "bytes": "330" }, { "name": "Shell", "bytes": "31357" }, { "name": "Swift", "bytes": "220" }, { "name": "TypeScript", "bytes": "13413255" }, { "name": "Visual Basic", "bytes": "893" } ], "symlink_target": "" }
using System; using System.Data; using System.Data.Common; namespace Mono.Data.Sqlite { public class SqliteDataSourceEnumerator : DbDataSourceEnumerator { public SqliteDataSourceEnumerator () { } public override DataTable GetDataSources () { DataTable dt = new DataTable (); DataColumn col; col = new DataColumn ("ServerName", typeof (string)); dt.Columns.Add (col); col = new DataColumn ("InstanceName", typeof (string)); dt.Columns.Add (col); col = new DataColumn ("IsClustered", typeof (bool)); dt.Columns.Add (col); col = new DataColumn ("Version", typeof (string)); dt.Columns.Add (col); col = new DataColumn ("FactoryName", typeof (string)); dt.Columns.Add (col); DataRow dr = dt.NewRow (); dr [0] = "Sqlite Embedded Database"; dr [1] = "Sqlite Default Instance"; dr [2] = false; dr [3] = "?"; dr [4] = "Mono.Data.Sqlite.SqliteConnectionFactory"; dt.Rows.Add (dr); return dt; } } } #endif
{ "content_hash": "990a3897c0ec3f2a20f530e5f065168c", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 72, "avg_line_length": 24.26086956521739, "alnum_prop": 0.5725806451612904, "repo_name": "anaselhajjaji/MimeKit", "id": "050e2e43af3d05678e72135b8ce99bf07d31f019", "size": "2466", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Mono.Data.Sqlite/SqliteDataSourceEnumerator.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.example.moodly; import android.app.Activity; import android.support.design.widget.FloatingActionButton; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; import android.view.KeyEvent; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.example.moodly.Activities.LoginScreen; import com.example.moodly.Activities.MoodBase; import com.example.moodly.Activities.ViewMood; import com.robotium.solo.Solo; import java.util.Random; /** * Created by tuongmin on 3/16/17. */ /* * Testing Add, Edit, Delete, Filters with Moods *PLEASE NOTE THAT YOU HAVE TO LOGOUT OF THE APPLICATION FOR THE INTENT TESTS TO WORK. */ public class MoodIntentTest extends ActivityInstrumentationTestCase2<LoginScreen> { private Solo solo; public MoodIntentTest() { super(com.example.moodly.Activities.LoginScreen.class); } public void setUp() throws Exception{ solo = new Solo(getInstrumentation(), getActivity()); } public void testStart() throws Exception { Activity activity = getActivity(); } /* * Login to user "Minh" */ public void actionLogin() { solo.assertCurrentActivity("Wrong Activity", LoginScreen.class); solo.enterText((EditText) solo.getView(R.id.userName), "Minh"); solo.clickOnButton("Login"); solo.assertCurrentActivity("Wrong Activities", MoodBase.class); } /* Log out of current user */ public void actionLogOut() { solo.sendKey(solo.MENU); solo.clickOnText("Log Out"); solo.assertCurrentActivity("Wrong Activity", LoginScreen.class); } /* Generate random strinf for test comment */ protected String getRDString() { String CHARS = "abcdefghijklmnopqrstuvwxyz1234567890"; StringBuilder stringBuilder = new StringBuilder(); Random rnd = new Random(); while (stringBuilder.length() < 18) { int index = (int) (rnd.nextFloat() * CHARS.length()); stringBuilder.append(CHARS.charAt(index)); } String Str = stringBuilder.toString(); return Str; } /* Test add mood Anger */ public void test1_AddMood() { actionLogin(); solo.clickOnView((FloatingActionButton) solo.getView(R.id.fab)); solo.assertCurrentActivity("Wrong Activities", ViewMood.class); Spinner emoij = (Spinner) solo.getView(R.id.spinner_emotion); solo.clickOnView(emoij); solo.clickOnText("Anger"); solo.clickOnView((EditText) solo.getView(R.id.view_date)); solo.clickOnText("OK"); solo.clickOnText("OK"); solo.enterText((EditText) solo.getView(R.id.view_reason), "test reason"); solo.clickOnText("Save Mood"); solo.assertCurrentActivity("Wrong Activity", MoodBase.class); assertEquals(solo.searchText("Anger"), true); actionLogOut(); } /* Test filter mood Add a Shame mood Filter it out and check if shame is still visible */ public void test2_FilterByMood () { actionLogin(); solo.clickOnView((FloatingActionButton) solo.getView(R.id.fab)); solo.assertCurrentActivity("Wrong Activities", ViewMood.class); Spinner emoij = (Spinner) solo.getView(R.id.spinner_emotion); solo.clickOnView(emoij); solo.clickOnText("Shame"); solo.clickOnView((EditText) solo.getView(R.id.view_date)); solo.clickOnText("OK"); solo.clickOnText("OK"); solo.enterText((EditText) solo.getView(R.id.view_reason), "test reason"); solo.clickOnText("Save Mood"); solo.clickOnView((FloatingActionButton) solo.getView(R.id.filterButton)); solo.clickOnText("Anger"); solo.clickOnText("OK"); solo.clickOnText("No"); solo.clickOnText("No"); assertFalse(solo.searchText("Shame")); solo.clickOnView((FloatingActionButton) solo.getView(R.id.refreshButton)); solo.clickLongOnText("Shame"); solo.clickOnText("Delete"); actionLogOut(); } /* Add a mood with random reason generated Filter it and chekc if it is visible */ public void test2_1_FilterByText () { actionLogin(); solo.clickOnView((FloatingActionButton) solo.getView(R.id.fab)); solo.assertCurrentActivity("Wrong Activities", ViewMood.class); Spinner emoij = (Spinner) solo.getView(R.id.spinner_emotion); solo.clickOnView(emoij); solo.clickOnText("Shame"); solo.clickOnView((EditText) solo.getView(R.id.view_date)); solo.clickOnText("OK"); solo.clickOnText("OK"); String reason = getRDString(); solo.enterText((EditText) solo.getView(R.id.view_reason), reason); solo.clickOnText("Save Mood"); solo.clickOnView((FloatingActionButton) solo.getView(R.id.filterButton)); solo.clickOnText("OK"); char[] ch_array = reason.toCharArray(); for(int i=0;i<ch_array.length;i++) { solo.sendKey( android_keycode(ch_array[i]) ); } solo.clickOnText("Yes"); solo.clickOnText("No"); assertTrue(solo.searchText("Shame")); solo.clickOnView((FloatingActionButton) solo.getView(R.id.refreshButton)); solo.clickLongOnText("Shame"); solo.clickOnText("Delete"); actionLogOut(); } /* Filter by date A mood is already added dated back few months Filtering by date would hide the mood */ public void test2_2_FilterByDate () { actionLogin(); solo.clickOnView((FloatingActionButton) solo.getView(R.id.fab)); solo.assertCurrentActivity("Wrong Activities", ViewMood.class); Spinner emoij = (Spinner) solo.getView(R.id.spinner_emotion); solo.clickOnView(emoij); solo.clickOnText("Shame"); solo.clearEditText((EditText) solo.getView(R.id.view_date)); solo.clickOnText("OK"); solo.clickOnText("OK"); solo.clickOnText("Save Mood"); solo.clickOnView((FloatingActionButton) solo.getView(R.id.filterButton)); solo.clickOnText("OK"); solo.clickOnText("No"); solo.clickOnText("Yes"); assertFalse(solo.searchText("Surprise")); assertTrue(solo.searchText("Shame")); solo.clickOnView((FloatingActionButton) solo.getView(R.id.refreshButton)); solo.clickLongOnText("Shame"); solo.clickOnText("Delete"); actionLogOut(); } /* Edit mood added in test1 to a Sad Mood */ public void test3_EditMood() { actionLogin(); solo.clickLongInList(0); solo.clickOnText("View/Edit"); solo.assertCurrentActivity("Wrong Activity", ViewMood.class); solo.clickOnView((Spinner) solo.getView(R.id.spinner_emotion)); solo.clickOnText("Sad"); solo.clickOnText("Save Mood"); solo.assertCurrentActivity("Wrong Activity", MoodBase.class); assertEquals(solo.searchText("Anger"), false); assertEquals(solo.searchText("Sad"), true); actionLogOut(); } /* Delete Mood added in test1 */ public void test4_DeleteMood() { actionLogin(); solo.clickLongInList(0); solo.clickOnText("Delete"); assertEquals(solo.searchText("Sad"), false); actionLogOut(); } /* Test adding comment to a mood of people following Add a comment of random generated string Check if it's in the comments */ public void test5_AddComment() { actionLogin(); solo.clickOnText("Following"); solo.clickLongOnText("haha"); solo.clickOnText("View"); solo.clickOnText("Add Comment"); String comment = getRDString(); char[] ch_array = comment.toCharArray(); for(int i=0;i<ch_array.length;i++) { solo.sendKey( android_keycode(ch_array[i]) ); } solo.clickOnText("OK"); solo.clickOnText("View Comments"); assertTrue(solo.searchText(comment)); solo.goBack(); solo.goBack(); actionLogOut(); } /* Decode string to ascii to input in pop up textEdit */ public int android_keycode(char ch) { int keycode = ch;//String.valueOf(ch).codePointAt(0); Log.v("T","in fun : "+ch+" : "+keycode + ""); if(keycode>=97 && keycode <=122) { Log.v("T","atoz : "+ch+" : "+keycode + " : " + (keycode-68)); return keycode-68; } else if(keycode>=65 && keycode <=90) { Log.v("T","atoz : "+ch+" : "+keycode + " : " + (keycode-36)); return keycode-36; } else if(keycode>=48 && keycode <=57) { Log.v("T","0to9"+ch+" : "+keycode + " : " + (keycode-41)); return keycode-41; } else if(keycode==64) { Log.v("T","@"+ch+" : "+keycode + " : " + "77"); return KeyEvent.KEYCODE_AT; } else if(ch=='.') { Log.v("T","DOT "+ch+" : "+keycode + " : " + "158"); return KeyEvent.KEYCODE_PERIOD; } else if(ch==',') { Log.v("T","comma "+ch+" : "+keycode + " : " + "55"); return KeyEvent.KEYCODE_COMMA; } return 62; } }
{ "content_hash": "0495ce46b86ce6f72b58e229b38f1d98", "timestamp": "", "source": "github", "line_count": 322, "max_line_length": 85, "avg_line_length": 29.350931677018632, "alnum_prop": 0.605015342291821, "repo_name": "CMPUT301W17T20/Harambe", "id": "13eb5e0ff97c310031e363f2426fdeee49de9afa", "size": "9451", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/src/androidTest/java/com/example/moodly/MoodIntentTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12842" }, { "name": "HTML", "bytes": "4339162" }, { "name": "Java", "bytes": "221783" }, { "name": "JavaScript", "bytes": "827" } ], "symlink_target": "" }
package sk import ( "time" "github.com/rickar/cal/v2" "github.com/rickar/cal/v2/aa" ) var ( // RepublicDay represents Republic Day on 1-Jan RepublicDay = aa.NewYear.Clone(&cal.Holiday{Name: "Deň vzniku Slovenskej republiky", Type: cal.ObservancePublic}) // Epiphany represents Epiphany on 6-Jan Epiphany = aa.Epiphany.Clone(&cal.Holiday{Name: "Zjavenie Pána", Type: cal.ObservancePublic}) // GoodFriday represents Good Friday - two days before Easter GoodFriday = aa.GoodFriday.Clone(&cal.Holiday{Name: "Veľkonočný piatok", Type: cal.ObservancePublic}) // EasterMonday represents Easter Monday - the day after Easter EasterMonday = aa.EasterMonday.Clone(&cal.Holiday{Name: "Veľkonočný pondelok", Type: cal.ObservancePublic}) // LabourDay represents Labour Day on 1-May LabourDay = aa.WorkersDay.Clone(&cal.Holiday{Name: "Sviatok práce", Type: cal.ObservancePublic}) // Liberation represents Liberation Day on 8-May Liberation = &cal.Holiday{ Name: "Deň víťazstva nad fašizmom", Type: cal.ObservancePublic, Month: time.May, Day: 8, Func: cal.CalcDayOfMonth, } // SaintsCyril represents St. Cyril and Methodius Day on 5-Jul SaintsCyril = &cal.Holiday{ Name: "Sviatok svätého Cyrila a Metoda", Type: cal.ObservancePublic, Month: time.July, Day: 5, Func: cal.CalcDayOfMonth, } // SNP represents Slovak National Uprising Anniversary on 29-Aug SNP = &cal.Holiday{ Name: "Výročie Slovenského národného povstania", Type: cal.ObservancePublic, Month: time.August, Day: 29, Func: cal.CalcDayOfMonth, } // Constitution represents Constitution Day on 1-Sep Constitution = &cal.Holiday{ Name: "Deň Ústavy Slovenskej republiky", Type: cal.ObservancePublic, Month: time.September, Day: 1, Func: cal.CalcDayOfMonth, } // LadyOfSorrows represents Day of Our Lady of the Seven Sorrows on 15-Sep LadyOfSorrows = &cal.Holiday{ Name: "Sviatok Panny Márie Sedembolestnej, patrónky Slovenska", Type: cal.ObservancePublic, Month: time.September, Day: 15, Func: cal.CalcDayOfMonth, } // AllSaints represents All Saints' Day on 1-Nov AllSaints = aa.AllSaintsDay.Clone(&cal.Holiday{Name: "Sviatok všetkých svätých", Type: cal.ObservancePublic}) // Freedom represents Struggle for Freedom and Democracy Day on 17-Nov Freedom = &cal.Holiday{ Name: "Deň boja za slobodu a demokraciu", Type: cal.ObservancePublic, Month: time.November, Day: 17, Func: cal.CalcDayOfMonth, } // ChristmasEve represents Christmas Eve on 24-Dec ChristmasEve = &cal.Holiday{ Name: "Štedrý deň", Type: cal.ObservancePublic, Month: time.December, Day: 24, Func: cal.CalcDayOfMonth, } // ChristmasDay represents Christmas Day on 25-Dec ChristmasDay = aa.ChristmasDay.Clone(&cal.Holiday{Name: "Prvý sviatok vianočný", Type: cal.ObservancePublic}) // SaintStephen represents Boxing Day on 26-Dec SaintStephen = aa.ChristmasDay2.Clone(&cal.Holiday{Name: "Druhý sviatok vianočný", Type: cal.ObservancePublic}) // Holidays provides a list of the standard national holidays Holidays = []*cal.Holiday{ RepublicDay, Epiphany, GoodFriday, EasterMonday, LabourDay, Liberation, SaintsCyril, SNP, Constitution, LadyOfSorrows, AllSaints, Freedom, ChristmasEve, ChristmasDay, SaintStephen, } )
{ "content_hash": "6b3037af134a08a188e4b05e5f739c54", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 114, "avg_line_length": 28.384615384615383, "alnum_prop": 0.7299006323396567, "repo_name": "rickar/cal", "id": "bfd0e0ee674d4752130883c2c0152b5368429c7e", "size": "3483", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v2/sk/sk_holidays.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Go", "bytes": "408341" } ], "symlink_target": "" }
import { set, del, nextTick, mergeOptions, classify, toArray, commonTagRE, warn, isPlainObject } from '../../util/index' import config from '../../config' import * as util from '../../util/index' import * as compiler from '../../compiler/index' import * as path from '../../parsers/path' import * as text from '../../parsers/text' import * as template from '../../parsers/template' import * as directive from '../../parsers/directive' import * as expression from '../../parsers/expression' import FragmentFactory from '../../fragment/factory' import internalDirectives from '../../directives/internal/index' export default function (Vue) { /** * Expose useful internals */ Vue.util = util Vue.config = config Vue.set = set Vue.delete = del Vue.nextTick = nextTick /** * The following are exposed for advanced usage / plugins */ Vue.compiler = compiler Vue.FragmentFactory = FragmentFactory Vue.internalDirectives = internalDirectives Vue.parsers = { path, text, template, directive, expression } /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0 var cid = 1 /** * Class inheritance * * @param {Object} extendOptions */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {} var Super = this var isFirstExtend = Super.cid === 0 if (isFirstExtend && extendOptions._Ctor) { return extendOptions._Ctor } var name = extendOptions.name || Super.options.name var Sub = createClass(name || 'VueComponent') Sub.prototype = Object.create(Super.prototype) Sub.prototype.constructor = Sub Sub.cid = cid++ Sub.options = mergeOptions( Super.options, extendOptions ) Sub['super'] = Super // allow further extension Sub.extend = Super.extend // create asset registers, so extended classes // can have their private assets too. config._assetTypes.forEach(function (type) { Sub[type] = Super[type] }) // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub } // cache constructor if (isFirstExtend) { extendOptions._Ctor = Sub } return Sub } /** * A function that returns a sub-class constructor with the * given name. This gives us much nicer output when * logging instances in the console. * * @param {String} name * @return {Function} */ function createClass (name) { return new Function( 'return function ' + classify(name) + ' (options) { this._init(options) }' )() } /** * Plugin system * * @param {Object} plugin */ Vue.use = function (plugin) { /* istanbul ignore if */ if (plugin.installed) { return } // additional parameters var args = toArray(arguments, 1) args.unshift(this) if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args) } else { plugin.apply(null, args) } plugin.installed = true return this } /** * Apply a global mixin by merging it into the default * options. */ Vue.mixin = function (mixin) { Vue.options = mergeOptions(Vue.options, mixin) } /** * Create asset registration methods with the following * signature: * * @param {String} id * @param {*} definition */ config._assetTypes.forEach(function (type) { Vue[type] = function (id, definition) { if (!definition) { return this.options[type + 's'][id] } else { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if (type === 'component' && commonTagRE.test(id)) { warn( 'Do not use built-in HTML elements as component ' + 'id: ' + id ) } } if ( type === 'component' && isPlainObject(definition) ) { definition.name = id definition = Vue.extend(definition) } this.options[type + 's'][id] = definition return definition } } }) }
{ "content_hash": "e99ec61aa960cb279954aa6e2ac0c508", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 65, "avg_line_length": 23.256830601092897, "alnum_prop": 0.6007988721804511, "repo_name": "docit/core", "id": "f05a1eaea24b5f304374aff5e6a7d65dc8ebc36c", "size": "4256", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "resources/assets/bower_components/vue/src/instance/api/global.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "256140" }, { "name": "JavaScript", "bytes": "1243869" }, { "name": "PHP", "bytes": "96861" } ], "symlink_target": "" }
package echosign.api.clientv20.dto20; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the echosign.api.clientv20.dto20 package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: echosign.api.clientv20.dto20 * */ public ObjectFactory() { } /** * Create an instance of {@link DocumentInfoList } * */ public DocumentInfoList createDocumentInfoList() { return new DocumentInfoList(); } /** * Create an instance of {@link DocumentEventsForUserOptions } * */ public DocumentEventsForUserOptions createDocumentEventsForUserOptions() { return new DocumentEventsForUserOptions(); } /** * Create an instance of {@link GetDocumentEventsForUserResult } * */ public GetDocumentEventsForUserResult createGetDocumentEventsForUserResult() { return new GetDocumentEventsForUserResult(); } /** * Create an instance of {@link DocumentInfo } * */ public DocumentInfo createDocumentInfo() { return new DocumentInfo(); } /** * Create an instance of {@link DocumentEventForUser } * */ public DocumentEventForUser createDocumentEventForUser() { return new DocumentEventForUser(); } /** * Create an instance of {@link ArrayOfDocumentInfo } * */ public ArrayOfDocumentInfo createArrayOfDocumentInfo() { return new ArrayOfDocumentInfo(); } /** * Create an instance of {@link PostSignOptions } * */ public PostSignOptions createPostSignOptions() { return new PostSignOptions(); } /** * Create an instance of {@link SendThroughWebOptions } * */ public SendThroughWebOptions createSendThroughWebOptions() { return new SendThroughWebOptions(); } /** * Create an instance of {@link ArrayOfDocumentEventForUser } * */ public ArrayOfDocumentEventForUser createArrayOfDocumentEventForUser() { return new ArrayOfDocumentEventForUser(); } /** * Create an instance of {@link FileUploadOptions } * */ public FileUploadOptions createFileUploadOptions() { return new FileUploadOptions(); } /** * Create an instance of {@link ArrayOfAgreementEventType } * */ public ArrayOfAgreementEventType createArrayOfAgreementEventType() { return new ArrayOfAgreementEventType(); } /** * Create an instance of {@link ArrayOfDocumentHistoryEvent } * */ public ArrayOfDocumentHistoryEvent createArrayOfDocumentHistoryEvent() { return new ArrayOfDocumentHistoryEvent(); } /** * Create an instance of {@link DocumentHistoryEvent } * */ public DocumentHistoryEvent createDocumentHistoryEvent() { return new DocumentHistoryEvent(); } }
{ "content_hash": "1b6ee843dc049a5f4f3cc1de0c0dacc9", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 142, "avg_line_length": 25.91176470588235, "alnum_prop": 0.6634506242905789, "repo_name": "OBHITA/Consent2Share", "id": "a5e99b745e819c2fd6090a8376fef700c042b49f", "size": "3524", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ThirdParty/adobe-echosign-api/src/main/java/echosign/api/clientv20/dto20/ObjectFactory.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "491834" }, { "name": "HTML", "bytes": "2415468" }, { "name": "Java", "bytes": "8076505" }, { "name": "JavaScript", "bytes": "659769" }, { "name": "Ruby", "bytes": "1504" }, { "name": "XSLT", "bytes": "341926" } ], "symlink_target": "" }
package org.nlpcn.es4sql.query.join; import java.util.AbstractMap; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.elasticsearch.client.Client; import org.nlpcn.es4sql.domain.Condition; import org.nlpcn.es4sql.domain.Field; import org.nlpcn.es4sql.domain.JoinSelect; import org.nlpcn.es4sql.domain.Where; import org.nlpcn.es4sql.domain.hints.Hint; import org.nlpcn.es4sql.domain.hints.HintType; import org.nlpcn.es4sql.exception.SqlParseException; /** * Created by Eliran on 22/8/2015. */ public class ESHashJoinQueryAction extends ESJoinQueryAction { public ESHashJoinQueryAction(Client client,JoinSelect joinSelect) { super(client, joinSelect); } @Override protected void fillSpecificRequestBuilder(JoinRequestBuilder requestBuilder) throws SqlParseException { String t1Alias = joinSelect.getFirstTable().getAlias(); String t2Alias = joinSelect.getSecondTable().getAlias(); List<List<Map.Entry<Field, Field>>> comparisonFields = getComparisonFields(t1Alias, t2Alias,joinSelect.getConnectedWhere()); ((HashJoinElasticRequestBuilder) requestBuilder).setT1ToT2FieldsComparison(comparisonFields); } @Override protected JoinRequestBuilder createSpecificBuilder() { return new HashJoinElasticRequestBuilder(); } @Override protected void updateRequestWithHints(JoinRequestBuilder requestBuilder) { super.updateRequestWithHints(requestBuilder); for(Hint hint : joinSelect.getHints()){ if(hint.getType() == HintType.HASH_WITH_TERMS_FILTER) { ((HashJoinElasticRequestBuilder) requestBuilder).setUseTermFiltersOptimization(true); } } } private List<Map.Entry<Field, Field>> getComparisonFields(String t1Alias, String t2Alias, List<Condition> connectedConditions) throws SqlParseException { List<Map.Entry<Field,Field>> comparisonFields = new ArrayList<>(); for(Condition condition : connectedConditions){ if(condition.getOpear() != Condition.OPEAR.EQ){ throw new SqlParseException(String.format("HashJoin should only be with EQ conditions, got:%s on condition:%s", condition.getOpear().name(), condition.toString())); } String firstField = condition.getName(); String secondField = condition.getValue().toString(); Field t1Field,t2Field; if(firstField.startsWith(t1Alias)){ t1Field = new Field(removeAlias(firstField,t1Alias),null); t2Field = new Field(removeAlias(secondField,t2Alias),null); } else { t1Field = new Field(removeAlias(secondField,t1Alias),null); t2Field = new Field(removeAlias(firstField,t2Alias),null); } comparisonFields.add(new AbstractMap.SimpleEntry<Field, Field>(t1Field, t2Field)); } return comparisonFields; } private List<List<Map.Entry<Field, Field>>> getComparisonFields(String t1Alias, String t2Alias, Where connectedWhere) throws SqlParseException { List<List<Map.Entry<Field,Field>>> comparisonFields = new ArrayList<>(); //where is AND with lots of conditions. if(connectedWhere == null) return comparisonFields; boolean allAnds = true; for(Where innerWhere : connectedWhere.getWheres()){ if(innerWhere.getConn() == Where.CONN.OR) { allAnds = false; break; } } if(allAnds) { List<Map.Entry<Field, Field>> innerComparisonFields = getComparisonFieldsFromWhere(t1Alias, t2Alias, connectedWhere); comparisonFields.add(innerComparisonFields); } else { for(Where innerWhere : connectedWhere.getWheres()){ comparisonFields.add(getComparisonFieldsFromWhere(t1Alias,t2Alias,innerWhere)); } } return comparisonFields; } private List<Map.Entry<Field, Field>> getComparisonFieldsFromWhere(String t1Alias, String t2Alias, Where where) throws SqlParseException { List<Condition> conditions = new ArrayList<>(); if(where instanceof Condition) conditions.add((Condition) where); else { for (Where innerWhere : where.getWheres()) { if (!(innerWhere instanceof Condition)) throw new SqlParseException("if connectedCondition is AND than all inner wheres should be Conditions "); conditions.add((Condition) innerWhere); } } return getComparisonFields(t1Alias, t2Alias, conditions); } private String removeAlias(String field, String alias) { return field.replace(alias+".",""); } }
{ "content_hash": "508228601d3672ba4cd2de1f8c7d5d16", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 180, "avg_line_length": 41.779661016949156, "alnum_prop": 0.6539553752535497, "repo_name": "visionsky1986/elasticsearch-sql", "id": "e2d8f3eaffc64e226f4d0258273d668475fb74de", "size": "4930", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/nlpcn/es4sql/query/join/ESHashJoinQueryAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4470" }, { "name": "HTML", "bytes": "12508" }, { "name": "Java", "bytes": "885126" }, { "name": "JavaScript", "bytes": "41456" } ], "symlink_target": "" }
package test.github1461; import org.testng.TestNG; import org.testng.annotations.Test; import org.testng.log4testng.Logger; /** * This class reproduces a memory leak problem when running TestNG tests. The same (memory behavior * will be shown when running this test as normal TestNG test (e.g. using Intellij) * * <p>See https://github.com/cbeust/testng/issues/1461 */ public class MemoryLeakTestNg { private static final Logger log = Logger.getLogger(MemoryLeakTestNg.class); @Test(timeOut = 10_000) public void testMemoryLeak() throws Exception { // we run the test programmatically runTest(); // lets wait for garbage collection waitForAllObjectsDestructed(); } private static void waitForAllObjectsDestructed() throws InterruptedException { while (true) { log.debug("waiting for clean up..."); // enforce a full gc System.gc(); // check if there are still instances of our test class if (MyTestClassWithGlobalReferenceCounterSample.currentNumberOfMyTestObjects == 0) { // if we reach this point, all test instances are gone, // ... however this never happens ... break; } // let's wait 1 seconds and try again ... Thread.sleep(1_000); log.debug( "[" + MyTestClassWithGlobalReferenceCounterSample.currentNumberOfMyTestObjects + "] test object(s) still exist."); } } private static void runTest() { // create TestNG class TestNG testng = new TestNG() { @Override @SuppressWarnings("deprecation") protected void finalize() { // it seems that this object will never be finalized !!! log.debug("TestNG finalized"); } }; // and set a test (which also will never be finalized ... see later) testng.setTestClasses( new Class[] { MyTestClassWithGlobalReferenceCounterSample.class, }); // lets run the test testng.run(); // At this point the test run through and we expect both instances // - testng and // - the test object of type (MyTest) // will be garbage collected when leaving this method // ... } }
{ "content_hash": "e6264a75af703c9244e13908c4feebae", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 99, "avg_line_length": 30.04054054054054, "alnum_prop": 0.6446243814664867, "repo_name": "krmahadevan/testng", "id": "d919692fd14373f54b0e7471361dc1fd79e3bc00", "size": "2223", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "testng-core/src/test/java/test/github1461/MemoryLeakTestNg.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "711" }, { "name": "CSS", "bytes": "12708" }, { "name": "Groovy", "bytes": "3285" }, { "name": "HTML", "bytes": "9063" }, { "name": "Java", "bytes": "3881030" }, { "name": "JavaScript", "bytes": "17303" }, { "name": "Kotlin", "bytes": "66354" }, { "name": "Shell", "bytes": "1458" } ], "symlink_target": "" }
<?php /** * wallee SDK * * This library allows to interact with the wallee payment service. * * 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. */ namespace Wallee\Sdk\Model; use \ArrayAccess; use \Wallee\Sdk\ObjectSerializer; /** * SubscriptionComponentReferenceConfiguration model * * @category Class * @description The component reference configuration adjusts the product component for a particular subscription. * @package Wallee\Sdk * @author customweb GmbH * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 */ class SubscriptionComponentReferenceConfiguration implements ModelInterface, ArrayAccess { const DISCRIMINATOR = null; /** * The original name of the model. * * @var string */ protected static $swaggerModelName = 'SubscriptionComponentReferenceConfiguration'; /** * Array of property to type mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerTypes = [ 'product_component_reference_id' => 'int', 'quantity' => 'float' ]; /** * Array of property to format mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerFormats = [ 'product_component_reference_id' => 'int64', 'quantity' => null ]; /** * Array of attributes where the key is the local name, * and the value is the original name * * @var string[] */ protected static $attributeMap = [ 'product_component_reference_id' => 'productComponentReferenceId', 'quantity' => 'quantity' ]; /** * Array of attributes to setter functions (for deserialization of responses) * * @var string[] */ protected static $setters = [ 'product_component_reference_id' => 'setProductComponentReferenceId', 'quantity' => 'setQuantity' ]; /** * Array of attributes to getter functions (for serialization of requests) * * @var string[] */ protected static $getters = [ 'product_component_reference_id' => 'getProductComponentReferenceId', 'quantity' => 'getQuantity' ]; /** * Associative array for storing property values * * @var mixed[] */ protected $container = []; /** * Constructor * * @param mixed[] $data Associated array of property values * initializing the model */ public function __construct(array $data = null) { $this->container['product_component_reference_id'] = isset($data['product_component_reference_id']) ? $data['product_component_reference_id'] : null; $this->container['quantity'] = isset($data['quantity']) ? $data['quantity'] : null; } /** * Show all the invalid properties with reasons. * * @return array invalid properties with reasons */ public function listInvalidProperties() { $invalidProperties = []; return $invalidProperties; } /** * Array of property to type mappings. Used for (de)serialization * * @return array */ public static function swaggerTypes() { return self::$swaggerTypes; } /** * Array of property to format mappings. Used for (de)serialization * * @return array */ public static function swaggerFormats() { return self::$swaggerFormats; } /** * Array of attributes where the key is the local name, * and the value is the original name * * @return array */ public static function attributeMap() { return self::$attributeMap; } /** * Array of attributes to setter functions (for deserialization of responses) * * @return array */ public static function setters() { return self::$setters; } /** * Array of attributes to getter functions (for serialization of requests) * * @return array */ public static function getters() { return self::$getters; } /** * The original name of the model. * * @return string */ public function getModelName() { return self::$swaggerModelName; } /** * Validate all the properties in the model * return true if all passed * * @return bool True if all properties are valid */ public function valid() { return count($this->listInvalidProperties()) === 0; } /** * Gets product_component_reference_id * * @return int */ public function getProductComponentReferenceId() { return $this->container['product_component_reference_id']; } /** * Sets product_component_reference_id * * @param int $product_component_reference_id * * @return $this */ public function setProductComponentReferenceId($product_component_reference_id) { $this->container['product_component_reference_id'] = $product_component_reference_id; return $this; } /** * Gets quantity * * @return float */ public function getQuantity() { return $this->container['quantity']; } /** * Sets quantity * * @param float $quantity * * @return $this */ public function setQuantity($quantity) { $this->container['quantity'] = $quantity; return $this; } /** * Returns true if offset exists. False otherwise. * * @param integer $offset Offset * * @return boolean */ #[\ReturnTypeWillChange] public function offsetExists($offset) { return isset($this->container[$offset]); } /** * Gets offset. * * @param integer $offset Offset * * @return mixed */ #[\ReturnTypeWillChange] public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** * Sets value based on offset. * * @param integer $offset Offset * @param mixed $value Value to be set * * @return void */ #[\ReturnTypeWillChange] public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } /** * Unsets offset. * * @param integer $offset Offset * * @return void */ #[\ReturnTypeWillChange] public function offsetUnset($offset) { unset($this->container[$offset]); } /** * Gets the string presentation of the object * * @return string */ public function __toString() { if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode( ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT ); } return json_encode(ObjectSerializer::sanitizeForSerialization($this)); } }
{ "content_hash": "86fb5dec4e4ee4cb45fdee24e773daa7", "timestamp": "", "source": "github", "line_count": 334, "max_line_length": 157, "avg_line_length": 23.18562874251497, "alnum_prop": 0.5856146694214877, "repo_name": "wallee-payment/wallee-php-sdk", "id": "a7571b6f2bf445d964bd409521cc00cd70ea4415", "size": "7744", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Model/SubscriptionComponentReferenceConfiguration.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "2580524" } ], "symlink_target": "" }
'use strict'; module.exports = function(driver, connectorSpec) { connectorSpec.shouldBehaveLikeMusicSite(driver, { url: 'https://zenplayer.audio/?v=03O2yKUgrKw' }); };
{ "content_hash": "b3d2f4bce9b11737ba71f84e778f27ef", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 50, "avg_line_length": 24.714285714285715, "alnum_prop": 0.7341040462427746, "repo_name": "Paszt/web-scrobbler", "id": "e081e83779af3ea7afaf7156d0dbae2d7fbfd3f2", "size": "173", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/connectors/zenplayer.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3318" }, { "name": "HTML", "bytes": "17242" }, { "name": "JavaScript", "bytes": "430988" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <DocSetNodes version="1.0"> <TOC> <Node type="folder"> <Name>SSPullToRefresh 1.0.2</Name> <Path>index.html</Path> <Subnodes> <Node type="folder"> <Name>Classes</Name> <Path>index.html</Path> <Subnodes> <NodeRef refid="1"/> <NodeRef refid="2"/> <NodeRef refid="3"/> </Subnodes> </Node> <Node type="folder"> <Name>Protocols</Name> <Path>index.html</Path> <Subnodes> <NodeRef refid="4"/> <NodeRef refid="5"/> </Subnodes> </Node> </Subnodes> </Node> </TOC> <Library> <Node id="1"> <Name>SSPullToRefreshDefaultContentView</Name> <Path>Classes/SSPullToRefreshDefaultContentView.html</Path> </Node> <Node id="2"> <Name>SSPullToRefreshSimpleContentView</Name> <Path>Classes/SSPullToRefreshSimpleContentView.html</Path> </Node> <Node id="3"> <Name>SSPullToRefreshView</Name> <Path>Classes/SSPullToRefreshView.html</Path> </Node> <Node id="4"> <Name>SSPullToRefreshContentView</Name> <Path>Protocols/SSPullToRefreshContentView.html</Path> </Node> <Node id="5"> <Name>SSPullToRefreshViewDelegate</Name> <Path>Protocols/SSPullToRefreshViewDelegate.html</Path> </Node> </Library> </DocSetNodes>
{ "content_hash": "14de5d5cfed9d863945dc8cfe705b541", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 62, "avg_line_length": 22.258064516129032, "alnum_prop": 0.5934782608695652, "repo_name": "City-Outdoors/City-Outdoors-iOS", "id": "3476fe28a62de3f05e188acad11c0d399c25e998", "size": "1380", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pods/Documentation/SSPullToRefresh/docset/Contents/Resources/Nodes.xml", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.util.gotoByName; import com.intellij.ide.IdeBundle; import com.intellij.ide.actions.GotoFileItemProvider; import com.intellij.ide.actions.NonProjectScopeDisablerEP; import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.PsiElementListCellRenderer; import com.intellij.navigation.ChooseByNameContributor; import com.intellij.navigation.NavigationItem; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileTypes.DirectoryFileType; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.NlsSafe; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileSystemItem; import com.intellij.psi.codeStyle.MinusculeMatcher; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.ui.IdeUICustomization; import com.intellij.util.PlatformIcons; import com.intellij.util.containers.JBIterable; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Collection; import java.util.Comparator; /** * Model for "Go to | File" action */ public class GotoFileModel extends FilteringGotoByModel<FileTypeRef> implements DumbAware, Comparator<Object> { private final int myMaxSize; public GotoFileModel(@NotNull Project project) { super(project, ChooseByNameContributor.FILE_EP_NAME.getExtensionList()); Application application = ApplicationManager.getApplication(); myMaxSize = (application.isUnitTestMode() || application.isHeadlessEnvironment()) ? Integer.MAX_VALUE : WindowManagerEx.getInstanceEx().getFrame(project).getSize().width; } public boolean isSlashlessMatchingEnabled() { return true; } @NotNull @Override public ChooseByNameItemProvider getItemProvider(@Nullable PsiElement context) { for (GotoFileCustomizer customizer : GotoFileCustomizer.EP_NAME.getExtensionList()) { GotoFileItemProvider provider = customizer.createItemProvider(myProject, context, this); if (provider != null) return provider; } return new GotoFileItemProvider(myProject, context, this); } @Override protected boolean acceptItem(final NavigationItem item) { if (item instanceof PsiFile) { final PsiFile file = (PsiFile)item; final Collection<FileTypeRef> types = getFilterItems(); // if language substitutors are used, PsiFile.getFileType() can be different from // PsiFile.getVirtualFile().getFileType() if (types != null) { if (types.contains(FileTypeRef.forFileType(file.getFileType()))) return true; VirtualFile vFile = file.getVirtualFile(); return vFile != null && types.contains(FileTypeRef.forFileType(vFile.getFileType())); } return true; } else if (item instanceof PsiDirectory) { final Collection<FileTypeRef> types = getFilterItems(); if (types != null) return types.contains(DIRECTORY_FILE_TYPE_REF); return true; } else { return super.acceptItem(item); } } @Nullable @Override protected FileTypeRef filterValueFor(NavigationItem item) { return item instanceof PsiFile ? FileTypeRef.forFileType(((PsiFile) item).getFileType()) : null; } @Override public String getPromptText() { return IdeBundle.message("prompt.gotofile.enter.file.name"); } @Override public String getCheckBoxName() { if (NonProjectScopeDisablerEP.EP_NAME.getExtensionList().stream().anyMatch(ep -> ep.disable)) { return null; } return IdeUICustomization.getInstance().projectMessage("checkbox.include.non.project.files"); } @NotNull @Override public String getNotInMessage() { return ""; } @NotNull @Override public String getNotFoundMessage() { return IdeBundle.message("label.no.files.found"); } @Override public boolean loadInitialCheckBoxState() { PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(myProject); return propertiesComponent.isTrueValue("GoToClass.toSaveIncludeLibraries") && propertiesComponent.isTrueValue("GoToFile.includeJavaFiles"); } @Override public void saveInitialCheckBoxState(boolean state) { PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(myProject); if (propertiesComponent.isTrueValue("GoToClass.toSaveIncludeLibraries")) { propertiesComponent.setValue("GoToFile.includeJavaFiles", Boolean.toString(state)); } } @NotNull @Override public PsiElementListCellRenderer getListCellRenderer() { return new GotoFileCellRenderer(myMaxSize) { @NotNull @Override public ItemMatchers getItemMatchers(@NotNull JList list, @NotNull Object value) { ItemMatchers defaultMatchers = super.getItemMatchers(list, value); if (!(value instanceof PsiFileSystemItem)) return defaultMatchers; return convertToFileItemMatchers(defaultMatchers, (PsiFileSystemItem) value, GotoFileModel.this); } }; } @Override @Nullable public String getFullName(@NotNull final Object element) { return element instanceof PsiFileSystemItem ? getFullName(((PsiFileSystemItem)element).getVirtualFile()) : getElementName(element); } @Nullable public String getFullName(@NotNull VirtualFile file) { VirtualFile root = getTopLevelRoot(file); return root != null ? GotoFileCellRenderer.getRelativePathFromRoot(file, root) : GotoFileCellRenderer.getRelativePath(file, myProject); } @Nullable public VirtualFile getTopLevelRoot(@NotNull VirtualFile file) { VirtualFile root = getContentRoot(file); return root == null ? null : JBIterable.generate(root, r -> getContentRoot(r.getParent())).last(); } private VirtualFile getContentRoot(@Nullable VirtualFile file) { return file == null ? null : GotoFileCellRenderer.getAnyRoot(file, myProject); } @Override public String @NotNull [] getSeparators() { return new String[] {"/", "\\"}; } @Override public String getHelpId() { return "procedures.navigating.goto.class"; } @Override public boolean willOpenEditor() { return true; } @NotNull @Override public String removeModelSpecificMarkup(@NotNull String pattern) { if (pattern.endsWith("/") || pattern.endsWith("\\")) { return pattern.substring(0, pattern.length() - 1); } return pattern; } /** Just to remove smartness from {@link ChooseByNameBase#calcSelectedIndex} */ @Override public int compare(Object o1, Object o2) { return 0; } @NotNull public static PsiElementListCellRenderer.ItemMatchers convertToFileItemMatchers(@NotNull PsiElementListCellRenderer.ItemMatchers defaultMatchers, @NotNull PsiFileSystemItem value, @NotNull GotoFileModel model) { String shortName = model.getElementName(value); String fullName = model.getFullName(value); if (shortName != null && fullName != null && defaultMatchers.nameMatcher instanceof MinusculeMatcher) { String sanitized = GotoFileItemProvider .getSanitizedPattern(((MinusculeMatcher)defaultMatchers.nameMatcher).getPattern(), model); for (int i = sanitized.lastIndexOf('/') + 1; i < sanitized.length() - 1; i++) { MinusculeMatcher nameMatcher = NameUtil.buildMatcher("*" + sanitized.substring(i), NameUtil.MatchingCaseSensitivity.NONE); if (nameMatcher.matches(shortName)) { String locationPattern = FileUtil.toSystemDependentName(StringUtil.trimEnd(sanitized.substring(0, i), "/")); return new PsiElementListCellRenderer.ItemMatchers(nameMatcher, GotoFileItemProvider.getQualifiedNameMatcher(locationPattern)); } } } return defaultMatchers; } public static final FileTypeRef DIRECTORY_FILE_TYPE_REF = FileTypeRef.forFileType(new DirectoryFileType() { @Override public @NonNls @NotNull String getName() { return IdeBundle.message("search.everywhere.directory.file.type.name"); } @Override public @NlsContexts.Label @NotNull String getDescription() { return IdeBundle.message("filetype.search.everywhere.directory.description"); } @Override public @NlsSafe @NotNull String getDefaultExtension() { return ""; } @Override public Icon getIcon() { return PlatformIcons.FOLDER_ICON; } @Override public boolean isBinary() { return false; } }); }
{ "content_hash": "7494a799782ebc28df14f14d91a84ef1", "timestamp": "", "source": "github", "line_count": 249, "max_line_length": 174, "avg_line_length": 36.606425702811244, "alnum_prop": 0.727921009325288, "repo_name": "ingokegel/intellij-community", "id": "9bd2f39c6fa979fdbfdb53e78d2028302e5adc1d", "size": "9115", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoFileModel.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#ifndef __OMX_STREAMER_H__ #define __OMX_STREAMER_H__ #ifdef __cplusplus extern "C" { #endif #include <bcm_host.h> #include <interface/vcos/vcos_semaphore.h> #include <interface/vmcs_host/vchost.h> #include <IL/OMX_Core.h> #include <IL/OMX_Component.h> #include <IL/OMX_Video.h> #include <IL/OMX_Broadcom.h> #ifdef __cplusplus } #endif #define OSCAM_DEF_SHARPNESS 0 // -100 .. 100 #define OSCAM_DEF_CONTRAST 0 // -100 .. 100 #define OSCAM_DEF_BRIGHTNESS 50 // 0 .. 100 #define OSCAM_DEF_SATURATION 0 // -100 .. 100 #define OSCAM_DEF_EXPOSURE_VALUE_COMPENSATION 0 // -10 .. 10 #define OSCAM_DEF_EXPOSURE_ISO_SENSITIVITY 100 // 100 .. 800 #define OSCAM_DEF_EXPOSURE_AUTO_SENSITIVITY OMX_FALSE #define OSCAM_DEF_FRAME_STABILISATION OMX_TRUE #define OSCAM_DEF_WHITE_BALANCE_CONTROL OMX_WhiteBalControlAuto // OMX_WHITEBALCONTROLTYPE #define OSCAM_DEF_IMAGE_FILTER OMX_ImageFilterNoise // OMX_IMAGEFILTERTYPE #define OSCAM_DEF_FLIP_HORIZONTAL OMX_FALSE #define OSCAM_DEF_FLIP_VERTICAL OMX_FALSE typedef struct omx_streamer_config_s { int camera_sharpness; // -100 .. 100 int camera_contrast; // -100 .. 100 int camera_brightness; // 0 .. 100 int camera_saturation; // -100 .. 100 int camera_ev; // -10 .. 10 int camera_iso; // 100 .. 800 OMX_BOOL camera_iso_auto; OMX_BOOL camera_frame_stabilisation; OMX_BOOL camera_flip_horizon; OMX_BOOL camera_flip_vertical; enum OMX_WHITEBALCONTROLTYPE camera_whitebalance; enum OMX_IMAGEFILTERTYPE camera_filter; } omx_streamer_config_t; typedef struct omx_streamer_s { int initialized; OMX_HANDLETYPE camera; OMX_HANDLETYPE encoder; OMX_HANDLETYPE null_sink; OMX_BUFFERHEADERTYPE *inbuf; // for camera OMX_BUFFERHEADERTYPE *outbuf; // for encoder int camera_ready; int encoder_output_buffer_available; int flushed; VCOS_SEMAPHORE_T handler_lock; // camera settings: XXX - not yet implemented omx_streamer_config_t config; //////// int width; int height; int fps_n; int fps_d; int bitrate; int gopsize; // buffer for encoded data int buffer_filled; int bufsize; unsigned char *buffer; // internal statistics int frame_out; // number of output frames // unsigned char sps[1024]; unsigned int spslen; unsigned char pps[1024]; unsigned int ppslen; // } omx_streamer_t; int omx_streamer_init(omx_streamer_t *ctx, omx_streamer_config_t *config, int width, int height, int fps_n, int fps_d, int bitrate, int gopsize); int omx_streamer_deinit(omx_streamer_t *ctx); int omx_streamer_suspend(omx_streamer_t *ctx); int omx_streamer_resume(omx_streamer_t *ctx); int omx_streamer_reconfigure(omx_streamer_t *ctx, int bitrateKbps, unsigned int framerate, unsigned int width, unsigned int height); /* start streaming */ int omx_streamer_start(omx_streamer_t *ctx); /* preparing stop: called before stop */ int omx_streamer_prepare_stop(omx_streamer_t *ctx); /* stop streaming */ int omx_streamer_stop(omx_streamer_t *ctx); /* get h.264 sps/pps */ const unsigned char * omx_streamer_get_h264_sps(omx_streamer_t *ctx, int *size); const unsigned char * omx_streamer_get_h264_pps(omx_streamer_t *ctx, int *size); /* get the encoded stream */ unsigned char * omx_streamer_get(omx_streamer_t *ctx, int *encsize); #endif /* __OMX_STREAMER_H__ */
{ "content_hash": "a8c2c0c07e4d2424f65077f4f20a295b", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 145, "avg_line_length": 34.44897959183673, "alnum_prop": 0.6966824644549763, "repo_name": "chunying/smartbeholder", "id": "61973e5f7eca67b98e3be75368154231f9e4dfcc", "size": "4069", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "codes/module/streamer-omx/omx-streamer.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "111504" }, { "name": "C++", "bytes": "485206" }, { "name": "Makefile", "bytes": "5486" }, { "name": "Shell", "bytes": "216" } ], "symlink_target": "" }
int32_t main(int32_t argc, char* argv[]) { pthread_mutexattr_init(&GenericSharedDeclarations_mutexAttribute_0); pthread_mutexattr_settype(&GenericSharedDeclarations_mutexAttribute_0,PTHREAD_MUTEX_RECURSIVE); int32_t v; GenericSharedDeclarations_SharedOf_int32_0_t vShared; pthread_mutex_init(&vShared.mutex,&GenericSharedDeclarations_mutexAttribute_0); { vShared.value = 5; v = vShared.value; } return 0; }
{ "content_hash": "913f3add05edf1492b0f7b5e2414dd02", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 97, "avg_line_length": 27.4375, "alnum_prop": 0.744874715261959, "repo_name": "aloifolia/ParallelMbeddr", "id": "225fc8e623aecad067072f41e707ba7893932ed8", "size": "595", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "implementation/solutions/basictests/source_gen/basictests/syncs/syncs.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1193699" }, { "name": "C++", "bytes": "6248" }, { "name": "Java", "bytes": "672448" }, { "name": "TeX", "bytes": "340137" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_55) on Wed May 21 00:38:33 EEST 2014 --> <title>DbIterator</title> <meta name="date" content="2014-05-21"> <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DbIterator"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../nxt/util/CountingOutputStream.html" title="class in nxt.util"><span class="strong">Prev Class</span></a></li> <li><a href="../../nxt/util/DbIterator.ResultSetReader.html" title="interface in nxt.util"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../index.html?nxt/util/DbIterator.html" target="_top">Frames</a></li> <li><a href="DbIterator.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">nxt.util</div> <h2 title="Class DbIterator" class="title">Class DbIterator&lt;T&gt;</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>nxt.util.DbIterator&lt;T&gt;</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.lang.AutoCloseable, java.util.Iterator&lt;T&gt;</dd> </dl> <hr> <br> <pre>public final class <span class="strong">DbIterator&lt;T&gt;</span> extends java.lang.Object implements java.util.Iterator&lt;T&gt;, java.lang.AutoCloseable</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested_class_summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation"> <caption><span>Nested Classes</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static interface&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../nxt/util/DbIterator.ResultSetReader.html" title="interface in nxt.util">DbIterator.ResultSetReader</a>&lt;<a href="../../nxt/util/DbIterator.ResultSetReader.html" title="type parameter in DbIterator.ResultSetReader">T</a>&gt;</strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../nxt/util/DbIterator.html#DbIterator(java.sql.Connection, java.sql.PreparedStatement, nxt.util.DbIterator.ResultSetReader)">DbIterator</a></strong>(java.sql.Connection&nbsp;con, java.sql.PreparedStatement&nbsp;pstmt, <a href="../../nxt/util/DbIterator.ResultSetReader.html" title="interface in nxt.util">DbIterator.ResultSetReader</a>&lt;<a href="../../nxt/util/DbIterator.html" title="type parameter in DbIterator">T</a>&gt;&nbsp;rsReader)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../nxt/util/DbIterator.html#close()">close</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../nxt/util/DbIterator.html#hasNext()">hasNext</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../nxt/util/DbIterator.html" title="type parameter in DbIterator">T</a></code></td> <td class="colLast"><code><strong><a href="../../nxt/util/DbIterator.html#next()">next</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../nxt/util/DbIterator.html#remove()">remove</a></strong>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="DbIterator(java.sql.Connection, java.sql.PreparedStatement, nxt.util.DbIterator.ResultSetReader)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DbIterator</h4> <pre>public&nbsp;DbIterator(java.sql.Connection&nbsp;con, java.sql.PreparedStatement&nbsp;pstmt, <a href="../../nxt/util/DbIterator.ResultSetReader.html" title="interface in nxt.util">DbIterator.ResultSetReader</a>&lt;<a href="../../nxt/util/DbIterator.html" title="type parameter in DbIterator">T</a>&gt;&nbsp;rsReader)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="hasNext()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hasNext</h4> <pre>public&nbsp;boolean&nbsp;hasNext()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>hasNext</code>&nbsp;in interface&nbsp;<code>java.util.Iterator&lt;<a href="../../nxt/util/DbIterator.html" title="type parameter in DbIterator">T</a>&gt;</code></dd> </dl> </li> </ul> <a name="next()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>next</h4> <pre>public&nbsp;<a href="../../nxt/util/DbIterator.html" title="type parameter in DbIterator">T</a>&nbsp;next()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>next</code>&nbsp;in interface&nbsp;<code>java.util.Iterator&lt;<a href="../../nxt/util/DbIterator.html" title="type parameter in DbIterator">T</a>&gt;</code></dd> </dl> </li> </ul> <a name="remove()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>remove</h4> <pre>public&nbsp;void&nbsp;remove()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>remove</code>&nbsp;in interface&nbsp;<code>java.util.Iterator&lt;<a href="../../nxt/util/DbIterator.html" title="type parameter in DbIterator">T</a>&gt;</code></dd> </dl> </li> </ul> <a name="close()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>close</h4> <pre>public&nbsp;void&nbsp;close()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>close</code>&nbsp;in interface&nbsp;<code>java.lang.AutoCloseable</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../nxt/util/CountingOutputStream.html" title="class in nxt.util"><span class="strong">Prev Class</span></a></li> <li><a href="../../nxt/util/DbIterator.ResultSetReader.html" title="interface in nxt.util"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../index.html?nxt/util/DbIterator.html" target="_top">Frames</a></li> <li><a href="DbIterator.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "d01782d9f8053b2338e7104a7e33b557", "timestamp": "", "source": "github", "line_count": 337, "max_line_length": 301, "avg_line_length": 35.047477744807125, "alnum_prop": 0.64499195665058, "repo_name": "liyang19901122/nextc", "id": "091246a1551fcfa139fbb8337317af86272f288a", "size": "11811", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "html/doc/nxt/util/DbIterator.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "114949" }, { "name": "Java", "bytes": "786765" }, { "name": "JavaScript", "bytes": "587787" }, { "name": "Shell", "bytes": "1041" } ], "symlink_target": "" }
package com.microsoft.azure.management.cosmosdb.v2020_04_01; import java.util.Map; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * The MongoDBCollectionGetPropertiesResource model. */ public class MongoDBCollectionGetPropertiesResource { /** * Name of the Cosmos DB MongoDB collection. */ @JsonProperty(value = "id", required = true) private String id; /** * A key-value pair of shard keys to be applied for the request. */ @JsonProperty(value = "shardKey") private Map<String, String> shardKey; /** * List of index keys. */ @JsonProperty(value = "indexes") private List<MongoIndex> indexes; /** * Analytical TTL. */ @JsonProperty(value = "analyticalStorageTtl") private Integer analyticalStorageTtl; /** * A system generated property. A unique identifier. */ @JsonProperty(value = "_rid", access = JsonProperty.Access.WRITE_ONLY) private String _rid; /** * A system generated property that denotes the last updated timestamp of * the resource. */ @JsonProperty(value = "_ts", access = JsonProperty.Access.WRITE_ONLY) private Object _ts; /** * A system generated property representing the resource etag required for * optimistic concurrency control. */ @JsonProperty(value = "_etag", access = JsonProperty.Access.WRITE_ONLY) private String _etag; /** * Get name of the Cosmos DB MongoDB collection. * * @return the id value */ public String id() { return this.id; } /** * Set name of the Cosmos DB MongoDB collection. * * @param id the id value to set * @return the MongoDBCollectionGetPropertiesResource object itself. */ public MongoDBCollectionGetPropertiesResource withId(String id) { this.id = id; return this; } /** * Get a key-value pair of shard keys to be applied for the request. * * @return the shardKey value */ public Map<String, String> shardKey() { return this.shardKey; } /** * Set a key-value pair of shard keys to be applied for the request. * * @param shardKey the shardKey value to set * @return the MongoDBCollectionGetPropertiesResource object itself. */ public MongoDBCollectionGetPropertiesResource withShardKey(Map<String, String> shardKey) { this.shardKey = shardKey; return this; } /** * Get list of index keys. * * @return the indexes value */ public List<MongoIndex> indexes() { return this.indexes; } /** * Set list of index keys. * * @param indexes the indexes value to set * @return the MongoDBCollectionGetPropertiesResource object itself. */ public MongoDBCollectionGetPropertiesResource withIndexes(List<MongoIndex> indexes) { this.indexes = indexes; return this; } /** * Get analytical TTL. * * @return the analyticalStorageTtl value */ public Integer analyticalStorageTtl() { return this.analyticalStorageTtl; } /** * Set analytical TTL. * * @param analyticalStorageTtl the analyticalStorageTtl value to set * @return the MongoDBCollectionGetPropertiesResource object itself. */ public MongoDBCollectionGetPropertiesResource withAnalyticalStorageTtl(Integer analyticalStorageTtl) { this.analyticalStorageTtl = analyticalStorageTtl; return this; } /** * Get a system generated property. A unique identifier. * * @return the _rid value */ public String _rid() { return this._rid; } /** * Get a system generated property that denotes the last updated timestamp of the resource. * * @return the _ts value */ public Object _ts() { return this._ts; } /** * Get a system generated property representing the resource etag required for optimistic concurrency control. * * @return the _etag value */ public String _etag() { return this._etag; } }
{ "content_hash": "33ef261f50c04c1a872c6766a799d8f8", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 114, "avg_line_length": 25.54268292682927, "alnum_prop": 0.6335640964430652, "repo_name": "selvasingh/azure-sdk-for-java", "id": "b14a9816e486798890b19e36ba3243616bf3b0ac", "size": "4419", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/cosmos/mgmt-v2020_04_01/src/main/java/com/microsoft/azure/management/cosmosdb/v2020_04_01/MongoDBCollectionGetPropertiesResource.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "29891970" }, { "name": "JavaScript", "bytes": "6198" }, { "name": "PowerShell", "bytes": "160" }, { "name": "Shell", "bytes": "609" } ], "symlink_target": "" }
package lejos.hardware; import lejos.hardware.Audio; import lejos.hardware.Power; import lejos.hardware.lcd.Font; import lejos.hardware.lcd.GraphicsLCD; import lejos.hardware.lcd.TextLCD; import lejos.hardware.port.Port; import lejos.hardware.video.Video; public interface Brick { /** * Return a port object for the request port name. This allows access to the * hardware associated with the specified port. * @param portName The name of port * @return the request port */ public Port getPort(String portName); /** * return a battery object which can be used to obtain battery voltage etc. * @return A battery object */ public Power getPower(); /** * return a Audio object which can be used to access the device's audio playback * @return A Audio device */ public Audio getAudio(); public Video getVideo(); /** * Get text access to the LCD using the default font * @return the text LCD */ public TextLCD getTextLCD(); /** * Get text access to the LCD using a specified font * @param f the font * @return the text LCD */ public TextLCD getTextLCD(Font f); /** * Get graphics access to the LCD * @return the graphics LCD */ public GraphicsLCD getGraphicsLCD(); /** * Test whether the brick is a local one * @return true iff brick is local */ public boolean isLocal(); /** * Get the type of brick, e.g. "EV3", "NXT", "BrickPi" * @return the brick type */ public String getType(); /** * Get he name of the brick * @return the name */ public String getName(); /** * Get the local Bluetooth device * @return the local Bluetooth device */ public LocalBTDevice getBluetoothDevice(); /** * Get the local Wifi device * @return the local Wifi device */ public LocalWifiDevice getWifiDevice(); /** * Set this brick as the default one for static methods */ public void setDefault(); /** * Get access to the keys (buttons) * @return an implementation of the Keys interface */ public Keys getKeys(); /** * Get access to a specific Key (aka Button) * @param name the key name * @return an implementation of the Key interface */ public Key getKey(String name); /** * Get access to the LED * @return an implementation of the LED interface */ public LED getLED(); }
{ "content_hash": "5150a203b735715447d1e11efdc5afa3", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 84, "avg_line_length": 24.121495327102803, "alnum_prop": 0.6090662533901589, "repo_name": "antoniardot/DockBot-Eve", "id": "85ffe2c5943be750af5890df3bf02bcda0b48398", "size": "2581", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/lejos/hardware/Brick.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2139498" } ], "symlink_target": "" }
#ifndef QSPLITTER_P_H #define QSPLITTER_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <QtWidgets/private/qtwidgetsglobal_p.h> #include "private/qframe_p.h" #include "qrubberband.h" QT_BEGIN_NAMESPACE static const uint Default = 2; class QSplitterLayoutStruct { public: QRect rect; int sizer; uint collapsed : 1; uint collapsible : 2; QWidget *widget; QSplitterHandle *handle; QSplitterLayoutStruct() : sizer(-1), collapsed(false), collapsible(Default), widget(0), handle(0) {} ~QSplitterLayoutStruct() { delete handle; } int getWidgetSize(Qt::Orientation orient); int getHandleSize(Qt::Orientation orient); int pick(const QSize &size, Qt::Orientation orient) { return (orient == Qt::Horizontal) ? size.width() : size.height(); } }; class QSplitterPrivate : public QFramePrivate { Q_DECLARE_PUBLIC(QSplitter) public: QSplitterPrivate() : rubberBand(0), opaque(true), firstShow(true), childrenCollapsible(true), compatMode(false), handleWidth(-1), blockChildAdd(false), opaqueResizeSet(false) {} ~QSplitterPrivate(); QPointer<QRubberBand> rubberBand; mutable QList<QSplitterLayoutStruct *> list; Qt::Orientation orient; bool opaque : 8; bool firstShow : 8; bool childrenCollapsible : 8; bool compatMode : 8; int handleWidth; bool blockChildAdd; bool opaqueResizeSet; inline int pick(const QPoint &pos) const { return orient == Qt::Horizontal ? pos.x() : pos.y(); } inline int pick(const QSize &s) const { return orient == Qt::Horizontal ? s.width() : s.height(); } inline int trans(const QPoint &pos) const { return orient == Qt::Vertical ? pos.x() : pos.y(); } inline int trans(const QSize &s) const { return orient == Qt::Vertical ? s.width() : s.height(); } void init(); void recalc(bool update = false); void doResize(); void storeSizes(); void getRange(int index, int *, int *, int *, int *) const; void addContribution(int, int *, int *, bool) const; int adjustPos(int, int, int *, int *, int *, int *) const; bool collapsible(QSplitterLayoutStruct *) const; bool collapsible(int index) const { return (index < 0 || index >= list.size()) ? true : collapsible(list.at(index)); } QSplitterLayoutStruct *findWidget(QWidget *) const; void insertWidget_helper(int index, QWidget *widget, bool show); QSplitterLayoutStruct *insertWidget(int index, QWidget *); void doMove(bool backwards, int pos, int index, int delta, bool mayCollapse, int *positions, int *widths); void setGeo(QSplitterLayoutStruct *s, int pos, int size, bool allowCollapse); int findWidgetJustBeforeOrJustAfter(int index, int delta, int &collapsibleSize) const; void updateHandles(); void setSizes_helper(const QList<int> &sizes, bool clampNegativeSize = false); }; class QSplitterHandlePrivate : public QWidgetPrivate { Q_DECLARE_PUBLIC(QSplitterHandle) public: QSplitterHandlePrivate() : s(0), orient(Qt::Horizontal), mouseOffset(0), opaq(false), hover(false), pressed(false) {} inline int pick(const QPoint &pos) const { return orient == Qt::Horizontal ? pos.x() : pos.y(); } QSplitter *s; Qt::Orientation orient; int mouseOffset; bool opaq : 1; bool hover : 1; bool pressed : 1; }; QT_END_NAMESPACE #endif
{ "content_hash": "8e37e4d3a3329d9e943b13bd42178c69", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 135, "avg_line_length": 31.849557522123895, "alnum_prop": 0.6685190330647403, "repo_name": "kecho/Pegasus", "id": "4422d9a8a4c87e72331087f99632c8b318023000", "size": "5521", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Lib/Qt/5.8/include/QtWidgets/5.8.0/QtWidgets/private/qsplitter_p.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5271" }, { "name": "C", "bytes": "5185798" }, { "name": "C#", "bytes": "19843" }, { "name": "C++", "bytes": "29476003" }, { "name": "CMake", "bytes": "398929" }, { "name": "Lex", "bytes": "27672" }, { "name": "M4", "bytes": "230051" }, { "name": "Makefile", "bytes": "62466" }, { "name": "Objective-C", "bytes": "965957" }, { "name": "Pascal", "bytes": "20701" }, { "name": "Perl", "bytes": "60214" }, { "name": "PostScript", "bytes": "22623" }, { "name": "QMake", "bytes": "102544" }, { "name": "Shell", "bytes": "10341" }, { "name": "XSLT", "bytes": "56886" }, { "name": "Yacc", "bytes": "29292" } ], "symlink_target": "" }
package org.kie.server.client.impl; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import org.kie.api.command.Command; import org.kie.server.api.commands.CallContainerCommand; import org.kie.server.api.commands.CommandScript; import org.kie.server.api.commands.CreateContainerCommand; import org.kie.server.api.commands.DisposeContainerCommand; import org.kie.server.api.commands.GetContainerInfoCommand; import org.kie.server.api.commands.GetScannerInfoCommand; import org.kie.server.api.commands.GetServerInfoCommand; import org.kie.server.api.commands.ListContainersCommand; import org.kie.server.api.commands.UpdateReleaseIdCommand; import org.kie.server.api.commands.UpdateScannerCommand; import org.kie.server.api.model.KieContainerResource; import org.kie.server.api.model.KieContainerResourceList; import org.kie.server.api.model.KieScannerResource; import org.kie.server.api.model.KieServerCommand; import org.kie.server.api.model.KieServerInfo; import org.kie.server.api.model.ReleaseId; import org.kie.server.api.model.ServiceResponse; import org.kie.server.api.model.ServiceResponsesList; import org.kie.server.client.KieServicesClient; import org.kie.server.client.KieServicesConfiguration; import org.kie.server.client.KieServicesException; import org.kie.server.client.RuleServicesClient; import org.kie.server.client.helper.KieServicesClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KieServicesClientImpl extends AbstractKieServicesClientImpl implements KieServicesClient { private static Logger logger = LoggerFactory.getLogger( KieServicesClientImpl.class ); private static final ServiceLoader<KieServicesClientBuilder> clientBuilders = ServiceLoader.load(KieServicesClientBuilder.class, KieServicesClientImpl.class.getClassLoader()); private static List<KieServicesClientBuilder> loadedClientBuilders = loadClientBuilders(); // load it only once to make sure it's thread safe private String conversationId; private KieServerInfo kieServerInfo; private Map<Class<?>, Object> servicesClients = new HashMap<Class<?>, Object>(); public KieServicesClientImpl(KieServicesConfiguration config) { super(config); init(); } public KieServicesClientImpl(KieServicesConfiguration config, ClassLoader classLoader) { super(config, classLoader); init(); } private void init() { setOwner(this); List<String> serverCapabilities = config.getCapabilities(); if (serverCapabilities == null) { // no explicit capabilities configuration given fetch them from kieServer kieServerInfo = getServerInfo().getResult(); logger.debug("KieServicesClient connected to: {} version {}", kieServerInfo.getServerId(), kieServerInfo.getVersion()); serverCapabilities = kieServerInfo.getCapabilities(); logger.debug("Supported capabilities by the server: {}", serverCapabilities); } if (serverCapabilities != null && !serverCapabilities.isEmpty()) { // process available client builders Map<String, KieServicesClientBuilder> clientBuildersByCapability = new HashMap<String, KieServicesClientBuilder>(); for (KieServicesClientBuilder builder : loadedClientBuilders) { clientBuildersByCapability.put(builder.getImplementedCapability(), builder); } // build client based on server capabilities for (String capability : serverCapabilities) { logger.debug("Building services client for server capability {}", capability); KieServicesClientBuilder builder = clientBuildersByCapability.get(capability); if (builder != null) { try { logger.debug("Builder '{}' for capability '{}'", builder, capability); Map<Class<?>, Object> clients = builder.build(config, classLoader); for (Object serviceClient : clients.values()) { if (serviceClient instanceof AbstractKieServicesClientImpl) { ((AbstractKieServicesClientImpl) serviceClient).setOwner(this); } } logger.debug("Capability implemented by {}", clients); servicesClients.putAll(clients); } catch (Exception e) { logger.warn("Builder {} throw exception while setting up clients, no {} capabilities will be available", builder, capability); } } else { logger.debug("No builder found for '{}' capability", capability); } } } } @Override public <T> T getServicesClient(Class<T> serviceClient) { if (servicesClients.containsKey(serviceClient)) { return (T) servicesClients.get(serviceClient); } throw new KieServicesException("Server that this client is connected to has no capabilities to handle " + serviceClient.getSimpleName()); } @Override public ServiceResponse<KieServerInfo> getServerInfo() { if( config.isRest() ) { return makeHttpGetRequestAndCreateServiceResponse(loadBalancer.getUrl(), KieServerInfo.class ); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new GetServerInfoCommand() ) ); return (ServiceResponse<KieServerInfo>) executeJmsCommand( script ).getResponses().get( 0 ); } } @Override public ServiceResponse<KieContainerResourceList> listContainers() { if( config.isRest() ) { return makeHttpGetRequestAndCreateServiceResponse( loadBalancer.getUrl() + "/containers", KieContainerResourceList.class ); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new ListContainersCommand() ) ); return (ServiceResponse<KieContainerResourceList>) executeJmsCommand( script ).getResponses().get( 0 ); } } @Override public ServiceResponse<KieContainerResource> createContainer(String id, KieContainerResource resource) { if( config.isRest() ) { return makeHttpPutRequestAndCreateServiceResponse( loadBalancer.getUrl() + "/containers/" + id, resource, KieContainerResource.class ); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new CreateContainerCommand( resource ) ) ); return (ServiceResponse<KieContainerResource>) executeJmsCommand( script, null, null, id ).getResponses().get( 0 ); } } @Override public ServiceResponse<KieContainerResource> getContainerInfo(String id) { if( config.isRest() ) { return makeHttpGetRequestAndCreateServiceResponse( loadBalancer.getUrl() + "/containers/" + id, KieContainerResource.class ); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new GetContainerInfoCommand( id ) ) ); return (ServiceResponse<KieContainerResource>) executeJmsCommand( script, null, null, id ).getResponses().get( 0 ); } } @Override public ServiceResponse<Void> disposeContainer(String id) { if( config.isRest() ) { return makeHttpDeleteRequestAndCreateServiceResponse( loadBalancer.getUrl() + "/containers/" + id, Void.class ); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new DisposeContainerCommand( id ) ) ); return (ServiceResponse<Void>) executeJmsCommand( script, null, null, id ).getResponses().get( 0 ); } } @Override public ServiceResponsesList executeScript(CommandScript script) { if( config.isRest() ) { return makeHttpPostRequestAndCreateCustomResponse( loadBalancer.getUrl() + "/config", script, ServiceResponsesList.class ); } else { return executeJmsCommand( script ); } } @Override public ServiceResponse<KieScannerResource> getScannerInfo(String id) { if( config.isRest() ) { return makeHttpGetRequestAndCreateServiceResponse( loadBalancer.getUrl() + "/containers/" + id + "/scanner", KieScannerResource.class ); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new GetScannerInfoCommand( id ) ) ); return (ServiceResponse<KieScannerResource>) executeJmsCommand( script, null, null, id ).getResponses().get( 0 ); } } @Override public ServiceResponse<KieScannerResource> updateScanner(String id, KieScannerResource resource) { if( config.isRest() ) { return makeHttpPostRequestAndCreateServiceResponse( loadBalancer.getUrl() + "/containers/" + id + "/scanner", resource, KieScannerResource.class ); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new UpdateScannerCommand( id, resource ) ) ); return (ServiceResponse<KieScannerResource>) executeJmsCommand( script, null, null, id ).getResponses().get( 0 ); } } @Override public ServiceResponse<ReleaseId> updateReleaseId(String id, ReleaseId releaseId) { if( config.isRest() ) { return makeHttpPostRequestAndCreateServiceResponse( loadBalancer.getUrl() + "/containers/" + id + "/release-id", releaseId, ReleaseId.class ); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new UpdateReleaseIdCommand( id, releaseId ) ) ); return (ServiceResponse<ReleaseId>) executeJmsCommand( script, null, null, id ).getResponses().get( 0 ); } } // for backward compatibility reason /** * This method is deprecated on KieServicesClient as it was moved to RuleServicesClient * @see RuleServicesClient#executeCommands(String, String) * @deprecated */ @Deprecated @Override public ServiceResponse<String> executeCommands(String id, String payload) { if( config.isRest() ) { return makeBackwardCompatibleHttpPostRequestAndCreateServiceResponse(loadBalancer.getUrl() + "/containers/instances/" + id, payload, String.class); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new CallContainerCommand( id, payload ) ) ); return (ServiceResponse<String>) executeJmsCommand( script, null, null, id ).getResponses().get( 0 ); } } /** * This method is deprecated on KieServicesClient as it was moved to RuleServicesClient * @see RuleServicesClient#executeCommands(String, Command) * @deprecated */ @Deprecated @Override public ServiceResponse<String> executeCommands(String id, Command<?> cmd) { if( config.isRest() ) { return makeBackwardCompatibleHttpPostRequestAndCreateServiceResponse(loadBalancer.getUrl() + "/containers/instances/" + id, cmd, String.class, getHeaders(cmd) ); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new CallContainerCommand( id, serialize(cmd) ) ) ); return (ServiceResponse<String>) executeJmsCommand( script, cmd.getClass().getName(), null, id ).getResponses().get( 0 ); } } @Override public String toString() { return "KieServicesClient{" + "kieServer=" + kieServerInfo + ", available clients=" + servicesClients + '}'; } @Override public void setClassLoader(ClassLoader classLoader) { this.marshaller.setClassLoader( classLoader ); } @Override public ClassLoader getClassLoader() { return this.marshaller.getClassLoader(); } @Override public String getConversationId() { return conversationId; } @Override public void completeConversation() { conversationId = null; } public void setConversationId(String conversationId) { if (conversationId != null) { this.conversationId = conversationId; } } private synchronized static List<KieServicesClientBuilder> loadClientBuilders() { List<KieServicesClientBuilder> builders = new ArrayList<KieServicesClientBuilder>(); for (KieServicesClientBuilder builder : clientBuilders) { builders.add(builder); } return builders; } }
{ "content_hash": "60fe75680e5a15015a22d21718f4d076", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 179, "avg_line_length": 44.734482758620686, "alnum_prop": 0.6772527557234256, "repo_name": "ibek/droolsjbpm-integration", "id": "2ca6d622baf34d5a05714db5aa1d653f165a254b", "size": "13549", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kie-server-parent/kie-server-remote/kie-server-client/src/main/java/org/kie/server/client/impl/KieServicesClientImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2569" }, { "name": "CSS", "bytes": "7748" }, { "name": "HTML", "bytes": "2654" }, { "name": "Java", "bytes": "6223954" }, { "name": "JavaScript", "bytes": "32051" }, { "name": "Shell", "bytes": "3525" }, { "name": "XSLT", "bytes": "2865" } ], "symlink_target": "" }
package org.pentaho.osgi.notification.webservice; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; /** * Created by bryan on 8/22/14. */ public class NotificationRequestWrapperTest { @Test public void testNoArgConstructor() { NotificationRequestWrapper notificationRequestWrapper = new NotificationRequestWrapper( ); assertNull( notificationRequestWrapper.getRequests() ); } @Test public void testRequestsConstructor() { NotificationRequest request = mock( NotificationRequest.class ); List<NotificationRequest> requests = new ArrayList<NotificationRequest>( Arrays.asList(request) ); NotificationRequestWrapper notificationRequestWrapper = new NotificationRequestWrapper( requests ); assertEquals( requests, notificationRequestWrapper.getRequests() ); } @Test public void testSetRequests() { NotificationRequest request = mock( NotificationRequest.class ); List<NotificationRequest> requests = new ArrayList<NotificationRequest>( Arrays.asList(request) ); NotificationRequestWrapper notificationRequestWrapper = new NotificationRequestWrapper( ); notificationRequestWrapper.setRequests( requests ); assertEquals( requests, notificationRequestWrapper.getRequests() ); } }
{ "content_hash": "daa9ce9d4d6026e4b648e29ece9ce1f8", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 103, "avg_line_length": 34.707317073170735, "alnum_prop": 0.7856640899508082, "repo_name": "marcoslarsen/pentaho-osgi-bundles", "id": "72e9c1154cfd3dfa8d27c0e77f05efb825a7eb69", "size": "2335", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pentaho-notification-webservice-bundle/src/test/java/org/pentaho/osgi/notification/webservice/NotificationRequestWrapperTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "5081" }, { "name": "Java", "bytes": "1135322" }, { "name": "JavaScript", "bytes": "53992" }, { "name": "Roff", "bytes": "126" } ], "symlink_target": "" }
package ir.isilearning.lmsapp.persistence; import android.provider.BaseColumns; /** * Structure of the quiz table. */ public interface QuizTable { String NAME = "quiz"; String COLUMN_ID = BaseColumns._ID; String FK_CATEGORY = "fk_category"; String COLUMN_TYPE = "type"; String COLUMN_QUESTION = "question"; String COLUMN_ANSWER = "answer"; String COLUMN_OPTIONS = "options"; String COLUMN_MIN = "min"; String COLUMN_MAX = "max"; String COLUMN_STEP = "step"; String COLUMN_START = "start"; String COLUMN_END = "end"; String COLUMN_SOLVED = "solved"; String Exam_Question_History_ID = "EQHID"; String Question_File = "QuestioFile"; String Options_Files = "OptionsFiles"; String USER_ANSWER = "UserAnswer"; String ANSWER_DATE = "answerdate"; String[] PROJECTION = new String[]{COLUMN_ID, FK_CATEGORY, COLUMN_TYPE, COLUMN_QUESTION, COLUMN_ANSWER, COLUMN_OPTIONS, COLUMN_MIN, COLUMN_MAX, COLUMN_STEP, COLUMN_START, COLUMN_END, COLUMN_SOLVED ,Exam_Question_History_ID, Question_File,Options_Files,USER_ANSWER,ANSWER_DATE}; String CREATE = "CREATE TABLE " + NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY, " + FK_CATEGORY + " REFERENCES " + CategoryTable.NAME + "(" + CategoryTable.COLUMN_ID + "), " + COLUMN_TYPE + " TEXT NOT NULL, " + COLUMN_QUESTION + " TEXT NOT NULL, " + COLUMN_ANSWER + " TEXT NOT NULL, " + COLUMN_OPTIONS + " TEXT, " + COLUMN_MIN + " TEXT , " + COLUMN_MAX + " TEXT , " + COLUMN_STEP + " TEXT , " + COLUMN_START + " TEXT , " + COLUMN_END + " TEXT , " + COLUMN_SOLVED + " TEXT , " + Question_File + " TEXT , " + Exam_Question_History_ID + " INTEGER , " + Options_Files + " TEXT , " + USER_ANSWER + " TEXT ," + ANSWER_DATE + " TEXT" + ");"; }
{ "content_hash": "cda4b7376a484dd193c2efd2ead4cfc7", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 103, "avg_line_length": 35.29824561403509, "alnum_prop": 0.5611332007952287, "repo_name": "MR612/TheApp", "id": "784434d8ba2409ff12f677c31f82f9bbffdd8ade", "size": "2607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/ir/isilearning/lmsapp/persistence/QuizTable.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "467522" }, { "name": "Prolog", "bytes": "226" } ], "symlink_target": "" }
/* $NetBSD: udf_write.h,v 1.4 2013/08/05 20:52:08 reinoud Exp $ */ /* * Copyright (c) 2006, 2008, 2013 Reinoud Zandijk * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef _FS_UDF_UDF_WRITE_H_ #define _FS_UDF_UDF_WRITE_H_ #include "udf_create.h" #if !HAVE_NBTOOL_CONFIG_H #define _EXPOSE_MMC #include <sys/cdio.h> #else #include "udf/cdio_mmc_structs.h" #endif /* prototypes */ int udf_write_dscr_virt(union dscrptr *dscr, uint32_t location, uint32_t vpart, uint32_t sects); void udf_metadata_alloc(int nblk, struct long_ad *pos); void udf_data_alloc(int nblk, struct long_ad *pos); int udf_derive_format(int req_enable, int req_disable, int force); int udf_proces_names(void); int udf_do_newfs_prefix(void); int udf_do_rootdir(void); int udf_do_newfs_postfix(void); #endif /* _FS_UDF_UDF_WRITE_H_ */
{ "content_hash": "af8be61893600833f1064bda0d914f9f", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 79, "avg_line_length": 37.96296296296296, "alnum_prop": 0.7414634146341463, "repo_name": "execunix/vinos", "id": "d2fd8ac0c7a9cb82ca14582eb0ce05bce5a8e346", "size": "2050", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sbin/newfs_udf/udf_write.h", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "9f41d170d31e36ab58282937c7a65542", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "7a62ae38bdc7f661c08f896f276e4886ee0e21ec", "size": "205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Chloroleucon/Chloroleucon mangense/ Syn. Pithecellobium undulatum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.google.cloud.bigtable.hbase; import com.google.cloud.bigtable.hbase.test_env.SharedTestEnvRule; import java.io.IOException; import java.util.List; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.RowMutations; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp; import org.apache.hadoop.hbase.util.Bytes; import org.junit.Assert; import org.junit.Test; public abstract class AbstractTestCheckAndMutate extends AbstractTest { /** * Requirement 7.1 - Atomically attempt a mutation, dependent on a successful value check within * the same row. * * <p>Requirement 7.3 - Pass a null value to check for the non-existence of a column. */ @Test public void testCheckAndPutSameQual() throws Exception { // Initialize try (Table table = getDefaultTable()) { byte[] rowKey = dataHelper.randomData("rowKey-"); byte[] qual = dataHelper.randomData("qualifier-"); byte[] value1 = dataHelper.randomData("value-"); byte[] value2 = dataHelper.randomData("value-"); // Put with a bad check on a null value, then try with a good one Put put = new Put(rowKey).addColumn(SharedTestEnvRule.COLUMN_FAMILY, qual, value1); boolean success = checkAndPut(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual, value2, put); Assert.assertFalse("Column doesn't exist. Should fail.", success); success = checkAndPut(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual, null, put); Assert.assertTrue(success); // Fail on null check, now there's a value there put = new Put(rowKey).addColumn(SharedTestEnvRule.COLUMN_FAMILY, qual, value2); success = checkAndPut(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual, null, put); Assert.assertFalse("Null check should fail", success); success = checkAndPut(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual, value2, put); Assert.assertFalse("Wrong value should fail", success); success = checkAndPut(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual, value1, put); Assert.assertTrue(success); // Check results Get get = new Get(rowKey); get.setMaxVersions(5); Result result = table.get(get); Assert.assertEquals("Should be two results", 2, result.size()); List<Cell> cells = result.getColumnCells(SharedTestEnvRule.COLUMN_FAMILY, qual); Assert.assertArrayEquals(value2, CellUtil.cloneValue(cells.get(0))); Assert.assertArrayEquals(value1, CellUtil.cloneValue(cells.get(1))); } } protected abstract boolean checkAndPut( byte[] rowKey, byte[] columnFamily, byte[] qual, byte[] value, Put put) throws Exception; protected abstract boolean checkAndPut( byte[] rowKey, byte[] columnFamily, byte[] qualToCheck, CompareOp op, byte[] bytes, Put someRandomPut) throws Exception; protected abstract boolean checkAndDelete( byte[] rowKey, byte[] columnFamily, byte[] qual, byte[] value, Delete delete) throws Exception; protected abstract boolean checkAndMutate( byte[] rowKey, byte[] columnFamily, byte[] qual, CompareOp op, byte[] value, RowMutations rm) throws Exception; /** Further tests for requirements 7.1 and 7.3. */ @Test public void testCheckAndDeleteSameQual() throws Exception { // Initialize Table table = getDefaultTable(); byte[] rowKey = dataHelper.randomData("rowKey-"); byte[] qual = dataHelper.randomData("qualifier-"); byte[] value1 = dataHelper.randomData("value-"); byte[] value2 = dataHelper.randomData("value-"); // Delete all previous versions if the value is found. Delete delete = new Delete(rowKey).addColumns(SharedTestEnvRule.COLUMN_FAMILY, qual); boolean success = checkAndDelete(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual, value1, delete); Assert.assertFalse("Column doesn't exist. Should fail.", success); success = checkAndDelete(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual, null, delete); // Add a value and check again Put put = new Put(rowKey).addColumn(SharedTestEnvRule.COLUMN_FAMILY, qual, value1); table.put(put); success = checkAndDelete(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual, value2, delete); Assert.assertFalse("Wrong value. Should fail.", success); success = checkAndDelete(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual, value1, delete); Assert.assertTrue(success); Assert.assertFalse("Row should be gone", table.exists(new Get(rowKey))); table.close(); } /** Further tests for requirements 7.1 and 7.3. */ @Test public void testCheckAndPutDiffQual() throws Exception { // Initialize Table table = getDefaultTable(); byte[] rowKey = dataHelper.randomData("rowKey-"); byte[] qual1 = dataHelper.randomData("qualifier-"); byte[] qual2 = dataHelper.randomData("qualifier-"); byte[] value1 = dataHelper.randomData("value-"); byte[] value2 = dataHelper.randomData("value-"); // Put then again Put put = new Put(rowKey).addColumn(SharedTestEnvRule.COLUMN_FAMILY, qual1, value1); boolean success = checkAndPut(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual2, value2, put); Assert.assertFalse("Column doesn't exist. Should fail.", success); success = checkAndPut(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual2, null, put); Assert.assertTrue(success); // Fail on null check, now there's a value there put = new Put(rowKey).addColumn(SharedTestEnvRule.COLUMN_FAMILY, qual2, value2); success = checkAndPut(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual1, null, put); Assert.assertFalse("Null check should fail", success); success = checkAndPut(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual1, value2, put); Assert.assertFalse("Wrong value should fail", success); success = checkAndPut(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual1, value1, put); Assert.assertTrue(success); // Check results Get get = new Get(rowKey); get.setMaxVersions(5); Result result = table.get(get); Assert.assertEquals("Should be two results", 2, result.size()); Assert.assertArrayEquals( value1, CellUtil.cloneValue(result.getColumnLatestCell(SharedTestEnvRule.COLUMN_FAMILY, qual1))); Assert.assertArrayEquals( value2, CellUtil.cloneValue(result.getColumnLatestCell(SharedTestEnvRule.COLUMN_FAMILY, qual2))); table.close(); } /** Further tests for requirements 7.1 and 7.3. */ @Test public void testCheckAndDeleteDiffQual() throws Exception { // Initialize Table table = getDefaultTable(); byte[] rowKey = dataHelper.randomData("rowKey-"); byte[] qual1 = dataHelper.randomData("qualifier-"); byte[] qual2 = dataHelper.randomData("qualifier-"); byte[] value1 = dataHelper.randomData("value-"); byte[] value2 = dataHelper.randomData("value-"); // Delete all versions of a column if the latest version matches Delete delete = new Delete(rowKey).addColumns(SharedTestEnvRule.COLUMN_FAMILY, qual1); boolean success = checkAndDelete(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual2, value2, delete); Assert.assertFalse("Column doesn't exist. Should fail.", success); success = checkAndDelete(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual2, null, delete); Assert.assertTrue(success); // Add a value now Put put = new Put(rowKey) .addColumn(SharedTestEnvRule.COLUMN_FAMILY, qual1, value1) .addColumn(SharedTestEnvRule.COLUMN_FAMILY, qual2, value2); table.put(put); // Fail on null check, now there's a value there success = checkAndDelete(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual2, null, delete); Assert.assertFalse("Null check should fail", success); success = checkAndDelete(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual2, value1, delete); Assert.assertFalse("Wrong value should fail", success); success = checkAndDelete(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual2, value2, delete); Assert.assertTrue(success); delete = new Delete(rowKey).addColumns(SharedTestEnvRule.COLUMN_FAMILY, qual2); success = checkAndDelete(rowKey, SharedTestEnvRule.COLUMN_FAMILY, qual1, null, delete); Assert.assertTrue(success); Assert.assertFalse("Row should be gone", table.exists(new Get(rowKey))); table.close(); } /** * Requirement 7.2 - Throws an IOException if the check is for a row other than the one in the * mutation attempt. */ @Test public void testCheckAndPutDiffRow() throws Exception { // Initialize Table table = getDefaultTable(); byte[] rowKey1 = dataHelper.randomData("rowKey-"); byte[] rowKey2 = dataHelper.randomData("rowKey-"); byte[] qual = dataHelper.randomData("qualifier-"); byte[] value = dataHelper.randomData("value-"); // Put then again Put put = new Put(rowKey1).addColumn(SharedTestEnvRule.COLUMN_FAMILY, qual, value); try { checkAndPut(rowKey2, SharedTestEnvRule.COLUMN_FAMILY, qual, null, put); } catch (IOException e) { assertGetRowException(e); } finally { table.close(); } } private static void assertGetRowException(IOException e) { Assert.assertTrue(e.getMessage(), e.getMessage().contains("Action's getRow must match")); } @Test public void testCheckAndDeleteDiffRow() throws Exception { // Initialize try (Table table = getDefaultTable()) { byte[] rowKey1 = dataHelper.randomData("rowKey-"); byte[] rowKey2 = dataHelper.randomData("rowKey-"); byte[] qual = dataHelper.randomData("qualifier-"); // Put then again Delete delete = new Delete(rowKey1).addColumns(SharedTestEnvRule.COLUMN_FAMILY, qual); checkAndDelete(rowKey2, SharedTestEnvRule.COLUMN_FAMILY, qual, null, delete); } catch (IOException e) { assertGetRowException(e); } } @Test public void testCheckAndMutate() throws Exception { // Initialize Table table = getDefaultTable(); byte[] rowKey = dataHelper.randomData("rowKey-"); byte[] qualCheck = dataHelper.randomData("qualifier-"); byte[] qualPut = dataHelper.randomData("qualifier-"); byte[] qualDelete = dataHelper.randomData("qualifier-"); byte[] valuePut = dataHelper.randomData("value-"); byte[] valueCheck = dataHelper.randomData("value-"); // Delete all versions of a column if the latest version matches RowMutations rm = new RowMutations(rowKey); rm.add(new Put(rowKey).addColumn(SharedTestEnvRule.COLUMN_FAMILY, qualPut, valuePut)); rm.add(new Delete(rowKey).addColumns(SharedTestEnvRule.COLUMN_FAMILY, qualDelete)); boolean success = checkAndMutate( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualCheck, CompareOp.EQUAL, valueCheck, rm); Assert.assertFalse("Column doesn't exist. Should fail.", success); success = checkAndMutate( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualCheck, CompareOp.EQUAL, null, rm); Assert.assertTrue(success); // Add a value now Put put = new Put(rowKey) .addColumn(SharedTestEnvRule.COLUMN_FAMILY, qualCheck, valueCheck) .addColumn(SharedTestEnvRule.COLUMN_FAMILY, qualDelete, Bytes.toBytes("todelete")); table.put(put); // Fail on null check, now there's a value there success = checkAndMutate( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualCheck, CompareOp.EQUAL, null, rm); Assert.assertFalse("Null check should fail", success); // valuePut is in qualPut and not in qualCheck so this will fail: success = checkAndMutate( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualCheck, CompareOp.EQUAL, valuePut, rm); Assert.assertFalse("Wrong value should fail", success); success = checkAndMutate( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualCheck, CompareOp.EQUAL, valueCheck, rm); Assert.assertTrue(success); Result row = table.get(new Get(rowKey).addFamily(SharedTestEnvRule.COLUMN_FAMILY)); // QualCheck and QualPut should exist Assert.assertEquals(2, row.size()); Assert.assertFalse( "QualDelete should be deleted", row.containsColumn(SharedTestEnvRule.COLUMN_FAMILY, qualDelete)); Assert.assertTrue( "QualPut should exist", row.containsColumn(SharedTestEnvRule.COLUMN_FAMILY, qualPut)); table.close(); } @Test public void testCompareOps() throws Exception { byte[] rowKey = dataHelper.randomData("rowKey-"); byte[] qualToCheck = dataHelper.randomData("toCheck-"); byte[] otherQual = dataHelper.randomData("other-"); boolean success; Table table = getDefaultTable(); table.put( new Put(rowKey) .addColumn(SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, Bytes.toBytes(2000l))); Put someRandomPut = new Put(rowKey).addColumn(SharedTestEnvRule.COLUMN_FAMILY, otherQual, Bytes.toBytes(1l)); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.LESS, Bytes.toBytes(1000l), someRandomPut); Assert.assertTrue("1000 < 2000 should succeed", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.LESS, Bytes.toBytes(4000l), someRandomPut); Assert.assertFalse("4000 < 2000 should fail", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.GREATER, Bytes.toBytes(1000l), someRandomPut); Assert.assertFalse("1000 > 2000 should fail", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.GREATER, Bytes.toBytes(4000l), someRandomPut); Assert.assertTrue("4000 > 2000 should succeed", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.LESS_OR_EQUAL, Bytes.toBytes(1000l), someRandomPut); Assert.assertTrue("1000 <= 2000 should succeed", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.LESS_OR_EQUAL, Bytes.toBytes(4000l), someRandomPut); Assert.assertFalse("4000 <= 2000 should fail", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.GREATER_OR_EQUAL, Bytes.toBytes(1000l), someRandomPut); Assert.assertFalse("1000 >= 2000 should fail", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.GREATER_OR_EQUAL, Bytes.toBytes(4000l), someRandomPut); Assert.assertTrue("4000 >= 2000 should succeed", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.EQUAL, Bytes.toBytes(1000l), someRandomPut); Assert.assertFalse("1000 == 2000 should fail", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.EQUAL, Bytes.toBytes(2000l), someRandomPut); Assert.assertTrue("2000 == 2000 should succeed", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.NOT_EQUAL, Bytes.toBytes(2000l), someRandomPut); Assert.assertFalse("2000 != 2000 should fail", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.NOT_EQUAL, Bytes.toBytes(4000l), someRandomPut); Assert.assertTrue("4000 != 2000 should succeed", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.GREATER_OR_EQUAL, new byte[] {Byte.MIN_VALUE}, someRandomPut); Assert.assertTrue("4000 > MIN_BYTES should succeed", success); } @Test public void testCompareOpsNull() throws Exception { byte[] rowKey = dataHelper.randomData("rowKey-"); byte[] nullQual = dataHelper.randomData("null-"); byte[] popluatedQual = dataHelper.randomData("pupulated-"); byte[] otherQual = dataHelper.randomData("other-"); boolean success; Table table = getDefaultTable(); table.put( new Put(rowKey) .addColumn(SharedTestEnvRule.COLUMN_FAMILY, popluatedQual, Bytes.toBytes(2000l))); Put someRandomPut = new Put(rowKey).addColumn(SharedTestEnvRule.COLUMN_FAMILY, otherQual, Bytes.toBytes(1l)); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, nullQual, CompareOp.LESS, null, someRandomPut); Assert.assertTrue("< null should succeed", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, nullQual, CompareOp.GREATER, null, someRandomPut); Assert.assertTrue("> null should succeed", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, nullQual, CompareOp.LESS_OR_EQUAL, null, someRandomPut); Assert.assertTrue("<= null should succeed", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, nullQual, CompareOp.GREATER_OR_EQUAL, null, someRandomPut); Assert.assertTrue(">= null should succeed", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, nullQual, CompareOp.EQUAL, null, someRandomPut); Assert.assertTrue("== null should succeed", success); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, nullQual, CompareOp.GREATER_OR_EQUAL, new byte[] {Byte.MIN_VALUE}, someRandomPut); Assert.assertFalse("> MIN_BYTES should fail", success); } /** * Bigtable supports a notion of `NOT_EQUALS null` checks equating with `check for existence`. * HBase does not support this notion, and always uses `{any comparator} null` to mean `check for * non-existence`. */ @Test public void testNotEqualsNull_BigtableOnly() throws Exception { if (!sharedTestEnv.isBigtable()) { return; } byte[] rowKey = dataHelper.randomData("rowKey-"); byte[] nullQual = dataHelper.randomData("null-"); byte[] popluatedQual = dataHelper.randomData("pupulated-"); byte[] otherQual = dataHelper.randomData("other-"); Table table = getDefaultTable(); table.put( new Put(rowKey) .addColumn(SharedTestEnvRule.COLUMN_FAMILY, popluatedQual, Bytes.toBytes(2000l))); Put someRandomPut = new Put(rowKey).addColumn(SharedTestEnvRule.COLUMN_FAMILY, otherQual, Bytes.toBytes(1l)); boolean success; // This doesn't work in HBase, but we need this to work in CBT success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, nullQual, CompareOp.NOT_EQUAL, null, someRandomPut); Assert.assertFalse("!= null should fail", success); // This doesn't work in HBase, but we need this to work in CBT success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, popluatedQual, CompareOp.NOT_EQUAL, null, someRandomPut); Assert.assertTrue("2000 != null should succeed", success); } @Test public void testCompareOpsVersions() throws Exception { byte[] rowKey = dataHelper.randomData("rowKey-"); byte[] qualToCheck = dataHelper.randomData("toCheck-"); byte[] otherQual = dataHelper.randomData("other-"); boolean success; Table table = getDefaultTable(); Put someRandomPut = new Put(rowKey).addColumn(SharedTestEnvRule.COLUMN_FAMILY, otherQual, Bytes.toBytes(1l)); table.put( new Put(rowKey, System.currentTimeMillis() - 10000) .addColumn(SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, Bytes.toBytes(2000l))); table.put( new Put(rowKey, System.currentTimeMillis()) .addColumn(SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, Bytes.toBytes(4000l))); success = checkAndPut( rowKey, SharedTestEnvRule.COLUMN_FAMILY, qualToCheck, CompareOp.GREATER, Bytes.toBytes(3000l), someRandomPut); Assert.assertFalse("3000 > 4000 should fail", success); } }
{ "content_hash": "1f58c478d436696fe29f8affcc777e1e", "timestamp": "", "source": "github", "line_count": 595, "max_line_length": 100, "avg_line_length": 36.371428571428574, "alnum_prop": 0.6567626264960029, "repo_name": "sduskis/cloud-bigtable-client", "id": "4cdc41f8fa20f09bee810ce6814b337d59d26c90", "size": "22256", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bigtable-client-core-parent/bigtable-hbase-integration-tests-common/src/test/java/com/google/cloud/bigtable/hbase/AbstractTestCheckAndMutate.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2617628" }, { "name": "Shell", "bytes": "438" } ], "symlink_target": "" }
from grab.spider.base import Spider # noqa from grab.spider.task import Task # noqa from grab.spider.error import * # noqa pylint: disable=wildcard-import
{ "content_hash": "c3ebddacfabcc1ce2a219f58a2fb24d5", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 71, "avg_line_length": 52.666666666666664, "alnum_prop": 0.7721518987341772, "repo_name": "lorien/grab", "id": "661ab001a72d280cc9460328ae2afe89062c5dd6", "size": "158", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "grab/spider/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "250730" }, { "name": "Makefile", "bytes": "879" }, { "name": "Python", "bytes": "347132" } ], "symlink_target": "" }
package com.example.phone_notes.activity; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Date; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.text.TextUtils; import android.text.format.DateFormat; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.example.phone_notes.R; import com.example.phone_notes.base.BaseActivity; import com.example.phone_notes.bean.notesItem; import com.example.phone_notes.constant.myConstant; import com.example.phone_notes.utils.TimeFormatUtil; import com.example.phone_notes.utils.ToastUtils; /** * * * * 笔记编辑和查看页面 * * @author孙文权 * */ public class NotesDetailEditActivity extends BaseActivity { private int CurrentOPerate;// 当前操作类型:添加或编辑,添加成功返回添加成功信息更新列表,产生编辑操作,返回编辑信息,提示修改成功 private Intent intent; private ImageView save;// 顶部保存按钮 private String parentTable;// 新添加笔记父列表 private EditText title;// 笔记标题 private ImageView btn_addtag;// 添加标签按钮 private LinearLayout tag_container;// 标签容器 private EditText note_message;// 笔记内容 private LinearLayout images_container;// 图片容器 private ImageView btn_addimgs;// 添加图片按钮 private ArrayList<String> tags = new ArrayList<String>();// 标签内容 private ArrayList<String> images = new ArrayList<String>();// 图片内容 private String currentType;// 当前所处分类 private ArrayList<Uri> imgUris = new ArrayList<Uri>(); private Uri imgUri; @Override protected void initView() { setContentView(R.layout.activity_notesdetailedit); save = (ImageView) findViewById(R.id.save); title = (EditText) findViewById(R.id.title); btn_addtag = (ImageView) findViewById(R.id.btn_addtag); tag_container = (LinearLayout) findViewById(R.id.tag_container); note_message = (EditText) findViewById(R.id.note_message); images_container = (LinearLayout) findViewById(R.id.images_container); btn_addimgs = (ImageView) findViewById(R.id.btn_addimgs); } @Override protected void initData() { intent = getIntent(); initOperate(); } @Override protected void initListener() { // 顶部保存按钮点击事件 save.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(title.getText().toString()) || TextUtils.isEmpty(note_message.getText().toString())) { ToastUtils.show(mContext, "您的输入不完整,请确定后再试"); } else if (tags.size() == 0 || images.size() == 0) {// 强制添加标签和图片 ToastUtils.show(mContext, "请确保您已添加图片和标签"); } else { notesItem item = new notesItem(); // 设置父表 item.setParentName(parentTable); // 设置标题 item.setNotesName(title.getText().toString()); // 设置标签 item.setLabels(tags); // 设置笔记内容 item.setMessage(note_message.getText().toString()); // 设置图片 item.setImages(images); // 设置时间 item.setNotesTime(TimeFormatUtil.format(new Date())); // 设置此项为笔记 item.setNotesType(1); // 保存到数据库 saveDataToDatabase(item); } } }); // 添加标签按钮 btn_addtag.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("添加标签"); View view = View .inflate(mContext, R.layout.dialog_addtag, null); final EditText input_tagname = (EditText) view .findViewById(R.id.input_tagname); Button ensure = (Button) view.findViewById(R.id.ensure); Button cancel = (Button) view.findViewById(R.id.cancel); builder.setView(view); final Dialog dialog = builder.create(); dialog.show(); // 确定按钮点击事件 ensure.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 点击确定按钮添加标签到编辑界面 final View view = View.inflate(mContext, R.layout.layout_tag, null); final TextView tag = (TextView) view .findViewById(R.id.tag); ImageView btn_close = (ImageView) view .findViewById(R.id.btn_close); // 添加标签 tag.setText(input_tagname.getText().toString()); tags.add(input_tagname.getText().toString()); tag_container.addView(view); dialog.dismiss(); // 点击关闭按钮 btn_close.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { tags.remove(tag.getText().toString()); tag_container.removeView(view); } }); } }); // 取消按钮点击事件 cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); } }); // 添加图片按钮 btn_addimgs.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("添加图片"); // 调用系统相机拍摄照片 builder.setPositiveButton("拍摄照片", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String path = DateFormat.format( "yyyyMMddhhmmss", new Date()) .toString(); File file = new File(Environment .getExternalStorageDirectory(), "/okq/imgs/" + path + ".jpg"); imgUri = Uri.fromFile(file); Intent intent = new Intent( "android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri); startActivityForResult(intent, myConstant.Take_Photo);// 启动相机拍照 dialog.dismiss(); } }); // 从相册选取图片 builder.setNegativeButton("选取图片", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent( "android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent, myConstant.Choose_Photo);// 从相册选取图片 dialog.dismiss(); } }); builder.create().show(); } }); } // 保存数据到数据库 private void saveDataToDatabase(notesItem item) { ContentValues values = new ContentValues(); values.put(myConstant.NotesName, item.getNotesName()); values.put(myConstant.NotesType, item.getNotesType()); values.put(myConstant.Notesmessage, item.getMessage()); values.put(myConstant.NotesLabel, splicecharacter(item.getLabels())); values.put(myConstant.Images, splicecharacter(item.getImages())); values.put(myConstant.Parent, parentTable); values.put(myConstant.NotesTime, item.getNotesTime()); // 插入数据 myNotesdatabase.insert(currentType, null, values); // 设置需要返回的数据,关闭当前页面 Intent intent = new Intent(); intent.putExtra(myConstant.NotesReturned, item); setResult(RESULT_OK, intent); finish(); } // 拼接标签或图片字符串 private String splicecharacter(ArrayList<String> data) { StringBuilder builder = new StringBuilder(); if (data.size() > 0) { for (int i = 0; i < data.size(); i++) { if (i != data.size() - 1) { builder.append(data.get(i) + "|"); } else { builder.append(data.get(i)); } } } return builder.toString(); } // 初始化操作,封装笔记的添加和编辑操作 private void initOperate() { switch (intent.getIntExtra( myConstant.NotesDetailEditActivity_operatetype, -1)) { // 笔记添加操作 case myConstant.NotesDetailEditActivity_ADD: handleNotesAdd(); break; // 笔记编辑操作 case myConstant.notesDetailEditActivity_EDIT: handleNotesEdit(); break; default: break; } } // 笔记添加操作 private void handleNotesAdd() { parentTable = intent.getStringExtra(myConstant.Parent); currentType = intent .getStringExtra(myConstant.notesDetailEditActivity_CurrentType); } // 笔记编辑操作 private void handleNotesEdit() { ToastUtils.show(mContext, "编辑笔记"); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case myConstant.Choose_Photo: // 选取图片 Uri uri_choose; uri_choose = data.getData();// 获取选取的图片路径 String path = DateFormat.format("yyyyMMddhhmmss", new Date()) .toString(); File file = new File(Environment.getExternalStorageDirectory(), "/okq/imgs/" + path + ".jpg"); imgUri = Uri.fromFile(file); Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri_choose, "image/*");// 第一个参数表示要处理图片的路径 intent.putExtra("scale", true);// 允许缩放 intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);// 输出路径 startActivityForResult(intent, myConstant.Crop_Photo); break; case myConstant.Take_Photo: // 拍摄照片 Intent intent2 = new Intent("com.android.camera.action.CROP"); intent2.setDataAndType(imgUri, "image/*"); intent2.putExtra("scale", true);// 允许缩放 intent2.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);// 输出路径 startActivityForResult(intent2, myConstant.Crop_Photo); break; case myConstant.Crop_Photo: // 裁剪照片 // 添加图片 final View view = View.inflate(mContext, R.layout.img_add, null); ImageView img_add = (ImageView) view.findViewById(R.id.img_add); ImageView img_del = (ImageView) view.findViewById(R.id.img_del); try { img_add.setImageBitmap(BitmapFactory .decodeStream(getContentResolver().openInputStream( imgUri))); images_container.addView(view); // 添加到需要保存的图片集合 images.add(imgUri.getPath()); } catch (FileNotFoundException e) { e.printStackTrace(); } // 删除按钮点击事件 img_del.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { images_container.removeView(view); images.remove(imgUri.getPath()); } }); break; default: break; } } }
{ "content_hash": "e7a9eabc6d072cf4b54a95520aaf8fb3", "timestamp": "", "source": "github", "line_count": 334, "max_line_length": 81, "avg_line_length": 30.176646706586826, "alnum_prop": 0.6864768330191487, "repo_name": "kydiwen/PhoneNotes", "id": "55bdf808d2a69b4ef611a9ea120d664752021793", "size": "11001", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/example/phone_notes/activity/NotesDetailEditActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "107096" } ], "symlink_target": "" }
[![GoDoc](https://godoc.org/github.com/skidder/gifs-client-go/gifs?status.svg)](https://godoc.org/github.com/skidder/gifs-client-go/gifs) [![Circle CI](https://circleci.com/gh/skidder/gifs-client-go.svg?style=svg)](https://circleci.com/gh/skidder/gifs-client-go) Go Client for the [GIFS API](http://docs.gifs.com/v1.0/docs). # Installation ```shell go get -u github.com/skidder/gifs-client-go/gifs ``` # Operations ## Import from URL Invokes the [Import](http://docs.gifs.com/docs/mediaimport) endpoint in the GIFS API. Sample client code follows: ```go package main import ( "fmt" "os" "github.com/skidder/gifs-client-go/gifs" ) func main() { client := gifs.NewGIFSClient(os.Getenv("GIFS_API_KEY")) request := &gifs.ImportRequest{ Title: os.Args[1], SourceURL: os.Args[2], } err := client.Import(request) if err != nil { fmt.Printf("Error importing file: %s\n", err.Error()) return } } ``` ## Upload File Invokes the [Upload](http://docs.gifs.com/docs/mediaupload) endpoint on the GIFS API. Sample code follows: ```go package main import ( "fmt" "os" "github.com/skidder/gifs-client-go/gifs" ) func main() { client := gifs.NewGIFSClient(os.Getenv("GIFS_API_KEY")) title := os.Args[1] filename := os.Args[2] inputFile, err := os.OpenFile(filename, os.O_RDONLY, os.FileMode(666)) if err != nil { fmt.Printf("Error opening file: %s\n", err.Error()) return } defer inputFile.Close() request := &gifs.UploadRequest{ Title: title, Filename: filename, } err = client.Upload(request, inputFile) if err != nil { fmt.Printf("Error uploading file: %s\n", err.Error()) return } } ```
{ "content_hash": "20718977230930795768f329491267ba", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 262, "avg_line_length": 21.350649350649352, "alnum_prop": 0.6776155717761557, "repo_name": "skidder/gifs-client-go", "id": "2f3dd2478a34fdf848850e0a81830ceeaa0a6244", "size": "1662", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "4162" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ro"> <head> <!-- Generated by javadoc (version 1.7.0_07) on Tue May 27 14:37:11 EEST 2014 --> <title>HeaderToolbarElementJsonHandler.ColumnInfo (JasperReports 5.6.0 API)</title> <meta name="date" content="2014-05-27"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="HeaderToolbarElementJsonHandler.ColumnInfo (JasperReports 5.6.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/HeaderToolbarElementJsonHandler.ColumnInfo.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.html" title="class in net.sf.jasperreports.components.headertoolbar.json"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.GroupInfo.html" title="class in net.sf.jasperreports.components.headertoolbar.json"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.ColumnInfo.html" target="_top">Frames</a></li> <li><a href="HeaderToolbarElementJsonHandler.ColumnInfo.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">net.sf.jasperreports.components.headertoolbar.json</div> <h2 title="Class HeaderToolbarElementJsonHandler.ColumnInfo" class="title">Class HeaderToolbarElementJsonHandler.ColumnInfo</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>net.sf.jasperreports.components.headertoolbar.json.HeaderToolbarElementJsonHandler.ColumnInfo</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../../../net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.html" title="class in net.sf.jasperreports.components.headertoolbar.json">HeaderToolbarElementJsonHandler</a></dd> </dl> <hr> <br> <pre>public static class <span class="strong">HeaderToolbarElementJsonHandler.ColumnInfo</span> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.ColumnInfo.html#getIndex()">getIndex</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.ColumnInfo.html#getInteractive()">getInteractive</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.ColumnInfo.html#getLabel()">getLabel</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.ColumnInfo.html#getUuid()">getUuid</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.ColumnInfo.html#getVisible()">getVisible</a></strong>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getIndex()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getIndex</h4> <pre>public&nbsp;java.lang.String&nbsp;getIndex()</pre> </li> </ul> <a name="getLabel()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getLabel</h4> <pre>public&nbsp;java.lang.String&nbsp;getLabel()</pre> </li> </ul> <a name="getUuid()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getUuid</h4> <pre>public&nbsp;java.lang.String&nbsp;getUuid()</pre> </li> </ul> <a name="getVisible()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getVisible</h4> <pre>public&nbsp;boolean&nbsp;getVisible()</pre> </li> </ul> <a name="getInteractive()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getInteractive</h4> <pre>public&nbsp;boolean&nbsp;getInteractive()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/HeaderToolbarElementJsonHandler.ColumnInfo.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.html" title="class in net.sf.jasperreports.components.headertoolbar.json"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.GroupInfo.html" title="class in net.sf.jasperreports.components.headertoolbar.json"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.ColumnInfo.html" target="_top">Frames</a></li> <li><a href="HeaderToolbarElementJsonHandler.ColumnInfo.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">&copy; 2001-2010 Jaspersoft Corporation <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span> </small></p> </body> </html>
{ "content_hash": "83d69e90e490d8bc8d2d219d0fe5223b", "timestamp": "", "source": "github", "line_count": 283, "max_line_length": 265, "avg_line_length": 37.113074204947, "alnum_prop": 0.6574312101304389, "repo_name": "phurtado1112/cnaemvc", "id": "f0f15eb4abeb38c62166926823eba11f55f6ab74", "size": "10503", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/JasperReport__5.6/docs/api/net/sf/jasperreports/components/headertoolbar/json/HeaderToolbarElementJsonHandler.ColumnInfo.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11139" }, { "name": "HTML", "bytes": "112926414" }, { "name": "Java", "bytes": "532942" } ], "symlink_target": "" }
<div class="message-container"> <div class="message" *ngFor="let msg of messages | async"> <avatar [author]="msg.author"></avatar> <div class="text-wrapper"> <p class="author">{{ msg.author | format: 'name'}}</p> <p title="{{msg.text}}">{{msg.text | format: 'cat'}}</p> </div> </div> </div> <div class="input-container"> <form (ngSubmit)="sendMessage(model)"> <input type="text" [(ngModel)]="model" placeholder="Enter your message"> <button type="submit">Send</button> </form> </div>
{ "content_hash": "af034636ccab3fa83b39c8f86bd68c8d", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 80, "avg_line_length": 37.53333333333333, "alnum_prop": 0.5630550621669627, "repo_name": "JazzCo/jazzco.github.io", "id": "2a67a48bafcd2eba7522d5dd0526acdf2059a01a", "size": "563", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "public/ngconf16/dist/app/catchat.component.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "23965" }, { "name": "HTML", "bytes": "5798" }, { "name": "Ruby", "bytes": "3166" } ], "symlink_target": "" }
using System; using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Collections; namespace MbUnit.Core.Reports { public sealed class NamePretifier { private string fixtureSuffix = "Test"; private string testSuffix = "Test"; private IDictionary ignoredTokens = new Hashtable(); private static Regex capitalWord = new Regex(@"[A-Z][a-z]*|[0-9]", RegexOptions.Compiled | RegexOptions.Singleline); public NamePretifier() { this.ignoredTokens.Add("SetUp", null); this.ignoredTokens.Add("TearDown", null); this.ignoredTokens.Add("", null); } public string FixtureSuffix { get { return this.fixtureSuffix; } set { this.fixtureSuffix=value; } } public string TestSuffix { get { return this.testSuffix; } set { this.testSuffix=value; } } public string PretifyFixture(string fixtureName) { if (fixtureName == null) throw new ArgumentNullException("fixtureName"); if (fixtureName.Length == 0) throw new ArgumentException("fitureName is empty"); string name = fixtureName; if (name.EndsWith(this.fixtureSuffix)) name = name.Substring(0, name.LastIndexOf(this.fixtureSuffix)); return name; } public string PretifyTest(string testName) { if (testName == null) throw new ArgumentNullException("testName"); if (testName.Length == 0) throw new ArgumentNullException("testName"); string name = testName; StringWriter sw= new StringWriter(); foreach(string action in name.Split('.')) { if (this.ignoredTokens.Contains(action)) continue; string a = action; if (a.EndsWith(this.testSuffix)) a = a.Substring(0, action.LastIndexOf(this.testSuffix)); string actionSentence = ConvertToSentence(a); sw.Write(",{0}",actionSentence); } return sw.ToString().TrimStart(','); } private static string ConvertToSentence(string word) { if (word.Length == 0) return ""; string sentence = capitalWord.Replace(word, new MatchEvaluator(SplitWord)).TrimStart(); return sentence; } private static string SplitWord(Match m) { return String.Format(" {0}",m.Value.ToLower()); } private static string Capitalize(string name) { if (name==null) return null; if (name.Length==0) return name; string capitalized = String.Format("{0}{1}", Char.ToUpper(name[0]), name.Substring(1,name.Length-1) ); return capitalized; } } }
{ "content_hash": "2e0d6ec5be293af5a1329e0a4460443a", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 99, "avg_line_length": 26.63716814159292, "alnum_prop": 0.554485049833887, "repo_name": "Gallio/mbunit-v2", "id": "f58adbbdef794dd936cbf75c230901fa3d72a097", "size": "4065", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/mbunit/MbUnit.Framework/Core/Reports/NamePretifier.cs", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package dataclass import scala.reflect.macros.whitebox.Context import scala.annotation.tailrec private[dataclass] class Macros(val c: Context) extends ImplTransformers { import c.universe._ import dataclass.Macros._ private val debug = sys.env .get("DATACLASS_MACROS_DEBUG") .map(_.toBoolean) .getOrElse(java.lang.Boolean.getBoolean("dataclass.macros.debug")) private class Transformer( generateApplyMethods: Boolean, generateOptionSetters: Boolean, generatedSettersCallApply: Boolean, cachedHashCode: Boolean ) extends ImplTransformer { override def transformClass( cdef: ClassDef, mdef: ModuleDef ): List[ImplDef] = cdef match { case q"""$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }""" => val allParams = paramss.flatten val tparamsRef = tparams.map { t => tq"${t.name}" } val hasToString = { def fromStats = stats.exists { case DefDef(_, nme, tparams, vparamss, _, _) if nme.decodedName.toString == "toString" && tparams.isEmpty && vparamss .forall(_.isEmpty) => true case t @ ValDef(_, name, _, _) if name.decodedName.toString == "toString" => true case _ => false } val fromFields = allParams.exists(_.name.decodedName.toString() == "toString") fromFields || fromStats } val hasHashCode = { def fromStats = stats.exists { case DefDef(_, nme, tparams, vparamss, _, _) if nme.decodedName.toString == "hashCode" && tparams.isEmpty && vparamss .forall(_.isEmpty) => true case t @ ValDef(_, name, _, _) if name.decodedName.toString == "hashCode" => true case _ => false } val fromFields = allParams.exists(_.name.decodedName.toString() == "hashCode") fromFields || fromStats } val hasTuple = { def fromStats = stats.exists { case DefDef(_, nme, tparams, vparamss, _, _) if nme.decodedName.toString == "tuple" && tparams.isEmpty && vparamss .forall(_.isEmpty) => true case t @ ValDef(_, name, _, _) if name.decodedName.toString == "tuple" => true case _ => false } val fromFields = allParams.exists(_.name.decodedName.toString() == "tuple") fromFields || fromStats } val namedArgs = paramss.map(_.map { p => q"${p.name}=this.${p.name}" }) val setters = paramss.zipWithIndex.flatMap { case (l, groupIdx) => l.zipWithIndex.flatMap { case (p, idx) => val namedArgs0 = namedArgs.updated( groupIdx, namedArgs(groupIdx).updated(idx, q"${p.name}=${p.name}") ) val fn = p.name.decodedName.toString.capitalize val withDefIdent = TermName(s"with$fn") def settersCallApply( tpe0: Tree, namedArgs0: List[List[Tree]] ) = if (generatedSettersCallApply) q"def $withDefIdent(${p.name}: $tpe0) = ${tpname.toTermName}[..$tparamsRef](...$namedArgs0)" else q"def $withDefIdent(${p.name}: $tpe0) = new $tpname[..$tparamsRef](...$namedArgs0)" val extraMethods = if (generateOptionSetters) { val wrappedOptionTpe = p.tpt match { case AppliedTypeTree( Ident(TypeName("Option")), List(wrapped) ) => Seq(wrapped) case _ => Nil } wrappedOptionTpe.map { tpe0 => val namedArgs0 = namedArgs.updated( groupIdx, namedArgs(groupIdx).updated( idx, q"${p.name}=_root_.scala.Some(${p.name})" ) ) settersCallApply(tpe0, namedArgs0) } } else Nil settersCallApply(p.tpt, namedArgs0) +: extraMethods } } val wildcardedTparams = tparams.map { case TypeDef(mods, name, tparams, rhs) if tparams.isEmpty => tq"$WildcardType" case TypeDef(mods, name, tparams, rhs) => val tparams0 = tparams.zipWithIndex.map { case (p, n) => TypeDef(p.mods, TypeName(s"X$n"), p.tparams, p.rhs) } tq"({type L[..$tparams0]=$WildcardType})#L" } val equalMethods = { val fldChecks = paramss.flatten .map { param => q"this.${param.name} == other.${param.name}" } .foldLeft[Tree](q"true")((a, b) => q"$a && $b") val hashCheck = if (cachedHashCode) q"obj.hashCode == hashCode" else q"true" Seq( q""" override def canEqual(obj: Any): _root_.scala.Boolean = obj != null && obj.isInstanceOf[$tpname[..$wildcardedTparams]] && $hashCheck """, q""" override def equals(obj: Any): _root_.scala.Boolean = this.eq(obj.asInstanceOf[AnyRef]) || canEqual(obj) && { val other = obj.asInstanceOf[$tpname[..$wildcardedTparams]] $fldChecks } """ ) } val hashCodeMethod = if (hasHashCode) Nil else { val fldLines = allParams .map { param => q"code = 37 * code + this.${param.name}.##" } if (cachedHashCode) { val Sentinel = q"0" Seq( q"""private var __hashCode: _root_.scala.Int = $Sentinel""", q"""override def hashCode: _root_.scala.Int = { if (__hashCode == $Sentinel) { var code = 17 + ${tpname.decodedName.toString()}.## ..$fldLines code *= 37 if (code == $Sentinel) { code = 1 } __hashCode = code } __hashCode } """ ) } else Seq( q"""override def hashCode: _root_.scala.Int = { var code = 17 + ${tpname.decodedName.toString()}.## ..$fldLines 37 * code } """ ) } val tupleMethod = if (hasTuple || allParams.lengthCompare(22) > 0) Nil else if (allParams.isEmpty) Seq(q"private def tuple = ()") else { val fields = allParams.map(p => q"this.${p.name}") val tupleName = TermName(s"Tuple${allParams.length}") Seq( q"private def tuple = _root_.scala.$tupleName(..$fields)" ) } val productMethods = { val prodElemNameMethods = if (productElemNameAvailable) { val elemNameCases = paramss.flatten.zipWithIndex .map { case (param, idx) => val name = param.name.decodedName.toString cq"$idx => $name" } Seq( q""" override def productElementName(n: _root_.scala.Int): _root_.java.lang.String = n match { case ..$elemNameCases case n => throw new _root_.java.lang.IndexOutOfBoundsException(n.toString) } """ ) } else Nil val elemCases = paramss.flatten.zipWithIndex .map { case (param, idx) => cq"$idx => this.${param.name}" } Seq( q""" override def productPrefix: _root_.java.lang.String = ${tpname.decodedName.toString} """, q""" override def productArity: _root_.scala.Int = ${allParams.length} """, q""" override def productElement(n: _root_.scala.Int): Any = n match { case ..$elemCases case n => throw new _root_.java.lang.IndexOutOfBoundsException(n.toString) } """ ) ++ prodElemNameMethods } val toStringMethod = if (hasToString) Nil else { val fldLines = allParams.zipWithIndex .flatMap { case (param, idx) => val before = if (idx == 0) Nil else Seq(q"""b.append(", ")""") before :+ q"""b.append(_root_.java.lang.String.valueOf(this.${param.name}))""" } Seq( q"""override def toString: _root_.java.lang.String = { val b = new _root_.java.lang.StringBuilder(${tpname.decodedName .toString() + "("}) ..$fldLines b.append(")") b.toString() } """ ) } val splits = { @tailrec def indexWithAllDefaults( l: List[ValDef], idx: Int, acc: Option[Int] ): Option[Int] = l match { case h :: t => val next = if (h.rhs.isEmpty) None else acc.orElse(Some(idx)) indexWithAllDefaults(t, idx + 1, next) case Nil => acc } val splits0 = Seq(paramss.head.length) ++ indexWithAllDefaults( paramss.head, 0, None ).toSeq ++ paramss.head.zipWithIndex .filter( _._1.mods.annotations .exists(_.toString().startsWith("new since(")) ) .map(_._2) splits0.distinct.sorted } val allParams0 = paramss.map(_.map { p => var flags0 = Flag.PARAMACCESSOR if (p.mods.hasFlag(Flag.IMPLICIT)) flags0 = flags0 | Flag.IMPLICIT if (p.mods.hasFlag(Flag.OVERRIDE)) flags0 = flags0 | Flag.OVERRIDE if (p.mods.hasFlag(Flag.PRIVATE) && !p.mods.hasFlag(Flag.LOCAL)) flags0 = flags0 | Flag.PRIVATE // TODO Keep PRIVATE / PROTECTED flags? Warn about them? val p0 = { val mods0 = Modifiers( flags0, p.mods.privateWithin, p.mods.annotations ) q"$mods0 val ${p.name}: ${p.tpt}" } val hasSince = p0.mods.annotations.exists(_.toString().startsWith("new since(")) if (hasSince) { val mods0 = Modifiers( p0.mods.flags, p0.mods.privateWithin, p0.mods.annotations .filter(!_.toString().startsWith("new since(")) ) q"$mods0 val ${p0.name}: ${p0.tpt}" } else p0 }) val extraConstructors = { // https://stackoverflow.com/questions/22756542/how-do-i-add-a-no-arg-constructor-to-a-scala-case-class-with-a-macro-annotation/22757936#22757936 splits.filter(_ != paramss.head.length).foreach { idx => val b = paramss.head.drop(idx) // Weirdly enough, things compile fine without this check (resulting in empty trees hanging around) b.foreach { p => if (p.rhs.isEmpty) c.abort( p.pos, s"Found parameter with no default value ${p.name} after @since annotation" ) } } lazy val newCtorPos = { val defaultCtorPos = c.enclosingPosition defaultCtorPos .withEnd(defaultCtorPos.end + 1) .withStart(defaultCtorPos.start + 1) .withPoint(defaultCtorPos.point + 1) } val len = allParams0.head.length splits.reverse.filter(_ != len).map { idx => val a = allParams0.head.take(idx) val b = paramss.head.drop(idx) val a0 = a.map { case ValDef(mods, name, tpt, _) => q"$name: $tpt" } val a1 = a0 :: allParams0.tail atPos(newCtorPos)(q""" $ctorMods def this(...$a1) = this(..${a .map(p => q"${p.name}") ++ b .map(_.rhs)}) """) } } val mods0 = Modifiers( mods.flags.|(Flag.FINAL), mods.privateWithin, mods.annotations ) val parents0 = parents ::: List( tq"_root_.scala.Product", tq"_root_.scala.Serializable" ) val res = q"""$mods0 class $tpname[..$tparams] $ctorMods(...$allParams0) extends { ..$earlydefns } with ..$parents0 { $self => ..$extraConstructors ..$stats ..$setters ..$toStringMethod ..$equalMethods ..$hashCodeMethod ..$tupleMethod ..$productMethods }""" if (debug) System.err.println(res) val q"$mmods object $mname extends { ..$mearlydefns } with ..$mparents { $mself => ..$mstats }" = mdef val applyMethods = if (generateApplyMethods) splits.map { idx => val a = allParams0.head.take(idx) val b = paramss.head.drop(idx) val a0 = a.map { case ValDef(mods, name, tpt, _) => q"$name: $tpt" } val a1 = a0 :: paramss.tail q""" def apply[..$tparams](...$a1): $tpname[..$tparamsRef] = new $tpname[..$tparamsRef](...${(a .map(p => q"${p.name}") ++ b.map(_.rhs)) :: paramss.tail .map( _.map(p => q"${p.name}") )})""" } else Nil val mdef0 = q"$mmods object $mname extends { ..$mearlydefns } with ..$mparents { $mself => ..$mstats; ..$applyMethods }" if (debug) System.err.println(mdef0) List(res, mdef0) case _ => c.abort(c.enclosingPosition, "@data must annotate a class") } } def impl(annottees: Tree*): Tree = { val params = c.prefix.tree match { case q"new data()" => Nil case q"new data(..$params0)" => params0 } def warnPublicConstructorParam(): Unit = c.warning( c.enclosingPosition, "publicConstructor parameter of @data annotation has no effect anymore, constructors are now always public" ) params.foreach { case q"publicConstructor=true" => warnPublicConstructorParam() case q"publicConstructor=false" => warnPublicConstructorParam() case _ => } val generateApplyMethods = params.forall { case q"apply=false" => false case _ => true } val generateOptionSetters = params.exists { case q"optionSetters=true" => true case _ => false } val generatedSettersCallApply = params.exists { case q"settersCallApply=true" => true case _ => false } val generatedCachedHashCode = params.exists { case q"cachedHashCode=true" => true case _ => false } annottees.transformAnnottees( new Transformer( generateApplyMethods, generateOptionSetters, generatedSettersCallApply, generatedCachedHashCode ) ) } } object Macros { // productElementName added in 2.13 private[dataclass] val productElemNameAvailable = { val sv = scala.util.Properties.versionNumberString !sv.startsWith("2.11.") && !sv.startsWith("2.12.") } }
{ "content_hash": "8a0fe8cb78cd5149442d0a3eac7f833d", "timestamp": "", "source": "github", "line_count": 525, "max_line_length": 157, "avg_line_length": 33.92761904761905, "alnum_prop": 0.4354367841904334, "repo_name": "alexarchambault/data-class", "id": "9365c0740deab95b97dc4e3a9c5e377205b5c643", "size": "17812", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/main/scala/dataclass/Macros.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "49543" }, { "name": "Shell", "bytes": "2782" } ], "symlink_target": "" }
class CommentsController < ApplicationController before_action :authenticate_user! #apply to all actions in this controller - Devise authentication - check if user is logged in before_action :find_comment, only: [:edit, :update, :destroy] before_action :authorize_ownership, only: [:edit, :update, :destroy] def create @comment = current_user.comments.build(comment_params) #associates comment with current user if @comment.save redirect_to @comment.story, notice: 'Comment created.' else @story = @comment.story render "stories/show", alert: 'Comment creation failed.' end end def edit end def update if @comment.update(comment_params) redirect_to @story, notice: 'Comment updated.' else render :edit, alert: 'Comment update failed.' end end def destroy @comment.destroy redirect_to @story, notice: 'Comment deleted.' end #------------------------------- private def find_comment @comment = Comment.find(params[:id]) @story = @comment.story end def authorize_ownership if @comment.user != current_user redirect_to stories_path, alert: 'You do not have required permissions.' return #guard clause end end def comment_params #strong params params.require(:comment).permit(:story_id, :content) end end
{ "content_hash": "19895d55de34afd4873f7b901f22548d", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 129, "avg_line_length": 26.88, "alnum_prop": 0.6733630952380952, "repo_name": "MitulMistry/rails-storyplan", "id": "c95f6314be240c647fc9307321a58adfb587335c", "size": "1344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/comments_controller.rb", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "42599" }, { "name": "JavaScript", "bytes": "7035" }, { "name": "Ruby", "bytes": "197851" }, { "name": "SCSS", "bytes": "6637" } ], "symlink_target": "" }
#include <Kokkos_Core.hpp> #if defined( KOKKOS_ENABLE_THREADS ) #include <feint.hpp> namespace Kokkos { namespace Example { template void feint< Kokkos::Threads ,false>( const unsigned global_elem_nx , const unsigned global_elem_ny , const unsigned global_elem_nz ); template void feint< Kokkos::Threads ,true>( const unsigned global_elem_nx , const unsigned global_elem_ny , const unsigned global_elem_nz ); } /* namespace Example */ } /* namespace Kokkos */ #endif /* #if defined( KOKKOS_ENABLE_THREADS ) */
{ "content_hash": "19f65c96ff45cf23b84a94a5dffc2846", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 49, "avg_line_length": 20.46153846153846, "alnum_prop": 0.7086466165413534, "repo_name": "nschloe/seacas", "id": "44016caadad17a368d32e9570104930d2ea722e0", "size": "2495", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "packages/kokkos/example/feint/feint_threads.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "16194234" }, { "name": "C++", "bytes": "8593376" }, { "name": "CMake", "bytes": "1710665" }, { "name": "CSS", "bytes": "10556" }, { "name": "Fortran", "bytes": "11575690" }, { "name": "HTML", "bytes": "1558835" }, { "name": "Lex", "bytes": "28717" }, { "name": "M4", "bytes": "67986" }, { "name": "Makefile", "bytes": "851848" }, { "name": "Matlab", "bytes": "23647" }, { "name": "Objective-C", "bytes": "7154" }, { "name": "Pascal", "bytes": "59" }, { "name": "Perl", "bytes": "22409" }, { "name": "Python", "bytes": "1196444" }, { "name": "Roff", "bytes": "1107836" }, { "name": "Shell", "bytes": "418975" }, { "name": "TeX", "bytes": "883374" }, { "name": "Yacc", "bytes": "21322" } ], "symlink_target": "" }
using System.Collections.Generic; using org.critterai.nmbuild; using org.critterai.nmgen; using org.critterai.nmbuild.u3d.editor; using UnityEngine; /// <summary> /// Assigns areas to components based on the component's tag. (Editor Only) /// </summary> /// <remarks> /// <para> /// Will not override the assignment of <see cref="NMGen.NullArea"/>. /// </para> /// </remarks> [System.Serializable] public sealed class TagAreaDef : ScriptableObject, IInputBuildProcessor { /// <summary> /// True if components whose parents have one of the tags should be assigned the area. /// </summary> public bool recursive; /// <summary> /// Tags to associate with areas. /// </summary> public List<string> tags; /// <summary> /// The area associated with each tag. /// </summary> public List<byte> areas; [SerializeField] private int mPriority = NMBuild.DefaultPriority; /// <summary> /// The priority of the processor. /// </summary> public int Priority { get { return mPriority; } } /// <summary> /// The name of the processor /// </summary> public string Name { get { return name; } } /// <summary> /// Sets the priority. /// </summary> /// <param name="value">The new priority.</param> public void SetPriority(int value) { mPriority = NMBuild.ClampPriority(value); } /// <summary> /// Duplicates allowed. (Always true.) /// </summary> public bool DuplicatesAllowed { get { return true; } } /// <summary> /// Processes the context. /// </summary> /// <remarks> /// <para> /// Applied during the <see cref="InputBuildState.ApplyAreaModifiers"/> state. /// </para> /// </remarks> /// <param name="state">The current state of the input build.</param> /// <param name="context">The input context to process.</param> /// <returns>False if the input build should abort.</returns> public bool ProcessInput(InputBuildContext context, InputBuildState state) { if (state != InputBuildState.ApplyAreaModifiers) return true; context.info.areaModifierCount++; if (tags == null || areas == null || tags.Count != areas.Count) { context.Log("Mesh/Area size error. (Invalid processor state.)", this); return false; } if (tags.Count == 0) { context.Log("No action taken. No tags defined.", this); return true; } List<Component> targetItems = context.components; List<byte> targetAreas = context.areas; int applied = 0; for (int iTarget = 0; iTarget < targetItems.Count; iTarget++) { Component targetItem = targetItems[iTarget]; if (targetItem == null || targetAreas[iTarget] == NMGen.NullArea) // Don't override null area. continue; int iSource = tags.IndexOf(targetItem.tag); if (iSource != -1) { targetAreas[iTarget] = areas[iSource]; applied++; continue; } if (recursive) { // Need to see if the tag is on any parent. Transform parent = targetItem.transform.parent; while (parent != null) { iSource = tags.IndexOf(parent.tag); if (iSource != -1) { // One of the tags is on this item. targetAreas[iTarget] = areas[iSource]; applied++; break; } parent = parent.parent; } } } context.Log(string.Format("{1}: Applied area(s) to {0} components", applied, name), this); return true; } }
{ "content_hash": "2813d3cb061d8bdb4032d3c6e6cfc14c", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 98, "avg_line_length": 29.528985507246375, "alnum_prop": 0.5266257668711657, "repo_name": "stevefsp/critterai", "id": "b8564164d123faf3216c23435dca9af1399f688f", "size": "5218", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/main/Assets/CAI/nmbuild-u3d/Editor/input/TagAreaDef.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5774" }, { "name": "C#", "bytes": "1581351" }, { "name": "C++", "bytes": "725383" }, { "name": "HTML", "bytes": "4869" }, { "name": "Java", "bytes": "807745" } ], "symlink_target": "" }
set -o errexit set -o nounset set -o pipefail . "$(dirname "${BASH_SOURCE[0]}")/common.sh" cd "${KOPS_ROOT}" make crds changed_files=$(git status --porcelain --untracked-files=no || true) if [ -n "${changed_files}" ]; then echo "Detected that CRD generation is needed; run 'make crds'" echo "changed files:" printf "%s" "${changed_files}\n" echo "git diff:" git --no-pager diff echo "To fix: run 'make crds'" exit 1 fi
{ "content_hash": "0b9b7463a18cba866ae5ca4cc126a048", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 68, "avg_line_length": 21.19047619047619, "alnum_prop": 0.6359550561797753, "repo_name": "justinsb/kops", "id": "99b85c13500aadcf131d15b5b9ffcd0e73ecd2a0", "size": "1054", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hack/verify-crds.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "3692" }, { "name": "Go", "bytes": "6343553" }, { "name": "HCL", "bytes": "2163692" }, { "name": "Makefile", "bytes": "52545" }, { "name": "Python", "bytes": "12002" }, { "name": "Roff", "bytes": "166125" }, { "name": "Shell", "bytes": "761369" }, { "name": "Starlark", "bytes": "5475" } ], "symlink_target": "" }
![Docker Compose UI](https://raw.githubusercontent.com/francescou/docker-compose-ui/master/static/images/logo-dark.png) [![Docker Stars](https://img.shields.io/docker/stars/francescou/docker-compose-ui.svg)](https://hub.docker.com/r/francescou/docker-compose-ui/) [![Docker Pulls](https://img.shields.io/docker/pulls/francescou/docker-compose-ui.svg)](https://hub.docker.com/r/francescou/docker-compose-ui/) ## What is it Docker Compose UI is a web interface for Docker Compose. The aim of this project is to provide a minimal HTTP API on top of Docker Compose while maintaining full interoperability with Docker Compose CLI. The application can be deployed as a single container, there are no dependencies nor databases to install. ![compose ui screenshots](https://raw.githubusercontent.com/francescou/docker-compose-ui/master/screenshots/docker-compose-ui.gif) ## Compose file format compatibility matrix | Compose file format | Docker Engine | | ------------- | ------------- | | 3.6 | 18.02.0+ | | 3.3 - 3.5 | 17.06.0+ | | 3.0 – 3.2| 1.13.0+ | | 2.3 | 17.06.0+ | | 2.2 | 1.13.0+ | | 2.1 | 1.12.0+ | | 2.0 | 1.10.0+ | | 1.0 | 1.9.1+ | ## Getting started Run the following command in terminal: docker run \ --name docker-compose-ui \ -p 5000:5000 \ -w /opt/docker-compose-projects/ \ -v /var/run/docker.sock:/var/run/docker.sock \ francescou/docker-compose-ui:1.13.0 You have to wait while Docker pulls the container from the Docker Hub: <https://hub.docker.com/r/francescou/docker-compose-ui/> Then open your browser to `http://localhost:5000` If you already have docker-compose installed, you can run `docker-compose up` and then open your browser to `http://localhost:8080`. ### Add your own docker-compose projects to use your own docker-compose projects run this command from the directory containing your docker-compose.yml files: docker run \ --name docker-compose-ui \ -v $(pwd):$(pwd) \ -w $(dirname $(pwd)) \ -p 5000:5000 \ -v /var/run/docker.sock:/var/run/docker.sock \ francescou/docker-compose-ui:1.13.0 you can download my example projects into */home/user/docker-compose-ui/demo-projects/* from https://github.com/francescou/docker-compose-ui/tree/master/demo-projects ### Load projects from a git repository (experimental) docker run \ --name docker-compose-ui \ -p 5000:5000 \ -w /opt/docker-compose-projects-git/ \ -v /var/run/docker.sock:/var/run/docker.sock \ -e GIT_REPO=https://github.com/francescou/docker-compose-ui.git \ francescou/docker-compose-ui:1.13.0 ### Note about scaling services Note that some of the services provided by the demo projects are not "scalable" with `docker-compose scale SERVICE=NUM` because of published ports conflicts. Check out this project if you are interested in scaling up and down a docker-compose service without having any down time: <https://github.com/francescou/docker-continuous-deployment> ### Note about volumes since you're running docker-compose inside a container you must pay attention to volumes mounted with relative paths, see [Issue #6](https://github.com/francescou/docker-compose-ui/issues/6) ### Integration with external web console Docker Compose UI support to lauch a console with a shell (one of `/bin/bash` or `/bin/sh`) in a given container if a suitable companion container is available, the only requirement for a web console is to support passing the container id (or name) and the command to exec as querystring parameters. For e.g. with [bitbull/docker-exec-web-console](https://github.com/bitbull-team/docker-exec-web-console) you can call `http://localhost:8888/?cid={containerName}&cmd={command}`, so you can pass the `WEB_CONSOLE_PATTERN` environment var to docker-compose-ui, that hold the pattern that will be used to build the url to load the console. Such pattern should include the `{containerName}` and `{command}` placeholders. Example usage: docker run \ --name docker_exec_web_console \ -p 8888:8888 \ -v /var/run/docker.sock:/var/run/docker.sock \ -e 'CONTEXT_PATH=/web-console/' \ bitbull/docker-exec-web-console docker run \ --name docker-compose-ui \ -p 5000:5000 \ -v /var/run/docker.sock:/var/run/docker.sock \ -e 'WEB_CONSOLE_PATTERN=http://localhost:8888/web-console/?cid={containerName}&cmd={command}' \ francescou/docker-compose-ui:1.13.0 ## Remote docker host You can also run containers on a remote docker host, e.g. docker run \ --name docker-compose-ui \ -p 5000:5000 \ -e DOCKER_HOST=remote-docker-host:2375 \ francescou/docker-compose-ui:1.13.0 ### Docker Swarm or HTTPS Remote docker host The project has been tested against a Docker Engines 1.12 cluster ([swarm mode](https://docs.docker.com/engine/swarm/swarm-tutorial/)). You need to add two environment properties to use an HTTPS remote docker host: `DOCKER_CERT_PATH` and `DOCKER_TLS_VERIFY`, see [example by @ymote](https://github.com/francescou/docker-compose-ui/issues/5#issuecomment-135697832) ### Authenticated docker registries If your projects require you to pull images from a private docker registry that requires authentication, you will need to provide a `config.json` file with the necessary configuration options to the docker-compose-ui container at `/root/.docker/config.json`. You can generate the file on any host by performing `docker login [your private registry address]` and copying the resulting file from your ~/.docker directory to where it is needed. For example: docker run \ --name docker-compose-ui \ -p 5000:5000 \ -w /opt/docker-compose-projects/ \ -v /home/user/.docker/config.json:/root/.docker/config.json:ro \ francescou/docker-compose-ui:1.13.0 ## Technologies Docker Compose UI has been developed using Flask (python microframework) to provide RESTful services and AngularJS to implement the Single Page Application web ui. The application uses [Docker Compose](https://docs.docker.com/compose) to monitor and edit the state of a set of docker compose projects (*docker-compose.yml* files). ## API API docs at <https://francescou.github.io/docker-compose-ui/api.html> ## Issues If you have any problems with or questions about this image, please open a GitHub issue on https://github.com/francescou/docker-compose-ui ## License - MIT The Docker Compose UI code is licensed under the MIT license. Docker Compose UI: Copyright (c) 2016 Francesco Uliana. www.uliana.it/francesco Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{ "content_hash": "6c73e2f7239ab307d625166833cc3d03", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 441, "avg_line_length": 43.70285714285714, "alnum_prop": 0.7315638075313807, "repo_name": "francescou/docker-compose-ui", "id": "9309acba8e50c12d0cbc9f03d2aea01d39afb761", "size": "7650", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5876" }, { "name": "HTML", "bytes": "20966" }, { "name": "JavaScript", "bytes": "26012" }, { "name": "Python", "bytes": "19936" } ], "symlink_target": "" }